cmGeneratorTarget.cxx 206 KB

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