cmGeneratorTarget.cxx 197 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057
  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. namespace {
  1807. bool IsSupportedClassifiedFlagsLanguage(std::string const& lang)
  1808. {
  1809. return lang == "CXX"_s;
  1810. }
  1811. bool CanUseCompilerLauncher(std::string const& lang)
  1812. {
  1813. // Also found in `cmCommonTargetGenerator::GetCompilerLauncher`.
  1814. return lang == "C"_s || lang == "CXX"_s || lang == "Fortran"_s ||
  1815. lang == "CUDA"_s || lang == "HIP"_s || lang == "ISPC"_s ||
  1816. lang == "OBJC"_s || lang == "OBJCXX"_s;
  1817. }
  1818. // FIXME: return a vector of `cm::string_view` instead to avoid lots of tiny
  1819. // allocations.
  1820. std::vector<std::string> SplitFlags(std::string const& flags)
  1821. {
  1822. std::vector<std::string> options;
  1823. #ifdef _WIN32
  1824. cmSystemTools::ParseWindowsCommandLine(flags.c_str(), options);
  1825. #else
  1826. cmSystemTools::ParseUnixCommandLine(flags.c_str(), options);
  1827. #endif
  1828. return options;
  1829. }
  1830. }
  1831. cmGeneratorTarget::ClassifiedFlags
  1832. cmGeneratorTarget::GetClassifiedFlagsForSource(cmSourceFile const* sf,
  1833. std::string const& config)
  1834. {
  1835. auto& sourceFlagsCache = this->Configs[config].SourceFlags;
  1836. auto cacheEntry = sourceFlagsCache.lower_bound(sf);
  1837. if (cacheEntry != sourceFlagsCache.end() && cacheEntry->first == sf) {
  1838. return cacheEntry->second;
  1839. }
  1840. ClassifiedFlags flags;
  1841. std::string const& lang = sf->GetLanguage();
  1842. if (!IsSupportedClassifiedFlagsLanguage(lang)) {
  1843. return flags;
  1844. }
  1845. auto* const lg = this->GetLocalGenerator();
  1846. auto const* const mf = this->Makefile;
  1847. // Compute the compiler launcher flags.
  1848. if (CanUseCompilerLauncher(lang)) {
  1849. // Compiler launchers are all execution flags and should not be relevant to
  1850. // the actual compilation.
  1851. FlagClassification cls = FlagClassification::ExecutionFlag;
  1852. FlagKind kind = FlagKind::NotAFlag;
  1853. std::string const clauncher_prop = cmStrCat(lang, "_COMPILER_LAUNCHER");
  1854. cmValue clauncher = this->GetProperty(clauncher_prop);
  1855. std::string const evaluatedClauncher = cmGeneratorExpression::Evaluate(
  1856. *clauncher, lg, config, this, nullptr, this, lang);
  1857. for (auto const& flag : SplitFlags(evaluatedClauncher)) {
  1858. flags.emplace_back(cls, kind, flag);
  1859. }
  1860. }
  1861. ClassifiedFlags define_flags;
  1862. ClassifiedFlags include_flags;
  1863. ClassifiedFlags compile_flags;
  1864. SourceVariables sfVars = this->GetSourceVariables(sf, config);
  1865. // Compute language flags.
  1866. {
  1867. FlagClassification cls = FlagClassification::BaselineFlag;
  1868. FlagKind kind = FlagKind::Compile;
  1869. std::string mfFlags;
  1870. // Explicitly add the explicit language flag before any other flag
  1871. // so user flags can override it.
  1872. this->AddExplicitLanguageFlags(mfFlags, *sf);
  1873. for (auto const& flag : SplitFlags(mfFlags)) {
  1874. flags.emplace_back(cls, kind, flag);
  1875. }
  1876. }
  1877. std::unordered_map<std::string, std::string> pchSources;
  1878. std::string filterArch;
  1879. {
  1880. std::vector<std::string> pchArchs = this->GetPchArchs(config, lang);
  1881. for (const std::string& arch : pchArchs) {
  1882. const std::string pchSource = this->GetPchSource(config, lang, arch);
  1883. if (pchSource == sf->GetFullPath()) {
  1884. filterArch = arch;
  1885. }
  1886. if (!pchSource.empty()) {
  1887. pchSources.insert(std::make_pair(pchSource, arch));
  1888. }
  1889. }
  1890. }
  1891. // Compute target-wide flags.
  1892. {
  1893. FlagClassification cls = FlagClassification::BaselineFlag;
  1894. // Compile flags
  1895. {
  1896. FlagKind kind = FlagKind::Compile;
  1897. std::string targetFlags;
  1898. lg->GetTargetCompileFlags(this, config, lang, targetFlags, filterArch);
  1899. for (auto&& flag : SplitFlags(targetFlags)) {
  1900. compile_flags.emplace_back(cls, kind, std::move(flag));
  1901. }
  1902. }
  1903. // Define flags
  1904. {
  1905. FlagKind kind = FlagKind::Definition;
  1906. std::set<std::string> defines;
  1907. lg->GetTargetDefines(this, config, lang, defines);
  1908. std::string defineFlags;
  1909. lg->JoinDefines(defines, defineFlags, lang);
  1910. for (auto&& flag : SplitFlags(defineFlags)) {
  1911. define_flags.emplace_back(cls, kind, std::move(flag));
  1912. }
  1913. }
  1914. // Include flags
  1915. {
  1916. FlagKind kind = FlagKind::Include;
  1917. std::vector<std::string> includes;
  1918. lg->GetIncludeDirectories(includes, this, lang, config);
  1919. auto includeFlags =
  1920. lg->GetIncludeFlags(includes, this, lang, config, false);
  1921. for (auto&& flag : SplitFlags(includeFlags)) {
  1922. include_flags.emplace_back(cls, kind, std::move(flag));
  1923. }
  1924. }
  1925. }
  1926. const std::string COMPILE_FLAGS("COMPILE_FLAGS");
  1927. const std::string COMPILE_OPTIONS("COMPILE_OPTIONS");
  1928. cmGeneratorExpressionInterpreter genexInterpreter(lg, config, this, lang);
  1929. // Source-specific flags.
  1930. {
  1931. FlagClassification cls = FlagClassification::PrivateFlag;
  1932. FlagKind kind = FlagKind::Compile;
  1933. std::string sourceFlags;
  1934. if (cmValue cflags = sf->GetProperty(COMPILE_FLAGS)) {
  1935. lg->AppendFlags(sourceFlags,
  1936. genexInterpreter.Evaluate(*cflags, COMPILE_FLAGS));
  1937. }
  1938. if (cmValue coptions = sf->GetProperty(COMPILE_OPTIONS)) {
  1939. lg->AppendCompileOptions(
  1940. sourceFlags, genexInterpreter.Evaluate(*coptions, COMPILE_OPTIONS));
  1941. }
  1942. for (auto&& flag : SplitFlags(sourceFlags)) {
  1943. compile_flags.emplace_back(cls, kind, std::move(flag));
  1944. }
  1945. // Dependency tracking flags.
  1946. {
  1947. if (!sfVars.DependencyFlags.empty()) {
  1948. cmRulePlaceholderExpander::RuleVariables vars;
  1949. auto rulePlaceholderExpander = lg->CreateRulePlaceholderExpander();
  1950. vars.DependencyFile = sfVars.DependencyFile.c_str();
  1951. vars.DependencyTarget = sfVars.DependencyTarget.c_str();
  1952. std::string depfileFlags = sfVars.DependencyFlags;
  1953. rulePlaceholderExpander->ExpandRuleVariables(lg, depfileFlags, vars);
  1954. for (auto&& flag : SplitFlags(depfileFlags)) {
  1955. compile_flags.emplace_back(FlagClassification::LocationFlag,
  1956. FlagKind::BuildSystem, std::move(flag));
  1957. }
  1958. }
  1959. }
  1960. }
  1961. // Precompiled headers.
  1962. {
  1963. FlagClassification cls = FlagClassification::PrivateFlag;
  1964. FlagKind kind = FlagKind::Compile;
  1965. std::string pchFlags;
  1966. // Add precompile headers compile options.
  1967. if (!sf->GetProperty("SKIP_PRECOMPILE_HEADERS")) {
  1968. if (!pchSources.empty()) {
  1969. std::string pchOptions;
  1970. auto pchIt = pchSources.find(sf->GetFullPath());
  1971. if (pchIt != pchSources.end()) {
  1972. pchOptions =
  1973. this->GetPchCreateCompileOptions(config, lang, pchIt->second);
  1974. } else {
  1975. pchOptions = this->GetPchUseCompileOptions(config, lang);
  1976. }
  1977. this->LocalGenerator->AppendCompileOptions(
  1978. pchFlags, genexInterpreter.Evaluate(pchOptions, COMPILE_OPTIONS));
  1979. }
  1980. }
  1981. for (auto&& flag : SplitFlags(pchFlags)) {
  1982. compile_flags.emplace_back(cls, kind, std::move(flag));
  1983. }
  1984. }
  1985. // C++ module flags.
  1986. if (lang == "CXX"_s) {
  1987. FlagClassification cls = FlagClassification::LocationFlag;
  1988. FlagKind kind = FlagKind::BuildSystem;
  1989. std::string bmiFlags;
  1990. auto const* fs = this->GetFileSetForSource(config, sf);
  1991. if (fs && fs->GetType() == "CXX_MODULES"_s) {
  1992. if (lang != "CXX"_s) {
  1993. mf->IssueMessage(
  1994. MessageType::FATAL_ERROR,
  1995. cmStrCat(
  1996. "Target \"", this->Target->GetName(), "\" contains the source\n ",
  1997. sf->GetFullPath(), "\nin a file set of type \"", fs->GetType(),
  1998. R"(" but the source is not classified as a "CXX" source.)"));
  1999. }
  2000. if (!this->Target->IsNormal()) {
  2001. auto flag = mf->GetSafeDefinition("CMAKE_CXX_MODULE_BMI_ONLY_FLAG");
  2002. cmRulePlaceholderExpander::RuleVariables compileObjectVars;
  2003. compileObjectVars.Object = sfVars.ObjectFileDir.c_str();
  2004. auto rulePlaceholderExpander = lg->CreateRulePlaceholderExpander();
  2005. rulePlaceholderExpander->ExpandRuleVariables(lg, flag,
  2006. compileObjectVars);
  2007. lg->AppendCompileOptions(bmiFlags, flag);
  2008. }
  2009. }
  2010. for (auto&& flag : SplitFlags(bmiFlags)) {
  2011. compile_flags.emplace_back(cls, kind, std::move(flag));
  2012. }
  2013. }
  2014. cmRulePlaceholderExpander::RuleVariables vars;
  2015. vars.CMTargetName = this->GetName().c_str();
  2016. vars.CMTargetType = cmState::GetTargetTypeName(this->GetType()).c_str();
  2017. vars.Language = lang.c_str();
  2018. auto const sfPath = this->LocalGenerator->ConvertToOutputFormat(
  2019. sf->GetFullPath(), cmOutputConverter::SHELL);
  2020. // Compute the base compiler command line. We'll find placeholders and
  2021. // replace them with arguments later in this function.
  2022. {
  2023. FlagClassification cls = FlagClassification::ExecutionFlag;
  2024. FlagKind kind = FlagKind::NotAFlag;
  2025. std::string const cmdVar = cmStrCat("CMAKE_", lang, "_COMPILE_OBJECT");
  2026. std::string const& compileCmd = mf->GetRequiredDefinition(cmdVar);
  2027. cmList compileCmds(compileCmd); // FIXME: which command to use?
  2028. std::string& cmd = compileCmds[0];
  2029. auto rulePlaceholderExpander = lg->CreateRulePlaceholderExpander();
  2030. static std::string const PlaceholderDefines = "__CMAKE_DEFINES";
  2031. static std::string const PlaceholderIncludes = "__CMAKE_INCLUDES";
  2032. static std::string const PlaceholderFlags = "__CMAKE_FLAGS";
  2033. static std::string const PlaceholderSource = "__CMAKE_SOURCE";
  2034. vars.Defines = PlaceholderDefines.c_str();
  2035. vars.Includes = PlaceholderIncludes.c_str();
  2036. vars.TargetPDB = sfVars.TargetPDB.c_str();
  2037. vars.TargetCompilePDB = sfVars.TargetCompilePDB.c_str();
  2038. vars.Object = sfVars.ObjectFileDir.c_str();
  2039. vars.ObjectDir = sfVars.ObjectDir.c_str();
  2040. vars.ObjectFileDir = sfVars.ObjectFileDir.c_str();
  2041. vars.Flags = PlaceholderFlags.c_str();
  2042. vars.DependencyFile = sfVars.DependencyFile.c_str();
  2043. vars.DependencyTarget = sfVars.DependencyTarget.c_str();
  2044. vars.Source = PlaceholderSource.c_str();
  2045. rulePlaceholderExpander->ExpandRuleVariables(lg, cmd, vars);
  2046. for (auto&& flag : SplitFlags(cmd)) {
  2047. if (flag == PlaceholderDefines) {
  2048. flags.insert(flags.end(), define_flags.begin(), define_flags.end());
  2049. } else if (flag == PlaceholderIncludes) {
  2050. flags.insert(flags.end(), include_flags.begin(), include_flags.end());
  2051. } else if (flag == PlaceholderFlags) {
  2052. flags.insert(flags.end(), compile_flags.begin(), compile_flags.end());
  2053. } else if (flag == PlaceholderSource) {
  2054. flags.emplace_back(FlagClassification::LocationFlag,
  2055. FlagKind::BuildSystem, sfPath);
  2056. } else {
  2057. flags.emplace_back(cls, kind, std::move(flag));
  2058. // All remaining flags here are build system flags.
  2059. kind = FlagKind::BuildSystem;
  2060. }
  2061. }
  2062. }
  2063. cacheEntry = sourceFlagsCache.emplace_hint(cacheEntry, sf, std::move(flags));
  2064. return cacheEntry->second;
  2065. }
  2066. cmGeneratorTarget::SourceVariables cmGeneratorTarget::GetSourceVariables(
  2067. cmSourceFile const* sf, std::string const& config)
  2068. {
  2069. SourceVariables vars;
  2070. auto const language = sf->GetLanguage();
  2071. auto const targetType = this->GetType();
  2072. auto const* const lg = this->GetLocalGenerator();
  2073. auto const* const gg = this->GetGlobalGenerator();
  2074. auto const* const mf = this->Makefile;
  2075. // PDB settings.
  2076. {
  2077. if (mf->GetDefinition("MSVC_C_ARCHITECTURE_ID") ||
  2078. mf->GetDefinition("MSVC_CXX_ARCHITECTURE_ID") ||
  2079. mf->GetDefinition("MSVC_CUDA_ARCHITECTURE_ID")) {
  2080. std::string pdbPath;
  2081. std::string compilePdbPath;
  2082. if (targetType <= cmStateEnums::OBJECT_LIBRARY) {
  2083. compilePdbPath = this->GetCompilePDBPath(config);
  2084. if (compilePdbPath.empty()) {
  2085. // Match VS default: `$(IntDir)vc$(PlatformToolsetVersion).pdb`.
  2086. // A trailing slash tells the toolchain to add its default file name.
  2087. compilePdbPath = this->GetSupportDirectory();
  2088. if (gg->IsMultiConfig()) {
  2089. compilePdbPath = cmStrCat(compilePdbPath, '/', config);
  2090. }
  2091. compilePdbPath += '/';
  2092. if (targetType == cmStateEnums::STATIC_LIBRARY) {
  2093. // Match VS default for static libs: `$(IntDir)$(ProjectName).pdb`.
  2094. compilePdbPath = cmStrCat(compilePdbPath, this->GetName(), ".pdb");
  2095. }
  2096. }
  2097. }
  2098. if (targetType == cmStateEnums::EXECUTABLE ||
  2099. targetType == cmStateEnums::STATIC_LIBRARY ||
  2100. targetType == cmStateEnums::SHARED_LIBRARY ||
  2101. targetType == cmStateEnums::MODULE_LIBRARY) {
  2102. pdbPath = cmStrCat(this->GetPDBDirectory(config), '/',
  2103. this->GetPDBName(config));
  2104. }
  2105. vars.TargetPDB = lg->ConvertToOutputFormat(
  2106. gg->ConvertToOutputPath(std::move(pdbPath)), cmOutputConverter::SHELL);
  2107. vars.TargetCompilePDB = lg->ConvertToOutputFormat(
  2108. gg->ConvertToOutputPath(std::move(compilePdbPath)),
  2109. cmOutputConverter::SHELL);
  2110. }
  2111. }
  2112. // Object settings.
  2113. {
  2114. std::string const objectDir = gg->ConvertToOutputPath(
  2115. cmStrCat(this->GetSupportDirectory(), gg->GetConfigDirectory(config)));
  2116. std::string const objectFileName = this->GetObjectName(sf);
  2117. std::string const objectFilePath =
  2118. cmStrCat(objectDir, '/', objectFileName);
  2119. vars.ObjectDir =
  2120. lg->ConvertToOutputFormat(objectDir, cmOutputConverter::SHELL);
  2121. vars.ObjectFileDir =
  2122. lg->ConvertToOutputFormat(objectFilePath, cmOutputConverter::SHELL);
  2123. // Dependency settings.
  2124. {
  2125. std::string const depfileFormatName =
  2126. cmStrCat("CMAKE_", language, "_DEPFILE_FORMAT");
  2127. std::string const depfileFormat =
  2128. mf->GetSafeDefinition(depfileFormatName);
  2129. if (depfileFormat != "msvc"_s) {
  2130. std::string const flagsName =
  2131. cmStrCat("CMAKE_DEPFILE_FLAGS_", language);
  2132. std::string const depfileFlags = mf->GetSafeDefinition(flagsName);
  2133. if (!depfileFlags.empty()) {
  2134. bool replaceExt = false;
  2135. if (!language.empty()) {
  2136. std::string const repVar =
  2137. cmStrCat("CMAKE_", language, "_DEPFILE_EXTENSION_REPLACE");
  2138. replaceExt = mf->IsOn(repVar);
  2139. }
  2140. std::string const depfilePath = cmStrCat(
  2141. objectDir, '/',
  2142. replaceExt
  2143. ? cmSystemTools::GetFilenameWithoutLastExtension(objectFileName)
  2144. : objectFileName,
  2145. ".d");
  2146. vars.DependencyFlags = depfileFlags;
  2147. vars.DependencyTarget = vars.ObjectFileDir;
  2148. vars.DependencyFile =
  2149. lg->ConvertToOutputFormat(depfilePath, cmOutputConverter::SHELL);
  2150. }
  2151. }
  2152. }
  2153. }
  2154. return vars;
  2155. }
  2156. void cmGeneratorTarget::AddExplicitLanguageFlags(std::string& flags,
  2157. cmSourceFile const& sf) const
  2158. {
  2159. cmValue lang = sf.GetProperty("LANGUAGE");
  2160. if (!lang) {
  2161. return;
  2162. }
  2163. switch (this->GetPolicyStatusCMP0119()) {
  2164. case cmPolicies::WARN:
  2165. CM_FALLTHROUGH;
  2166. case cmPolicies::OLD:
  2167. // The OLD behavior is to not add explicit language flags.
  2168. return;
  2169. case cmPolicies::NEW:
  2170. // The NEW behavior is to add explicit language flags.
  2171. break;
  2172. }
  2173. this->LocalGenerator->AppendFeatureOptions(flags, *lang,
  2174. "EXPLICIT_LANGUAGE");
  2175. }
  2176. void cmGeneratorTarget::AddCUDAArchitectureFlags(cmBuildStep compileOrLink,
  2177. std::string const& config,
  2178. std::string& flags) const
  2179. {
  2180. std::string arch = this->GetSafeProperty("CUDA_ARCHITECTURES");
  2181. if (arch.empty()) {
  2182. switch (this->GetPolicyStatusCMP0104()) {
  2183. case cmPolicies::WARN:
  2184. if (!this->LocalGenerator->GetCMakeInstance()->GetIsInTryCompile()) {
  2185. this->Makefile->IssueMessage(
  2186. MessageType::AUTHOR_WARNING,
  2187. cmPolicies::GetPolicyWarning(cmPolicies::CMP0104) +
  2188. "\nCUDA_ARCHITECTURES is empty for target \"" + this->GetName() +
  2189. "\".");
  2190. }
  2191. CM_FALLTHROUGH;
  2192. case cmPolicies::OLD:
  2193. break;
  2194. default:
  2195. this->Makefile->IssueMessage(
  2196. MessageType::FATAL_ERROR,
  2197. "CUDA_ARCHITECTURES is empty for target \"" + this->GetName() +
  2198. "\".");
  2199. }
  2200. }
  2201. // If CUDA_ARCHITECTURES is false we don't add any architectures.
  2202. if (cmIsOff(arch)) {
  2203. return;
  2204. }
  2205. this->AddCUDAArchitectureFlagsImpl(compileOrLink, config, "CUDA",
  2206. std::move(arch), flags);
  2207. }
  2208. void cmGeneratorTarget::AddCUDAArchitectureFlagsImpl(cmBuildStep compileOrLink,
  2209. std::string const& config,
  2210. std::string const& lang,
  2211. std::string arch,
  2212. std::string& flags) const
  2213. {
  2214. std::string const& compiler = this->Makefile->GetSafeDefinition(
  2215. cmStrCat("CMAKE_", lang, "_COMPILER_ID"));
  2216. const bool ipoEnabled = this->IsIPOEnabled(lang, config);
  2217. // Check for special modes: `all`, `all-major`.
  2218. if (arch == "all" || arch == "all-major") {
  2219. if (compiler == "NVIDIA" &&
  2220. cmSystemTools::VersionCompare(cmSystemTools::OP_GREATER_EQUAL,
  2221. this->Makefile->GetDefinition(cmStrCat(
  2222. "CMAKE_", lang, "_COMPILER_VERSION")),
  2223. "11.5")) {
  2224. flags = cmStrCat(flags, " -arch=", arch);
  2225. return;
  2226. }
  2227. if (arch == "all") {
  2228. arch = *this->Makefile->GetDefinition(
  2229. cmStrCat("CMAKE_", lang, "_ARCHITECTURES_ALL"));
  2230. } else if (arch == "all-major") {
  2231. arch = *this->Makefile->GetDefinition(
  2232. cmStrCat("CMAKE_", lang, "_ARCHITECTURES_ALL_MAJOR"));
  2233. }
  2234. } else if (arch == "native") {
  2235. cmValue native = this->Makefile->GetDefinition(
  2236. cmStrCat("CMAKE_", lang, "_ARCHITECTURES_NATIVE"));
  2237. if (native.IsEmpty()) {
  2238. this->Makefile->IssueMessage(
  2239. MessageType::FATAL_ERROR,
  2240. cmStrCat(lang,
  2241. "_ARCHITECTURES is set to \"native\", but no NVIDIA GPU was "
  2242. "detected."));
  2243. }
  2244. if (compiler == "NVIDIA" &&
  2245. cmSystemTools::VersionCompare(cmSystemTools::OP_GREATER_EQUAL,
  2246. this->Makefile->GetDefinition(cmStrCat(
  2247. "CMAKE_", lang, "_COMPILER_VERSION")),
  2248. "11.6")) {
  2249. flags = cmStrCat(flags, " -arch=", arch);
  2250. return;
  2251. }
  2252. arch = *native;
  2253. }
  2254. struct CudaArchitecture
  2255. {
  2256. std::string name;
  2257. bool real{ true };
  2258. bool virtual_{ true };
  2259. };
  2260. std::vector<CudaArchitecture> architectures;
  2261. {
  2262. cmList options(arch);
  2263. for (auto& option : options) {
  2264. CudaArchitecture architecture;
  2265. // Architecture name is up to the first specifier.
  2266. std::size_t pos = option.find_first_of('-');
  2267. architecture.name = option.substr(0, pos);
  2268. if (pos != std::string::npos) {
  2269. cm::string_view specifier{ option.c_str() + pos + 1,
  2270. option.length() - pos - 1 };
  2271. if (specifier == "real") {
  2272. architecture.real = true;
  2273. architecture.virtual_ = false;
  2274. } else if (specifier == "virtual") {
  2275. architecture.real = false;
  2276. architecture.virtual_ = true;
  2277. } else {
  2278. this->Makefile->IssueMessage(
  2279. MessageType::FATAL_ERROR,
  2280. "Unknown CUDA architecture specifier \"" + std::string(specifier) +
  2281. "\".");
  2282. }
  2283. }
  2284. architectures.emplace_back(architecture);
  2285. }
  2286. }
  2287. if (compiler == "NVIDIA") {
  2288. if (ipoEnabled && compileOrLink == cmBuildStep::Link) {
  2289. if (cmValue cudaIPOFlags = this->Makefile->GetDefinition(
  2290. cmStrCat("CMAKE_", lang, "_LINK_OPTIONS_IPO"))) {
  2291. flags += *cudaIPOFlags;
  2292. }
  2293. }
  2294. for (CudaArchitecture& architecture : architectures) {
  2295. flags +=
  2296. " \"--generate-code=arch=compute_" + architecture.name + ",code=[";
  2297. if (architecture.virtual_) {
  2298. flags += "compute_" + architecture.name;
  2299. if (ipoEnabled || architecture.real) {
  2300. flags += ",";
  2301. }
  2302. }
  2303. if (ipoEnabled) {
  2304. if (compileOrLink == cmBuildStep::Compile) {
  2305. flags += "lto_" + architecture.name;
  2306. } else if (compileOrLink == cmBuildStep::Link) {
  2307. flags += "sm_" + architecture.name;
  2308. }
  2309. } else if (architecture.real) {
  2310. flags += "sm_" + architecture.name;
  2311. }
  2312. flags += "]\"";
  2313. }
  2314. } else if (compiler == "Clang" && compileOrLink == cmBuildStep::Compile) {
  2315. for (CudaArchitecture& architecture : architectures) {
  2316. flags += " --cuda-gpu-arch=sm_" + architecture.name;
  2317. if (!architecture.real) {
  2318. this->Makefile->IssueMessage(
  2319. MessageType::WARNING,
  2320. "Clang doesn't support disabling CUDA real code generation.");
  2321. }
  2322. if (!architecture.virtual_) {
  2323. flags += " --no-cuda-include-ptx=sm_" + architecture.name;
  2324. }
  2325. }
  2326. }
  2327. }
  2328. void cmGeneratorTarget::AddISPCTargetFlags(std::string& flags) const
  2329. {
  2330. const std::string& arch = this->GetSafeProperty("ISPC_INSTRUCTION_SETS");
  2331. // If ISPC_TARGET is false we don't add any architectures.
  2332. if (cmIsOff(arch)) {
  2333. return;
  2334. }
  2335. std::string const& compiler =
  2336. this->Makefile->GetSafeDefinition("CMAKE_ISPC_COMPILER_ID");
  2337. if (compiler == "Intel") {
  2338. cmList targets(arch);
  2339. if (!targets.empty()) {
  2340. flags += cmStrCat(" --target=", cmWrap("", targets, "", ","));
  2341. }
  2342. }
  2343. }
  2344. void cmGeneratorTarget::AddHIPArchitectureFlags(cmBuildStep compileOrLink,
  2345. std::string const& config,
  2346. std::string& flags) const
  2347. {
  2348. std::string arch = this->GetSafeProperty("HIP_ARCHITECTURES");
  2349. if (arch.empty()) {
  2350. this->Makefile->IssueMessage(MessageType::FATAL_ERROR,
  2351. "HIP_ARCHITECTURES is empty for target \"" +
  2352. this->GetName() + "\".");
  2353. }
  2354. // If HIP_ARCHITECTURES is false we don't add any architectures.
  2355. if (cmIsOff(arch)) {
  2356. return;
  2357. }
  2358. if (this->Makefile->GetSafeDefinition("CMAKE_HIP_PLATFORM") == "nvidia") {
  2359. this->AddCUDAArchitectureFlagsImpl(compileOrLink, config, "HIP",
  2360. std::move(arch), flags);
  2361. return;
  2362. }
  2363. cmList options(arch);
  2364. for (std::string& option : options) {
  2365. flags += " --offload-arch=" + option;
  2366. }
  2367. }
  2368. void cmGeneratorTarget::AddCUDAToolkitFlags(std::string& flags) const
  2369. {
  2370. std::string const& compiler =
  2371. this->Makefile->GetSafeDefinition("CMAKE_CUDA_COMPILER_ID");
  2372. if (compiler == "Clang") {
  2373. // Pass CUDA toolkit explicitly to Clang.
  2374. // Clang's searching for the system CUDA toolkit isn't very good and it's
  2375. // expected the user will explicitly pass the toolkit path.
  2376. // This also avoids Clang having to search for the toolkit on every
  2377. // invocation.
  2378. std::string toolkitRoot =
  2379. this->Makefile->GetSafeDefinition("CMAKE_CUDA_COMPILER_LIBRARY_ROOT");
  2380. if (!toolkitRoot.empty()) {
  2381. flags += " --cuda-path=" +
  2382. this->LocalGenerator->ConvertToOutputFormat(toolkitRoot,
  2383. cmOutputConverter::SHELL);
  2384. }
  2385. }
  2386. }
  2387. //----------------------------------------------------------------------------
  2388. std::string cmGeneratorTarget::GetFeatureSpecificLinkRuleVariable(
  2389. std::string const& var, std::string const& lang,
  2390. std::string const& config) const
  2391. {
  2392. if (this->IsIPOEnabled(lang, config)) {
  2393. std::string varIPO = var + "_IPO";
  2394. if (this->Makefile->IsDefinitionSet(varIPO)) {
  2395. return varIPO;
  2396. }
  2397. }
  2398. return var;
  2399. }
  2400. //----------------------------------------------------------------------------
  2401. std::string cmGeneratorTarget::GetCreateRuleVariable(
  2402. std::string const& lang, std::string const& config) const
  2403. {
  2404. switch (this->GetType()) {
  2405. case cmStateEnums::STATIC_LIBRARY: {
  2406. std::string var = "CMAKE_" + lang + "_CREATE_STATIC_LIBRARY";
  2407. return this->GetFeatureSpecificLinkRuleVariable(var, lang, config);
  2408. }
  2409. case cmStateEnums::SHARED_LIBRARY:
  2410. if (this->IsArchivedAIXSharedLibrary()) {
  2411. return "CMAKE_" + lang + "_CREATE_SHARED_LIBRARY_ARCHIVE";
  2412. }
  2413. return "CMAKE_" + lang + "_CREATE_SHARED_LIBRARY";
  2414. case cmStateEnums::MODULE_LIBRARY:
  2415. return "CMAKE_" + lang + "_CREATE_SHARED_MODULE";
  2416. case cmStateEnums::EXECUTABLE:
  2417. if (this->IsExecutableWithExports()) {
  2418. std::string linkExeWithExports =
  2419. "CMAKE_" + lang + "_LINK_EXECUTABLE_WITH_EXPORTS";
  2420. if (this->Makefile->IsDefinitionSet(linkExeWithExports)) {
  2421. return linkExeWithExports;
  2422. }
  2423. }
  2424. return "CMAKE_" + lang + "_LINK_EXECUTABLE";
  2425. default:
  2426. break;
  2427. }
  2428. return "";
  2429. }
  2430. //----------------------------------------------------------------------------
  2431. std::string cmGeneratorTarget::GetClangTidyExportFixesDirectory(
  2432. const std::string& lang) const
  2433. {
  2434. cmValue val =
  2435. this->GetProperty(cmStrCat(lang, "_CLANG_TIDY_EXPORT_FIXES_DIR"));
  2436. if (!cmNonempty(val)) {
  2437. return {};
  2438. }
  2439. std::string path = *val;
  2440. if (!cmSystemTools::FileIsFullPath(path)) {
  2441. path =
  2442. cmStrCat(this->LocalGenerator->GetCurrentBinaryDirectory(), '/', path);
  2443. }
  2444. return cmSystemTools::CollapseFullPath(path);
  2445. }
  2446. std::vector<std::string> cmGeneratorTarget::GetPchArchs(
  2447. std::string const& config, std::string const& lang) const
  2448. {
  2449. std::vector<std::string> pchArchs;
  2450. if (!this->GetGlobalGenerator()->IsXcode()) {
  2451. pchArchs = this->GetAppleArchs(config, lang);
  2452. }
  2453. if (pchArchs.size() < 2) {
  2454. // We do not need per-arch PCH files when building for one architecture.
  2455. pchArchs = { {} };
  2456. }
  2457. return pchArchs;
  2458. }
  2459. std::string cmGeneratorTarget::GetPchHeader(const std::string& config,
  2460. const std::string& language,
  2461. const std::string& arch) const
  2462. {
  2463. if (language != "C" && language != "CXX" && language != "OBJC" &&
  2464. language != "OBJCXX") {
  2465. return std::string();
  2466. }
  2467. if (this->GetPropertyAsBool("DISABLE_PRECOMPILE_HEADERS")) {
  2468. return std::string();
  2469. }
  2470. const cmGeneratorTarget* generatorTarget = this;
  2471. cmValue pchReuseFrom =
  2472. generatorTarget->GetProperty("PRECOMPILE_HEADERS_REUSE_FROM");
  2473. const auto inserted =
  2474. this->PchHeaders.insert(std::make_pair(language + config + arch, ""));
  2475. if (inserted.second) {
  2476. const std::vector<BT<std::string>> headers =
  2477. this->GetPrecompileHeaders(config, language);
  2478. if (headers.empty() && !pchReuseFrom) {
  2479. return std::string();
  2480. }
  2481. std::string& filename = inserted.first->second;
  2482. if (pchReuseFrom) {
  2483. generatorTarget =
  2484. this->GetGlobalGenerator()->FindGeneratorTarget(*pchReuseFrom);
  2485. }
  2486. const std::map<std::string, std::string> languageToExtension = {
  2487. { "C", ".h" },
  2488. { "CXX", ".hxx" },
  2489. { "OBJC", ".objc.h" },
  2490. { "OBJCXX", ".objcxx.hxx" }
  2491. };
  2492. filename = generatorTarget->GetSupportDirectory();
  2493. if (this->GetGlobalGenerator()->IsMultiConfig()) {
  2494. filename = cmStrCat(filename, "/", config);
  2495. }
  2496. filename =
  2497. cmStrCat(filename, "/cmake_pch", arch.empty() ? "" : cmStrCat("_", arch),
  2498. languageToExtension.at(language));
  2499. const std::string filename_tmp = cmStrCat(filename, ".tmp");
  2500. if (!pchReuseFrom) {
  2501. cmValue pchPrologue =
  2502. this->Makefile->GetDefinition("CMAKE_PCH_PROLOGUE");
  2503. cmValue pchEpilogue =
  2504. this->Makefile->GetDefinition("CMAKE_PCH_EPILOGUE");
  2505. std::string firstHeaderOnDisk;
  2506. {
  2507. cmGeneratedFileStream file(
  2508. filename_tmp, false,
  2509. this->GetGlobalGenerator()->GetMakefileEncoding());
  2510. file << "/* generated by CMake */\n\n";
  2511. if (pchPrologue) {
  2512. file << *pchPrologue << "\n";
  2513. }
  2514. if (this->GetGlobalGenerator()->IsXcode()) {
  2515. file << "#ifndef CMAKE_SKIP_PRECOMPILE_HEADERS\n";
  2516. }
  2517. if (language == "CXX" && !this->GetGlobalGenerator()->IsXcode()) {
  2518. file << "#ifdef __cplusplus\n";
  2519. }
  2520. for (auto const& header_bt : headers) {
  2521. if (header_bt.Value.empty()) {
  2522. continue;
  2523. }
  2524. if (header_bt.Value[0] == '<' || header_bt.Value[0] == '\"') {
  2525. file << "#include " << header_bt.Value << "\n";
  2526. } else {
  2527. file << "#include \"" << header_bt.Value << "\"\n";
  2528. }
  2529. if (cmSystemTools::FileExists(header_bt.Value) &&
  2530. firstHeaderOnDisk.empty()) {
  2531. firstHeaderOnDisk = header_bt.Value;
  2532. }
  2533. }
  2534. if (language == "CXX" && !this->GetGlobalGenerator()->IsXcode()) {
  2535. file << "#endif // __cplusplus\n";
  2536. }
  2537. if (this->GetGlobalGenerator()->IsXcode()) {
  2538. file << "#endif // CMAKE_SKIP_PRECOMPILE_HEADERS\n";
  2539. }
  2540. if (pchEpilogue) {
  2541. file << *pchEpilogue << "\n";
  2542. }
  2543. }
  2544. if (!firstHeaderOnDisk.empty()) {
  2545. cmFileTimes::Copy(firstHeaderOnDisk, filename_tmp);
  2546. }
  2547. cmSystemTools::MoveFileIfDifferent(filename_tmp, filename);
  2548. }
  2549. }
  2550. return inserted.first->second;
  2551. }
  2552. std::string cmGeneratorTarget::GetPchSource(const std::string& config,
  2553. const std::string& language,
  2554. const std::string& arch) const
  2555. {
  2556. if (language != "C" && language != "CXX" && language != "OBJC" &&
  2557. language != "OBJCXX") {
  2558. return std::string();
  2559. }
  2560. const auto inserted =
  2561. this->PchSources.insert(std::make_pair(language + config + arch, ""));
  2562. if (inserted.second) {
  2563. const std::string pchHeader = this->GetPchHeader(config, language, arch);
  2564. if (pchHeader.empty()) {
  2565. return std::string();
  2566. }
  2567. std::string& filename = inserted.first->second;
  2568. const cmGeneratorTarget* generatorTarget = this;
  2569. cmValue pchReuseFrom =
  2570. generatorTarget->GetProperty("PRECOMPILE_HEADERS_REUSE_FROM");
  2571. if (pchReuseFrom) {
  2572. generatorTarget =
  2573. this->GetGlobalGenerator()->FindGeneratorTarget(*pchReuseFrom);
  2574. }
  2575. filename = cmStrCat(generatorTarget->GetSupportDirectory(), "/cmake_pch");
  2576. // For GCC the source extension will be transformed into .h[xx].gch
  2577. if (!this->Makefile->IsOn("CMAKE_LINK_PCH")) {
  2578. const std::map<std::string, std::string> languageToExtension = {
  2579. { "C", ".h.c" },
  2580. { "CXX", ".hxx.cxx" },
  2581. { "OBJC", ".objc.h.m" },
  2582. { "OBJCXX", ".objcxx.hxx.mm" }
  2583. };
  2584. filename = cmStrCat(filename, arch.empty() ? "" : cmStrCat("_", arch),
  2585. languageToExtension.at(language));
  2586. } else {
  2587. const std::map<std::string, std::string> languageToExtension = {
  2588. { "C", ".c" }, { "CXX", ".cxx" }, { "OBJC", ".m" }, { "OBJCXX", ".mm" }
  2589. };
  2590. filename = cmStrCat(filename, arch.empty() ? "" : cmStrCat("_", arch),
  2591. languageToExtension.at(language));
  2592. }
  2593. const std::string filename_tmp = cmStrCat(filename, ".tmp");
  2594. if (!pchReuseFrom) {
  2595. {
  2596. cmGeneratedFileStream file(filename_tmp);
  2597. file << "/* generated by CMake */\n";
  2598. }
  2599. cmFileTimes::Copy(pchHeader, filename_tmp);
  2600. cmSystemTools::MoveFileIfDifferent(filename_tmp, filename);
  2601. }
  2602. }
  2603. return inserted.first->second;
  2604. }
  2605. std::string cmGeneratorTarget::GetPchFileObject(const std::string& config,
  2606. const std::string& language,
  2607. const std::string& arch)
  2608. {
  2609. if (language != "C" && language != "CXX" && language != "OBJC" &&
  2610. language != "OBJCXX") {
  2611. return std::string();
  2612. }
  2613. const auto inserted =
  2614. this->PchObjectFiles.insert(std::make_pair(language + config + arch, ""));
  2615. if (inserted.second) {
  2616. const std::string pchSource = this->GetPchSource(config, language, arch);
  2617. if (pchSource.empty()) {
  2618. return std::string();
  2619. }
  2620. std::string& filename = inserted.first->second;
  2621. auto* pchSf = this->Makefile->GetOrCreateSource(
  2622. pchSource, false, cmSourceFileLocationKind::Known);
  2623. filename = cmStrCat(this->ObjectDirectory, this->GetObjectName(pchSf));
  2624. if (this->GetGlobalGenerator()->IsMultiConfig()) {
  2625. cmSystemTools::ReplaceString(
  2626. filename, this->GetGlobalGenerator()->GetCMakeCFGIntDir(), config);
  2627. }
  2628. }
  2629. return inserted.first->second;
  2630. }
  2631. std::string cmGeneratorTarget::GetPchFile(const std::string& config,
  2632. const std::string& language,
  2633. const std::string& arch)
  2634. {
  2635. const auto inserted =
  2636. this->PchFiles.insert(std::make_pair(language + config + arch, ""));
  2637. if (inserted.second) {
  2638. std::string& pchFile = inserted.first->second;
  2639. const std::string pchExtension =
  2640. this->Makefile->GetSafeDefinition("CMAKE_PCH_EXTENSION");
  2641. if (this->Makefile->IsOn("CMAKE_LINK_PCH")) {
  2642. auto replaceExtension = [](const std::string& str,
  2643. const std::string& ext) -> std::string {
  2644. auto dot_pos = str.rfind('.');
  2645. std::string result;
  2646. if (dot_pos != std::string::npos) {
  2647. result = str.substr(0, dot_pos);
  2648. }
  2649. result += ext;
  2650. return result;
  2651. };
  2652. cmGeneratorTarget* generatorTarget = this;
  2653. cmValue pchReuseFrom =
  2654. generatorTarget->GetProperty("PRECOMPILE_HEADERS_REUSE_FROM");
  2655. if (pchReuseFrom) {
  2656. generatorTarget =
  2657. this->GetGlobalGenerator()->FindGeneratorTarget(*pchReuseFrom);
  2658. }
  2659. const std::string pchFileObject =
  2660. generatorTarget->GetPchFileObject(config, language, arch);
  2661. if (!pchExtension.empty()) {
  2662. pchFile = replaceExtension(pchFileObject, pchExtension);
  2663. }
  2664. } else {
  2665. pchFile = this->GetPchHeader(config, language, arch);
  2666. pchFile += pchExtension;
  2667. }
  2668. }
  2669. return inserted.first->second;
  2670. }
  2671. std::string cmGeneratorTarget::GetPchCreateCompileOptions(
  2672. const std::string& config, const std::string& language,
  2673. const std::string& arch)
  2674. {
  2675. const auto inserted = this->PchCreateCompileOptions.insert(
  2676. std::make_pair(language + config + arch, ""));
  2677. if (inserted.second) {
  2678. std::string& createOptionList = inserted.first->second;
  2679. if (this->GetPropertyAsBool("PCH_WARN_INVALID")) {
  2680. createOptionList = this->Makefile->GetSafeDefinition(
  2681. cmStrCat("CMAKE_", language, "_COMPILE_OPTIONS_INVALID_PCH"));
  2682. }
  2683. if (this->GetPropertyAsBool("PCH_INSTANTIATE_TEMPLATES")) {
  2684. std::string varName = cmStrCat(
  2685. "CMAKE_", language, "_COMPILE_OPTIONS_INSTANTIATE_TEMPLATES_PCH");
  2686. std::string instantiateOption =
  2687. this->Makefile->GetSafeDefinition(varName);
  2688. if (!instantiateOption.empty()) {
  2689. createOptionList = cmStrCat(createOptionList, ";", instantiateOption);
  2690. }
  2691. }
  2692. const std::string createOptVar =
  2693. cmStrCat("CMAKE_", language, "_COMPILE_OPTIONS_CREATE_PCH");
  2694. createOptionList = cmStrCat(
  2695. createOptionList, ";", this->Makefile->GetSafeDefinition(createOptVar));
  2696. const std::string pchHeader = this->GetPchHeader(config, language, arch);
  2697. const std::string pchFile = this->GetPchFile(config, language, arch);
  2698. cmSystemTools::ReplaceString(createOptionList, "<PCH_HEADER>", pchHeader);
  2699. cmSystemTools::ReplaceString(createOptionList, "<PCH_FILE>", pchFile);
  2700. }
  2701. return inserted.first->second;
  2702. }
  2703. std::string cmGeneratorTarget::GetPchUseCompileOptions(
  2704. const std::string& config, const std::string& language,
  2705. const std::string& arch)
  2706. {
  2707. const auto inserted = this->PchUseCompileOptions.insert(
  2708. std::make_pair(language + config + arch, ""));
  2709. if (inserted.second) {
  2710. std::string& useOptionList = inserted.first->second;
  2711. if (this->GetPropertyAsBool("PCH_WARN_INVALID")) {
  2712. useOptionList = this->Makefile->GetSafeDefinition(
  2713. cmStrCat("CMAKE_", language, "_COMPILE_OPTIONS_INVALID_PCH"));
  2714. }
  2715. const std::string useOptVar =
  2716. cmStrCat(language, "_COMPILE_OPTIONS_USE_PCH");
  2717. std::string const& useOptionListProperty =
  2718. this->GetSafeProperty(useOptVar);
  2719. useOptionList = cmStrCat(
  2720. useOptionList, ";",
  2721. useOptionListProperty.empty()
  2722. ? this->Makefile->GetSafeDefinition(cmStrCat("CMAKE_", useOptVar))
  2723. : useOptionListProperty);
  2724. const std::string pchHeader = this->GetPchHeader(config, language, arch);
  2725. const std::string pchFile = this->GetPchFile(config, language, arch);
  2726. cmSystemTools::ReplaceString(useOptionList, "<PCH_HEADER>", pchHeader);
  2727. cmSystemTools::ReplaceString(useOptionList, "<PCH_FILE>", pchFile);
  2728. }
  2729. return inserted.first->second;
  2730. }
  2731. void cmGeneratorTarget::AddSourceFileToUnityBatch(
  2732. const std::string& sourceFilename)
  2733. {
  2734. this->UnityBatchedSourceFiles.insert(sourceFilename);
  2735. }
  2736. bool cmGeneratorTarget::IsSourceFilePartOfUnityBatch(
  2737. const std::string& sourceFilename) const
  2738. {
  2739. if (!this->GetPropertyAsBool("UNITY_BUILD")) {
  2740. return false;
  2741. }
  2742. return this->UnityBatchedSourceFiles.find(sourceFilename) !=
  2743. this->UnityBatchedSourceFiles.end();
  2744. }
  2745. void cmGeneratorTarget::ComputeTargetManifest(const std::string& config) const
  2746. {
  2747. if (this->IsImported()) {
  2748. return;
  2749. }
  2750. cmGlobalGenerator* gg = this->LocalGenerator->GetGlobalGenerator();
  2751. // Get the names.
  2752. cmGeneratorTarget::Names targetNames;
  2753. if (this->GetType() == cmStateEnums::EXECUTABLE) {
  2754. targetNames = this->GetExecutableNames(config);
  2755. } else if (this->GetType() == cmStateEnums::STATIC_LIBRARY ||
  2756. this->GetType() == cmStateEnums::SHARED_LIBRARY ||
  2757. this->GetType() == cmStateEnums::MODULE_LIBRARY) {
  2758. targetNames = this->GetLibraryNames(config);
  2759. } else {
  2760. return;
  2761. }
  2762. // Get the directory.
  2763. std::string dir =
  2764. this->GetDirectory(config, cmStateEnums::RuntimeBinaryArtifact);
  2765. // Add each name.
  2766. std::string f;
  2767. if (!targetNames.Output.empty()) {
  2768. f = cmStrCat(dir, '/', targetNames.Output);
  2769. gg->AddToManifest(f);
  2770. }
  2771. if (!targetNames.SharedObject.empty()) {
  2772. f = cmStrCat(dir, '/', targetNames.SharedObject);
  2773. gg->AddToManifest(f);
  2774. }
  2775. if (!targetNames.Real.empty()) {
  2776. f = cmStrCat(dir, '/', targetNames.Real);
  2777. gg->AddToManifest(f);
  2778. }
  2779. if (!targetNames.PDB.empty()) {
  2780. f = cmStrCat(dir, '/', targetNames.PDB);
  2781. gg->AddToManifest(f);
  2782. }
  2783. dir = this->GetDirectory(config, cmStateEnums::ImportLibraryArtifact);
  2784. if (!targetNames.ImportOutput.empty()) {
  2785. f = cmStrCat(dir, '/', targetNames.ImportOutput);
  2786. gg->AddToManifest(f);
  2787. }
  2788. if (!targetNames.ImportLibrary.empty()) {
  2789. f = cmStrCat(dir, '/', targetNames.ImportLibrary);
  2790. gg->AddToManifest(f);
  2791. }
  2792. if (!targetNames.ImportReal.empty()) {
  2793. f = cmStrCat(dir, '/', targetNames.ImportReal);
  2794. gg->AddToManifest(f);
  2795. }
  2796. }
  2797. cm::optional<cmStandardLevel> cmGeneratorTarget::GetExplicitStandardLevel(
  2798. std::string const& lang, std::string const& config) const
  2799. {
  2800. cm::optional<cmStandardLevel> level;
  2801. std::string key = cmStrCat(cmSystemTools::UpperCase(config), '-', lang);
  2802. auto i = this->ExplicitStandardLevel.find(key);
  2803. if (i != this->ExplicitStandardLevel.end()) {
  2804. level = i->second;
  2805. }
  2806. return level;
  2807. }
  2808. void cmGeneratorTarget::UpdateExplicitStandardLevel(std::string const& lang,
  2809. std::string const& config,
  2810. cmStandardLevel level)
  2811. {
  2812. auto e = this->ExplicitStandardLevel.emplace(
  2813. cmStrCat(cmSystemTools::UpperCase(config), '-', lang), level);
  2814. if (!e.second && e.first->second < level) {
  2815. e.first->second = level;
  2816. }
  2817. }
  2818. bool cmGeneratorTarget::ComputeCompileFeatures(std::string const& config)
  2819. {
  2820. cmStandardLevelResolver standardResolver(this->Makefile);
  2821. for (std::string const& lang :
  2822. this->Makefile->GetState()->GetEnabledLanguages()) {
  2823. if (cmValue languageStd = this->GetLanguageStandard(lang, config)) {
  2824. if (cm::optional<cmStandardLevel> langLevel =
  2825. standardResolver.LanguageStandardLevel(lang, *languageStd)) {
  2826. this->UpdateExplicitStandardLevel(lang, config, *langLevel);
  2827. }
  2828. }
  2829. }
  2830. // Compute the language standard based on the compile features.
  2831. std::vector<BT<std::string>> features = this->GetCompileFeatures(config);
  2832. for (BT<std::string> const& f : features) {
  2833. std::string lang;
  2834. if (!standardResolver.CompileFeatureKnown(this->Target->GetName(), f.Value,
  2835. lang, nullptr)) {
  2836. return false;
  2837. }
  2838. std::string key = cmStrCat(cmSystemTools::UpperCase(config), '-', lang);
  2839. cmValue currentLanguageStandard = this->GetLanguageStandard(lang, config);
  2840. cm::optional<cmStandardLevel> featureLevel;
  2841. std::string newRequiredStandard;
  2842. if (!standardResolver.GetNewRequiredStandard(
  2843. this->Target->GetName(), f.Value, currentLanguageStandard,
  2844. featureLevel, newRequiredStandard)) {
  2845. return false;
  2846. }
  2847. if (featureLevel) {
  2848. this->UpdateExplicitStandardLevel(lang, config, *featureLevel);
  2849. }
  2850. if (!newRequiredStandard.empty()) {
  2851. BTs<std::string>& languageStandardProperty =
  2852. this->LanguageStandardMap[key];
  2853. if (languageStandardProperty.Value != newRequiredStandard) {
  2854. languageStandardProperty.Value = newRequiredStandard;
  2855. languageStandardProperty.Backtraces.clear();
  2856. }
  2857. languageStandardProperty.Backtraces.emplace_back(f.Backtrace);
  2858. }
  2859. }
  2860. return true;
  2861. }
  2862. bool cmGeneratorTarget::ComputeCompileFeatures(
  2863. std::string const& config, std::set<LanguagePair> const& languagePairs)
  2864. {
  2865. for (const auto& language : languagePairs) {
  2866. BTs<std::string> const* generatorTargetLanguageStandard =
  2867. this->GetLanguageStandardProperty(language.first, config);
  2868. if (!generatorTargetLanguageStandard) {
  2869. // If the standard isn't explicitly set we copy it over from the
  2870. // specified paired language.
  2871. std::string key =
  2872. cmStrCat(cmSystemTools::UpperCase(config), '-', language.first);
  2873. BTs<std::string> const* standardToCopy =
  2874. this->GetLanguageStandardProperty(language.second, config);
  2875. if (standardToCopy) {
  2876. this->LanguageStandardMap[key] = *standardToCopy;
  2877. generatorTargetLanguageStandard = &this->LanguageStandardMap[key];
  2878. } else {
  2879. cmValue defaultStandard = this->Makefile->GetDefinition(
  2880. cmStrCat("CMAKE_", language.second, "_STANDARD_DEFAULT"));
  2881. if (defaultStandard) {
  2882. this->LanguageStandardMap[key] = BTs<std::string>(*defaultStandard);
  2883. generatorTargetLanguageStandard = &this->LanguageStandardMap[key];
  2884. }
  2885. }
  2886. // Custom updates for the CUDA standard.
  2887. if (generatorTargetLanguageStandard && (language.first == "CUDA")) {
  2888. if (generatorTargetLanguageStandard->Value == "98") {
  2889. this->LanguageStandardMap[key].Value = "03";
  2890. }
  2891. }
  2892. }
  2893. }
  2894. return true;
  2895. }
  2896. std::string cmGeneratorTarget::GetImportedLibName(
  2897. std::string const& config) const
  2898. {
  2899. if (cmGeneratorTarget::ImportInfo const* info =
  2900. this->GetImportInfo(config)) {
  2901. return info->LibName;
  2902. }
  2903. return std::string();
  2904. }
  2905. std::string cmGeneratorTarget::GetFullPath(const std::string& config,
  2906. cmStateEnums::ArtifactType artifact,
  2907. bool realname) const
  2908. {
  2909. if (this->IsImported()) {
  2910. return this->Target->ImportedGetFullPath(config, artifact);
  2911. }
  2912. return this->NormalGetFullPath(config, artifact, realname);
  2913. }
  2914. std::string cmGeneratorTarget::NormalGetFullPath(
  2915. const std::string& config, cmStateEnums::ArtifactType artifact,
  2916. bool realname) const
  2917. {
  2918. std::string fpath = cmStrCat(this->GetDirectory(config, artifact), '/');
  2919. if (this->IsAppBundleOnApple()) {
  2920. fpath =
  2921. cmStrCat(this->BuildBundleDirectory(fpath, config, FullLevel), '/');
  2922. }
  2923. // Add the full name of the target.
  2924. switch (artifact) {
  2925. case cmStateEnums::RuntimeBinaryArtifact:
  2926. if (realname) {
  2927. fpath += this->NormalGetRealName(config);
  2928. } else {
  2929. fpath +=
  2930. this->GetFullName(config, cmStateEnums::RuntimeBinaryArtifact);
  2931. }
  2932. break;
  2933. case cmStateEnums::ImportLibraryArtifact:
  2934. if (realname) {
  2935. fpath +=
  2936. this->NormalGetRealName(config, cmStateEnums::ImportLibraryArtifact);
  2937. } else {
  2938. fpath +=
  2939. this->GetFullName(config, cmStateEnums::ImportLibraryArtifact);
  2940. }
  2941. break;
  2942. }
  2943. return fpath;
  2944. }
  2945. std::string cmGeneratorTarget::NormalGetRealName(
  2946. const std::string& config, cmStateEnums::ArtifactType artifact) const
  2947. {
  2948. // This should not be called for imported targets.
  2949. // TODO: Split cmTarget into a class hierarchy to get compile-time
  2950. // enforcement of the limited imported target API.
  2951. if (this->IsImported()) {
  2952. std::string msg = cmStrCat("NormalGetRealName called on imported target: ",
  2953. this->GetName());
  2954. this->LocalGenerator->IssueMessage(MessageType::INTERNAL_ERROR, msg);
  2955. }
  2956. Names names = this->GetType() == cmStateEnums::EXECUTABLE
  2957. ? this->GetExecutableNames(config)
  2958. : this->GetLibraryNames(config);
  2959. // Compute the real name that will be built.
  2960. return artifact == cmStateEnums::RuntimeBinaryArtifact ? names.Real
  2961. : names.ImportReal;
  2962. }
  2963. cmGeneratorTarget::Names cmGeneratorTarget::GetLibraryNames(
  2964. const std::string& config) const
  2965. {
  2966. cmGeneratorTarget::Names targetNames;
  2967. // This should not be called for imported targets.
  2968. // TODO: Split cmTarget into a class hierarchy to get compile-time
  2969. // enforcement of the limited imported target API.
  2970. if (this->IsImported()) {
  2971. std::string msg =
  2972. cmStrCat("GetLibraryNames called on imported target: ", this->GetName());
  2973. this->LocalGenerator->IssueMessage(MessageType::INTERNAL_ERROR, msg);
  2974. }
  2975. // Check for library version properties.
  2976. cmValue version = this->GetProperty("VERSION");
  2977. cmValue soversion = this->GetProperty("SOVERSION");
  2978. if (!this->HasSOName(config) ||
  2979. this->Makefile->IsOn("CMAKE_PLATFORM_NO_VERSIONED_SONAME") ||
  2980. this->IsFrameworkOnApple()) {
  2981. // Versioning is supported only for shared libraries and modules,
  2982. // and then only when the platform supports an soname flag.
  2983. version = nullptr;
  2984. soversion = nullptr;
  2985. }
  2986. if (version && !soversion) {
  2987. // The soversion must be set if the library version is set. Use
  2988. // the library version as the soversion.
  2989. soversion = version;
  2990. }
  2991. if (!version && soversion) {
  2992. // Use the soversion as the library version.
  2993. version = soversion;
  2994. }
  2995. // Get the components of the library name.
  2996. NameComponents const& components = this->GetFullNameInternalComponents(
  2997. config, cmStateEnums::RuntimeBinaryArtifact);
  2998. // The library name.
  2999. targetNames.Base = components.base;
  3000. targetNames.Output =
  3001. cmStrCat(components.prefix, targetNames.Base, components.suffix);
  3002. if (this->IsFrameworkOnApple()) {
  3003. targetNames.Real = components.prefix;
  3004. if (!this->Makefile->PlatformIsAppleEmbedded()) {
  3005. targetNames.Real +=
  3006. cmStrCat("Versions/", this->GetFrameworkVersion(), '/');
  3007. }
  3008. targetNames.Real += cmStrCat(targetNames.Base, components.suffix);
  3009. targetNames.SharedObject = targetNames.Real;
  3010. } else if (this->IsArchivedAIXSharedLibrary()) {
  3011. targetNames.SharedObject =
  3012. cmStrCat(components.prefix, targetNames.Base, ".so");
  3013. if (soversion) {
  3014. targetNames.SharedObject += ".";
  3015. targetNames.SharedObject += *soversion;
  3016. }
  3017. targetNames.Real = targetNames.Output;
  3018. } else {
  3019. // The library's soname.
  3020. targetNames.SharedObject = this->ComputeVersionedName(
  3021. components.prefix, targetNames.Base, components.suffix,
  3022. targetNames.Output, soversion);
  3023. // The library's real name on disk.
  3024. targetNames.Real = this->ComputeVersionedName(
  3025. components.prefix, targetNames.Base, components.suffix,
  3026. targetNames.Output, version);
  3027. }
  3028. // The import library names.
  3029. if (this->GetType() == cmStateEnums::SHARED_LIBRARY ||
  3030. this->GetType() == cmStateEnums::MODULE_LIBRARY) {
  3031. NameComponents const& importComponents =
  3032. this->GetFullNameInternalComponents(config,
  3033. cmStateEnums::ImportLibraryArtifact);
  3034. targetNames.ImportOutput = cmStrCat(
  3035. importComponents.prefix, importComponents.base, importComponents.suffix);
  3036. if (this->IsFrameworkOnApple() && this->IsSharedLibraryWithExports()) {
  3037. targetNames.ImportReal = components.prefix;
  3038. if (!this->Makefile->PlatformIsAppleEmbedded()) {
  3039. targetNames.ImportReal +=
  3040. cmStrCat("Versions/", this->GetFrameworkVersion(), '/');
  3041. }
  3042. targetNames.ImportReal +=
  3043. cmStrCat(importComponents.base, importComponents.suffix);
  3044. targetNames.ImportLibrary = targetNames.ImportOutput;
  3045. } else {
  3046. // The import library's soname.
  3047. targetNames.ImportLibrary = this->ComputeVersionedName(
  3048. importComponents.prefix, importComponents.base,
  3049. importComponents.suffix, targetNames.ImportOutput, soversion);
  3050. // The import library's real name on disk.
  3051. targetNames.ImportReal = this->ComputeVersionedName(
  3052. importComponents.prefix, importComponents.base,
  3053. importComponents.suffix, targetNames.ImportOutput, version);
  3054. }
  3055. }
  3056. // The program database file name.
  3057. targetNames.PDB = this->GetPDBName(config);
  3058. return targetNames;
  3059. }
  3060. cmGeneratorTarget::Names cmGeneratorTarget::GetExecutableNames(
  3061. const std::string& config) const
  3062. {
  3063. cmGeneratorTarget::Names targetNames;
  3064. // This should not be called for imported targets.
  3065. // TODO: Split cmTarget into a class hierarchy to get compile-time
  3066. // enforcement of the limited imported target API.
  3067. if (this->IsImported()) {
  3068. std::string msg = cmStrCat(
  3069. "GetExecutableNames called on imported target: ", this->GetName());
  3070. this->LocalGenerator->IssueMessage(MessageType::INTERNAL_ERROR, msg);
  3071. }
  3072. // This versioning is supported only for executables and then only
  3073. // when the platform supports symbolic links.
  3074. #if defined(_WIN32) && !defined(__CYGWIN__)
  3075. cmValue version;
  3076. #else
  3077. // Check for executable version properties.
  3078. cmValue version = this->GetProperty("VERSION");
  3079. if (this->GetType() != cmStateEnums::EXECUTABLE ||
  3080. this->Makefile->IsOn("XCODE")) {
  3081. version = nullptr;
  3082. }
  3083. #endif
  3084. // Get the components of the executable name.
  3085. NameComponents const& components = this->GetFullNameInternalComponents(
  3086. config, cmStateEnums::RuntimeBinaryArtifact);
  3087. // The executable name.
  3088. targetNames.Base = components.base;
  3089. if (this->IsArchivedAIXSharedLibrary()) {
  3090. targetNames.Output = components.prefix + targetNames.Base;
  3091. } else {
  3092. targetNames.Output =
  3093. components.prefix + targetNames.Base + components.suffix;
  3094. }
  3095. // The executable's real name on disk.
  3096. #if defined(__CYGWIN__)
  3097. targetNames.Real = components.prefix + targetNames.Base;
  3098. #else
  3099. targetNames.Real = targetNames.Output;
  3100. #endif
  3101. if (version) {
  3102. targetNames.Real += "-";
  3103. targetNames.Real += *version;
  3104. }
  3105. #if defined(__CYGWIN__)
  3106. targetNames.Real += components.suffix;
  3107. #endif
  3108. // The import library name.
  3109. targetNames.ImportLibrary =
  3110. this->GetFullNameInternal(config, cmStateEnums::ImportLibraryArtifact);
  3111. targetNames.ImportReal = targetNames.ImportLibrary;
  3112. targetNames.ImportOutput = targetNames.ImportLibrary;
  3113. // The program database file name.
  3114. targetNames.PDB = this->GetPDBName(config);
  3115. return targetNames;
  3116. }
  3117. std::string cmGeneratorTarget::GetFullNameInternal(
  3118. const std::string& config, cmStateEnums::ArtifactType artifact) const
  3119. {
  3120. NameComponents const& components =
  3121. this->GetFullNameInternalComponents(config, artifact);
  3122. return components.prefix + components.base + components.suffix;
  3123. }
  3124. std::string cmGeneratorTarget::ImportedGetLocation(
  3125. const std::string& config) const
  3126. {
  3127. assert(this->IsImported());
  3128. return this->Target->ImportedGetFullPath(
  3129. config, cmStateEnums::RuntimeBinaryArtifact);
  3130. }
  3131. std::string cmGeneratorTarget::GetFullNameImported(
  3132. const std::string& config, cmStateEnums::ArtifactType artifact) const
  3133. {
  3134. return cmSystemTools::GetFilenameName(
  3135. this->Target->ImportedGetFullPath(config, artifact));
  3136. }
  3137. cmGeneratorTarget::NameComponents const&
  3138. cmGeneratorTarget::GetFullNameInternalComponents(
  3139. std::string const& config, cmStateEnums::ArtifactType artifact) const
  3140. {
  3141. assert(artifact == cmStateEnums::RuntimeBinaryArtifact ||
  3142. artifact == cmStateEnums::ImportLibraryArtifact);
  3143. FullNameCache& cache = artifact == cmStateEnums::RuntimeBinaryArtifact
  3144. ? RuntimeBinaryFullNameCache
  3145. : ImportLibraryFullNameCache;
  3146. auto search = cache.find(config);
  3147. if (search != cache.end()) {
  3148. return search->second;
  3149. }
  3150. // Use just the target name for non-main target types.
  3151. if (this->GetType() != cmStateEnums::STATIC_LIBRARY &&
  3152. this->GetType() != cmStateEnums::SHARED_LIBRARY &&
  3153. this->GetType() != cmStateEnums::MODULE_LIBRARY &&
  3154. this->GetType() != cmStateEnums::EXECUTABLE) {
  3155. NameComponents components;
  3156. components.base = this->GetName();
  3157. return cache.emplace(config, std::move(components)).first->second;
  3158. }
  3159. const bool isImportedLibraryArtifact =
  3160. (artifact == cmStateEnums::ImportLibraryArtifact);
  3161. // Return an empty name for the import library if this platform
  3162. // does not support import libraries.
  3163. if (isImportedLibraryArtifact && !this->NeedImportLibraryName(config)) {
  3164. return cache.emplace(config, NameComponents()).first->second;
  3165. }
  3166. NameComponents parts;
  3167. std::string& outPrefix = parts.prefix;
  3168. std::string& outBase = parts.base;
  3169. std::string& outSuffix = parts.suffix;
  3170. // retrieve prefix and suffix
  3171. std::string ll = this->GetLinkerLanguage(config);
  3172. cmValue targetPrefix = this->GetFilePrefixInternal(config, artifact, ll);
  3173. cmValue targetSuffix = this->GetFileSuffixInternal(config, artifact, ll);
  3174. // The implib option is only allowed for shared libraries, module
  3175. // libraries, and executables.
  3176. if (this->GetType() != cmStateEnums::SHARED_LIBRARY &&
  3177. this->GetType() != cmStateEnums::MODULE_LIBRARY &&
  3178. this->GetType() != cmStateEnums::EXECUTABLE) {
  3179. artifact = cmStateEnums::RuntimeBinaryArtifact;
  3180. }
  3181. // Compute the full name for main target types.
  3182. std::string configPostfix = this->GetFilePostfix(config);
  3183. // frameworks have directory prefix
  3184. std::string fw_prefix;
  3185. if (this->IsFrameworkOnApple()) {
  3186. fw_prefix =
  3187. cmStrCat(this->GetFrameworkDirectory(config, ContentLevel), '/');
  3188. targetPrefix = cmValue(fw_prefix);
  3189. if (!isImportedLibraryArtifact) {
  3190. // no suffix
  3191. targetSuffix = nullptr;
  3192. }
  3193. }
  3194. if (this->IsCFBundleOnApple()) {
  3195. fw_prefix = cmStrCat(this->GetCFBundleDirectory(config, FullLevel), '/');
  3196. targetPrefix = cmValue(fw_prefix);
  3197. targetSuffix = nullptr;
  3198. }
  3199. // Begin the final name with the prefix.
  3200. outPrefix = targetPrefix ? *targetPrefix : "";
  3201. // Append the target name or property-specified name.
  3202. outBase += this->GetOutputName(config, artifact);
  3203. // Append the per-configuration postfix.
  3204. // When using Xcode, the postfix should be part of the suffix rather than
  3205. // the base, because the suffix ends up being used in Xcode's
  3206. // EXECUTABLE_SUFFIX attribute.
  3207. if (this->IsFrameworkOnApple() && this->GetGlobalGenerator()->IsXcode()) {
  3208. configPostfix += *targetSuffix;
  3209. targetSuffix = cmValue(configPostfix);
  3210. } else {
  3211. outBase += configPostfix;
  3212. }
  3213. // Name shared libraries with their version number on some platforms.
  3214. if (cmValue soversion = this->GetProperty("SOVERSION")) {
  3215. cmValue dllProp;
  3216. if (this->IsDLLPlatform()) {
  3217. dllProp = this->GetProperty("DLL_NAME_WITH_SOVERSION");
  3218. }
  3219. if (this->GetType() == cmStateEnums::SHARED_LIBRARY &&
  3220. !isImportedLibraryArtifact &&
  3221. (dllProp.IsOn() ||
  3222. (!dllProp.IsSet() &&
  3223. this->Makefile->IsOn("CMAKE_SHARED_LIBRARY_NAME_WITH_VERSION")))) {
  3224. outBase += "-";
  3225. outBase += *soversion;
  3226. }
  3227. }
  3228. // Append the suffix.
  3229. outSuffix = targetSuffix ? *targetSuffix : "";
  3230. return cache.emplace(config, std::move(parts)).first->second;
  3231. }
  3232. std::string cmGeneratorTarget::GetLinkerLanguage(
  3233. const std::string& config) const
  3234. {
  3235. return this->GetLinkClosure(config)->LinkerLanguage;
  3236. }
  3237. std::string cmGeneratorTarget::GetLinkerTool(const std::string& config) const
  3238. {
  3239. return this->GetLinkerTool(this->GetLinkerLanguage(config), config);
  3240. }
  3241. std::string cmGeneratorTarget::GetLinkerTool(const std::string& lang,
  3242. const std::string& config) const
  3243. {
  3244. auto usingLinker =
  3245. cmStrCat("CMAKE_", lang, "_USING_", this->IsDeviceLink() ? "DEVICE_" : "",
  3246. "LINKER_");
  3247. auto format = this->Makefile->GetDefinition(cmStrCat(usingLinker, "MODE"));
  3248. if (!format || format != "TOOL"_s) {
  3249. return this->Makefile->GetDefinition("CMAKE_LINKER");
  3250. }
  3251. auto linkerType = this->GetLinkerTypeProperty(lang, config);
  3252. if (linkerType.empty()) {
  3253. linkerType = "DEFAULT";
  3254. }
  3255. usingLinker = cmStrCat(usingLinker, linkerType);
  3256. auto linkerTool = this->Makefile->GetDefinition(usingLinker);
  3257. if (!linkerTool) {
  3258. if (this->GetGlobalGenerator()->IsVisualStudio() &&
  3259. linkerType == "DEFAULT"_s) {
  3260. return std::string{};
  3261. }
  3262. // fall-back to generic definition
  3263. linkerTool = this->Makefile->GetDefinition("CMAKE_LINKER");
  3264. if (linkerType != "DEFAULT"_s) {
  3265. auto isCMakeLinkerType = [](const std::string& type) -> bool {
  3266. return std::all_of(type.cbegin(), type.cend(),
  3267. [](char c) { return std::isupper(c); });
  3268. };
  3269. if (isCMakeLinkerType(linkerType)) {
  3270. this->LocalGenerator->IssueMessage(
  3271. MessageType::FATAL_ERROR,
  3272. cmStrCat("LINKER_TYPE '", linkerType,
  3273. "' is unknown or not supported by this toolchain."));
  3274. } else {
  3275. this->LocalGenerator->IssueMessage(
  3276. MessageType::FATAL_ERROR,
  3277. cmStrCat("LINKER_TYPE '", linkerType,
  3278. "' is unknown. Did you forget to define the '", usingLinker,
  3279. "' variable?"));
  3280. }
  3281. }
  3282. }
  3283. return linkerTool;
  3284. }
  3285. bool cmGeneratorTarget::LinkerEnforcesNoAllowShLibUndefined(
  3286. std::string const& config) const
  3287. {
  3288. // FIXME(#25486): Account for the LINKER_TYPE target property.
  3289. // Also factor out the hard-coded list below into a platform
  3290. // information table based on the linker id.
  3291. std::string ll = this->GetLinkerLanguage(config);
  3292. std::string linkerIdVar = cmStrCat("CMAKE_", ll, "_COMPILER_LINKER_ID");
  3293. cmValue linkerId = this->Makefile->GetDefinition(linkerIdVar);
  3294. // The GNU bfd-based linker may enforce '--no-allow-shlib-undefined'
  3295. // recursively by default. The Solaris linker has similar behavior.
  3296. return linkerId && (*linkerId == "GNU" || *linkerId == "Solaris");
  3297. }
  3298. std::string cmGeneratorTarget::GetPDBOutputName(
  3299. const std::string& config) const
  3300. {
  3301. std::string base =
  3302. this->GetOutputName(config, cmStateEnums::RuntimeBinaryArtifact);
  3303. std::vector<std::string> props;
  3304. std::string configUpper = cmSystemTools::UpperCase(config);
  3305. if (!configUpper.empty()) {
  3306. // PDB_NAME_<CONFIG>
  3307. props.push_back("PDB_NAME_" + configUpper);
  3308. }
  3309. // PDB_NAME
  3310. props.emplace_back("PDB_NAME");
  3311. for (std::string const& p : props) {
  3312. if (cmValue outName = this->GetProperty(p)) {
  3313. base = *outName;
  3314. break;
  3315. }
  3316. }
  3317. return base;
  3318. }
  3319. std::string cmGeneratorTarget::GetPDBName(const std::string& config) const
  3320. {
  3321. NameComponents const& parts = this->GetFullNameInternalComponents(
  3322. config, cmStateEnums::RuntimeBinaryArtifact);
  3323. std::vector<std::string> props;
  3324. std::string configUpper = cmSystemTools::UpperCase(config);
  3325. if (!configUpper.empty()) {
  3326. // PDB_NAME_<CONFIG>
  3327. props.push_back("PDB_NAME_" + configUpper);
  3328. }
  3329. // PDB_NAME
  3330. props.emplace_back("PDB_NAME");
  3331. for (std::string const& p : props) {
  3332. if (cmValue outName = this->GetProperty(p)) {
  3333. return parts.prefix + *outName + ".pdb";
  3334. }
  3335. }
  3336. return parts.prefix + parts.base + ".pdb";
  3337. }
  3338. std::string cmGeneratorTarget::GetObjectDirectory(
  3339. std::string const& config) const
  3340. {
  3341. std::string obj_dir =
  3342. this->GlobalGenerator->ExpandCFGIntDir(this->ObjectDirectory, config);
  3343. #if defined(__APPLE__)
  3344. // Replace Xcode's placeholder for the object file directory since
  3345. // installation and export scripts need to know the real directory.
  3346. // Xcode has build-time settings (e.g. for sanitizers) that affect this,
  3347. // but we use the default here. Users that want to enable sanitizers
  3348. // will do so at the cost of object library installation and export.
  3349. cmSystemTools::ReplaceString(obj_dir, "$(OBJECT_FILE_DIR_normal:base)",
  3350. "Objects-normal");
  3351. #endif
  3352. return obj_dir;
  3353. }
  3354. void cmGeneratorTarget::GetTargetObjectNames(
  3355. std::string const& config, std::vector<std::string>& objects) const
  3356. {
  3357. std::vector<cmSourceFile const*> objectSources;
  3358. this->GetObjectSources(objectSources, config);
  3359. std::map<cmSourceFile const*, std::string> mapping;
  3360. for (cmSourceFile const* sf : objectSources) {
  3361. mapping[sf];
  3362. }
  3363. this->LocalGenerator->ComputeObjectFilenames(mapping, this);
  3364. for (cmSourceFile const* src : objectSources) {
  3365. // Find the object file name corresponding to this source file.
  3366. auto map_it = mapping.find(src);
  3367. // It must exist because we populated the mapping just above.
  3368. assert(!map_it->second.empty());
  3369. objects.push_back(map_it->second);
  3370. }
  3371. // We need to compute the relative path from the root of
  3372. // of the object directory to handle subdirectory paths
  3373. std::string rootObjectDir = this->GetObjectDirectory(config);
  3374. rootObjectDir = cmSystemTools::CollapseFullPath(rootObjectDir);
  3375. auto ispcObjects = this->GetGeneratedISPCObjects(config);
  3376. for (std::string const& output : ispcObjects) {
  3377. auto relativePathFromObjectDir = output.substr(rootObjectDir.size());
  3378. objects.push_back(relativePathFromObjectDir);
  3379. }
  3380. }
  3381. bool cmGeneratorTarget::StrictTargetComparison::operator()(
  3382. cmGeneratorTarget const* t1, cmGeneratorTarget const* t2) const
  3383. {
  3384. int nameResult = strcmp(t1->GetName().c_str(), t2->GetName().c_str());
  3385. if (nameResult == 0) {
  3386. return strcmp(
  3387. t1->GetLocalGenerator()->GetCurrentBinaryDirectory().c_str(),
  3388. t2->GetLocalGenerator()->GetCurrentBinaryDirectory().c_str()) < 0;
  3389. }
  3390. return nameResult < 0;
  3391. }
  3392. struct cmGeneratorTarget::SourceFileFlags
  3393. cmGeneratorTarget::GetTargetSourceFileFlags(const cmSourceFile* sf) const
  3394. {
  3395. struct SourceFileFlags flags;
  3396. this->ConstructSourceFileFlags();
  3397. auto si = this->SourceFlagsMap.find(sf);
  3398. if (si != this->SourceFlagsMap.end()) {
  3399. flags = si->second;
  3400. } else {
  3401. // Handle the MACOSX_PACKAGE_LOCATION property on source files that
  3402. // were not listed in one of the other lists.
  3403. if (cmValue location = sf->GetProperty("MACOSX_PACKAGE_LOCATION")) {
  3404. flags.MacFolder = location->c_str();
  3405. const bool stripResources =
  3406. this->GlobalGenerator->ShouldStripResourcePath(this->Makefile);
  3407. if (*location == "Resources") {
  3408. flags.Type = cmGeneratorTarget::SourceFileTypeResource;
  3409. if (stripResources) {
  3410. flags.MacFolder = "";
  3411. }
  3412. } else if (cmHasLiteralPrefix(*location, "Resources/")) {
  3413. flags.Type = cmGeneratorTarget::SourceFileTypeDeepResource;
  3414. if (stripResources) {
  3415. flags.MacFolder += cmStrLen("Resources/");
  3416. }
  3417. } else {
  3418. flags.Type = cmGeneratorTarget::SourceFileTypeMacContent;
  3419. }
  3420. }
  3421. }
  3422. return flags;
  3423. }
  3424. void cmGeneratorTarget::ConstructSourceFileFlags() const
  3425. {
  3426. if (this->SourceFileFlagsConstructed) {
  3427. return;
  3428. }
  3429. this->SourceFileFlagsConstructed = true;
  3430. // Process public headers to mark the source files.
  3431. if (cmValue files = this->GetProperty("PUBLIC_HEADER")) {
  3432. cmList relFiles{ *files };
  3433. for (auto const& relFile : relFiles) {
  3434. if (cmSourceFile* sf = this->Makefile->GetSource(relFile)) {
  3435. SourceFileFlags& flags = this->SourceFlagsMap[sf];
  3436. flags.MacFolder = "Headers";
  3437. flags.Type = cmGeneratorTarget::SourceFileTypePublicHeader;
  3438. }
  3439. }
  3440. }
  3441. // Process private headers after public headers so that they take
  3442. // precedence if a file is listed in both.
  3443. if (cmValue files = this->GetProperty("PRIVATE_HEADER")) {
  3444. cmList relFiles{ *files };
  3445. for (auto const& relFile : relFiles) {
  3446. if (cmSourceFile* sf = this->Makefile->GetSource(relFile)) {
  3447. SourceFileFlags& flags = this->SourceFlagsMap[sf];
  3448. flags.MacFolder = "PrivateHeaders";
  3449. flags.Type = cmGeneratorTarget::SourceFileTypePrivateHeader;
  3450. }
  3451. }
  3452. }
  3453. // Mark sources listed as resources.
  3454. if (cmValue files = this->GetProperty("RESOURCE")) {
  3455. cmList relFiles{ *files };
  3456. for (auto const& relFile : relFiles) {
  3457. if (cmSourceFile* sf = this->Makefile->GetSource(relFile)) {
  3458. SourceFileFlags& flags = this->SourceFlagsMap[sf];
  3459. flags.MacFolder = "";
  3460. if (!this->GlobalGenerator->ShouldStripResourcePath(this->Makefile)) {
  3461. flags.MacFolder = "Resources";
  3462. }
  3463. flags.Type = cmGeneratorTarget::SourceFileTypeResource;
  3464. }
  3465. }
  3466. }
  3467. }
  3468. bool cmGeneratorTarget::SetDeviceLink(bool deviceLink)
  3469. {
  3470. bool previous = this->DeviceLink;
  3471. this->DeviceLink = deviceLink;
  3472. return previous;
  3473. }
  3474. void cmGeneratorTarget::GetTargetVersion(int& major, int& minor) const
  3475. {
  3476. int patch;
  3477. this->GetTargetVersion("VERSION", major, minor, patch);
  3478. }
  3479. void cmGeneratorTarget::GetTargetVersionFallback(
  3480. const std::string& property, const std::string& fallback_property,
  3481. int& major, int& minor, int& patch) const
  3482. {
  3483. if (this->GetProperty(property)) {
  3484. this->GetTargetVersion(property, major, minor, patch);
  3485. } else {
  3486. this->GetTargetVersion(fallback_property, major, minor, patch);
  3487. }
  3488. }
  3489. void cmGeneratorTarget::GetTargetVersion(const std::string& property,
  3490. int& major, int& minor,
  3491. int& patch) const
  3492. {
  3493. // Set the default values.
  3494. major = 0;
  3495. minor = 0;
  3496. patch = 0;
  3497. assert(this->GetType() != cmStateEnums::INTERFACE_LIBRARY);
  3498. if (cmValue version = this->GetProperty(property)) {
  3499. // Try to parse the version number and store the results that were
  3500. // successfully parsed.
  3501. int parsed_major;
  3502. int parsed_minor;
  3503. int parsed_patch;
  3504. switch (sscanf(version->c_str(), "%d.%d.%d", &parsed_major, &parsed_minor,
  3505. &parsed_patch)) {
  3506. case 3:
  3507. patch = parsed_patch;
  3508. CM_FALLTHROUGH;
  3509. case 2:
  3510. minor = parsed_minor;
  3511. CM_FALLTHROUGH;
  3512. case 1:
  3513. major = parsed_major;
  3514. CM_FALLTHROUGH;
  3515. default:
  3516. break;
  3517. }
  3518. }
  3519. }
  3520. std::string cmGeneratorTarget::GetRuntimeLinkLibrary(
  3521. std::string const& lang, std::string const& config) const
  3522. {
  3523. // This is activated by the presence of a default selection whether or
  3524. // not it is overridden by a property.
  3525. cmValue runtimeLibraryDefault = this->Makefile->GetDefinition(
  3526. cmStrCat("CMAKE_", lang, "_RUNTIME_LIBRARY_DEFAULT"));
  3527. if (!cmNonempty(runtimeLibraryDefault)) {
  3528. return std::string();
  3529. }
  3530. cmValue runtimeLibraryValue =
  3531. this->Target->GetProperty(cmStrCat(lang, "_RUNTIME_LIBRARY"));
  3532. if (!runtimeLibraryValue) {
  3533. runtimeLibraryValue = runtimeLibraryDefault;
  3534. }
  3535. return cmSystemTools::UpperCase(cmGeneratorExpression::Evaluate(
  3536. *runtimeLibraryValue, this->LocalGenerator, config, this));
  3537. }
  3538. std::string cmGeneratorTarget::GetFortranModuleDirectory(
  3539. std::string const& working_dir) const
  3540. {
  3541. if (!this->FortranModuleDirectoryCreated) {
  3542. this->FortranModuleDirectory =
  3543. this->CreateFortranModuleDirectory(working_dir);
  3544. this->FortranModuleDirectoryCreated = true;
  3545. }
  3546. return this->FortranModuleDirectory;
  3547. }
  3548. bool cmGeneratorTarget::IsFortranBuildingIntrinsicModules() const
  3549. {
  3550. // ATTENTION Before 3.32 the property name was misspelled.
  3551. // Check the correct name first and than the old name.
  3552. if (cmValue prop = this->GetProperty("Fortran_BUILDING_INTRINSIC_MODULES")) {
  3553. return prop.IsOn();
  3554. }
  3555. if (cmValue prop =
  3556. this->GetProperty("Fortran_BUILDING_INSTRINSIC_MODULES")) {
  3557. return prop.IsOn();
  3558. }
  3559. return false;
  3560. }
  3561. std::string cmGeneratorTarget::CreateFortranModuleDirectory(
  3562. std::string const& working_dir) const
  3563. {
  3564. std::string mod_dir;
  3565. std::string target_mod_dir;
  3566. if (cmValue prop = this->GetProperty("Fortran_MODULE_DIRECTORY")) {
  3567. target_mod_dir = *prop;
  3568. } else {
  3569. std::string const& default_mod_dir =
  3570. this->LocalGenerator->GetCurrentBinaryDirectory();
  3571. if (default_mod_dir != working_dir) {
  3572. target_mod_dir = default_mod_dir;
  3573. }
  3574. }
  3575. cmValue moddir_flag =
  3576. this->Makefile->GetDefinition("CMAKE_Fortran_MODDIR_FLAG");
  3577. if (!target_mod_dir.empty() && moddir_flag) {
  3578. // Compute the full path to the module directory.
  3579. if (cmSystemTools::FileIsFullPath(target_mod_dir)) {
  3580. // Already a full path.
  3581. mod_dir = target_mod_dir;
  3582. } else {
  3583. // Interpret relative to the current output directory.
  3584. mod_dir = cmStrCat(this->LocalGenerator->GetCurrentBinaryDirectory(),
  3585. '/', target_mod_dir);
  3586. }
  3587. // Make sure the module output directory exists.
  3588. cmSystemTools::MakeDirectory(mod_dir);
  3589. }
  3590. return mod_dir;
  3591. }
  3592. void cmGeneratorTarget::AddISPCGeneratedHeader(std::string const& header,
  3593. std::string const& config)
  3594. {
  3595. std::string config_upper;
  3596. if (!config.empty()) {
  3597. config_upper = cmSystemTools::UpperCase(config);
  3598. }
  3599. auto iter = this->ISPCGeneratedHeaders.find(config_upper);
  3600. if (iter == this->ISPCGeneratedHeaders.end()) {
  3601. std::vector<std::string> headers;
  3602. headers.emplace_back(header);
  3603. this->ISPCGeneratedHeaders.insert({ config_upper, headers });
  3604. } else {
  3605. iter->second.emplace_back(header);
  3606. }
  3607. }
  3608. std::vector<std::string> cmGeneratorTarget::GetGeneratedISPCHeaders(
  3609. std::string const& config) const
  3610. {
  3611. std::string config_upper;
  3612. if (!config.empty()) {
  3613. config_upper = cmSystemTools::UpperCase(config);
  3614. }
  3615. auto iter = this->ISPCGeneratedHeaders.find(config_upper);
  3616. if (iter == this->ISPCGeneratedHeaders.end()) {
  3617. return std::vector<std::string>{};
  3618. }
  3619. return iter->second;
  3620. }
  3621. void cmGeneratorTarget::AddISPCGeneratedObject(std::vector<std::string>&& objs,
  3622. std::string const& config)
  3623. {
  3624. std::string config_upper;
  3625. if (!config.empty()) {
  3626. config_upper = cmSystemTools::UpperCase(config);
  3627. }
  3628. auto iter = this->ISPCGeneratedObjects.find(config_upper);
  3629. if (iter == this->ISPCGeneratedObjects.end()) {
  3630. this->ISPCGeneratedObjects.insert({ config_upper, objs });
  3631. } else {
  3632. iter->second.insert(iter->second.end(), objs.begin(), objs.end());
  3633. }
  3634. }
  3635. std::vector<std::string> cmGeneratorTarget::GetGeneratedISPCObjects(
  3636. std::string const& config) const
  3637. {
  3638. std::string config_upper;
  3639. if (!config.empty()) {
  3640. config_upper = cmSystemTools::UpperCase(config);
  3641. }
  3642. auto iter = this->ISPCGeneratedObjects.find(config_upper);
  3643. if (iter == this->ISPCGeneratedObjects.end()) {
  3644. return std::vector<std::string>{};
  3645. }
  3646. return iter->second;
  3647. }
  3648. std::string cmGeneratorTarget::GetFrameworkVersion() const
  3649. {
  3650. assert(this->GetType() != cmStateEnums::INTERFACE_LIBRARY);
  3651. if (cmValue fversion = this->GetProperty("FRAMEWORK_VERSION")) {
  3652. return *fversion;
  3653. }
  3654. if (cmValue tversion = this->GetProperty("VERSION")) {
  3655. return *tversion;
  3656. }
  3657. return "A";
  3658. }
  3659. std::string cmGeneratorTarget::ComputeVersionedName(std::string const& prefix,
  3660. std::string const& base,
  3661. std::string const& suffix,
  3662. std::string const& name,
  3663. cmValue version) const
  3664. {
  3665. std::string vName = this->IsApple() ? (prefix + base) : name;
  3666. if (version) {
  3667. vName += ".";
  3668. vName += *version;
  3669. }
  3670. vName += this->IsApple() ? suffix : std::string();
  3671. return vName;
  3672. }
  3673. std::vector<std::string> cmGeneratorTarget::GetPropertyKeys() const
  3674. {
  3675. return this->Target->GetProperties().GetKeys();
  3676. }
  3677. void cmGeneratorTarget::ReportPropertyOrigin(
  3678. const std::string& p, const std::string& result, const std::string& report,
  3679. const std::string& compatibilityType) const
  3680. {
  3681. cmList debugProperties{ this->Target->GetMakefile()->GetDefinition(
  3682. "CMAKE_DEBUG_TARGET_PROPERTIES") };
  3683. bool debugOrigin = !this->DebugCompatiblePropertiesDone[p] &&
  3684. cm::contains(debugProperties, p);
  3685. if (this->GlobalGenerator->GetConfigureDoneCMP0026()) {
  3686. this->DebugCompatiblePropertiesDone[p] = true;
  3687. }
  3688. if (!debugOrigin) {
  3689. return;
  3690. }
  3691. std::string areport =
  3692. cmStrCat(compatibilityType, " of property \"", p, "\" for target \"",
  3693. this->GetName(), "\" (result: \"", result, "\"):\n", report);
  3694. this->LocalGenerator->GetCMakeInstance()->IssueMessage(MessageType::LOG,
  3695. areport);
  3696. }
  3697. std::string cmGeneratorTarget::GetDirectory(
  3698. const std::string& config, cmStateEnums::ArtifactType artifact) const
  3699. {
  3700. if (this->IsImported()) {
  3701. auto fullPath = this->Target->ImportedGetFullPath(config, artifact);
  3702. if (this->IsFrameworkOnApple()) {
  3703. auto fwDescriptor = this->GetGlobalGenerator()->SplitFrameworkPath(
  3704. fullPath, cmGlobalGenerator::FrameworkFormat::Strict);
  3705. if (fwDescriptor) {
  3706. return fwDescriptor->Directory;
  3707. }
  3708. }
  3709. // Return the directory from which the target is imported.
  3710. return cmSystemTools::GetFilenamePath(fullPath);
  3711. }
  3712. if (OutputInfo const* info = this->GetOutputInfo(config)) {
  3713. // Return the directory in which the target will be built.
  3714. switch (artifact) {
  3715. case cmStateEnums::RuntimeBinaryArtifact:
  3716. return info->OutDir;
  3717. case cmStateEnums::ImportLibraryArtifact:
  3718. return info->ImpDir;
  3719. }
  3720. }
  3721. return "";
  3722. }
  3723. bool cmGeneratorTarget::UsesDefaultOutputDir(
  3724. const std::string& config, cmStateEnums::ArtifactType artifact) const
  3725. {
  3726. std::string dir;
  3727. return this->ComputeOutputDir(config, artifact, dir);
  3728. }
  3729. cmGeneratorTarget::OutputInfo const* cmGeneratorTarget::GetOutputInfo(
  3730. const std::string& config) const
  3731. {
  3732. // There is no output information for imported targets.
  3733. if (this->IsImported()) {
  3734. return nullptr;
  3735. }
  3736. // Synthetic targets don't have output.
  3737. if (this->IsSynthetic()) {
  3738. return nullptr;
  3739. }
  3740. // Only libraries and executables have well-defined output files.
  3741. if (!this->HaveWellDefinedOutputFiles()) {
  3742. std::string msg = cmStrCat("cmGeneratorTarget::GetOutputInfo called for ",
  3743. this->GetName(), " which has type ",
  3744. cmState::GetTargetTypeName(this->GetType()));
  3745. this->LocalGenerator->IssueMessage(MessageType::INTERNAL_ERROR, msg);
  3746. return nullptr;
  3747. }
  3748. // Lookup/compute/cache the output information for this configuration.
  3749. std::string config_upper;
  3750. if (!config.empty()) {
  3751. config_upper = cmSystemTools::UpperCase(config);
  3752. }
  3753. auto i = this->OutputInfoMap.find(config_upper);
  3754. if (i == this->OutputInfoMap.end()) {
  3755. // Add empty info in map to detect potential recursion.
  3756. OutputInfo info;
  3757. OutputInfoMapType::value_type entry(config_upper, info);
  3758. i = this->OutputInfoMap.insert(entry).first;
  3759. // Compute output directories.
  3760. this->ComputeOutputDir(config, cmStateEnums::RuntimeBinaryArtifact,
  3761. info.OutDir);
  3762. this->ComputeOutputDir(config, cmStateEnums::ImportLibraryArtifact,
  3763. info.ImpDir);
  3764. if (!this->ComputePDBOutputDir("PDB", config, info.PdbDir)) {
  3765. info.PdbDir = info.OutDir;
  3766. }
  3767. // Now update the previously-prepared map entry.
  3768. i->second = info;
  3769. } else if (i->second.empty()) {
  3770. // An empty map entry indicates we have been called recursively
  3771. // from the above block.
  3772. this->LocalGenerator->GetCMakeInstance()->IssueMessage(
  3773. MessageType::FATAL_ERROR,
  3774. "Target '" + this->GetName() + "' OUTPUT_DIRECTORY depends on itself.",
  3775. this->GetBacktrace());
  3776. return nullptr;
  3777. }
  3778. return &i->second;
  3779. }
  3780. bool cmGeneratorTarget::ComputeOutputDir(const std::string& config,
  3781. cmStateEnums::ArtifactType artifact,
  3782. std::string& out) const
  3783. {
  3784. bool usesDefaultOutputDir = false;
  3785. std::string conf = config;
  3786. // Look for a target property defining the target output directory
  3787. // based on the target type.
  3788. std::string targetTypeName = this->GetOutputTargetType(artifact);
  3789. std::string propertyName;
  3790. if (!targetTypeName.empty()) {
  3791. propertyName = cmStrCat(targetTypeName, "_OUTPUT_DIRECTORY");
  3792. }
  3793. // Check for a per-configuration output directory target property.
  3794. std::string configUpper = cmSystemTools::UpperCase(conf);
  3795. std::string configProp;
  3796. if (!targetTypeName.empty()) {
  3797. configProp = cmStrCat(targetTypeName, "_OUTPUT_DIRECTORY_", configUpper);
  3798. }
  3799. // Select an output directory.
  3800. if (cmValue config_outdir = this->GetProperty(configProp)) {
  3801. // Use the user-specified per-configuration output directory.
  3802. out = cmGeneratorExpression::Evaluate(*config_outdir, this->LocalGenerator,
  3803. config, this);
  3804. // Skip per-configuration subdirectory.
  3805. conf.clear();
  3806. } else if (cmValue outdir = this->GetProperty(propertyName)) {
  3807. // Use the user-specified output directory.
  3808. out = cmGeneratorExpression::Evaluate(*outdir, this->LocalGenerator,
  3809. config, this);
  3810. // Skip per-configuration subdirectory if the value contained a
  3811. // generator expression.
  3812. if (out != *outdir) {
  3813. conf.clear();
  3814. }
  3815. } else if (this->GetType() == cmStateEnums::EXECUTABLE) {
  3816. // Lookup the output path for executables.
  3817. out = this->Makefile->GetSafeDefinition("EXECUTABLE_OUTPUT_PATH");
  3818. } else if (this->GetType() == cmStateEnums::STATIC_LIBRARY ||
  3819. this->GetType() == cmStateEnums::SHARED_LIBRARY ||
  3820. this->GetType() == cmStateEnums::MODULE_LIBRARY) {
  3821. // Lookup the output path for libraries.
  3822. out = this->Makefile->GetSafeDefinition("LIBRARY_OUTPUT_PATH");
  3823. }
  3824. if (out.empty()) {
  3825. // Default to the current output directory.
  3826. usesDefaultOutputDir = true;
  3827. out = ".";
  3828. }
  3829. // Convert the output path to a full path in case it is
  3830. // specified as a relative path. Treat a relative path as
  3831. // relative to the current output directory for this makefile.
  3832. out = (cmSystemTools::CollapseFullPath(
  3833. out, this->LocalGenerator->GetCurrentBinaryDirectory()));
  3834. // The generator may add the configuration's subdirectory.
  3835. if (!conf.empty()) {
  3836. bool useEPN =
  3837. this->GlobalGenerator->UseEffectivePlatformName(this->Makefile);
  3838. std::string suffix =
  3839. usesDefaultOutputDir && useEPN ? "${EFFECTIVE_PLATFORM_NAME}" : "";
  3840. this->LocalGenerator->GetGlobalGenerator()->AppendDirectoryForConfig(
  3841. "/", conf, suffix, out);
  3842. }
  3843. return usesDefaultOutputDir;
  3844. }
  3845. bool cmGeneratorTarget::ComputePDBOutputDir(const std::string& kind,
  3846. const std::string& config,
  3847. std::string& out) const
  3848. {
  3849. // Look for a target property defining the target output directory
  3850. // based on the target type.
  3851. std::string propertyName;
  3852. if (!kind.empty()) {
  3853. propertyName = cmStrCat(kind, "_OUTPUT_DIRECTORY");
  3854. }
  3855. std::string conf = config;
  3856. // Check for a per-configuration output directory target property.
  3857. std::string configUpper = cmSystemTools::UpperCase(conf);
  3858. std::string configProp;
  3859. if (!kind.empty()) {
  3860. configProp = cmStrCat(kind, "_OUTPUT_DIRECTORY_", configUpper);
  3861. }
  3862. // Select an output directory.
  3863. if (cmValue config_outdir = this->GetProperty(configProp)) {
  3864. // Use the user-specified per-configuration output directory.
  3865. out = cmGeneratorExpression::Evaluate(*config_outdir, this->LocalGenerator,
  3866. config);
  3867. // Skip per-configuration subdirectory.
  3868. conf.clear();
  3869. } else if (cmValue outdir = this->GetProperty(propertyName)) {
  3870. // Use the user-specified output directory.
  3871. out =
  3872. cmGeneratorExpression::Evaluate(*outdir, this->LocalGenerator, config);
  3873. // Skip per-configuration subdirectory if the value contained a
  3874. // generator expression.
  3875. if (out != *outdir) {
  3876. conf.clear();
  3877. }
  3878. }
  3879. if (out.empty()) {
  3880. return false;
  3881. }
  3882. // Convert the output path to a full path in case it is
  3883. // specified as a relative path. Treat a relative path as
  3884. // relative to the current output directory for this makefile.
  3885. out = (cmSystemTools::CollapseFullPath(
  3886. out, this->LocalGenerator->GetCurrentBinaryDirectory()));
  3887. // The generator may add the configuration's subdirectory.
  3888. if (!conf.empty()) {
  3889. this->LocalGenerator->GetGlobalGenerator()->AppendDirectoryForConfig(
  3890. "/", conf, "", out);
  3891. }
  3892. return true;
  3893. }
  3894. bool cmGeneratorTarget::HaveInstallTreeRPATH(const std::string& config) const
  3895. {
  3896. std::string install_rpath;
  3897. this->GetInstallRPATH(config, install_rpath);
  3898. return !install_rpath.empty() &&
  3899. !this->Makefile->IsOn("CMAKE_SKIP_INSTALL_RPATH");
  3900. }
  3901. bool cmGeneratorTarget::GetBuildRPATH(const std::string& config,
  3902. std::string& rpath) const
  3903. {
  3904. return this->GetRPATH(config, "BUILD_RPATH", rpath);
  3905. }
  3906. bool cmGeneratorTarget::GetInstallRPATH(const std::string& config,
  3907. std::string& rpath) const
  3908. {
  3909. return this->GetRPATH(config, "INSTALL_RPATH", rpath);
  3910. }
  3911. bool cmGeneratorTarget::GetRPATH(const std::string& config,
  3912. const std::string& prop,
  3913. std::string& rpath) const
  3914. {
  3915. cmValue value = this->GetProperty(prop);
  3916. if (!value) {
  3917. return false;
  3918. }
  3919. rpath =
  3920. cmGeneratorExpression::Evaluate(*value, this->LocalGenerator, config);
  3921. return true;
  3922. }
  3923. cmGeneratorTarget::ImportInfo const* cmGeneratorTarget::GetImportInfo(
  3924. const std::string& config) const
  3925. {
  3926. // There is no imported information for non-imported targets.
  3927. if (!this->IsImported()) {
  3928. return nullptr;
  3929. }
  3930. // Lookup/compute/cache the import information for this
  3931. // configuration.
  3932. std::string config_upper;
  3933. if (!config.empty()) {
  3934. config_upper = cmSystemTools::UpperCase(config);
  3935. } else {
  3936. config_upper = "NOCONFIG";
  3937. }
  3938. auto i = this->ImportInfoMap.find(config_upper);
  3939. if (i == this->ImportInfoMap.end()) {
  3940. ImportInfo info;
  3941. this->ComputeImportInfo(config_upper, info);
  3942. ImportInfoMapType::value_type entry(config_upper, info);
  3943. i = this->ImportInfoMap.insert(entry).first;
  3944. }
  3945. if (this->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
  3946. return &i->second;
  3947. }
  3948. // If the location is empty then the target is not available for
  3949. // this configuration.
  3950. if (i->second.Location.empty() && i->second.ImportLibrary.empty()) {
  3951. return nullptr;
  3952. }
  3953. // Return the import information.
  3954. return &i->second;
  3955. }
  3956. void cmGeneratorTarget::ComputeImportInfo(std::string const& desired_config,
  3957. ImportInfo& info) const
  3958. {
  3959. // This method finds information about an imported target from its
  3960. // properties. The "IMPORTED_" namespace is reserved for properties
  3961. // defined by the project exporting the target.
  3962. // Initialize members.
  3963. info.NoSOName = false;
  3964. cmValue loc = nullptr;
  3965. cmValue imp = nullptr;
  3966. std::string suffix;
  3967. if (!this->Target->GetMappedConfig(desired_config, loc, imp, suffix)) {
  3968. return;
  3969. }
  3970. // Get the link interface.
  3971. {
  3972. // Use the INTERFACE_LINK_LIBRARIES special representation directly
  3973. // to get backtraces.
  3974. cmBTStringRange entries = this->Target->GetLinkInterfaceEntries();
  3975. if (!entries.empty()) {
  3976. info.LibrariesProp = "INTERFACE_LINK_LIBRARIES";
  3977. for (BT<std::string> const& entry : entries) {
  3978. info.Libraries.emplace_back(entry);
  3979. }
  3980. } else if (this->GetType() != cmStateEnums::INTERFACE_LIBRARY) {
  3981. std::string linkProp =
  3982. cmStrCat("IMPORTED_LINK_INTERFACE_LIBRARIES", suffix);
  3983. cmValue propertyLibs = this->GetProperty(linkProp);
  3984. if (!propertyLibs) {
  3985. linkProp = "IMPORTED_LINK_INTERFACE_LIBRARIES";
  3986. propertyLibs = this->GetProperty(linkProp);
  3987. }
  3988. if (propertyLibs) {
  3989. info.LibrariesProp = linkProp;
  3990. info.Libraries.emplace_back(*propertyLibs);
  3991. }
  3992. }
  3993. }
  3994. for (BT<std::string> const& entry :
  3995. this->Target->GetLinkInterfaceDirectEntries()) {
  3996. info.LibrariesHeadInclude.emplace_back(entry);
  3997. }
  3998. for (BT<std::string> const& entry :
  3999. this->Target->GetLinkInterfaceDirectExcludeEntries()) {
  4000. info.LibrariesHeadExclude.emplace_back(entry);
  4001. }
  4002. if (this->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
  4003. if (loc) {
  4004. info.LibName = *loc;
  4005. }
  4006. return;
  4007. }
  4008. // A provided configuration has been chosen. Load the
  4009. // configuration's properties.
  4010. // Get the location.
  4011. if (loc) {
  4012. info.Location = *loc;
  4013. } else {
  4014. std::string impProp = cmStrCat("IMPORTED_LOCATION", suffix);
  4015. if (cmValue config_location = this->GetProperty(impProp)) {
  4016. info.Location = *config_location;
  4017. } else if (cmValue location = this->GetProperty("IMPORTED_LOCATION")) {
  4018. info.Location = *location;
  4019. }
  4020. }
  4021. // Get the soname.
  4022. if (this->GetType() == cmStateEnums::SHARED_LIBRARY) {
  4023. std::string soProp = cmStrCat("IMPORTED_SONAME", suffix);
  4024. if (cmValue config_soname = this->GetProperty(soProp)) {
  4025. info.SOName = *config_soname;
  4026. } else if (cmValue soname = this->GetProperty("IMPORTED_SONAME")) {
  4027. info.SOName = *soname;
  4028. }
  4029. }
  4030. // Get the "no-soname" mark.
  4031. if (this->GetType() == cmStateEnums::SHARED_LIBRARY) {
  4032. std::string soProp = cmStrCat("IMPORTED_NO_SONAME", suffix);
  4033. if (cmValue config_no_soname = this->GetProperty(soProp)) {
  4034. info.NoSOName = config_no_soname.IsOn();
  4035. } else if (cmValue no_soname = this->GetProperty("IMPORTED_NO_SONAME")) {
  4036. info.NoSOName = no_soname.IsOn();
  4037. }
  4038. }
  4039. // Get the import library.
  4040. if (imp) {
  4041. info.ImportLibrary = *imp;
  4042. } else if (this->GetType() == cmStateEnums::SHARED_LIBRARY ||
  4043. this->IsExecutableWithExports()) {
  4044. std::string impProp = cmStrCat("IMPORTED_IMPLIB", suffix);
  4045. if (cmValue config_implib = this->GetProperty(impProp)) {
  4046. info.ImportLibrary = *config_implib;
  4047. } else if (cmValue implib = this->GetProperty("IMPORTED_IMPLIB")) {
  4048. info.ImportLibrary = *implib;
  4049. }
  4050. }
  4051. // Get the link dependencies.
  4052. {
  4053. std::string linkProp =
  4054. cmStrCat("IMPORTED_LINK_DEPENDENT_LIBRARIES", suffix);
  4055. if (cmValue config_libs = this->GetProperty(linkProp)) {
  4056. info.SharedDeps = *config_libs;
  4057. } else if (cmValue libs =
  4058. this->GetProperty("IMPORTED_LINK_DEPENDENT_LIBRARIES")) {
  4059. info.SharedDeps = *libs;
  4060. }
  4061. }
  4062. // Get the link languages.
  4063. if (this->LinkLanguagePropagatesToDependents()) {
  4064. std::string linkProp =
  4065. cmStrCat("IMPORTED_LINK_INTERFACE_LANGUAGES", suffix);
  4066. if (cmValue config_libs = this->GetProperty(linkProp)) {
  4067. info.Languages = *config_libs;
  4068. } else if (cmValue libs =
  4069. this->GetProperty("IMPORTED_LINK_INTERFACE_LANGUAGES")) {
  4070. info.Languages = *libs;
  4071. }
  4072. }
  4073. // Get information if target is managed assembly.
  4074. {
  4075. std::string linkProp = "IMPORTED_COMMON_LANGUAGE_RUNTIME";
  4076. if (cmValue pc = this->GetProperty(linkProp + suffix)) {
  4077. info.Managed = this->CheckManagedType(*pc);
  4078. } else if (cmValue p = this->GetProperty(linkProp)) {
  4079. info.Managed = this->CheckManagedType(*p);
  4080. }
  4081. }
  4082. // Get the cyclic repetition count.
  4083. if (this->GetType() == cmStateEnums::STATIC_LIBRARY) {
  4084. std::string linkProp =
  4085. cmStrCat("IMPORTED_LINK_INTERFACE_MULTIPLICITY", suffix);
  4086. if (cmValue config_reps = this->GetProperty(linkProp)) {
  4087. sscanf(config_reps->c_str(), "%u", &info.Multiplicity);
  4088. } else if (cmValue reps =
  4089. this->GetProperty("IMPORTED_LINK_INTERFACE_MULTIPLICITY")) {
  4090. sscanf(reps->c_str(), "%u", &info.Multiplicity);
  4091. }
  4092. }
  4093. }
  4094. bool cmGeneratorTarget::GetConfigCommonSourceFilesForXcode(
  4095. std::vector<cmSourceFile*>& files) const
  4096. {
  4097. std::vector<std::string> const& configs =
  4098. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  4099. auto it = configs.begin();
  4100. const std::string& firstConfig = *it;
  4101. this->GetSourceFilesWithoutObjectLibraries(files, firstConfig);
  4102. for (; it != configs.end(); ++it) {
  4103. std::vector<cmSourceFile*> configFiles;
  4104. this->GetSourceFilesWithoutObjectLibraries(configFiles, *it);
  4105. if (configFiles != files) {
  4106. std::string firstConfigFiles;
  4107. const char* sep = "";
  4108. for (cmSourceFile* f : files) {
  4109. firstConfigFiles += sep;
  4110. firstConfigFiles += f->ResolveFullPath();
  4111. sep = "\n ";
  4112. }
  4113. std::string thisConfigFiles;
  4114. sep = "";
  4115. for (cmSourceFile* f : configFiles) {
  4116. thisConfigFiles += sep;
  4117. thisConfigFiles += f->ResolveFullPath();
  4118. sep = "\n ";
  4119. }
  4120. std::ostringstream e;
  4121. /* clang-format off */
  4122. e << "Target \"" << this->GetName()
  4123. << "\" has source files which vary by "
  4124. "configuration. This is not supported by the \""
  4125. << this->GlobalGenerator->GetName()
  4126. << "\" generator.\n"
  4127. "Config \"" << firstConfig << "\":\n"
  4128. " " << firstConfigFiles << "\n"
  4129. "Config \"" << *it << "\":\n"
  4130. " " << thisConfigFiles << "\n";
  4131. /* clang-format on */
  4132. this->LocalGenerator->IssueMessage(MessageType::FATAL_ERROR, e.str());
  4133. return false;
  4134. }
  4135. }
  4136. return true;
  4137. }
  4138. void cmGeneratorTarget::GetObjectLibrariesCMP0026(
  4139. std::vector<cmGeneratorTarget*>& objlibs) const
  4140. {
  4141. // At configure-time, this method can be called as part of getting the
  4142. // LOCATION property or to export() a file to be include()d. However
  4143. // there is no cmGeneratorTarget at configure-time, so search the SOURCES
  4144. // for TARGET_OBJECTS instead for backwards compatibility with OLD
  4145. // behavior of CMP0024 and CMP0026 only.
  4146. cmBTStringRange rng = this->Target->GetSourceEntries();
  4147. for (auto const& entry : rng) {
  4148. cmList files{ entry.Value };
  4149. for (auto const& li : files) {
  4150. if (cmHasLiteralPrefix(li, "$<TARGET_OBJECTS:") && li.back() == '>') {
  4151. std::string objLibName = li.substr(17, li.size() - 18);
  4152. if (cmGeneratorExpression::Find(objLibName) != std::string::npos) {
  4153. continue;
  4154. }
  4155. cmGeneratorTarget* objLib =
  4156. this->LocalGenerator->FindGeneratorTargetToUse(objLibName);
  4157. if (objLib) {
  4158. objlibs.push_back(objLib);
  4159. }
  4160. }
  4161. }
  4162. }
  4163. }
  4164. std::string cmGeneratorTarget::CheckCMP0004(std::string const& item) const
  4165. {
  4166. // Strip whitespace off the library names because we used to do this
  4167. // in case variables were expanded at generate time. We no longer
  4168. // do the expansion but users link to libraries like " ${VAR} ".
  4169. std::string lib = item;
  4170. std::string::size_type pos = lib.find_first_not_of(" \t\r\n");
  4171. if (pos != std::string::npos) {
  4172. lib = lib.substr(pos);
  4173. }
  4174. pos = lib.find_last_not_of(" \t\r\n");
  4175. if (pos != std::string::npos) {
  4176. lib = lib.substr(0, pos + 1);
  4177. }
  4178. if (lib != item) {
  4179. cmake* cm = this->LocalGenerator->GetCMakeInstance();
  4180. switch (this->GetPolicyStatusCMP0004()) {
  4181. case cmPolicies::WARN: {
  4182. std::ostringstream w;
  4183. w << cmPolicies::GetPolicyWarning(cmPolicies::CMP0004) << "\n"
  4184. << "Target \"" << this->GetName() << "\" links to item \"" << item
  4185. << "\" which has leading or trailing whitespace.";
  4186. cm->IssueMessage(MessageType::AUTHOR_WARNING, w.str(),
  4187. this->GetBacktrace());
  4188. }
  4189. CM_FALLTHROUGH;
  4190. case cmPolicies::OLD:
  4191. break;
  4192. case cmPolicies::NEW: {
  4193. std::ostringstream e;
  4194. e << "Target \"" << this->GetName() << "\" links to item \"" << item
  4195. << "\" which has leading or trailing whitespace. "
  4196. << "This is now an error according to policy CMP0004.";
  4197. cm->IssueMessage(MessageType::FATAL_ERROR, e.str(),
  4198. this->GetBacktrace());
  4199. } break;
  4200. }
  4201. }
  4202. return lib;
  4203. }
  4204. bool cmGeneratorTarget::IsDeprecated() const
  4205. {
  4206. cmValue deprecation = this->GetProperty("DEPRECATION");
  4207. return cmNonempty(deprecation);
  4208. }
  4209. std::string cmGeneratorTarget::GetDeprecation() const
  4210. {
  4211. // find DEPRECATION property
  4212. if (cmValue deprecation = this->GetProperty("DEPRECATION")) {
  4213. return *deprecation;
  4214. }
  4215. return std::string();
  4216. }
  4217. void cmGeneratorTarget::GetLanguages(std::set<std::string>& languages,
  4218. const std::string& config) const
  4219. {
  4220. // Targets that do not compile anything have no languages.
  4221. if (!this->CanCompileSources()) {
  4222. return;
  4223. }
  4224. std::vector<cmSourceFile*> sourceFiles;
  4225. this->GetSourceFiles(sourceFiles, config);
  4226. for (cmSourceFile* src : sourceFiles) {
  4227. const std::string& lang = src->GetOrDetermineLanguage();
  4228. if (!lang.empty()) {
  4229. languages.insert(lang);
  4230. }
  4231. }
  4232. std::set<cmGeneratorTarget const*> objectLibraries;
  4233. if (!this->GlobalGenerator->GetConfigureDoneCMP0026()) {
  4234. std::vector<cmGeneratorTarget*> objectTargets;
  4235. this->GetObjectLibrariesCMP0026(objectTargets);
  4236. for (cmGeneratorTarget* gt : objectTargets) {
  4237. objectLibraries.insert(gt);
  4238. }
  4239. } else {
  4240. objectLibraries = this->GetSourceObjectLibraries(config);
  4241. }
  4242. for (cmGeneratorTarget const* objLib : objectLibraries) {
  4243. objLib->GetLanguages(languages, config);
  4244. }
  4245. }
  4246. std::set<cmGeneratorTarget const*> cmGeneratorTarget::GetSourceObjectLibraries(
  4247. std::string const& config) const
  4248. {
  4249. std::set<cmGeneratorTarget const*> objectLibraries;
  4250. std::vector<cmSourceFile const*> externalObjects;
  4251. this->GetExternalObjects(externalObjects, config);
  4252. for (cmSourceFile const* extObj : externalObjects) {
  4253. std::string objLib = extObj->GetObjectLibrary();
  4254. if (cmGeneratorTarget* tgt =
  4255. this->LocalGenerator->FindGeneratorTargetToUse(objLib)) {
  4256. objectLibraries.insert(tgt);
  4257. }
  4258. }
  4259. return objectLibraries;
  4260. }
  4261. bool cmGeneratorTarget::IsLanguageUsed(std::string const& language,
  4262. std::string const& config) const
  4263. {
  4264. std::set<std::string> languages;
  4265. this->GetLanguages(languages, config);
  4266. return languages.count(language);
  4267. }
  4268. bool cmGeneratorTarget::IsCSharpOnly() const
  4269. {
  4270. // Only certain target types may compile CSharp.
  4271. if (this->GetType() != cmStateEnums::SHARED_LIBRARY &&
  4272. this->GetType() != cmStateEnums::STATIC_LIBRARY &&
  4273. this->GetType() != cmStateEnums::EXECUTABLE) {
  4274. return false;
  4275. }
  4276. std::set<std::string> languages = this->GetAllConfigCompileLanguages();
  4277. // Consider an explicit linker language property, but *not* the
  4278. // computed linker language that may depend on linked targets.
  4279. cmValue linkLang = this->GetProperty("LINKER_LANGUAGE");
  4280. if (cmNonempty(linkLang)) {
  4281. languages.insert(*linkLang);
  4282. }
  4283. return languages.size() == 1 && languages.count("CSharp") > 0;
  4284. }
  4285. bool cmGeneratorTarget::IsDotNetSdkTarget() const
  4286. {
  4287. return !this->GetProperty("DOTNET_SDK").IsEmpty();
  4288. }
  4289. void cmGeneratorTarget::ComputeLinkImplementationLanguages(
  4290. const std::string& config, cmOptionalLinkImplementation& impl) const
  4291. {
  4292. // This target needs runtime libraries for its source languages.
  4293. std::set<std::string> languages;
  4294. // Get languages used in our source files.
  4295. this->GetLanguages(languages, config);
  4296. // Copy the set of languages to the link implementation.
  4297. impl.Languages.insert(impl.Languages.begin(), languages.begin(),
  4298. languages.end());
  4299. }
  4300. bool cmGeneratorTarget::HaveBuildTreeRPATH(const std::string& config) const
  4301. {
  4302. if (this->GetPropertyAsBool("SKIP_BUILD_RPATH")) {
  4303. return false;
  4304. }
  4305. std::string build_rpath;
  4306. if (this->GetBuildRPATH(config, build_rpath)) {
  4307. return true;
  4308. }
  4309. if (cmLinkImplementationLibraries const* impl =
  4310. this->GetLinkImplementationLibraries(config, UseTo::Link)) {
  4311. return !impl->Libraries.empty();
  4312. }
  4313. return false;
  4314. }
  4315. bool cmGeneratorTarget::IsNullImpliedByLinkLibraries(
  4316. const std::string& p) const
  4317. {
  4318. return cm::contains(this->LinkImplicitNullProperties, p);
  4319. }
  4320. bool cmGeneratorTarget::ApplyCXXStdTargets()
  4321. {
  4322. cmStandardLevelResolver standardResolver(this->Makefile);
  4323. cmStandardLevel const cxxStd23 =
  4324. *standardResolver.LanguageStandardLevel("CXX", "23");
  4325. std::vector<std::string> const& configs =
  4326. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  4327. auto std_prop = this->GetProperty("CXX_MODULE_STD");
  4328. if (!std_prop) {
  4329. // TODO(cxxmodules): Add a target policy to flip the default here. Set
  4330. // `std_prop` based on it.
  4331. return true;
  4332. }
  4333. std::string std_prop_value;
  4334. if (std_prop) {
  4335. // Evaluate generator expressions.
  4336. cmGeneratorExpression ge(*this->LocalGenerator->GetCMakeInstance());
  4337. auto cge = ge.Parse(*std_prop);
  4338. if (!cge) {
  4339. this->Makefile->IssueMessage(
  4340. MessageType::FATAL_ERROR,
  4341. cmStrCat(R"(The "CXX_MODULE_STD" property on the target ")",
  4342. this->GetName(), "\" is not a valid generator expression."));
  4343. return false;
  4344. }
  4345. // But do not allow context-sensitive queries. Whether a target uses
  4346. // `import std` should not depend on configuration or properties of the
  4347. // consumer (head target). The link language also shouldn't matter, so ban
  4348. // it as well.
  4349. if (cge->GetHadHeadSensitiveCondition()) {
  4350. // Not reachable; all target-sensitive genexes actually fail to parse.
  4351. this->Makefile->IssueMessage(
  4352. MessageType::FATAL_ERROR,
  4353. cmStrCat(R"(The "CXX_MODULE_STD" property on the target ")",
  4354. this->GetName(),
  4355. "\" contains a condition that queries the "
  4356. "consuming target which is not supported."));
  4357. return false;
  4358. }
  4359. if (cge->GetHadLinkLanguageSensitiveCondition()) {
  4360. // Not reachable; all link language genexes actually fail to parse.
  4361. this->Makefile->IssueMessage(
  4362. MessageType::FATAL_ERROR,
  4363. cmStrCat(R"(The "CXX_MODULE_STD" property on the target ")",
  4364. this->GetName(),
  4365. "\" contains a condition that queries the "
  4366. "link language which is not supported."));
  4367. return false;
  4368. }
  4369. std_prop_value = cge->Evaluate(this->LocalGenerator, "");
  4370. if (cge->GetHadContextSensitiveCondition()) {
  4371. this->Makefile->IssueMessage(
  4372. MessageType::FATAL_ERROR,
  4373. cmStrCat(R"(The "CXX_MODULE_STD" property on the target ")",
  4374. this->GetName(),
  4375. "\" contains a context-sensitive condition "
  4376. "that is not supported."));
  4377. return false;
  4378. }
  4379. }
  4380. auto use_std = cmIsOn(std_prop_value);
  4381. // If we have a value and it is not true, there's nothing to do.
  4382. if (std_prop && !use_std) {
  4383. return true;
  4384. }
  4385. for (auto const& config : configs) {
  4386. if (this->HaveCxxModuleSupport(config) != Cxx20SupportLevel::Supported) {
  4387. continue;
  4388. }
  4389. cm::optional<cmStandardLevel> explicitLevel =
  4390. this->GetExplicitStandardLevel("CXX", config);
  4391. if (!explicitLevel || *explicitLevel < cxxStd23) {
  4392. continue;
  4393. }
  4394. auto const stdLevel =
  4395. standardResolver.GetLevelString("CXX", *explicitLevel);
  4396. auto const targetName = cmStrCat("__CMAKE::CXX", stdLevel);
  4397. if (!this->Makefile->FindTargetToUse(targetName)) {
  4398. auto basicReason = this->Makefile->GetDefinition(cmStrCat(
  4399. "CMAKE_CXX", stdLevel, "_COMPILER_IMPORT_STD_NOT_FOUND_MESSAGE"));
  4400. std::string reason;
  4401. if (!basicReason.IsEmpty()) {
  4402. reason = cmStrCat(" Reason:\n ", basicReason);
  4403. }
  4404. this->Makefile->IssueMessage(
  4405. MessageType::FATAL_ERROR,
  4406. cmStrCat(R"(The "CXX_MODULE_STD" property on the target ")",
  4407. this->GetName(), "\" requires that the \"", targetName,
  4408. "\" target exist, but it was not provided by the toolchain.",
  4409. reason));
  4410. break;
  4411. }
  4412. // Check the experimental feature here as well. A toolchain may have
  4413. // provided the target and skipped the check in the toolchain preparation
  4414. // logic.
  4415. if (!cmExperimental::HasSupportEnabled(
  4416. *this->Makefile, cmExperimental::Feature::CxxImportStd)) {
  4417. break;
  4418. }
  4419. this->Target->AppendProperty(
  4420. "LINK_LIBRARIES",
  4421. cmStrCat("$<BUILD_LOCAL_INTERFACE:$<$<CONFIG:", config, ">:", targetName,
  4422. ">>"));
  4423. }
  4424. return true;
  4425. }
  4426. bool cmGeneratorTarget::DiscoverSyntheticTargets(cmSyntheticTargetCache& cache,
  4427. std::string const& config)
  4428. {
  4429. std::vector<std::string> allConfigs =
  4430. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  4431. cmOptionalLinkImplementation impl;
  4432. this->ComputeLinkImplementationLibraries(config, impl, this, UseTo::Link);
  4433. cmCxxModuleUsageEffects usage(this);
  4434. auto& SyntheticDeps = this->Configs[config].SyntheticDeps;
  4435. for (auto const& entry : impl.Libraries) {
  4436. auto const* gt = entry.Target;
  4437. if (!gt || !gt->IsImported()) {
  4438. continue;
  4439. }
  4440. if (gt->HaveCxx20ModuleSources()) {
  4441. cmCryptoHash hasher(cmCryptoHash::AlgoSHA3_512);
  4442. constexpr size_t HASH_TRUNCATION = 12;
  4443. auto dirhash = hasher.HashString(
  4444. gt->GetLocalGenerator()->GetCurrentBinaryDirectory());
  4445. std::string safeName = gt->GetName();
  4446. cmSystemTools::ReplaceString(safeName, ":", "_");
  4447. auto targetIdent =
  4448. hasher.HashString(cmStrCat("@d_", dirhash, "@u_", usage.GetHash()));
  4449. std::string targetName =
  4450. cmStrCat(safeName, "@synth_", targetIdent.substr(0, HASH_TRUNCATION));
  4451. // Check the cache to see if this instance of the imported target has
  4452. // already been created.
  4453. auto cached = cache.CxxModuleTargets.find(targetName);
  4454. cmGeneratorTarget const* synthDep = nullptr;
  4455. if (cached == cache.CxxModuleTargets.end()) {
  4456. auto const* model = gt->Target;
  4457. auto* mf = gt->Makefile;
  4458. auto* lg = gt->GetLocalGenerator();
  4459. auto* tgt = mf->AddSynthesizedTarget(cmStateEnums::INTERFACE_LIBRARY,
  4460. targetName);
  4461. // Copy relevant information from the existing IMPORTED target.
  4462. // Copy policies to the target.
  4463. tgt->CopyPolicyStatuses(model);
  4464. // Copy file sets.
  4465. {
  4466. auto fsNames = model->GetAllFileSetNames();
  4467. for (auto const& fsName : fsNames) {
  4468. auto const* fs = model->GetFileSet(fsName);
  4469. if (!fs) {
  4470. mf->IssueMessage(MessageType::INTERNAL_ERROR,
  4471. cmStrCat("Failed to find file set named '",
  4472. fsName, "' on target '",
  4473. tgt->GetName(), '\''));
  4474. continue;
  4475. }
  4476. auto* newFs = tgt
  4477. ->GetOrCreateFileSet(fs->GetName(), fs->GetType(),
  4478. fs->GetVisibility())
  4479. .first;
  4480. newFs->CopyEntries(fs);
  4481. }
  4482. }
  4483. // Copy imported C++ module properties.
  4484. tgt->CopyImportedCxxModulesEntries(model);
  4485. // Copy other properties which may affect the C++ module BMI
  4486. // generation.
  4487. tgt->CopyImportedCxxModulesProperties(model);
  4488. tgt->AddLinkLibrary(*mf,
  4489. cmStrCat("$<COMPILE_ONLY:", model->GetName(), '>'),
  4490. GENERAL_LibraryType);
  4491. // Apply usage requirements to the target.
  4492. usage.ApplyToTarget(tgt);
  4493. // Create the generator target and attach it to the local generator.
  4494. auto gtp = cm::make_unique<cmGeneratorTarget>(tgt, lg);
  4495. synthDep = gtp.get();
  4496. cache.CxxModuleTargets[targetName] = synthDep;
  4497. // See `localGen->ComputeTargetCompileFeatures()` call in
  4498. // `cmGlobalGenerator::Compute` for where non-synthetic targets resolve
  4499. // this.
  4500. for (auto const& innerConfig : allConfigs) {
  4501. gtp->ComputeCompileFeatures(innerConfig);
  4502. }
  4503. // See `cmGlobalGenerator::ApplyCXXStdTargets` in
  4504. // `cmGlobalGenerator::Compute` for non-synthetic target resolutions.
  4505. gtp->ApplyCXXStdTargets();
  4506. gtp->DiscoverSyntheticTargets(cache, config);
  4507. lg->AddGeneratorTarget(std::move(gtp));
  4508. } else {
  4509. synthDep = cached->second;
  4510. }
  4511. SyntheticDeps[gt].push_back(synthDep);
  4512. }
  4513. }
  4514. return true;
  4515. }
  4516. bool cmGeneratorTarget::HasPackageReferences() const
  4517. {
  4518. return this->IsInBuildSystem() &&
  4519. !this->GetProperty("VS_PACKAGE_REFERENCES")->empty();
  4520. }
  4521. std::vector<std::string> cmGeneratorTarget::GetPackageReferences() const
  4522. {
  4523. cmList packageReferences;
  4524. if (this->IsInBuildSystem()) {
  4525. if (cmValue vsPackageReferences =
  4526. this->GetProperty("VS_PACKAGE_REFERENCES")) {
  4527. packageReferences.assign(*vsPackageReferences);
  4528. }
  4529. }
  4530. return std::move(packageReferences.data());
  4531. }
  4532. std::string cmGeneratorTarget::GetPDBDirectory(const std::string& config) const
  4533. {
  4534. if (OutputInfo const* info = this->GetOutputInfo(config)) {
  4535. // Return the directory in which the target will be built.
  4536. return info->PdbDir;
  4537. }
  4538. return "";
  4539. }
  4540. bool cmGeneratorTarget::HasImplibGNUtoMS(std::string const& config) const
  4541. {
  4542. return this->HasImportLibrary(config) && this->GetPropertyAsBool("GNUtoMS");
  4543. }
  4544. bool cmGeneratorTarget::GetImplibGNUtoMS(std::string const& config,
  4545. std::string const& gnuName,
  4546. std::string& out,
  4547. const char* newExt) const
  4548. {
  4549. if (this->HasImplibGNUtoMS(config) && gnuName.size() > 6 &&
  4550. gnuName.substr(gnuName.size() - 6) == ".dll.a") {
  4551. out = cmStrCat(cm::string_view(gnuName).substr(0, gnuName.size() - 6),
  4552. newExt ? newExt : ".lib");
  4553. return true;
  4554. }
  4555. return false;
  4556. }
  4557. bool cmGeneratorTarget::HasContextDependentSources() const
  4558. {
  4559. return this->SourcesAreContextDependent == Tribool::True;
  4560. }
  4561. bool cmGeneratorTarget::IsExecutableWithExports() const
  4562. {
  4563. return this->Target->IsExecutableWithExports();
  4564. }
  4565. bool cmGeneratorTarget::IsSharedLibraryWithExports() const
  4566. {
  4567. return this->Target->IsSharedLibraryWithExports();
  4568. }
  4569. bool cmGeneratorTarget::HasImportLibrary(std::string const& config) const
  4570. {
  4571. bool generate_Stubs = true;
  4572. if (this->GetGlobalGenerator()->IsXcode()) {
  4573. // take care of CMAKE_XCODE_ATTRIBUTE_GENERATE_TEXT_BASED_STUBS variable
  4574. // as well as XCODE_ATTRIBUTE_GENERATE_TEXT_BASED_STUBS property
  4575. if (cmValue propGenStubs =
  4576. this->GetProperty("XCODE_ATTRIBUTE_GENERATE_TEXT_BASED_STUBS")) {
  4577. generate_Stubs = propGenStubs == "YES";
  4578. } else if (cmValue varGenStubs = this->Makefile->GetDefinition(
  4579. "CMAKE_XCODE_ATTRIBUTE_GENERATE_TEXT_BASED_STUBS")) {
  4580. generate_Stubs = varGenStubs == "YES";
  4581. }
  4582. }
  4583. return (this->IsDLLPlatform() &&
  4584. (this->GetType() == cmStateEnums::SHARED_LIBRARY ||
  4585. this->IsExecutableWithExports()) &&
  4586. // Assemblies which have only managed code do not have
  4587. // import libraries.
  4588. this->GetManagedType(config) != ManagedType::Managed) ||
  4589. (this->IsAIX() && this->IsExecutableWithExports()) ||
  4590. (this->Makefile->PlatformSupportsAppleTextStubs() &&
  4591. this->IsSharedLibraryWithExports() && generate_Stubs);
  4592. }
  4593. bool cmGeneratorTarget::NeedImportLibraryName(std::string const& config) const
  4594. {
  4595. return this->HasImportLibrary(config) ||
  4596. // On DLL platforms we always generate the import library name
  4597. // just in case the sources have export markup.
  4598. (this->IsDLLPlatform() &&
  4599. (this->GetType() == cmStateEnums::EXECUTABLE ||
  4600. this->GetType() == cmStateEnums::MODULE_LIBRARY));
  4601. }
  4602. std::string cmGeneratorTarget::GetSupportDirectory() const
  4603. {
  4604. std::string dir = cmStrCat(this->LocalGenerator->GetCurrentBinaryDirectory(),
  4605. "/CMakeFiles/", this->GetName());
  4606. #if defined(__VMS)
  4607. dir += "_dir";
  4608. #else
  4609. dir += ".dir";
  4610. #endif
  4611. return dir;
  4612. }
  4613. bool cmGeneratorTarget::IsLinkable() const
  4614. {
  4615. return (this->GetType() == cmStateEnums::STATIC_LIBRARY ||
  4616. this->GetType() == cmStateEnums::SHARED_LIBRARY ||
  4617. this->GetType() == cmStateEnums::MODULE_LIBRARY ||
  4618. this->GetType() == cmStateEnums::UNKNOWN_LIBRARY ||
  4619. this->GetType() == cmStateEnums::OBJECT_LIBRARY ||
  4620. this->GetType() == cmStateEnums::INTERFACE_LIBRARY ||
  4621. this->IsExecutableWithExports());
  4622. }
  4623. bool cmGeneratorTarget::HasLinkDependencyFile(std::string const& config) const
  4624. {
  4625. if (this->GetType() != cmStateEnums::EXECUTABLE &&
  4626. this->GetType() != cmStateEnums::SHARED_LIBRARY &&
  4627. this->GetType() != cmStateEnums::MODULE_LIBRARY) {
  4628. return false;
  4629. }
  4630. if (this->Target->GetProperty("LINK_DEPENDS_NO_SHARED").IsOn()) {
  4631. // Do not use the linker dependency file because it includes shared
  4632. // libraries as well
  4633. return false;
  4634. }
  4635. const std::string depsUseLinker{ "CMAKE_LINK_DEPENDS_USE_LINKER" };
  4636. auto linkLanguage = this->GetLinkerLanguage(config);
  4637. const std::string langDepsUseLinker{ cmStrCat("CMAKE_", linkLanguage,
  4638. "_LINK_DEPENDS_USE_LINKER") };
  4639. return (!this->Makefile->IsDefinitionSet(depsUseLinker) ||
  4640. this->Makefile->IsOn(depsUseLinker)) &&
  4641. this->Makefile->IsOn(langDepsUseLinker);
  4642. }
  4643. bool cmGeneratorTarget::IsFrameworkOnApple() const
  4644. {
  4645. return this->Target->IsFrameworkOnApple();
  4646. }
  4647. bool cmGeneratorTarget::IsArchivedAIXSharedLibrary() const
  4648. {
  4649. return this->Target->IsArchivedAIXSharedLibrary();
  4650. }
  4651. bool cmGeneratorTarget::IsImportedFrameworkFolderOnApple(
  4652. const std::string& config) const
  4653. {
  4654. if (this->IsApple() && this->IsImported() &&
  4655. (this->GetType() == cmStateEnums::STATIC_LIBRARY ||
  4656. this->GetType() == cmStateEnums::SHARED_LIBRARY ||
  4657. this->GetType() == cmStateEnums::UNKNOWN_LIBRARY)) {
  4658. std::string cfg = config;
  4659. if (cfg.empty() && this->GetGlobalGenerator()->IsXcode()) {
  4660. // FIXME(#25515): Remove the need for this workaround.
  4661. // The Xcode generator queries include directories without any
  4662. // specific configuration. Pick one in case this target does
  4663. // not set either IMPORTED_LOCATION or IMPORTED_CONFIGURATIONS.
  4664. cfg =
  4665. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig)[0];
  4666. }
  4667. return cmSystemTools::IsPathToFramework(this->GetLocation(cfg));
  4668. }
  4669. return false;
  4670. }
  4671. bool cmGeneratorTarget::IsAppBundleOnApple() const
  4672. {
  4673. return this->Target->IsAppBundleOnApple();
  4674. }
  4675. bool cmGeneratorTarget::IsXCTestOnApple() const
  4676. {
  4677. return (this->IsCFBundleOnApple() && this->GetPropertyAsBool("XCTEST"));
  4678. }
  4679. bool cmGeneratorTarget::IsCFBundleOnApple() const
  4680. {
  4681. return (this->GetType() == cmStateEnums::MODULE_LIBRARY && this->IsApple() &&
  4682. this->GetPropertyAsBool("BUNDLE"));
  4683. }
  4684. cmGeneratorTarget::ManagedType cmGeneratorTarget::CheckManagedType(
  4685. std::string const& propval) const
  4686. {
  4687. // The type of the managed assembly (mixed unmanaged C++ and C++/CLI,
  4688. // or only C++/CLI) does only depend on whether the property is an empty
  4689. // string or contains any value at all. In Visual Studio generators
  4690. // this propval is prepended with /clr[:] which results in:
  4691. //
  4692. // 1. propval does not exist: no /clr flag, unmanaged target, has import
  4693. // lib
  4694. // 2. empty propval: add /clr as flag, mixed unmanaged/managed
  4695. // target, has import lib
  4696. // 3. netcore propval: add /clr:netcore as flag, mixed
  4697. // unmanaged/managed target, has import lib.
  4698. // 4. any value (safe,pure): add /clr:[propval] as flag, target with
  4699. // managed code only, no import lib
  4700. if (propval.empty() || propval == "netcore") {
  4701. return ManagedType::Mixed;
  4702. }
  4703. return ManagedType::Managed;
  4704. }
  4705. cmGeneratorTarget::ManagedType cmGeneratorTarget::GetManagedType(
  4706. const std::string& config) const
  4707. {
  4708. // Only libraries and executables can be managed targets.
  4709. if (this->GetType() > cmStateEnums::SHARED_LIBRARY) {
  4710. return ManagedType::Undefined;
  4711. }
  4712. if (this->GetType() == cmStateEnums::STATIC_LIBRARY) {
  4713. return ManagedType::Native;
  4714. }
  4715. // Check imported target.
  4716. if (this->IsImported()) {
  4717. if (cmGeneratorTarget::ImportInfo const* info =
  4718. this->GetImportInfo(config)) {
  4719. return info->Managed;
  4720. }
  4721. return ManagedType::Undefined;
  4722. }
  4723. // Check for explicitly set clr target property.
  4724. if (cmValue clr = this->GetProperty("COMMON_LANGUAGE_RUNTIME")) {
  4725. return this->CheckManagedType(*clr);
  4726. }
  4727. // C# targets are always managed. This language specific check
  4728. // is added to avoid that the COMMON_LANGUAGE_RUNTIME target property
  4729. // has to be set manually for C# targets.
  4730. return this->IsCSharpOnly() ? ManagedType::Managed : ManagedType::Native;
  4731. }
  4732. bool cmGeneratorTarget::AddHeaderSetVerification()
  4733. {
  4734. if (!this->GetPropertyAsBool("VERIFY_INTERFACE_HEADER_SETS")) {
  4735. return true;
  4736. }
  4737. if (this->GetType() != cmStateEnums::STATIC_LIBRARY &&
  4738. this->GetType() != cmStateEnums::SHARED_LIBRARY &&
  4739. this->GetType() != cmStateEnums::UNKNOWN_LIBRARY &&
  4740. this->GetType() != cmStateEnums::OBJECT_LIBRARY &&
  4741. this->GetType() != cmStateEnums::INTERFACE_LIBRARY &&
  4742. !this->IsExecutableWithExports()) {
  4743. return true;
  4744. }
  4745. auto verifyValue = this->GetProperty("INTERFACE_HEADER_SETS_TO_VERIFY");
  4746. const bool all = verifyValue.IsEmpty();
  4747. std::set<std::string> verifySet;
  4748. if (!all) {
  4749. cmList verifyList{ verifyValue };
  4750. verifySet.insert(verifyList.begin(), verifyList.end());
  4751. }
  4752. cmTarget* verifyTarget = nullptr;
  4753. cmTarget* allVerifyTarget =
  4754. this->GlobalGenerator->GetMakefiles().front()->FindTargetToUse(
  4755. "all_verify_interface_header_sets", true);
  4756. auto interfaceFileSetEntries = this->Target->GetInterfaceHeaderSetsEntries();
  4757. std::set<cmFileSet*> fileSets;
  4758. for (auto const& entry : interfaceFileSetEntries) {
  4759. for (auto const& name : cmList{ entry.Value }) {
  4760. if (all || verifySet.count(name)) {
  4761. fileSets.insert(this->Target->GetFileSet(name));
  4762. verifySet.erase(name);
  4763. }
  4764. }
  4765. }
  4766. if (!verifySet.empty()) {
  4767. this->Makefile->IssueMessage(
  4768. MessageType::FATAL_ERROR,
  4769. cmStrCat("Property INTERFACE_HEADER_SETS_TO_VERIFY of target \"",
  4770. this->GetName(),
  4771. "\" contained the following header sets that are nonexistent "
  4772. "or not INTERFACE:\n ",
  4773. cmJoin(verifySet, "\n ")));
  4774. return false;
  4775. }
  4776. cm::optional<std::set<std::string>> languages;
  4777. for (auto* fileSet : fileSets) {
  4778. auto dirCges = fileSet->CompileDirectoryEntries();
  4779. auto fileCges = fileSet->CompileFileEntries();
  4780. static auto const contextSensitive =
  4781. [](const std::unique_ptr<cmCompiledGeneratorExpression>& cge) {
  4782. return cge->GetHadContextSensitiveCondition();
  4783. };
  4784. bool dirCgesContextSensitive = false;
  4785. bool fileCgesContextSensitive = false;
  4786. std::vector<std::string> dirs;
  4787. std::map<std::string, std::vector<std::string>> filesPerDir;
  4788. bool first = true;
  4789. for (auto const& config : this->Makefile->GetGeneratorConfigs(
  4790. cmMakefile::GeneratorConfigQuery::IncludeEmptyConfig)) {
  4791. if (first || dirCgesContextSensitive) {
  4792. dirs = fileSet->EvaluateDirectoryEntries(dirCges, this->LocalGenerator,
  4793. config, this);
  4794. dirCgesContextSensitive =
  4795. std::any_of(dirCges.begin(), dirCges.end(), contextSensitive);
  4796. }
  4797. if (first || fileCgesContextSensitive) {
  4798. filesPerDir.clear();
  4799. for (auto const& fileCge : fileCges) {
  4800. fileSet->EvaluateFileEntry(dirs, filesPerDir, fileCge,
  4801. this->LocalGenerator, config, this);
  4802. if (fileCge->GetHadContextSensitiveCondition()) {
  4803. fileCgesContextSensitive = true;
  4804. }
  4805. }
  4806. }
  4807. for (auto const& files : filesPerDir) {
  4808. for (auto const& file : files.second) {
  4809. std::string filename = this->GenerateHeaderSetVerificationFile(
  4810. *this->Makefile->GetOrCreateSource(file), files.first, languages);
  4811. if (filename.empty()) {
  4812. continue;
  4813. }
  4814. if (!verifyTarget) {
  4815. {
  4816. cmMakefile::PolicyPushPop polScope(this->Makefile);
  4817. this->Makefile->SetPolicy(cmPolicies::CMP0119, cmPolicies::NEW);
  4818. verifyTarget = this->Makefile->AddLibrary(
  4819. cmStrCat(this->GetName(), "_verify_interface_header_sets"),
  4820. cmStateEnums::OBJECT_LIBRARY, {}, true);
  4821. }
  4822. verifyTarget->AddLinkLibrary(
  4823. *this->Makefile, this->GetName(),
  4824. cmTargetLinkLibraryType::GENERAL_LibraryType);
  4825. verifyTarget->SetProperty("AUTOMOC", "OFF");
  4826. verifyTarget->SetProperty("AUTORCC", "OFF");
  4827. verifyTarget->SetProperty("AUTOUIC", "OFF");
  4828. verifyTarget->SetProperty("DISABLE_PRECOMPILE_HEADERS", "ON");
  4829. verifyTarget->SetProperty("UNITY_BUILD", "OFF");
  4830. verifyTarget->SetProperty("CXX_SCAN_FOR_MODULES", "OFF");
  4831. cm::optional<std::map<std::string, cmValue>>
  4832. perConfigCompileDefinitions;
  4833. verifyTarget->FinalizeTargetConfiguration(
  4834. this->Makefile->GetCompileDefinitionsEntries(),
  4835. perConfigCompileDefinitions);
  4836. if (!allVerifyTarget) {
  4837. allVerifyTarget = this->GlobalGenerator->GetMakefiles()
  4838. .front()
  4839. ->AddNewUtilityTarget(
  4840. "all_verify_interface_header_sets", true);
  4841. }
  4842. allVerifyTarget->AddUtility(verifyTarget->GetName(), false);
  4843. }
  4844. if (fileCgesContextSensitive) {
  4845. filename = cmStrCat("$<$<CONFIG:", config, ">:", filename, ">");
  4846. }
  4847. verifyTarget->AddSource(filename);
  4848. }
  4849. }
  4850. if (!dirCgesContextSensitive && !fileCgesContextSensitive) {
  4851. break;
  4852. }
  4853. first = false;
  4854. }
  4855. }
  4856. if (verifyTarget) {
  4857. this->LocalGenerator->AddGeneratorTarget(
  4858. cm::make_unique<cmGeneratorTarget>(verifyTarget, this->LocalGenerator));
  4859. }
  4860. return true;
  4861. }
  4862. std::string cmGeneratorTarget::GenerateHeaderSetVerificationFile(
  4863. cmSourceFile& source, const std::string& dir,
  4864. cm::optional<std::set<std::string>>& languages) const
  4865. {
  4866. std::string extension;
  4867. std::string language = source.GetOrDetermineLanguage();
  4868. if (source.GetPropertyAsBool("SKIP_LINTING")) {
  4869. return std::string{};
  4870. }
  4871. if (language.empty()) {
  4872. if (!languages) {
  4873. languages.emplace();
  4874. for (auto const& tgtSource : this->GetAllConfigSources()) {
  4875. auto const& tgtSourceLanguage =
  4876. tgtSource.Source->GetOrDetermineLanguage();
  4877. if (tgtSourceLanguage == "CXX") {
  4878. languages->insert("CXX");
  4879. break; // C++ overrides everything else, so we don't need to keep
  4880. // checking.
  4881. }
  4882. if (tgtSourceLanguage == "C") {
  4883. languages->insert("C");
  4884. }
  4885. }
  4886. if (languages->empty()) {
  4887. std::vector<std::string> languagesVector;
  4888. this->GlobalGenerator->GetEnabledLanguages(languagesVector);
  4889. languages->insert(languagesVector.begin(), languagesVector.end());
  4890. }
  4891. }
  4892. if (languages->count("CXX")) {
  4893. language = "CXX";
  4894. } else if (languages->count("C")) {
  4895. language = "C";
  4896. }
  4897. }
  4898. if (language == "C") {
  4899. extension = ".c";
  4900. } else if (language == "CXX") {
  4901. extension = ".cxx";
  4902. } else {
  4903. return "";
  4904. }
  4905. std::string headerFilename = dir;
  4906. if (!headerFilename.empty()) {
  4907. headerFilename += '/';
  4908. }
  4909. headerFilename += source.GetLocation().GetName();
  4910. auto filename = cmStrCat(
  4911. this->LocalGenerator->GetCurrentBinaryDirectory(), '/', this->GetName(),
  4912. "_verify_interface_header_sets/", headerFilename, extension);
  4913. auto* verificationSource = this->Makefile->GetOrCreateSource(filename);
  4914. verificationSource->SetProperty("LANGUAGE", language);
  4915. cmSystemTools::MakeDirectory(cmSystemTools::GetFilenamePath(filename));
  4916. cmGeneratedFileStream fout(filename);
  4917. fout.SetCopyIfDifferent(true);
  4918. // The IWYU "associated" pragma tells include-what-you-use to
  4919. // consider the headerFile as part of the entire language
  4920. // unit within include-what-you-use and as a result allows
  4921. // one to get IWYU advice for headers.
  4922. // Also suppress clang-tidy include checks in generated code.
  4923. fout
  4924. << "/* NOLINTNEXTLINE(misc-header-include-cycle,misc-include-cleaner) */\n"
  4925. << "#include <" << headerFilename << "> /* IWYU pragma: associated */\n";
  4926. fout.close();
  4927. return filename;
  4928. }
  4929. std::string cmGeneratorTarget::GetImportedXcFrameworkPath(
  4930. const std::string& config) const
  4931. {
  4932. if (!(this->IsApple() && this->IsImported() &&
  4933. (this->GetType() == cmStateEnums::SHARED_LIBRARY ||
  4934. this->GetType() == cmStateEnums::STATIC_LIBRARY ||
  4935. this->GetType() == cmStateEnums::UNKNOWN_LIBRARY))) {
  4936. return {};
  4937. }
  4938. std::string desiredConfig = config;
  4939. if (config.empty()) {
  4940. desiredConfig = "NOCONFIG";
  4941. }
  4942. std::string result;
  4943. cmValue loc = nullptr;
  4944. cmValue imp = nullptr;
  4945. std::string suffix;
  4946. if (this->Target->GetMappedConfig(desiredConfig, loc, imp, suffix)) {
  4947. if (loc) {
  4948. result = *loc;
  4949. } else {
  4950. std::string impProp = cmStrCat("IMPORTED_LOCATION", suffix);
  4951. if (cmValue configLocation = this->GetProperty(impProp)) {
  4952. result = *configLocation;
  4953. } else if (cmValue location = this->GetProperty("IMPORTED_LOCATION")) {
  4954. result = *location;
  4955. }
  4956. }
  4957. if (cmSystemTools::IsPathToXcFramework(result)) {
  4958. return result;
  4959. }
  4960. }
  4961. return {};
  4962. }
  4963. bool cmGeneratorTarget::HaveFortranSources(std::string const& config) const
  4964. {
  4965. auto sources = this->GetSourceFiles(config);
  4966. bool const have_direct = std::any_of(
  4967. sources.begin(), sources.end(), [](BT<cmSourceFile*> const& sf) -> bool {
  4968. return sf.Value->GetLanguage() == "Fortran"_s;
  4969. });
  4970. bool have_via_target_objects = false;
  4971. if (!have_direct) {
  4972. auto const sourceObjectLibraries = this->GetSourceObjectLibraries(config);
  4973. have_via_target_objects =
  4974. std::any_of(sourceObjectLibraries.begin(), sourceObjectLibraries.end(),
  4975. [&config](cmGeneratorTarget const* tgt) -> bool {
  4976. return tgt->HaveFortranSources(config);
  4977. });
  4978. }
  4979. return have_direct || have_via_target_objects;
  4980. }
  4981. bool cmGeneratorTarget::HaveFortranSources() const
  4982. {
  4983. auto sources = this->GetAllConfigSources();
  4984. bool const have_direct = std::any_of(
  4985. sources.begin(), sources.end(), [](AllConfigSource const& sf) -> bool {
  4986. return sf.Source->GetLanguage() == "Fortran"_s;
  4987. });
  4988. bool have_via_target_objects = false;
  4989. if (!have_direct) {
  4990. std::vector<std::string> configs =
  4991. this->Makefile->GetGeneratorConfigs(cmMakefile::IncludeEmptyConfig);
  4992. for (auto const& config : configs) {
  4993. auto const sourceObjectLibraries =
  4994. this->GetSourceObjectLibraries(config);
  4995. have_via_target_objects =
  4996. std::any_of(sourceObjectLibraries.begin(), sourceObjectLibraries.end(),
  4997. [&config](cmGeneratorTarget const* tgt) -> bool {
  4998. return tgt->HaveFortranSources(config);
  4999. });
  5000. if (have_via_target_objects) {
  5001. break;
  5002. }
  5003. }
  5004. }
  5005. return have_direct || have_via_target_objects;
  5006. }
  5007. bool cmGeneratorTarget::HaveCxx20ModuleSources(std::string* errorMessage) const
  5008. {
  5009. auto const& fs_names = this->Target->GetAllFileSetNames();
  5010. return std::any_of(
  5011. fs_names.begin(), fs_names.end(),
  5012. [this, errorMessage](std::string const& name) -> bool {
  5013. auto const* file_set = this->Target->GetFileSet(name);
  5014. if (!file_set) {
  5015. auto message = cmStrCat("Target \"", this->Target->GetName(),
  5016. "\" is tracked to have file set \"", name,
  5017. "\", but it was not found.");
  5018. if (errorMessage) {
  5019. *errorMessage = std::move(message);
  5020. } else {
  5021. this->Makefile->IssueMessage(MessageType::INTERNAL_ERROR, message);
  5022. }
  5023. return false;
  5024. }
  5025. auto const& fs_type = file_set->GetType();
  5026. return fs_type == "CXX_MODULES"_s;
  5027. });
  5028. }
  5029. cmGeneratorTarget::Cxx20SupportLevel cmGeneratorTarget::HaveCxxModuleSupport(
  5030. std::string const& config) const
  5031. {
  5032. auto const* state = this->Makefile->GetState();
  5033. if (!state->GetLanguageEnabled("CXX")) {
  5034. return Cxx20SupportLevel::MissingCxx;
  5035. }
  5036. cmValue standardDefault =
  5037. this->Makefile->GetDefinition("CMAKE_CXX_STANDARD_DEFAULT");
  5038. if (!standardDefault || standardDefault->empty()) {
  5039. // We do not know any meaningful C++ standard levels for this compiler.
  5040. return Cxx20SupportLevel::NoCxx20;
  5041. }
  5042. cmStandardLevelResolver standardResolver(this->Makefile);
  5043. cmStandardLevel const cxxStd20 =
  5044. *standardResolver.LanguageStandardLevel("CXX", "20");
  5045. cm::optional<cmStandardLevel> explicitLevel =
  5046. this->GetExplicitStandardLevel("CXX", config);
  5047. if (!explicitLevel || *explicitLevel < cxxStd20) {
  5048. return Cxx20SupportLevel::NoCxx20;
  5049. }
  5050. cmValue scandepRule =
  5051. this->Makefile->GetDefinition("CMAKE_CXX_SCANDEP_SOURCE");
  5052. if (!scandepRule) {
  5053. return Cxx20SupportLevel::MissingRule;
  5054. }
  5055. return Cxx20SupportLevel::Supported;
  5056. }
  5057. void cmGeneratorTarget::CheckCxxModuleStatus(std::string const& config) const
  5058. {
  5059. bool haveScannableSources = false;
  5060. // Check for `CXX_MODULE*` file sets and a lack of support.
  5061. if (this->HaveCxx20ModuleSources()) {
  5062. haveScannableSources = true;
  5063. }
  5064. if (!haveScannableSources) {
  5065. // Check to see if there are regular sources that have requested scanning.
  5066. auto sources = this->GetSourceFiles(config);
  5067. for (auto const& source : sources) {
  5068. auto const* sf = source.Value;
  5069. auto const& lang = sf->GetLanguage();
  5070. if (lang != "CXX"_s) {
  5071. continue;
  5072. }
  5073. // Ignore sources which do not need dyndep.
  5074. if (this->NeedDyndepForSource(lang, config, sf)) {
  5075. haveScannableSources = true;
  5076. }
  5077. }
  5078. }
  5079. // If there isn't anything scannable, ignore it.
  5080. if (!haveScannableSources) {
  5081. return;
  5082. }
  5083. // If the generator doesn't support modules at all, error that we have
  5084. // sources that require the support.
  5085. if (!this->GetGlobalGenerator()->CheckCxxModuleSupport(
  5086. cmGlobalGenerator::CxxModuleSupportQuery::Expected)) {
  5087. this->Makefile->IssueMessage(
  5088. MessageType::FATAL_ERROR,
  5089. cmStrCat("The target named \"", this->GetName(),
  5090. "\" has C++ sources that may use modules, but modules are not "
  5091. "supported by this generator:\n ",
  5092. this->GetGlobalGenerator()->GetName(), '\n',
  5093. "Modules are supported only by Ninja, Ninja Multi-Config, "
  5094. "and Visual Studio generators for VS 17.4 and newer. "
  5095. "See the cmake-cxxmodules(7) manual for details. "
  5096. "Use the CMAKE_CXX_SCAN_FOR_MODULES variable to enable or "
  5097. "disable scanning."));
  5098. return;
  5099. }
  5100. switch (this->HaveCxxModuleSupport(config)) {
  5101. case cmGeneratorTarget::Cxx20SupportLevel::MissingCxx:
  5102. this->Makefile->IssueMessage(
  5103. MessageType::FATAL_ERROR,
  5104. cmStrCat("The target named \"", this->GetName(),
  5105. "\" has C++ sources that use modules, but the \"CXX\" "
  5106. "language has not been enabled."));
  5107. break;
  5108. case cmGeneratorTarget::Cxx20SupportLevel::NoCxx20: {
  5109. cmStandardLevelResolver standardResolver(this->Makefile);
  5110. auto effStandard =
  5111. standardResolver.GetEffectiveStandard(this, "CXX", config);
  5112. if (effStandard.empty()) {
  5113. effStandard = "; no C++ standard found";
  5114. } else {
  5115. effStandard = cmStrCat("; found \"cxx_std_", effStandard, '"');
  5116. }
  5117. this->Makefile->IssueMessage(
  5118. MessageType::FATAL_ERROR,
  5119. cmStrCat(
  5120. "The target named \"", this->GetName(),
  5121. "\" has C++ sources that use modules, but does not include "
  5122. "\"cxx_std_20\" (or newer) among its `target_compile_features`",
  5123. effStandard, '.'));
  5124. } break;
  5125. case cmGeneratorTarget::Cxx20SupportLevel::MissingRule: {
  5126. this->Makefile->IssueMessage(
  5127. MessageType::FATAL_ERROR,
  5128. cmStrCat("The target named \"", this->GetName(),
  5129. "\" has C++ sources that may use modules, but the compiler "
  5130. "does not provide a way to discover the import graph "
  5131. "dependencies. See the cmake-cxxmodules(7) manual for "
  5132. "details. Use the CMAKE_CXX_SCAN_FOR_MODULES variable to "
  5133. "enable or disable scanning."));
  5134. } break;
  5135. case cmGeneratorTarget::Cxx20SupportLevel::Supported:
  5136. // All is well.
  5137. break;
  5138. }
  5139. }
  5140. bool cmGeneratorTarget::NeedCxxModuleSupport(std::string const& lang,
  5141. std::string const& config) const
  5142. {
  5143. if (lang != "CXX"_s) {
  5144. return false;
  5145. }
  5146. return this->HaveCxxModuleSupport(config) == Cxx20SupportLevel::Supported &&
  5147. this->GetGlobalGenerator()->CheckCxxModuleSupport(
  5148. cmGlobalGenerator::CxxModuleSupportQuery::Inspect);
  5149. }
  5150. bool cmGeneratorTarget::NeedDyndep(std::string const& lang,
  5151. std::string const& config) const
  5152. {
  5153. return lang == "Fortran"_s || this->NeedCxxModuleSupport(lang, config);
  5154. }
  5155. cmFileSet const* cmGeneratorTarget::GetFileSetForSource(
  5156. std::string const& config, cmSourceFile const* sf) const
  5157. {
  5158. this->BuildFileSetInfoCache(config);
  5159. auto const& path = sf->GetFullPath();
  5160. auto const& per_config = this->Configs[config];
  5161. auto const fsit = per_config.FileSetCache.find(path);
  5162. if (fsit == per_config.FileSetCache.end()) {
  5163. return nullptr;
  5164. }
  5165. return fsit->second;
  5166. }
  5167. bool cmGeneratorTarget::NeedDyndepForSource(std::string const& lang,
  5168. std::string const& config,
  5169. cmSourceFile const* sf) const
  5170. {
  5171. // Fortran always needs to be scanned.
  5172. if (lang == "Fortran"_s) {
  5173. return true;
  5174. }
  5175. // Only C++ code needs scanned otherwise.
  5176. if (lang != "CXX"_s) {
  5177. return false;
  5178. }
  5179. // Any file in `CXX_MODULES` file sets need scanned (it being `CXX` is
  5180. // enforced elsewhere).
  5181. auto const* fs = this->GetFileSetForSource(config, sf);
  5182. if (fs && fs->GetType() == "CXX_MODULES"_s) {
  5183. return true;
  5184. }
  5185. auto targetDyndep = this->NeedCxxDyndep(config);
  5186. if (targetDyndep == CxxModuleSupport::Unavailable) {
  5187. return false;
  5188. }
  5189. auto const sfProp = sf->GetProperty("CXX_SCAN_FOR_MODULES");
  5190. if (sfProp.IsSet()) {
  5191. return sfProp.IsOn();
  5192. }
  5193. return targetDyndep == CxxModuleSupport::Enabled;
  5194. }
  5195. cmGeneratorTarget::CxxModuleSupport cmGeneratorTarget::NeedCxxDyndep(
  5196. std::string const& config) const
  5197. {
  5198. bool haveRule = false;
  5199. switch (this->HaveCxxModuleSupport(config)) {
  5200. case Cxx20SupportLevel::MissingCxx:
  5201. case Cxx20SupportLevel::NoCxx20:
  5202. return CxxModuleSupport::Unavailable;
  5203. case Cxx20SupportLevel::MissingRule:
  5204. break;
  5205. case Cxx20SupportLevel::Supported:
  5206. haveRule = true;
  5207. break;
  5208. }
  5209. bool haveGeneratorSupport =
  5210. this->GetGlobalGenerator()->CheckCxxModuleSupport(
  5211. cmGlobalGenerator::CxxModuleSupportQuery::Inspect);
  5212. auto const tgtProp = this->GetProperty("CXX_SCAN_FOR_MODULES");
  5213. if (tgtProp.IsSet()) {
  5214. return tgtProp.IsOn() ? CxxModuleSupport::Enabled
  5215. : CxxModuleSupport::Disabled;
  5216. }
  5217. CxxModuleSupport policyAnswer = CxxModuleSupport::Unavailable;
  5218. switch (this->GetPolicyStatusCMP0155()) {
  5219. case cmPolicies::WARN:
  5220. case cmPolicies::OLD:
  5221. // The OLD behavior is to not scan the source.
  5222. policyAnswer = CxxModuleSupport::Disabled;
  5223. break;
  5224. case cmPolicies::NEW:
  5225. // The NEW behavior is to scan the source if the compiler supports
  5226. // scanning and the generator supports it.
  5227. if (haveRule && haveGeneratorSupport) {
  5228. policyAnswer = CxxModuleSupport::Enabled;
  5229. } else {
  5230. policyAnswer = CxxModuleSupport::Disabled;
  5231. }
  5232. break;
  5233. }
  5234. return policyAnswer;
  5235. }
  5236. std::string cmGeneratorTarget::BuildDatabasePath(
  5237. std::string const& lang, std::string const& config) const
  5238. {
  5239. // Check to see if the target wants it.
  5240. if (!this->GetPropertyAsBool("EXPORT_BUILD_DATABASE")) {
  5241. return {};
  5242. }
  5243. if (!cmExperimental::HasSupportEnabled(
  5244. *this->Makefile, cmExperimental::Feature::ExportBuildDatabase)) {
  5245. return {};
  5246. }
  5247. // Check to see if the generator supports it.
  5248. if (!this->GetGlobalGenerator()->SupportsBuildDatabase()) {
  5249. return {};
  5250. }
  5251. if (this->GetGlobalGenerator()->IsMultiConfig()) {
  5252. return cmStrCat(this->GetSupportDirectory(), '/', config, '/', lang,
  5253. "_build_database.json");
  5254. }
  5255. return cmStrCat(this->GetSupportDirectory(), '/', lang,
  5256. "_build_database.json");
  5257. }
  5258. void cmGeneratorTarget::BuildFileSetInfoCache(std::string const& config) const
  5259. {
  5260. auto& per_config = this->Configs[config];
  5261. if (per_config.BuiltFileSetCache) {
  5262. return;
  5263. }
  5264. auto const* tgt = this->Target;
  5265. for (auto const& name : tgt->GetAllFileSetNames()) {
  5266. auto const* file_set = tgt->GetFileSet(name);
  5267. if (!file_set) {
  5268. tgt->GetMakefile()->IssueMessage(
  5269. MessageType::INTERNAL_ERROR,
  5270. cmStrCat("Target \"", tgt->GetName(),
  5271. "\" is tracked to have file set \"", name,
  5272. "\", but it was not found."));
  5273. continue;
  5274. }
  5275. auto fileEntries = file_set->CompileFileEntries();
  5276. auto directoryEntries = file_set->CompileDirectoryEntries();
  5277. auto directories = file_set->EvaluateDirectoryEntries(
  5278. directoryEntries, this->LocalGenerator, config, this);
  5279. std::map<std::string, std::vector<std::string>> files;
  5280. for (auto const& entry : fileEntries) {
  5281. file_set->EvaluateFileEntry(directories, files, entry,
  5282. this->LocalGenerator, config, this);
  5283. }
  5284. for (auto const& it : files) {
  5285. for (auto const& filename : it.second) {
  5286. auto collapsedFile = cmSystemTools::CollapseFullPath(filename);
  5287. per_config.FileSetCache[collapsedFile] = file_set;
  5288. }
  5289. }
  5290. }
  5291. per_config.BuiltFileSetCache = true;
  5292. }
  5293. std::string cmGeneratorTarget::GetSwiftModuleName() const
  5294. {
  5295. return this->GetPropertyOrDefault("Swift_MODULE_NAME", this->GetName());
  5296. }
  5297. std::string cmGeneratorTarget::GetSwiftModuleFileName() const
  5298. {
  5299. return this->GetPropertyOrDefault(
  5300. "Swift_MODULE", this->GetSwiftModuleName() + ".swiftmodule");
  5301. }
  5302. std::string cmGeneratorTarget::GetSwiftModuleDirectory(
  5303. std::string const& config) const
  5304. {
  5305. // This is like the *_OUTPUT_DIRECTORY properties except that we don't have a
  5306. // separate per-configuration target property.
  5307. //
  5308. // The property expands generator expressions. Multi-config generators append
  5309. // a per-configuration subdirectory to the specified directory unless a
  5310. // generator expression is used.
  5311. bool appendConfigDir = true;
  5312. std::string moduleDirectory;
  5313. if (cmValue value = this->GetProperty("Swift_MODULE_DIRECTORY")) {
  5314. moduleDirectory = cmGeneratorExpression::Evaluate(
  5315. *value, this->LocalGenerator, config, this);
  5316. appendConfigDir = *value == moduleDirectory;
  5317. }
  5318. if (moduleDirectory.empty()) {
  5319. moduleDirectory = this->LocalGenerator->GetCurrentBinaryDirectory();
  5320. }
  5321. if (appendConfigDir) {
  5322. this->LocalGenerator->GetGlobalGenerator()->AppendDirectoryForConfig(
  5323. "/", config, "", moduleDirectory);
  5324. }
  5325. return moduleDirectory;
  5326. }
  5327. std::string cmGeneratorTarget::GetSwiftModulePath(
  5328. std::string const& config) const
  5329. {
  5330. return this->GetSwiftModuleDirectory(config) + "/" +
  5331. this->GetSwiftModuleFileName();
  5332. }
  5333. std::string cmGeneratorTarget::GetPropertyOrDefault(
  5334. std::string const& property, std::string defaultValue) const
  5335. {
  5336. if (cmValue name = this->GetProperty(property)) {
  5337. return *name;
  5338. }
  5339. return defaultValue;
  5340. }