cmGeneratorTarget.cxx 197 KB

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