cmGeneratorTarget.cxx 207 KB

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