cmGeneratorTarget.cxx 205 KB

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