cmGeneratorTarget.cxx 196 KB

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