cmGeneratorTarget.cxx 196 KB

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