cmGeneratorTarget.cxx 196 KB

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