cmGeneratorTarget.cxx 180 KB

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