cmGeneratorTarget.cxx 197 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file Copyright.txt or https://cmake.org/licensing for details. */
  3. #include "cmGeneratorTarget.h"
  4. #include <algorithm>
  5. #include <array>
  6. #include <cassert>
  7. #include <cctype>
  8. #include <cstddef>
  9. #include <cstdio>
  10. #include <cstring>
  11. #include <sstream>
  12. #include <type_traits>
  13. #include <unordered_set>
  14. #include <utility>
  15. #include <cm/memory>
  16. #include <cm/optional>
  17. #include <cm/string_view>
  18. #include <cmext/algorithm>
  19. #include <cmext/string_view>
  20. #include "cmAlgorithms.h"
  21. #include "cmComputeLinkInformation.h" // IWYU pragma: keep
  22. #include "cmCryptoHash.h"
  23. #include "cmCxxModuleUsageEffects.h"
  24. #include "cmExperimental.h"
  25. #include "cmFileSet.h"
  26. #include "cmFileTimes.h"
  27. #include "cmGeneratedFileStream.h"
  28. #include "cmGeneratorExpression.h"
  29. #include "cmGeneratorExpressionDAGChecker.h"
  30. #include "cmGlobalGenerator.h"
  31. #include "cmList.h"
  32. #include "cmLocalGenerator.h"
  33. #include "cmMakefile.h"
  34. #include "cmMessageType.h"
  35. #include "cmOutputConverter.h"
  36. #include "cmPropertyMap.h"
  37. #include "cmRulePlaceholderExpander.h"
  38. #include "cmSourceFile.h"
  39. #include "cmSourceFileLocation.h"
  40. #include "cmSourceFileLocationKind.h"
  41. #include "cmStandardLevel.h"
  42. #include "cmStandardLevelResolver.h"
  43. #include "cmState.h"
  44. #include "cmStringAlgorithms.h"
  45. #include "cmSyntheticTargetCache.h"
  46. #include "cmSystemTools.h"
  47. #include "cmTarget.h"
  48. #include "cmTargetLinkLibraryType.h"
  49. #include "cmTargetPropertyComputer.h"
  50. #include "cmTargetTraceDependencies.h"
  51. #include "cmake.h"
  52. namespace {
  53. using UseTo = cmGeneratorTarget::UseTo;
  54. }
  55. template <>
  56. cmValue cmTargetPropertyComputer::GetSources<cmGeneratorTarget>(
  57. cmGeneratorTarget const* tgt, cmMakefile const& /* mf */)
  58. {
  59. return tgt->GetSourcesProperty();
  60. }
  61. template <>
  62. const std::string&
  63. cmTargetPropertyComputer::ComputeLocationForBuild<cmGeneratorTarget>(
  64. cmGeneratorTarget const* tgt)
  65. {
  66. return tgt->GetLocation("");
  67. }
  68. template <>
  69. const std::string&
  70. cmTargetPropertyComputer::ComputeLocation<cmGeneratorTarget>(
  71. cmGeneratorTarget const* tgt, const std::string& config)
  72. {
  73. return tgt->GetLocation(config);
  74. }
  75. static void CreatePropertyGeneratorExpressions(
  76. cmake& cmakeInstance, cmBTStringRange entries,
  77. std::vector<std::unique_ptr<cmGeneratorTarget::TargetPropertyEntry>>& items,
  78. bool evaluateForBuildsystem = false)
  79. {
  80. for (auto const& entry : entries) {
  81. items.push_back(cmGeneratorTarget::TargetPropertyEntry::Create(
  82. cmakeInstance, entry, evaluateForBuildsystem));
  83. }
  84. }
  85. cmGeneratorTarget::cmGeneratorTarget(cmTarget* t, cmLocalGenerator* lg)
  86. : Target(t)
  87. {
  88. this->Makefile = this->Target->GetMakefile();
  89. this->LocalGenerator = lg;
  90. this->GlobalGenerator = this->LocalGenerator->GetGlobalGenerator();
  91. this->GlobalGenerator->ComputeTargetObjectDirectory(this);
  92. CreatePropertyGeneratorExpressions(*lg->GetCMakeInstance(),
  93. t->GetIncludeDirectoriesEntries(),
  94. this->IncludeDirectoriesEntries);
  95. CreatePropertyGeneratorExpressions(*lg->GetCMakeInstance(),
  96. t->GetCompileOptionsEntries(),
  97. this->CompileOptionsEntries);
  98. CreatePropertyGeneratorExpressions(*lg->GetCMakeInstance(),
  99. t->GetCompileFeaturesEntries(),
  100. this->CompileFeaturesEntries);
  101. CreatePropertyGeneratorExpressions(*lg->GetCMakeInstance(),
  102. t->GetCompileDefinitionsEntries(),
  103. this->CompileDefinitionsEntries);
  104. CreatePropertyGeneratorExpressions(*lg->GetCMakeInstance(),
  105. t->GetLinkOptionsEntries(),
  106. this->LinkOptionsEntries);
  107. CreatePropertyGeneratorExpressions(*lg->GetCMakeInstance(),
  108. t->GetLinkDirectoriesEntries(),
  109. this->LinkDirectoriesEntries);
  110. CreatePropertyGeneratorExpressions(*lg->GetCMakeInstance(),
  111. t->GetPrecompileHeadersEntries(),
  112. this->PrecompileHeadersEntries);
  113. CreatePropertyGeneratorExpressions(
  114. *lg->GetCMakeInstance(), t->GetSourceEntries(), this->SourceEntries, true);
  115. this->PolicyMap = t->GetPolicyMap();
  116. // Get hard-coded linker language
  117. if (this->Target->GetProperty("HAS_CXX")) {
  118. this->LinkerLanguage = "CXX";
  119. } else {
  120. this->LinkerLanguage = this->Target->GetSafeProperty("LINKER_LANGUAGE");
  121. }
  122. auto configs =
  123. this->Makefile->GetGeneratorConfigs(cmMakefile::ExcludeEmptyConfig);
  124. std::string build_db_languages[] = { "CXX" };
  125. for (auto const& language : build_db_languages) {
  126. for (auto const& config : configs) {
  127. auto bdb_path = this->BuildDatabasePath(language, config);
  128. if (!bdb_path.empty()) {
  129. this->Makefile->GetOrCreateGeneratedSource(bdb_path);
  130. this->GetGlobalGenerator()->AddBuildDatabaseFile(language, config,
  131. bdb_path);
  132. }
  133. }
  134. }
  135. }
  136. cmGeneratorTarget::~cmGeneratorTarget() = default;
  137. cmValue cmGeneratorTarget::GetSourcesProperty() const
  138. {
  139. std::vector<std::string> values;
  140. for (auto const& se : this->SourceEntries) {
  141. values.push_back(se->GetInput());
  142. }
  143. static std::string value;
  144. value = cmList::to_string(values);
  145. return cmValue(value);
  146. }
  147. cmGlobalGenerator* cmGeneratorTarget::GetGlobalGenerator() const
  148. {
  149. return this->GetLocalGenerator()->GetGlobalGenerator();
  150. }
  151. cmLocalGenerator* cmGeneratorTarget::GetLocalGenerator() const
  152. {
  153. return this->LocalGenerator;
  154. }
  155. cmStateEnums::TargetType cmGeneratorTarget::GetType() const
  156. {
  157. return this->Target->GetType();
  158. }
  159. const std::string& cmGeneratorTarget::GetName() const
  160. {
  161. return this->Target->GetName();
  162. }
  163. std::string cmGeneratorTarget::GetFamilyName() const
  164. {
  165. if (!this->IsImported() && !this->IsSynthetic()) {
  166. return this->Target->GetTemplateName();
  167. }
  168. cmCryptoHash hasher(cmCryptoHash::AlgoSHA3_512);
  169. constexpr size_t HASH_TRUNCATION = 12;
  170. auto dirhash =
  171. hasher.HashString(this->GetLocalGenerator()->GetCurrentBinaryDirectory());
  172. auto targetIdent = hasher.HashString(cmStrCat("@d_", dirhash));
  173. return cmStrCat(this->Target->GetTemplateName(), '@',
  174. targetIdent.substr(0, HASH_TRUNCATION));
  175. }
  176. std::string cmGeneratorTarget::GetExportName() const
  177. {
  178. cmValue exportName = this->GetProperty("EXPORT_NAME");
  179. if (cmNonempty(exportName)) {
  180. if (!cmGeneratorExpression::IsValidTargetName(*exportName)) {
  181. std::ostringstream e;
  182. e << "EXPORT_NAME property \"" << *exportName << "\" for \""
  183. << this->GetName() << "\": is not valid.";
  184. cmSystemTools::Error(e.str());
  185. return "";
  186. }
  187. return *exportName;
  188. }
  189. return this->GetName();
  190. }
  191. std::string cmGeneratorTarget::GetFilesystemExportName() const
  192. {
  193. auto fs_safe = this->GetExportName();
  194. // First escape any `_` characters to avoid collisions.
  195. cmSystemTools::ReplaceString(fs_safe, "_", "__");
  196. // Escape other characters that are not generally filesystem-safe.
  197. cmSystemTools::ReplaceString(fs_safe, ":", "_c");
  198. return fs_safe;
  199. }
  200. cmValue cmGeneratorTarget::GetProperty(const std::string& prop) const
  201. {
  202. if (cmValue result =
  203. cmTargetPropertyComputer::GetProperty(this, prop, *this->Makefile)) {
  204. return result;
  205. }
  206. if (cmSystemTools::GetFatalErrorOccurred()) {
  207. return nullptr;
  208. }
  209. return this->Target->GetProperty(prop);
  210. }
  211. std::string const& cmGeneratorTarget::GetSafeProperty(
  212. std::string const& prop) const
  213. {
  214. return this->GetProperty(prop);
  215. }
  216. const char* cmGeneratorTarget::GetOutputTargetType(
  217. cmStateEnums::ArtifactType artifact) const
  218. {
  219. if (this->IsFrameworkOnApple() || this->GetGlobalGenerator()->IsXcode()) {
  220. // import file (i.e. .tbd file) is always in same location as library
  221. artifact = cmStateEnums::RuntimeBinaryArtifact;
  222. }
  223. switch (this->GetType()) {
  224. case cmStateEnums::SHARED_LIBRARY:
  225. if (this->IsDLLPlatform()) {
  226. switch (artifact) {
  227. case cmStateEnums::RuntimeBinaryArtifact:
  228. // A DLL shared library is treated as a runtime target.
  229. return "RUNTIME";
  230. case cmStateEnums::ImportLibraryArtifact:
  231. // A DLL import library is treated as an archive target.
  232. return "ARCHIVE";
  233. }
  234. } else {
  235. switch (artifact) {
  236. case cmStateEnums::RuntimeBinaryArtifact:
  237. // For non-DLL platforms shared libraries are treated as
  238. // library targets.
  239. return "LIBRARY";
  240. case cmStateEnums::ImportLibraryArtifact:
  241. // Library import libraries are treated as archive targets.
  242. return "ARCHIVE";
  243. }
  244. }
  245. break;
  246. case cmStateEnums::STATIC_LIBRARY:
  247. // Static libraries are always treated as archive targets.
  248. return "ARCHIVE";
  249. case cmStateEnums::MODULE_LIBRARY:
  250. switch (artifact) {
  251. case cmStateEnums::RuntimeBinaryArtifact:
  252. // Module libraries are always treated as library targets.
  253. return "LIBRARY";
  254. case cmStateEnums::ImportLibraryArtifact:
  255. // Module import libraries are treated as archive targets.
  256. return "ARCHIVE";
  257. }
  258. break;
  259. case cmStateEnums::OBJECT_LIBRARY:
  260. // Object libraries are always treated as object targets.
  261. return "OBJECT";
  262. case cmStateEnums::EXECUTABLE:
  263. switch (artifact) {
  264. case cmStateEnums::RuntimeBinaryArtifact:
  265. // Executables are always treated as runtime targets.
  266. return "RUNTIME";
  267. case cmStateEnums::ImportLibraryArtifact:
  268. // Executable import libraries are treated as archive targets.
  269. return "ARCHIVE";
  270. }
  271. break;
  272. default:
  273. break;
  274. }
  275. return "";
  276. }
  277. std::string cmGeneratorTarget::GetOutputName(
  278. const std::string& config, cmStateEnums::ArtifactType artifact) const
  279. {
  280. // Lookup/compute/cache the output name for this configuration.
  281. OutputNameKey key(config, artifact);
  282. auto i = this->OutputNameMap.find(key);
  283. if (i == this->OutputNameMap.end()) {
  284. // Add empty name in map to detect potential recursion.
  285. OutputNameMapType::value_type entry(key, "");
  286. i = this->OutputNameMap.insert(entry).first;
  287. // Compute output name.
  288. std::vector<std::string> props;
  289. std::string type = this->GetOutputTargetType(artifact);
  290. std::string configUpper = cmSystemTools::UpperCase(config);
  291. if (!type.empty() && !configUpper.empty()) {
  292. // <ARCHIVE|LIBRARY|RUNTIME>_OUTPUT_NAME_<CONFIG>
  293. props.push_back(type + "_OUTPUT_NAME_" + configUpper);
  294. }
  295. if (!type.empty()) {
  296. // <ARCHIVE|LIBRARY|RUNTIME>_OUTPUT_NAME
  297. props.push_back(type + "_OUTPUT_NAME");
  298. }
  299. if (!configUpper.empty()) {
  300. // OUTPUT_NAME_<CONFIG>
  301. props.push_back("OUTPUT_NAME_" + configUpper);
  302. // <CONFIG>_OUTPUT_NAME
  303. props.push_back(configUpper + "_OUTPUT_NAME");
  304. }
  305. // OUTPUT_NAME
  306. props.emplace_back("OUTPUT_NAME");
  307. std::string outName;
  308. for (std::string const& p : props) {
  309. if (cmValue outNameProp = this->GetProperty(p)) {
  310. outName = *outNameProp;
  311. break;
  312. }
  313. }
  314. if (outName.empty()) {
  315. outName = this->GetName();
  316. }
  317. // Now evaluate genex and update the previously-prepared map entry.
  318. i->second =
  319. cmGeneratorExpression::Evaluate(outName, this->LocalGenerator, config);
  320. } else if (i->second.empty()) {
  321. // An empty map entry indicates we have been called recursively
  322. // from the above block.
  323. this->LocalGenerator->GetCMakeInstance()->IssueMessage(
  324. MessageType::FATAL_ERROR,
  325. "Target '" + this->GetName() + "' OUTPUT_NAME depends on itself.",
  326. this->GetBacktrace());
  327. }
  328. return i->second;
  329. }
  330. std::string cmGeneratorTarget::GetFilePrefix(
  331. const std::string& config, cmStateEnums::ArtifactType artifact) const
  332. {
  333. if (this->IsImported()) {
  334. cmValue prefix = this->GetFilePrefixInternal(config, artifact);
  335. return prefix ? *prefix : std::string();
  336. }
  337. return this->GetFullNameInternalComponents(config, artifact).prefix;
  338. }
  339. std::string cmGeneratorTarget::GetFileSuffix(
  340. const std::string& config, cmStateEnums::ArtifactType artifact) const
  341. {
  342. if (this->IsImported()) {
  343. cmValue suffix = this->GetFileSuffixInternal(config, artifact);
  344. return suffix ? *suffix : std::string();
  345. }
  346. return this->GetFullNameInternalComponents(config, artifact).suffix;
  347. }
  348. std::string cmGeneratorTarget::GetFilePostfix(const std::string& config) const
  349. {
  350. cmValue postfix = nullptr;
  351. std::string frameworkPostfix;
  352. if (!config.empty()) {
  353. std::string configProp =
  354. cmStrCat(cmSystemTools::UpperCase(config), "_POSTFIX");
  355. postfix = this->GetProperty(configProp);
  356. // Mac application bundles and frameworks have no regular postfix like
  357. // libraries do.
  358. if (!this->IsImported() && postfix &&
  359. (this->IsAppBundleOnApple() || this->IsFrameworkOnApple())) {
  360. postfix = nullptr;
  361. }
  362. // Frameworks created by multi config generators can have a special
  363. // framework postfix.
  364. frameworkPostfix = this->GetFrameworkMultiConfigPostfix(config);
  365. if (!frameworkPostfix.empty()) {
  366. postfix = cmValue(frameworkPostfix);
  367. }
  368. }
  369. return postfix ? *postfix : std::string();
  370. }
  371. std::string cmGeneratorTarget::GetFrameworkMultiConfigPostfix(
  372. const std::string& config) const
  373. {
  374. cmValue postfix = nullptr;
  375. if (!config.empty()) {
  376. std::string configProp = cmStrCat("FRAMEWORK_MULTI_CONFIG_POSTFIX_",
  377. cmSystemTools::UpperCase(config));
  378. postfix = this->GetProperty(configProp);
  379. if (!this->IsImported() && postfix &&
  380. (this->IsFrameworkOnApple() &&
  381. !this->GetGlobalGenerator()->IsMultiConfig())) {
  382. postfix = nullptr;
  383. }
  384. }
  385. return postfix ? *postfix : std::string();
  386. }
  387. cmValue cmGeneratorTarget::GetFilePrefixInternal(
  388. std::string const& config, cmStateEnums::ArtifactType artifact,
  389. const std::string& language) const
  390. {
  391. // no prefix for non-main target types.
  392. if (this->GetType() != cmStateEnums::STATIC_LIBRARY &&
  393. this->GetType() != cmStateEnums::SHARED_LIBRARY &&
  394. this->GetType() != cmStateEnums::MODULE_LIBRARY &&
  395. this->GetType() != cmStateEnums::EXECUTABLE) {
  396. return nullptr;
  397. }
  398. const bool isImportedLibraryArtifact =
  399. (artifact == cmStateEnums::ImportLibraryArtifact);
  400. // Return an empty prefix for the import library if this platform
  401. // does not support import libraries.
  402. if (isImportedLibraryArtifact && !this->NeedImportLibraryName(config)) {
  403. return nullptr;
  404. }
  405. // The implib option is only allowed for shared libraries, module
  406. // libraries, and executables.
  407. if (this->GetType() != cmStateEnums::SHARED_LIBRARY &&
  408. this->GetType() != cmStateEnums::MODULE_LIBRARY &&
  409. this->GetType() != cmStateEnums::EXECUTABLE) {
  410. artifact = cmStateEnums::RuntimeBinaryArtifact;
  411. }
  412. // Compute prefix value.
  413. cmValue targetPrefix =
  414. (isImportedLibraryArtifact ? this->GetProperty("IMPORT_PREFIX")
  415. : this->GetProperty("PREFIX"));
  416. if (!targetPrefix) {
  417. const char* prefixVar = this->Target->GetPrefixVariableInternal(artifact);
  418. if (!language.empty() && cmNonempty(prefixVar)) {
  419. std::string langPrefix = cmStrCat(prefixVar, "_", language);
  420. targetPrefix = this->Makefile->GetDefinition(langPrefix);
  421. }
  422. // if there is no prefix on the target nor specific language
  423. // use the cmake definition.
  424. if (!targetPrefix && prefixVar) {
  425. targetPrefix = this->Makefile->GetDefinition(prefixVar);
  426. }
  427. }
  428. return targetPrefix;
  429. }
  430. cmValue cmGeneratorTarget::GetFileSuffixInternal(
  431. std::string const& config, cmStateEnums::ArtifactType artifact,
  432. const std::string& language) const
  433. {
  434. // no suffix for non-main target types.
  435. if (this->GetType() != cmStateEnums::STATIC_LIBRARY &&
  436. this->GetType() != cmStateEnums::SHARED_LIBRARY &&
  437. this->GetType() != cmStateEnums::MODULE_LIBRARY &&
  438. this->GetType() != cmStateEnums::EXECUTABLE) {
  439. return nullptr;
  440. }
  441. const bool isImportedLibraryArtifact =
  442. (artifact == cmStateEnums::ImportLibraryArtifact);
  443. // Return an empty suffix for the import library if this platform
  444. // does not support import libraries.
  445. if (isImportedLibraryArtifact && !this->NeedImportLibraryName(config)) {
  446. return nullptr;
  447. }
  448. // The implib option is only allowed for shared libraries, module
  449. // libraries, and executables.
  450. if (this->GetType() != cmStateEnums::SHARED_LIBRARY &&
  451. this->GetType() != cmStateEnums::MODULE_LIBRARY &&
  452. this->GetType() != cmStateEnums::EXECUTABLE) {
  453. artifact = cmStateEnums::RuntimeBinaryArtifact;
  454. }
  455. // Compute suffix value.
  456. cmValue targetSuffix =
  457. (isImportedLibraryArtifact ? this->GetProperty("IMPORT_SUFFIX")
  458. : this->GetProperty("SUFFIX"));
  459. if (!targetSuffix) {
  460. const char* suffixVar = this->Target->GetSuffixVariableInternal(artifact);
  461. if (!language.empty() && cmNonempty(suffixVar)) {
  462. std::string langSuffix = cmStrCat(suffixVar, "_", language);
  463. targetSuffix = this->Makefile->GetDefinition(langSuffix);
  464. }
  465. // if there is no suffix on the target nor specific language
  466. // use the cmake definition.
  467. if (!targetSuffix && suffixVar) {
  468. targetSuffix = this->Makefile->GetDefinition(suffixVar);
  469. }
  470. }
  471. return targetSuffix;
  472. }
  473. void cmGeneratorTarget::ClearSourcesCache()
  474. {
  475. this->AllConfigSources.clear();
  476. this->KindedSourcesMap.clear();
  477. this->SourcesAreContextDependent = Tribool::Indeterminate;
  478. this->Objects.clear();
  479. this->VisitedConfigsForObjects.clear();
  480. this->LinkImplClosureForLinkMap.clear();
  481. this->LinkImplClosureForUsageMap.clear();
  482. this->LinkImplMap.clear();
  483. this->LinkImplUsageRequirementsOnlyMap.clear();
  484. this->IncludeDirectoriesCache.clear();
  485. this->CompileOptionsCache.clear();
  486. this->CompileDefinitionsCache.clear();
  487. this->CustomTransitiveBuildPropertiesMap.clear();
  488. this->CustomTransitiveInterfacePropertiesMap.clear();
  489. this->PrecompileHeadersCache.clear();
  490. this->LinkOptionsCache.clear();
  491. this->LinkDirectoriesCache.clear();
  492. this->RuntimeBinaryFullNameCache.clear();
  493. this->ImportLibraryFullNameCache.clear();
  494. }
  495. void cmGeneratorTarget::ClearLinkInterfaceCache()
  496. {
  497. this->LinkInterfaceMap.clear();
  498. this->LinkInterfaceUsageRequirementsOnlyMap.clear();
  499. }
  500. void cmGeneratorTarget::AddSourceCommon(const std::string& src, bool before)
  501. {
  502. this->SourceEntries.insert(
  503. before ? this->SourceEntries.begin() : this->SourceEntries.end(),
  504. TargetPropertyEntry::Create(
  505. *this->LocalGenerator->GetCMakeInstance(),
  506. BT<std::string>(src, this->Makefile->GetBacktrace()), true));
  507. this->ClearSourcesCache();
  508. }
  509. void cmGeneratorTarget::AddSource(const std::string& src, bool before)
  510. {
  511. this->Target->AddSource(src, before);
  512. this->AddSourceCommon(src, before);
  513. }
  514. void cmGeneratorTarget::AddTracedSources(std::vector<std::string> const& srcs)
  515. {
  516. this->Target->AddTracedSources(srcs);
  517. if (!srcs.empty()) {
  518. this->AddSourceCommon(cmJoin(srcs, ";"));
  519. }
  520. }
  521. void cmGeneratorTarget::AddIncludeDirectory(const std::string& src,
  522. bool before)
  523. {
  524. this->Target->InsertInclude(
  525. BT<std::string>(src, this->Makefile->GetBacktrace()), before);
  526. this->IncludeDirectoriesEntries.insert(
  527. before ? this->IncludeDirectoriesEntries.begin()
  528. : this->IncludeDirectoriesEntries.end(),
  529. TargetPropertyEntry::Create(
  530. *this->Makefile->GetCMakeInstance(),
  531. BT<std::string>(src, this->Makefile->GetBacktrace()), true));
  532. }
  533. void cmGeneratorTarget::AddSystemIncludeDirectory(std::string const& inc,
  534. std::string const& lang)
  535. {
  536. std::string config_upper;
  537. auto const& configs =
  538. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  539. for (auto const& config : configs) {
  540. std::string inc_with_config = inc;
  541. if (!config.empty()) {
  542. cmSystemTools::ReplaceString(inc_with_config, "$<CONFIG>", config);
  543. config_upper = cmSystemTools::UpperCase(config);
  544. }
  545. auto const& key = cmStrCat(config_upper, "/", lang);
  546. this->Target->AddSystemIncludeDirectories({ inc_with_config });
  547. if (this->SystemIncludesCache.find(key) ==
  548. this->SystemIncludesCache.end()) {
  549. this->AddSystemIncludeCacheKey(key, config, lang);
  550. }
  551. this->SystemIncludesCache[key].emplace_back(inc_with_config);
  552. // SystemIncludesCache should be sorted so that binary search can be used
  553. std::sort(this->SystemIncludesCache[key].begin(),
  554. this->SystemIncludesCache[key].end());
  555. }
  556. }
  557. std::vector<cmSourceFile*> const* cmGeneratorTarget::GetSourceDepends(
  558. cmSourceFile const* sf) const
  559. {
  560. auto i = this->SourceDepends.find(sf);
  561. if (i != this->SourceDepends.end()) {
  562. return &i->second.Depends;
  563. }
  564. return nullptr;
  565. }
  566. namespace {
  567. void handleSystemIncludesDep(cmLocalGenerator* lg,
  568. cmGeneratorTarget const* depTgt,
  569. const std::string& config,
  570. cmGeneratorTarget const* headTarget,
  571. cmGeneratorExpressionDAGChecker* dagChecker,
  572. cmList& result, bool excludeImported,
  573. std::string const& language)
  574. {
  575. if (cmValue dirs =
  576. depTgt->GetProperty("INTERFACE_SYSTEM_INCLUDE_DIRECTORIES")) {
  577. result.append(cmGeneratorExpression::Evaluate(
  578. *dirs, lg, config, headTarget, dagChecker, depTgt, language));
  579. }
  580. if (!depTgt->GetPropertyAsBool("SYSTEM")) {
  581. return;
  582. }
  583. if (depTgt->IsImported()) {
  584. if (excludeImported) {
  585. return;
  586. }
  587. if (depTgt->GetPropertyAsBool("IMPORTED_NO_SYSTEM")) {
  588. return;
  589. }
  590. }
  591. if (cmValue dirs = depTgt->GetProperty("INTERFACE_INCLUDE_DIRECTORIES")) {
  592. result.append(cmGeneratorExpression::Evaluate(
  593. *dirs, lg, config, headTarget, dagChecker, depTgt, language));
  594. }
  595. if (depTgt->Target->IsFrameworkOnApple() ||
  596. depTgt->IsImportedFrameworkFolderOnApple(config)) {
  597. if (auto fwDescriptor = depTgt->GetGlobalGenerator()->SplitFrameworkPath(
  598. depTgt->GetLocation(config))) {
  599. result.push_back(fwDescriptor->Directory);
  600. result.push_back(fwDescriptor->GetFrameworkPath());
  601. }
  602. }
  603. }
  604. }
  605. /* clang-format off */
  606. #define IMPLEMENT_VISIT(KIND) \
  607. do { \
  608. KindedSources const& kinded = this->GetKindedSources(config); \
  609. for (SourceAndKind const& s : kinded.Sources) { \
  610. if (s.Kind == KIND) { \
  611. data.push_back(s.Source.Value); \
  612. } \
  613. } \
  614. } while (false)
  615. /* clang-format on */
  616. void cmGeneratorTarget::GetObjectSources(
  617. std::vector<cmSourceFile const*>& data, const std::string& config) const
  618. {
  619. IMPLEMENT_VISIT(SourceKindObjectSource);
  620. if (this->VisitedConfigsForObjects.count(config)) {
  621. return;
  622. }
  623. for (cmSourceFile const* it : data) {
  624. this->Objects[it];
  625. }
  626. this->LocalGenerator->ComputeObjectFilenames(this->Objects, this);
  627. this->VisitedConfigsForObjects.insert(config);
  628. }
  629. void cmGeneratorTarget::ComputeObjectMapping()
  630. {
  631. auto const& configs =
  632. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  633. std::set<std::string> configSet(configs.begin(), configs.end());
  634. if (configSet == this->VisitedConfigsForObjects) {
  635. return;
  636. }
  637. for (std::string const& c : configs) {
  638. std::vector<cmSourceFile const*> sourceFiles;
  639. this->GetObjectSources(sourceFiles, c);
  640. }
  641. }
  642. cmValue cmGeneratorTarget::GetFeature(const std::string& feature,
  643. const std::string& config) const
  644. {
  645. if (!config.empty()) {
  646. std::string featureConfig =
  647. cmStrCat(feature, '_', cmSystemTools::UpperCase(config));
  648. if (cmValue value = this->GetProperty(featureConfig)) {
  649. return value;
  650. }
  651. }
  652. if (cmValue value = this->GetProperty(feature)) {
  653. return value;
  654. }
  655. return this->LocalGenerator->GetFeature(feature, config);
  656. }
  657. std::string cmGeneratorTarget::GetLinkerTypeProperty(
  658. std::string const& lang, std::string const& config) const
  659. {
  660. std::string propName{ "LINKER_TYPE" };
  661. auto linkerType = this->GetProperty(propName);
  662. if (!linkerType.IsEmpty()) {
  663. cmGeneratorExpressionDAGChecker dagChecker{
  664. this, propName, nullptr, nullptr, this->LocalGenerator, config,
  665. };
  666. auto ltype =
  667. cmGeneratorExpression::Evaluate(*linkerType, this->GetLocalGenerator(),
  668. config, this, &dagChecker, this, lang);
  669. if (this->IsDeviceLink()) {
  670. cmList list{ ltype };
  671. const auto DL_BEGIN = "<DEVICE_LINK>"_s;
  672. const auto DL_END = "</DEVICE_LINK>"_s;
  673. cm::erase_if(list, [&](const std::string& item) {
  674. return item == DL_BEGIN || item == DL_END;
  675. });
  676. return list.to_string();
  677. }
  678. return ltype;
  679. }
  680. return std::string{};
  681. }
  682. const char* cmGeneratorTarget::GetLinkPIEProperty(
  683. const std::string& config) const
  684. {
  685. static std::string PICValue;
  686. PICValue = this->GetLinkInterfaceDependentStringAsBoolProperty(
  687. "POSITION_INDEPENDENT_CODE", config);
  688. if (PICValue == "(unset)") {
  689. // POSITION_INDEPENDENT_CODE is not set
  690. return nullptr;
  691. }
  692. auto status = this->GetPolicyStatusCMP0083();
  693. return (status != cmPolicies::WARN && status != cmPolicies::OLD)
  694. ? PICValue.c_str()
  695. : nullptr;
  696. }
  697. bool cmGeneratorTarget::IsIPOEnabled(std::string const& lang,
  698. std::string const& config) const
  699. {
  700. cmValue feature = this->GetFeature("INTERPROCEDURAL_OPTIMIZATION", config);
  701. if (!feature.IsOn()) {
  702. // 'INTERPROCEDURAL_OPTIMIZATION' is off, no need to check policies
  703. return false;
  704. }
  705. if (lang != "C" && lang != "CXX" && lang != "CUDA" && lang != "Fortran") {
  706. // We do not define IPO behavior for other languages.
  707. return false;
  708. }
  709. if (lang == "CUDA") {
  710. // CUDA IPO requires both CUDA_ARCHITECTURES and CUDA_SEPARABLE_COMPILATION
  711. if (cmIsOff(this->GetSafeProperty("CUDA_ARCHITECTURES")) ||
  712. cmIsOff(this->GetSafeProperty("CUDA_SEPARABLE_COMPILATION"))) {
  713. return false;
  714. }
  715. }
  716. cmPolicies::PolicyStatus cmp0069 = this->GetPolicyStatusCMP0069();
  717. if (cmp0069 == cmPolicies::OLD || cmp0069 == cmPolicies::WARN) {
  718. if (this->Makefile->IsOn("_CMAKE_" + lang + "_IPO_LEGACY_BEHAVIOR")) {
  719. return true;
  720. }
  721. if (this->PolicyReportedCMP0069) {
  722. // problem is already reported, no need to issue a message
  723. return false;
  724. }
  725. const bool in_try_compile =
  726. this->LocalGenerator->GetCMakeInstance()->GetIsInTryCompile();
  727. if (cmp0069 == cmPolicies::WARN && !in_try_compile) {
  728. std::ostringstream w;
  729. w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0069) << "\n";
  730. w << "INTERPROCEDURAL_OPTIMIZATION property will be ignored for target "
  731. << "'" << this->GetName() << "'.";
  732. this->LocalGenerator->GetCMakeInstance()->IssueMessage(
  733. MessageType::AUTHOR_WARNING, w.str(), this->GetBacktrace());
  734. this->PolicyReportedCMP0069 = true;
  735. }
  736. return false;
  737. }
  738. // Note: check consistency with messages from CheckIPOSupported
  739. const char* message = nullptr;
  740. if (!this->Makefile->IsOn("_CMAKE_" + lang + "_IPO_SUPPORTED_BY_CMAKE")) {
  741. message = "CMake doesn't support IPO for current compiler";
  742. } else if (!this->Makefile->IsOn("_CMAKE_" + lang +
  743. "_IPO_MAY_BE_SUPPORTED_BY_COMPILER")) {
  744. message = "Compiler doesn't support IPO";
  745. } else if (!this->GlobalGenerator->IsIPOSupported()) {
  746. message = "CMake doesn't support IPO for current generator";
  747. }
  748. if (!message) {
  749. // No error/warning messages
  750. return true;
  751. }
  752. if (this->PolicyReportedCMP0069) {
  753. // problem is already reported, no need to issue a message
  754. return false;
  755. }
  756. this->PolicyReportedCMP0069 = true;
  757. this->LocalGenerator->GetCMakeInstance()->IssueMessage(
  758. MessageType::FATAL_ERROR, message, this->GetBacktrace());
  759. return false;
  760. }
  761. const std::string& cmGeneratorTarget::GetObjectName(cmSourceFile const* file)
  762. {
  763. this->ComputeObjectMapping();
  764. return this->Objects[file];
  765. }
  766. const char* cmGeneratorTarget::GetCustomObjectExtension() const
  767. {
  768. struct compiler_mode
  769. {
  770. std::string variable;
  771. std::string extension;
  772. };
  773. static std::array<compiler_mode, 4> const modes{
  774. { { "CUDA_PTX_COMPILATION", ".ptx" },
  775. { "CUDA_CUBIN_COMPILATION", ".cubin" },
  776. { "CUDA_FATBIN_COMPILATION", ".fatbin" },
  777. { "CUDA_OPTIX_COMPILATION", ".optixir" } }
  778. };
  779. std::string const& compiler =
  780. this->Makefile->GetSafeDefinition("CMAKE_CUDA_COMPILER_ID");
  781. if (!compiler.empty()) {
  782. for (const auto& m : modes) {
  783. const bool has_extension = this->GetPropertyAsBool(m.variable);
  784. if (has_extension) {
  785. return m.extension.c_str();
  786. }
  787. }
  788. }
  789. return nullptr;
  790. }
  791. void cmGeneratorTarget::AddExplicitObjectName(cmSourceFile const* sf)
  792. {
  793. this->ExplicitObjectName.insert(sf);
  794. }
  795. bool cmGeneratorTarget::HasExplicitObjectName(cmSourceFile const* file) const
  796. {
  797. const_cast<cmGeneratorTarget*>(this)->ComputeObjectMapping();
  798. auto it = this->ExplicitObjectName.find(file);
  799. return it != this->ExplicitObjectName.end();
  800. }
  801. BTs<std::string> const* cmGeneratorTarget::GetLanguageStandardProperty(
  802. std::string const& lang, std::string const& config) const
  803. {
  804. std::string key = cmStrCat(cmSystemTools::UpperCase(config), '-', lang);
  805. auto langStandardIter = this->LanguageStandardMap.find(key);
  806. if (langStandardIter != this->LanguageStandardMap.end()) {
  807. return &langStandardIter->second;
  808. }
  809. return this->Target->GetLanguageStandardProperty(
  810. cmStrCat(lang, "_STANDARD"));
  811. }
  812. cmValue cmGeneratorTarget::GetLanguageStandard(std::string const& lang,
  813. std::string const& config) const
  814. {
  815. BTs<std::string> const* languageStandard =
  816. this->GetLanguageStandardProperty(lang, config);
  817. if (languageStandard) {
  818. return cmValue(languageStandard->Value);
  819. }
  820. return nullptr;
  821. }
  822. cmValue cmGeneratorTarget::GetPropertyWithPairedLanguageSupport(
  823. std::string const& lang, const char* suffix) const
  824. {
  825. cmValue propertyValue = this->Target->GetProperty(cmStrCat(lang, suffix));
  826. if (!propertyValue) {
  827. // Check if we should use the value set by another language.
  828. if (lang == "OBJC") {
  829. propertyValue = this->GetPropertyWithPairedLanguageSupport("C", suffix);
  830. } else if (lang == "OBJCXX" || lang == "CUDA" || lang == "HIP") {
  831. propertyValue =
  832. this->GetPropertyWithPairedLanguageSupport("CXX", suffix);
  833. }
  834. }
  835. return propertyValue;
  836. }
  837. cmValue cmGeneratorTarget::GetLanguageExtensions(std::string const& lang) const
  838. {
  839. return this->GetPropertyWithPairedLanguageSupport(lang, "_EXTENSIONS");
  840. }
  841. bool cmGeneratorTarget::GetLanguageStandardRequired(
  842. std::string const& lang) const
  843. {
  844. return this->GetPropertyWithPairedLanguageSupport(lang, "_STANDARD_REQUIRED")
  845. .IsOn();
  846. }
  847. void cmGeneratorTarget::GetModuleDefinitionSources(
  848. std::vector<cmSourceFile const*>& data, const std::string& config) const
  849. {
  850. IMPLEMENT_VISIT(SourceKindModuleDefinition);
  851. }
  852. void cmGeneratorTarget::GetHeaderSources(
  853. std::vector<cmSourceFile const*>& data, const std::string& config) const
  854. {
  855. IMPLEMENT_VISIT(SourceKindHeader);
  856. }
  857. void cmGeneratorTarget::GetCxxModuleSources(
  858. std::vector<cmSourceFile const*>& data, const std::string& config) const
  859. {
  860. IMPLEMENT_VISIT(SourceKindCxxModuleSource);
  861. }
  862. void cmGeneratorTarget::GetExtraSources(std::vector<cmSourceFile const*>& data,
  863. const std::string& config) const
  864. {
  865. IMPLEMENT_VISIT(SourceKindExtra);
  866. }
  867. void cmGeneratorTarget::GetCustomCommands(
  868. std::vector<cmSourceFile const*>& data, const std::string& config) const
  869. {
  870. IMPLEMENT_VISIT(SourceKindCustomCommand);
  871. }
  872. void cmGeneratorTarget::GetExternalObjects(
  873. std::vector<cmSourceFile const*>& data, const std::string& config) const
  874. {
  875. IMPLEMENT_VISIT(SourceKindExternalObject);
  876. }
  877. void cmGeneratorTarget::GetManifests(std::vector<cmSourceFile const*>& data,
  878. const std::string& config) const
  879. {
  880. IMPLEMENT_VISIT(SourceKindManifest);
  881. }
  882. std::set<cmLinkItem> const& cmGeneratorTarget::GetUtilityItems() const
  883. {
  884. if (!this->UtilityItemsDone) {
  885. this->UtilityItemsDone = true;
  886. std::set<BT<std::pair<std::string, bool>>> const& utilities =
  887. this->GetUtilities();
  888. for (BT<std::pair<std::string, bool>> const& i : utilities) {
  889. if (cmGeneratorTarget* gt =
  890. this->LocalGenerator->FindGeneratorTargetToUse(i.Value.first)) {
  891. this->UtilityItems.insert(cmLinkItem(gt, i.Value.second, i.Backtrace));
  892. } else {
  893. this->UtilityItems.insert(
  894. cmLinkItem(i.Value.first, i.Value.second, i.Backtrace));
  895. }
  896. }
  897. }
  898. return this->UtilityItems;
  899. }
  900. const std::string& cmGeneratorTarget::GetLocation(
  901. const std::string& config) const
  902. {
  903. static std::string location;
  904. if (this->IsImported()) {
  905. location = this->Target->ImportedGetFullPath(
  906. config, cmStateEnums::RuntimeBinaryArtifact);
  907. } else {
  908. location = this->GetFullPath(config, cmStateEnums::RuntimeBinaryArtifact);
  909. }
  910. return location;
  911. }
  912. cm::optional<std::string> cmGeneratorTarget::MaybeGetLocation(
  913. std::string const& config) const
  914. {
  915. cm::optional<std::string> location;
  916. if (cmGeneratorTarget::ImportInfo const* imp = this->GetImportInfo(config)) {
  917. if (!imp->Location.empty()) {
  918. location = imp->Location;
  919. }
  920. } else {
  921. location = this->GetFullPath(config, cmStateEnums::RuntimeBinaryArtifact);
  922. }
  923. return location;
  924. }
  925. std::vector<cmCustomCommand> const& cmGeneratorTarget::GetPreBuildCommands()
  926. const
  927. {
  928. return this->Target->GetPreBuildCommands();
  929. }
  930. std::vector<cmCustomCommand> const& cmGeneratorTarget::GetPreLinkCommands()
  931. const
  932. {
  933. return this->Target->GetPreLinkCommands();
  934. }
  935. std::vector<cmCustomCommand> const& cmGeneratorTarget::GetPostBuildCommands()
  936. const
  937. {
  938. return this->Target->GetPostBuildCommands();
  939. }
  940. void cmGeneratorTarget::AppendCustomCommandSideEffects(
  941. std::set<cmGeneratorTarget const*>& sideEffects) const
  942. {
  943. if (!this->GetPreBuildCommands().empty() ||
  944. !this->GetPreLinkCommands().empty() ||
  945. !this->GetPostBuildCommands().empty()) {
  946. sideEffects.insert(this);
  947. } else {
  948. for (auto const& source : this->GetAllConfigSources()) {
  949. if (source.Source->GetCustomCommand()) {
  950. sideEffects.insert(this);
  951. break;
  952. }
  953. }
  954. }
  955. }
  956. void cmGeneratorTarget::AppendLanguageSideEffects(
  957. std::map<std::string, std::set<cmGeneratorTarget const*>>& sideEffects) const
  958. {
  959. static const std::set<cm::string_view> LANGS_WITH_NO_SIDE_EFFECTS = {
  960. "C"_s, "CXX"_s, "OBJC"_s, "OBJCXX"_s, "ASM"_s, "CUDA"_s, "HIP"_s
  961. };
  962. for (auto const& lang : this->GetAllConfigCompileLanguages()) {
  963. if (!LANGS_WITH_NO_SIDE_EFFECTS.count(lang)) {
  964. sideEffects[lang].insert(this);
  965. }
  966. }
  967. }
  968. bool cmGeneratorTarget::IsInBuildSystem() const
  969. {
  970. if (this->IsImported()) {
  971. return false;
  972. }
  973. switch (this->Target->GetType()) {
  974. case cmStateEnums::EXECUTABLE:
  975. case cmStateEnums::STATIC_LIBRARY:
  976. case cmStateEnums::SHARED_LIBRARY:
  977. case cmStateEnums::MODULE_LIBRARY:
  978. case cmStateEnums::OBJECT_LIBRARY:
  979. case cmStateEnums::UTILITY:
  980. case cmStateEnums::GLOBAL_TARGET:
  981. return true;
  982. case cmStateEnums::INTERFACE_LIBRARY:
  983. // An INTERFACE library is in the build system if it has SOURCES
  984. // or C++ module filesets.
  985. if (!this->SourceEntries.empty() ||
  986. !this->Target->GetHeaderSetsEntries().empty() ||
  987. !this->Target->GetCxxModuleSetsEntries().empty()) {
  988. return true;
  989. }
  990. break;
  991. case cmStateEnums::UNKNOWN_LIBRARY:
  992. break;
  993. }
  994. return false;
  995. }
  996. bool cmGeneratorTarget::IsNormal() const
  997. {
  998. return this->Target->IsNormal();
  999. }
  1000. bool cmGeneratorTarget::IsRuntimeBinary() const
  1001. {
  1002. return this->Target->IsRuntimeBinary();
  1003. }
  1004. bool cmGeneratorTarget::IsSynthetic() const
  1005. {
  1006. return this->Target->IsSynthetic();
  1007. }
  1008. bool cmGeneratorTarget::IsImported() const
  1009. {
  1010. return this->Target->IsImported();
  1011. }
  1012. bool cmGeneratorTarget::IsImportedGloballyVisible() const
  1013. {
  1014. return this->Target->IsImportedGloballyVisible();
  1015. }
  1016. bool cmGeneratorTarget::CanCompileSources() const
  1017. {
  1018. return this->Target->CanCompileSources();
  1019. }
  1020. bool cmGeneratorTarget::HasKnownRuntimeArtifactLocation(
  1021. std::string const& config) const
  1022. {
  1023. if (!this->IsRuntimeBinary()) {
  1024. return false;
  1025. }
  1026. if (!this->IsImported()) {
  1027. return true;
  1028. }
  1029. ImportInfo const* info = this->GetImportInfo(config);
  1030. return info && !info->Location.empty();
  1031. }
  1032. const std::string& cmGeneratorTarget::GetLocationForBuild() const
  1033. {
  1034. static std::string location;
  1035. if (this->IsImported()) {
  1036. location = this->Target->ImportedGetFullPath(
  1037. "", cmStateEnums::RuntimeBinaryArtifact);
  1038. return location;
  1039. }
  1040. // Now handle the deprecated build-time configuration location.
  1041. std::string const noConfig;
  1042. location = this->GetDirectory(noConfig);
  1043. cmValue cfgid = this->Makefile->GetDefinition("CMAKE_CFG_INTDIR");
  1044. if (cfgid && (*cfgid != ".")) {
  1045. location += "/";
  1046. location += *cfgid;
  1047. }
  1048. if (this->IsAppBundleOnApple()) {
  1049. std::string macdir = this->BuildBundleDirectory("", "", FullLevel);
  1050. if (!macdir.empty()) {
  1051. location += "/";
  1052. location += macdir;
  1053. }
  1054. }
  1055. location += "/";
  1056. location += this->GetFullName("", cmStateEnums::RuntimeBinaryArtifact);
  1057. return location;
  1058. }
  1059. void cmGeneratorTarget::AddSystemIncludeCacheKey(
  1060. const std::string& key, const std::string& config,
  1061. const std::string& language) const
  1062. {
  1063. cmGeneratorExpressionDAGChecker dagChecker{
  1064. this, "SYSTEM_INCLUDE_DIRECTORIES", nullptr,
  1065. nullptr, this->LocalGenerator, config,
  1066. };
  1067. bool excludeImported = this->GetPropertyAsBool("NO_SYSTEM_FROM_IMPORTED");
  1068. cmList result;
  1069. for (std::string const& it : this->Target->GetSystemIncludeDirectories()) {
  1070. result.append(cmGeneratorExpression::Evaluate(
  1071. it, this->LocalGenerator, config, this, &dagChecker, nullptr, language));
  1072. }
  1073. std::vector<cmGeneratorTarget const*> const& deps =
  1074. this->GetLinkImplementationClosure(config, UseTo::Compile);
  1075. for (cmGeneratorTarget const* dep : deps) {
  1076. handleSystemIncludesDep(this->LocalGenerator, dep, config, this,
  1077. &dagChecker, result, excludeImported, language);
  1078. }
  1079. cmLinkImplementation const* impl =
  1080. this->GetLinkImplementation(config, UseTo::Compile);
  1081. if (impl) {
  1082. auto runtimeEntries = impl->LanguageRuntimeLibraries.find(language);
  1083. if (runtimeEntries != impl->LanguageRuntimeLibraries.end()) {
  1084. for (auto const& lib : runtimeEntries->second) {
  1085. if (lib.Target) {
  1086. handleSystemIncludesDep(this->LocalGenerator, lib.Target, config,
  1087. this, &dagChecker, result, excludeImported,
  1088. language);
  1089. }
  1090. }
  1091. }
  1092. }
  1093. std::for_each(result.begin(), result.end(),
  1094. cmSystemTools::ConvertToUnixSlashes);
  1095. std::sort(result.begin(), result.end());
  1096. result.erase(std::unique(result.begin(), result.end()), result.end());
  1097. SystemIncludesCache.emplace(key, result);
  1098. }
  1099. bool cmGeneratorTarget::IsSystemIncludeDirectory(
  1100. const std::string& dir, const std::string& config,
  1101. const std::string& language) const
  1102. {
  1103. std::string config_upper;
  1104. if (!config.empty()) {
  1105. config_upper = cmSystemTools::UpperCase(config);
  1106. }
  1107. std::string key = cmStrCat(config_upper, '/', language);
  1108. auto iter = this->SystemIncludesCache.find(key);
  1109. if (iter == this->SystemIncludesCache.end()) {
  1110. this->AddSystemIncludeCacheKey(key, config, language);
  1111. iter = this->SystemIncludesCache.find(key);
  1112. }
  1113. return std::binary_search(iter->second.begin(), iter->second.end(), dir);
  1114. }
  1115. bool cmGeneratorTarget::GetPropertyAsBool(const std::string& prop) const
  1116. {
  1117. return this->Target->GetPropertyAsBool(prop);
  1118. }
  1119. std::string cmGeneratorTarget::GetCompilePDBName(
  1120. const std::string& config) const
  1121. {
  1122. // Check for a per-configuration output directory target property.
  1123. std::string configUpper = cmSystemTools::UpperCase(config);
  1124. std::string configProp = cmStrCat("COMPILE_PDB_NAME_", configUpper);
  1125. cmValue config_name = this->GetProperty(configProp);
  1126. if (cmNonempty(config_name)) {
  1127. NameComponents const& components = GetFullNameInternalComponents(
  1128. config, cmStateEnums::RuntimeBinaryArtifact);
  1129. return components.prefix + *config_name + ".pdb";
  1130. }
  1131. cmValue name = this->GetProperty("COMPILE_PDB_NAME");
  1132. if (cmNonempty(name)) {
  1133. NameComponents const& components = GetFullNameInternalComponents(
  1134. config, cmStateEnums::RuntimeBinaryArtifact);
  1135. return components.prefix + *name + ".pdb";
  1136. }
  1137. return "";
  1138. }
  1139. std::string cmGeneratorTarget::GetCompilePDBPath(
  1140. const std::string& config) const
  1141. {
  1142. std::string dir = this->GetCompilePDBDirectory(config);
  1143. std::string name = this->GetCompilePDBName(config);
  1144. if (dir.empty() && !name.empty() && this->HaveWellDefinedOutputFiles()) {
  1145. dir = this->GetPDBDirectory(config);
  1146. }
  1147. if (!dir.empty()) {
  1148. dir += "/";
  1149. }
  1150. return dir + name;
  1151. }
  1152. bool cmGeneratorTarget::HasSOName(const std::string& config) const
  1153. {
  1154. // soname is supported only for shared libraries and modules,
  1155. // and then only when the platform supports an soname flag.
  1156. return ((this->GetType() == cmStateEnums::SHARED_LIBRARY) &&
  1157. !this->GetPropertyAsBool("NO_SONAME") &&
  1158. (this->Makefile->GetSONameFlag(this->GetLinkerLanguage(config)) ||
  1159. this->IsArchivedAIXSharedLibrary()));
  1160. }
  1161. bool cmGeneratorTarget::NeedRelinkBeforeInstall(
  1162. const std::string& config) const
  1163. {
  1164. // Only executables and shared libraries can have an rpath and may
  1165. // need relinking.
  1166. if (this->GetType() != cmStateEnums::EXECUTABLE &&
  1167. this->GetType() != cmStateEnums::SHARED_LIBRARY &&
  1168. this->GetType() != cmStateEnums::MODULE_LIBRARY) {
  1169. return false;
  1170. }
  1171. // If there is no install location this target will not be installed
  1172. // and therefore does not need relinking.
  1173. if (!this->Target->GetHaveInstallRule()) {
  1174. return false;
  1175. }
  1176. // If skipping all rpaths completely then no relinking is needed.
  1177. if (this->Makefile->IsOn("CMAKE_SKIP_RPATH")) {
  1178. return false;
  1179. }
  1180. // If building with the install-tree rpath no relinking is needed.
  1181. if (this->GetPropertyAsBool("BUILD_WITH_INSTALL_RPATH")) {
  1182. return false;
  1183. }
  1184. // If chrpath is going to be used no relinking is needed.
  1185. if (this->IsChrpathUsed(config)) {
  1186. return false;
  1187. }
  1188. // Check for rpath support on this platform.
  1189. std::string ll = this->GetLinkerLanguage(config);
  1190. if (!ll.empty()) {
  1191. std::string flagVar =
  1192. cmStrCat("CMAKE_SHARED_LIBRARY_RUNTIME_", ll, "_FLAG");
  1193. if (!this->Makefile->IsSet(flagVar)) {
  1194. // There is no rpath support on this platform so nothing needs
  1195. // relinking.
  1196. return false;
  1197. }
  1198. } else {
  1199. // No linker language is known. This error will be reported by
  1200. // other code.
  1201. return false;
  1202. }
  1203. // If either a build or install tree rpath is set then the rpath
  1204. // will likely change between the build tree and install tree and
  1205. // this target must be relinked.
  1206. bool have_rpath =
  1207. this->HaveBuildTreeRPATH(config) || this->HaveInstallTreeRPATH(config);
  1208. bool is_ninja = this->LocalGenerator->GetGlobalGenerator()->IsNinja();
  1209. if (have_rpath && is_ninja) {
  1210. std::ostringstream w;
  1211. /* clang-format off */
  1212. w <<
  1213. "The install of the " << this->GetName() << " target requires changing "
  1214. "an RPATH from the build tree, but this is not supported with the Ninja "
  1215. "generator unless on an ELF-based or XCOFF-based platform. "
  1216. "The CMAKE_BUILD_WITH_INSTALL_RPATH variable may be set to avoid this "
  1217. "relinking step."
  1218. ;
  1219. /* clang-format on */
  1220. cmake* cm = this->LocalGenerator->GetCMakeInstance();
  1221. cm->IssueMessage(MessageType::FATAL_ERROR, w.str(), this->GetBacktrace());
  1222. }
  1223. return have_rpath;
  1224. }
  1225. bool cmGeneratorTarget::IsChrpathUsed(const std::string& config) const
  1226. {
  1227. // Only certain target types have an rpath.
  1228. if (!(this->GetType() == cmStateEnums::SHARED_LIBRARY ||
  1229. this->GetType() == cmStateEnums::MODULE_LIBRARY ||
  1230. this->GetType() == cmStateEnums::EXECUTABLE)) {
  1231. return false;
  1232. }
  1233. // If the target will not be installed we do not need to change its
  1234. // rpath.
  1235. if (!this->Target->GetHaveInstallRule()) {
  1236. return false;
  1237. }
  1238. // Skip chrpath if skipping rpath altogether.
  1239. if (this->Makefile->IsOn("CMAKE_SKIP_RPATH")) {
  1240. return false;
  1241. }
  1242. // Skip chrpath if it does not need to be changed at install time.
  1243. if (this->GetPropertyAsBool("BUILD_WITH_INSTALL_RPATH")) {
  1244. return false;
  1245. }
  1246. // Allow the user to disable builtin chrpath explicitly.
  1247. if (this->Makefile->IsOn("CMAKE_NO_BUILTIN_CHRPATH")) {
  1248. return false;
  1249. }
  1250. if (this->Makefile->IsOn("CMAKE_PLATFORM_HAS_INSTALLNAME")) {
  1251. return true;
  1252. }
  1253. // Enable if the rpath flag uses a separator and the target uses
  1254. // binaries we know how to edit.
  1255. std::string ll = this->GetLinkerLanguage(config);
  1256. if (!ll.empty()) {
  1257. std::string sepVar =
  1258. cmStrCat("CMAKE_SHARED_LIBRARY_RUNTIME_", ll, "_FLAG_SEP");
  1259. cmValue sep = this->Makefile->GetDefinition(sepVar);
  1260. if (cmNonempty(sep)) {
  1261. // TODO: Add binary format check to ABI detection and get rid of
  1262. // CMAKE_EXECUTABLE_FORMAT.
  1263. if (cmValue fmt =
  1264. this->Makefile->GetDefinition("CMAKE_EXECUTABLE_FORMAT")) {
  1265. if (*fmt == "ELF") {
  1266. return true;
  1267. }
  1268. #if defined(CMake_USE_XCOFF_PARSER)
  1269. if (*fmt == "XCOFF") {
  1270. return true;
  1271. }
  1272. #endif
  1273. }
  1274. }
  1275. }
  1276. return false;
  1277. }
  1278. bool cmGeneratorTarget::IsImportedSharedLibWithoutSOName(
  1279. const std::string& config) const
  1280. {
  1281. if (this->IsImported() && this->GetType() == cmStateEnums::SHARED_LIBRARY) {
  1282. if (cmGeneratorTarget::ImportInfo const* info =
  1283. this->GetImportInfo(config)) {
  1284. return info->NoSOName;
  1285. }
  1286. }
  1287. return false;
  1288. }
  1289. bool cmGeneratorTarget::HasMacOSXRpathInstallNameDir(
  1290. const std::string& config) const
  1291. {
  1292. TargetPtrToBoolMap& cache = this->MacOSXRpathInstallNameDirCache[config];
  1293. const auto lookup = cache.find(this->Target);
  1294. if (lookup != cache.cend()) {
  1295. return lookup->second;
  1296. }
  1297. const bool result = this->DetermineHasMacOSXRpathInstallNameDir(config);
  1298. cache[this->Target] = result;
  1299. return result;
  1300. }
  1301. bool cmGeneratorTarget::DetermineHasMacOSXRpathInstallNameDir(
  1302. const std::string& config) const
  1303. {
  1304. bool install_name_is_rpath = false;
  1305. bool macosx_rpath = false;
  1306. if (!this->IsImported()) {
  1307. if (this->GetType() != cmStateEnums::SHARED_LIBRARY) {
  1308. return false;
  1309. }
  1310. cmValue install_name = this->GetProperty("INSTALL_NAME_DIR");
  1311. bool use_install_name = this->MacOSXUseInstallNameDir();
  1312. if (install_name && use_install_name && *install_name == "@rpath") {
  1313. install_name_is_rpath = true;
  1314. } else if (install_name && use_install_name) {
  1315. return false;
  1316. }
  1317. if (!install_name_is_rpath) {
  1318. macosx_rpath = this->MacOSXRpathInstallNameDirDefault();
  1319. }
  1320. } else {
  1321. // Lookup the imported soname.
  1322. if (cmGeneratorTarget::ImportInfo const* info =
  1323. this->GetImportInfo(config)) {
  1324. if (!info->NoSOName && !info->SOName.empty()) {
  1325. if (cmHasLiteralPrefix(info->SOName, "@rpath/")) {
  1326. install_name_is_rpath = true;
  1327. }
  1328. } else {
  1329. std::string install_name;
  1330. cmSystemTools::GuessLibraryInstallName(info->Location, install_name);
  1331. if (install_name.find("@rpath") != std::string::npos) {
  1332. install_name_is_rpath = true;
  1333. }
  1334. }
  1335. }
  1336. }
  1337. if (!install_name_is_rpath && !macosx_rpath) {
  1338. return false;
  1339. }
  1340. if (!this->Makefile->IsSet("CMAKE_SHARED_LIBRARY_RUNTIME_C_FLAG")) {
  1341. std::ostringstream w;
  1342. w << "Attempting to use ";
  1343. if (macosx_rpath) {
  1344. w << "MACOSX_RPATH";
  1345. } else {
  1346. w << "@rpath";
  1347. }
  1348. w << " without CMAKE_SHARED_LIBRARY_RUNTIME_C_FLAG being set.";
  1349. w << " This could be because you are using a Mac OS X version";
  1350. w << " less than 10.5 or because CMake's platform configuration is";
  1351. w << " corrupt.";
  1352. cmake* cm = this->LocalGenerator->GetCMakeInstance();
  1353. cm->IssueMessage(MessageType::FATAL_ERROR, w.str(), this->GetBacktrace());
  1354. }
  1355. return true;
  1356. }
  1357. bool cmGeneratorTarget::MacOSXRpathInstallNameDirDefault() const
  1358. {
  1359. // we can't do rpaths when unsupported
  1360. if (!this->Makefile->IsSet("CMAKE_SHARED_LIBRARY_RUNTIME_C_FLAG")) {
  1361. return false;
  1362. }
  1363. cmValue macosx_rpath_str = this->GetProperty("MACOSX_RPATH");
  1364. if (macosx_rpath_str) {
  1365. return this->GetPropertyAsBool("MACOSX_RPATH");
  1366. }
  1367. cmPolicies::PolicyStatus cmp0042 = this->GetPolicyStatusCMP0042();
  1368. if (cmp0042 == cmPolicies::WARN) {
  1369. this->LocalGenerator->GetGlobalGenerator()->AddCMP0042WarnTarget(
  1370. this->GetName());
  1371. }
  1372. return cmp0042 == cmPolicies::NEW;
  1373. }
  1374. bool cmGeneratorTarget::MacOSXUseInstallNameDir() const
  1375. {
  1376. cmValue build_with_install_name =
  1377. this->GetProperty("BUILD_WITH_INSTALL_NAME_DIR");
  1378. if (build_with_install_name) {
  1379. return build_with_install_name.IsOn();
  1380. }
  1381. cmPolicies::PolicyStatus cmp0068 = this->GetPolicyStatusCMP0068();
  1382. if (cmp0068 == cmPolicies::NEW) {
  1383. return false;
  1384. }
  1385. bool use_install_name = this->GetPropertyAsBool("BUILD_WITH_INSTALL_RPATH");
  1386. if (use_install_name && cmp0068 == cmPolicies::WARN) {
  1387. this->LocalGenerator->GetGlobalGenerator()->AddCMP0068WarnTarget(
  1388. this->GetName());
  1389. }
  1390. return use_install_name;
  1391. }
  1392. bool cmGeneratorTarget::CanGenerateInstallNameDir(
  1393. InstallNameType name_type) const
  1394. {
  1395. cmPolicies::PolicyStatus cmp0068 = this->GetPolicyStatusCMP0068();
  1396. if (cmp0068 == cmPolicies::NEW) {
  1397. return true;
  1398. }
  1399. bool skip = this->Makefile->IsOn("CMAKE_SKIP_RPATH");
  1400. if (name_type == INSTALL_NAME_FOR_INSTALL) {
  1401. skip |= this->Makefile->IsOn("CMAKE_SKIP_INSTALL_RPATH");
  1402. } else {
  1403. skip |= this->GetPropertyAsBool("SKIP_BUILD_RPATH");
  1404. }
  1405. if (skip && cmp0068 == cmPolicies::WARN) {
  1406. this->LocalGenerator->GetGlobalGenerator()->AddCMP0068WarnTarget(
  1407. this->GetName());
  1408. }
  1409. return !skip;
  1410. }
  1411. std::string cmGeneratorTarget::GetSOName(
  1412. const std::string& config, cmStateEnums::ArtifactType artifact) const
  1413. {
  1414. if (this->IsImported()) {
  1415. // Lookup the imported soname.
  1416. if (cmGeneratorTarget::ImportInfo const* info =
  1417. this->GetImportInfo(config)) {
  1418. if (info->NoSOName) {
  1419. // The imported library has no builtin soname so the name
  1420. // searched at runtime will be just the filename.
  1421. return cmSystemTools::GetFilenameName(info->Location);
  1422. }
  1423. // Use the soname given if any.
  1424. if (this->IsFrameworkOnApple()) {
  1425. auto fwDescriptor = this->GetGlobalGenerator()->SplitFrameworkPath(
  1426. info->SOName, cmGlobalGenerator::FrameworkFormat::Strict);
  1427. if (fwDescriptor) {
  1428. return fwDescriptor->GetVersionedName();
  1429. }
  1430. }
  1431. if (cmHasLiteralPrefix(info->SOName, "@rpath/")) {
  1432. return info->SOName.substr(cmStrLen("@rpath/"));
  1433. }
  1434. return info->SOName;
  1435. }
  1436. return "";
  1437. }
  1438. // Compute the soname that will be built.
  1439. return artifact == cmStateEnums::RuntimeBinaryArtifact
  1440. ? this->GetLibraryNames(config).SharedObject
  1441. : this->GetLibraryNames(config).ImportLibrary;
  1442. }
  1443. namespace {
  1444. bool shouldAddFullLevel(cmGeneratorTarget::BundleDirectoryLevel level)
  1445. {
  1446. return level == cmGeneratorTarget::FullLevel;
  1447. }
  1448. bool shouldAddContentLevel(cmGeneratorTarget::BundleDirectoryLevel level)
  1449. {
  1450. return level == cmGeneratorTarget::ContentLevel || shouldAddFullLevel(level);
  1451. }
  1452. }
  1453. std::string cmGeneratorTarget::GetAppBundleDirectory(
  1454. const std::string& config, BundleDirectoryLevel level) const
  1455. {
  1456. std::string fpath = cmStrCat(
  1457. this->GetFullName(config, cmStateEnums::RuntimeBinaryArtifact), '.');
  1458. cmValue ext = this->GetProperty("BUNDLE_EXTENSION");
  1459. fpath += (ext ? *ext : "app");
  1460. if (shouldAddContentLevel(level) &&
  1461. !this->Makefile->PlatformIsAppleEmbedded()) {
  1462. fpath += "/Contents";
  1463. if (shouldAddFullLevel(level)) {
  1464. fpath += "/MacOS";
  1465. }
  1466. }
  1467. return fpath;
  1468. }
  1469. bool cmGeneratorTarget::IsBundleOnApple() const
  1470. {
  1471. return this->IsFrameworkOnApple() || this->IsAppBundleOnApple() ||
  1472. this->IsCFBundleOnApple();
  1473. }
  1474. bool cmGeneratorTarget::IsWin32Executable(const std::string& config) const
  1475. {
  1476. return cmIsOn(cmGeneratorExpression::Evaluate(
  1477. this->GetSafeProperty("WIN32_EXECUTABLE"), this->LocalGenerator, config));
  1478. }
  1479. std::string cmGeneratorTarget::GetCFBundleDirectory(
  1480. const std::string& config, BundleDirectoryLevel level) const
  1481. {
  1482. std::string fpath = cmStrCat(
  1483. this->GetOutputName(config, cmStateEnums::RuntimeBinaryArtifact), '.');
  1484. std::string ext;
  1485. if (cmValue p = this->GetProperty("BUNDLE_EXTENSION")) {
  1486. ext = *p;
  1487. } else {
  1488. if (this->IsXCTestOnApple()) {
  1489. ext = "xctest";
  1490. } else {
  1491. ext = "bundle";
  1492. }
  1493. }
  1494. fpath += ext;
  1495. if (shouldAddContentLevel(level) &&
  1496. !this->Makefile->PlatformIsAppleEmbedded()) {
  1497. fpath += "/Contents";
  1498. if (shouldAddFullLevel(level)) {
  1499. fpath += "/MacOS";
  1500. }
  1501. }
  1502. return fpath;
  1503. }
  1504. std::string cmGeneratorTarget::GetFrameworkDirectory(
  1505. const std::string& config, BundleDirectoryLevel level) const
  1506. {
  1507. std::string fpath = cmStrCat(
  1508. this->GetOutputName(config, cmStateEnums::RuntimeBinaryArtifact), '.');
  1509. cmValue ext = this->GetProperty("BUNDLE_EXTENSION");
  1510. fpath += (ext ? *ext : "framework");
  1511. if (shouldAddFullLevel(level) &&
  1512. !this->Makefile->PlatformIsAppleEmbedded()) {
  1513. fpath += "/Versions/";
  1514. fpath += this->GetFrameworkVersion();
  1515. }
  1516. return fpath;
  1517. }
  1518. std::string cmGeneratorTarget::GetFullName(
  1519. const std::string& config, cmStateEnums::ArtifactType artifact) const
  1520. {
  1521. if (this->IsImported()) {
  1522. return this->GetFullNameImported(config, artifact);
  1523. }
  1524. return this->GetFullNameInternal(config, artifact);
  1525. }
  1526. std::string cmGeneratorTarget::GetInstallNameDirForBuildTree(
  1527. const std::string& config) const
  1528. {
  1529. if (this->Makefile->IsOn("CMAKE_PLATFORM_HAS_INSTALLNAME")) {
  1530. // If building directly for installation then the build tree install_name
  1531. // is the same as the install tree.
  1532. if (this->MacOSXUseInstallNameDir()) {
  1533. std::string installPrefix =
  1534. this->Makefile->GetSafeDefinition("CMAKE_INSTALL_PREFIX");
  1535. return this->GetInstallNameDirForInstallTree(config, installPrefix);
  1536. }
  1537. // Use the build tree directory for the target.
  1538. if (this->CanGenerateInstallNameDir(INSTALL_NAME_FOR_BUILD)) {
  1539. std::string dir;
  1540. if (this->MacOSXRpathInstallNameDirDefault()) {
  1541. dir = "@rpath";
  1542. } else {
  1543. dir = this->GetDirectory(config);
  1544. }
  1545. dir += "/";
  1546. return dir;
  1547. }
  1548. }
  1549. return "";
  1550. }
  1551. std::string cmGeneratorTarget::GetInstallNameDirForInstallTree(
  1552. const std::string& config, const std::string& installPrefix) const
  1553. {
  1554. if (this->Makefile->IsOn("CMAKE_PLATFORM_HAS_INSTALLNAME")) {
  1555. std::string dir;
  1556. cmValue install_name_dir = this->GetProperty("INSTALL_NAME_DIR");
  1557. if (this->CanGenerateInstallNameDir(INSTALL_NAME_FOR_INSTALL)) {
  1558. if (cmNonempty(install_name_dir)) {
  1559. dir = *install_name_dir;
  1560. cmGeneratorExpression::ReplaceInstallPrefix(dir, installPrefix);
  1561. dir =
  1562. cmGeneratorExpression::Evaluate(dir, this->LocalGenerator, config);
  1563. if (!dir.empty()) {
  1564. dir = cmStrCat(dir, '/');
  1565. }
  1566. }
  1567. }
  1568. if (!install_name_dir) {
  1569. if (this->MacOSXRpathInstallNameDirDefault()) {
  1570. dir = "@rpath/";
  1571. }
  1572. }
  1573. return dir;
  1574. }
  1575. return "";
  1576. }
  1577. cmListFileBacktrace cmGeneratorTarget::GetBacktrace() const
  1578. {
  1579. return this->Target->GetBacktrace();
  1580. }
  1581. const std::set<BT<std::pair<std::string, bool>>>&
  1582. cmGeneratorTarget::GetUtilities() const
  1583. {
  1584. return this->Target->GetUtilities();
  1585. }
  1586. bool cmGeneratorTarget::HaveWellDefinedOutputFiles() const
  1587. {
  1588. return this->GetType() == cmStateEnums::STATIC_LIBRARY ||
  1589. this->GetType() == cmStateEnums::SHARED_LIBRARY ||
  1590. this->GetType() == cmStateEnums::MODULE_LIBRARY ||
  1591. this->GetType() == cmStateEnums::OBJECT_LIBRARY ||
  1592. this->GetType() == cmStateEnums::EXECUTABLE;
  1593. }
  1594. const std::string* cmGeneratorTarget::GetExportMacro() const
  1595. {
  1596. // Define the symbol for targets that export symbols.
  1597. if (this->GetType() == cmStateEnums::SHARED_LIBRARY ||
  1598. this->GetType() == cmStateEnums::MODULE_LIBRARY ||
  1599. this->IsExecutableWithExports()) {
  1600. if (cmValue custom_export_name = this->GetProperty("DEFINE_SYMBOL")) {
  1601. this->ExportMacro = *custom_export_name;
  1602. } else {
  1603. std::string in = cmStrCat(this->GetName(), "_EXPORTS");
  1604. this->ExportMacro = cmSystemTools::MakeCidentifier(in);
  1605. }
  1606. return &this->ExportMacro;
  1607. }
  1608. return nullptr;
  1609. }
  1610. cmGeneratorTarget::NameComponents const&
  1611. cmGeneratorTarget::GetFullNameComponents(
  1612. std::string const& config, cmStateEnums::ArtifactType artifact) const
  1613. {
  1614. return this->GetFullNameInternalComponents(config, artifact);
  1615. }
  1616. std::string cmGeneratorTarget::BuildBundleDirectory(
  1617. const std::string& base, const std::string& config,
  1618. BundleDirectoryLevel level) const
  1619. {
  1620. std::string fpath = base;
  1621. if (this->IsAppBundleOnApple()) {
  1622. fpath += this->GetAppBundleDirectory(config, level);
  1623. }
  1624. if (this->IsFrameworkOnApple()) {
  1625. fpath += this->GetFrameworkDirectory(config, level);
  1626. }
  1627. if (this->IsCFBundleOnApple()) {
  1628. fpath += this->GetCFBundleDirectory(config, level);
  1629. }
  1630. return fpath;
  1631. }
  1632. std::string cmGeneratorTarget::GetMacContentDirectory(
  1633. const std::string& config, cmStateEnums::ArtifactType artifact) const
  1634. {
  1635. // Start with the output directory for the target.
  1636. std::string fpath = cmStrCat(this->GetDirectory(config, artifact), '/');
  1637. BundleDirectoryLevel level = ContentLevel;
  1638. if (this->IsFrameworkOnApple()) {
  1639. // additional files with a framework go into the version specific
  1640. // directory
  1641. level = FullLevel;
  1642. }
  1643. fpath = this->BuildBundleDirectory(fpath, config, level);
  1644. return fpath;
  1645. }
  1646. std::string cmGeneratorTarget::GetEffectiveFolderName() const
  1647. {
  1648. std::string effectiveFolder;
  1649. if (!this->GlobalGenerator->UseFolderProperty()) {
  1650. return effectiveFolder;
  1651. }
  1652. cmValue targetFolder = this->GetProperty("FOLDER");
  1653. if (targetFolder) {
  1654. effectiveFolder += *targetFolder;
  1655. }
  1656. return effectiveFolder;
  1657. }
  1658. cmGeneratorTarget::CompileInfo const* cmGeneratorTarget::GetCompileInfo(
  1659. const std::string& config) const
  1660. {
  1661. // There is no compile information for imported targets.
  1662. if (this->IsImported()) {
  1663. return nullptr;
  1664. }
  1665. if (this->GetType() > cmStateEnums::OBJECT_LIBRARY) {
  1666. std::string msg = cmStrCat("cmTarget::GetCompileInfo called for ",
  1667. this->GetName(), " which has type ",
  1668. cmState::GetTargetTypeName(this->GetType()));
  1669. this->LocalGenerator->IssueMessage(MessageType::INTERNAL_ERROR, msg);
  1670. return nullptr;
  1671. }
  1672. // Lookup/compute/cache the compile information for this configuration.
  1673. std::string config_upper;
  1674. if (!config.empty()) {
  1675. config_upper = cmSystemTools::UpperCase(config);
  1676. }
  1677. auto i = this->CompileInfoMap.find(config_upper);
  1678. if (i == this->CompileInfoMap.end()) {
  1679. CompileInfo info;
  1680. this->ComputePDBOutputDir("COMPILE_PDB", config, info.CompilePdbDir);
  1681. CompileInfoMapType::value_type entry(config_upper, info);
  1682. i = this->CompileInfoMap.insert(entry).first;
  1683. }
  1684. return &i->second;
  1685. }
  1686. cmGeneratorTarget::ModuleDefinitionInfo const*
  1687. cmGeneratorTarget::GetModuleDefinitionInfo(std::string const& config) const
  1688. {
  1689. // A module definition file only makes sense on certain target types.
  1690. if (this->GetType() != cmStateEnums::SHARED_LIBRARY &&
  1691. this->GetType() != cmStateEnums::MODULE_LIBRARY &&
  1692. !this->IsExecutableWithExports()) {
  1693. return nullptr;
  1694. }
  1695. // Lookup/compute/cache the compile information for this configuration.
  1696. std::string config_upper;
  1697. if (!config.empty()) {
  1698. config_upper = cmSystemTools::UpperCase(config);
  1699. }
  1700. auto i = this->ModuleDefinitionInfoMap.find(config_upper);
  1701. if (i == this->ModuleDefinitionInfoMap.end()) {
  1702. ModuleDefinitionInfo info;
  1703. this->ComputeModuleDefinitionInfo(config, info);
  1704. ModuleDefinitionInfoMapType::value_type entry(config_upper, info);
  1705. i = this->ModuleDefinitionInfoMap.insert(entry).first;
  1706. }
  1707. return &i->second;
  1708. }
  1709. void cmGeneratorTarget::ComputeModuleDefinitionInfo(
  1710. std::string const& config, ModuleDefinitionInfo& info) const
  1711. {
  1712. this->GetModuleDefinitionSources(info.Sources, config);
  1713. info.WindowsExportAllSymbols =
  1714. this->Makefile->IsOn("CMAKE_SUPPORT_WINDOWS_EXPORT_ALL_SYMBOLS") &&
  1715. this->GetPropertyAsBool("WINDOWS_EXPORT_ALL_SYMBOLS");
  1716. #if !defined(CMAKE_BOOTSTRAP)
  1717. info.DefFileGenerated =
  1718. info.WindowsExportAllSymbols || info.Sources.size() > 1;
  1719. #else
  1720. // Our __create_def helper is not available during CMake bootstrap.
  1721. info.DefFileGenerated = false;
  1722. #endif
  1723. if (info.DefFileGenerated) {
  1724. info.DefFile =
  1725. this->GetObjectDirectory(config) /* has slash */ + "exports.def";
  1726. } else if (!info.Sources.empty()) {
  1727. info.DefFile = info.Sources.front()->GetFullPath();
  1728. }
  1729. }
  1730. bool cmGeneratorTarget::IsAIX() const
  1731. {
  1732. return this->Target->IsAIX();
  1733. }
  1734. bool cmGeneratorTarget::IsApple() const
  1735. {
  1736. return this->Target->IsApple();
  1737. }
  1738. bool cmGeneratorTarget::IsDLLPlatform() const
  1739. {
  1740. return this->Target->IsDLLPlatform();
  1741. }
  1742. void cmGeneratorTarget::GetAutoUicOptions(std::vector<std::string>& result,
  1743. const std::string& config) const
  1744. {
  1745. const char* prop =
  1746. this->GetLinkInterfaceDependentStringProperty("AUTOUIC_OPTIONS", config);
  1747. if (!prop) {
  1748. return;
  1749. }
  1750. cmGeneratorExpressionDAGChecker dagChecker{
  1751. this, "AUTOUIC_OPTIONS", nullptr, nullptr, this->LocalGenerator, config,
  1752. };
  1753. cmExpandList(cmGeneratorExpression::Evaluate(prop, this->LocalGenerator,
  1754. config, this, &dagChecker),
  1755. result);
  1756. }
  1757. void cmGeneratorTarget::TraceDependencies()
  1758. {
  1759. // CMake-generated targets have no dependencies to trace. Normally tracing
  1760. // would find nothing anyway, but when building CMake itself the "install"
  1761. // target command ends up referencing the "cmake" target but we do not
  1762. // really want the dependency because "install" depend on "all" anyway.
  1763. if (this->GetType() == cmStateEnums::GLOBAL_TARGET) {
  1764. return;
  1765. }
  1766. // Use a helper object to trace the dependencies.
  1767. cmTargetTraceDependencies tracer(this);
  1768. tracer.Trace();
  1769. }
  1770. std::string cmGeneratorTarget::GetCompilePDBDirectory(
  1771. const std::string& config) const
  1772. {
  1773. if (CompileInfo const* info = this->GetCompileInfo(config)) {
  1774. return info->CompilePdbDir;
  1775. }
  1776. return "";
  1777. }
  1778. std::vector<std::string> cmGeneratorTarget::GetAppleArchs(
  1779. std::string const& config, cm::optional<std::string> lang) const
  1780. {
  1781. cmList archList;
  1782. if (!this->IsApple()) {
  1783. return std::move(archList.data());
  1784. }
  1785. cmValue archs = nullptr;
  1786. if (!config.empty()) {
  1787. std::string defVarName =
  1788. cmStrCat("OSX_ARCHITECTURES_", cmSystemTools::UpperCase(config));
  1789. archs = this->GetProperty(defVarName);
  1790. }
  1791. if (!archs) {
  1792. archs = this->GetProperty("OSX_ARCHITECTURES");
  1793. }
  1794. if (archs) {
  1795. archList.assign(*archs);
  1796. }
  1797. if (archList.empty() &&
  1798. // Fall back to a default architecture if no compiler target is set.
  1799. (!lang ||
  1800. this->Makefile
  1801. ->GetDefinition(cmStrCat("CMAKE_", *lang, "_COMPILER_TARGET"))
  1802. .IsEmpty())) {
  1803. archList.assign(
  1804. this->Makefile->GetDefinition("_CMAKE_APPLE_ARCHS_DEFAULT"));
  1805. }
  1806. return std::move(archList.data());
  1807. }
  1808. namespace {
  1809. bool IsSupportedClassifiedFlagsLanguage(std::string const& lang)
  1810. {
  1811. return lang == "CXX"_s;
  1812. }
  1813. bool CanUseCompilerLauncher(std::string const& lang)
  1814. {
  1815. // Also found in `cmCommonTargetGenerator::GetCompilerLauncher`.
  1816. return lang == "C"_s || lang == "CXX"_s || lang == "Fortran"_s ||
  1817. lang == "CUDA"_s || lang == "HIP"_s || lang == "ISPC"_s ||
  1818. lang == "OBJC"_s || lang == "OBJCXX"_s;
  1819. }
  1820. // FIXME: return a vector of `cm::string_view` instead to avoid lots of tiny
  1821. // allocations.
  1822. std::vector<std::string> SplitFlags(std::string const& flags)
  1823. {
  1824. std::vector<std::string> options;
  1825. #ifdef _WIN32
  1826. cmSystemTools::ParseWindowsCommandLine(flags.c_str(), options);
  1827. #else
  1828. cmSystemTools::ParseUnixCommandLine(flags.c_str(), options);
  1829. #endif
  1830. return options;
  1831. }
  1832. }
  1833. cmGeneratorTarget::ClassifiedFlags
  1834. cmGeneratorTarget::GetClassifiedFlagsForSource(cmSourceFile const* sf,
  1835. std::string const& config)
  1836. {
  1837. auto& sourceFlagsCache = this->Configs[config].SourceFlags;
  1838. auto cacheEntry = sourceFlagsCache.lower_bound(sf);
  1839. if (cacheEntry != sourceFlagsCache.end() && cacheEntry->first == sf) {
  1840. return cacheEntry->second;
  1841. }
  1842. ClassifiedFlags flags;
  1843. std::string const& lang = sf->GetLanguage();
  1844. if (!IsSupportedClassifiedFlagsLanguage(lang)) {
  1845. return flags;
  1846. }
  1847. auto* const lg = this->GetLocalGenerator();
  1848. auto const* const mf = this->Makefile;
  1849. // Compute the compiler launcher flags.
  1850. if (CanUseCompilerLauncher(lang)) {
  1851. // Compiler launchers are all execution flags and should not be relevant to
  1852. // the actual compilation.
  1853. FlagClassification cls = FlagClassification::ExecutionFlag;
  1854. FlagKind kind = FlagKind::NotAFlag;
  1855. std::string const clauncher_prop = cmStrCat(lang, "_COMPILER_LAUNCHER");
  1856. cmValue clauncher = this->GetProperty(clauncher_prop);
  1857. std::string const evaluatedClauncher = cmGeneratorExpression::Evaluate(
  1858. *clauncher, lg, config, this, nullptr, this, lang);
  1859. for (auto const& flag : SplitFlags(evaluatedClauncher)) {
  1860. flags.emplace_back(cls, kind, flag);
  1861. }
  1862. }
  1863. ClassifiedFlags define_flags;
  1864. ClassifiedFlags include_flags;
  1865. ClassifiedFlags compile_flags;
  1866. SourceVariables sfVars = this->GetSourceVariables(sf, config);
  1867. // Compute language flags.
  1868. {
  1869. FlagClassification cls = FlagClassification::BaselineFlag;
  1870. FlagKind kind = FlagKind::Compile;
  1871. std::string mfFlags;
  1872. // Explicitly add the explicit language flag before any other flag
  1873. // so user flags can override it.
  1874. this->AddExplicitLanguageFlags(mfFlags, *sf);
  1875. for (auto const& flag : SplitFlags(mfFlags)) {
  1876. flags.emplace_back(cls, kind, flag);
  1877. }
  1878. }
  1879. std::unordered_map<std::string, std::string> pchSources;
  1880. std::string filterArch;
  1881. {
  1882. std::vector<std::string> pchArchs = this->GetPchArchs(config, lang);
  1883. for (const std::string& arch : pchArchs) {
  1884. const std::string pchSource = this->GetPchSource(config, lang, arch);
  1885. if (pchSource == sf->GetFullPath()) {
  1886. filterArch = arch;
  1887. }
  1888. if (!pchSource.empty()) {
  1889. pchSources.insert(std::make_pair(pchSource, arch));
  1890. }
  1891. }
  1892. }
  1893. // Compute target-wide flags.
  1894. {
  1895. FlagClassification cls = FlagClassification::BaselineFlag;
  1896. // Compile flags
  1897. {
  1898. FlagKind kind = FlagKind::Compile;
  1899. std::string targetFlags;
  1900. lg->GetTargetCompileFlags(this, config, lang, targetFlags, filterArch);
  1901. for (auto&& flag : SplitFlags(targetFlags)) {
  1902. compile_flags.emplace_back(cls, kind, std::move(flag));
  1903. }
  1904. }
  1905. // Define flags
  1906. {
  1907. FlagKind kind = FlagKind::Definition;
  1908. std::set<std::string> defines;
  1909. lg->GetTargetDefines(this, config, lang, defines);
  1910. std::string defineFlags;
  1911. lg->JoinDefines(defines, defineFlags, lang);
  1912. for (auto&& flag : SplitFlags(defineFlags)) {
  1913. define_flags.emplace_back(cls, kind, std::move(flag));
  1914. }
  1915. }
  1916. // Include flags
  1917. {
  1918. FlagKind kind = FlagKind::Include;
  1919. std::vector<std::string> includes;
  1920. lg->GetIncludeDirectories(includes, this, lang, config);
  1921. auto includeFlags =
  1922. lg->GetIncludeFlags(includes, this, lang, config, false);
  1923. for (auto&& flag : SplitFlags(includeFlags)) {
  1924. include_flags.emplace_back(cls, kind, std::move(flag));
  1925. }
  1926. }
  1927. }
  1928. const std::string COMPILE_FLAGS("COMPILE_FLAGS");
  1929. const std::string COMPILE_OPTIONS("COMPILE_OPTIONS");
  1930. cmGeneratorExpressionInterpreter genexInterpreter(lg, config, this, lang);
  1931. // Source-specific flags.
  1932. {
  1933. FlagClassification cls = FlagClassification::PrivateFlag;
  1934. FlagKind kind = FlagKind::Compile;
  1935. std::string sourceFlags;
  1936. if (cmValue cflags = sf->GetProperty(COMPILE_FLAGS)) {
  1937. lg->AppendFlags(sourceFlags,
  1938. genexInterpreter.Evaluate(*cflags, COMPILE_FLAGS));
  1939. }
  1940. if (cmValue coptions = sf->GetProperty(COMPILE_OPTIONS)) {
  1941. lg->AppendCompileOptions(
  1942. sourceFlags, genexInterpreter.Evaluate(*coptions, COMPILE_OPTIONS));
  1943. }
  1944. for (auto&& flag : SplitFlags(sourceFlags)) {
  1945. compile_flags.emplace_back(cls, kind, std::move(flag));
  1946. }
  1947. // Dependency tracking flags.
  1948. {
  1949. if (!sfVars.DependencyFlags.empty()) {
  1950. cmRulePlaceholderExpander::RuleVariables vars;
  1951. auto rulePlaceholderExpander = lg->CreateRulePlaceholderExpander();
  1952. vars.DependencyFile = sfVars.DependencyFile.c_str();
  1953. vars.DependencyTarget = sfVars.DependencyTarget.c_str();
  1954. std::string depfileFlags = sfVars.DependencyFlags;
  1955. rulePlaceholderExpander->ExpandRuleVariables(lg, depfileFlags, vars);
  1956. for (auto&& flag : SplitFlags(depfileFlags)) {
  1957. compile_flags.emplace_back(FlagClassification::LocationFlag,
  1958. FlagKind::BuildSystem, std::move(flag));
  1959. }
  1960. }
  1961. }
  1962. }
  1963. // Precompiled headers.
  1964. {
  1965. FlagClassification cls = FlagClassification::PrivateFlag;
  1966. FlagKind kind = FlagKind::Compile;
  1967. std::string pchFlags;
  1968. // Add precompile headers compile options.
  1969. if (!sf->GetProperty("SKIP_PRECOMPILE_HEADERS")) {
  1970. if (!pchSources.empty()) {
  1971. std::string pchOptions;
  1972. auto pchIt = pchSources.find(sf->GetFullPath());
  1973. if (pchIt != pchSources.end()) {
  1974. pchOptions =
  1975. this->GetPchCreateCompileOptions(config, lang, pchIt->second);
  1976. } else {
  1977. pchOptions = this->GetPchUseCompileOptions(config, lang);
  1978. }
  1979. this->LocalGenerator->AppendCompileOptions(
  1980. pchFlags, genexInterpreter.Evaluate(pchOptions, COMPILE_OPTIONS));
  1981. }
  1982. }
  1983. for (auto&& flag : SplitFlags(pchFlags)) {
  1984. compile_flags.emplace_back(cls, kind, std::move(flag));
  1985. }
  1986. }
  1987. // C++ module flags.
  1988. if (lang == "CXX"_s) {
  1989. FlagClassification cls = FlagClassification::LocationFlag;
  1990. FlagKind kind = FlagKind::BuildSystem;
  1991. std::string bmiFlags;
  1992. auto const* fs = this->GetFileSetForSource(config, sf);
  1993. if (fs && fs->GetType() == "CXX_MODULES"_s) {
  1994. if (lang != "CXX"_s) {
  1995. mf->IssueMessage(
  1996. MessageType::FATAL_ERROR,
  1997. cmStrCat(
  1998. "Target \"", this->Target->GetName(), "\" contains the source\n ",
  1999. sf->GetFullPath(), "\nin a file set of type \"", fs->GetType(),
  2000. R"(" but the source is not classified as a "CXX" source.)"));
  2001. }
  2002. if (!this->Target->IsNormal()) {
  2003. auto flag = mf->GetSafeDefinition("CMAKE_CXX_MODULE_BMI_ONLY_FLAG");
  2004. cmRulePlaceholderExpander::RuleVariables compileObjectVars;
  2005. compileObjectVars.Object = sfVars.ObjectFileDir.c_str();
  2006. auto rulePlaceholderExpander = lg->CreateRulePlaceholderExpander();
  2007. rulePlaceholderExpander->ExpandRuleVariables(lg, flag,
  2008. compileObjectVars);
  2009. lg->AppendCompileOptions(bmiFlags, flag);
  2010. }
  2011. }
  2012. for (auto&& flag : SplitFlags(bmiFlags)) {
  2013. compile_flags.emplace_back(cls, kind, std::move(flag));
  2014. }
  2015. }
  2016. cmRulePlaceholderExpander::RuleVariables vars;
  2017. vars.CMTargetName = this->GetName().c_str();
  2018. vars.CMTargetType = cmState::GetTargetTypeName(this->GetType()).c_str();
  2019. vars.Language = lang.c_str();
  2020. auto const sfPath = this->LocalGenerator->ConvertToOutputFormat(
  2021. sf->GetFullPath(), cmOutputConverter::SHELL);
  2022. // Compute the base compiler command line. We'll find placeholders and
  2023. // replace them with arguments later in this function.
  2024. {
  2025. FlagClassification cls = FlagClassification::ExecutionFlag;
  2026. FlagKind kind = FlagKind::NotAFlag;
  2027. std::string const cmdVar = cmStrCat("CMAKE_", lang, "_COMPILE_OBJECT");
  2028. std::string const& compileCmd = mf->GetRequiredDefinition(cmdVar);
  2029. cmList compileCmds(compileCmd); // FIXME: which command to use?
  2030. std::string& cmd = compileCmds[0];
  2031. auto rulePlaceholderExpander = lg->CreateRulePlaceholderExpander();
  2032. static std::string const PlaceholderDefines = "__CMAKE_DEFINES";
  2033. static std::string const PlaceholderIncludes = "__CMAKE_INCLUDES";
  2034. static std::string const PlaceholderFlags = "__CMAKE_FLAGS";
  2035. static std::string const PlaceholderSource = "__CMAKE_SOURCE";
  2036. vars.Defines = PlaceholderDefines.c_str();
  2037. vars.Includes = PlaceholderIncludes.c_str();
  2038. vars.TargetPDB = sfVars.TargetPDB.c_str();
  2039. vars.TargetCompilePDB = sfVars.TargetCompilePDB.c_str();
  2040. vars.Object = sfVars.ObjectFileDir.c_str();
  2041. vars.ObjectDir = sfVars.ObjectDir.c_str();
  2042. vars.ObjectFileDir = sfVars.ObjectFileDir.c_str();
  2043. vars.Flags = PlaceholderFlags.c_str();
  2044. vars.DependencyFile = sfVars.DependencyFile.c_str();
  2045. vars.DependencyTarget = sfVars.DependencyTarget.c_str();
  2046. vars.Source = PlaceholderSource.c_str();
  2047. rulePlaceholderExpander->ExpandRuleVariables(lg, cmd, vars);
  2048. for (auto&& flag : SplitFlags(cmd)) {
  2049. if (flag == PlaceholderDefines) {
  2050. flags.insert(flags.end(), define_flags.begin(), define_flags.end());
  2051. } else if (flag == PlaceholderIncludes) {
  2052. flags.insert(flags.end(), include_flags.begin(), include_flags.end());
  2053. } else if (flag == PlaceholderFlags) {
  2054. flags.insert(flags.end(), compile_flags.begin(), compile_flags.end());
  2055. } else if (flag == PlaceholderSource) {
  2056. flags.emplace_back(FlagClassification::LocationFlag,
  2057. FlagKind::BuildSystem, sfPath);
  2058. } else {
  2059. flags.emplace_back(cls, kind, std::move(flag));
  2060. // All remaining flags here are build system flags.
  2061. kind = FlagKind::BuildSystem;
  2062. }
  2063. }
  2064. }
  2065. cacheEntry = sourceFlagsCache.emplace_hint(cacheEntry, sf, std::move(flags));
  2066. return cacheEntry->second;
  2067. }
  2068. cmGeneratorTarget::SourceVariables cmGeneratorTarget::GetSourceVariables(
  2069. cmSourceFile const* sf, std::string const& config)
  2070. {
  2071. SourceVariables vars;
  2072. auto const language = sf->GetLanguage();
  2073. auto const targetType = this->GetType();
  2074. auto const* const lg = this->GetLocalGenerator();
  2075. auto const* const gg = this->GetGlobalGenerator();
  2076. auto const* const mf = this->Makefile;
  2077. // PDB settings.
  2078. {
  2079. if (mf->GetDefinition("MSVC_C_ARCHITECTURE_ID") ||
  2080. mf->GetDefinition("MSVC_CXX_ARCHITECTURE_ID") ||
  2081. mf->GetDefinition("MSVC_CUDA_ARCHITECTURE_ID")) {
  2082. std::string pdbPath;
  2083. std::string compilePdbPath;
  2084. if (targetType <= cmStateEnums::OBJECT_LIBRARY) {
  2085. compilePdbPath = this->GetCompilePDBPath(config);
  2086. if (compilePdbPath.empty()) {
  2087. // Match VS default: `$(IntDir)vc$(PlatformToolsetVersion).pdb`.
  2088. // A trailing slash tells the toolchain to add its default file name.
  2089. compilePdbPath = this->GetSupportDirectory();
  2090. if (gg->IsMultiConfig()) {
  2091. compilePdbPath = cmStrCat(compilePdbPath, '/', config);
  2092. }
  2093. compilePdbPath += '/';
  2094. if (targetType == cmStateEnums::STATIC_LIBRARY) {
  2095. // Match VS default for static libs: `$(IntDir)$(ProjectName).pdb`.
  2096. compilePdbPath = cmStrCat(compilePdbPath, this->GetName(), ".pdb");
  2097. }
  2098. }
  2099. }
  2100. if (targetType == cmStateEnums::EXECUTABLE ||
  2101. targetType == cmStateEnums::STATIC_LIBRARY ||
  2102. targetType == cmStateEnums::SHARED_LIBRARY ||
  2103. targetType == cmStateEnums::MODULE_LIBRARY) {
  2104. pdbPath = cmStrCat(this->GetPDBDirectory(config), '/',
  2105. this->GetPDBName(config));
  2106. }
  2107. vars.TargetPDB = lg->ConvertToOutputFormat(
  2108. gg->ConvertToOutputPath(std::move(pdbPath)), cmOutputConverter::SHELL);
  2109. vars.TargetCompilePDB = lg->ConvertToOutputFormat(
  2110. gg->ConvertToOutputPath(std::move(compilePdbPath)),
  2111. cmOutputConverter::SHELL);
  2112. }
  2113. }
  2114. // Object settings.
  2115. {
  2116. std::string const objectDir = gg->ConvertToOutputPath(
  2117. cmStrCat(this->GetSupportDirectory(), gg->GetConfigDirectory(config)));
  2118. std::string const objectFileName = this->GetObjectName(sf);
  2119. std::string const objectFilePath =
  2120. cmStrCat(objectDir, '/', objectFileName);
  2121. vars.ObjectDir =
  2122. lg->ConvertToOutputFormat(objectDir, cmOutputConverter::SHELL);
  2123. vars.ObjectFileDir =
  2124. lg->ConvertToOutputFormat(objectFilePath, cmOutputConverter::SHELL);
  2125. // Dependency settings.
  2126. {
  2127. std::string const depfileFormatName =
  2128. cmStrCat("CMAKE_", language, "_DEPFILE_FORMAT");
  2129. std::string const depfileFormat =
  2130. mf->GetSafeDefinition(depfileFormatName);
  2131. if (depfileFormat != "msvc"_s) {
  2132. std::string const flagsName =
  2133. cmStrCat("CMAKE_DEPFILE_FLAGS_", language);
  2134. std::string const depfileFlags = mf->GetSafeDefinition(flagsName);
  2135. if (!depfileFlags.empty()) {
  2136. bool replaceExt = false;
  2137. if (!language.empty()) {
  2138. std::string const repVar =
  2139. cmStrCat("CMAKE_", language, "_DEPFILE_EXTENSION_REPLACE");
  2140. replaceExt = mf->IsOn(repVar);
  2141. }
  2142. std::string const depfilePath = cmStrCat(
  2143. objectDir, '/',
  2144. replaceExt
  2145. ? cmSystemTools::GetFilenameWithoutLastExtension(objectFileName)
  2146. : objectFileName,
  2147. ".d");
  2148. vars.DependencyFlags = depfileFlags;
  2149. vars.DependencyTarget = vars.ObjectFileDir;
  2150. vars.DependencyFile =
  2151. lg->ConvertToOutputFormat(depfilePath, cmOutputConverter::SHELL);
  2152. }
  2153. }
  2154. }
  2155. }
  2156. return vars;
  2157. }
  2158. void cmGeneratorTarget::AddExplicitLanguageFlags(std::string& flags,
  2159. cmSourceFile const& sf) const
  2160. {
  2161. cmValue lang = sf.GetProperty("LANGUAGE");
  2162. if (!lang) {
  2163. return;
  2164. }
  2165. switch (this->GetPolicyStatusCMP0119()) {
  2166. case cmPolicies::WARN:
  2167. CM_FALLTHROUGH;
  2168. case cmPolicies::OLD:
  2169. // The OLD behavior is to not add explicit language flags.
  2170. return;
  2171. case cmPolicies::REQUIRED_ALWAYS:
  2172. case cmPolicies::REQUIRED_IF_USED:
  2173. case cmPolicies::NEW:
  2174. // The NEW behavior is to add explicit language flags.
  2175. break;
  2176. }
  2177. this->LocalGenerator->AppendFeatureOptions(flags, *lang,
  2178. "EXPLICIT_LANGUAGE");
  2179. }
  2180. void cmGeneratorTarget::AddCUDAArchitectureFlags(cmBuildStep compileOrLink,
  2181. std::string const& config,
  2182. std::string& flags) const
  2183. {
  2184. std::string arch = this->GetSafeProperty("CUDA_ARCHITECTURES");
  2185. if (arch.empty()) {
  2186. switch (this->GetPolicyStatusCMP0104()) {
  2187. case cmPolicies::WARN:
  2188. if (!this->LocalGenerator->GetCMakeInstance()->GetIsInTryCompile()) {
  2189. this->Makefile->IssueMessage(
  2190. MessageType::AUTHOR_WARNING,
  2191. cmPolicies::GetPolicyWarning(cmPolicies::CMP0104) +
  2192. "\nCUDA_ARCHITECTURES is empty for target \"" + this->GetName() +
  2193. "\".");
  2194. }
  2195. CM_FALLTHROUGH;
  2196. case cmPolicies::OLD:
  2197. break;
  2198. default:
  2199. this->Makefile->IssueMessage(
  2200. MessageType::FATAL_ERROR,
  2201. "CUDA_ARCHITECTURES is empty for target \"" + this->GetName() +
  2202. "\".");
  2203. }
  2204. }
  2205. // If CUDA_ARCHITECTURES is false we don't add any architectures.
  2206. if (cmIsOff(arch)) {
  2207. return;
  2208. }
  2209. return this->AddCUDAArchitectureFlagsImpl(compileOrLink, config, "CUDA",
  2210. std::move(arch), flags);
  2211. }
  2212. void cmGeneratorTarget::AddCUDAArchitectureFlagsImpl(cmBuildStep compileOrLink,
  2213. std::string const& config,
  2214. std::string const& lang,
  2215. std::string arch,
  2216. std::string& flags) const
  2217. {
  2218. std::string const& compiler = this->Makefile->GetSafeDefinition(
  2219. cmStrCat("CMAKE_", lang, "_COMPILER_ID"));
  2220. const bool ipoEnabled = this->IsIPOEnabled(lang, config);
  2221. // Check for special modes: `all`, `all-major`.
  2222. if (arch == "all" || arch == "all-major") {
  2223. if (compiler == "NVIDIA" &&
  2224. cmSystemTools::VersionCompare(cmSystemTools::OP_GREATER_EQUAL,
  2225. this->Makefile->GetDefinition(cmStrCat(
  2226. "CMAKE_", lang, "_COMPILER_VERSION")),
  2227. "11.5")) {
  2228. flags = cmStrCat(flags, " -arch=", arch);
  2229. return;
  2230. }
  2231. if (arch == "all") {
  2232. arch = *this->Makefile->GetDefinition(
  2233. cmStrCat("CMAKE_", lang, "_ARCHITECTURES_ALL"));
  2234. } else if (arch == "all-major") {
  2235. arch = *this->Makefile->GetDefinition(
  2236. cmStrCat("CMAKE_", lang, "_ARCHITECTURES_ALL_MAJOR"));
  2237. }
  2238. } else if (arch == "native") {
  2239. cmValue native = this->Makefile->GetDefinition(
  2240. cmStrCat("CMAKE_", lang, "_ARCHITECTURES_NATIVE"));
  2241. if (native.IsEmpty()) {
  2242. this->Makefile->IssueMessage(
  2243. MessageType::FATAL_ERROR,
  2244. cmStrCat(lang,
  2245. "_ARCHITECTURES is set to \"native\", but no NVIDIA GPU was "
  2246. "detected."));
  2247. }
  2248. if (compiler == "NVIDIA" &&
  2249. cmSystemTools::VersionCompare(cmSystemTools::OP_GREATER_EQUAL,
  2250. this->Makefile->GetDefinition(cmStrCat(
  2251. "CMAKE_", lang, "_COMPILER_VERSION")),
  2252. "11.6")) {
  2253. flags = cmStrCat(flags, " -arch=", arch);
  2254. return;
  2255. }
  2256. arch = *native;
  2257. }
  2258. struct CudaArchitecture
  2259. {
  2260. std::string name;
  2261. bool real{ true };
  2262. bool virtual_{ true };
  2263. };
  2264. std::vector<CudaArchitecture> architectures;
  2265. {
  2266. cmList options(arch);
  2267. for (auto& option : options) {
  2268. CudaArchitecture architecture;
  2269. // Architecture name is up to the first specifier.
  2270. std::size_t pos = option.find_first_of('-');
  2271. architecture.name = option.substr(0, pos);
  2272. if (pos != std::string::npos) {
  2273. cm::string_view specifier{ option.c_str() + pos + 1,
  2274. option.length() - pos - 1 };
  2275. if (specifier == "real") {
  2276. architecture.real = true;
  2277. architecture.virtual_ = false;
  2278. } else if (specifier == "virtual") {
  2279. architecture.real = false;
  2280. architecture.virtual_ = true;
  2281. } else {
  2282. this->Makefile->IssueMessage(
  2283. MessageType::FATAL_ERROR,
  2284. "Unknown CUDA architecture specifier \"" + std::string(specifier) +
  2285. "\".");
  2286. }
  2287. }
  2288. architectures.emplace_back(architecture);
  2289. }
  2290. }
  2291. if (compiler == "NVIDIA") {
  2292. if (ipoEnabled && compileOrLink == cmBuildStep::Link) {
  2293. if (cmValue cudaIPOFlags = this->Makefile->GetDefinition(
  2294. cmStrCat("CMAKE_", lang, "_LINK_OPTIONS_IPO"))) {
  2295. flags += *cudaIPOFlags;
  2296. }
  2297. }
  2298. for (CudaArchitecture& architecture : architectures) {
  2299. flags +=
  2300. " \"--generate-code=arch=compute_" + architecture.name + ",code=[";
  2301. if (architecture.virtual_) {
  2302. flags += "compute_" + architecture.name;
  2303. if (ipoEnabled || architecture.real) {
  2304. flags += ",";
  2305. }
  2306. }
  2307. if (ipoEnabled) {
  2308. if (compileOrLink == cmBuildStep::Compile) {
  2309. flags += "lto_" + architecture.name;
  2310. } else if (compileOrLink == cmBuildStep::Link) {
  2311. flags += "sm_" + architecture.name;
  2312. }
  2313. } else if (architecture.real) {
  2314. flags += "sm_" + architecture.name;
  2315. }
  2316. flags += "]\"";
  2317. }
  2318. } else if (compiler == "Clang" && compileOrLink == cmBuildStep::Compile) {
  2319. for (CudaArchitecture& architecture : architectures) {
  2320. flags += " --cuda-gpu-arch=sm_" + architecture.name;
  2321. if (!architecture.real) {
  2322. this->Makefile->IssueMessage(
  2323. MessageType::WARNING,
  2324. "Clang doesn't support disabling CUDA real code generation.");
  2325. }
  2326. if (!architecture.virtual_) {
  2327. flags += " --no-cuda-include-ptx=sm_" + architecture.name;
  2328. }
  2329. }
  2330. }
  2331. }
  2332. void cmGeneratorTarget::AddISPCTargetFlags(std::string& flags) const
  2333. {
  2334. const std::string& arch = this->GetSafeProperty("ISPC_INSTRUCTION_SETS");
  2335. // If ISPC_TARGET is false we don't add any architectures.
  2336. if (cmIsOff(arch)) {
  2337. return;
  2338. }
  2339. std::string const& compiler =
  2340. this->Makefile->GetSafeDefinition("CMAKE_ISPC_COMPILER_ID");
  2341. if (compiler == "Intel") {
  2342. cmList targets(arch);
  2343. if (!targets.empty()) {
  2344. flags += cmStrCat(" --target=", cmWrap("", targets, "", ","));
  2345. }
  2346. }
  2347. }
  2348. void cmGeneratorTarget::AddHIPArchitectureFlags(cmBuildStep compileOrLink,
  2349. std::string const& config,
  2350. std::string& flags) const
  2351. {
  2352. std::string arch = this->GetSafeProperty("HIP_ARCHITECTURES");
  2353. if (arch.empty()) {
  2354. this->Makefile->IssueMessage(MessageType::FATAL_ERROR,
  2355. "HIP_ARCHITECTURES is empty for target \"" +
  2356. this->GetName() + "\".");
  2357. }
  2358. // If HIP_ARCHITECTURES is false we don't add any architectures.
  2359. if (cmIsOff(arch)) {
  2360. return;
  2361. }
  2362. if (this->Makefile->GetSafeDefinition("CMAKE_HIP_PLATFORM") == "nvidia") {
  2363. return this->AddCUDAArchitectureFlagsImpl(compileOrLink, config, "HIP",
  2364. std::move(arch), flags);
  2365. }
  2366. cmList options(arch);
  2367. for (std::string& option : options) {
  2368. flags += " --offload-arch=" + option;
  2369. }
  2370. }
  2371. void cmGeneratorTarget::AddCUDAToolkitFlags(std::string& flags) const
  2372. {
  2373. std::string const& compiler =
  2374. this->Makefile->GetSafeDefinition("CMAKE_CUDA_COMPILER_ID");
  2375. if (compiler == "Clang") {
  2376. // Pass CUDA toolkit explicitly to Clang.
  2377. // Clang's searching for the system CUDA toolkit isn't very good and it's
  2378. // expected the user will explicitly pass the toolkit path.
  2379. // This also avoids Clang having to search for the toolkit on every
  2380. // invocation.
  2381. std::string toolkitRoot =
  2382. this->Makefile->GetSafeDefinition("CMAKE_CUDA_COMPILER_LIBRARY_ROOT");
  2383. if (!toolkitRoot.empty()) {
  2384. flags += " --cuda-path=" +
  2385. this->LocalGenerator->ConvertToOutputFormat(toolkitRoot,
  2386. cmOutputConverter::SHELL);
  2387. }
  2388. }
  2389. }
  2390. //----------------------------------------------------------------------------
  2391. std::string cmGeneratorTarget::GetFeatureSpecificLinkRuleVariable(
  2392. std::string const& var, std::string const& lang,
  2393. std::string const& config) const
  2394. {
  2395. if (this->IsIPOEnabled(lang, config)) {
  2396. std::string varIPO = var + "_IPO";
  2397. if (this->Makefile->IsDefinitionSet(varIPO)) {
  2398. return varIPO;
  2399. }
  2400. }
  2401. return var;
  2402. }
  2403. //----------------------------------------------------------------------------
  2404. std::string cmGeneratorTarget::GetCreateRuleVariable(
  2405. std::string const& lang, std::string const& config) const
  2406. {
  2407. switch (this->GetType()) {
  2408. case cmStateEnums::STATIC_LIBRARY: {
  2409. std::string var = "CMAKE_" + lang + "_CREATE_STATIC_LIBRARY";
  2410. return this->GetFeatureSpecificLinkRuleVariable(var, lang, config);
  2411. }
  2412. case cmStateEnums::SHARED_LIBRARY:
  2413. if (this->IsArchivedAIXSharedLibrary()) {
  2414. return "CMAKE_" + lang + "_CREATE_SHARED_LIBRARY_ARCHIVE";
  2415. }
  2416. return "CMAKE_" + lang + "_CREATE_SHARED_LIBRARY";
  2417. case cmStateEnums::MODULE_LIBRARY:
  2418. return "CMAKE_" + lang + "_CREATE_SHARED_MODULE";
  2419. case cmStateEnums::EXECUTABLE:
  2420. if (this->IsExecutableWithExports()) {
  2421. std::string linkExeWithExports =
  2422. "CMAKE_" + lang + "_LINK_EXECUTABLE_WITH_EXPORTS";
  2423. if (this->Makefile->IsDefinitionSet(linkExeWithExports)) {
  2424. return linkExeWithExports;
  2425. }
  2426. }
  2427. return "CMAKE_" + lang + "_LINK_EXECUTABLE";
  2428. default:
  2429. break;
  2430. }
  2431. return "";
  2432. }
  2433. //----------------------------------------------------------------------------
  2434. std::string cmGeneratorTarget::GetClangTidyExportFixesDirectory(
  2435. const std::string& lang) const
  2436. {
  2437. cmValue val =
  2438. this->GetProperty(cmStrCat(lang, "_CLANG_TIDY_EXPORT_FIXES_DIR"));
  2439. if (!cmNonempty(val)) {
  2440. return {};
  2441. }
  2442. std::string path = *val;
  2443. if (!cmSystemTools::FileIsFullPath(path)) {
  2444. path =
  2445. cmStrCat(this->LocalGenerator->GetCurrentBinaryDirectory(), '/', path);
  2446. }
  2447. return cmSystemTools::CollapseFullPath(path);
  2448. }
  2449. std::vector<std::string> cmGeneratorTarget::GetPchArchs(
  2450. std::string const& config, std::string const& lang) const
  2451. {
  2452. std::vector<std::string> pchArchs;
  2453. if (!this->GetGlobalGenerator()->IsXcode()) {
  2454. pchArchs = this->GetAppleArchs(config, lang);
  2455. }
  2456. if (pchArchs.size() < 2) {
  2457. // We do not need per-arch PCH files when building for one architecture.
  2458. pchArchs = { {} };
  2459. }
  2460. return pchArchs;
  2461. }
  2462. std::string cmGeneratorTarget::GetPchHeader(const std::string& config,
  2463. const std::string& language,
  2464. const std::string& arch) const
  2465. {
  2466. if (language != "C" && language != "CXX" && language != "OBJC" &&
  2467. language != "OBJCXX") {
  2468. return std::string();
  2469. }
  2470. if (this->GetPropertyAsBool("DISABLE_PRECOMPILE_HEADERS")) {
  2471. return std::string();
  2472. }
  2473. const cmGeneratorTarget* generatorTarget = this;
  2474. cmValue pchReuseFrom =
  2475. generatorTarget->GetProperty("PRECOMPILE_HEADERS_REUSE_FROM");
  2476. const auto inserted =
  2477. this->PchHeaders.insert(std::make_pair(language + config + arch, ""));
  2478. if (inserted.second) {
  2479. const std::vector<BT<std::string>> headers =
  2480. this->GetPrecompileHeaders(config, language);
  2481. if (headers.empty() && !pchReuseFrom) {
  2482. return std::string();
  2483. }
  2484. std::string& filename = inserted.first->second;
  2485. if (pchReuseFrom) {
  2486. generatorTarget =
  2487. this->GetGlobalGenerator()->FindGeneratorTarget(*pchReuseFrom);
  2488. }
  2489. const std::map<std::string, std::string> languageToExtension = {
  2490. { "C", ".h" },
  2491. { "CXX", ".hxx" },
  2492. { "OBJC", ".objc.h" },
  2493. { "OBJCXX", ".objcxx.hxx" }
  2494. };
  2495. filename = generatorTarget->GetSupportDirectory();
  2496. if (this->GetGlobalGenerator()->IsMultiConfig()) {
  2497. filename = cmStrCat(filename, "/", config);
  2498. }
  2499. filename =
  2500. cmStrCat(filename, "/cmake_pch", arch.empty() ? "" : cmStrCat("_", arch),
  2501. languageToExtension.at(language));
  2502. const std::string filename_tmp = cmStrCat(filename, ".tmp");
  2503. if (!pchReuseFrom) {
  2504. cmValue pchPrologue =
  2505. this->Makefile->GetDefinition("CMAKE_PCH_PROLOGUE");
  2506. cmValue pchEpilogue =
  2507. this->Makefile->GetDefinition("CMAKE_PCH_EPILOGUE");
  2508. std::string firstHeaderOnDisk;
  2509. {
  2510. cmGeneratedFileStream file(
  2511. filename_tmp, false,
  2512. this->GetGlobalGenerator()->GetMakefileEncoding());
  2513. file << "/* generated by CMake */\n\n";
  2514. if (pchPrologue) {
  2515. file << *pchPrologue << "\n";
  2516. }
  2517. if (this->GetGlobalGenerator()->IsXcode()) {
  2518. file << "#ifndef CMAKE_SKIP_PRECOMPILE_HEADERS\n";
  2519. }
  2520. if (language == "CXX" && !this->GetGlobalGenerator()->IsXcode()) {
  2521. file << "#ifdef __cplusplus\n";
  2522. }
  2523. for (auto const& header_bt : headers) {
  2524. if (header_bt.Value.empty()) {
  2525. continue;
  2526. }
  2527. if (header_bt.Value[0] == '<' || header_bt.Value[0] == '\"') {
  2528. file << "#include " << header_bt.Value << "\n";
  2529. } else {
  2530. file << "#include \"" << header_bt.Value << "\"\n";
  2531. }
  2532. if (cmSystemTools::FileExists(header_bt.Value) &&
  2533. firstHeaderOnDisk.empty()) {
  2534. firstHeaderOnDisk = header_bt.Value;
  2535. }
  2536. }
  2537. if (language == "CXX" && !this->GetGlobalGenerator()->IsXcode()) {
  2538. file << "#endif // __cplusplus\n";
  2539. }
  2540. if (this->GetGlobalGenerator()->IsXcode()) {
  2541. file << "#endif // CMAKE_SKIP_PRECOMPILE_HEADERS\n";
  2542. }
  2543. if (pchEpilogue) {
  2544. file << *pchEpilogue << "\n";
  2545. }
  2546. }
  2547. if (!firstHeaderOnDisk.empty()) {
  2548. cmFileTimes::Copy(firstHeaderOnDisk, filename_tmp);
  2549. }
  2550. cmSystemTools::MoveFileIfDifferent(filename_tmp, filename);
  2551. }
  2552. }
  2553. return inserted.first->second;
  2554. }
  2555. std::string cmGeneratorTarget::GetPchSource(const std::string& config,
  2556. const std::string& language,
  2557. const std::string& arch) const
  2558. {
  2559. if (language != "C" && language != "CXX" && language != "OBJC" &&
  2560. language != "OBJCXX") {
  2561. return std::string();
  2562. }
  2563. const auto inserted =
  2564. this->PchSources.insert(std::make_pair(language + config + arch, ""));
  2565. if (inserted.second) {
  2566. const std::string pchHeader = this->GetPchHeader(config, language, arch);
  2567. if (pchHeader.empty()) {
  2568. return std::string();
  2569. }
  2570. std::string& filename = inserted.first->second;
  2571. const cmGeneratorTarget* generatorTarget = this;
  2572. cmValue pchReuseFrom =
  2573. generatorTarget->GetProperty("PRECOMPILE_HEADERS_REUSE_FROM");
  2574. if (pchReuseFrom) {
  2575. generatorTarget =
  2576. this->GetGlobalGenerator()->FindGeneratorTarget(*pchReuseFrom);
  2577. }
  2578. filename = cmStrCat(generatorTarget->GetSupportDirectory(), "/cmake_pch");
  2579. // For GCC the source extension will be transformed into .h[xx].gch
  2580. if (!this->Makefile->IsOn("CMAKE_LINK_PCH")) {
  2581. const std::map<std::string, std::string> languageToExtension = {
  2582. { "C", ".h.c" },
  2583. { "CXX", ".hxx.cxx" },
  2584. { "OBJC", ".objc.h.m" },
  2585. { "OBJCXX", ".objcxx.hxx.mm" }
  2586. };
  2587. filename = cmStrCat(filename, arch.empty() ? "" : cmStrCat("_", arch),
  2588. languageToExtension.at(language));
  2589. } else {
  2590. const std::map<std::string, std::string> languageToExtension = {
  2591. { "C", ".c" }, { "CXX", ".cxx" }, { "OBJC", ".m" }, { "OBJCXX", ".mm" }
  2592. };
  2593. filename = cmStrCat(filename, arch.empty() ? "" : cmStrCat("_", arch),
  2594. languageToExtension.at(language));
  2595. }
  2596. const std::string filename_tmp = cmStrCat(filename, ".tmp");
  2597. if (!pchReuseFrom) {
  2598. {
  2599. cmGeneratedFileStream file(filename_tmp);
  2600. file << "/* generated by CMake */\n";
  2601. }
  2602. cmFileTimes::Copy(pchHeader, filename_tmp);
  2603. cmSystemTools::MoveFileIfDifferent(filename_tmp, filename);
  2604. }
  2605. }
  2606. return inserted.first->second;
  2607. }
  2608. std::string cmGeneratorTarget::GetPchFileObject(const std::string& config,
  2609. const std::string& language,
  2610. const std::string& arch)
  2611. {
  2612. if (language != "C" && language != "CXX" && language != "OBJC" &&
  2613. language != "OBJCXX") {
  2614. return std::string();
  2615. }
  2616. const auto inserted =
  2617. this->PchObjectFiles.insert(std::make_pair(language + config + arch, ""));
  2618. if (inserted.second) {
  2619. const std::string pchSource = this->GetPchSource(config, language, arch);
  2620. if (pchSource.empty()) {
  2621. return std::string();
  2622. }
  2623. std::string& filename = inserted.first->second;
  2624. auto* pchSf = this->Makefile->GetOrCreateSource(
  2625. pchSource, false, cmSourceFileLocationKind::Known);
  2626. filename = cmStrCat(this->ObjectDirectory, this->GetObjectName(pchSf));
  2627. if (this->GetGlobalGenerator()->IsMultiConfig()) {
  2628. cmSystemTools::ReplaceString(
  2629. filename, this->GetGlobalGenerator()->GetCMakeCFGIntDir(), config);
  2630. }
  2631. }
  2632. return inserted.first->second;
  2633. }
  2634. std::string cmGeneratorTarget::GetPchFile(const std::string& config,
  2635. const std::string& language,
  2636. const std::string& arch)
  2637. {
  2638. const auto inserted =
  2639. this->PchFiles.insert(std::make_pair(language + config + arch, ""));
  2640. if (inserted.second) {
  2641. std::string& pchFile = inserted.first->second;
  2642. const std::string pchExtension =
  2643. this->Makefile->GetSafeDefinition("CMAKE_PCH_EXTENSION");
  2644. if (this->Makefile->IsOn("CMAKE_LINK_PCH")) {
  2645. auto replaceExtension = [](const std::string& str,
  2646. const std::string& ext) -> std::string {
  2647. auto dot_pos = str.rfind('.');
  2648. std::string result;
  2649. if (dot_pos != std::string::npos) {
  2650. result = str.substr(0, dot_pos);
  2651. }
  2652. result += ext;
  2653. return result;
  2654. };
  2655. cmGeneratorTarget* generatorTarget = this;
  2656. cmValue pchReuseFrom =
  2657. generatorTarget->GetProperty("PRECOMPILE_HEADERS_REUSE_FROM");
  2658. if (pchReuseFrom) {
  2659. generatorTarget =
  2660. this->GetGlobalGenerator()->FindGeneratorTarget(*pchReuseFrom);
  2661. }
  2662. const std::string pchFileObject =
  2663. generatorTarget->GetPchFileObject(config, language, arch);
  2664. if (!pchExtension.empty()) {
  2665. pchFile = replaceExtension(pchFileObject, pchExtension);
  2666. }
  2667. } else {
  2668. pchFile = this->GetPchHeader(config, language, arch);
  2669. pchFile += pchExtension;
  2670. }
  2671. }
  2672. return inserted.first->second;
  2673. }
  2674. std::string cmGeneratorTarget::GetPchCreateCompileOptions(
  2675. const std::string& config, const std::string& language,
  2676. const std::string& arch)
  2677. {
  2678. const auto inserted = this->PchCreateCompileOptions.insert(
  2679. std::make_pair(language + config + arch, ""));
  2680. if (inserted.second) {
  2681. std::string& createOptionList = inserted.first->second;
  2682. if (this->GetPropertyAsBool("PCH_WARN_INVALID")) {
  2683. createOptionList = this->Makefile->GetSafeDefinition(
  2684. cmStrCat("CMAKE_", language, "_COMPILE_OPTIONS_INVALID_PCH"));
  2685. }
  2686. if (this->GetPropertyAsBool("PCH_INSTANTIATE_TEMPLATES")) {
  2687. std::string varName = cmStrCat(
  2688. "CMAKE_", language, "_COMPILE_OPTIONS_INSTANTIATE_TEMPLATES_PCH");
  2689. std::string instantiateOption =
  2690. this->Makefile->GetSafeDefinition(varName);
  2691. if (!instantiateOption.empty()) {
  2692. createOptionList = cmStrCat(createOptionList, ";", instantiateOption);
  2693. }
  2694. }
  2695. const std::string createOptVar =
  2696. cmStrCat("CMAKE_", language, "_COMPILE_OPTIONS_CREATE_PCH");
  2697. createOptionList = cmStrCat(
  2698. createOptionList, ";", this->Makefile->GetSafeDefinition(createOptVar));
  2699. const std::string pchHeader = this->GetPchHeader(config, language, arch);
  2700. const std::string pchFile = this->GetPchFile(config, language, arch);
  2701. cmSystemTools::ReplaceString(createOptionList, "<PCH_HEADER>", pchHeader);
  2702. cmSystemTools::ReplaceString(createOptionList, "<PCH_FILE>", pchFile);
  2703. }
  2704. return inserted.first->second;
  2705. }
  2706. std::string cmGeneratorTarget::GetPchUseCompileOptions(
  2707. const std::string& config, const std::string& language,
  2708. const std::string& arch)
  2709. {
  2710. const auto inserted = this->PchUseCompileOptions.insert(
  2711. std::make_pair(language + config + arch, ""));
  2712. if (inserted.second) {
  2713. std::string& useOptionList = inserted.first->second;
  2714. if (this->GetPropertyAsBool("PCH_WARN_INVALID")) {
  2715. useOptionList = this->Makefile->GetSafeDefinition(
  2716. cmStrCat("CMAKE_", language, "_COMPILE_OPTIONS_INVALID_PCH"));
  2717. }
  2718. const std::string useOptVar =
  2719. cmStrCat(language, "_COMPILE_OPTIONS_USE_PCH");
  2720. std::string const& useOptionListProperty =
  2721. this->GetSafeProperty(useOptVar);
  2722. useOptionList = cmStrCat(
  2723. useOptionList, ";",
  2724. useOptionListProperty.empty()
  2725. ? this->Makefile->GetSafeDefinition(cmStrCat("CMAKE_", useOptVar))
  2726. : useOptionListProperty);
  2727. const std::string pchHeader = this->GetPchHeader(config, language, arch);
  2728. const std::string pchFile = this->GetPchFile(config, language, arch);
  2729. cmSystemTools::ReplaceString(useOptionList, "<PCH_HEADER>", pchHeader);
  2730. cmSystemTools::ReplaceString(useOptionList, "<PCH_FILE>", pchFile);
  2731. }
  2732. return inserted.first->second;
  2733. }
  2734. void cmGeneratorTarget::AddSourceFileToUnityBatch(
  2735. const std::string& sourceFilename)
  2736. {
  2737. this->UnityBatchedSourceFiles.insert(sourceFilename);
  2738. }
  2739. bool cmGeneratorTarget::IsSourceFilePartOfUnityBatch(
  2740. const std::string& sourceFilename) const
  2741. {
  2742. if (!this->GetPropertyAsBool("UNITY_BUILD")) {
  2743. return false;
  2744. }
  2745. return this->UnityBatchedSourceFiles.find(sourceFilename) !=
  2746. this->UnityBatchedSourceFiles.end();
  2747. }
  2748. void cmGeneratorTarget::ComputeTargetManifest(const std::string& config) const
  2749. {
  2750. if (this->IsImported()) {
  2751. return;
  2752. }
  2753. cmGlobalGenerator* gg = this->LocalGenerator->GetGlobalGenerator();
  2754. // Get the names.
  2755. cmGeneratorTarget::Names targetNames;
  2756. if (this->GetType() == cmStateEnums::EXECUTABLE) {
  2757. targetNames = this->GetExecutableNames(config);
  2758. } else if (this->GetType() == cmStateEnums::STATIC_LIBRARY ||
  2759. this->GetType() == cmStateEnums::SHARED_LIBRARY ||
  2760. this->GetType() == cmStateEnums::MODULE_LIBRARY) {
  2761. targetNames = this->GetLibraryNames(config);
  2762. } else {
  2763. return;
  2764. }
  2765. // Get the directory.
  2766. std::string dir =
  2767. this->GetDirectory(config, cmStateEnums::RuntimeBinaryArtifact);
  2768. // Add each name.
  2769. std::string f;
  2770. if (!targetNames.Output.empty()) {
  2771. f = cmStrCat(dir, '/', targetNames.Output);
  2772. gg->AddToManifest(f);
  2773. }
  2774. if (!targetNames.SharedObject.empty()) {
  2775. f = cmStrCat(dir, '/', targetNames.SharedObject);
  2776. gg->AddToManifest(f);
  2777. }
  2778. if (!targetNames.Real.empty()) {
  2779. f = cmStrCat(dir, '/', targetNames.Real);
  2780. gg->AddToManifest(f);
  2781. }
  2782. if (!targetNames.PDB.empty()) {
  2783. f = cmStrCat(dir, '/', targetNames.PDB);
  2784. gg->AddToManifest(f);
  2785. }
  2786. dir = this->GetDirectory(config, cmStateEnums::ImportLibraryArtifact);
  2787. if (!targetNames.ImportOutput.empty()) {
  2788. f = cmStrCat(dir, '/', targetNames.ImportOutput);
  2789. gg->AddToManifest(f);
  2790. }
  2791. if (!targetNames.ImportLibrary.empty()) {
  2792. f = cmStrCat(dir, '/', targetNames.ImportLibrary);
  2793. gg->AddToManifest(f);
  2794. }
  2795. if (!targetNames.ImportReal.empty()) {
  2796. f = cmStrCat(dir, '/', targetNames.ImportReal);
  2797. gg->AddToManifest(f);
  2798. }
  2799. }
  2800. cm::optional<cmStandardLevel> cmGeneratorTarget::GetExplicitStandardLevel(
  2801. std::string const& lang, std::string const& config) const
  2802. {
  2803. cm::optional<cmStandardLevel> level;
  2804. std::string key = cmStrCat(cmSystemTools::UpperCase(config), '-', lang);
  2805. auto i = this->ExplicitStandardLevel.find(key);
  2806. if (i != this->ExplicitStandardLevel.end()) {
  2807. level = i->second;
  2808. }
  2809. return level;
  2810. }
  2811. void cmGeneratorTarget::UpdateExplicitStandardLevel(std::string const& lang,
  2812. std::string const& config,
  2813. cmStandardLevel level)
  2814. {
  2815. auto e = this->ExplicitStandardLevel.emplace(
  2816. cmStrCat(cmSystemTools::UpperCase(config), '-', lang), level);
  2817. if (!e.second && e.first->second < level) {
  2818. e.first->second = level;
  2819. }
  2820. }
  2821. bool cmGeneratorTarget::ComputeCompileFeatures(std::string const& config)
  2822. {
  2823. cmStandardLevelResolver standardResolver(this->Makefile);
  2824. for (std::string const& lang :
  2825. this->Makefile->GetState()->GetEnabledLanguages()) {
  2826. if (cmValue languageStd = this->GetLanguageStandard(lang, config)) {
  2827. if (cm::optional<cmStandardLevel> langLevel =
  2828. standardResolver.LanguageStandardLevel(lang, *languageStd)) {
  2829. this->UpdateExplicitStandardLevel(lang, config, *langLevel);
  2830. }
  2831. }
  2832. }
  2833. // Compute the language standard based on the compile features.
  2834. std::vector<BT<std::string>> features = this->GetCompileFeatures(config);
  2835. for (BT<std::string> const& f : features) {
  2836. std::string lang;
  2837. if (!standardResolver.CompileFeatureKnown(this->Target->GetName(), f.Value,
  2838. lang, nullptr)) {
  2839. return false;
  2840. }
  2841. std::string key = cmStrCat(cmSystemTools::UpperCase(config), '-', lang);
  2842. cmValue currentLanguageStandard = this->GetLanguageStandard(lang, config);
  2843. cm::optional<cmStandardLevel> featureLevel;
  2844. std::string newRequiredStandard;
  2845. if (!standardResolver.GetNewRequiredStandard(
  2846. this->Target->GetName(), f.Value, currentLanguageStandard,
  2847. featureLevel, newRequiredStandard)) {
  2848. return false;
  2849. }
  2850. if (featureLevel) {
  2851. this->UpdateExplicitStandardLevel(lang, config, *featureLevel);
  2852. }
  2853. if (!newRequiredStandard.empty()) {
  2854. BTs<std::string>& languageStandardProperty =
  2855. this->LanguageStandardMap[key];
  2856. if (languageStandardProperty.Value != newRequiredStandard) {
  2857. languageStandardProperty.Value = newRequiredStandard;
  2858. languageStandardProperty.Backtraces.clear();
  2859. }
  2860. languageStandardProperty.Backtraces.emplace_back(f.Backtrace);
  2861. }
  2862. }
  2863. return true;
  2864. }
  2865. bool cmGeneratorTarget::ComputeCompileFeatures(
  2866. std::string const& config, std::set<LanguagePair> const& languagePairs)
  2867. {
  2868. for (const auto& language : languagePairs) {
  2869. BTs<std::string> const* generatorTargetLanguageStandard =
  2870. this->GetLanguageStandardProperty(language.first, config);
  2871. if (!generatorTargetLanguageStandard) {
  2872. // If the standard isn't explicitly set we copy it over from the
  2873. // specified paired language.
  2874. std::string key =
  2875. cmStrCat(cmSystemTools::UpperCase(config), '-', language.first);
  2876. BTs<std::string> const* standardToCopy =
  2877. this->GetLanguageStandardProperty(language.second, config);
  2878. if (standardToCopy) {
  2879. this->LanguageStandardMap[key] = *standardToCopy;
  2880. generatorTargetLanguageStandard = &this->LanguageStandardMap[key];
  2881. } else {
  2882. cmValue defaultStandard = this->Makefile->GetDefinition(
  2883. cmStrCat("CMAKE_", language.second, "_STANDARD_DEFAULT"));
  2884. if (defaultStandard) {
  2885. this->LanguageStandardMap[key] = BTs<std::string>(*defaultStandard);
  2886. generatorTargetLanguageStandard = &this->LanguageStandardMap[key];
  2887. }
  2888. }
  2889. // Custom updates for the CUDA standard.
  2890. if (generatorTargetLanguageStandard && (language.first == "CUDA")) {
  2891. if (generatorTargetLanguageStandard->Value == "98") {
  2892. this->LanguageStandardMap[key].Value = "03";
  2893. }
  2894. }
  2895. }
  2896. }
  2897. return true;
  2898. }
  2899. std::string cmGeneratorTarget::GetImportedLibName(
  2900. std::string const& config) const
  2901. {
  2902. if (cmGeneratorTarget::ImportInfo const* info =
  2903. this->GetImportInfo(config)) {
  2904. return info->LibName;
  2905. }
  2906. return std::string();
  2907. }
  2908. std::string cmGeneratorTarget::GetFullPath(const std::string& config,
  2909. cmStateEnums::ArtifactType artifact,
  2910. bool realname) const
  2911. {
  2912. if (this->IsImported()) {
  2913. return this->Target->ImportedGetFullPath(config, artifact);
  2914. }
  2915. return this->NormalGetFullPath(config, artifact, realname);
  2916. }
  2917. std::string cmGeneratorTarget::NormalGetFullPath(
  2918. const std::string& config, cmStateEnums::ArtifactType artifact,
  2919. bool realname) const
  2920. {
  2921. std::string fpath = cmStrCat(this->GetDirectory(config, artifact), '/');
  2922. if (this->IsAppBundleOnApple()) {
  2923. fpath =
  2924. cmStrCat(this->BuildBundleDirectory(fpath, config, FullLevel), '/');
  2925. }
  2926. // Add the full name of the target.
  2927. switch (artifact) {
  2928. case cmStateEnums::RuntimeBinaryArtifact:
  2929. if (realname) {
  2930. fpath += this->NormalGetRealName(config);
  2931. } else {
  2932. fpath +=
  2933. this->GetFullName(config, cmStateEnums::RuntimeBinaryArtifact);
  2934. }
  2935. break;
  2936. case cmStateEnums::ImportLibraryArtifact:
  2937. if (realname) {
  2938. fpath +=
  2939. this->NormalGetRealName(config, cmStateEnums::ImportLibraryArtifact);
  2940. } else {
  2941. fpath +=
  2942. this->GetFullName(config, cmStateEnums::ImportLibraryArtifact);
  2943. }
  2944. break;
  2945. }
  2946. return fpath;
  2947. }
  2948. std::string cmGeneratorTarget::NormalGetRealName(
  2949. const std::string& config, cmStateEnums::ArtifactType artifact) const
  2950. {
  2951. // This should not be called for imported targets.
  2952. // TODO: Split cmTarget into a class hierarchy to get compile-time
  2953. // enforcement of the limited imported target API.
  2954. if (this->IsImported()) {
  2955. std::string msg = cmStrCat("NormalGetRealName called on imported target: ",
  2956. this->GetName());
  2957. this->LocalGenerator->IssueMessage(MessageType::INTERNAL_ERROR, msg);
  2958. }
  2959. Names names = this->GetType() == cmStateEnums::EXECUTABLE
  2960. ? this->GetExecutableNames(config)
  2961. : this->GetLibraryNames(config);
  2962. // Compute the real name that will be built.
  2963. return artifact == cmStateEnums::RuntimeBinaryArtifact ? names.Real
  2964. : names.ImportReal;
  2965. }
  2966. cmGeneratorTarget::Names cmGeneratorTarget::GetLibraryNames(
  2967. const std::string& config) const
  2968. {
  2969. cmGeneratorTarget::Names targetNames;
  2970. // This should not be called for imported targets.
  2971. // TODO: Split cmTarget into a class hierarchy to get compile-time
  2972. // enforcement of the limited imported target API.
  2973. if (this->IsImported()) {
  2974. std::string msg =
  2975. cmStrCat("GetLibraryNames called on imported target: ", this->GetName());
  2976. this->LocalGenerator->IssueMessage(MessageType::INTERNAL_ERROR, msg);
  2977. }
  2978. // Check for library version properties.
  2979. cmValue version = this->GetProperty("VERSION");
  2980. cmValue soversion = this->GetProperty("SOVERSION");
  2981. if (!this->HasSOName(config) ||
  2982. this->Makefile->IsOn("CMAKE_PLATFORM_NO_VERSIONED_SONAME") ||
  2983. this->IsFrameworkOnApple()) {
  2984. // Versioning is supported only for shared libraries and modules,
  2985. // and then only when the platform supports an soname flag.
  2986. version = nullptr;
  2987. soversion = nullptr;
  2988. }
  2989. if (version && !soversion) {
  2990. // The soversion must be set if the library version is set. Use
  2991. // the library version as the soversion.
  2992. soversion = version;
  2993. }
  2994. if (!version && soversion) {
  2995. // Use the soversion as the library version.
  2996. version = soversion;
  2997. }
  2998. // Get the components of the library name.
  2999. NameComponents const& components = this->GetFullNameInternalComponents(
  3000. config, cmStateEnums::RuntimeBinaryArtifact);
  3001. // The library name.
  3002. targetNames.Base = components.base;
  3003. targetNames.Output =
  3004. cmStrCat(components.prefix, targetNames.Base, components.suffix);
  3005. if (this->IsFrameworkOnApple()) {
  3006. targetNames.Real = components.prefix;
  3007. if (!this->Makefile->PlatformIsAppleEmbedded()) {
  3008. targetNames.Real +=
  3009. cmStrCat("Versions/", this->GetFrameworkVersion(), '/');
  3010. }
  3011. targetNames.Real += cmStrCat(targetNames.Base, components.suffix);
  3012. targetNames.SharedObject = targetNames.Real;
  3013. } else if (this->IsArchivedAIXSharedLibrary()) {
  3014. targetNames.SharedObject =
  3015. cmStrCat(components.prefix, targetNames.Base, ".so");
  3016. if (soversion) {
  3017. targetNames.SharedObject += ".";
  3018. targetNames.SharedObject += *soversion;
  3019. }
  3020. targetNames.Real = targetNames.Output;
  3021. } else {
  3022. // The library's soname.
  3023. targetNames.SharedObject = this->ComputeVersionedName(
  3024. components.prefix, targetNames.Base, components.suffix,
  3025. targetNames.Output, soversion);
  3026. // The library's real name on disk.
  3027. targetNames.Real = this->ComputeVersionedName(
  3028. components.prefix, targetNames.Base, components.suffix,
  3029. targetNames.Output, version);
  3030. }
  3031. // The import library names.
  3032. if (this->GetType() == cmStateEnums::SHARED_LIBRARY ||
  3033. this->GetType() == cmStateEnums::MODULE_LIBRARY) {
  3034. NameComponents const& importComponents =
  3035. this->GetFullNameInternalComponents(config,
  3036. cmStateEnums::ImportLibraryArtifact);
  3037. targetNames.ImportOutput = cmStrCat(
  3038. importComponents.prefix, importComponents.base, importComponents.suffix);
  3039. if (this->IsFrameworkOnApple() && this->IsSharedLibraryWithExports()) {
  3040. targetNames.ImportReal = components.prefix;
  3041. if (!this->Makefile->PlatformIsAppleEmbedded()) {
  3042. targetNames.ImportReal +=
  3043. cmStrCat("Versions/", this->GetFrameworkVersion(), '/');
  3044. }
  3045. targetNames.ImportReal +=
  3046. cmStrCat(importComponents.base, importComponents.suffix);
  3047. targetNames.ImportLibrary = targetNames.ImportOutput;
  3048. } else {
  3049. // The import library's soname.
  3050. targetNames.ImportLibrary = this->ComputeVersionedName(
  3051. importComponents.prefix, importComponents.base,
  3052. importComponents.suffix, targetNames.ImportOutput, soversion);
  3053. // The import library's real name on disk.
  3054. targetNames.ImportReal = this->ComputeVersionedName(
  3055. importComponents.prefix, importComponents.base,
  3056. importComponents.suffix, targetNames.ImportOutput, version);
  3057. }
  3058. }
  3059. // The program database file name.
  3060. targetNames.PDB = this->GetPDBName(config);
  3061. return targetNames;
  3062. }
  3063. cmGeneratorTarget::Names cmGeneratorTarget::GetExecutableNames(
  3064. const std::string& config) const
  3065. {
  3066. cmGeneratorTarget::Names targetNames;
  3067. // This should not be called for imported targets.
  3068. // TODO: Split cmTarget into a class hierarchy to get compile-time
  3069. // enforcement of the limited imported target API.
  3070. if (this->IsImported()) {
  3071. std::string msg = cmStrCat(
  3072. "GetExecutableNames called on imported target: ", this->GetName());
  3073. this->LocalGenerator->IssueMessage(MessageType::INTERNAL_ERROR, msg);
  3074. }
  3075. // This versioning is supported only for executables and then only
  3076. // when the platform supports symbolic links.
  3077. #if defined(_WIN32) && !defined(__CYGWIN__)
  3078. cmValue version;
  3079. #else
  3080. // Check for executable version properties.
  3081. cmValue version = this->GetProperty("VERSION");
  3082. if (this->GetType() != cmStateEnums::EXECUTABLE ||
  3083. this->Makefile->IsOn("XCODE")) {
  3084. version = nullptr;
  3085. }
  3086. #endif
  3087. // Get the components of the executable name.
  3088. NameComponents const& components = this->GetFullNameInternalComponents(
  3089. config, cmStateEnums::RuntimeBinaryArtifact);
  3090. // The executable name.
  3091. targetNames.Base = components.base;
  3092. if (this->IsArchivedAIXSharedLibrary()) {
  3093. targetNames.Output = components.prefix + targetNames.Base;
  3094. } else {
  3095. targetNames.Output =
  3096. components.prefix + targetNames.Base + components.suffix;
  3097. }
  3098. // The executable's real name on disk.
  3099. #if defined(__CYGWIN__)
  3100. targetNames.Real = components.prefix + targetNames.Base;
  3101. #else
  3102. targetNames.Real = targetNames.Output;
  3103. #endif
  3104. if (version) {
  3105. targetNames.Real += "-";
  3106. targetNames.Real += *version;
  3107. }
  3108. #if defined(__CYGWIN__)
  3109. targetNames.Real += components.suffix;
  3110. #endif
  3111. // The import library name.
  3112. targetNames.ImportLibrary =
  3113. this->GetFullNameInternal(config, cmStateEnums::ImportLibraryArtifact);
  3114. targetNames.ImportReal = targetNames.ImportLibrary;
  3115. targetNames.ImportOutput = targetNames.ImportLibrary;
  3116. // The program database file name.
  3117. targetNames.PDB = this->GetPDBName(config);
  3118. return targetNames;
  3119. }
  3120. std::string cmGeneratorTarget::GetFullNameInternal(
  3121. const std::string& config, cmStateEnums::ArtifactType artifact) const
  3122. {
  3123. NameComponents const& components =
  3124. this->GetFullNameInternalComponents(config, artifact);
  3125. return components.prefix + components.base + components.suffix;
  3126. }
  3127. std::string cmGeneratorTarget::ImportedGetLocation(
  3128. const std::string& config) const
  3129. {
  3130. assert(this->IsImported());
  3131. return this->Target->ImportedGetFullPath(
  3132. config, cmStateEnums::RuntimeBinaryArtifact);
  3133. }
  3134. std::string cmGeneratorTarget::GetFullNameImported(
  3135. const std::string& config, cmStateEnums::ArtifactType artifact) const
  3136. {
  3137. return cmSystemTools::GetFilenameName(
  3138. this->Target->ImportedGetFullPath(config, artifact));
  3139. }
  3140. cmGeneratorTarget::NameComponents const&
  3141. cmGeneratorTarget::GetFullNameInternalComponents(
  3142. std::string const& config, cmStateEnums::ArtifactType artifact) const
  3143. {
  3144. assert(artifact == cmStateEnums::RuntimeBinaryArtifact ||
  3145. artifact == cmStateEnums::ImportLibraryArtifact);
  3146. FullNameCache& cache = artifact == cmStateEnums::RuntimeBinaryArtifact
  3147. ? RuntimeBinaryFullNameCache
  3148. : ImportLibraryFullNameCache;
  3149. auto search = cache.find(config);
  3150. if (search != cache.end()) {
  3151. return search->second;
  3152. }
  3153. // Use just the target name for non-main target types.
  3154. if (this->GetType() != cmStateEnums::STATIC_LIBRARY &&
  3155. this->GetType() != cmStateEnums::SHARED_LIBRARY &&
  3156. this->GetType() != cmStateEnums::MODULE_LIBRARY &&
  3157. this->GetType() != cmStateEnums::EXECUTABLE) {
  3158. NameComponents components;
  3159. components.base = this->GetName();
  3160. return cache.emplace(config, std::move(components)).first->second;
  3161. }
  3162. const bool isImportedLibraryArtifact =
  3163. (artifact == cmStateEnums::ImportLibraryArtifact);
  3164. // Return an empty name for the import library if this platform
  3165. // does not support import libraries.
  3166. if (isImportedLibraryArtifact && !this->NeedImportLibraryName(config)) {
  3167. return cache.emplace(config, NameComponents()).first->second;
  3168. }
  3169. NameComponents parts;
  3170. std::string& outPrefix = parts.prefix;
  3171. std::string& outBase = parts.base;
  3172. std::string& outSuffix = parts.suffix;
  3173. // retrieve prefix and suffix
  3174. std::string ll = this->GetLinkerLanguage(config);
  3175. cmValue targetPrefix = this->GetFilePrefixInternal(config, artifact, ll);
  3176. cmValue targetSuffix = this->GetFileSuffixInternal(config, artifact, ll);
  3177. // The implib option is only allowed for shared libraries, module
  3178. // libraries, and executables.
  3179. if (this->GetType() != cmStateEnums::SHARED_LIBRARY &&
  3180. this->GetType() != cmStateEnums::MODULE_LIBRARY &&
  3181. this->GetType() != cmStateEnums::EXECUTABLE) {
  3182. artifact = cmStateEnums::RuntimeBinaryArtifact;
  3183. }
  3184. // Compute the full name for main target types.
  3185. std::string configPostfix = this->GetFilePostfix(config);
  3186. // frameworks have directory prefix
  3187. std::string fw_prefix;
  3188. if (this->IsFrameworkOnApple()) {
  3189. fw_prefix =
  3190. cmStrCat(this->GetFrameworkDirectory(config, ContentLevel), '/');
  3191. targetPrefix = cmValue(fw_prefix);
  3192. if (!isImportedLibraryArtifact) {
  3193. // no suffix
  3194. targetSuffix = nullptr;
  3195. }
  3196. }
  3197. if (this->IsCFBundleOnApple()) {
  3198. fw_prefix = cmStrCat(this->GetCFBundleDirectory(config, FullLevel), '/');
  3199. targetPrefix = cmValue(fw_prefix);
  3200. targetSuffix = nullptr;
  3201. }
  3202. // Begin the final name with the prefix.
  3203. outPrefix = targetPrefix ? *targetPrefix : "";
  3204. // Append the target name or property-specified name.
  3205. outBase += this->GetOutputName(config, artifact);
  3206. // Append the per-configuration postfix.
  3207. // When using Xcode, the postfix should be part of the suffix rather than
  3208. // the base, because the suffix ends up being used in Xcode's
  3209. // EXECUTABLE_SUFFIX attribute.
  3210. if (this->IsFrameworkOnApple() && this->GetGlobalGenerator()->IsXcode()) {
  3211. configPostfix += *targetSuffix;
  3212. targetSuffix = cmValue(configPostfix);
  3213. } else {
  3214. outBase += configPostfix;
  3215. }
  3216. // Name shared libraries with their version number on some platforms.
  3217. if (cmValue soversion = this->GetProperty("SOVERSION")) {
  3218. cmValue dllProp;
  3219. if (this->IsDLLPlatform()) {
  3220. dllProp = this->GetProperty("DLL_NAME_WITH_SOVERSION");
  3221. }
  3222. if (this->GetType() == cmStateEnums::SHARED_LIBRARY &&
  3223. !isImportedLibraryArtifact &&
  3224. (dllProp.IsOn() ||
  3225. (!dllProp.IsSet() &&
  3226. this->Makefile->IsOn("CMAKE_SHARED_LIBRARY_NAME_WITH_VERSION")))) {
  3227. outBase += "-";
  3228. outBase += *soversion;
  3229. }
  3230. }
  3231. // Append the suffix.
  3232. outSuffix = targetSuffix ? *targetSuffix : "";
  3233. return cache.emplace(config, std::move(parts)).first->second;
  3234. }
  3235. std::string cmGeneratorTarget::GetLinkerLanguage(
  3236. const std::string& config) const
  3237. {
  3238. return this->GetLinkClosure(config)->LinkerLanguage;
  3239. }
  3240. std::string cmGeneratorTarget::GetLinkerTool(const std::string& config) const
  3241. {
  3242. return this->GetLinkerTool(this->GetLinkerLanguage(config), config);
  3243. }
  3244. std::string cmGeneratorTarget::GetLinkerTool(const std::string& lang,
  3245. const std::string& config) const
  3246. {
  3247. auto usingLinker =
  3248. cmStrCat("CMAKE_", lang, "_USING_", this->IsDeviceLink() ? "DEVICE_" : "",
  3249. "LINKER_");
  3250. auto format = this->Makefile->GetDefinition(cmStrCat(usingLinker, "MODE"));
  3251. if (!format || format != "TOOL"_s) {
  3252. return this->Makefile->GetDefinition("CMAKE_LINKER");
  3253. }
  3254. auto linkerType = this->GetLinkerTypeProperty(lang, config);
  3255. if (linkerType.empty()) {
  3256. linkerType = "DEFAULT";
  3257. }
  3258. usingLinker = cmStrCat(usingLinker, linkerType);
  3259. auto linkerTool = this->Makefile->GetDefinition(usingLinker);
  3260. if (!linkerTool) {
  3261. if (this->GetGlobalGenerator()->IsVisualStudio() &&
  3262. linkerType == "DEFAULT"_s) {
  3263. return std::string{};
  3264. }
  3265. // fall-back to generic definition
  3266. linkerTool = this->Makefile->GetDefinition("CMAKE_LINKER");
  3267. if (linkerType != "DEFAULT"_s) {
  3268. auto isCMakeLinkerType = [](const std::string& type) -> bool {
  3269. return std::all_of(type.cbegin(), type.cend(),
  3270. [](char c) { return std::isupper(c); });
  3271. };
  3272. if (isCMakeLinkerType(linkerType)) {
  3273. this->LocalGenerator->IssueMessage(
  3274. MessageType::FATAL_ERROR,
  3275. cmStrCat("LINKER_TYPE '", linkerType,
  3276. "' is unknown or not supported by this toolchain."));
  3277. } else {
  3278. this->LocalGenerator->IssueMessage(
  3279. MessageType::FATAL_ERROR,
  3280. cmStrCat("LINKER_TYPE '", linkerType,
  3281. "' is unknown. Did you forget to define the '", usingLinker,
  3282. "' variable?"));
  3283. }
  3284. }
  3285. }
  3286. return linkerTool;
  3287. }
  3288. bool cmGeneratorTarget::LinkerEnforcesNoAllowShLibUndefined(
  3289. std::string const& config) const
  3290. {
  3291. // FIXME(#25486): Account for the LINKER_TYPE target property.
  3292. // Also factor out the hard-coded list below into a platform
  3293. // information table based on the linker id.
  3294. std::string ll = this->GetLinkerLanguage(config);
  3295. std::string linkerIdVar = cmStrCat("CMAKE_", ll, "_COMPILER_LINKER_ID");
  3296. cmValue linkerId = this->Makefile->GetDefinition(linkerIdVar);
  3297. // The GNU bfd-based linker may enforce '--no-allow-shlib-undefined'
  3298. // recursively by default. The Solaris linker has similar behavior.
  3299. return linkerId && (*linkerId == "GNU" || *linkerId == "Solaris");
  3300. }
  3301. std::string cmGeneratorTarget::GetPDBOutputName(
  3302. const std::string& config) const
  3303. {
  3304. std::string base =
  3305. this->GetOutputName(config, cmStateEnums::RuntimeBinaryArtifact);
  3306. std::vector<std::string> props;
  3307. std::string configUpper = cmSystemTools::UpperCase(config);
  3308. if (!configUpper.empty()) {
  3309. // PDB_NAME_<CONFIG>
  3310. props.push_back("PDB_NAME_" + configUpper);
  3311. }
  3312. // PDB_NAME
  3313. props.emplace_back("PDB_NAME");
  3314. for (std::string const& p : props) {
  3315. if (cmValue outName = this->GetProperty(p)) {
  3316. base = *outName;
  3317. break;
  3318. }
  3319. }
  3320. return base;
  3321. }
  3322. std::string cmGeneratorTarget::GetPDBName(const std::string& config) const
  3323. {
  3324. NameComponents const& parts = this->GetFullNameInternalComponents(
  3325. config, cmStateEnums::RuntimeBinaryArtifact);
  3326. std::vector<std::string> props;
  3327. std::string configUpper = cmSystemTools::UpperCase(config);
  3328. if (!configUpper.empty()) {
  3329. // PDB_NAME_<CONFIG>
  3330. props.push_back("PDB_NAME_" + configUpper);
  3331. }
  3332. // PDB_NAME
  3333. props.emplace_back("PDB_NAME");
  3334. for (std::string const& p : props) {
  3335. if (cmValue outName = this->GetProperty(p)) {
  3336. return parts.prefix + *outName + ".pdb";
  3337. }
  3338. }
  3339. return parts.prefix + parts.base + ".pdb";
  3340. }
  3341. std::string cmGeneratorTarget::GetObjectDirectory(
  3342. std::string const& config) const
  3343. {
  3344. std::string obj_dir =
  3345. this->GlobalGenerator->ExpandCFGIntDir(this->ObjectDirectory, config);
  3346. #if defined(__APPLE__)
  3347. // Replace Xcode's placeholder for the object file directory since
  3348. // installation and export scripts need to know the real directory.
  3349. // Xcode has build-time settings (e.g. for sanitizers) that affect this,
  3350. // but we use the default here. Users that want to enable sanitizers
  3351. // will do so at the cost of object library installation and export.
  3352. cmSystemTools::ReplaceString(obj_dir, "$(OBJECT_FILE_DIR_normal:base)",
  3353. "Objects-normal");
  3354. #endif
  3355. return obj_dir;
  3356. }
  3357. void cmGeneratorTarget::GetTargetObjectNames(
  3358. std::string const& config, std::vector<std::string>& objects) const
  3359. {
  3360. std::vector<cmSourceFile const*> objectSources;
  3361. this->GetObjectSources(objectSources, config);
  3362. std::map<cmSourceFile const*, std::string> mapping;
  3363. for (cmSourceFile const* sf : objectSources) {
  3364. mapping[sf];
  3365. }
  3366. this->LocalGenerator->ComputeObjectFilenames(mapping, this);
  3367. for (cmSourceFile const* src : objectSources) {
  3368. // Find the object file name corresponding to this source file.
  3369. auto map_it = mapping.find(src);
  3370. // It must exist because we populated the mapping just above.
  3371. assert(!map_it->second.empty());
  3372. objects.push_back(map_it->second);
  3373. }
  3374. // We need to compute the relative path from the root of
  3375. // of the object directory to handle subdirectory paths
  3376. std::string rootObjectDir = this->GetObjectDirectory(config);
  3377. rootObjectDir = cmSystemTools::CollapseFullPath(rootObjectDir);
  3378. auto ispcObjects = this->GetGeneratedISPCObjects(config);
  3379. for (std::string const& output : ispcObjects) {
  3380. auto relativePathFromObjectDir = output.substr(rootObjectDir.size());
  3381. objects.push_back(relativePathFromObjectDir);
  3382. }
  3383. }
  3384. bool cmGeneratorTarget::StrictTargetComparison::operator()(
  3385. cmGeneratorTarget const* t1, cmGeneratorTarget const* t2) const
  3386. {
  3387. int nameResult = strcmp(t1->GetName().c_str(), t2->GetName().c_str());
  3388. if (nameResult == 0) {
  3389. return strcmp(
  3390. t1->GetLocalGenerator()->GetCurrentBinaryDirectory().c_str(),
  3391. t2->GetLocalGenerator()->GetCurrentBinaryDirectory().c_str()) < 0;
  3392. }
  3393. return nameResult < 0;
  3394. }
  3395. struct cmGeneratorTarget::SourceFileFlags
  3396. cmGeneratorTarget::GetTargetSourceFileFlags(const cmSourceFile* sf) const
  3397. {
  3398. struct SourceFileFlags flags;
  3399. this->ConstructSourceFileFlags();
  3400. auto si = this->SourceFlagsMap.find(sf);
  3401. if (si != this->SourceFlagsMap.end()) {
  3402. flags = si->second;
  3403. } else {
  3404. // Handle the MACOSX_PACKAGE_LOCATION property on source files that
  3405. // were not listed in one of the other lists.
  3406. if (cmValue location = sf->GetProperty("MACOSX_PACKAGE_LOCATION")) {
  3407. flags.MacFolder = location->c_str();
  3408. const bool stripResources =
  3409. this->GlobalGenerator->ShouldStripResourcePath(this->Makefile);
  3410. if (*location == "Resources") {
  3411. flags.Type = cmGeneratorTarget::SourceFileTypeResource;
  3412. if (stripResources) {
  3413. flags.MacFolder = "";
  3414. }
  3415. } else if (cmHasLiteralPrefix(*location, "Resources/")) {
  3416. flags.Type = cmGeneratorTarget::SourceFileTypeDeepResource;
  3417. if (stripResources) {
  3418. flags.MacFolder += cmStrLen("Resources/");
  3419. }
  3420. } else {
  3421. flags.Type = cmGeneratorTarget::SourceFileTypeMacContent;
  3422. }
  3423. }
  3424. }
  3425. return flags;
  3426. }
  3427. void cmGeneratorTarget::ConstructSourceFileFlags() const
  3428. {
  3429. if (this->SourceFileFlagsConstructed) {
  3430. return;
  3431. }
  3432. this->SourceFileFlagsConstructed = true;
  3433. // Process public headers to mark the source files.
  3434. if (cmValue files = this->GetProperty("PUBLIC_HEADER")) {
  3435. cmList relFiles{ *files };
  3436. for (auto const& relFile : relFiles) {
  3437. if (cmSourceFile* sf = this->Makefile->GetSource(relFile)) {
  3438. SourceFileFlags& flags = this->SourceFlagsMap[sf];
  3439. flags.MacFolder = "Headers";
  3440. flags.Type = cmGeneratorTarget::SourceFileTypePublicHeader;
  3441. }
  3442. }
  3443. }
  3444. // Process private headers after public headers so that they take
  3445. // precedence if a file is listed in both.
  3446. if (cmValue files = this->GetProperty("PRIVATE_HEADER")) {
  3447. cmList relFiles{ *files };
  3448. for (auto const& relFile : relFiles) {
  3449. if (cmSourceFile* sf = this->Makefile->GetSource(relFile)) {
  3450. SourceFileFlags& flags = this->SourceFlagsMap[sf];
  3451. flags.MacFolder = "PrivateHeaders";
  3452. flags.Type = cmGeneratorTarget::SourceFileTypePrivateHeader;
  3453. }
  3454. }
  3455. }
  3456. // Mark sources listed as resources.
  3457. if (cmValue files = this->GetProperty("RESOURCE")) {
  3458. cmList relFiles{ *files };
  3459. for (auto const& relFile : relFiles) {
  3460. if (cmSourceFile* sf = this->Makefile->GetSource(relFile)) {
  3461. SourceFileFlags& flags = this->SourceFlagsMap[sf];
  3462. flags.MacFolder = "";
  3463. if (!this->GlobalGenerator->ShouldStripResourcePath(this->Makefile)) {
  3464. flags.MacFolder = "Resources";
  3465. }
  3466. flags.Type = cmGeneratorTarget::SourceFileTypeResource;
  3467. }
  3468. }
  3469. }
  3470. }
  3471. bool cmGeneratorTarget::SetDeviceLink(bool deviceLink)
  3472. {
  3473. bool previous = this->DeviceLink;
  3474. this->DeviceLink = deviceLink;
  3475. return previous;
  3476. }
  3477. void cmGeneratorTarget::GetTargetVersion(int& major, int& minor) const
  3478. {
  3479. int patch;
  3480. this->GetTargetVersion("VERSION", major, minor, patch);
  3481. }
  3482. void cmGeneratorTarget::GetTargetVersionFallback(
  3483. const std::string& property, const std::string& fallback_property,
  3484. int& major, int& minor, int& patch) const
  3485. {
  3486. if (this->GetProperty(property)) {
  3487. this->GetTargetVersion(property, major, minor, patch);
  3488. } else {
  3489. this->GetTargetVersion(fallback_property, major, minor, patch);
  3490. }
  3491. }
  3492. void cmGeneratorTarget::GetTargetVersion(const std::string& property,
  3493. int& major, int& minor,
  3494. int& patch) const
  3495. {
  3496. // Set the default values.
  3497. major = 0;
  3498. minor = 0;
  3499. patch = 0;
  3500. assert(this->GetType() != cmStateEnums::INTERFACE_LIBRARY);
  3501. if (cmValue version = this->GetProperty(property)) {
  3502. // Try to parse the version number and store the results that were
  3503. // successfully parsed.
  3504. int parsed_major;
  3505. int parsed_minor;
  3506. int parsed_patch;
  3507. switch (sscanf(version->c_str(), "%d.%d.%d", &parsed_major, &parsed_minor,
  3508. &parsed_patch)) {
  3509. case 3:
  3510. patch = parsed_patch;
  3511. CM_FALLTHROUGH;
  3512. case 2:
  3513. minor = parsed_minor;
  3514. CM_FALLTHROUGH;
  3515. case 1:
  3516. major = parsed_major;
  3517. CM_FALLTHROUGH;
  3518. default:
  3519. break;
  3520. }
  3521. }
  3522. }
  3523. std::string cmGeneratorTarget::GetRuntimeLinkLibrary(
  3524. std::string const& lang, std::string const& config) const
  3525. {
  3526. // This is activated by the presence of a default selection whether or
  3527. // not it is overridden by a property.
  3528. cmValue runtimeLibraryDefault = this->Makefile->GetDefinition(
  3529. cmStrCat("CMAKE_", lang, "_RUNTIME_LIBRARY_DEFAULT"));
  3530. if (!cmNonempty(runtimeLibraryDefault)) {
  3531. return std::string();
  3532. }
  3533. cmValue runtimeLibraryValue =
  3534. this->Target->GetProperty(cmStrCat(lang, "_RUNTIME_LIBRARY"));
  3535. if (!runtimeLibraryValue) {
  3536. runtimeLibraryValue = runtimeLibraryDefault;
  3537. }
  3538. return cmSystemTools::UpperCase(cmGeneratorExpression::Evaluate(
  3539. *runtimeLibraryValue, this->LocalGenerator, config, this));
  3540. }
  3541. std::string cmGeneratorTarget::GetFortranModuleDirectory(
  3542. std::string const& working_dir) const
  3543. {
  3544. if (!this->FortranModuleDirectoryCreated) {
  3545. this->FortranModuleDirectory =
  3546. this->CreateFortranModuleDirectory(working_dir);
  3547. this->FortranModuleDirectoryCreated = true;
  3548. }
  3549. return this->FortranModuleDirectory;
  3550. }
  3551. bool cmGeneratorTarget::IsFortranBuildingInstrinsicModules() const
  3552. {
  3553. if (cmValue prop =
  3554. this->GetProperty("Fortran_BUILDING_INSTRINSIC_MODULES")) {
  3555. return prop.IsOn();
  3556. }
  3557. return false;
  3558. }
  3559. std::string cmGeneratorTarget::CreateFortranModuleDirectory(
  3560. std::string const& working_dir) const
  3561. {
  3562. std::string mod_dir;
  3563. std::string target_mod_dir;
  3564. if (cmValue prop = this->GetProperty("Fortran_MODULE_DIRECTORY")) {
  3565. target_mod_dir = *prop;
  3566. } else {
  3567. std::string const& default_mod_dir =
  3568. this->LocalGenerator->GetCurrentBinaryDirectory();
  3569. if (default_mod_dir != working_dir) {
  3570. target_mod_dir = default_mod_dir;
  3571. }
  3572. }
  3573. cmValue moddir_flag =
  3574. this->Makefile->GetDefinition("CMAKE_Fortran_MODDIR_FLAG");
  3575. if (!target_mod_dir.empty() && moddir_flag) {
  3576. // Compute the full path to the module directory.
  3577. if (cmSystemTools::FileIsFullPath(target_mod_dir)) {
  3578. // Already a full path.
  3579. mod_dir = target_mod_dir;
  3580. } else {
  3581. // Interpret relative to the current output directory.
  3582. mod_dir = cmStrCat(this->LocalGenerator->GetCurrentBinaryDirectory(),
  3583. '/', target_mod_dir);
  3584. }
  3585. // Make sure the module output directory exists.
  3586. cmSystemTools::MakeDirectory(mod_dir);
  3587. }
  3588. return mod_dir;
  3589. }
  3590. void cmGeneratorTarget::AddISPCGeneratedHeader(std::string const& header,
  3591. std::string const& config)
  3592. {
  3593. std::string config_upper;
  3594. if (!config.empty()) {
  3595. config_upper = cmSystemTools::UpperCase(config);
  3596. }
  3597. auto iter = this->ISPCGeneratedHeaders.find(config_upper);
  3598. if (iter == this->ISPCGeneratedHeaders.end()) {
  3599. std::vector<std::string> headers;
  3600. headers.emplace_back(header);
  3601. this->ISPCGeneratedHeaders.insert({ config_upper, headers });
  3602. } else {
  3603. iter->second.emplace_back(header);
  3604. }
  3605. }
  3606. std::vector<std::string> cmGeneratorTarget::GetGeneratedISPCHeaders(
  3607. std::string const& config) const
  3608. {
  3609. std::string config_upper;
  3610. if (!config.empty()) {
  3611. config_upper = cmSystemTools::UpperCase(config);
  3612. }
  3613. auto iter = this->ISPCGeneratedHeaders.find(config_upper);
  3614. if (iter == this->ISPCGeneratedHeaders.end()) {
  3615. return std::vector<std::string>{};
  3616. }
  3617. return iter->second;
  3618. }
  3619. void cmGeneratorTarget::AddISPCGeneratedObject(std::vector<std::string>&& objs,
  3620. std::string const& config)
  3621. {
  3622. std::string config_upper;
  3623. if (!config.empty()) {
  3624. config_upper = cmSystemTools::UpperCase(config);
  3625. }
  3626. auto iter = this->ISPCGeneratedObjects.find(config_upper);
  3627. if (iter == this->ISPCGeneratedObjects.end()) {
  3628. this->ISPCGeneratedObjects.insert({ config_upper, objs });
  3629. } else {
  3630. iter->second.insert(iter->second.end(), objs.begin(), objs.end());
  3631. }
  3632. }
  3633. std::vector<std::string> cmGeneratorTarget::GetGeneratedISPCObjects(
  3634. std::string const& config) const
  3635. {
  3636. std::string config_upper;
  3637. if (!config.empty()) {
  3638. config_upper = cmSystemTools::UpperCase(config);
  3639. }
  3640. auto iter = this->ISPCGeneratedObjects.find(config_upper);
  3641. if (iter == this->ISPCGeneratedObjects.end()) {
  3642. return std::vector<std::string>{};
  3643. }
  3644. return iter->second;
  3645. }
  3646. std::string cmGeneratorTarget::GetFrameworkVersion() const
  3647. {
  3648. assert(this->GetType() != cmStateEnums::INTERFACE_LIBRARY);
  3649. if (cmValue fversion = this->GetProperty("FRAMEWORK_VERSION")) {
  3650. return *fversion;
  3651. }
  3652. if (cmValue tversion = this->GetProperty("VERSION")) {
  3653. return *tversion;
  3654. }
  3655. return "A";
  3656. }
  3657. std::string cmGeneratorTarget::ComputeVersionedName(std::string const& prefix,
  3658. std::string const& base,
  3659. std::string const& suffix,
  3660. std::string const& name,
  3661. cmValue version) const
  3662. {
  3663. std::string vName = this->IsApple() ? (prefix + base) : name;
  3664. if (version) {
  3665. vName += ".";
  3666. vName += *version;
  3667. }
  3668. vName += this->IsApple() ? suffix : std::string();
  3669. return vName;
  3670. }
  3671. std::vector<std::string> cmGeneratorTarget::GetPropertyKeys() const
  3672. {
  3673. return this->Target->GetProperties().GetKeys();
  3674. }
  3675. void cmGeneratorTarget::ReportPropertyOrigin(
  3676. const std::string& p, const std::string& result, const std::string& report,
  3677. const std::string& compatibilityType) const
  3678. {
  3679. cmList debugProperties{ this->Target->GetMakefile()->GetDefinition(
  3680. "CMAKE_DEBUG_TARGET_PROPERTIES") };
  3681. bool debugOrigin = !this->DebugCompatiblePropertiesDone[p] &&
  3682. cm::contains(debugProperties, p);
  3683. if (this->GlobalGenerator->GetConfigureDoneCMP0026()) {
  3684. this->DebugCompatiblePropertiesDone[p] = true;
  3685. }
  3686. if (!debugOrigin) {
  3687. return;
  3688. }
  3689. std::string areport =
  3690. cmStrCat(compatibilityType, " of property \"", p, "\" for target \"",
  3691. this->GetName(), "\" (result: \"", result, "\"):\n", report);
  3692. this->LocalGenerator->GetCMakeInstance()->IssueMessage(MessageType::LOG,
  3693. areport);
  3694. }
  3695. std::string cmGeneratorTarget::GetDirectory(
  3696. const std::string& config, cmStateEnums::ArtifactType artifact) const
  3697. {
  3698. if (this->IsImported()) {
  3699. auto fullPath = this->Target->ImportedGetFullPath(config, artifact);
  3700. if (this->IsFrameworkOnApple()) {
  3701. auto fwDescriptor = this->GetGlobalGenerator()->SplitFrameworkPath(
  3702. fullPath, cmGlobalGenerator::FrameworkFormat::Strict);
  3703. if (fwDescriptor) {
  3704. return fwDescriptor->Directory;
  3705. }
  3706. }
  3707. // Return the directory from which the target is imported.
  3708. return cmSystemTools::GetFilenamePath(fullPath);
  3709. }
  3710. if (OutputInfo const* info = this->GetOutputInfo(config)) {
  3711. // Return the directory in which the target will be built.
  3712. switch (artifact) {
  3713. case cmStateEnums::RuntimeBinaryArtifact:
  3714. return info->OutDir;
  3715. case cmStateEnums::ImportLibraryArtifact:
  3716. return info->ImpDir;
  3717. }
  3718. }
  3719. return "";
  3720. }
  3721. bool cmGeneratorTarget::UsesDefaultOutputDir(
  3722. const std::string& config, cmStateEnums::ArtifactType artifact) const
  3723. {
  3724. std::string dir;
  3725. return this->ComputeOutputDir(config, artifact, dir);
  3726. }
  3727. cmGeneratorTarget::OutputInfo const* cmGeneratorTarget::GetOutputInfo(
  3728. const std::string& config) const
  3729. {
  3730. // There is no output information for imported targets.
  3731. if (this->IsImported()) {
  3732. return nullptr;
  3733. }
  3734. // Synthetic targets don't have output.
  3735. if (this->IsSynthetic()) {
  3736. return nullptr;
  3737. }
  3738. // Only libraries and executables have well-defined output files.
  3739. if (!this->HaveWellDefinedOutputFiles()) {
  3740. std::string msg = cmStrCat("cmGeneratorTarget::GetOutputInfo called for ",
  3741. this->GetName(), " which has type ",
  3742. cmState::GetTargetTypeName(this->GetType()));
  3743. this->LocalGenerator->IssueMessage(MessageType::INTERNAL_ERROR, msg);
  3744. return nullptr;
  3745. }
  3746. // Lookup/compute/cache the output information for this configuration.
  3747. std::string config_upper;
  3748. if (!config.empty()) {
  3749. config_upper = cmSystemTools::UpperCase(config);
  3750. }
  3751. auto i = this->OutputInfoMap.find(config_upper);
  3752. if (i == this->OutputInfoMap.end()) {
  3753. // Add empty info in map to detect potential recursion.
  3754. OutputInfo info;
  3755. OutputInfoMapType::value_type entry(config_upper, info);
  3756. i = this->OutputInfoMap.insert(entry).first;
  3757. // Compute output directories.
  3758. this->ComputeOutputDir(config, cmStateEnums::RuntimeBinaryArtifact,
  3759. info.OutDir);
  3760. this->ComputeOutputDir(config, cmStateEnums::ImportLibraryArtifact,
  3761. info.ImpDir);
  3762. if (!this->ComputePDBOutputDir("PDB", config, info.PdbDir)) {
  3763. info.PdbDir = info.OutDir;
  3764. }
  3765. // Now update the previously-prepared map entry.
  3766. i->second = info;
  3767. } else if (i->second.empty()) {
  3768. // An empty map entry indicates we have been called recursively
  3769. // from the above block.
  3770. this->LocalGenerator->GetCMakeInstance()->IssueMessage(
  3771. MessageType::FATAL_ERROR,
  3772. "Target '" + this->GetName() + "' OUTPUT_DIRECTORY depends on itself.",
  3773. this->GetBacktrace());
  3774. return nullptr;
  3775. }
  3776. return &i->second;
  3777. }
  3778. bool cmGeneratorTarget::ComputeOutputDir(const std::string& config,
  3779. cmStateEnums::ArtifactType artifact,
  3780. std::string& out) const
  3781. {
  3782. bool usesDefaultOutputDir = false;
  3783. std::string conf = config;
  3784. // Look for a target property defining the target output directory
  3785. // based on the target type.
  3786. std::string targetTypeName = this->GetOutputTargetType(artifact);
  3787. std::string propertyName;
  3788. if (!targetTypeName.empty()) {
  3789. propertyName = cmStrCat(targetTypeName, "_OUTPUT_DIRECTORY");
  3790. }
  3791. // Check for a per-configuration output directory target property.
  3792. std::string configUpper = cmSystemTools::UpperCase(conf);
  3793. std::string configProp;
  3794. if (!targetTypeName.empty()) {
  3795. configProp = cmStrCat(targetTypeName, "_OUTPUT_DIRECTORY_", configUpper);
  3796. }
  3797. // Select an output directory.
  3798. if (cmValue config_outdir = this->GetProperty(configProp)) {
  3799. // Use the user-specified per-configuration output directory.
  3800. out = cmGeneratorExpression::Evaluate(*config_outdir, this->LocalGenerator,
  3801. config, this);
  3802. // Skip per-configuration subdirectory.
  3803. conf.clear();
  3804. } else if (cmValue outdir = this->GetProperty(propertyName)) {
  3805. // Use the user-specified output directory.
  3806. out = cmGeneratorExpression::Evaluate(*outdir, this->LocalGenerator,
  3807. config, this);
  3808. // Skip per-configuration subdirectory if the value contained a
  3809. // generator expression.
  3810. if (out != *outdir) {
  3811. conf.clear();
  3812. }
  3813. } else if (this->GetType() == cmStateEnums::EXECUTABLE) {
  3814. // Lookup the output path for executables.
  3815. out = this->Makefile->GetSafeDefinition("EXECUTABLE_OUTPUT_PATH");
  3816. } else if (this->GetType() == cmStateEnums::STATIC_LIBRARY ||
  3817. this->GetType() == cmStateEnums::SHARED_LIBRARY ||
  3818. this->GetType() == cmStateEnums::MODULE_LIBRARY) {
  3819. // Lookup the output path for libraries.
  3820. out = this->Makefile->GetSafeDefinition("LIBRARY_OUTPUT_PATH");
  3821. }
  3822. if (out.empty()) {
  3823. // Default to the current output directory.
  3824. usesDefaultOutputDir = true;
  3825. out = ".";
  3826. }
  3827. // Convert the output path to a full path in case it is
  3828. // specified as a relative path. Treat a relative path as
  3829. // relative to the current output directory for this makefile.
  3830. out = (cmSystemTools::CollapseFullPath(
  3831. out, this->LocalGenerator->GetCurrentBinaryDirectory()));
  3832. // The generator may add the configuration's subdirectory.
  3833. if (!conf.empty()) {
  3834. bool useEPN =
  3835. this->GlobalGenerator->UseEffectivePlatformName(this->Makefile);
  3836. std::string suffix =
  3837. usesDefaultOutputDir && useEPN ? "${EFFECTIVE_PLATFORM_NAME}" : "";
  3838. this->LocalGenerator->GetGlobalGenerator()->AppendDirectoryForConfig(
  3839. "/", conf, suffix, out);
  3840. }
  3841. return usesDefaultOutputDir;
  3842. }
  3843. bool cmGeneratorTarget::ComputePDBOutputDir(const std::string& kind,
  3844. const std::string& config,
  3845. std::string& out) const
  3846. {
  3847. // Look for a target property defining the target output directory
  3848. // based on the target type.
  3849. std::string propertyName;
  3850. if (!kind.empty()) {
  3851. propertyName = cmStrCat(kind, "_OUTPUT_DIRECTORY");
  3852. }
  3853. std::string conf = config;
  3854. // Check for a per-configuration output directory target property.
  3855. std::string configUpper = cmSystemTools::UpperCase(conf);
  3856. std::string configProp;
  3857. if (!kind.empty()) {
  3858. configProp = cmStrCat(kind, "_OUTPUT_DIRECTORY_", configUpper);
  3859. }
  3860. // Select an output directory.
  3861. if (cmValue config_outdir = this->GetProperty(configProp)) {
  3862. // Use the user-specified per-configuration output directory.
  3863. out = cmGeneratorExpression::Evaluate(*config_outdir, this->LocalGenerator,
  3864. config);
  3865. // Skip per-configuration subdirectory.
  3866. conf.clear();
  3867. } else if (cmValue outdir = this->GetProperty(propertyName)) {
  3868. // Use the user-specified output directory.
  3869. out =
  3870. cmGeneratorExpression::Evaluate(*outdir, this->LocalGenerator, config);
  3871. // Skip per-configuration subdirectory if the value contained a
  3872. // generator expression.
  3873. if (out != *outdir) {
  3874. conf.clear();
  3875. }
  3876. }
  3877. if (out.empty()) {
  3878. return false;
  3879. }
  3880. // Convert the output path to a full path in case it is
  3881. // specified as a relative path. Treat a relative path as
  3882. // relative to the current output directory for this makefile.
  3883. out = (cmSystemTools::CollapseFullPath(
  3884. out, this->LocalGenerator->GetCurrentBinaryDirectory()));
  3885. // The generator may add the configuration's subdirectory.
  3886. if (!conf.empty()) {
  3887. this->LocalGenerator->GetGlobalGenerator()->AppendDirectoryForConfig(
  3888. "/", conf, "", out);
  3889. }
  3890. return true;
  3891. }
  3892. bool cmGeneratorTarget::HaveInstallTreeRPATH(const std::string& config) const
  3893. {
  3894. std::string install_rpath;
  3895. this->GetInstallRPATH(config, install_rpath);
  3896. return !install_rpath.empty() &&
  3897. !this->Makefile->IsOn("CMAKE_SKIP_INSTALL_RPATH");
  3898. }
  3899. bool cmGeneratorTarget::GetBuildRPATH(const std::string& config,
  3900. std::string& rpath) const
  3901. {
  3902. return this->GetRPATH(config, "BUILD_RPATH", rpath);
  3903. }
  3904. bool cmGeneratorTarget::GetInstallRPATH(const std::string& config,
  3905. std::string& rpath) const
  3906. {
  3907. return this->GetRPATH(config, "INSTALL_RPATH", rpath);
  3908. }
  3909. bool cmGeneratorTarget::GetRPATH(const std::string& config,
  3910. const std::string& prop,
  3911. std::string& rpath) const
  3912. {
  3913. cmValue value = this->GetProperty(prop);
  3914. if (!value) {
  3915. return false;
  3916. }
  3917. rpath =
  3918. cmGeneratorExpression::Evaluate(*value, this->LocalGenerator, config);
  3919. return true;
  3920. }
  3921. cmGeneratorTarget::ImportInfo const* cmGeneratorTarget::GetImportInfo(
  3922. const std::string& config) const
  3923. {
  3924. // There is no imported information for non-imported targets.
  3925. if (!this->IsImported()) {
  3926. return nullptr;
  3927. }
  3928. // Lookup/compute/cache the import information for this
  3929. // configuration.
  3930. std::string config_upper;
  3931. if (!config.empty()) {
  3932. config_upper = cmSystemTools::UpperCase(config);
  3933. } else {
  3934. config_upper = "NOCONFIG";
  3935. }
  3936. auto i = this->ImportInfoMap.find(config_upper);
  3937. if (i == this->ImportInfoMap.end()) {
  3938. ImportInfo info;
  3939. this->ComputeImportInfo(config_upper, info);
  3940. ImportInfoMapType::value_type entry(config_upper, info);
  3941. i = this->ImportInfoMap.insert(entry).first;
  3942. }
  3943. if (this->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
  3944. return &i->second;
  3945. }
  3946. // If the location is empty then the target is not available for
  3947. // this configuration.
  3948. if (i->second.Location.empty() && i->second.ImportLibrary.empty()) {
  3949. return nullptr;
  3950. }
  3951. // Return the import information.
  3952. return &i->second;
  3953. }
  3954. void cmGeneratorTarget::ComputeImportInfo(std::string const& desired_config,
  3955. ImportInfo& info) const
  3956. {
  3957. // This method finds information about an imported target from its
  3958. // properties. The "IMPORTED_" namespace is reserved for properties
  3959. // defined by the project exporting the target.
  3960. // Initialize members.
  3961. info.NoSOName = false;
  3962. cmValue loc = nullptr;
  3963. cmValue imp = nullptr;
  3964. std::string suffix;
  3965. if (!this->Target->GetMappedConfig(desired_config, loc, imp, suffix)) {
  3966. return;
  3967. }
  3968. // Get the link interface.
  3969. {
  3970. // Use the INTERFACE_LINK_LIBRARIES special representation directly
  3971. // to get backtraces.
  3972. cmBTStringRange entries = this->Target->GetLinkInterfaceEntries();
  3973. if (!entries.empty()) {
  3974. info.LibrariesProp = "INTERFACE_LINK_LIBRARIES";
  3975. for (BT<std::string> const& entry : entries) {
  3976. info.Libraries.emplace_back(entry);
  3977. }
  3978. } else if (this->GetType() != cmStateEnums::INTERFACE_LIBRARY) {
  3979. std::string linkProp =
  3980. cmStrCat("IMPORTED_LINK_INTERFACE_LIBRARIES", suffix);
  3981. cmValue propertyLibs = this->GetProperty(linkProp);
  3982. if (!propertyLibs) {
  3983. linkProp = "IMPORTED_LINK_INTERFACE_LIBRARIES";
  3984. propertyLibs = this->GetProperty(linkProp);
  3985. }
  3986. if (propertyLibs) {
  3987. info.LibrariesProp = linkProp;
  3988. info.Libraries.emplace_back(*propertyLibs);
  3989. }
  3990. }
  3991. }
  3992. for (BT<std::string> const& entry :
  3993. this->Target->GetLinkInterfaceDirectEntries()) {
  3994. info.LibrariesHeadInclude.emplace_back(entry);
  3995. }
  3996. for (BT<std::string> const& entry :
  3997. this->Target->GetLinkInterfaceDirectExcludeEntries()) {
  3998. info.LibrariesHeadExclude.emplace_back(entry);
  3999. }
  4000. if (this->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
  4001. if (loc) {
  4002. info.LibName = *loc;
  4003. }
  4004. return;
  4005. }
  4006. // A provided configuration has been chosen. Load the
  4007. // configuration's properties.
  4008. // Get the location.
  4009. if (loc) {
  4010. info.Location = *loc;
  4011. } else {
  4012. std::string impProp = cmStrCat("IMPORTED_LOCATION", suffix);
  4013. if (cmValue config_location = this->GetProperty(impProp)) {
  4014. info.Location = *config_location;
  4015. } else if (cmValue location = this->GetProperty("IMPORTED_LOCATION")) {
  4016. info.Location = *location;
  4017. }
  4018. }
  4019. // Get the soname.
  4020. if (this->GetType() == cmStateEnums::SHARED_LIBRARY) {
  4021. std::string soProp = cmStrCat("IMPORTED_SONAME", suffix);
  4022. if (cmValue config_soname = this->GetProperty(soProp)) {
  4023. info.SOName = *config_soname;
  4024. } else if (cmValue soname = this->GetProperty("IMPORTED_SONAME")) {
  4025. info.SOName = *soname;
  4026. }
  4027. }
  4028. // Get the "no-soname" mark.
  4029. if (this->GetType() == cmStateEnums::SHARED_LIBRARY) {
  4030. std::string soProp = cmStrCat("IMPORTED_NO_SONAME", suffix);
  4031. if (cmValue config_no_soname = this->GetProperty(soProp)) {
  4032. info.NoSOName = config_no_soname.IsOn();
  4033. } else if (cmValue no_soname = this->GetProperty("IMPORTED_NO_SONAME")) {
  4034. info.NoSOName = no_soname.IsOn();
  4035. }
  4036. }
  4037. // Get the import library.
  4038. if (imp) {
  4039. info.ImportLibrary = *imp;
  4040. } else if (this->GetType() == cmStateEnums::SHARED_LIBRARY ||
  4041. this->IsExecutableWithExports()) {
  4042. std::string impProp = cmStrCat("IMPORTED_IMPLIB", suffix);
  4043. if (cmValue config_implib = this->GetProperty(impProp)) {
  4044. info.ImportLibrary = *config_implib;
  4045. } else if (cmValue implib = this->GetProperty("IMPORTED_IMPLIB")) {
  4046. info.ImportLibrary = *implib;
  4047. }
  4048. }
  4049. // Get the link dependencies.
  4050. {
  4051. std::string linkProp =
  4052. cmStrCat("IMPORTED_LINK_DEPENDENT_LIBRARIES", suffix);
  4053. if (cmValue config_libs = this->GetProperty(linkProp)) {
  4054. info.SharedDeps = *config_libs;
  4055. } else if (cmValue libs =
  4056. this->GetProperty("IMPORTED_LINK_DEPENDENT_LIBRARIES")) {
  4057. info.SharedDeps = *libs;
  4058. }
  4059. }
  4060. // Get the link languages.
  4061. if (this->LinkLanguagePropagatesToDependents()) {
  4062. std::string linkProp =
  4063. cmStrCat("IMPORTED_LINK_INTERFACE_LANGUAGES", suffix);
  4064. if (cmValue config_libs = this->GetProperty(linkProp)) {
  4065. info.Languages = *config_libs;
  4066. } else if (cmValue libs =
  4067. this->GetProperty("IMPORTED_LINK_INTERFACE_LANGUAGES")) {
  4068. info.Languages = *libs;
  4069. }
  4070. }
  4071. // Get information if target is managed assembly.
  4072. {
  4073. std::string linkProp = "IMPORTED_COMMON_LANGUAGE_RUNTIME";
  4074. if (cmValue pc = this->GetProperty(linkProp + suffix)) {
  4075. info.Managed = this->CheckManagedType(*pc);
  4076. } else if (cmValue p = this->GetProperty(linkProp)) {
  4077. info.Managed = this->CheckManagedType(*p);
  4078. }
  4079. }
  4080. // Get the cyclic repetition count.
  4081. if (this->GetType() == cmStateEnums::STATIC_LIBRARY) {
  4082. std::string linkProp =
  4083. cmStrCat("IMPORTED_LINK_INTERFACE_MULTIPLICITY", suffix);
  4084. if (cmValue config_reps = this->GetProperty(linkProp)) {
  4085. sscanf(config_reps->c_str(), "%u", &info.Multiplicity);
  4086. } else if (cmValue reps =
  4087. this->GetProperty("IMPORTED_LINK_INTERFACE_MULTIPLICITY")) {
  4088. sscanf(reps->c_str(), "%u", &info.Multiplicity);
  4089. }
  4090. }
  4091. }
  4092. bool cmGeneratorTarget::GetConfigCommonSourceFilesForXcode(
  4093. std::vector<cmSourceFile*>& files) const
  4094. {
  4095. std::vector<std::string> const& configs =
  4096. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  4097. auto it = configs.begin();
  4098. const std::string& firstConfig = *it;
  4099. this->GetSourceFilesWithoutObjectLibraries(files, firstConfig);
  4100. for (; it != configs.end(); ++it) {
  4101. std::vector<cmSourceFile*> configFiles;
  4102. this->GetSourceFilesWithoutObjectLibraries(configFiles, *it);
  4103. if (configFiles != files) {
  4104. std::string firstConfigFiles;
  4105. const char* sep = "";
  4106. for (cmSourceFile* f : files) {
  4107. firstConfigFiles += sep;
  4108. firstConfigFiles += f->ResolveFullPath();
  4109. sep = "\n ";
  4110. }
  4111. std::string thisConfigFiles;
  4112. sep = "";
  4113. for (cmSourceFile* f : configFiles) {
  4114. thisConfigFiles += sep;
  4115. thisConfigFiles += f->ResolveFullPath();
  4116. sep = "\n ";
  4117. }
  4118. std::ostringstream e;
  4119. /* clang-format off */
  4120. e << "Target \"" << this->GetName()
  4121. << "\" has source files which vary by "
  4122. "configuration. This is not supported by the \""
  4123. << this->GlobalGenerator->GetName()
  4124. << "\" generator.\n"
  4125. "Config \"" << firstConfig << "\":\n"
  4126. " " << firstConfigFiles << "\n"
  4127. "Config \"" << *it << "\":\n"
  4128. " " << thisConfigFiles << "\n";
  4129. /* clang-format on */
  4130. this->LocalGenerator->IssueMessage(MessageType::FATAL_ERROR, e.str());
  4131. return false;
  4132. }
  4133. }
  4134. return true;
  4135. }
  4136. void cmGeneratorTarget::GetObjectLibrariesCMP0026(
  4137. std::vector<cmGeneratorTarget*>& objlibs) const
  4138. {
  4139. // At configure-time, this method can be called as part of getting the
  4140. // LOCATION property or to export() a file to be include()d. However
  4141. // there is no cmGeneratorTarget at configure-time, so search the SOURCES
  4142. // for TARGET_OBJECTS instead for backwards compatibility with OLD
  4143. // behavior of CMP0024 and CMP0026 only.
  4144. cmBTStringRange rng = this->Target->GetSourceEntries();
  4145. for (auto const& entry : rng) {
  4146. cmList files{ entry.Value };
  4147. for (auto const& li : files) {
  4148. if (cmHasLiteralPrefix(li, "$<TARGET_OBJECTS:") && li.back() == '>') {
  4149. std::string objLibName = li.substr(17, li.size() - 18);
  4150. if (cmGeneratorExpression::Find(objLibName) != std::string::npos) {
  4151. continue;
  4152. }
  4153. cmGeneratorTarget* objLib =
  4154. this->LocalGenerator->FindGeneratorTargetToUse(objLibName);
  4155. if (objLib) {
  4156. objlibs.push_back(objLib);
  4157. }
  4158. }
  4159. }
  4160. }
  4161. }
  4162. std::string cmGeneratorTarget::CheckCMP0004(std::string const& item) const
  4163. {
  4164. // Strip whitespace off the library names because we used to do this
  4165. // in case variables were expanded at generate time. We no longer
  4166. // do the expansion but users link to libraries like " ${VAR} ".
  4167. std::string lib = item;
  4168. std::string::size_type pos = lib.find_first_not_of(" \t\r\n");
  4169. if (pos != std::string::npos) {
  4170. lib = lib.substr(pos);
  4171. }
  4172. pos = lib.find_last_not_of(" \t\r\n");
  4173. if (pos != std::string::npos) {
  4174. lib = lib.substr(0, pos + 1);
  4175. }
  4176. if (lib != item) {
  4177. cmake* cm = this->LocalGenerator->GetCMakeInstance();
  4178. switch (this->GetPolicyStatusCMP0004()) {
  4179. case cmPolicies::WARN: {
  4180. std::ostringstream w;
  4181. w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0004) << "\n"
  4182. << "Target \"" << this->GetName() << "\" links to item \"" << item
  4183. << "\" which has leading or trailing whitespace.";
  4184. cm->IssueMessage(MessageType::AUTHOR_WARNING, w.str(),
  4185. this->GetBacktrace());
  4186. }
  4187. CM_FALLTHROUGH;
  4188. case cmPolicies::OLD:
  4189. break;
  4190. case cmPolicies::NEW: {
  4191. std::ostringstream e;
  4192. e << "Target \"" << this->GetName() << "\" links to item \"" << item
  4193. << "\" which has leading or trailing whitespace. "
  4194. << "This is now an error according to policy CMP0004.";
  4195. cm->IssueMessage(MessageType::FATAL_ERROR, e.str(),
  4196. this->GetBacktrace());
  4197. } break;
  4198. case cmPolicies::REQUIRED_IF_USED:
  4199. case cmPolicies::REQUIRED_ALWAYS: {
  4200. std::ostringstream e;
  4201. e << cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0004) << "\n"
  4202. << "Target \"" << this->GetName() << "\" links to item \"" << item
  4203. << "\" which has leading or trailing whitespace.";
  4204. cm->IssueMessage(MessageType::FATAL_ERROR, e.str(),
  4205. this->GetBacktrace());
  4206. } break;
  4207. }
  4208. }
  4209. return lib;
  4210. }
  4211. bool cmGeneratorTarget::IsDeprecated() const
  4212. {
  4213. cmValue deprecation = this->GetProperty("DEPRECATION");
  4214. return cmNonempty(deprecation);
  4215. }
  4216. std::string cmGeneratorTarget::GetDeprecation() const
  4217. {
  4218. // find DEPRECATION property
  4219. if (cmValue deprecation = this->GetProperty("DEPRECATION")) {
  4220. return *deprecation;
  4221. }
  4222. return std::string();
  4223. }
  4224. void cmGeneratorTarget::GetLanguages(std::set<std::string>& languages,
  4225. const std::string& config) const
  4226. {
  4227. // Targets that do not compile anything have no languages.
  4228. if (!this->CanCompileSources()) {
  4229. return;
  4230. }
  4231. std::vector<cmSourceFile*> sourceFiles;
  4232. this->GetSourceFiles(sourceFiles, config);
  4233. for (cmSourceFile* src : sourceFiles) {
  4234. const std::string& lang = src->GetOrDetermineLanguage();
  4235. if (!lang.empty()) {
  4236. languages.insert(lang);
  4237. }
  4238. }
  4239. std::set<cmGeneratorTarget const*> objectLibraries;
  4240. if (!this->GlobalGenerator->GetConfigureDoneCMP0026()) {
  4241. std::vector<cmGeneratorTarget*> objectTargets;
  4242. this->GetObjectLibrariesCMP0026(objectTargets);
  4243. for (cmGeneratorTarget* gt : objectTargets) {
  4244. objectLibraries.insert(gt);
  4245. }
  4246. } else {
  4247. objectLibraries = this->GetSourceObjectLibraries(config);
  4248. }
  4249. for (cmGeneratorTarget const* objLib : objectLibraries) {
  4250. objLib->GetLanguages(languages, config);
  4251. }
  4252. }
  4253. std::set<cmGeneratorTarget const*> cmGeneratorTarget::GetSourceObjectLibraries(
  4254. std::string const& config) const
  4255. {
  4256. std::set<cmGeneratorTarget const*> objectLibraries;
  4257. std::vector<cmSourceFile const*> externalObjects;
  4258. this->GetExternalObjects(externalObjects, config);
  4259. for (cmSourceFile const* extObj : externalObjects) {
  4260. std::string objLib = extObj->GetObjectLibrary();
  4261. if (cmGeneratorTarget* tgt =
  4262. this->LocalGenerator->FindGeneratorTargetToUse(objLib)) {
  4263. objectLibraries.insert(tgt);
  4264. }
  4265. }
  4266. return objectLibraries;
  4267. }
  4268. bool cmGeneratorTarget::IsLanguageUsed(std::string const& language,
  4269. std::string const& config) const
  4270. {
  4271. std::set<std::string> languages;
  4272. this->GetLanguages(languages, config);
  4273. return languages.count(language);
  4274. }
  4275. bool cmGeneratorTarget::IsCSharpOnly() const
  4276. {
  4277. // Only certain target types may compile CSharp.
  4278. if (this->GetType() != cmStateEnums::SHARED_LIBRARY &&
  4279. this->GetType() != cmStateEnums::STATIC_LIBRARY &&
  4280. this->GetType() != cmStateEnums::EXECUTABLE) {
  4281. return false;
  4282. }
  4283. std::set<std::string> languages = this->GetAllConfigCompileLanguages();
  4284. // Consider an explicit linker language property, but *not* the
  4285. // computed linker language that may depend on linked targets.
  4286. cmValue linkLang = this->GetProperty("LINKER_LANGUAGE");
  4287. if (cmNonempty(linkLang)) {
  4288. languages.insert(*linkLang);
  4289. }
  4290. return languages.size() == 1 && languages.count("CSharp") > 0;
  4291. }
  4292. bool cmGeneratorTarget::IsDotNetSdkTarget() const
  4293. {
  4294. return !this->GetProperty("DOTNET_SDK").IsEmpty();
  4295. }
  4296. void cmGeneratorTarget::ComputeLinkImplementationLanguages(
  4297. const std::string& config, cmOptionalLinkImplementation& impl) const
  4298. {
  4299. // This target needs runtime libraries for its source languages.
  4300. std::set<std::string> languages;
  4301. // Get languages used in our source files.
  4302. this->GetLanguages(languages, config);
  4303. // Copy the set of languages to the link implementation.
  4304. impl.Languages.insert(impl.Languages.begin(), languages.begin(),
  4305. languages.end());
  4306. }
  4307. bool cmGeneratorTarget::HaveBuildTreeRPATH(const std::string& config) const
  4308. {
  4309. if (this->GetPropertyAsBool("SKIP_BUILD_RPATH")) {
  4310. return false;
  4311. }
  4312. std::string build_rpath;
  4313. if (this->GetBuildRPATH(config, build_rpath)) {
  4314. return true;
  4315. }
  4316. if (cmLinkImplementationLibraries const* impl =
  4317. this->GetLinkImplementationLibraries(config, UseTo::Link)) {
  4318. return !impl->Libraries.empty();
  4319. }
  4320. return false;
  4321. }
  4322. bool cmGeneratorTarget::IsNullImpliedByLinkLibraries(
  4323. const std::string& p) const
  4324. {
  4325. return cm::contains(this->LinkImplicitNullProperties, p);
  4326. }
  4327. bool cmGeneratorTarget::ApplyCXXStdTargets()
  4328. {
  4329. cmStandardLevelResolver standardResolver(this->Makefile);
  4330. cmStandardLevel const cxxStd23 =
  4331. *standardResolver.LanguageStandardLevel("CXX", "23");
  4332. std::vector<std::string> const& configs =
  4333. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  4334. auto std_prop = this->GetProperty("CXX_MODULE_STD");
  4335. if (!std_prop) {
  4336. // TODO(cxxmodules): Add a target policy to flip the default here. Set
  4337. // `std_prop` based on it.
  4338. return true;
  4339. }
  4340. std::string std_prop_value;
  4341. if (std_prop) {
  4342. // Evaluate generator expressions.
  4343. cmGeneratorExpression ge(*this->LocalGenerator->GetCMakeInstance());
  4344. auto cge = ge.Parse(*std_prop);
  4345. if (!cge) {
  4346. this->Makefile->IssueMessage(
  4347. MessageType::FATAL_ERROR,
  4348. cmStrCat(R"(The "CXX_MODULE_STD" property on the target ")",
  4349. this->GetName(), "\" is not a valid generator expression."));
  4350. return false;
  4351. }
  4352. // But do not allow context-sensitive queries. Whether a target uses
  4353. // `import std` should not depend on configuration or properties of the
  4354. // consumer (head target). The link language also shouldn't matter, so ban
  4355. // it as well.
  4356. if (cge->GetHadHeadSensitiveCondition()) {
  4357. // Not reachable; all target-sensitive genexes actually fail to parse.
  4358. this->Makefile->IssueMessage(
  4359. MessageType::FATAL_ERROR,
  4360. cmStrCat(R"(The "CXX_MODULE_STD" property on the target ")",
  4361. this->GetName(),
  4362. "\" contains a condition that queries the "
  4363. "consuming target which is not supported."));
  4364. return false;
  4365. }
  4366. if (cge->GetHadLinkLanguageSensitiveCondition()) {
  4367. // Not reachable; all link language genexes actually fail to parse.
  4368. this->Makefile->IssueMessage(
  4369. MessageType::FATAL_ERROR,
  4370. cmStrCat(R"(The "CXX_MODULE_STD" property on the target ")",
  4371. this->GetName(),
  4372. "\" contains a condition that queries the "
  4373. "link language which is not supported."));
  4374. return false;
  4375. }
  4376. std_prop_value = cge->Evaluate(this->LocalGenerator, "");
  4377. if (cge->GetHadContextSensitiveCondition()) {
  4378. this->Makefile->IssueMessage(
  4379. MessageType::FATAL_ERROR,
  4380. cmStrCat(R"(The "CXX_MODULE_STD" property on the target ")",
  4381. this->GetName(),
  4382. "\" contains a context-sensitive condition "
  4383. "that is not supported."));
  4384. return false;
  4385. }
  4386. }
  4387. auto use_std = cmIsOn(std_prop_value);
  4388. // If we have a value and it is not true, there's nothing to do.
  4389. if (std_prop && !use_std) {
  4390. return true;
  4391. }
  4392. for (auto const& config : configs) {
  4393. if (this->HaveCxxModuleSupport(config) != Cxx20SupportLevel::Supported) {
  4394. continue;
  4395. }
  4396. cm::optional<cmStandardLevel> explicitLevel =
  4397. this->GetExplicitStandardLevel("CXX", config);
  4398. if (!explicitLevel || *explicitLevel < cxxStd23) {
  4399. continue;
  4400. }
  4401. auto const stdLevel =
  4402. standardResolver.GetLevelString("CXX", *explicitLevel);
  4403. auto const targetName = cmStrCat("__CMAKE::CXX", stdLevel);
  4404. if (!this->Makefile->FindTargetToUse(targetName)) {
  4405. auto basicReason = this->Makefile->GetDefinition(cmStrCat(
  4406. "CMAKE_CXX", stdLevel, "_COMPILER_IMPORT_STD_NOT_FOUND_MESSAGE"));
  4407. std::string reason;
  4408. if (!basicReason.IsEmpty()) {
  4409. reason = cmStrCat(" Reason:\n ", basicReason);
  4410. }
  4411. this->Makefile->IssueMessage(
  4412. MessageType::FATAL_ERROR,
  4413. cmStrCat(R"(The "CXX_MODULE_STD" property on the target ")",
  4414. this->GetName(), "\" requires that the \"", targetName,
  4415. "\" target exist, but it was not provided by the toolchain.",
  4416. reason));
  4417. break;
  4418. }
  4419. // Check the experimental feature here as well. A toolchain may have
  4420. // provided the target and skipped the check in the toolchain preparation
  4421. // logic.
  4422. if (!cmExperimental::HasSupportEnabled(
  4423. *this->Makefile, cmExperimental::Feature::CxxImportStd)) {
  4424. break;
  4425. }
  4426. this->Target->AppendProperty(
  4427. "LINK_LIBRARIES",
  4428. cmStrCat("$<BUILD_LOCAL_INTERFACE:$<$<CONFIG:", config, ">:", targetName,
  4429. ">>"));
  4430. }
  4431. return true;
  4432. }
  4433. bool cmGeneratorTarget::DiscoverSyntheticTargets(cmSyntheticTargetCache& cache,
  4434. std::string const& config)
  4435. {
  4436. std::vector<std::string> allConfigs =
  4437. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  4438. cmOptionalLinkImplementation impl;
  4439. this->ComputeLinkImplementationLibraries(config, impl, this, UseTo::Link);
  4440. cmCxxModuleUsageEffects usage(this);
  4441. auto& SyntheticDeps = this->Configs[config].SyntheticDeps;
  4442. for (auto const& entry : impl.Libraries) {
  4443. auto const* gt = entry.Target;
  4444. if (!gt || !gt->IsImported()) {
  4445. continue;
  4446. }
  4447. if (gt->HaveCxx20ModuleSources()) {
  4448. cmCryptoHash hasher(cmCryptoHash::AlgoSHA3_512);
  4449. constexpr size_t HASH_TRUNCATION = 12;
  4450. auto dirhash = hasher.HashString(
  4451. gt->GetLocalGenerator()->GetCurrentBinaryDirectory());
  4452. std::string safeName = gt->GetName();
  4453. cmSystemTools::ReplaceString(safeName, ":", "_");
  4454. auto targetIdent =
  4455. hasher.HashString(cmStrCat("@d_", dirhash, "@u_", usage.GetHash()));
  4456. std::string targetName =
  4457. cmStrCat(safeName, "@synth_", targetIdent.substr(0, HASH_TRUNCATION));
  4458. // Check the cache to see if this instance of the imported target has
  4459. // already been created.
  4460. auto cached = cache.CxxModuleTargets.find(targetName);
  4461. cmGeneratorTarget const* synthDep = nullptr;
  4462. if (cached == cache.CxxModuleTargets.end()) {
  4463. auto const* model = gt->Target;
  4464. auto* mf = gt->Makefile;
  4465. auto* lg = gt->GetLocalGenerator();
  4466. auto* tgt = mf->AddSynthesizedTarget(cmStateEnums::INTERFACE_LIBRARY,
  4467. targetName);
  4468. // Copy relevant information from the existing IMPORTED target.
  4469. // Copy policies to the target.
  4470. tgt->CopyPolicyStatuses(model);
  4471. // Copy file sets.
  4472. {
  4473. auto fsNames = model->GetAllFileSetNames();
  4474. for (auto const& fsName : fsNames) {
  4475. auto const* fs = model->GetFileSet(fsName);
  4476. if (!fs) {
  4477. mf->IssueMessage(MessageType::INTERNAL_ERROR,
  4478. cmStrCat("Failed to find file set named '",
  4479. fsName, "' on target '",
  4480. tgt->GetName(), '\''));
  4481. continue;
  4482. }
  4483. auto* newFs = tgt
  4484. ->GetOrCreateFileSet(fs->GetName(), fs->GetType(),
  4485. fs->GetVisibility())
  4486. .first;
  4487. newFs->CopyEntries(fs);
  4488. }
  4489. }
  4490. // Copy imported C++ module properties.
  4491. tgt->CopyImportedCxxModulesEntries(model);
  4492. // Copy other properties which may affect the C++ module BMI
  4493. // generation.
  4494. tgt->CopyImportedCxxModulesProperties(model);
  4495. tgt->AddLinkLibrary(*mf,
  4496. cmStrCat("$<COMPILE_ONLY:", model->GetName(), '>'),
  4497. GENERAL_LibraryType);
  4498. // Apply usage requirements to the target.
  4499. usage.ApplyToTarget(tgt);
  4500. // Create the generator target and attach it to the local generator.
  4501. auto gtp = cm::make_unique<cmGeneratorTarget>(tgt, lg);
  4502. synthDep = gtp.get();
  4503. cache.CxxModuleTargets[targetName] = synthDep;
  4504. // See `localGen->ComputeTargetCompileFeatures()` call in
  4505. // `cmGlobalGenerator::Compute` for where non-synthetic targets resolve
  4506. // this.
  4507. for (auto const& innerConfig : allConfigs) {
  4508. gtp->ComputeCompileFeatures(innerConfig);
  4509. }
  4510. // See `cmGlobalGenerator::ApplyCXXStdTargets` in
  4511. // `cmGlobalGenerator::Compute` for non-synthetic target resolutions.
  4512. gtp->ApplyCXXStdTargets();
  4513. gtp->DiscoverSyntheticTargets(cache, config);
  4514. lg->AddGeneratorTarget(std::move(gtp));
  4515. } else {
  4516. synthDep = cached->second;
  4517. }
  4518. SyntheticDeps[gt].push_back(synthDep);
  4519. }
  4520. }
  4521. return true;
  4522. }
  4523. bool cmGeneratorTarget::HasPackageReferences() const
  4524. {
  4525. return this->IsInBuildSystem() &&
  4526. !this->GetProperty("VS_PACKAGE_REFERENCES")->empty();
  4527. }
  4528. std::vector<std::string> cmGeneratorTarget::GetPackageReferences() const
  4529. {
  4530. cmList packageReferences;
  4531. if (this->IsInBuildSystem()) {
  4532. if (cmValue vsPackageReferences =
  4533. this->GetProperty("VS_PACKAGE_REFERENCES")) {
  4534. packageReferences.assign(*vsPackageReferences);
  4535. }
  4536. }
  4537. return std::move(packageReferences.data());
  4538. }
  4539. std::string cmGeneratorTarget::GetPDBDirectory(const std::string& config) const
  4540. {
  4541. if (OutputInfo const* info = this->GetOutputInfo(config)) {
  4542. // Return the directory in which the target will be built.
  4543. return info->PdbDir;
  4544. }
  4545. return "";
  4546. }
  4547. bool cmGeneratorTarget::HasImplibGNUtoMS(std::string const& config) const
  4548. {
  4549. return this->HasImportLibrary(config) && this->GetPropertyAsBool("GNUtoMS");
  4550. }
  4551. bool cmGeneratorTarget::GetImplibGNUtoMS(std::string const& config,
  4552. std::string const& gnuName,
  4553. std::string& out,
  4554. const char* newExt) const
  4555. {
  4556. if (this->HasImplibGNUtoMS(config) && gnuName.size() > 6 &&
  4557. gnuName.substr(gnuName.size() - 6) == ".dll.a") {
  4558. out = cmStrCat(cm::string_view(gnuName).substr(0, gnuName.size() - 6),
  4559. newExt ? newExt : ".lib");
  4560. return true;
  4561. }
  4562. return false;
  4563. }
  4564. bool cmGeneratorTarget::HasContextDependentSources() const
  4565. {
  4566. return this->SourcesAreContextDependent == Tribool::True;
  4567. }
  4568. bool cmGeneratorTarget::IsExecutableWithExports() const
  4569. {
  4570. return this->Target->IsExecutableWithExports();
  4571. }
  4572. bool cmGeneratorTarget::IsSharedLibraryWithExports() const
  4573. {
  4574. return this->Target->IsSharedLibraryWithExports();
  4575. }
  4576. bool cmGeneratorTarget::HasImportLibrary(std::string const& config) const
  4577. {
  4578. bool generate_Stubs = true;
  4579. if (this->GetGlobalGenerator()->IsXcode()) {
  4580. // take care of CMAKE_XCODE_ATTRIBUTE_GENERATE_TEXT_BASED_STUBS variable
  4581. // as well as XCODE_ATTRIBUTE_GENERATE_TEXT_BASED_STUBS property
  4582. if (cmValue propGenStubs =
  4583. this->GetProperty("XCODE_ATTRIBUTE_GENERATE_TEXT_BASED_STUBS")) {
  4584. generate_Stubs = propGenStubs == "YES";
  4585. } else if (cmValue varGenStubs = this->Makefile->GetDefinition(
  4586. "CMAKE_XCODE_ATTRIBUTE_GENERATE_TEXT_BASED_STUBS")) {
  4587. generate_Stubs = varGenStubs == "YES";
  4588. }
  4589. }
  4590. return (this->IsDLLPlatform() &&
  4591. (this->GetType() == cmStateEnums::SHARED_LIBRARY ||
  4592. this->IsExecutableWithExports()) &&
  4593. // Assemblies which have only managed code do not have
  4594. // import libraries.
  4595. this->GetManagedType(config) != ManagedType::Managed) ||
  4596. (this->IsAIX() && this->IsExecutableWithExports()) ||
  4597. (this->Makefile->PlatformSupportsAppleTextStubs() &&
  4598. this->IsSharedLibraryWithExports() && generate_Stubs);
  4599. }
  4600. bool cmGeneratorTarget::NeedImportLibraryName(std::string const& config) const
  4601. {
  4602. return this->HasImportLibrary(config) ||
  4603. // On DLL platforms we always generate the import library name
  4604. // just in case the sources have export markup.
  4605. (this->IsDLLPlatform() &&
  4606. (this->GetType() == cmStateEnums::EXECUTABLE ||
  4607. this->GetType() == cmStateEnums::MODULE_LIBRARY));
  4608. }
  4609. std::string cmGeneratorTarget::GetSupportDirectory() const
  4610. {
  4611. std::string dir = cmStrCat(this->LocalGenerator->GetCurrentBinaryDirectory(),
  4612. "/CMakeFiles/", this->GetName());
  4613. #if defined(__VMS)
  4614. dir += "_dir";
  4615. #else
  4616. dir += ".dir";
  4617. #endif
  4618. return dir;
  4619. }
  4620. bool cmGeneratorTarget::IsLinkable() const
  4621. {
  4622. return (this->GetType() == cmStateEnums::STATIC_LIBRARY ||
  4623. this->GetType() == cmStateEnums::SHARED_LIBRARY ||
  4624. this->GetType() == cmStateEnums::MODULE_LIBRARY ||
  4625. this->GetType() == cmStateEnums::UNKNOWN_LIBRARY ||
  4626. this->GetType() == cmStateEnums::OBJECT_LIBRARY ||
  4627. this->GetType() == cmStateEnums::INTERFACE_LIBRARY ||
  4628. this->IsExecutableWithExports());
  4629. }
  4630. bool cmGeneratorTarget::HasLinkDependencyFile(std::string const& config) const
  4631. {
  4632. if (this->GetType() != cmStateEnums::EXECUTABLE &&
  4633. this->GetType() != cmStateEnums::SHARED_LIBRARY &&
  4634. this->GetType() != cmStateEnums::MODULE_LIBRARY) {
  4635. return false;
  4636. }
  4637. if (this->Target->GetProperty("LINK_DEPENDS_NO_SHARED").IsOn()) {
  4638. // Do not use the linker dependency file because it includes shared
  4639. // libraries as well
  4640. return false;
  4641. }
  4642. const std::string depsUseLinker{ "CMAKE_LINK_DEPENDS_USE_LINKER" };
  4643. auto linkLanguage = this->GetLinkerLanguage(config);
  4644. const std::string langDepsUseLinker{ cmStrCat("CMAKE_", linkLanguage,
  4645. "_LINK_DEPENDS_USE_LINKER") };
  4646. return (!this->Makefile->IsDefinitionSet(depsUseLinker) ||
  4647. this->Makefile->IsOn(depsUseLinker)) &&
  4648. this->Makefile->IsOn(langDepsUseLinker);
  4649. }
  4650. bool cmGeneratorTarget::IsFrameworkOnApple() const
  4651. {
  4652. return this->Target->IsFrameworkOnApple();
  4653. }
  4654. bool cmGeneratorTarget::IsArchivedAIXSharedLibrary() const
  4655. {
  4656. return this->Target->IsArchivedAIXSharedLibrary();
  4657. }
  4658. bool cmGeneratorTarget::IsImportedFrameworkFolderOnApple(
  4659. const std::string& config) const
  4660. {
  4661. if (this->IsApple() && this->IsImported() &&
  4662. (this->GetType() == cmStateEnums::STATIC_LIBRARY ||
  4663. this->GetType() == cmStateEnums::SHARED_LIBRARY ||
  4664. this->GetType() == cmStateEnums::UNKNOWN_LIBRARY)) {
  4665. std::string cfg = config;
  4666. if (cfg.empty() && this->GetGlobalGenerator()->IsXcode()) {
  4667. // FIXME(#25515): Remove the need for this workaround.
  4668. // The Xcode generator queries include directories without any
  4669. // specific configuration. Pick one in case this target does
  4670. // not set either IMPORTED_LOCATION or IMPORTED_CONFIGURATIONS.
  4671. cfg =
  4672. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig)[0];
  4673. }
  4674. return cmSystemTools::IsPathToFramework(this->GetLocation(cfg));
  4675. }
  4676. return false;
  4677. }
  4678. bool cmGeneratorTarget::IsAppBundleOnApple() const
  4679. {
  4680. return this->Target->IsAppBundleOnApple();
  4681. }
  4682. bool cmGeneratorTarget::IsXCTestOnApple() const
  4683. {
  4684. return (this->IsCFBundleOnApple() && this->GetPropertyAsBool("XCTEST"));
  4685. }
  4686. bool cmGeneratorTarget::IsCFBundleOnApple() const
  4687. {
  4688. return (this->GetType() == cmStateEnums::MODULE_LIBRARY && this->IsApple() &&
  4689. this->GetPropertyAsBool("BUNDLE"));
  4690. }
  4691. cmGeneratorTarget::ManagedType cmGeneratorTarget::CheckManagedType(
  4692. std::string const& propval) const
  4693. {
  4694. // The type of the managed assembly (mixed unmanaged C++ and C++/CLI,
  4695. // or only C++/CLI) does only depend on whether the property is an empty
  4696. // string or contains any value at all. In Visual Studio generators
  4697. // this propval is prepended with /clr[:] which results in:
  4698. //
  4699. // 1. propval does not exist: no /clr flag, unmanaged target, has import
  4700. // lib
  4701. // 2. empty propval: add /clr as flag, mixed unmanaged/managed
  4702. // target, has import lib
  4703. // 3. netcore propval: add /clr:netcore as flag, mixed
  4704. // unmanaged/managed target, has import lib.
  4705. // 4. any value (safe,pure): add /clr:[propval] as flag, target with
  4706. // managed code only, no import lib
  4707. if (propval.empty() || propval == "netcore") {
  4708. return ManagedType::Mixed;
  4709. }
  4710. return ManagedType::Managed;
  4711. }
  4712. cmGeneratorTarget::ManagedType cmGeneratorTarget::GetManagedType(
  4713. const std::string& config) const
  4714. {
  4715. // Only libraries and executables can be managed targets.
  4716. if (this->GetType() > cmStateEnums::SHARED_LIBRARY) {
  4717. return ManagedType::Undefined;
  4718. }
  4719. if (this->GetType() == cmStateEnums::STATIC_LIBRARY) {
  4720. return ManagedType::Native;
  4721. }
  4722. // Check imported target.
  4723. if (this->IsImported()) {
  4724. if (cmGeneratorTarget::ImportInfo const* info =
  4725. this->GetImportInfo(config)) {
  4726. return info->Managed;
  4727. }
  4728. return ManagedType::Undefined;
  4729. }
  4730. // Check for explicitly set clr target property.
  4731. if (cmValue clr = this->GetProperty("COMMON_LANGUAGE_RUNTIME")) {
  4732. return this->CheckManagedType(*clr);
  4733. }
  4734. // C# targets are always managed. This language specific check
  4735. // is added to avoid that the COMMON_LANGUAGE_RUNTIME target property
  4736. // has to be set manually for C# targets.
  4737. return this->IsCSharpOnly() ? ManagedType::Managed : ManagedType::Native;
  4738. }
  4739. bool cmGeneratorTarget::AddHeaderSetVerification()
  4740. {
  4741. if (!this->GetPropertyAsBool("VERIFY_INTERFACE_HEADER_SETS")) {
  4742. return true;
  4743. }
  4744. if (this->GetType() != cmStateEnums::STATIC_LIBRARY &&
  4745. this->GetType() != cmStateEnums::SHARED_LIBRARY &&
  4746. this->GetType() != cmStateEnums::UNKNOWN_LIBRARY &&
  4747. this->GetType() != cmStateEnums::OBJECT_LIBRARY &&
  4748. this->GetType() != cmStateEnums::INTERFACE_LIBRARY &&
  4749. !this->IsExecutableWithExports()) {
  4750. return true;
  4751. }
  4752. auto verifyValue = this->GetProperty("INTERFACE_HEADER_SETS_TO_VERIFY");
  4753. const bool all = verifyValue.IsEmpty();
  4754. std::set<std::string> verifySet;
  4755. if (!all) {
  4756. cmList verifyList{ verifyValue };
  4757. verifySet.insert(verifyList.begin(), verifyList.end());
  4758. }
  4759. cmTarget* verifyTarget = nullptr;
  4760. cmTarget* allVerifyTarget =
  4761. this->GlobalGenerator->GetMakefiles().front()->FindTargetToUse(
  4762. "all_verify_interface_header_sets", true);
  4763. auto interfaceFileSetEntries = this->Target->GetInterfaceHeaderSetsEntries();
  4764. std::set<cmFileSet*> fileSets;
  4765. for (auto const& entry : interfaceFileSetEntries) {
  4766. for (auto const& name : cmList{ entry.Value }) {
  4767. if (all || verifySet.count(name)) {
  4768. fileSets.insert(this->Target->GetFileSet(name));
  4769. verifySet.erase(name);
  4770. }
  4771. }
  4772. }
  4773. if (!verifySet.empty()) {
  4774. this->Makefile->IssueMessage(
  4775. MessageType::FATAL_ERROR,
  4776. cmStrCat("Property INTERFACE_HEADER_SETS_TO_VERIFY of target \"",
  4777. this->GetName(),
  4778. "\" contained the following header sets that are nonexistent "
  4779. "or not INTERFACE:\n ",
  4780. cmJoin(verifySet, "\n ")));
  4781. return false;
  4782. }
  4783. cm::optional<std::set<std::string>> languages;
  4784. for (auto* fileSet : fileSets) {
  4785. auto dirCges = fileSet->CompileDirectoryEntries();
  4786. auto fileCges = fileSet->CompileFileEntries();
  4787. static auto const contextSensitive =
  4788. [](const std::unique_ptr<cmCompiledGeneratorExpression>& cge) {
  4789. return cge->GetHadContextSensitiveCondition();
  4790. };
  4791. bool dirCgesContextSensitive = false;
  4792. bool fileCgesContextSensitive = false;
  4793. std::vector<std::string> dirs;
  4794. std::map<std::string, std::vector<std::string>> filesPerDir;
  4795. bool first = true;
  4796. for (auto const& config : this->Makefile->GetGeneratorConfigs(
  4797. cmMakefile::GeneratorConfigQuery::IncludeEmptyConfig)) {
  4798. if (first || dirCgesContextSensitive) {
  4799. dirs = fileSet->EvaluateDirectoryEntries(dirCges, this->LocalGenerator,
  4800. config, this);
  4801. dirCgesContextSensitive =
  4802. std::any_of(dirCges.begin(), dirCges.end(), contextSensitive);
  4803. }
  4804. if (first || fileCgesContextSensitive) {
  4805. filesPerDir.clear();
  4806. for (auto const& fileCge : fileCges) {
  4807. fileSet->EvaluateFileEntry(dirs, filesPerDir, fileCge,
  4808. this->LocalGenerator, config, this);
  4809. if (fileCge->GetHadContextSensitiveCondition()) {
  4810. fileCgesContextSensitive = true;
  4811. }
  4812. }
  4813. }
  4814. for (auto const& files : filesPerDir) {
  4815. for (auto const& file : files.second) {
  4816. std::string filename = this->GenerateHeaderSetVerificationFile(
  4817. *this->Makefile->GetOrCreateSource(file), files.first, languages);
  4818. if (filename.empty()) {
  4819. continue;
  4820. }
  4821. if (!verifyTarget) {
  4822. {
  4823. cmMakefile::PolicyPushPop polScope(this->Makefile);
  4824. this->Makefile->SetPolicy(cmPolicies::CMP0119, cmPolicies::NEW);
  4825. verifyTarget = this->Makefile->AddLibrary(
  4826. cmStrCat(this->GetName(), "_verify_interface_header_sets"),
  4827. cmStateEnums::OBJECT_LIBRARY, {}, true);
  4828. }
  4829. verifyTarget->AddLinkLibrary(
  4830. *this->Makefile, this->GetName(),
  4831. cmTargetLinkLibraryType::GENERAL_LibraryType);
  4832. verifyTarget->SetProperty("AUTOMOC", "OFF");
  4833. verifyTarget->SetProperty("AUTORCC", "OFF");
  4834. verifyTarget->SetProperty("AUTOUIC", "OFF");
  4835. verifyTarget->SetProperty("DISABLE_PRECOMPILE_HEADERS", "ON");
  4836. verifyTarget->SetProperty("UNITY_BUILD", "OFF");
  4837. verifyTarget->SetProperty("CXX_SCAN_FOR_MODULES", "OFF");
  4838. cm::optional<std::map<std::string, cmValue>>
  4839. perConfigCompileDefinitions;
  4840. verifyTarget->FinalizeTargetConfiguration(
  4841. this->Makefile->GetCompileDefinitionsEntries(),
  4842. perConfigCompileDefinitions);
  4843. if (!allVerifyTarget) {
  4844. allVerifyTarget = this->GlobalGenerator->GetMakefiles()
  4845. .front()
  4846. ->AddNewUtilityTarget(
  4847. "all_verify_interface_header_sets", true);
  4848. }
  4849. allVerifyTarget->AddUtility(verifyTarget->GetName(), false);
  4850. }
  4851. if (fileCgesContextSensitive) {
  4852. filename = cmStrCat("$<$<CONFIG:", config, ">:", filename, ">");
  4853. }
  4854. verifyTarget->AddSource(filename);
  4855. }
  4856. }
  4857. if (!dirCgesContextSensitive && !fileCgesContextSensitive) {
  4858. break;
  4859. }
  4860. first = false;
  4861. }
  4862. }
  4863. if (verifyTarget) {
  4864. this->LocalGenerator->AddGeneratorTarget(
  4865. cm::make_unique<cmGeneratorTarget>(verifyTarget, this->LocalGenerator));
  4866. }
  4867. return true;
  4868. }
  4869. std::string cmGeneratorTarget::GenerateHeaderSetVerificationFile(
  4870. cmSourceFile& source, const std::string& dir,
  4871. cm::optional<std::set<std::string>>& languages) const
  4872. {
  4873. std::string extension;
  4874. std::string language = source.GetOrDetermineLanguage();
  4875. if (source.GetPropertyAsBool("SKIP_LINTING")) {
  4876. return std::string{};
  4877. }
  4878. if (language.empty()) {
  4879. if (!languages) {
  4880. languages.emplace();
  4881. for (auto const& tgtSource : this->GetAllConfigSources()) {
  4882. auto const& tgtSourceLanguage =
  4883. tgtSource.Source->GetOrDetermineLanguage();
  4884. if (tgtSourceLanguage == "CXX") {
  4885. languages->insert("CXX");
  4886. break; // C++ overrides everything else, so we don't need to keep
  4887. // checking.
  4888. }
  4889. if (tgtSourceLanguage == "C") {
  4890. languages->insert("C");
  4891. }
  4892. }
  4893. if (languages->empty()) {
  4894. std::vector<std::string> languagesVector;
  4895. this->GlobalGenerator->GetEnabledLanguages(languagesVector);
  4896. languages->insert(languagesVector.begin(), languagesVector.end());
  4897. }
  4898. }
  4899. if (languages->count("CXX")) {
  4900. language = "CXX";
  4901. } else if (languages->count("C")) {
  4902. language = "C";
  4903. }
  4904. }
  4905. if (language == "C") {
  4906. extension = ".c";
  4907. } else if (language == "CXX") {
  4908. extension = ".cxx";
  4909. } else {
  4910. return "";
  4911. }
  4912. std::string headerFilename = dir;
  4913. if (!headerFilename.empty()) {
  4914. headerFilename += '/';
  4915. }
  4916. headerFilename += source.GetLocation().GetName();
  4917. auto filename = cmStrCat(
  4918. this->LocalGenerator->GetCurrentBinaryDirectory(), '/', this->GetName(),
  4919. "_verify_interface_header_sets/", headerFilename, extension);
  4920. auto* verificationSource = this->Makefile->GetOrCreateSource(filename);
  4921. verificationSource->SetProperty("LANGUAGE", language);
  4922. cmSystemTools::MakeDirectory(cmSystemTools::GetFilenamePath(filename));
  4923. cmGeneratedFileStream fout(filename);
  4924. fout.SetCopyIfDifferent(true);
  4925. // The IWYU "associated" pragma tells include-what-you-use to
  4926. // consider the headerFile as part of the entire language
  4927. // unit within include-what-you-use and as a result allows
  4928. // one to get IWYU advice for headers.
  4929. // Also suppress clang-tidy include checks in generated code.
  4930. fout
  4931. << "/* NOLINTNEXTLINE(misc-header-include-cycle,misc-include-cleaner) */\n"
  4932. << "#include <" << headerFilename << "> /* IWYU pragma: associated */\n";
  4933. fout.close();
  4934. return filename;
  4935. }
  4936. std::string cmGeneratorTarget::GetImportedXcFrameworkPath(
  4937. const std::string& config) const
  4938. {
  4939. if (!(this->IsApple() && this->IsImported() &&
  4940. (this->GetType() == cmStateEnums::SHARED_LIBRARY ||
  4941. this->GetType() == cmStateEnums::STATIC_LIBRARY ||
  4942. this->GetType() == cmStateEnums::UNKNOWN_LIBRARY))) {
  4943. return {};
  4944. }
  4945. std::string desiredConfig = config;
  4946. if (config.empty()) {
  4947. desiredConfig = "NOCONFIG";
  4948. }
  4949. std::string result;
  4950. cmValue loc = nullptr;
  4951. cmValue imp = nullptr;
  4952. std::string suffix;
  4953. if (this->Target->GetMappedConfig(desiredConfig, loc, imp, suffix)) {
  4954. if (loc) {
  4955. result = *loc;
  4956. } else {
  4957. std::string impProp = cmStrCat("IMPORTED_LOCATION", suffix);
  4958. if (cmValue configLocation = this->GetProperty(impProp)) {
  4959. result = *configLocation;
  4960. } else if (cmValue location = this->GetProperty("IMPORTED_LOCATION")) {
  4961. result = *location;
  4962. }
  4963. }
  4964. if (cmSystemTools::IsPathToXcFramework(result)) {
  4965. return result;
  4966. }
  4967. }
  4968. return {};
  4969. }
  4970. bool cmGeneratorTarget::HaveFortranSources(std::string const& config) const
  4971. {
  4972. auto sources = this->GetSourceFiles(config);
  4973. bool const have_direct = std::any_of(
  4974. sources.begin(), sources.end(), [](BT<cmSourceFile*> const& sf) -> bool {
  4975. return sf.Value->GetLanguage() == "Fortran"_s;
  4976. });
  4977. bool have_via_target_objects = false;
  4978. if (!have_direct) {
  4979. auto const sourceObjectLibraries = this->GetSourceObjectLibraries(config);
  4980. have_via_target_objects =
  4981. std::any_of(sourceObjectLibraries.begin(), sourceObjectLibraries.end(),
  4982. [&config](cmGeneratorTarget const* tgt) -> bool {
  4983. return tgt->HaveFortranSources(config);
  4984. });
  4985. }
  4986. return have_direct || have_via_target_objects;
  4987. }
  4988. bool cmGeneratorTarget::HaveFortranSources() const
  4989. {
  4990. auto sources = this->GetAllConfigSources();
  4991. bool const have_direct = std::any_of(
  4992. sources.begin(), sources.end(), [](AllConfigSource const& sf) -> bool {
  4993. return sf.Source->GetLanguage() == "Fortran"_s;
  4994. });
  4995. bool have_via_target_objects = false;
  4996. if (!have_direct) {
  4997. std::vector<std::string> configs =
  4998. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  4999. for (auto const& config : configs) {
  5000. auto const sourceObjectLibraries =
  5001. this->GetSourceObjectLibraries(config);
  5002. have_via_target_objects =
  5003. std::any_of(sourceObjectLibraries.begin(), sourceObjectLibraries.end(),
  5004. [&config](cmGeneratorTarget const* tgt) -> bool {
  5005. return tgt->HaveFortranSources(config);
  5006. });
  5007. if (have_via_target_objects) {
  5008. break;
  5009. }
  5010. }
  5011. }
  5012. return have_direct || have_via_target_objects;
  5013. }
  5014. bool cmGeneratorTarget::HaveCxx20ModuleSources(std::string* errorMessage) const
  5015. {
  5016. auto const& fs_names = this->Target->GetAllFileSetNames();
  5017. return std::any_of(
  5018. fs_names.begin(), fs_names.end(),
  5019. [this, errorMessage](std::string const& name) -> bool {
  5020. auto const* file_set = this->Target->GetFileSet(name);
  5021. if (!file_set) {
  5022. auto message = cmStrCat("Target \"", this->Target->GetName(),
  5023. "\" is tracked to have file set \"", name,
  5024. "\", but it was not found.");
  5025. if (errorMessage) {
  5026. *errorMessage = std::move(message);
  5027. } else {
  5028. this->Makefile->IssueMessage(MessageType::INTERNAL_ERROR, message);
  5029. }
  5030. return false;
  5031. }
  5032. auto const& fs_type = file_set->GetType();
  5033. return fs_type == "CXX_MODULES"_s;
  5034. });
  5035. }
  5036. cmGeneratorTarget::Cxx20SupportLevel cmGeneratorTarget::HaveCxxModuleSupport(
  5037. std::string const& config) const
  5038. {
  5039. auto const* state = this->Makefile->GetState();
  5040. if (!state->GetLanguageEnabled("CXX")) {
  5041. return Cxx20SupportLevel::MissingCxx;
  5042. }
  5043. cmValue standardDefault =
  5044. this->Makefile->GetDefinition("CMAKE_CXX_STANDARD_DEFAULT");
  5045. if (!standardDefault || standardDefault->empty()) {
  5046. // We do not know any meaningful C++ standard levels for this compiler.
  5047. return Cxx20SupportLevel::NoCxx20;
  5048. }
  5049. cmStandardLevelResolver standardResolver(this->Makefile);
  5050. cmStandardLevel const cxxStd20 =
  5051. *standardResolver.LanguageStandardLevel("CXX", "20");
  5052. cm::optional<cmStandardLevel> explicitLevel =
  5053. this->GetExplicitStandardLevel("CXX", config);
  5054. if (!explicitLevel || *explicitLevel < cxxStd20) {
  5055. return Cxx20SupportLevel::NoCxx20;
  5056. }
  5057. cmValue scandepRule =
  5058. this->Makefile->GetDefinition("CMAKE_CXX_SCANDEP_SOURCE");
  5059. if (!scandepRule) {
  5060. return Cxx20SupportLevel::MissingRule;
  5061. }
  5062. return Cxx20SupportLevel::Supported;
  5063. }
  5064. void cmGeneratorTarget::CheckCxxModuleStatus(std::string const& config) const
  5065. {
  5066. bool haveScannableSources = false;
  5067. // Check for `CXX_MODULE*` file sets and a lack of support.
  5068. if (this->HaveCxx20ModuleSources()) {
  5069. haveScannableSources = true;
  5070. }
  5071. if (!haveScannableSources) {
  5072. // Check to see if there are regular sources that have requested scanning.
  5073. auto sources = this->GetSourceFiles(config);
  5074. for (auto const& source : sources) {
  5075. auto const* sf = source.Value;
  5076. auto const& lang = sf->GetLanguage();
  5077. if (lang != "CXX"_s) {
  5078. continue;
  5079. }
  5080. // Ignore sources which do not need dyndep.
  5081. if (this->NeedDyndepForSource(lang, config, sf)) {
  5082. haveScannableSources = true;
  5083. }
  5084. }
  5085. }
  5086. // If there isn't anything scannable, ignore it.
  5087. if (!haveScannableSources) {
  5088. return;
  5089. }
  5090. // If the generator doesn't support modules at all, error that we have
  5091. // sources that require the support.
  5092. if (!this->GetGlobalGenerator()->CheckCxxModuleSupport(
  5093. cmGlobalGenerator::CxxModuleSupportQuery::Expected)) {
  5094. this->Makefile->IssueMessage(
  5095. MessageType::FATAL_ERROR,
  5096. cmStrCat("The target named \"", this->GetName(),
  5097. "\" has C++ sources that may use modules, but modules are not "
  5098. "supported by this generator:\n ",
  5099. this->GetGlobalGenerator()->GetName(), '\n',
  5100. "Modules are supported only by Ninja, Ninja Multi-Config, "
  5101. "and Visual Studio generators for VS 17.4 and newer. "
  5102. "See the cmake-cxxmodules(7) manual for details. "
  5103. "Use the CMAKE_CXX_SCAN_FOR_MODULES variable to enable or "
  5104. "disable scanning."));
  5105. return;
  5106. }
  5107. switch (this->HaveCxxModuleSupport(config)) {
  5108. case cmGeneratorTarget::Cxx20SupportLevel::MissingCxx:
  5109. this->Makefile->IssueMessage(
  5110. MessageType::FATAL_ERROR,
  5111. cmStrCat("The target named \"", this->GetName(),
  5112. "\" has C++ sources that use modules, but the \"CXX\" "
  5113. "language has not been enabled."));
  5114. break;
  5115. case cmGeneratorTarget::Cxx20SupportLevel::NoCxx20: {
  5116. cmStandardLevelResolver standardResolver(this->Makefile);
  5117. auto effStandard =
  5118. standardResolver.GetEffectiveStandard(this, "CXX", config);
  5119. if (effStandard.empty()) {
  5120. effStandard = "; no C++ standard found";
  5121. } else {
  5122. effStandard = cmStrCat("; found \"cxx_std_", effStandard, '"');
  5123. }
  5124. this->Makefile->IssueMessage(
  5125. MessageType::FATAL_ERROR,
  5126. cmStrCat(
  5127. "The target named \"", this->GetName(),
  5128. "\" has C++ sources that use modules, but does not include "
  5129. "\"cxx_std_20\" (or newer) among its `target_compile_features`",
  5130. effStandard, '.'));
  5131. } break;
  5132. case cmGeneratorTarget::Cxx20SupportLevel::MissingRule: {
  5133. this->Makefile->IssueMessage(
  5134. MessageType::FATAL_ERROR,
  5135. cmStrCat("The target named \"", this->GetName(),
  5136. "\" has C++ sources that may use modules, but the compiler "
  5137. "does not provide a way to discover the import graph "
  5138. "dependencies. See the cmake-cxxmodules(7) manual for "
  5139. "details. Use the CMAKE_CXX_SCAN_FOR_MODULES variable to "
  5140. "enable or disable scanning."));
  5141. } break;
  5142. case cmGeneratorTarget::Cxx20SupportLevel::Supported:
  5143. // All is well.
  5144. break;
  5145. }
  5146. }
  5147. bool cmGeneratorTarget::NeedCxxModuleSupport(std::string const& lang,
  5148. std::string const& config) const
  5149. {
  5150. if (lang != "CXX"_s) {
  5151. return false;
  5152. }
  5153. return this->HaveCxxModuleSupport(config) == Cxx20SupportLevel::Supported &&
  5154. this->GetGlobalGenerator()->CheckCxxModuleSupport(
  5155. cmGlobalGenerator::CxxModuleSupportQuery::Inspect);
  5156. }
  5157. bool cmGeneratorTarget::NeedDyndep(std::string const& lang,
  5158. std::string const& config) const
  5159. {
  5160. return lang == "Fortran"_s || this->NeedCxxModuleSupport(lang, config);
  5161. }
  5162. cmFileSet const* cmGeneratorTarget::GetFileSetForSource(
  5163. std::string const& config, cmSourceFile const* sf) const
  5164. {
  5165. this->BuildFileSetInfoCache(config);
  5166. auto const& path = sf->GetFullPath();
  5167. auto const& per_config = this->Configs[config];
  5168. auto const fsit = per_config.FileSetCache.find(path);
  5169. if (fsit == per_config.FileSetCache.end()) {
  5170. return nullptr;
  5171. }
  5172. return fsit->second;
  5173. }
  5174. bool cmGeneratorTarget::NeedDyndepForSource(std::string const& lang,
  5175. std::string const& config,
  5176. cmSourceFile const* sf) const
  5177. {
  5178. // Fortran always needs to be scanned.
  5179. if (lang == "Fortran"_s) {
  5180. return true;
  5181. }
  5182. // Only C++ code needs scanned otherwise.
  5183. if (lang != "CXX"_s) {
  5184. return false;
  5185. }
  5186. // Any file in `CXX_MODULES` file sets need scanned (it being `CXX` is
  5187. // enforced elsewhere).
  5188. auto const* fs = this->GetFileSetForSource(config, sf);
  5189. if (fs && fs->GetType() == "CXX_MODULES"_s) {
  5190. return true;
  5191. }
  5192. auto targetDyndep = this->NeedCxxDyndep(config);
  5193. if (targetDyndep == CxxModuleSupport::Unavailable) {
  5194. return false;
  5195. }
  5196. auto const sfProp = sf->GetProperty("CXX_SCAN_FOR_MODULES");
  5197. if (sfProp.IsSet()) {
  5198. return sfProp.IsOn();
  5199. }
  5200. return targetDyndep == CxxModuleSupport::Enabled;
  5201. }
  5202. cmGeneratorTarget::CxxModuleSupport cmGeneratorTarget::NeedCxxDyndep(
  5203. std::string const& config) const
  5204. {
  5205. bool haveRule = false;
  5206. switch (this->HaveCxxModuleSupport(config)) {
  5207. case Cxx20SupportLevel::MissingCxx:
  5208. case Cxx20SupportLevel::NoCxx20:
  5209. return CxxModuleSupport::Unavailable;
  5210. case Cxx20SupportLevel::MissingRule:
  5211. break;
  5212. case Cxx20SupportLevel::Supported:
  5213. haveRule = true;
  5214. break;
  5215. }
  5216. bool haveGeneratorSupport =
  5217. this->GetGlobalGenerator()->CheckCxxModuleSupport(
  5218. cmGlobalGenerator::CxxModuleSupportQuery::Inspect);
  5219. auto const tgtProp = this->GetProperty("CXX_SCAN_FOR_MODULES");
  5220. if (tgtProp.IsSet()) {
  5221. return tgtProp.IsOn() ? CxxModuleSupport::Enabled
  5222. : CxxModuleSupport::Disabled;
  5223. }
  5224. CxxModuleSupport policyAnswer = CxxModuleSupport::Unavailable;
  5225. switch (this->GetPolicyStatusCMP0155()) {
  5226. case cmPolicies::WARN:
  5227. case cmPolicies::OLD:
  5228. // The OLD behavior is to not scan the source.
  5229. policyAnswer = CxxModuleSupport::Disabled;
  5230. break;
  5231. case cmPolicies::REQUIRED_ALWAYS:
  5232. case cmPolicies::REQUIRED_IF_USED:
  5233. case cmPolicies::NEW:
  5234. // The NEW behavior is to scan the source if the compiler supports
  5235. // scanning and the generator supports it.
  5236. if (haveRule && haveGeneratorSupport) {
  5237. policyAnswer = CxxModuleSupport::Enabled;
  5238. } else {
  5239. policyAnswer = CxxModuleSupport::Disabled;
  5240. }
  5241. break;
  5242. }
  5243. return policyAnswer;
  5244. }
  5245. std::string cmGeneratorTarget::BuildDatabasePath(
  5246. std::string const& lang, std::string const& config) const
  5247. {
  5248. // Check to see if the target wants it.
  5249. if (!this->GetPropertyAsBool("EXPORT_BUILD_DATABASE")) {
  5250. return {};
  5251. }
  5252. if (!cmExperimental::HasSupportEnabled(
  5253. *this->Makefile, cmExperimental::Feature::ExportBuildDatabase)) {
  5254. return {};
  5255. }
  5256. // Check to see if the generator supports it.
  5257. if (!this->GetGlobalGenerator()->SupportsBuildDatabase()) {
  5258. return {};
  5259. }
  5260. if (this->GetGlobalGenerator()->IsMultiConfig()) {
  5261. return cmStrCat(this->GetSupportDirectory(), '/', config, '/', lang,
  5262. "_build_database.json");
  5263. }
  5264. return cmStrCat(this->GetSupportDirectory(), '/', lang,
  5265. "_build_database.json");
  5266. }
  5267. void cmGeneratorTarget::BuildFileSetInfoCache(std::string const& config) const
  5268. {
  5269. auto& per_config = this->Configs[config];
  5270. if (per_config.BuiltFileSetCache) {
  5271. return;
  5272. }
  5273. auto const* tgt = this->Target;
  5274. for (auto const& name : tgt->GetAllFileSetNames()) {
  5275. auto const* file_set = tgt->GetFileSet(name);
  5276. if (!file_set) {
  5277. tgt->GetMakefile()->IssueMessage(
  5278. MessageType::INTERNAL_ERROR,
  5279. cmStrCat("Target \"", tgt->GetName(),
  5280. "\" is tracked to have file set \"", name,
  5281. "\", but it was not found."));
  5282. continue;
  5283. }
  5284. auto fileEntries = file_set->CompileFileEntries();
  5285. auto directoryEntries = file_set->CompileDirectoryEntries();
  5286. auto directories = file_set->EvaluateDirectoryEntries(
  5287. directoryEntries, this->LocalGenerator, config, this);
  5288. std::map<std::string, std::vector<std::string>> files;
  5289. for (auto const& entry : fileEntries) {
  5290. file_set->EvaluateFileEntry(directories, files, entry,
  5291. this->LocalGenerator, config, this);
  5292. }
  5293. for (auto const& it : files) {
  5294. for (auto const& filename : it.second) {
  5295. auto collapsedFile = cmSystemTools::CollapseFullPath(filename);
  5296. per_config.FileSetCache[collapsedFile] = file_set;
  5297. }
  5298. }
  5299. }
  5300. per_config.BuiltFileSetCache = true;
  5301. }
  5302. std::string cmGeneratorTarget::GetSwiftModuleName() const
  5303. {
  5304. return this->GetPropertyOrDefault("Swift_MODULE_NAME", this->GetName());
  5305. }
  5306. std::string cmGeneratorTarget::GetSwiftModuleFileName() const
  5307. {
  5308. return this->GetPropertyOrDefault(
  5309. "Swift_MODULE", this->GetSwiftModuleName() + ".swiftmodule");
  5310. }
  5311. std::string cmGeneratorTarget::GetSwiftModuleDirectory(
  5312. std::string const& config) const
  5313. {
  5314. std::string moduleDirectory =
  5315. this->GetPropertyOrDefault("Swift_MODULE_DIRECTORY", "");
  5316. if (moduleDirectory.empty()) {
  5317. moduleDirectory = this->LocalGenerator->GetCurrentBinaryDirectory();
  5318. this->LocalGenerator->GetGlobalGenerator()->AppendDirectoryForConfig(
  5319. "/", config, "", moduleDirectory);
  5320. }
  5321. return moduleDirectory;
  5322. }
  5323. std::string cmGeneratorTarget::GetSwiftModulePath(
  5324. std::string const& config) const
  5325. {
  5326. return this->GetSwiftModuleDirectory(config) + "/" +
  5327. this->GetSwiftModuleFileName();
  5328. }
  5329. std::string cmGeneratorTarget::GetPropertyOrDefault(
  5330. std::string const& property, std::string defaultValue) const
  5331. {
  5332. if (cmValue name = this->GetProperty(property)) {
  5333. return *name;
  5334. }
  5335. return defaultValue;
  5336. }