cmGeneratorTarget.cxx 196 KB

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