cmGeneratorTarget.cxx 180 KB

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