cmGeneratorTarget.cxx 204 KB

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