CodeGenModule.cpp 221 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871
  1. //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This coordinates the per-module state used while generating code.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "CodeGenModule.h"
  13. #include "CGBlocks.h"
  14. #include "CGCUDARuntime.h"
  15. #include "CGCXXABI.h"
  16. #include "CGCall.h"
  17. #include "CGDebugInfo.h"
  18. #include "CGObjCRuntime.h"
  19. #include "CGOpenCLRuntime.h"
  20. #include "CGOpenMPRuntime.h"
  21. #include "CGOpenMPRuntimeNVPTX.h"
  22. #include "CodeGenFunction.h"
  23. #include "CodeGenPGO.h"
  24. #include "ConstantEmitter.h"
  25. #include "CoverageMappingGen.h"
  26. #include "TargetInfo.h"
  27. #include "clang/AST/ASTContext.h"
  28. #include "clang/AST/CharUnits.h"
  29. #include "clang/AST/DeclCXX.h"
  30. #include "clang/AST/DeclObjC.h"
  31. #include "clang/AST/DeclTemplate.h"
  32. #include "clang/AST/Mangle.h"
  33. #include "clang/AST/RecordLayout.h"
  34. #include "clang/AST/RecursiveASTVisitor.h"
  35. #include "clang/AST/StmtVisitor.h"
  36. #include "clang/Basic/Builtins.h"
  37. #include "clang/Basic/CharInfo.h"
  38. #include "clang/Basic/CodeGenOptions.h"
  39. #include "clang/Basic/Diagnostic.h"
  40. #include "clang/Basic/Module.h"
  41. #include "clang/Basic/SourceManager.h"
  42. #include "clang/Basic/TargetInfo.h"
  43. #include "clang/Basic/Version.h"
  44. #include "clang/CodeGen/ConstantInitBuilder.h"
  45. #include "clang/Frontend/FrontendDiagnostic.h"
  46. #include "llvm/ADT/StringSwitch.h"
  47. #include "llvm/ADT/Triple.h"
  48. #include "llvm/Analysis/TargetLibraryInfo.h"
  49. #include "llvm/IR/CallingConv.h"
  50. #include "llvm/IR/DataLayout.h"
  51. #include "llvm/IR/Intrinsics.h"
  52. #include "llvm/IR/LLVMContext.h"
  53. #include "llvm/IR/Module.h"
  54. #include "llvm/IR/ProfileSummary.h"
  55. #include "llvm/ProfileData/InstrProfReader.h"
  56. #include "llvm/Support/CodeGen.h"
  57. #include "llvm/Support/ConvertUTF.h"
  58. #include "llvm/Support/ErrorHandling.h"
  59. #include "llvm/Support/MD5.h"
  60. #include "llvm/Support/TimeProfiler.h"
  61. using namespace clang;
  62. using namespace CodeGen;
  63. static llvm::cl::opt<bool> LimitedCoverage(
  64. "limited-coverage-experimental", llvm::cl::ZeroOrMore, llvm::cl::Hidden,
  65. llvm::cl::desc("Emit limited coverage mapping information (experimental)"),
  66. llvm::cl::init(false));
  67. static const char AnnotationSection[] = "llvm.metadata";
  68. static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
  69. switch (CGM.getTarget().getCXXABI().getKind()) {
  70. case TargetCXXABI::GenericAArch64:
  71. case TargetCXXABI::GenericARM:
  72. case TargetCXXABI::iOS:
  73. case TargetCXXABI::iOS64:
  74. case TargetCXXABI::WatchOS:
  75. case TargetCXXABI::GenericMIPS:
  76. case TargetCXXABI::GenericItanium:
  77. case TargetCXXABI::WebAssembly:
  78. return CreateItaniumCXXABI(CGM);
  79. case TargetCXXABI::Microsoft:
  80. return CreateMicrosoftCXXABI(CGM);
  81. }
  82. llvm_unreachable("invalid C++ ABI kind");
  83. }
  84. CodeGenModule::CodeGenModule(ASTContext &C, const HeaderSearchOptions &HSO,
  85. const PreprocessorOptions &PPO,
  86. const CodeGenOptions &CGO, llvm::Module &M,
  87. DiagnosticsEngine &diags,
  88. CoverageSourceInfo *CoverageInfo)
  89. : Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO),
  90. PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
  91. Target(C.getTargetInfo()), ABI(createCXXABI(*this)),
  92. VMContext(M.getContext()), Types(*this), VTables(*this),
  93. SanitizerMD(new SanitizerMetadata(*this)) {
  94. // Initialize the type cache.
  95. llvm::LLVMContext &LLVMContext = M.getContext();
  96. VoidTy = llvm::Type::getVoidTy(LLVMContext);
  97. Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
  98. Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
  99. Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
  100. Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
  101. HalfTy = llvm::Type::getHalfTy(LLVMContext);
  102. FloatTy = llvm::Type::getFloatTy(LLVMContext);
  103. DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
  104. PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
  105. PointerAlignInBytes =
  106. C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
  107. SizeSizeInBytes =
  108. C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity();
  109. IntAlignInBytes =
  110. C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity();
  111. IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
  112. IntPtrTy = llvm::IntegerType::get(LLVMContext,
  113. C.getTargetInfo().getMaxPointerWidth());
  114. Int8PtrTy = Int8Ty->getPointerTo(0);
  115. Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
  116. AllocaInt8PtrTy = Int8Ty->getPointerTo(
  117. M.getDataLayout().getAllocaAddrSpace());
  118. ASTAllocaAddressSpace = getTargetCodeGenInfo().getASTAllocaAddressSpace();
  119. RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
  120. if (LangOpts.ObjC)
  121. createObjCRuntime();
  122. if (LangOpts.OpenCL)
  123. createOpenCLRuntime();
  124. if (LangOpts.OpenMP)
  125. createOpenMPRuntime();
  126. if (LangOpts.CUDA)
  127. createCUDARuntime();
  128. // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
  129. if (LangOpts.Sanitize.has(SanitizerKind::Thread) ||
  130. (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
  131. TBAA.reset(new CodeGenTBAA(Context, TheModule, CodeGenOpts, getLangOpts(),
  132. getCXXABI().getMangleContext()));
  133. // If debug info or coverage generation is enabled, create the CGDebugInfo
  134. // object.
  135. if (CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo ||
  136. CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)
  137. DebugInfo.reset(new CGDebugInfo(*this));
  138. Block.GlobalUniqueCount = 0;
  139. if (C.getLangOpts().ObjC)
  140. ObjCData.reset(new ObjCEntrypoints());
  141. if (CodeGenOpts.hasProfileClangUse()) {
  142. auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
  143. CodeGenOpts.ProfileInstrumentUsePath, CodeGenOpts.ProfileRemappingFile);
  144. if (auto E = ReaderOrErr.takeError()) {
  145. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  146. "Could not read profile %0: %1");
  147. llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) {
  148. getDiags().Report(DiagID) << CodeGenOpts.ProfileInstrumentUsePath
  149. << EI.message();
  150. });
  151. } else
  152. PGOReader = std::move(ReaderOrErr.get());
  153. }
  154. // If coverage mapping generation is enabled, create the
  155. // CoverageMappingModuleGen object.
  156. if (CodeGenOpts.CoverageMapping)
  157. CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
  158. }
  159. CodeGenModule::~CodeGenModule() {}
  160. void CodeGenModule::createObjCRuntime() {
  161. // This is just isGNUFamily(), but we want to force implementors of
  162. // new ABIs to decide how best to do this.
  163. switch (LangOpts.ObjCRuntime.getKind()) {
  164. case ObjCRuntime::GNUstep:
  165. case ObjCRuntime::GCC:
  166. case ObjCRuntime::ObjFW:
  167. ObjCRuntime.reset(CreateGNUObjCRuntime(*this));
  168. return;
  169. case ObjCRuntime::FragileMacOSX:
  170. case ObjCRuntime::MacOSX:
  171. case ObjCRuntime::iOS:
  172. case ObjCRuntime::WatchOS:
  173. ObjCRuntime.reset(CreateMacObjCRuntime(*this));
  174. return;
  175. }
  176. llvm_unreachable("bad runtime kind");
  177. }
  178. void CodeGenModule::createOpenCLRuntime() {
  179. OpenCLRuntime.reset(new CGOpenCLRuntime(*this));
  180. }
  181. void CodeGenModule::createOpenMPRuntime() {
  182. // Select a specialized code generation class based on the target, if any.
  183. // If it does not exist use the default implementation.
  184. switch (getTriple().getArch()) {
  185. case llvm::Triple::nvptx:
  186. case llvm::Triple::nvptx64:
  187. assert(getLangOpts().OpenMPIsDevice &&
  188. "OpenMP NVPTX is only prepared to deal with device code.");
  189. OpenMPRuntime.reset(new CGOpenMPRuntimeNVPTX(*this));
  190. break;
  191. default:
  192. if (LangOpts.OpenMPSimd)
  193. OpenMPRuntime.reset(new CGOpenMPSIMDRuntime(*this));
  194. else
  195. OpenMPRuntime.reset(new CGOpenMPRuntime(*this));
  196. break;
  197. }
  198. }
  199. void CodeGenModule::createCUDARuntime() {
  200. CUDARuntime.reset(CreateNVCUDARuntime(*this));
  201. }
  202. void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
  203. Replacements[Name] = C;
  204. }
  205. void CodeGenModule::applyReplacements() {
  206. for (auto &I : Replacements) {
  207. StringRef MangledName = I.first();
  208. llvm::Constant *Replacement = I.second;
  209. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  210. if (!Entry)
  211. continue;
  212. auto *OldF = cast<llvm::Function>(Entry);
  213. auto *NewF = dyn_cast<llvm::Function>(Replacement);
  214. if (!NewF) {
  215. if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
  216. NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
  217. } else {
  218. auto *CE = cast<llvm::ConstantExpr>(Replacement);
  219. assert(CE->getOpcode() == llvm::Instruction::BitCast ||
  220. CE->getOpcode() == llvm::Instruction::GetElementPtr);
  221. NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
  222. }
  223. }
  224. // Replace old with new, but keep the old order.
  225. OldF->replaceAllUsesWith(Replacement);
  226. if (NewF) {
  227. NewF->removeFromParent();
  228. OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
  229. NewF);
  230. }
  231. OldF->eraseFromParent();
  232. }
  233. }
  234. void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) {
  235. GlobalValReplacements.push_back(std::make_pair(GV, C));
  236. }
  237. void CodeGenModule::applyGlobalValReplacements() {
  238. for (auto &I : GlobalValReplacements) {
  239. llvm::GlobalValue *GV = I.first;
  240. llvm::Constant *C = I.second;
  241. GV->replaceAllUsesWith(C);
  242. GV->eraseFromParent();
  243. }
  244. }
  245. // This is only used in aliases that we created and we know they have a
  246. // linear structure.
  247. static const llvm::GlobalObject *getAliasedGlobal(
  248. const llvm::GlobalIndirectSymbol &GIS) {
  249. llvm::SmallPtrSet<const llvm::GlobalIndirectSymbol*, 4> Visited;
  250. const llvm::Constant *C = &GIS;
  251. for (;;) {
  252. C = C->stripPointerCasts();
  253. if (auto *GO = dyn_cast<llvm::GlobalObject>(C))
  254. return GO;
  255. // stripPointerCasts will not walk over weak aliases.
  256. auto *GIS2 = dyn_cast<llvm::GlobalIndirectSymbol>(C);
  257. if (!GIS2)
  258. return nullptr;
  259. if (!Visited.insert(GIS2).second)
  260. return nullptr;
  261. C = GIS2->getIndirectSymbol();
  262. }
  263. }
  264. void CodeGenModule::checkAliases() {
  265. // Check if the constructed aliases are well formed. It is really unfortunate
  266. // that we have to do this in CodeGen, but we only construct mangled names
  267. // and aliases during codegen.
  268. bool Error = false;
  269. DiagnosticsEngine &Diags = getDiags();
  270. for (const GlobalDecl &GD : Aliases) {
  271. const auto *D = cast<ValueDecl>(GD.getDecl());
  272. SourceLocation Location;
  273. bool IsIFunc = D->hasAttr<IFuncAttr>();
  274. if (const Attr *A = D->getDefiningAttr())
  275. Location = A->getLocation();
  276. else
  277. llvm_unreachable("Not an alias or ifunc?");
  278. StringRef MangledName = getMangledName(GD);
  279. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  280. auto *Alias = cast<llvm::GlobalIndirectSymbol>(Entry);
  281. const llvm::GlobalValue *GV = getAliasedGlobal(*Alias);
  282. if (!GV) {
  283. Error = true;
  284. Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc;
  285. } else if (GV->isDeclaration()) {
  286. Error = true;
  287. Diags.Report(Location, diag::err_alias_to_undefined)
  288. << IsIFunc << IsIFunc;
  289. } else if (IsIFunc) {
  290. // Check resolver function type.
  291. llvm::FunctionType *FTy = dyn_cast<llvm::FunctionType>(
  292. GV->getType()->getPointerElementType());
  293. assert(FTy);
  294. if (!FTy->getReturnType()->isPointerTy())
  295. Diags.Report(Location, diag::err_ifunc_resolver_return);
  296. }
  297. llvm::Constant *Aliasee = Alias->getIndirectSymbol();
  298. llvm::GlobalValue *AliaseeGV;
  299. if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
  300. AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
  301. else
  302. AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
  303. if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
  304. StringRef AliasSection = SA->getName();
  305. if (AliasSection != AliaseeGV->getSection())
  306. Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
  307. << AliasSection << IsIFunc << IsIFunc;
  308. }
  309. // We have to handle alias to weak aliases in here. LLVM itself disallows
  310. // this since the object semantics would not match the IL one. For
  311. // compatibility with gcc we implement it by just pointing the alias
  312. // to its aliasee's aliasee. We also warn, since the user is probably
  313. // expecting the link to be weak.
  314. if (auto GA = dyn_cast<llvm::GlobalIndirectSymbol>(AliaseeGV)) {
  315. if (GA->isInterposable()) {
  316. Diags.Report(Location, diag::warn_alias_to_weak_alias)
  317. << GV->getName() << GA->getName() << IsIFunc;
  318. Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
  319. GA->getIndirectSymbol(), Alias->getType());
  320. Alias->setIndirectSymbol(Aliasee);
  321. }
  322. }
  323. }
  324. if (!Error)
  325. return;
  326. for (const GlobalDecl &GD : Aliases) {
  327. StringRef MangledName = getMangledName(GD);
  328. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  329. auto *Alias = dyn_cast<llvm::GlobalIndirectSymbol>(Entry);
  330. Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
  331. Alias->eraseFromParent();
  332. }
  333. }
  334. void CodeGenModule::clear() {
  335. DeferredDeclsToEmit.clear();
  336. if (OpenMPRuntime)
  337. OpenMPRuntime->clear();
  338. }
  339. void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags,
  340. StringRef MainFile) {
  341. if (!hasDiagnostics())
  342. return;
  343. if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
  344. if (MainFile.empty())
  345. MainFile = "<stdin>";
  346. Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
  347. } else {
  348. if (Mismatched > 0)
  349. Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched;
  350. if (Missing > 0)
  351. Diags.Report(diag::warn_profile_data_missing) << Visited << Missing;
  352. }
  353. }
  354. void CodeGenModule::Release() {
  355. EmitDeferred();
  356. EmitVTablesOpportunistically();
  357. applyGlobalValReplacements();
  358. applyReplacements();
  359. checkAliases();
  360. emitMultiVersionFunctions();
  361. EmitCXXGlobalInitFunc();
  362. EmitCXXGlobalDtorFunc();
  363. registerGlobalDtorsWithAtExit();
  364. EmitCXXThreadLocalInitFunc();
  365. if (ObjCRuntime)
  366. if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
  367. AddGlobalCtor(ObjCInitFunction);
  368. if (Context.getLangOpts().CUDA && !Context.getLangOpts().CUDAIsDevice &&
  369. CUDARuntime) {
  370. if (llvm::Function *CudaCtorFunction =
  371. CUDARuntime->makeModuleCtorFunction())
  372. AddGlobalCtor(CudaCtorFunction);
  373. }
  374. if (OpenMPRuntime) {
  375. if (llvm::Function *OpenMPRequiresDirectiveRegFun =
  376. OpenMPRuntime->emitRequiresDirectiveRegFun()) {
  377. AddGlobalCtor(OpenMPRequiresDirectiveRegFun, 0);
  378. }
  379. if (llvm::Function *OpenMPRegistrationFunction =
  380. OpenMPRuntime->emitRegistrationFunction()) {
  381. auto ComdatKey = OpenMPRegistrationFunction->hasComdat() ?
  382. OpenMPRegistrationFunction : nullptr;
  383. AddGlobalCtor(OpenMPRegistrationFunction, 0, ComdatKey);
  384. }
  385. OpenMPRuntime->clear();
  386. }
  387. if (PGOReader) {
  388. getModule().setProfileSummary(
  389. PGOReader->getSummary(/* UseCS */ false).getMD(VMContext),
  390. llvm::ProfileSummary::PSK_Instr);
  391. if (PGOStats.hasDiagnostics())
  392. PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
  393. }
  394. EmitCtorList(GlobalCtors, "llvm.global_ctors");
  395. EmitCtorList(GlobalDtors, "llvm.global_dtors");
  396. EmitGlobalAnnotations();
  397. EmitStaticExternCAliases();
  398. EmitDeferredUnusedCoverageMappings();
  399. if (CoverageMapping)
  400. CoverageMapping->emit();
  401. if (CodeGenOpts.SanitizeCfiCrossDso) {
  402. CodeGenFunction(*this).EmitCfiCheckFail();
  403. CodeGenFunction(*this).EmitCfiCheckStub();
  404. }
  405. emitAtAvailableLinkGuard();
  406. emitLLVMUsed();
  407. if (SanStats)
  408. SanStats->finish();
  409. if (CodeGenOpts.Autolink &&
  410. (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
  411. EmitModuleLinkOptions();
  412. }
  413. // On ELF we pass the dependent library specifiers directly to the linker
  414. // without manipulating them. This is in contrast to other platforms where
  415. // they are mapped to a specific linker option by the compiler. This
  416. // difference is a result of the greater variety of ELF linkers and the fact
  417. // that ELF linkers tend to handle libraries in a more complicated fashion
  418. // than on other platforms. This forces us to defer handling the dependent
  419. // libs to the linker.
  420. //
  421. // CUDA/HIP device and host libraries are different. Currently there is no
  422. // way to differentiate dependent libraries for host or device. Existing
  423. // usage of #pragma comment(lib, *) is intended for host libraries on
  424. // Windows. Therefore emit llvm.dependent-libraries only for host.
  425. if (!ELFDependentLibraries.empty() && !Context.getLangOpts().CUDAIsDevice) {
  426. auto *NMD = getModule().getOrInsertNamedMetadata("llvm.dependent-libraries");
  427. for (auto *MD : ELFDependentLibraries)
  428. NMD->addOperand(MD);
  429. }
  430. // Record mregparm value now so it is visible through rest of codegen.
  431. if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
  432. getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters",
  433. CodeGenOpts.NumRegisterParameters);
  434. if (CodeGenOpts.DwarfVersion) {
  435. // We actually want the latest version when there are conflicts.
  436. // We can change from Warning to Latest if such mode is supported.
  437. getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version",
  438. CodeGenOpts.DwarfVersion);
  439. }
  440. if (CodeGenOpts.EmitCodeView) {
  441. // Indicate that we want CodeView in the metadata.
  442. getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1);
  443. }
  444. if (CodeGenOpts.CodeViewGHash) {
  445. getModule().addModuleFlag(llvm::Module::Warning, "CodeViewGHash", 1);
  446. }
  447. if (CodeGenOpts.ControlFlowGuard) {
  448. // We want function ID tables for Control Flow Guard.
  449. getModule().addModuleFlag(llvm::Module::Warning, "cfguardtable", 1);
  450. }
  451. if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
  452. // We don't support LTO with 2 with different StrictVTablePointers
  453. // FIXME: we could support it by stripping all the information introduced
  454. // by StrictVTablePointers.
  455. getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1);
  456. llvm::Metadata *Ops[2] = {
  457. llvm::MDString::get(VMContext, "StrictVTablePointers"),
  458. llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
  459. llvm::Type::getInt32Ty(VMContext), 1))};
  460. getModule().addModuleFlag(llvm::Module::Require,
  461. "StrictVTablePointersRequirement",
  462. llvm::MDNode::get(VMContext, Ops));
  463. }
  464. if (DebugInfo)
  465. // We support a single version in the linked module. The LLVM
  466. // parser will drop debug info with a different version number
  467. // (and warn about it, too).
  468. getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
  469. llvm::DEBUG_METADATA_VERSION);
  470. // We need to record the widths of enums and wchar_t, so that we can generate
  471. // the correct build attributes in the ARM backend. wchar_size is also used by
  472. // TargetLibraryInfo.
  473. uint64_t WCharWidth =
  474. Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
  475. getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
  476. llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
  477. if ( Arch == llvm::Triple::arm
  478. || Arch == llvm::Triple::armeb
  479. || Arch == llvm::Triple::thumb
  480. || Arch == llvm::Triple::thumbeb) {
  481. // The minimum width of an enum in bytes
  482. uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
  483. getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
  484. }
  485. if (CodeGenOpts.SanitizeCfiCrossDso) {
  486. // Indicate that we want cross-DSO control flow integrity checks.
  487. getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1);
  488. }
  489. if (LangOpts.Sanitize.has(SanitizerKind::CFIICall)) {
  490. getModule().addModuleFlag(llvm::Module::Override,
  491. "CFI Canonical Jump Tables",
  492. CodeGenOpts.SanitizeCfiCanonicalJumpTables);
  493. }
  494. if (CodeGenOpts.CFProtectionReturn &&
  495. Target.checkCFProtectionReturnSupported(getDiags())) {
  496. // Indicate that we want to instrument return control flow protection.
  497. getModule().addModuleFlag(llvm::Module::Override, "cf-protection-return",
  498. 1);
  499. }
  500. if (CodeGenOpts.CFProtectionBranch &&
  501. Target.checkCFProtectionBranchSupported(getDiags())) {
  502. // Indicate that we want to instrument branch control flow protection.
  503. getModule().addModuleFlag(llvm::Module::Override, "cf-protection-branch",
  504. 1);
  505. }
  506. if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) {
  507. // Indicate whether __nvvm_reflect should be configured to flush denormal
  508. // floating point values to 0. (This corresponds to its "__CUDA_FTZ"
  509. // property.)
  510. getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz",
  511. CodeGenOpts.FlushDenorm ? 1 : 0);
  512. }
  513. // Emit OpenCL specific module metadata: OpenCL/SPIR version.
  514. if (LangOpts.OpenCL) {
  515. EmitOpenCLMetadata();
  516. // Emit SPIR version.
  517. if (getTriple().isSPIR()) {
  518. // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the
  519. // opencl.spir.version named metadata.
  520. // C++ is backwards compatible with OpenCL v2.0.
  521. auto Version = LangOpts.OpenCLCPlusPlus ? 200 : LangOpts.OpenCLVersion;
  522. llvm::Metadata *SPIRVerElts[] = {
  523. llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
  524. Int32Ty, Version / 100)),
  525. llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
  526. Int32Ty, (Version / 100 > 1) ? 0 : 2))};
  527. llvm::NamedMDNode *SPIRVerMD =
  528. TheModule.getOrInsertNamedMetadata("opencl.spir.version");
  529. llvm::LLVMContext &Ctx = TheModule.getContext();
  530. SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
  531. }
  532. }
  533. if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
  534. assert(PLevel < 3 && "Invalid PIC Level");
  535. getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel));
  536. if (Context.getLangOpts().PIE)
  537. getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel));
  538. }
  539. if (getCodeGenOpts().CodeModel.size() > 0) {
  540. unsigned CM = llvm::StringSwitch<unsigned>(getCodeGenOpts().CodeModel)
  541. .Case("tiny", llvm::CodeModel::Tiny)
  542. .Case("small", llvm::CodeModel::Small)
  543. .Case("kernel", llvm::CodeModel::Kernel)
  544. .Case("medium", llvm::CodeModel::Medium)
  545. .Case("large", llvm::CodeModel::Large)
  546. .Default(~0u);
  547. if (CM != ~0u) {
  548. llvm::CodeModel::Model codeModel = static_cast<llvm::CodeModel::Model>(CM);
  549. getModule().setCodeModel(codeModel);
  550. }
  551. }
  552. if (CodeGenOpts.NoPLT)
  553. getModule().setRtLibUseGOT();
  554. SimplifyPersonality();
  555. if (getCodeGenOpts().EmitDeclMetadata)
  556. EmitDeclMetadata();
  557. if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
  558. EmitCoverageFile();
  559. if (DebugInfo)
  560. DebugInfo->finalize();
  561. if (getCodeGenOpts().EmitVersionIdentMetadata)
  562. EmitVersionIdentMetadata();
  563. if (!getCodeGenOpts().RecordCommandLine.empty())
  564. EmitCommandLineMetadata();
  565. EmitTargetMetadata();
  566. }
  567. void CodeGenModule::EmitOpenCLMetadata() {
  568. // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the
  569. // opencl.ocl.version named metadata node.
  570. // C++ is backwards compatible with OpenCL v2.0.
  571. // FIXME: We might need to add CXX version at some point too?
  572. auto Version = LangOpts.OpenCLCPlusPlus ? 200 : LangOpts.OpenCLVersion;
  573. llvm::Metadata *OCLVerElts[] = {
  574. llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
  575. Int32Ty, Version / 100)),
  576. llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
  577. Int32Ty, (Version % 100) / 10))};
  578. llvm::NamedMDNode *OCLVerMD =
  579. TheModule.getOrInsertNamedMetadata("opencl.ocl.version");
  580. llvm::LLVMContext &Ctx = TheModule.getContext();
  581. OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
  582. }
  583. void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
  584. // Make sure that this type is translated.
  585. Types.UpdateCompletedType(TD);
  586. }
  587. void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) {
  588. // Make sure that this type is translated.
  589. Types.RefreshTypeCacheForClass(RD);
  590. }
  591. llvm::MDNode *CodeGenModule::getTBAATypeInfo(QualType QTy) {
  592. if (!TBAA)
  593. return nullptr;
  594. return TBAA->getTypeInfo(QTy);
  595. }
  596. TBAAAccessInfo CodeGenModule::getTBAAAccessInfo(QualType AccessType) {
  597. if (!TBAA)
  598. return TBAAAccessInfo();
  599. return TBAA->getAccessInfo(AccessType);
  600. }
  601. TBAAAccessInfo
  602. CodeGenModule::getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType) {
  603. if (!TBAA)
  604. return TBAAAccessInfo();
  605. return TBAA->getVTablePtrAccessInfo(VTablePtrType);
  606. }
  607. llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
  608. if (!TBAA)
  609. return nullptr;
  610. return TBAA->getTBAAStructInfo(QTy);
  611. }
  612. llvm::MDNode *CodeGenModule::getTBAABaseTypeInfo(QualType QTy) {
  613. if (!TBAA)
  614. return nullptr;
  615. return TBAA->getBaseTypeInfo(QTy);
  616. }
  617. llvm::MDNode *CodeGenModule::getTBAAAccessTagInfo(TBAAAccessInfo Info) {
  618. if (!TBAA)
  619. return nullptr;
  620. return TBAA->getAccessTagInfo(Info);
  621. }
  622. TBAAAccessInfo CodeGenModule::mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo,
  623. TBAAAccessInfo TargetInfo) {
  624. if (!TBAA)
  625. return TBAAAccessInfo();
  626. return TBAA->mergeTBAAInfoForCast(SourceInfo, TargetInfo);
  627. }
  628. TBAAAccessInfo
  629. CodeGenModule::mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA,
  630. TBAAAccessInfo InfoB) {
  631. if (!TBAA)
  632. return TBAAAccessInfo();
  633. return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB);
  634. }
  635. TBAAAccessInfo
  636. CodeGenModule::mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo,
  637. TBAAAccessInfo SrcInfo) {
  638. if (!TBAA)
  639. return TBAAAccessInfo();
  640. return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo);
  641. }
  642. void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst,
  643. TBAAAccessInfo TBAAInfo) {
  644. if (llvm::MDNode *Tag = getTBAAAccessTagInfo(TBAAInfo))
  645. Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag);
  646. }
  647. void CodeGenModule::DecorateInstructionWithInvariantGroup(
  648. llvm::Instruction *I, const CXXRecordDecl *RD) {
  649. I->setMetadata(llvm::LLVMContext::MD_invariant_group,
  650. llvm::MDNode::get(getLLVMContext(), {}));
  651. }
  652. void CodeGenModule::Error(SourceLocation loc, StringRef message) {
  653. unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
  654. getDiags().Report(Context.getFullLoc(loc), diagID) << message;
  655. }
  656. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  657. /// specified stmt yet.
  658. void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
  659. unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
  660. "cannot compile this %0 yet");
  661. std::string Msg = Type;
  662. getDiags().Report(Context.getFullLoc(S->getBeginLoc()), DiagID)
  663. << Msg << S->getSourceRange();
  664. }
  665. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  666. /// specified decl yet.
  667. void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
  668. unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
  669. "cannot compile this %0 yet");
  670. std::string Msg = Type;
  671. getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
  672. }
  673. llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
  674. return llvm::ConstantInt::get(SizeTy, size.getQuantity());
  675. }
  676. void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
  677. const NamedDecl *D) const {
  678. if (GV->hasDLLImportStorageClass())
  679. return;
  680. // Internal definitions always have default visibility.
  681. if (GV->hasLocalLinkage()) {
  682. GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
  683. return;
  684. }
  685. if (!D)
  686. return;
  687. // Set visibility for definitions, and for declarations if requested globally
  688. // or set explicitly.
  689. LinkageInfo LV = D->getLinkageAndVisibility();
  690. if (LV.isVisibilityExplicit() || getLangOpts().SetVisibilityForExternDecls ||
  691. !GV->isDeclarationForLinker())
  692. GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
  693. }
  694. static bool shouldAssumeDSOLocal(const CodeGenModule &CGM,
  695. llvm::GlobalValue *GV) {
  696. if (GV->hasLocalLinkage())
  697. return true;
  698. if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage())
  699. return true;
  700. // DLLImport explicitly marks the GV as external.
  701. if (GV->hasDLLImportStorageClass())
  702. return false;
  703. const llvm::Triple &TT = CGM.getTriple();
  704. if (TT.isWindowsGNUEnvironment()) {
  705. // In MinGW, variables without DLLImport can still be automatically
  706. // imported from a DLL by the linker; don't mark variables that
  707. // potentially could come from another DLL as DSO local.
  708. if (GV->isDeclarationForLinker() && isa<llvm::GlobalVariable>(GV) &&
  709. !GV->isThreadLocal())
  710. return false;
  711. }
  712. // On COFF, don't mark 'extern_weak' symbols as DSO local. If these symbols
  713. // remain unresolved in the link, they can be resolved to zero, which is
  714. // outside the current DSO.
  715. if (TT.isOSBinFormatCOFF() && GV->hasExternalWeakLinkage())
  716. return false;
  717. // Every other GV is local on COFF.
  718. // Make an exception for windows OS in the triple: Some firmware builds use
  719. // *-win32-macho triples. This (accidentally?) produced windows relocations
  720. // without GOT tables in older clang versions; Keep this behaviour.
  721. // FIXME: even thread local variables?
  722. if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO()))
  723. return true;
  724. // Only handle COFF and ELF for now.
  725. if (!TT.isOSBinFormatELF())
  726. return false;
  727. // If this is not an executable, don't assume anything is local.
  728. const auto &CGOpts = CGM.getCodeGenOpts();
  729. llvm::Reloc::Model RM = CGOpts.RelocationModel;
  730. const auto &LOpts = CGM.getLangOpts();
  731. if (RM != llvm::Reloc::Static && !LOpts.PIE && !LOpts.OpenMPIsDevice)
  732. return false;
  733. // A definition cannot be preempted from an executable.
  734. if (!GV->isDeclarationForLinker())
  735. return true;
  736. // Most PIC code sequences that assume that a symbol is local cannot produce a
  737. // 0 if it turns out the symbol is undefined. While this is ABI and relocation
  738. // depended, it seems worth it to handle it here.
  739. if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage())
  740. return false;
  741. // PPC has no copy relocations and cannot use a plt entry as a symbol address.
  742. llvm::Triple::ArchType Arch = TT.getArch();
  743. if (Arch == llvm::Triple::ppc || Arch == llvm::Triple::ppc64 ||
  744. Arch == llvm::Triple::ppc64le)
  745. return false;
  746. // If we can use copy relocations we can assume it is local.
  747. if (auto *Var = dyn_cast<llvm::GlobalVariable>(GV))
  748. if (!Var->isThreadLocal() &&
  749. (RM == llvm::Reloc::Static || CGOpts.PIECopyRelocations))
  750. return true;
  751. // If we can use a plt entry as the symbol address we can assume it
  752. // is local.
  753. // FIXME: This should work for PIE, but the gold linker doesn't support it.
  754. if (isa<llvm::Function>(GV) && !CGOpts.NoPLT && RM == llvm::Reloc::Static)
  755. return true;
  756. // Otherwise don't assue it is local.
  757. return false;
  758. }
  759. void CodeGenModule::setDSOLocal(llvm::GlobalValue *GV) const {
  760. GV->setDSOLocal(shouldAssumeDSOLocal(*this, GV));
  761. }
  762. void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
  763. GlobalDecl GD) const {
  764. const auto *D = dyn_cast<NamedDecl>(GD.getDecl());
  765. // C++ destructors have a few C++ ABI specific special cases.
  766. if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(D)) {
  767. getCXXABI().setCXXDestructorDLLStorage(GV, Dtor, GD.getDtorType());
  768. return;
  769. }
  770. setDLLImportDLLExport(GV, D);
  771. }
  772. void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
  773. const NamedDecl *D) const {
  774. if (D && D->isExternallyVisible()) {
  775. if (D->hasAttr<DLLImportAttr>())
  776. GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
  777. else if (D->hasAttr<DLLExportAttr>() && !GV->isDeclarationForLinker())
  778. GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
  779. }
  780. }
  781. void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
  782. GlobalDecl GD) const {
  783. setDLLImportDLLExport(GV, GD);
  784. setGVPropertiesAux(GV, dyn_cast<NamedDecl>(GD.getDecl()));
  785. }
  786. void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
  787. const NamedDecl *D) const {
  788. setDLLImportDLLExport(GV, D);
  789. setGVPropertiesAux(GV, D);
  790. }
  791. void CodeGenModule::setGVPropertiesAux(llvm::GlobalValue *GV,
  792. const NamedDecl *D) const {
  793. setGlobalVisibility(GV, D);
  794. setDSOLocal(GV);
  795. GV->setPartition(CodeGenOpts.SymbolPartition);
  796. }
  797. static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
  798. return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
  799. .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
  800. .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
  801. .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
  802. .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
  803. }
  804. static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
  805. CodeGenOptions::TLSModel M) {
  806. switch (M) {
  807. case CodeGenOptions::GeneralDynamicTLSModel:
  808. return llvm::GlobalVariable::GeneralDynamicTLSModel;
  809. case CodeGenOptions::LocalDynamicTLSModel:
  810. return llvm::GlobalVariable::LocalDynamicTLSModel;
  811. case CodeGenOptions::InitialExecTLSModel:
  812. return llvm::GlobalVariable::InitialExecTLSModel;
  813. case CodeGenOptions::LocalExecTLSModel:
  814. return llvm::GlobalVariable::LocalExecTLSModel;
  815. }
  816. llvm_unreachable("Invalid TLS model!");
  817. }
  818. void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
  819. assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
  820. llvm::GlobalValue::ThreadLocalMode TLM;
  821. TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
  822. // Override the TLS model if it is explicitly specified.
  823. if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
  824. TLM = GetLLVMTLSModel(Attr->getModel());
  825. }
  826. GV->setThreadLocalMode(TLM);
  827. }
  828. static std::string getCPUSpecificMangling(const CodeGenModule &CGM,
  829. StringRef Name) {
  830. const TargetInfo &Target = CGM.getTarget();
  831. return (Twine('.') + Twine(Target.CPUSpecificManglingCharacter(Name))).str();
  832. }
  833. static void AppendCPUSpecificCPUDispatchMangling(const CodeGenModule &CGM,
  834. const CPUSpecificAttr *Attr,
  835. unsigned CPUIndex,
  836. raw_ostream &Out) {
  837. // cpu_specific gets the current name, dispatch gets the resolver if IFunc is
  838. // supported.
  839. if (Attr)
  840. Out << getCPUSpecificMangling(CGM, Attr->getCPUName(CPUIndex)->getName());
  841. else if (CGM.getTarget().supportsIFunc())
  842. Out << ".resolver";
  843. }
  844. static void AppendTargetMangling(const CodeGenModule &CGM,
  845. const TargetAttr *Attr, raw_ostream &Out) {
  846. if (Attr->isDefaultVersion())
  847. return;
  848. Out << '.';
  849. const TargetInfo &Target = CGM.getTarget();
  850. TargetAttr::ParsedTargetAttr Info =
  851. Attr->parse([&Target](StringRef LHS, StringRef RHS) {
  852. // Multiversioning doesn't allow "no-${feature}", so we can
  853. // only have "+" prefixes here.
  854. assert(LHS.startswith("+") && RHS.startswith("+") &&
  855. "Features should always have a prefix.");
  856. return Target.multiVersionSortPriority(LHS.substr(1)) >
  857. Target.multiVersionSortPriority(RHS.substr(1));
  858. });
  859. bool IsFirst = true;
  860. if (!Info.Architecture.empty()) {
  861. IsFirst = false;
  862. Out << "arch_" << Info.Architecture;
  863. }
  864. for (StringRef Feat : Info.Features) {
  865. if (!IsFirst)
  866. Out << '_';
  867. IsFirst = false;
  868. Out << Feat.substr(1);
  869. }
  870. }
  871. static std::string getMangledNameImpl(const CodeGenModule &CGM, GlobalDecl GD,
  872. const NamedDecl *ND,
  873. bool OmitMultiVersionMangling = false) {
  874. SmallString<256> Buffer;
  875. llvm::raw_svector_ostream Out(Buffer);
  876. MangleContext &MC = CGM.getCXXABI().getMangleContext();
  877. if (MC.shouldMangleDeclName(ND)) {
  878. llvm::raw_svector_ostream Out(Buffer);
  879. if (const auto *D = dyn_cast<CXXConstructorDecl>(ND))
  880. MC.mangleCXXCtor(D, GD.getCtorType(), Out);
  881. else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND))
  882. MC.mangleCXXDtor(D, GD.getDtorType(), Out);
  883. else
  884. MC.mangleName(ND, Out);
  885. } else {
  886. IdentifierInfo *II = ND->getIdentifier();
  887. assert(II && "Attempt to mangle unnamed decl.");
  888. const auto *FD = dyn_cast<FunctionDecl>(ND);
  889. if (FD &&
  890. FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) {
  891. llvm::raw_svector_ostream Out(Buffer);
  892. Out << "__regcall3__" << II->getName();
  893. } else {
  894. Out << II->getName();
  895. }
  896. }
  897. if (const auto *FD = dyn_cast<FunctionDecl>(ND))
  898. if (FD->isMultiVersion() && !OmitMultiVersionMangling) {
  899. switch (FD->getMultiVersionKind()) {
  900. case MultiVersionKind::CPUDispatch:
  901. case MultiVersionKind::CPUSpecific:
  902. AppendCPUSpecificCPUDispatchMangling(CGM,
  903. FD->getAttr<CPUSpecificAttr>(),
  904. GD.getMultiVersionIndex(), Out);
  905. break;
  906. case MultiVersionKind::Target:
  907. AppendTargetMangling(CGM, FD->getAttr<TargetAttr>(), Out);
  908. break;
  909. case MultiVersionKind::None:
  910. llvm_unreachable("None multiversion type isn't valid here");
  911. }
  912. }
  913. return Out.str();
  914. }
  915. void CodeGenModule::UpdateMultiVersionNames(GlobalDecl GD,
  916. const FunctionDecl *FD) {
  917. if (!FD->isMultiVersion())
  918. return;
  919. // Get the name of what this would be without the 'target' attribute. This
  920. // allows us to lookup the version that was emitted when this wasn't a
  921. // multiversion function.
  922. std::string NonTargetName =
  923. getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
  924. GlobalDecl OtherGD;
  925. if (lookupRepresentativeDecl(NonTargetName, OtherGD)) {
  926. assert(OtherGD.getCanonicalDecl()
  927. .getDecl()
  928. ->getAsFunction()
  929. ->isMultiVersion() &&
  930. "Other GD should now be a multiversioned function");
  931. // OtherFD is the version of this function that was mangled BEFORE
  932. // becoming a MultiVersion function. It potentially needs to be updated.
  933. const FunctionDecl *OtherFD = OtherGD.getCanonicalDecl()
  934. .getDecl()
  935. ->getAsFunction()
  936. ->getMostRecentDecl();
  937. std::string OtherName = getMangledNameImpl(*this, OtherGD, OtherFD);
  938. // This is so that if the initial version was already the 'default'
  939. // version, we don't try to update it.
  940. if (OtherName != NonTargetName) {
  941. // Remove instead of erase, since others may have stored the StringRef
  942. // to this.
  943. const auto ExistingRecord = Manglings.find(NonTargetName);
  944. if (ExistingRecord != std::end(Manglings))
  945. Manglings.remove(&(*ExistingRecord));
  946. auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD));
  947. MangledDeclNames[OtherGD.getCanonicalDecl()] = Result.first->first();
  948. if (llvm::GlobalValue *Entry = GetGlobalValue(NonTargetName))
  949. Entry->setName(OtherName);
  950. }
  951. }
  952. }
  953. StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
  954. GlobalDecl CanonicalGD = GD.getCanonicalDecl();
  955. // Some ABIs don't have constructor variants. Make sure that base and
  956. // complete constructors get mangled the same.
  957. if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) {
  958. if (!getTarget().getCXXABI().hasConstructorVariants()) {
  959. CXXCtorType OrigCtorType = GD.getCtorType();
  960. assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete);
  961. if (OrigCtorType == Ctor_Base)
  962. CanonicalGD = GlobalDecl(CD, Ctor_Complete);
  963. }
  964. }
  965. auto FoundName = MangledDeclNames.find(CanonicalGD);
  966. if (FoundName != MangledDeclNames.end())
  967. return FoundName->second;
  968. // Keep the first result in the case of a mangling collision.
  969. const auto *ND = cast<NamedDecl>(GD.getDecl());
  970. std::string MangledName = getMangledNameImpl(*this, GD, ND);
  971. // Adjust kernel stub mangling as we may need to be able to differentiate
  972. // them from the kernel itself (e.g., for HIP).
  973. if (auto *FD = dyn_cast<FunctionDecl>(GD.getDecl()))
  974. if (!getLangOpts().CUDAIsDevice && FD->hasAttr<CUDAGlobalAttr>())
  975. MangledName = getCUDARuntime().getDeviceStubName(MangledName);
  976. auto Result = Manglings.insert(std::make_pair(MangledName, GD));
  977. return MangledDeclNames[CanonicalGD] = Result.first->first();
  978. }
  979. StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
  980. const BlockDecl *BD) {
  981. MangleContext &MangleCtx = getCXXABI().getMangleContext();
  982. const Decl *D = GD.getDecl();
  983. SmallString<256> Buffer;
  984. llvm::raw_svector_ostream Out(Buffer);
  985. if (!D)
  986. MangleCtx.mangleGlobalBlock(BD,
  987. dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
  988. else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
  989. MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
  990. else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
  991. MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
  992. else
  993. MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
  994. auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
  995. return Result.first->first();
  996. }
  997. llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
  998. return getModule().getNamedValue(Name);
  999. }
  1000. /// AddGlobalCtor - Add a function to the list that will be called before
  1001. /// main() runs.
  1002. void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
  1003. llvm::Constant *AssociatedData) {
  1004. // FIXME: Type coercion of void()* types.
  1005. GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
  1006. }
  1007. /// AddGlobalDtor - Add a function to the list that will be called
  1008. /// when the module is unloaded.
  1009. void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) {
  1010. if (CodeGenOpts.RegisterGlobalDtorsWithAtExit) {
  1011. DtorsUsingAtExit[Priority].push_back(Dtor);
  1012. return;
  1013. }
  1014. // FIXME: Type coercion of void()* types.
  1015. GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
  1016. }
  1017. void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) {
  1018. if (Fns.empty()) return;
  1019. // Ctor function type is void()*.
  1020. llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
  1021. llvm::Type *CtorPFTy = llvm::PointerType::get(CtorFTy,
  1022. TheModule.getDataLayout().getProgramAddressSpace());
  1023. // Get the type of a ctor entry, { i32, void ()*, i8* }.
  1024. llvm::StructType *CtorStructTy = llvm::StructType::get(
  1025. Int32Ty, CtorPFTy, VoidPtrTy);
  1026. // Construct the constructor and destructor arrays.
  1027. ConstantInitBuilder builder(*this);
  1028. auto ctors = builder.beginArray(CtorStructTy);
  1029. for (const auto &I : Fns) {
  1030. auto ctor = ctors.beginStruct(CtorStructTy);
  1031. ctor.addInt(Int32Ty, I.Priority);
  1032. ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy));
  1033. if (I.AssociatedData)
  1034. ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy));
  1035. else
  1036. ctor.addNullPointer(VoidPtrTy);
  1037. ctor.finishAndAddTo(ctors);
  1038. }
  1039. auto list =
  1040. ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(),
  1041. /*constant*/ false,
  1042. llvm::GlobalValue::AppendingLinkage);
  1043. // The LTO linker doesn't seem to like it when we set an alignment
  1044. // on appending variables. Take it off as a workaround.
  1045. list->setAlignment(0);
  1046. Fns.clear();
  1047. }
  1048. llvm::GlobalValue::LinkageTypes
  1049. CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
  1050. const auto *D = cast<FunctionDecl>(GD.getDecl());
  1051. GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
  1052. if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(D))
  1053. return getCXXABI().getCXXDestructorLinkage(Linkage, Dtor, GD.getDtorType());
  1054. if (isa<CXXConstructorDecl>(D) &&
  1055. cast<CXXConstructorDecl>(D)->isInheritingConstructor() &&
  1056. Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  1057. // Our approach to inheriting constructors is fundamentally different from
  1058. // that used by the MS ABI, so keep our inheriting constructor thunks
  1059. // internal rather than trying to pick an unambiguous mangling for them.
  1060. return llvm::GlobalValue::InternalLinkage;
  1061. }
  1062. return getLLVMLinkageForDeclarator(D, Linkage, /*IsConstantVariable=*/false);
  1063. }
  1064. llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) {
  1065. llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
  1066. if (!MDS) return nullptr;
  1067. return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString()));
  1068. }
  1069. void CodeGenModule::SetLLVMFunctionAttributes(GlobalDecl GD,
  1070. const CGFunctionInfo &Info,
  1071. llvm::Function *F) {
  1072. unsigned CallingConv;
  1073. llvm::AttributeList PAL;
  1074. ConstructAttributeList(F->getName(), Info, GD, PAL, CallingConv, false);
  1075. F->setAttributes(PAL);
  1076. F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
  1077. }
  1078. static void removeImageAccessQualifier(std::string& TyName) {
  1079. std::string ReadOnlyQual("__read_only");
  1080. std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual);
  1081. if (ReadOnlyPos != std::string::npos)
  1082. // "+ 1" for the space after access qualifier.
  1083. TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1);
  1084. else {
  1085. std::string WriteOnlyQual("__write_only");
  1086. std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual);
  1087. if (WriteOnlyPos != std::string::npos)
  1088. TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1);
  1089. else {
  1090. std::string ReadWriteQual("__read_write");
  1091. std::string::size_type ReadWritePos = TyName.find(ReadWriteQual);
  1092. if (ReadWritePos != std::string::npos)
  1093. TyName.erase(ReadWritePos, ReadWriteQual.size() + 1);
  1094. }
  1095. }
  1096. }
  1097. // Returns the address space id that should be produced to the
  1098. // kernel_arg_addr_space metadata. This is always fixed to the ids
  1099. // as specified in the SPIR 2.0 specification in order to differentiate
  1100. // for example in clGetKernelArgInfo() implementation between the address
  1101. // spaces with targets without unique mapping to the OpenCL address spaces
  1102. // (basically all single AS CPUs).
  1103. static unsigned ArgInfoAddressSpace(LangAS AS) {
  1104. switch (AS) {
  1105. case LangAS::opencl_global: return 1;
  1106. case LangAS::opencl_constant: return 2;
  1107. case LangAS::opencl_local: return 3;
  1108. case LangAS::opencl_generic: return 4; // Not in SPIR 2.0 specs.
  1109. default:
  1110. return 0; // Assume private.
  1111. }
  1112. }
  1113. void CodeGenModule::GenOpenCLArgMetadata(llvm::Function *Fn,
  1114. const FunctionDecl *FD,
  1115. CodeGenFunction *CGF) {
  1116. assert(((FD && CGF) || (!FD && !CGF)) &&
  1117. "Incorrect use - FD and CGF should either be both null or not!");
  1118. // Create MDNodes that represent the kernel arg metadata.
  1119. // Each MDNode is a list in the form of "key", N number of values which is
  1120. // the same number of values as their are kernel arguments.
  1121. const PrintingPolicy &Policy = Context.getPrintingPolicy();
  1122. // MDNode for the kernel argument address space qualifiers.
  1123. SmallVector<llvm::Metadata *, 8> addressQuals;
  1124. // MDNode for the kernel argument access qualifiers (images only).
  1125. SmallVector<llvm::Metadata *, 8> accessQuals;
  1126. // MDNode for the kernel argument type names.
  1127. SmallVector<llvm::Metadata *, 8> argTypeNames;
  1128. // MDNode for the kernel argument base type names.
  1129. SmallVector<llvm::Metadata *, 8> argBaseTypeNames;
  1130. // MDNode for the kernel argument type qualifiers.
  1131. SmallVector<llvm::Metadata *, 8> argTypeQuals;
  1132. // MDNode for the kernel argument names.
  1133. SmallVector<llvm::Metadata *, 8> argNames;
  1134. if (FD && CGF)
  1135. for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) {
  1136. const ParmVarDecl *parm = FD->getParamDecl(i);
  1137. QualType ty = parm->getType();
  1138. std::string typeQuals;
  1139. if (ty->isPointerType()) {
  1140. QualType pointeeTy = ty->getPointeeType();
  1141. // Get address qualifier.
  1142. addressQuals.push_back(
  1143. llvm::ConstantAsMetadata::get(CGF->Builder.getInt32(
  1144. ArgInfoAddressSpace(pointeeTy.getAddressSpace()))));
  1145. // Get argument type name.
  1146. std::string typeName =
  1147. pointeeTy.getUnqualifiedType().getAsString(Policy) + "*";
  1148. // Turn "unsigned type" to "utype"
  1149. std::string::size_type pos = typeName.find("unsigned");
  1150. if (pointeeTy.isCanonical() && pos != std::string::npos)
  1151. typeName.erase(pos + 1, 8);
  1152. argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
  1153. std::string baseTypeName =
  1154. pointeeTy.getUnqualifiedType().getCanonicalType().getAsString(
  1155. Policy) +
  1156. "*";
  1157. // Turn "unsigned type" to "utype"
  1158. pos = baseTypeName.find("unsigned");
  1159. if (pos != std::string::npos)
  1160. baseTypeName.erase(pos + 1, 8);
  1161. argBaseTypeNames.push_back(
  1162. llvm::MDString::get(VMContext, baseTypeName));
  1163. // Get argument type qualifiers:
  1164. if (ty.isRestrictQualified())
  1165. typeQuals = "restrict";
  1166. if (pointeeTy.isConstQualified() ||
  1167. (pointeeTy.getAddressSpace() == LangAS::opencl_constant))
  1168. typeQuals += typeQuals.empty() ? "const" : " const";
  1169. if (pointeeTy.isVolatileQualified())
  1170. typeQuals += typeQuals.empty() ? "volatile" : " volatile";
  1171. } else {
  1172. uint32_t AddrSpc = 0;
  1173. bool isPipe = ty->isPipeType();
  1174. if (ty->isImageType() || isPipe)
  1175. AddrSpc = ArgInfoAddressSpace(LangAS::opencl_global);
  1176. addressQuals.push_back(
  1177. llvm::ConstantAsMetadata::get(CGF->Builder.getInt32(AddrSpc)));
  1178. // Get argument type name.
  1179. std::string typeName;
  1180. if (isPipe)
  1181. typeName = ty.getCanonicalType()
  1182. ->getAs<PipeType>()
  1183. ->getElementType()
  1184. .getAsString(Policy);
  1185. else
  1186. typeName = ty.getUnqualifiedType().getAsString(Policy);
  1187. // Turn "unsigned type" to "utype"
  1188. std::string::size_type pos = typeName.find("unsigned");
  1189. if (ty.isCanonical() && pos != std::string::npos)
  1190. typeName.erase(pos + 1, 8);
  1191. std::string baseTypeName;
  1192. if (isPipe)
  1193. baseTypeName = ty.getCanonicalType()
  1194. ->getAs<PipeType>()
  1195. ->getElementType()
  1196. .getCanonicalType()
  1197. .getAsString(Policy);
  1198. else
  1199. baseTypeName =
  1200. ty.getUnqualifiedType().getCanonicalType().getAsString(Policy);
  1201. // Remove access qualifiers on images
  1202. // (as they are inseparable from type in clang implementation,
  1203. // but OpenCL spec provides a special query to get access qualifier
  1204. // via clGetKernelArgInfo with CL_KERNEL_ARG_ACCESS_QUALIFIER):
  1205. if (ty->isImageType()) {
  1206. removeImageAccessQualifier(typeName);
  1207. removeImageAccessQualifier(baseTypeName);
  1208. }
  1209. argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
  1210. // Turn "unsigned type" to "utype"
  1211. pos = baseTypeName.find("unsigned");
  1212. if (pos != std::string::npos)
  1213. baseTypeName.erase(pos + 1, 8);
  1214. argBaseTypeNames.push_back(
  1215. llvm::MDString::get(VMContext, baseTypeName));
  1216. if (isPipe)
  1217. typeQuals = "pipe";
  1218. }
  1219. argTypeQuals.push_back(llvm::MDString::get(VMContext, typeQuals));
  1220. // Get image and pipe access qualifier:
  1221. if (ty->isImageType() || ty->isPipeType()) {
  1222. const Decl *PDecl = parm;
  1223. if (auto *TD = dyn_cast<TypedefType>(ty))
  1224. PDecl = TD->getDecl();
  1225. const OpenCLAccessAttr *A = PDecl->getAttr<OpenCLAccessAttr>();
  1226. if (A && A->isWriteOnly())
  1227. accessQuals.push_back(llvm::MDString::get(VMContext, "write_only"));
  1228. else if (A && A->isReadWrite())
  1229. accessQuals.push_back(llvm::MDString::get(VMContext, "read_write"));
  1230. else
  1231. accessQuals.push_back(llvm::MDString::get(VMContext, "read_only"));
  1232. } else
  1233. accessQuals.push_back(llvm::MDString::get(VMContext, "none"));
  1234. // Get argument name.
  1235. argNames.push_back(llvm::MDString::get(VMContext, parm->getName()));
  1236. }
  1237. Fn->setMetadata("kernel_arg_addr_space",
  1238. llvm::MDNode::get(VMContext, addressQuals));
  1239. Fn->setMetadata("kernel_arg_access_qual",
  1240. llvm::MDNode::get(VMContext, accessQuals));
  1241. Fn->setMetadata("kernel_arg_type",
  1242. llvm::MDNode::get(VMContext, argTypeNames));
  1243. Fn->setMetadata("kernel_arg_base_type",
  1244. llvm::MDNode::get(VMContext, argBaseTypeNames));
  1245. Fn->setMetadata("kernel_arg_type_qual",
  1246. llvm::MDNode::get(VMContext, argTypeQuals));
  1247. if (getCodeGenOpts().EmitOpenCLArgMetadata)
  1248. Fn->setMetadata("kernel_arg_name",
  1249. llvm::MDNode::get(VMContext, argNames));
  1250. }
  1251. /// Determines whether the language options require us to model
  1252. /// unwind exceptions. We treat -fexceptions as mandating this
  1253. /// except under the fragile ObjC ABI with only ObjC exceptions
  1254. /// enabled. This means, for example, that C with -fexceptions
  1255. /// enables this.
  1256. static bool hasUnwindExceptions(const LangOptions &LangOpts) {
  1257. // If exceptions are completely disabled, obviously this is false.
  1258. if (!LangOpts.Exceptions) return false;
  1259. // If C++ exceptions are enabled, this is true.
  1260. if (LangOpts.CXXExceptions) return true;
  1261. // If ObjC exceptions are enabled, this depends on the ABI.
  1262. if (LangOpts.ObjCExceptions) {
  1263. return LangOpts.ObjCRuntime.hasUnwindExceptions();
  1264. }
  1265. return true;
  1266. }
  1267. static bool requiresMemberFunctionPointerTypeMetadata(CodeGenModule &CGM,
  1268. const CXXMethodDecl *MD) {
  1269. // Check that the type metadata can ever actually be used by a call.
  1270. if (!CGM.getCodeGenOpts().LTOUnit ||
  1271. !CGM.HasHiddenLTOVisibility(MD->getParent()))
  1272. return false;
  1273. // Only functions whose address can be taken with a member function pointer
  1274. // need this sort of type metadata.
  1275. return !MD->isStatic() && !MD->isVirtual() && !isa<CXXConstructorDecl>(MD) &&
  1276. !isa<CXXDestructorDecl>(MD);
  1277. }
  1278. std::vector<const CXXRecordDecl *>
  1279. CodeGenModule::getMostBaseClasses(const CXXRecordDecl *RD) {
  1280. llvm::SetVector<const CXXRecordDecl *> MostBases;
  1281. std::function<void (const CXXRecordDecl *)> CollectMostBases;
  1282. CollectMostBases = [&](const CXXRecordDecl *RD) {
  1283. if (RD->getNumBases() == 0)
  1284. MostBases.insert(RD);
  1285. for (const CXXBaseSpecifier &B : RD->bases())
  1286. CollectMostBases(B.getType()->getAsCXXRecordDecl());
  1287. };
  1288. CollectMostBases(RD);
  1289. return MostBases.takeVector();
  1290. }
  1291. void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
  1292. llvm::Function *F) {
  1293. llvm::AttrBuilder B;
  1294. if (CodeGenOpts.UnwindTables)
  1295. B.addAttribute(llvm::Attribute::UWTable);
  1296. if (!hasUnwindExceptions(LangOpts))
  1297. B.addAttribute(llvm::Attribute::NoUnwind);
  1298. if (!D || !D->hasAttr<NoStackProtectorAttr>()) {
  1299. if (LangOpts.getStackProtector() == LangOptions::SSPOn)
  1300. B.addAttribute(llvm::Attribute::StackProtect);
  1301. else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
  1302. B.addAttribute(llvm::Attribute::StackProtectStrong);
  1303. else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
  1304. B.addAttribute(llvm::Attribute::StackProtectReq);
  1305. }
  1306. if (!D) {
  1307. // If we don't have a declaration to control inlining, the function isn't
  1308. // explicitly marked as alwaysinline for semantic reasons, and inlining is
  1309. // disabled, mark the function as noinline.
  1310. if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
  1311. CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining)
  1312. B.addAttribute(llvm::Attribute::NoInline);
  1313. F->addAttributes(llvm::AttributeList::FunctionIndex, B);
  1314. return;
  1315. }
  1316. // Track whether we need to add the optnone LLVM attribute,
  1317. // starting with the default for this optimization level.
  1318. bool ShouldAddOptNone =
  1319. !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
  1320. // We can't add optnone in the following cases, it won't pass the verifier.
  1321. ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>();
  1322. ShouldAddOptNone &= !F->hasFnAttribute(llvm::Attribute::AlwaysInline);
  1323. ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>();
  1324. if (ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) {
  1325. B.addAttribute(llvm::Attribute::OptimizeNone);
  1326. // OptimizeNone implies noinline; we should not be inlining such functions.
  1327. B.addAttribute(llvm::Attribute::NoInline);
  1328. assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
  1329. "OptimizeNone and AlwaysInline on same function!");
  1330. // We still need to handle naked functions even though optnone subsumes
  1331. // much of their semantics.
  1332. if (D->hasAttr<NakedAttr>())
  1333. B.addAttribute(llvm::Attribute::Naked);
  1334. // OptimizeNone wins over OptimizeForSize and MinSize.
  1335. F->removeFnAttr(llvm::Attribute::OptimizeForSize);
  1336. F->removeFnAttr(llvm::Attribute::MinSize);
  1337. } else if (D->hasAttr<NakedAttr>()) {
  1338. // Naked implies noinline: we should not be inlining such functions.
  1339. B.addAttribute(llvm::Attribute::Naked);
  1340. B.addAttribute(llvm::Attribute::NoInline);
  1341. } else if (D->hasAttr<NoDuplicateAttr>()) {
  1342. B.addAttribute(llvm::Attribute::NoDuplicate);
  1343. } else if (D->hasAttr<NoInlineAttr>()) {
  1344. B.addAttribute(llvm::Attribute::NoInline);
  1345. } else if (D->hasAttr<AlwaysInlineAttr>() &&
  1346. !F->hasFnAttribute(llvm::Attribute::NoInline)) {
  1347. // (noinline wins over always_inline, and we can't specify both in IR)
  1348. B.addAttribute(llvm::Attribute::AlwaysInline);
  1349. } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) {
  1350. // If we're not inlining, then force everything that isn't always_inline to
  1351. // carry an explicit noinline attribute.
  1352. if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
  1353. B.addAttribute(llvm::Attribute::NoInline);
  1354. } else {
  1355. // Otherwise, propagate the inline hint attribute and potentially use its
  1356. // absence to mark things as noinline.
  1357. if (auto *FD = dyn_cast<FunctionDecl>(D)) {
  1358. // Search function and template pattern redeclarations for inline.
  1359. auto CheckForInline = [](const FunctionDecl *FD) {
  1360. auto CheckRedeclForInline = [](const FunctionDecl *Redecl) {
  1361. return Redecl->isInlineSpecified();
  1362. };
  1363. if (any_of(FD->redecls(), CheckRedeclForInline))
  1364. return true;
  1365. const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern();
  1366. if (!Pattern)
  1367. return false;
  1368. return any_of(Pattern->redecls(), CheckRedeclForInline);
  1369. };
  1370. if (CheckForInline(FD)) {
  1371. B.addAttribute(llvm::Attribute::InlineHint);
  1372. } else if (CodeGenOpts.getInlining() ==
  1373. CodeGenOptions::OnlyHintInlining &&
  1374. !FD->isInlined() &&
  1375. !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
  1376. B.addAttribute(llvm::Attribute::NoInline);
  1377. }
  1378. }
  1379. }
  1380. // Add other optimization related attributes if we are optimizing this
  1381. // function.
  1382. if (!D->hasAttr<OptimizeNoneAttr>()) {
  1383. if (D->hasAttr<ColdAttr>()) {
  1384. if (!ShouldAddOptNone)
  1385. B.addAttribute(llvm::Attribute::OptimizeForSize);
  1386. B.addAttribute(llvm::Attribute::Cold);
  1387. }
  1388. if (D->hasAttr<MinSizeAttr>())
  1389. B.addAttribute(llvm::Attribute::MinSize);
  1390. }
  1391. F->addAttributes(llvm::AttributeList::FunctionIndex, B);
  1392. unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
  1393. if (alignment)
  1394. F->setAlignment(alignment);
  1395. if (!D->hasAttr<AlignedAttr>())
  1396. if (LangOpts.FunctionAlignment)
  1397. F->setAlignment(1 << LangOpts.FunctionAlignment);
  1398. // Some C++ ABIs require 2-byte alignment for member functions, in order to
  1399. // reserve a bit for differentiating between virtual and non-virtual member
  1400. // functions. If the current target's C++ ABI requires this and this is a
  1401. // member function, set its alignment accordingly.
  1402. if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
  1403. if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
  1404. F->setAlignment(2);
  1405. }
  1406. // In the cross-dso CFI mode with canonical jump tables, we want !type
  1407. // attributes on definitions only.
  1408. if (CodeGenOpts.SanitizeCfiCrossDso &&
  1409. CodeGenOpts.SanitizeCfiCanonicalJumpTables) {
  1410. if (auto *FD = dyn_cast<FunctionDecl>(D)) {
  1411. // Skip available_externally functions. They won't be codegen'ed in the
  1412. // current module anyway.
  1413. if (getContext().GetGVALinkageForFunction(FD) != GVA_AvailableExternally)
  1414. CreateFunctionTypeMetadataForIcall(FD, F);
  1415. }
  1416. }
  1417. // Emit type metadata on member functions for member function pointer checks.
  1418. // These are only ever necessary on definitions; we're guaranteed that the
  1419. // definition will be present in the LTO unit as a result of LTO visibility.
  1420. auto *MD = dyn_cast<CXXMethodDecl>(D);
  1421. if (MD && requiresMemberFunctionPointerTypeMetadata(*this, MD)) {
  1422. for (const CXXRecordDecl *Base : getMostBaseClasses(MD->getParent())) {
  1423. llvm::Metadata *Id =
  1424. CreateMetadataIdentifierForType(Context.getMemberPointerType(
  1425. MD->getType(), Context.getRecordType(Base).getTypePtr()));
  1426. F->addTypeMetadata(0, Id);
  1427. }
  1428. }
  1429. }
  1430. void CodeGenModule::SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV) {
  1431. const Decl *D = GD.getDecl();
  1432. if (dyn_cast_or_null<NamedDecl>(D))
  1433. setGVProperties(GV, GD);
  1434. else
  1435. GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
  1436. if (D && D->hasAttr<UsedAttr>())
  1437. addUsedGlobal(GV);
  1438. if (CodeGenOpts.KeepStaticConsts && D && isa<VarDecl>(D)) {
  1439. const auto *VD = cast<VarDecl>(D);
  1440. if (VD->getType().isConstQualified() &&
  1441. VD->getStorageDuration() == SD_Static)
  1442. addUsedGlobal(GV);
  1443. }
  1444. }
  1445. bool CodeGenModule::GetCPUAndFeaturesAttributes(GlobalDecl GD,
  1446. llvm::AttrBuilder &Attrs) {
  1447. // Add target-cpu and target-features attributes to functions. If
  1448. // we have a decl for the function and it has a target attribute then
  1449. // parse that and add it to the feature set.
  1450. StringRef TargetCPU = getTarget().getTargetOpts().CPU;
  1451. std::vector<std::string> Features;
  1452. const auto *FD = dyn_cast_or_null<FunctionDecl>(GD.getDecl());
  1453. FD = FD ? FD->getMostRecentDecl() : FD;
  1454. const auto *TD = FD ? FD->getAttr<TargetAttr>() : nullptr;
  1455. const auto *SD = FD ? FD->getAttr<CPUSpecificAttr>() : nullptr;
  1456. bool AddedAttr = false;
  1457. if (TD || SD) {
  1458. llvm::StringMap<bool> FeatureMap;
  1459. getFunctionFeatureMap(FeatureMap, GD);
  1460. // Produce the canonical string for this set of features.
  1461. for (const llvm::StringMap<bool>::value_type &Entry : FeatureMap)
  1462. Features.push_back((Entry.getValue() ? "+" : "-") + Entry.getKey().str());
  1463. // Now add the target-cpu and target-features to the function.
  1464. // While we populated the feature map above, we still need to
  1465. // get and parse the target attribute so we can get the cpu for
  1466. // the function.
  1467. if (TD) {
  1468. TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
  1469. if (ParsedAttr.Architecture != "" &&
  1470. getTarget().isValidCPUName(ParsedAttr.Architecture))
  1471. TargetCPU = ParsedAttr.Architecture;
  1472. }
  1473. } else {
  1474. // Otherwise just add the existing target cpu and target features to the
  1475. // function.
  1476. Features = getTarget().getTargetOpts().Features;
  1477. }
  1478. if (TargetCPU != "") {
  1479. Attrs.addAttribute("target-cpu", TargetCPU);
  1480. AddedAttr = true;
  1481. }
  1482. if (!Features.empty()) {
  1483. llvm::sort(Features);
  1484. Attrs.addAttribute("target-features", llvm::join(Features, ","));
  1485. AddedAttr = true;
  1486. }
  1487. return AddedAttr;
  1488. }
  1489. void CodeGenModule::setNonAliasAttributes(GlobalDecl GD,
  1490. llvm::GlobalObject *GO) {
  1491. const Decl *D = GD.getDecl();
  1492. SetCommonAttributes(GD, GO);
  1493. if (D) {
  1494. if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
  1495. if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>())
  1496. GV->addAttribute("bss-section", SA->getName());
  1497. if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>())
  1498. GV->addAttribute("data-section", SA->getName());
  1499. if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>())
  1500. GV->addAttribute("rodata-section", SA->getName());
  1501. }
  1502. if (auto *F = dyn_cast<llvm::Function>(GO)) {
  1503. if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>())
  1504. if (!D->getAttr<SectionAttr>())
  1505. F->addFnAttr("implicit-section-name", SA->getName());
  1506. llvm::AttrBuilder Attrs;
  1507. if (GetCPUAndFeaturesAttributes(GD, Attrs)) {
  1508. // We know that GetCPUAndFeaturesAttributes will always have the
  1509. // newest set, since it has the newest possible FunctionDecl, so the
  1510. // new ones should replace the old.
  1511. F->removeFnAttr("target-cpu");
  1512. F->removeFnAttr("target-features");
  1513. F->addAttributes(llvm::AttributeList::FunctionIndex, Attrs);
  1514. }
  1515. }
  1516. if (const auto *CSA = D->getAttr<CodeSegAttr>())
  1517. GO->setSection(CSA->getName());
  1518. else if (const auto *SA = D->getAttr<SectionAttr>())
  1519. GO->setSection(SA->getName());
  1520. }
  1521. getTargetCodeGenInfo().setTargetAttributes(D, GO, *this);
  1522. }
  1523. void CodeGenModule::SetInternalFunctionAttributes(GlobalDecl GD,
  1524. llvm::Function *F,
  1525. const CGFunctionInfo &FI) {
  1526. const Decl *D = GD.getDecl();
  1527. SetLLVMFunctionAttributes(GD, FI, F);
  1528. SetLLVMFunctionAttributesForDefinition(D, F);
  1529. F->setLinkage(llvm::Function::InternalLinkage);
  1530. setNonAliasAttributes(GD, F);
  1531. }
  1532. static void setLinkageForGV(llvm::GlobalValue *GV, const NamedDecl *ND) {
  1533. // Set linkage and visibility in case we never see a definition.
  1534. LinkageInfo LV = ND->getLinkageAndVisibility();
  1535. // Don't set internal linkage on declarations.
  1536. // "extern_weak" is overloaded in LLVM; we probably should have
  1537. // separate linkage types for this.
  1538. if (isExternallyVisible(LV.getLinkage()) &&
  1539. (ND->hasAttr<WeakAttr>() || ND->isWeakImported()))
  1540. GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
  1541. }
  1542. void CodeGenModule::CreateFunctionTypeMetadataForIcall(const FunctionDecl *FD,
  1543. llvm::Function *F) {
  1544. // Only if we are checking indirect calls.
  1545. if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
  1546. return;
  1547. // Non-static class methods are handled via vtable or member function pointer
  1548. // checks elsewhere.
  1549. if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
  1550. return;
  1551. llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType());
  1552. F->addTypeMetadata(0, MD);
  1553. F->addTypeMetadata(0, CreateMetadataIdentifierGeneralized(FD->getType()));
  1554. // Emit a hash-based bit set entry for cross-DSO calls.
  1555. if (CodeGenOpts.SanitizeCfiCrossDso)
  1556. if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
  1557. F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
  1558. }
  1559. void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
  1560. bool IsIncompleteFunction,
  1561. bool IsThunk) {
  1562. if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
  1563. // If this is an intrinsic function, set the function's attributes
  1564. // to the intrinsic's attributes.
  1565. F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
  1566. return;
  1567. }
  1568. const auto *FD = cast<FunctionDecl>(GD.getDecl());
  1569. if (!IsIncompleteFunction)
  1570. SetLLVMFunctionAttributes(GD, getTypes().arrangeGlobalDeclaration(GD), F);
  1571. // Add the Returned attribute for "this", except for iOS 5 and earlier
  1572. // where substantial code, including the libstdc++ dylib, was compiled with
  1573. // GCC and does not actually return "this".
  1574. if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
  1575. !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) {
  1576. assert(!F->arg_empty() &&
  1577. F->arg_begin()->getType()
  1578. ->canLosslesslyBitCastTo(F->getReturnType()) &&
  1579. "unexpected this return");
  1580. F->addAttribute(1, llvm::Attribute::Returned);
  1581. }
  1582. // Only a few attributes are set on declarations; these may later be
  1583. // overridden by a definition.
  1584. setLinkageForGV(F, FD);
  1585. setGVProperties(F, FD);
  1586. // Setup target-specific attributes.
  1587. if (!IsIncompleteFunction && F->isDeclaration())
  1588. getTargetCodeGenInfo().setTargetAttributes(FD, F, *this);
  1589. if (const auto *CSA = FD->getAttr<CodeSegAttr>())
  1590. F->setSection(CSA->getName());
  1591. else if (const auto *SA = FD->getAttr<SectionAttr>())
  1592. F->setSection(SA->getName());
  1593. if (FD->isReplaceableGlobalAllocationFunction()) {
  1594. // A replaceable global allocation function does not act like a builtin by
  1595. // default, only if it is invoked by a new-expression or delete-expression.
  1596. F->addAttribute(llvm::AttributeList::FunctionIndex,
  1597. llvm::Attribute::NoBuiltin);
  1598. // A sane operator new returns a non-aliasing pointer.
  1599. // FIXME: Also add NonNull attribute to the return value
  1600. // for the non-nothrow forms?
  1601. auto Kind = FD->getDeclName().getCXXOverloadedOperator();
  1602. if (getCodeGenOpts().AssumeSaneOperatorNew &&
  1603. (Kind == OO_New || Kind == OO_Array_New))
  1604. F->addAttribute(llvm::AttributeList::ReturnIndex,
  1605. llvm::Attribute::NoAlias);
  1606. }
  1607. if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
  1608. F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  1609. else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
  1610. if (MD->isVirtual())
  1611. F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  1612. // Don't emit entries for function declarations in the cross-DSO mode. This
  1613. // is handled with better precision by the receiving DSO. But if jump tables
  1614. // are non-canonical then we need type metadata in order to produce the local
  1615. // jump table.
  1616. if (!CodeGenOpts.SanitizeCfiCrossDso ||
  1617. !CodeGenOpts.SanitizeCfiCanonicalJumpTables)
  1618. CreateFunctionTypeMetadataForIcall(FD, F);
  1619. if (getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>())
  1620. getOpenMPRuntime().emitDeclareSimdFunction(FD, F);
  1621. if (const auto *CB = FD->getAttr<CallbackAttr>()) {
  1622. // Annotate the callback behavior as metadata:
  1623. // - The callback callee (as argument number).
  1624. // - The callback payloads (as argument numbers).
  1625. llvm::LLVMContext &Ctx = F->getContext();
  1626. llvm::MDBuilder MDB(Ctx);
  1627. // The payload indices are all but the first one in the encoding. The first
  1628. // identifies the callback callee.
  1629. int CalleeIdx = *CB->encoding_begin();
  1630. ArrayRef<int> PayloadIndices(CB->encoding_begin() + 1, CB->encoding_end());
  1631. F->addMetadata(llvm::LLVMContext::MD_callback,
  1632. *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding(
  1633. CalleeIdx, PayloadIndices,
  1634. /* VarArgsArePassed */ false)}));
  1635. }
  1636. }
  1637. void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
  1638. assert(!GV->isDeclaration() &&
  1639. "Only globals with definition can force usage.");
  1640. LLVMUsed.emplace_back(GV);
  1641. }
  1642. void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
  1643. assert(!GV->isDeclaration() &&
  1644. "Only globals with definition can force usage.");
  1645. LLVMCompilerUsed.emplace_back(GV);
  1646. }
  1647. static void emitUsed(CodeGenModule &CGM, StringRef Name,
  1648. std::vector<llvm::WeakTrackingVH> &List) {
  1649. // Don't create llvm.used if there is no need.
  1650. if (List.empty())
  1651. return;
  1652. // Convert List to what ConstantArray needs.
  1653. SmallVector<llvm::Constant*, 8> UsedArray;
  1654. UsedArray.resize(List.size());
  1655. for (unsigned i = 0, e = List.size(); i != e; ++i) {
  1656. UsedArray[i] =
  1657. llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
  1658. cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
  1659. }
  1660. if (UsedArray.empty())
  1661. return;
  1662. llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
  1663. auto *GV = new llvm::GlobalVariable(
  1664. CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
  1665. llvm::ConstantArray::get(ATy, UsedArray), Name);
  1666. GV->setSection("llvm.metadata");
  1667. }
  1668. void CodeGenModule::emitLLVMUsed() {
  1669. emitUsed(*this, "llvm.used", LLVMUsed);
  1670. emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
  1671. }
  1672. void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
  1673. auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
  1674. LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
  1675. }
  1676. void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
  1677. llvm::SmallString<32> Opt;
  1678. getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
  1679. auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
  1680. LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
  1681. }
  1682. void CodeGenModule::AddDependentLib(StringRef Lib) {
  1683. auto &C = getLLVMContext();
  1684. if (getTarget().getTriple().isOSBinFormatELF()) {
  1685. ELFDependentLibraries.push_back(
  1686. llvm::MDNode::get(C, llvm::MDString::get(C, Lib)));
  1687. return;
  1688. }
  1689. llvm::SmallString<24> Opt;
  1690. getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
  1691. auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
  1692. LinkerOptionsMetadata.push_back(llvm::MDNode::get(C, MDOpts));
  1693. }
  1694. /// Add link options implied by the given module, including modules
  1695. /// it depends on, using a postorder walk.
  1696. static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
  1697. SmallVectorImpl<llvm::MDNode *> &Metadata,
  1698. llvm::SmallPtrSet<Module *, 16> &Visited) {
  1699. // Import this module's parent.
  1700. if (Mod->Parent && Visited.insert(Mod->Parent).second) {
  1701. addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
  1702. }
  1703. // Import this module's dependencies.
  1704. for (unsigned I = Mod->Imports.size(); I > 0; --I) {
  1705. if (Visited.insert(Mod->Imports[I - 1]).second)
  1706. addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
  1707. }
  1708. // Add linker options to link against the libraries/frameworks
  1709. // described by this module.
  1710. llvm::LLVMContext &Context = CGM.getLLVMContext();
  1711. bool IsELF = CGM.getTarget().getTriple().isOSBinFormatELF();
  1712. // For modules that use export_as for linking, use that module
  1713. // name instead.
  1714. if (Mod->UseExportAsModuleLinkName)
  1715. return;
  1716. for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
  1717. // Link against a framework. Frameworks are currently Darwin only, so we
  1718. // don't to ask TargetCodeGenInfo for the spelling of the linker option.
  1719. if (Mod->LinkLibraries[I-1].IsFramework) {
  1720. llvm::Metadata *Args[2] = {
  1721. llvm::MDString::get(Context, "-framework"),
  1722. llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)};
  1723. Metadata.push_back(llvm::MDNode::get(Context, Args));
  1724. continue;
  1725. }
  1726. // Link against a library.
  1727. if (IsELF) {
  1728. llvm::Metadata *Args[2] = {
  1729. llvm::MDString::get(Context, "lib"),
  1730. llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library),
  1731. };
  1732. Metadata.push_back(llvm::MDNode::get(Context, Args));
  1733. } else {
  1734. llvm::SmallString<24> Opt;
  1735. CGM.getTargetCodeGenInfo().getDependentLibraryOption(
  1736. Mod->LinkLibraries[I - 1].Library, Opt);
  1737. auto *OptString = llvm::MDString::get(Context, Opt);
  1738. Metadata.push_back(llvm::MDNode::get(Context, OptString));
  1739. }
  1740. }
  1741. }
  1742. void CodeGenModule::EmitModuleLinkOptions() {
  1743. // Collect the set of all of the modules we want to visit to emit link
  1744. // options, which is essentially the imported modules and all of their
  1745. // non-explicit child modules.
  1746. llvm::SetVector<clang::Module *> LinkModules;
  1747. llvm::SmallPtrSet<clang::Module *, 16> Visited;
  1748. SmallVector<clang::Module *, 16> Stack;
  1749. // Seed the stack with imported modules.
  1750. for (Module *M : ImportedModules) {
  1751. // Do not add any link flags when an implementation TU of a module imports
  1752. // a header of that same module.
  1753. if (M->getTopLevelModuleName() == getLangOpts().CurrentModule &&
  1754. !getLangOpts().isCompilingModule())
  1755. continue;
  1756. if (Visited.insert(M).second)
  1757. Stack.push_back(M);
  1758. }
  1759. // Find all of the modules to import, making a little effort to prune
  1760. // non-leaf modules.
  1761. while (!Stack.empty()) {
  1762. clang::Module *Mod = Stack.pop_back_val();
  1763. bool AnyChildren = false;
  1764. // Visit the submodules of this module.
  1765. for (const auto &SM : Mod->submodules()) {
  1766. // Skip explicit children; they need to be explicitly imported to be
  1767. // linked against.
  1768. if (SM->IsExplicit)
  1769. continue;
  1770. if (Visited.insert(SM).second) {
  1771. Stack.push_back(SM);
  1772. AnyChildren = true;
  1773. }
  1774. }
  1775. // We didn't find any children, so add this module to the list of
  1776. // modules to link against.
  1777. if (!AnyChildren) {
  1778. LinkModules.insert(Mod);
  1779. }
  1780. }
  1781. // Add link options for all of the imported modules in reverse topological
  1782. // order. We don't do anything to try to order import link flags with respect
  1783. // to linker options inserted by things like #pragma comment().
  1784. SmallVector<llvm::MDNode *, 16> MetadataArgs;
  1785. Visited.clear();
  1786. for (Module *M : LinkModules)
  1787. if (Visited.insert(M).second)
  1788. addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
  1789. std::reverse(MetadataArgs.begin(), MetadataArgs.end());
  1790. LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
  1791. // Add the linker options metadata flag.
  1792. auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options");
  1793. for (auto *MD : LinkerOptionsMetadata)
  1794. NMD->addOperand(MD);
  1795. }
  1796. void CodeGenModule::EmitDeferred() {
  1797. // Emit deferred declare target declarations.
  1798. if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd)
  1799. getOpenMPRuntime().emitDeferredTargetDecls();
  1800. // Emit code for any potentially referenced deferred decls. Since a
  1801. // previously unused static decl may become used during the generation of code
  1802. // for a static function, iterate until no changes are made.
  1803. if (!DeferredVTables.empty()) {
  1804. EmitDeferredVTables();
  1805. // Emitting a vtable doesn't directly cause more vtables to
  1806. // become deferred, although it can cause functions to be
  1807. // emitted that then need those vtables.
  1808. assert(DeferredVTables.empty());
  1809. }
  1810. // Stop if we're out of both deferred vtables and deferred declarations.
  1811. if (DeferredDeclsToEmit.empty())
  1812. return;
  1813. // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
  1814. // work, it will not interfere with this.
  1815. std::vector<GlobalDecl> CurDeclsToEmit;
  1816. CurDeclsToEmit.swap(DeferredDeclsToEmit);
  1817. for (GlobalDecl &D : CurDeclsToEmit) {
  1818. // We should call GetAddrOfGlobal with IsForDefinition set to true in order
  1819. // to get GlobalValue with exactly the type we need, not something that
  1820. // might had been created for another decl with the same mangled name but
  1821. // different type.
  1822. llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
  1823. GetAddrOfGlobal(D, ForDefinition));
  1824. // In case of different address spaces, we may still get a cast, even with
  1825. // IsForDefinition equal to true. Query mangled names table to get
  1826. // GlobalValue.
  1827. if (!GV)
  1828. GV = GetGlobalValue(getMangledName(D));
  1829. // Make sure GetGlobalValue returned non-null.
  1830. assert(GV);
  1831. // Check to see if we've already emitted this. This is necessary
  1832. // for a couple of reasons: first, decls can end up in the
  1833. // deferred-decls queue multiple times, and second, decls can end
  1834. // up with definitions in unusual ways (e.g. by an extern inline
  1835. // function acquiring a strong function redefinition). Just
  1836. // ignore these cases.
  1837. if (!GV->isDeclaration())
  1838. continue;
  1839. // If this is OpenMP, check if it is legal to emit this global normally.
  1840. if (LangOpts.OpenMP && OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(D))
  1841. continue;
  1842. // Otherwise, emit the definition and move on to the next one.
  1843. EmitGlobalDefinition(D, GV);
  1844. // If we found out that we need to emit more decls, do that recursively.
  1845. // This has the advantage that the decls are emitted in a DFS and related
  1846. // ones are close together, which is convenient for testing.
  1847. if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
  1848. EmitDeferred();
  1849. assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
  1850. }
  1851. }
  1852. }
  1853. void CodeGenModule::EmitVTablesOpportunistically() {
  1854. // Try to emit external vtables as available_externally if they have emitted
  1855. // all inlined virtual functions. It runs after EmitDeferred() and therefore
  1856. // is not allowed to create new references to things that need to be emitted
  1857. // lazily. Note that it also uses fact that we eagerly emitting RTTI.
  1858. assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
  1859. && "Only emit opportunistic vtables with optimizations");
  1860. for (const CXXRecordDecl *RD : OpportunisticVTables) {
  1861. assert(getVTables().isVTableExternal(RD) &&
  1862. "This queue should only contain external vtables");
  1863. if (getCXXABI().canSpeculativelyEmitVTable(RD))
  1864. VTables.GenerateClassData(RD);
  1865. }
  1866. OpportunisticVTables.clear();
  1867. }
  1868. void CodeGenModule::EmitGlobalAnnotations() {
  1869. if (Annotations.empty())
  1870. return;
  1871. // Create a new global variable for the ConstantStruct in the Module.
  1872. llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
  1873. Annotations[0]->getType(), Annotations.size()), Annotations);
  1874. auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
  1875. llvm::GlobalValue::AppendingLinkage,
  1876. Array, "llvm.global.annotations");
  1877. gv->setSection(AnnotationSection);
  1878. }
  1879. llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
  1880. llvm::Constant *&AStr = AnnotationStrings[Str];
  1881. if (AStr)
  1882. return AStr;
  1883. // Not found yet, create a new global.
  1884. llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
  1885. auto *gv =
  1886. new llvm::GlobalVariable(getModule(), s->getType(), true,
  1887. llvm::GlobalValue::PrivateLinkage, s, ".str");
  1888. gv->setSection(AnnotationSection);
  1889. gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  1890. AStr = gv;
  1891. return gv;
  1892. }
  1893. llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
  1894. SourceManager &SM = getContext().getSourceManager();
  1895. PresumedLoc PLoc = SM.getPresumedLoc(Loc);
  1896. if (PLoc.isValid())
  1897. return EmitAnnotationString(PLoc.getFilename());
  1898. return EmitAnnotationString(SM.getBufferName(Loc));
  1899. }
  1900. llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
  1901. SourceManager &SM = getContext().getSourceManager();
  1902. PresumedLoc PLoc = SM.getPresumedLoc(L);
  1903. unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
  1904. SM.getExpansionLineNumber(L);
  1905. return llvm::ConstantInt::get(Int32Ty, LineNo);
  1906. }
  1907. llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
  1908. const AnnotateAttr *AA,
  1909. SourceLocation L) {
  1910. // Get the globals for file name, annotation, and the line number.
  1911. llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
  1912. *UnitGV = EmitAnnotationUnit(L),
  1913. *LineNoCst = EmitAnnotationLineNo(L);
  1914. // Create the ConstantStruct for the global annotation.
  1915. llvm::Constant *Fields[4] = {
  1916. llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
  1917. llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
  1918. llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
  1919. LineNoCst
  1920. };
  1921. return llvm::ConstantStruct::getAnon(Fields);
  1922. }
  1923. void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
  1924. llvm::GlobalValue *GV) {
  1925. assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
  1926. // Get the struct elements for these annotations.
  1927. for (const auto *I : D->specific_attrs<AnnotateAttr>())
  1928. Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
  1929. }
  1930. bool CodeGenModule::isInSanitizerBlacklist(SanitizerMask Kind,
  1931. llvm::Function *Fn,
  1932. SourceLocation Loc) const {
  1933. const auto &SanitizerBL = getContext().getSanitizerBlacklist();
  1934. // Blacklist by function name.
  1935. if (SanitizerBL.isBlacklistedFunction(Kind, Fn->getName()))
  1936. return true;
  1937. // Blacklist by location.
  1938. if (Loc.isValid())
  1939. return SanitizerBL.isBlacklistedLocation(Kind, Loc);
  1940. // If location is unknown, this may be a compiler-generated function. Assume
  1941. // it's located in the main file.
  1942. auto &SM = Context.getSourceManager();
  1943. if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
  1944. return SanitizerBL.isBlacklistedFile(Kind, MainFile->getName());
  1945. }
  1946. return false;
  1947. }
  1948. bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV,
  1949. SourceLocation Loc, QualType Ty,
  1950. StringRef Category) const {
  1951. // For now globals can be blacklisted only in ASan and KASan.
  1952. const SanitizerMask EnabledAsanMask =
  1953. LangOpts.Sanitize.Mask &
  1954. (SanitizerKind::Address | SanitizerKind::KernelAddress |
  1955. SanitizerKind::HWAddress | SanitizerKind::KernelHWAddress |
  1956. SanitizerKind::MemTag);
  1957. if (!EnabledAsanMask)
  1958. return false;
  1959. const auto &SanitizerBL = getContext().getSanitizerBlacklist();
  1960. if (SanitizerBL.isBlacklistedGlobal(EnabledAsanMask, GV->getName(), Category))
  1961. return true;
  1962. if (SanitizerBL.isBlacklistedLocation(EnabledAsanMask, Loc, Category))
  1963. return true;
  1964. // Check global type.
  1965. if (!Ty.isNull()) {
  1966. // Drill down the array types: if global variable of a fixed type is
  1967. // blacklisted, we also don't instrument arrays of them.
  1968. while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
  1969. Ty = AT->getElementType();
  1970. Ty = Ty.getCanonicalType().getUnqualifiedType();
  1971. // We allow to blacklist only record types (classes, structs etc.)
  1972. if (Ty->isRecordType()) {
  1973. std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
  1974. if (SanitizerBL.isBlacklistedType(EnabledAsanMask, TypeStr, Category))
  1975. return true;
  1976. }
  1977. }
  1978. return false;
  1979. }
  1980. bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
  1981. StringRef Category) const {
  1982. const auto &XRayFilter = getContext().getXRayFilter();
  1983. using ImbueAttr = XRayFunctionFilter::ImbueAttribute;
  1984. auto Attr = ImbueAttr::NONE;
  1985. if (Loc.isValid())
  1986. Attr = XRayFilter.shouldImbueLocation(Loc, Category);
  1987. if (Attr == ImbueAttr::NONE)
  1988. Attr = XRayFilter.shouldImbueFunction(Fn->getName());
  1989. switch (Attr) {
  1990. case ImbueAttr::NONE:
  1991. return false;
  1992. case ImbueAttr::ALWAYS:
  1993. Fn->addFnAttr("function-instrument", "xray-always");
  1994. break;
  1995. case ImbueAttr::ALWAYS_ARG1:
  1996. Fn->addFnAttr("function-instrument", "xray-always");
  1997. Fn->addFnAttr("xray-log-args", "1");
  1998. break;
  1999. case ImbueAttr::NEVER:
  2000. Fn->addFnAttr("function-instrument", "xray-never");
  2001. break;
  2002. }
  2003. return true;
  2004. }
  2005. bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
  2006. // Never defer when EmitAllDecls is specified.
  2007. if (LangOpts.EmitAllDecls)
  2008. return true;
  2009. if (CodeGenOpts.KeepStaticConsts) {
  2010. const auto *VD = dyn_cast<VarDecl>(Global);
  2011. if (VD && VD->getType().isConstQualified() &&
  2012. VD->getStorageDuration() == SD_Static)
  2013. return true;
  2014. }
  2015. return getContext().DeclMustBeEmitted(Global);
  2016. }
  2017. bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
  2018. if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
  2019. if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  2020. // Implicit template instantiations may change linkage if they are later
  2021. // explicitly instantiated, so they should not be emitted eagerly.
  2022. return false;
  2023. // In OpenMP 5.0 function may be marked as device_type(nohost) and we should
  2024. // not emit them eagerly unless we sure that the function must be emitted on
  2025. // the host.
  2026. if (LangOpts.OpenMP >= 50 && !LangOpts.OpenMPSimd &&
  2027. !LangOpts.OpenMPIsDevice &&
  2028. !OMPDeclareTargetDeclAttr::getDeviceType(FD) &&
  2029. !FD->isUsed(/*CheckUsedAttr=*/false) && !FD->isReferenced())
  2030. return false;
  2031. }
  2032. if (const auto *VD = dyn_cast<VarDecl>(Global))
  2033. if (Context.getInlineVariableDefinitionKind(VD) ==
  2034. ASTContext::InlineVariableDefinitionKind::WeakUnknown)
  2035. // A definition of an inline constexpr static data member may change
  2036. // linkage later if it's redeclared outside the class.
  2037. return false;
  2038. // If OpenMP is enabled and threadprivates must be generated like TLS, delay
  2039. // codegen for global variables, because they may be marked as threadprivate.
  2040. if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
  2041. getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global) &&
  2042. !isTypeConstant(Global->getType(), false) &&
  2043. !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Global))
  2044. return false;
  2045. return true;
  2046. }
  2047. ConstantAddress CodeGenModule::GetAddrOfUuidDescriptor(
  2048. const CXXUuidofExpr* E) {
  2049. // Sema has verified that IIDSource has a __declspec(uuid()), and that its
  2050. // well-formed.
  2051. StringRef Uuid = E->getUuidStr();
  2052. std::string Name = "_GUID_" + Uuid.lower();
  2053. std::replace(Name.begin(), Name.end(), '-', '_');
  2054. // The UUID descriptor should be pointer aligned.
  2055. CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes);
  2056. // Look for an existing global.
  2057. if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
  2058. return ConstantAddress(GV, Alignment);
  2059. llvm::Constant *Init = EmitUuidofInitializer(Uuid);
  2060. assert(Init && "failed to initialize as constant");
  2061. auto *GV = new llvm::GlobalVariable(
  2062. getModule(), Init->getType(),
  2063. /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
  2064. if (supportsCOMDAT())
  2065. GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
  2066. setDSOLocal(GV);
  2067. return ConstantAddress(GV, Alignment);
  2068. }
  2069. ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
  2070. const AliasAttr *AA = VD->getAttr<AliasAttr>();
  2071. assert(AA && "No alias?");
  2072. CharUnits Alignment = getContext().getDeclAlign(VD);
  2073. llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
  2074. // See if there is already something with the target's name in the module.
  2075. llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
  2076. if (Entry) {
  2077. unsigned AS = getContext().getTargetAddressSpace(VD->getType());
  2078. auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
  2079. return ConstantAddress(Ptr, Alignment);
  2080. }
  2081. llvm::Constant *Aliasee;
  2082. if (isa<llvm::FunctionType>(DeclTy))
  2083. Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
  2084. GlobalDecl(cast<FunctionDecl>(VD)),
  2085. /*ForVTable=*/false);
  2086. else
  2087. Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
  2088. llvm::PointerType::getUnqual(DeclTy),
  2089. nullptr);
  2090. auto *F = cast<llvm::GlobalValue>(Aliasee);
  2091. F->setLinkage(llvm::Function::ExternalWeakLinkage);
  2092. WeakRefReferences.insert(F);
  2093. return ConstantAddress(Aliasee, Alignment);
  2094. }
  2095. void CodeGenModule::EmitGlobal(GlobalDecl GD) {
  2096. const auto *Global = cast<ValueDecl>(GD.getDecl());
  2097. // Weak references don't produce any output by themselves.
  2098. if (Global->hasAttr<WeakRefAttr>())
  2099. return;
  2100. // If this is an alias definition (which otherwise looks like a declaration)
  2101. // emit it now.
  2102. if (Global->hasAttr<AliasAttr>())
  2103. return EmitAliasDefinition(GD);
  2104. // IFunc like an alias whose value is resolved at runtime by calling resolver.
  2105. if (Global->hasAttr<IFuncAttr>())
  2106. return emitIFuncDefinition(GD);
  2107. // If this is a cpu_dispatch multiversion function, emit the resolver.
  2108. if (Global->hasAttr<CPUDispatchAttr>())
  2109. return emitCPUDispatchDefinition(GD);
  2110. // If this is CUDA, be selective about which declarations we emit.
  2111. if (LangOpts.CUDA) {
  2112. if (LangOpts.CUDAIsDevice) {
  2113. if (!Global->hasAttr<CUDADeviceAttr>() &&
  2114. !Global->hasAttr<CUDAGlobalAttr>() &&
  2115. !Global->hasAttr<CUDAConstantAttr>() &&
  2116. !Global->hasAttr<CUDASharedAttr>() &&
  2117. !(LangOpts.HIP && Global->hasAttr<HIPPinnedShadowAttr>()))
  2118. return;
  2119. } else {
  2120. // We need to emit host-side 'shadows' for all global
  2121. // device-side variables because the CUDA runtime needs their
  2122. // size and host-side address in order to provide access to
  2123. // their device-side incarnations.
  2124. // So device-only functions are the only things we skip.
  2125. if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() &&
  2126. Global->hasAttr<CUDADeviceAttr>())
  2127. return;
  2128. assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
  2129. "Expected Variable or Function");
  2130. }
  2131. }
  2132. if (LangOpts.OpenMP) {
  2133. // If this is OpenMP, check if it is legal to emit this global normally.
  2134. if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
  2135. return;
  2136. if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
  2137. if (MustBeEmitted(Global))
  2138. EmitOMPDeclareReduction(DRD);
  2139. return;
  2140. } else if (auto *DMD = dyn_cast<OMPDeclareMapperDecl>(Global)) {
  2141. if (MustBeEmitted(Global))
  2142. EmitOMPDeclareMapper(DMD);
  2143. return;
  2144. }
  2145. }
  2146. // Ignore declarations, they will be emitted on their first use.
  2147. if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
  2148. // Forward declarations are emitted lazily on first use.
  2149. if (!FD->doesThisDeclarationHaveABody()) {
  2150. if (!FD->doesDeclarationForceExternallyVisibleDefinition())
  2151. return;
  2152. StringRef MangledName = getMangledName(GD);
  2153. // Compute the function info and LLVM type.
  2154. const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
  2155. llvm::Type *Ty = getTypes().GetFunctionType(FI);
  2156. GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
  2157. /*DontDefer=*/false);
  2158. return;
  2159. }
  2160. } else {
  2161. const auto *VD = cast<VarDecl>(Global);
  2162. assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
  2163. if (VD->isThisDeclarationADefinition() != VarDecl::Definition &&
  2164. !Context.isMSStaticDataMemberInlineDefinition(VD)) {
  2165. if (LangOpts.OpenMP) {
  2166. // Emit declaration of the must-be-emitted declare target variable.
  2167. if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
  2168. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
  2169. bool UnifiedMemoryEnabled =
  2170. getOpenMPRuntime().hasRequiresUnifiedSharedMemory();
  2171. if (*Res == OMPDeclareTargetDeclAttr::MT_To &&
  2172. !UnifiedMemoryEnabled) {
  2173. (void)GetAddrOfGlobalVar(VD);
  2174. } else {
  2175. assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
  2176. (*Res == OMPDeclareTargetDeclAttr::MT_To &&
  2177. UnifiedMemoryEnabled)) &&
  2178. "Link clause or to clause with unified memory expected.");
  2179. (void)getOpenMPRuntime().getAddrOfDeclareTargetVar(VD);
  2180. }
  2181. return;
  2182. }
  2183. }
  2184. // If this declaration may have caused an inline variable definition to
  2185. // change linkage, make sure that it's emitted.
  2186. if (Context.getInlineVariableDefinitionKind(VD) ==
  2187. ASTContext::InlineVariableDefinitionKind::Strong)
  2188. GetAddrOfGlobalVar(VD);
  2189. return;
  2190. }
  2191. }
  2192. // Defer code generation to first use when possible, e.g. if this is an inline
  2193. // function. If the global must always be emitted, do it eagerly if possible
  2194. // to benefit from cache locality.
  2195. if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
  2196. // Emit the definition if it can't be deferred.
  2197. EmitGlobalDefinition(GD);
  2198. return;
  2199. }
  2200. // If we're deferring emission of a C++ variable with an
  2201. // initializer, remember the order in which it appeared in the file.
  2202. if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
  2203. cast<VarDecl>(Global)->hasInit()) {
  2204. DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
  2205. CXXGlobalInits.push_back(nullptr);
  2206. }
  2207. StringRef MangledName = getMangledName(GD);
  2208. if (GetGlobalValue(MangledName) != nullptr) {
  2209. // The value has already been used and should therefore be emitted.
  2210. addDeferredDeclToEmit(GD);
  2211. } else if (MustBeEmitted(Global)) {
  2212. // The value must be emitted, but cannot be emitted eagerly.
  2213. assert(!MayBeEmittedEagerly(Global));
  2214. addDeferredDeclToEmit(GD);
  2215. } else {
  2216. // Otherwise, remember that we saw a deferred decl with this name. The
  2217. // first use of the mangled name will cause it to move into
  2218. // DeferredDeclsToEmit.
  2219. DeferredDecls[MangledName] = GD;
  2220. }
  2221. }
  2222. // Check if T is a class type with a destructor that's not dllimport.
  2223. static bool HasNonDllImportDtor(QualType T) {
  2224. if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>())
  2225. if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
  2226. if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
  2227. return true;
  2228. return false;
  2229. }
  2230. namespace {
  2231. struct FunctionIsDirectlyRecursive
  2232. : public ConstStmtVisitor<FunctionIsDirectlyRecursive, bool> {
  2233. const StringRef Name;
  2234. const Builtin::Context &BI;
  2235. FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C)
  2236. : Name(N), BI(C) {}
  2237. bool VisitCallExpr(const CallExpr *E) {
  2238. const FunctionDecl *FD = E->getDirectCallee();
  2239. if (!FD)
  2240. return false;
  2241. AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
  2242. if (Attr && Name == Attr->getLabel())
  2243. return true;
  2244. unsigned BuiltinID = FD->getBuiltinID();
  2245. if (!BuiltinID || !BI.isLibFunction(BuiltinID))
  2246. return false;
  2247. StringRef BuiltinName = BI.getName(BuiltinID);
  2248. if (BuiltinName.startswith("__builtin_") &&
  2249. Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
  2250. return true;
  2251. }
  2252. return false;
  2253. }
  2254. bool VisitStmt(const Stmt *S) {
  2255. for (const Stmt *Child : S->children())
  2256. if (Child && this->Visit(Child))
  2257. return true;
  2258. return false;
  2259. }
  2260. };
  2261. // Make sure we're not referencing non-imported vars or functions.
  2262. struct DLLImportFunctionVisitor
  2263. : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
  2264. bool SafeToInline = true;
  2265. bool shouldVisitImplicitCode() const { return true; }
  2266. bool VisitVarDecl(VarDecl *VD) {
  2267. if (VD->getTLSKind()) {
  2268. // A thread-local variable cannot be imported.
  2269. SafeToInline = false;
  2270. return SafeToInline;
  2271. }
  2272. // A variable definition might imply a destructor call.
  2273. if (VD->isThisDeclarationADefinition())
  2274. SafeToInline = !HasNonDllImportDtor(VD->getType());
  2275. return SafeToInline;
  2276. }
  2277. bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
  2278. if (const auto *D = E->getTemporary()->getDestructor())
  2279. SafeToInline = D->hasAttr<DLLImportAttr>();
  2280. return SafeToInline;
  2281. }
  2282. bool VisitDeclRefExpr(DeclRefExpr *E) {
  2283. ValueDecl *VD = E->getDecl();
  2284. if (isa<FunctionDecl>(VD))
  2285. SafeToInline = VD->hasAttr<DLLImportAttr>();
  2286. else if (VarDecl *V = dyn_cast<VarDecl>(VD))
  2287. SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
  2288. return SafeToInline;
  2289. }
  2290. bool VisitCXXConstructExpr(CXXConstructExpr *E) {
  2291. SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
  2292. return SafeToInline;
  2293. }
  2294. bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
  2295. CXXMethodDecl *M = E->getMethodDecl();
  2296. if (!M) {
  2297. // Call through a pointer to member function. This is safe to inline.
  2298. SafeToInline = true;
  2299. } else {
  2300. SafeToInline = M->hasAttr<DLLImportAttr>();
  2301. }
  2302. return SafeToInline;
  2303. }
  2304. bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
  2305. SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
  2306. return SafeToInline;
  2307. }
  2308. bool VisitCXXNewExpr(CXXNewExpr *E) {
  2309. SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
  2310. return SafeToInline;
  2311. }
  2312. };
  2313. }
  2314. // isTriviallyRecursive - Check if this function calls another
  2315. // decl that, because of the asm attribute or the other decl being a builtin,
  2316. // ends up pointing to itself.
  2317. bool
  2318. CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
  2319. StringRef Name;
  2320. if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
  2321. // asm labels are a special kind of mangling we have to support.
  2322. AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
  2323. if (!Attr)
  2324. return false;
  2325. Name = Attr->getLabel();
  2326. } else {
  2327. Name = FD->getName();
  2328. }
  2329. FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
  2330. const Stmt *Body = FD->getBody();
  2331. return Body ? Walker.Visit(Body) : false;
  2332. }
  2333. bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
  2334. if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
  2335. return true;
  2336. const auto *F = cast<FunctionDecl>(GD.getDecl());
  2337. if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
  2338. return false;
  2339. if (F->hasAttr<DLLImportAttr>()) {
  2340. // Check whether it would be safe to inline this dllimport function.
  2341. DLLImportFunctionVisitor Visitor;
  2342. Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
  2343. if (!Visitor.SafeToInline)
  2344. return false;
  2345. if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
  2346. // Implicit destructor invocations aren't captured in the AST, so the
  2347. // check above can't see them. Check for them manually here.
  2348. for (const Decl *Member : Dtor->getParent()->decls())
  2349. if (isa<FieldDecl>(Member))
  2350. if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType()))
  2351. return false;
  2352. for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
  2353. if (HasNonDllImportDtor(B.getType()))
  2354. return false;
  2355. }
  2356. }
  2357. // PR9614. Avoid cases where the source code is lying to us. An available
  2358. // externally function should have an equivalent function somewhere else,
  2359. // but a function that calls itself is clearly not equivalent to the real
  2360. // implementation.
  2361. // This happens in glibc's btowc and in some configure checks.
  2362. return !isTriviallyRecursive(F);
  2363. }
  2364. bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
  2365. return CodeGenOpts.OptimizationLevel > 0;
  2366. }
  2367. void CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD,
  2368. llvm::GlobalValue *GV) {
  2369. const auto *FD = cast<FunctionDecl>(GD.getDecl());
  2370. if (FD->isCPUSpecificMultiVersion()) {
  2371. auto *Spec = FD->getAttr<CPUSpecificAttr>();
  2372. for (unsigned I = 0; I < Spec->cpus_size(); ++I)
  2373. EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr);
  2374. // Requires multiple emits.
  2375. } else
  2376. EmitGlobalFunctionDefinition(GD, GV);
  2377. }
  2378. void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
  2379. const auto *D = cast<ValueDecl>(GD.getDecl());
  2380. PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
  2381. Context.getSourceManager(),
  2382. "Generating code for declaration");
  2383. if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
  2384. // At -O0, don't generate IR for functions with available_externally
  2385. // linkage.
  2386. if (!shouldEmitFunction(GD))
  2387. return;
  2388. llvm::TimeTraceScope TimeScope("CodeGen Function", [&]() {
  2389. std::string Name;
  2390. llvm::raw_string_ostream OS(Name);
  2391. FD->getNameForDiagnostic(OS, getContext().getPrintingPolicy(),
  2392. /*Qualified=*/true);
  2393. return Name;
  2394. });
  2395. if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
  2396. // Make sure to emit the definition(s) before we emit the thunks.
  2397. // This is necessary for the generation of certain thunks.
  2398. if (isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method))
  2399. ABI->emitCXXStructor(GD);
  2400. else if (FD->isMultiVersion())
  2401. EmitMultiVersionFunctionDefinition(GD, GV);
  2402. else
  2403. EmitGlobalFunctionDefinition(GD, GV);
  2404. if (Method->isVirtual())
  2405. getVTables().EmitThunks(GD);
  2406. return;
  2407. }
  2408. if (FD->isMultiVersion())
  2409. return EmitMultiVersionFunctionDefinition(GD, GV);
  2410. return EmitGlobalFunctionDefinition(GD, GV);
  2411. }
  2412. if (const auto *VD = dyn_cast<VarDecl>(D))
  2413. return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
  2414. llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
  2415. }
  2416. static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
  2417. llvm::Function *NewFn);
  2418. static unsigned
  2419. TargetMVPriority(const TargetInfo &TI,
  2420. const CodeGenFunction::MultiVersionResolverOption &RO) {
  2421. unsigned Priority = 0;
  2422. for (StringRef Feat : RO.Conditions.Features)
  2423. Priority = std::max(Priority, TI.multiVersionSortPriority(Feat));
  2424. if (!RO.Conditions.Architecture.empty())
  2425. Priority = std::max(
  2426. Priority, TI.multiVersionSortPriority(RO.Conditions.Architecture));
  2427. return Priority;
  2428. }
  2429. void CodeGenModule::emitMultiVersionFunctions() {
  2430. for (GlobalDecl GD : MultiVersionFuncs) {
  2431. SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
  2432. const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
  2433. getContext().forEachMultiversionedFunctionVersion(
  2434. FD, [this, &GD, &Options](const FunctionDecl *CurFD) {
  2435. GlobalDecl CurGD{
  2436. (CurFD->isDefined() ? CurFD->getDefinition() : CurFD)};
  2437. StringRef MangledName = getMangledName(CurGD);
  2438. llvm::Constant *Func = GetGlobalValue(MangledName);
  2439. if (!Func) {
  2440. if (CurFD->isDefined()) {
  2441. EmitGlobalFunctionDefinition(CurGD, nullptr);
  2442. Func = GetGlobalValue(MangledName);
  2443. } else {
  2444. const CGFunctionInfo &FI =
  2445. getTypes().arrangeGlobalDeclaration(GD);
  2446. llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
  2447. Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false,
  2448. /*DontDefer=*/false, ForDefinition);
  2449. }
  2450. assert(Func && "This should have just been created");
  2451. }
  2452. const auto *TA = CurFD->getAttr<TargetAttr>();
  2453. llvm::SmallVector<StringRef, 8> Feats;
  2454. TA->getAddedFeatures(Feats);
  2455. Options.emplace_back(cast<llvm::Function>(Func),
  2456. TA->getArchitecture(), Feats);
  2457. });
  2458. llvm::Function *ResolverFunc;
  2459. const TargetInfo &TI = getTarget();
  2460. if (TI.supportsIFunc() || FD->isTargetMultiVersion()) {
  2461. ResolverFunc = cast<llvm::Function>(
  2462. GetGlobalValue((getMangledName(GD) + ".resolver").str()));
  2463. ResolverFunc->setLinkage(llvm::Function::WeakODRLinkage);
  2464. } else {
  2465. ResolverFunc = cast<llvm::Function>(GetGlobalValue(getMangledName(GD)));
  2466. }
  2467. if (supportsCOMDAT())
  2468. ResolverFunc->setComdat(
  2469. getModule().getOrInsertComdat(ResolverFunc->getName()));
  2470. llvm::stable_sort(
  2471. Options, [&TI](const CodeGenFunction::MultiVersionResolverOption &LHS,
  2472. const CodeGenFunction::MultiVersionResolverOption &RHS) {
  2473. return TargetMVPriority(TI, LHS) > TargetMVPriority(TI, RHS);
  2474. });
  2475. CodeGenFunction CGF(*this);
  2476. CGF.EmitMultiVersionResolver(ResolverFunc, Options);
  2477. }
  2478. }
  2479. void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) {
  2480. const auto *FD = cast<FunctionDecl>(GD.getDecl());
  2481. assert(FD && "Not a FunctionDecl?");
  2482. const auto *DD = FD->getAttr<CPUDispatchAttr>();
  2483. assert(DD && "Not a cpu_dispatch Function?");
  2484. llvm::Type *DeclTy = getTypes().ConvertType(FD->getType());
  2485. if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) {
  2486. const CGFunctionInfo &FInfo = getTypes().arrangeCXXMethodDeclaration(CXXFD);
  2487. DeclTy = getTypes().GetFunctionType(FInfo);
  2488. }
  2489. StringRef ResolverName = getMangledName(GD);
  2490. llvm::Type *ResolverType;
  2491. GlobalDecl ResolverGD;
  2492. if (getTarget().supportsIFunc())
  2493. ResolverType = llvm::FunctionType::get(
  2494. llvm::PointerType::get(DeclTy,
  2495. Context.getTargetAddressSpace(FD->getType())),
  2496. false);
  2497. else {
  2498. ResolverType = DeclTy;
  2499. ResolverGD = GD;
  2500. }
  2501. auto *ResolverFunc = cast<llvm::Function>(GetOrCreateLLVMFunction(
  2502. ResolverName, ResolverType, ResolverGD, /*ForVTable=*/false));
  2503. ResolverFunc->setLinkage(llvm::Function::WeakODRLinkage);
  2504. if (supportsCOMDAT())
  2505. ResolverFunc->setComdat(
  2506. getModule().getOrInsertComdat(ResolverFunc->getName()));
  2507. SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
  2508. const TargetInfo &Target = getTarget();
  2509. unsigned Index = 0;
  2510. for (const IdentifierInfo *II : DD->cpus()) {
  2511. // Get the name of the target function so we can look it up/create it.
  2512. std::string MangledName = getMangledNameImpl(*this, GD, FD, true) +
  2513. getCPUSpecificMangling(*this, II->getName());
  2514. llvm::Constant *Func = GetGlobalValue(MangledName);
  2515. if (!Func) {
  2516. GlobalDecl ExistingDecl = Manglings.lookup(MangledName);
  2517. if (ExistingDecl.getDecl() &&
  2518. ExistingDecl.getDecl()->getAsFunction()->isDefined()) {
  2519. EmitGlobalFunctionDefinition(ExistingDecl, nullptr);
  2520. Func = GetGlobalValue(MangledName);
  2521. } else {
  2522. if (!ExistingDecl.getDecl())
  2523. ExistingDecl = GD.getWithMultiVersionIndex(Index);
  2524. Func = GetOrCreateLLVMFunction(
  2525. MangledName, DeclTy, ExistingDecl,
  2526. /*ForVTable=*/false, /*DontDefer=*/true,
  2527. /*IsThunk=*/false, llvm::AttributeList(), ForDefinition);
  2528. }
  2529. }
  2530. llvm::SmallVector<StringRef, 32> Features;
  2531. Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features);
  2532. llvm::transform(Features, Features.begin(),
  2533. [](StringRef Str) { return Str.substr(1); });
  2534. Features.erase(std::remove_if(
  2535. Features.begin(), Features.end(), [&Target](StringRef Feat) {
  2536. return !Target.validateCpuSupports(Feat);
  2537. }), Features.end());
  2538. Options.emplace_back(cast<llvm::Function>(Func), StringRef{}, Features);
  2539. ++Index;
  2540. }
  2541. llvm::sort(
  2542. Options, [](const CodeGenFunction::MultiVersionResolverOption &LHS,
  2543. const CodeGenFunction::MultiVersionResolverOption &RHS) {
  2544. return CodeGenFunction::GetX86CpuSupportsMask(LHS.Conditions.Features) >
  2545. CodeGenFunction::GetX86CpuSupportsMask(RHS.Conditions.Features);
  2546. });
  2547. // If the list contains multiple 'default' versions, such as when it contains
  2548. // 'pentium' and 'generic', don't emit the call to the generic one (since we
  2549. // always run on at least a 'pentium'). We do this by deleting the 'least
  2550. // advanced' (read, lowest mangling letter).
  2551. while (Options.size() > 1 &&
  2552. CodeGenFunction::GetX86CpuSupportsMask(
  2553. (Options.end() - 2)->Conditions.Features) == 0) {
  2554. StringRef LHSName = (Options.end() - 2)->Function->getName();
  2555. StringRef RHSName = (Options.end() - 1)->Function->getName();
  2556. if (LHSName.compare(RHSName) < 0)
  2557. Options.erase(Options.end() - 2);
  2558. else
  2559. Options.erase(Options.end() - 1);
  2560. }
  2561. CodeGenFunction CGF(*this);
  2562. CGF.EmitMultiVersionResolver(ResolverFunc, Options);
  2563. if (getTarget().supportsIFunc()) {
  2564. std::string AliasName = getMangledNameImpl(
  2565. *this, GD, FD, /*OmitMultiVersionMangling=*/true);
  2566. llvm::Constant *AliasFunc = GetGlobalValue(AliasName);
  2567. if (!AliasFunc) {
  2568. auto *IFunc = cast<llvm::GlobalIFunc>(GetOrCreateLLVMFunction(
  2569. AliasName, DeclTy, GD, /*ForVTable=*/false, /*DontDefer=*/true,
  2570. /*IsThunk=*/false, llvm::AttributeList(), NotForDefinition));
  2571. auto *GA = llvm::GlobalAlias::create(
  2572. DeclTy, 0, getFunctionLinkage(GD), AliasName, IFunc, &getModule());
  2573. GA->setLinkage(llvm::Function::WeakODRLinkage);
  2574. SetCommonAttributes(GD, GA);
  2575. }
  2576. }
  2577. }
  2578. /// If a dispatcher for the specified mangled name is not in the module, create
  2579. /// and return an llvm Function with the specified type.
  2580. llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver(
  2581. GlobalDecl GD, llvm::Type *DeclTy, const FunctionDecl *FD) {
  2582. std::string MangledName =
  2583. getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
  2584. // Holds the name of the resolver, in ifunc mode this is the ifunc (which has
  2585. // a separate resolver).
  2586. std::string ResolverName = MangledName;
  2587. if (getTarget().supportsIFunc())
  2588. ResolverName += ".ifunc";
  2589. else if (FD->isTargetMultiVersion())
  2590. ResolverName += ".resolver";
  2591. // If this already exists, just return that one.
  2592. if (llvm::GlobalValue *ResolverGV = GetGlobalValue(ResolverName))
  2593. return ResolverGV;
  2594. // Since this is the first time we've created this IFunc, make sure
  2595. // that we put this multiversioned function into the list to be
  2596. // replaced later if necessary (target multiversioning only).
  2597. if (!FD->isCPUDispatchMultiVersion() && !FD->isCPUSpecificMultiVersion())
  2598. MultiVersionFuncs.push_back(GD);
  2599. if (getTarget().supportsIFunc()) {
  2600. llvm::Type *ResolverType = llvm::FunctionType::get(
  2601. llvm::PointerType::get(
  2602. DeclTy, getContext().getTargetAddressSpace(FD->getType())),
  2603. false);
  2604. llvm::Constant *Resolver = GetOrCreateLLVMFunction(
  2605. MangledName + ".resolver", ResolverType, GlobalDecl{},
  2606. /*ForVTable=*/false);
  2607. llvm::GlobalIFunc *GIF = llvm::GlobalIFunc::create(
  2608. DeclTy, 0, llvm::Function::WeakODRLinkage, "", Resolver, &getModule());
  2609. GIF->setName(ResolverName);
  2610. SetCommonAttributes(FD, GIF);
  2611. return GIF;
  2612. }
  2613. llvm::Constant *Resolver = GetOrCreateLLVMFunction(
  2614. ResolverName, DeclTy, GlobalDecl{}, /*ForVTable=*/false);
  2615. assert(isa<llvm::GlobalValue>(Resolver) &&
  2616. "Resolver should be created for the first time");
  2617. SetCommonAttributes(FD, cast<llvm::GlobalValue>(Resolver));
  2618. return Resolver;
  2619. }
  2620. /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
  2621. /// module, create and return an llvm Function with the specified type. If there
  2622. /// is something in the module with the specified name, return it potentially
  2623. /// bitcasted to the right type.
  2624. ///
  2625. /// If D is non-null, it specifies a decl that correspond to this. This is used
  2626. /// to set the attributes on the function when it is first created.
  2627. llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
  2628. StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable,
  2629. bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs,
  2630. ForDefinition_t IsForDefinition) {
  2631. const Decl *D = GD.getDecl();
  2632. // Any attempts to use a MultiVersion function should result in retrieving
  2633. // the iFunc instead. Name Mangling will handle the rest of the changes.
  2634. if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) {
  2635. // For the device mark the function as one that should be emitted.
  2636. if (getLangOpts().OpenMPIsDevice && OpenMPRuntime &&
  2637. !OpenMPRuntime->markAsGlobalTarget(GD) && FD->isDefined() &&
  2638. !DontDefer && !IsForDefinition) {
  2639. if (const FunctionDecl *FDDef = FD->getDefinition()) {
  2640. GlobalDecl GDDef;
  2641. if (const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef))
  2642. GDDef = GlobalDecl(CD, GD.getCtorType());
  2643. else if (const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef))
  2644. GDDef = GlobalDecl(DD, GD.getDtorType());
  2645. else
  2646. GDDef = GlobalDecl(FDDef);
  2647. EmitGlobal(GDDef);
  2648. }
  2649. }
  2650. if (FD->isMultiVersion()) {
  2651. const auto *TA = FD->getAttr<TargetAttr>();
  2652. if (TA && TA->isDefaultVersion())
  2653. UpdateMultiVersionNames(GD, FD);
  2654. if (!IsForDefinition)
  2655. return GetOrCreateMultiVersionResolver(GD, Ty, FD);
  2656. }
  2657. }
  2658. // Lookup the entry, lazily creating it if necessary.
  2659. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  2660. if (Entry) {
  2661. if (WeakRefReferences.erase(Entry)) {
  2662. const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
  2663. if (FD && !FD->hasAttr<WeakAttr>())
  2664. Entry->setLinkage(llvm::Function::ExternalLinkage);
  2665. }
  2666. // Handle dropped DLL attributes.
  2667. if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) {
  2668. Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
  2669. setDSOLocal(Entry);
  2670. }
  2671. // If there are two attempts to define the same mangled name, issue an
  2672. // error.
  2673. if (IsForDefinition && !Entry->isDeclaration()) {
  2674. GlobalDecl OtherGD;
  2675. // Check that GD is not yet in DiagnosedConflictingDefinitions is required
  2676. // to make sure that we issue an error only once.
  2677. if (lookupRepresentativeDecl(MangledName, OtherGD) &&
  2678. (GD.getCanonicalDecl().getDecl() !=
  2679. OtherGD.getCanonicalDecl().getDecl()) &&
  2680. DiagnosedConflictingDefinitions.insert(GD).second) {
  2681. getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
  2682. << MangledName;
  2683. getDiags().Report(OtherGD.getDecl()->getLocation(),
  2684. diag::note_previous_definition);
  2685. }
  2686. }
  2687. if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
  2688. (Entry->getType()->getElementType() == Ty)) {
  2689. return Entry;
  2690. }
  2691. // Make sure the result is of the correct type.
  2692. // (If function is requested for a definition, we always need to create a new
  2693. // function, not just return a bitcast.)
  2694. if (!IsForDefinition)
  2695. return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
  2696. }
  2697. // This function doesn't have a complete type (for example, the return
  2698. // type is an incomplete struct). Use a fake type instead, and make
  2699. // sure not to try to set attributes.
  2700. bool IsIncompleteFunction = false;
  2701. llvm::FunctionType *FTy;
  2702. if (isa<llvm::FunctionType>(Ty)) {
  2703. FTy = cast<llvm::FunctionType>(Ty);
  2704. } else {
  2705. FTy = llvm::FunctionType::get(VoidTy, false);
  2706. IsIncompleteFunction = true;
  2707. }
  2708. llvm::Function *F =
  2709. llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
  2710. Entry ? StringRef() : MangledName, &getModule());
  2711. // If we already created a function with the same mangled name (but different
  2712. // type) before, take its name and add it to the list of functions to be
  2713. // replaced with F at the end of CodeGen.
  2714. //
  2715. // This happens if there is a prototype for a function (e.g. "int f()") and
  2716. // then a definition of a different type (e.g. "int f(int x)").
  2717. if (Entry) {
  2718. F->takeName(Entry);
  2719. // This might be an implementation of a function without a prototype, in
  2720. // which case, try to do special replacement of calls which match the new
  2721. // prototype. The really key thing here is that we also potentially drop
  2722. // arguments from the call site so as to make a direct call, which makes the
  2723. // inliner happier and suppresses a number of optimizer warnings (!) about
  2724. // dropping arguments.
  2725. if (!Entry->use_empty()) {
  2726. ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
  2727. Entry->removeDeadConstantUsers();
  2728. }
  2729. llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
  2730. F, Entry->getType()->getElementType()->getPointerTo());
  2731. addGlobalValReplacement(Entry, BC);
  2732. }
  2733. assert(F->getName() == MangledName && "name was uniqued!");
  2734. if (D)
  2735. SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
  2736. if (ExtraAttrs.hasAttributes(llvm::AttributeList::FunctionIndex)) {
  2737. llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex);
  2738. F->addAttributes(llvm::AttributeList::FunctionIndex, B);
  2739. }
  2740. if (!DontDefer) {
  2741. // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
  2742. // each other bottoming out with the base dtor. Therefore we emit non-base
  2743. // dtors on usage, even if there is no dtor definition in the TU.
  2744. if (D && isa<CXXDestructorDecl>(D) &&
  2745. getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
  2746. GD.getDtorType()))
  2747. addDeferredDeclToEmit(GD);
  2748. // This is the first use or definition of a mangled name. If there is a
  2749. // deferred decl with this name, remember that we need to emit it at the end
  2750. // of the file.
  2751. auto DDI = DeferredDecls.find(MangledName);
  2752. if (DDI != DeferredDecls.end()) {
  2753. // Move the potentially referenced deferred decl to the
  2754. // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
  2755. // don't need it anymore).
  2756. addDeferredDeclToEmit(DDI->second);
  2757. DeferredDecls.erase(DDI);
  2758. // Otherwise, there are cases we have to worry about where we're
  2759. // using a declaration for which we must emit a definition but where
  2760. // we might not find a top-level definition:
  2761. // - member functions defined inline in their classes
  2762. // - friend functions defined inline in some class
  2763. // - special member functions with implicit definitions
  2764. // If we ever change our AST traversal to walk into class methods,
  2765. // this will be unnecessary.
  2766. //
  2767. // We also don't emit a definition for a function if it's going to be an
  2768. // entry in a vtable, unless it's already marked as used.
  2769. } else if (getLangOpts().CPlusPlus && D) {
  2770. // Look for a declaration that's lexically in a record.
  2771. for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
  2772. FD = FD->getPreviousDecl()) {
  2773. if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
  2774. if (FD->doesThisDeclarationHaveABody()) {
  2775. addDeferredDeclToEmit(GD.getWithDecl(FD));
  2776. break;
  2777. }
  2778. }
  2779. }
  2780. }
  2781. }
  2782. // Make sure the result is of the requested type.
  2783. if (!IsIncompleteFunction) {
  2784. assert(F->getType()->getElementType() == Ty);
  2785. return F;
  2786. }
  2787. llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
  2788. return llvm::ConstantExpr::getBitCast(F, PTy);
  2789. }
  2790. /// GetAddrOfFunction - Return the address of the given function. If Ty is
  2791. /// non-null, then this function will use the specified type if it has to
  2792. /// create it (this occurs when we see a definition of the function).
  2793. llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
  2794. llvm::Type *Ty,
  2795. bool ForVTable,
  2796. bool DontDefer,
  2797. ForDefinition_t IsForDefinition) {
  2798. // If there was no specific requested type, just convert it now.
  2799. if (!Ty) {
  2800. const auto *FD = cast<FunctionDecl>(GD.getDecl());
  2801. Ty = getTypes().ConvertType(FD->getType());
  2802. }
  2803. // Devirtualized destructor calls may come through here instead of via
  2804. // getAddrOfCXXStructor. Make sure we use the MS ABI base destructor instead
  2805. // of the complete destructor when necessary.
  2806. if (const auto *DD = dyn_cast<CXXDestructorDecl>(GD.getDecl())) {
  2807. if (getTarget().getCXXABI().isMicrosoft() &&
  2808. GD.getDtorType() == Dtor_Complete &&
  2809. DD->getParent()->getNumVBases() == 0)
  2810. GD = GlobalDecl(DD, Dtor_Base);
  2811. }
  2812. StringRef MangledName = getMangledName(GD);
  2813. return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
  2814. /*IsThunk=*/false, llvm::AttributeList(),
  2815. IsForDefinition);
  2816. }
  2817. static const FunctionDecl *
  2818. GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
  2819. TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
  2820. DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
  2821. IdentifierInfo &CII = C.Idents.get(Name);
  2822. for (const auto &Result : DC->lookup(&CII))
  2823. if (const auto FD = dyn_cast<FunctionDecl>(Result))
  2824. return FD;
  2825. if (!C.getLangOpts().CPlusPlus)
  2826. return nullptr;
  2827. // Demangle the premangled name from getTerminateFn()
  2828. IdentifierInfo &CXXII =
  2829. (Name == "_ZSt9terminatev" || Name == "?terminate@@YAXXZ")
  2830. ? C.Idents.get("terminate")
  2831. : C.Idents.get(Name);
  2832. for (const auto &N : {"__cxxabiv1", "std"}) {
  2833. IdentifierInfo &NS = C.Idents.get(N);
  2834. for (const auto &Result : DC->lookup(&NS)) {
  2835. NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
  2836. if (auto LSD = dyn_cast<LinkageSpecDecl>(Result))
  2837. for (const auto &Result : LSD->lookup(&NS))
  2838. if ((ND = dyn_cast<NamespaceDecl>(Result)))
  2839. break;
  2840. if (ND)
  2841. for (const auto &Result : ND->lookup(&CXXII))
  2842. if (const auto *FD = dyn_cast<FunctionDecl>(Result))
  2843. return FD;
  2844. }
  2845. }
  2846. return nullptr;
  2847. }
  2848. /// CreateRuntimeFunction - Create a new runtime function with the specified
  2849. /// type and name.
  2850. llvm::FunctionCallee
  2851. CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
  2852. llvm::AttributeList ExtraAttrs,
  2853. bool Local) {
  2854. llvm::Constant *C =
  2855. GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
  2856. /*DontDefer=*/false, /*IsThunk=*/false,
  2857. ExtraAttrs);
  2858. if (auto *F = dyn_cast<llvm::Function>(C)) {
  2859. if (F->empty()) {
  2860. F->setCallingConv(getRuntimeCC());
  2861. // In Windows Itanium environments, try to mark runtime functions
  2862. // dllimport. For Mingw and MSVC, don't. We don't really know if the user
  2863. // will link their standard library statically or dynamically. Marking
  2864. // functions imported when they are not imported can cause linker errors
  2865. // and warnings.
  2866. if (!Local && getTriple().isWindowsItaniumEnvironment() &&
  2867. !getCodeGenOpts().LTOVisibilityPublicStd) {
  2868. const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
  2869. if (!FD || FD->hasAttr<DLLImportAttr>()) {
  2870. F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
  2871. F->setLinkage(llvm::GlobalValue::ExternalLinkage);
  2872. }
  2873. }
  2874. setDSOLocal(F);
  2875. }
  2876. }
  2877. return {FTy, C};
  2878. }
  2879. /// isTypeConstant - Determine whether an object of this type can be emitted
  2880. /// as a constant.
  2881. ///
  2882. /// If ExcludeCtor is true, the duration when the object's constructor runs
  2883. /// will not be considered. The caller will need to verify that the object is
  2884. /// not written to during its construction.
  2885. bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
  2886. if (!Ty.isConstant(Context) && !Ty->isReferenceType())
  2887. return false;
  2888. if (Context.getLangOpts().CPlusPlus) {
  2889. if (const CXXRecordDecl *Record
  2890. = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
  2891. return ExcludeCtor && !Record->hasMutableFields() &&
  2892. Record->hasTrivialDestructor();
  2893. }
  2894. return true;
  2895. }
  2896. /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
  2897. /// create and return an llvm GlobalVariable with the specified type. If there
  2898. /// is something in the module with the specified name, return it potentially
  2899. /// bitcasted to the right type.
  2900. ///
  2901. /// If D is non-null, it specifies a decl that correspond to this. This is used
  2902. /// to set the attributes on the global when it is first created.
  2903. ///
  2904. /// If IsForDefinition is true, it is guaranteed that an actual global with
  2905. /// type Ty will be returned, not conversion of a variable with the same
  2906. /// mangled name but some other type.
  2907. llvm::Constant *
  2908. CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
  2909. llvm::PointerType *Ty,
  2910. const VarDecl *D,
  2911. ForDefinition_t IsForDefinition) {
  2912. // Lookup the entry, lazily creating it if necessary.
  2913. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  2914. if (Entry) {
  2915. if (WeakRefReferences.erase(Entry)) {
  2916. if (D && !D->hasAttr<WeakAttr>())
  2917. Entry->setLinkage(llvm::Function::ExternalLinkage);
  2918. }
  2919. // Handle dropped DLL attributes.
  2920. if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
  2921. Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
  2922. if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D)
  2923. getOpenMPRuntime().registerTargetGlobalVariable(D, Entry);
  2924. if (Entry->getType() == Ty)
  2925. return Entry;
  2926. // If there are two attempts to define the same mangled name, issue an
  2927. // error.
  2928. if (IsForDefinition && !Entry->isDeclaration()) {
  2929. GlobalDecl OtherGD;
  2930. const VarDecl *OtherD;
  2931. // Check that D is not yet in DiagnosedConflictingDefinitions is required
  2932. // to make sure that we issue an error only once.
  2933. if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
  2934. (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
  2935. (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
  2936. OtherD->hasInit() &&
  2937. DiagnosedConflictingDefinitions.insert(D).second) {
  2938. getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
  2939. << MangledName;
  2940. getDiags().Report(OtherGD.getDecl()->getLocation(),
  2941. diag::note_previous_definition);
  2942. }
  2943. }
  2944. // Make sure the result is of the correct type.
  2945. if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
  2946. return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
  2947. // (If global is requested for a definition, we always need to create a new
  2948. // global, not just return a bitcast.)
  2949. if (!IsForDefinition)
  2950. return llvm::ConstantExpr::getBitCast(Entry, Ty);
  2951. }
  2952. auto AddrSpace = GetGlobalVarAddressSpace(D);
  2953. auto TargetAddrSpace = getContext().getTargetAddressSpace(AddrSpace);
  2954. auto *GV = new llvm::GlobalVariable(
  2955. getModule(), Ty->getElementType(), false,
  2956. llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
  2957. llvm::GlobalVariable::NotThreadLocal, TargetAddrSpace);
  2958. // If we already created a global with the same mangled name (but different
  2959. // type) before, take its name and remove it from its parent.
  2960. if (Entry) {
  2961. GV->takeName(Entry);
  2962. if (!Entry->use_empty()) {
  2963. llvm::Constant *NewPtrForOldDecl =
  2964. llvm::ConstantExpr::getBitCast(GV, Entry->getType());
  2965. Entry->replaceAllUsesWith(NewPtrForOldDecl);
  2966. }
  2967. Entry->eraseFromParent();
  2968. }
  2969. // This is the first use or definition of a mangled name. If there is a
  2970. // deferred decl with this name, remember that we need to emit it at the end
  2971. // of the file.
  2972. auto DDI = DeferredDecls.find(MangledName);
  2973. if (DDI != DeferredDecls.end()) {
  2974. // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
  2975. // list, and remove it from DeferredDecls (since we don't need it anymore).
  2976. addDeferredDeclToEmit(DDI->second);
  2977. DeferredDecls.erase(DDI);
  2978. }
  2979. // Handle things which are present even on external declarations.
  2980. if (D) {
  2981. if (LangOpts.OpenMP && !LangOpts.OpenMPSimd)
  2982. getOpenMPRuntime().registerTargetGlobalVariable(D, GV);
  2983. // FIXME: This code is overly simple and should be merged with other global
  2984. // handling.
  2985. GV->setConstant(isTypeConstant(D->getType(), false));
  2986. GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
  2987. setLinkageForGV(GV, D);
  2988. if (D->getTLSKind()) {
  2989. if (D->getTLSKind() == VarDecl::TLS_Dynamic)
  2990. CXXThreadLocals.push_back(D);
  2991. setTLSMode(GV, *D);
  2992. }
  2993. setGVProperties(GV, D);
  2994. // If required by the ABI, treat declarations of static data members with
  2995. // inline initializers as definitions.
  2996. if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
  2997. EmitGlobalVarDefinition(D);
  2998. }
  2999. // Emit section information for extern variables.
  3000. if (D->hasExternalStorage()) {
  3001. if (const SectionAttr *SA = D->getAttr<SectionAttr>())
  3002. GV->setSection(SA->getName());
  3003. }
  3004. // Handle XCore specific ABI requirements.
  3005. if (getTriple().getArch() == llvm::Triple::xcore &&
  3006. D->getLanguageLinkage() == CLanguageLinkage &&
  3007. D->getType().isConstant(Context) &&
  3008. isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
  3009. GV->setSection(".cp.rodata");
  3010. // Check if we a have a const declaration with an initializer, we may be
  3011. // able to emit it as available_externally to expose it's value to the
  3012. // optimizer.
  3013. if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
  3014. D->getType().isConstQualified() && !GV->hasInitializer() &&
  3015. !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) {
  3016. const auto *Record =
  3017. Context.getBaseElementType(D->getType())->getAsCXXRecordDecl();
  3018. bool HasMutableFields = Record && Record->hasMutableFields();
  3019. if (!HasMutableFields) {
  3020. const VarDecl *InitDecl;
  3021. const Expr *InitExpr = D->getAnyInitializer(InitDecl);
  3022. if (InitExpr) {
  3023. ConstantEmitter emitter(*this);
  3024. llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl);
  3025. if (Init) {
  3026. auto *InitType = Init->getType();
  3027. if (GV->getType()->getElementType() != InitType) {
  3028. // The type of the initializer does not match the definition.
  3029. // This happens when an initializer has a different type from
  3030. // the type of the global (because of padding at the end of a
  3031. // structure for instance).
  3032. GV->setName(StringRef());
  3033. // Make a new global with the correct type, this is now guaranteed
  3034. // to work.
  3035. auto *NewGV = cast<llvm::GlobalVariable>(
  3036. GetAddrOfGlobalVar(D, InitType, IsForDefinition));
  3037. // Erase the old global, since it is no longer used.
  3038. GV->eraseFromParent();
  3039. GV = NewGV;
  3040. } else {
  3041. GV->setInitializer(Init);
  3042. GV->setConstant(true);
  3043. GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
  3044. }
  3045. emitter.finalize(GV);
  3046. }
  3047. }
  3048. }
  3049. }
  3050. }
  3051. LangAS ExpectedAS =
  3052. D ? D->getType().getAddressSpace()
  3053. : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default);
  3054. assert(getContext().getTargetAddressSpace(ExpectedAS) ==
  3055. Ty->getPointerAddressSpace());
  3056. if (AddrSpace != ExpectedAS)
  3057. return getTargetCodeGenInfo().performAddrSpaceCast(*this, GV, AddrSpace,
  3058. ExpectedAS, Ty);
  3059. if (GV->isDeclaration())
  3060. getTargetCodeGenInfo().setTargetAttributes(D, GV, *this);
  3061. return GV;
  3062. }
  3063. llvm::Constant *
  3064. CodeGenModule::GetAddrOfGlobal(GlobalDecl GD,
  3065. ForDefinition_t IsForDefinition) {
  3066. const Decl *D = GD.getDecl();
  3067. if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
  3068. return getAddrOfCXXStructor(GD, /*FnInfo=*/nullptr, /*FnType=*/nullptr,
  3069. /*DontDefer=*/false, IsForDefinition);
  3070. else if (isa<CXXMethodDecl>(D)) {
  3071. auto FInfo = &getTypes().arrangeCXXMethodDeclaration(
  3072. cast<CXXMethodDecl>(D));
  3073. auto Ty = getTypes().GetFunctionType(*FInfo);
  3074. return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
  3075. IsForDefinition);
  3076. } else if (isa<FunctionDecl>(D)) {
  3077. const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
  3078. llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
  3079. return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
  3080. IsForDefinition);
  3081. } else
  3082. return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr,
  3083. IsForDefinition);
  3084. }
  3085. llvm::GlobalVariable *CodeGenModule::CreateOrReplaceCXXRuntimeVariable(
  3086. StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage,
  3087. unsigned Alignment) {
  3088. llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
  3089. llvm::GlobalVariable *OldGV = nullptr;
  3090. if (GV) {
  3091. // Check if the variable has the right type.
  3092. if (GV->getType()->getElementType() == Ty)
  3093. return GV;
  3094. // Because C++ name mangling, the only way we can end up with an already
  3095. // existing global with the same name is if it has been declared extern "C".
  3096. assert(GV->isDeclaration() && "Declaration has wrong type!");
  3097. OldGV = GV;
  3098. }
  3099. // Create a new variable.
  3100. GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
  3101. Linkage, nullptr, Name);
  3102. if (OldGV) {
  3103. // Replace occurrences of the old variable if needed.
  3104. GV->takeName(OldGV);
  3105. if (!OldGV->use_empty()) {
  3106. llvm::Constant *NewPtrForOldDecl =
  3107. llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
  3108. OldGV->replaceAllUsesWith(NewPtrForOldDecl);
  3109. }
  3110. OldGV->eraseFromParent();
  3111. }
  3112. if (supportsCOMDAT() && GV->isWeakForLinker() &&
  3113. !GV->hasAvailableExternallyLinkage())
  3114. GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
  3115. GV->setAlignment(Alignment);
  3116. return GV;
  3117. }
  3118. /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
  3119. /// given global variable. If Ty is non-null and if the global doesn't exist,
  3120. /// then it will be created with the specified type instead of whatever the
  3121. /// normal requested type would be. If IsForDefinition is true, it is guaranteed
  3122. /// that an actual global with type Ty will be returned, not conversion of a
  3123. /// variable with the same mangled name but some other type.
  3124. llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
  3125. llvm::Type *Ty,
  3126. ForDefinition_t IsForDefinition) {
  3127. assert(D->hasGlobalStorage() && "Not a global variable");
  3128. QualType ASTTy = D->getType();
  3129. if (!Ty)
  3130. Ty = getTypes().ConvertTypeForMem(ASTTy);
  3131. llvm::PointerType *PTy =
  3132. llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
  3133. StringRef MangledName = getMangledName(D);
  3134. return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition);
  3135. }
  3136. /// CreateRuntimeVariable - Create a new runtime global variable with the
  3137. /// specified type and name.
  3138. llvm::Constant *
  3139. CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
  3140. StringRef Name) {
  3141. auto PtrTy =
  3142. getContext().getLangOpts().OpenCL
  3143. ? llvm::PointerType::get(
  3144. Ty, getContext().getTargetAddressSpace(LangAS::opencl_global))
  3145. : llvm::PointerType::getUnqual(Ty);
  3146. auto *Ret = GetOrCreateLLVMGlobal(Name, PtrTy, nullptr);
  3147. setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts()));
  3148. return Ret;
  3149. }
  3150. void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
  3151. assert(!D->getInit() && "Cannot emit definite definitions here!");
  3152. StringRef MangledName = getMangledName(D);
  3153. llvm::GlobalValue *GV = GetGlobalValue(MangledName);
  3154. // We already have a definition, not declaration, with the same mangled name.
  3155. // Emitting of declaration is not required (and actually overwrites emitted
  3156. // definition).
  3157. if (GV && !GV->isDeclaration())
  3158. return;
  3159. // If we have not seen a reference to this variable yet, place it into the
  3160. // deferred declarations table to be emitted if needed later.
  3161. if (!MustBeEmitted(D) && !GV) {
  3162. DeferredDecls[MangledName] = D;
  3163. return;
  3164. }
  3165. // The tentative definition is the only definition.
  3166. EmitGlobalVarDefinition(D);
  3167. }
  3168. CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
  3169. return Context.toCharUnitsFromBits(
  3170. getDataLayout().getTypeStoreSizeInBits(Ty));
  3171. }
  3172. LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) {
  3173. LangAS AddrSpace = LangAS::Default;
  3174. if (LangOpts.OpenCL) {
  3175. AddrSpace = D ? D->getType().getAddressSpace() : LangAS::opencl_global;
  3176. assert(AddrSpace == LangAS::opencl_global ||
  3177. AddrSpace == LangAS::opencl_constant ||
  3178. AddrSpace == LangAS::opencl_local ||
  3179. AddrSpace >= LangAS::FirstTargetAddressSpace);
  3180. return AddrSpace;
  3181. }
  3182. if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
  3183. if (D && D->hasAttr<CUDAConstantAttr>())
  3184. return LangAS::cuda_constant;
  3185. else if (D && D->hasAttr<CUDASharedAttr>())
  3186. return LangAS::cuda_shared;
  3187. else if (D && D->hasAttr<CUDADeviceAttr>())
  3188. return LangAS::cuda_device;
  3189. else if (D && D->getType().isConstQualified())
  3190. return LangAS::cuda_constant;
  3191. else
  3192. return LangAS::cuda_device;
  3193. }
  3194. if (LangOpts.OpenMP) {
  3195. LangAS AS;
  3196. if (OpenMPRuntime->hasAllocateAttributeForGlobalVar(D, AS))
  3197. return AS;
  3198. }
  3199. return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D);
  3200. }
  3201. LangAS CodeGenModule::getStringLiteralAddressSpace() const {
  3202. // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
  3203. if (LangOpts.OpenCL)
  3204. return LangAS::opencl_constant;
  3205. if (auto AS = getTarget().getConstantAddressSpace())
  3206. return AS.getValue();
  3207. return LangAS::Default;
  3208. }
  3209. // In address space agnostic languages, string literals are in default address
  3210. // space in AST. However, certain targets (e.g. amdgcn) request them to be
  3211. // emitted in constant address space in LLVM IR. To be consistent with other
  3212. // parts of AST, string literal global variables in constant address space
  3213. // need to be casted to default address space before being put into address
  3214. // map and referenced by other part of CodeGen.
  3215. // In OpenCL, string literals are in constant address space in AST, therefore
  3216. // they should not be casted to default address space.
  3217. static llvm::Constant *
  3218. castStringLiteralToDefaultAddressSpace(CodeGenModule &CGM,
  3219. llvm::GlobalVariable *GV) {
  3220. llvm::Constant *Cast = GV;
  3221. if (!CGM.getLangOpts().OpenCL) {
  3222. if (auto AS = CGM.getTarget().getConstantAddressSpace()) {
  3223. if (AS != LangAS::Default)
  3224. Cast = CGM.getTargetCodeGenInfo().performAddrSpaceCast(
  3225. CGM, GV, AS.getValue(), LangAS::Default,
  3226. GV->getValueType()->getPointerTo(
  3227. CGM.getContext().getTargetAddressSpace(LangAS::Default)));
  3228. }
  3229. }
  3230. return Cast;
  3231. }
  3232. template<typename SomeDecl>
  3233. void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
  3234. llvm::GlobalValue *GV) {
  3235. if (!getLangOpts().CPlusPlus)
  3236. return;
  3237. // Must have 'used' attribute, or else inline assembly can't rely on
  3238. // the name existing.
  3239. if (!D->template hasAttr<UsedAttr>())
  3240. return;
  3241. // Must have internal linkage and an ordinary name.
  3242. if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
  3243. return;
  3244. // Must be in an extern "C" context. Entities declared directly within
  3245. // a record are not extern "C" even if the record is in such a context.
  3246. const SomeDecl *First = D->getFirstDecl();
  3247. if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
  3248. return;
  3249. // OK, this is an internal linkage entity inside an extern "C" linkage
  3250. // specification. Make a note of that so we can give it the "expected"
  3251. // mangled name if nothing else is using that name.
  3252. std::pair<StaticExternCMap::iterator, bool> R =
  3253. StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
  3254. // If we have multiple internal linkage entities with the same name
  3255. // in extern "C" regions, none of them gets that name.
  3256. if (!R.second)
  3257. R.first->second = nullptr;
  3258. }
  3259. static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
  3260. if (!CGM.supportsCOMDAT())
  3261. return false;
  3262. // Do not set COMDAT attribute for CUDA/HIP stub functions to prevent
  3263. // them being "merged" by the COMDAT Folding linker optimization.
  3264. if (D.hasAttr<CUDAGlobalAttr>())
  3265. return false;
  3266. if (D.hasAttr<SelectAnyAttr>())
  3267. return true;
  3268. GVALinkage Linkage;
  3269. if (auto *VD = dyn_cast<VarDecl>(&D))
  3270. Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
  3271. else
  3272. Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
  3273. switch (Linkage) {
  3274. case GVA_Internal:
  3275. case GVA_AvailableExternally:
  3276. case GVA_StrongExternal:
  3277. return false;
  3278. case GVA_DiscardableODR:
  3279. case GVA_StrongODR:
  3280. return true;
  3281. }
  3282. llvm_unreachable("No such linkage");
  3283. }
  3284. void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
  3285. llvm::GlobalObject &GO) {
  3286. if (!shouldBeInCOMDAT(*this, D))
  3287. return;
  3288. GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
  3289. }
  3290. /// Pass IsTentative as true if you want to create a tentative definition.
  3291. void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
  3292. bool IsTentative) {
  3293. // OpenCL global variables of sampler type are translated to function calls,
  3294. // therefore no need to be translated.
  3295. QualType ASTTy = D->getType();
  3296. if (getLangOpts().OpenCL && ASTTy->isSamplerT())
  3297. return;
  3298. // If this is OpenMP device, check if it is legal to emit this global
  3299. // normally.
  3300. if (LangOpts.OpenMPIsDevice && OpenMPRuntime &&
  3301. OpenMPRuntime->emitTargetGlobalVariable(D))
  3302. return;
  3303. llvm::Constant *Init = nullptr;
  3304. bool NeedsGlobalCtor = false;
  3305. bool NeedsGlobalDtor =
  3306. D->needsDestruction(getContext()) == QualType::DK_cxx_destructor;
  3307. const VarDecl *InitDecl;
  3308. const Expr *InitExpr = D->getAnyInitializer(InitDecl);
  3309. Optional<ConstantEmitter> emitter;
  3310. // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
  3311. // as part of their declaration." Sema has already checked for
  3312. // error cases, so we just need to set Init to UndefValue.
  3313. bool IsCUDASharedVar =
  3314. getLangOpts().CUDAIsDevice && D->hasAttr<CUDASharedAttr>();
  3315. // Shadows of initialized device-side global variables are also left
  3316. // undefined.
  3317. bool IsCUDAShadowVar =
  3318. !getLangOpts().CUDAIsDevice &&
  3319. (D->hasAttr<CUDAConstantAttr>() || D->hasAttr<CUDADeviceAttr>() ||
  3320. D->hasAttr<CUDASharedAttr>());
  3321. // HIP pinned shadow of initialized host-side global variables are also
  3322. // left undefined.
  3323. bool IsHIPPinnedShadowVar =
  3324. getLangOpts().CUDAIsDevice && D->hasAttr<HIPPinnedShadowAttr>();
  3325. if (getLangOpts().CUDA &&
  3326. (IsCUDASharedVar || IsCUDAShadowVar || IsHIPPinnedShadowVar))
  3327. Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy));
  3328. else if (!InitExpr) {
  3329. // This is a tentative definition; tentative definitions are
  3330. // implicitly initialized with { 0 }.
  3331. //
  3332. // Note that tentative definitions are only emitted at the end of
  3333. // a translation unit, so they should never have incomplete
  3334. // type. In addition, EmitTentativeDefinition makes sure that we
  3335. // never attempt to emit a tentative definition if a real one
  3336. // exists. A use may still exists, however, so we still may need
  3337. // to do a RAUW.
  3338. assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
  3339. Init = EmitNullConstant(D->getType());
  3340. } else {
  3341. initializedGlobalDecl = GlobalDecl(D);
  3342. emitter.emplace(*this);
  3343. Init = emitter->tryEmitForInitializer(*InitDecl);
  3344. if (!Init) {
  3345. QualType T = InitExpr->getType();
  3346. if (D->getType()->isReferenceType())
  3347. T = D->getType();
  3348. if (getLangOpts().CPlusPlus) {
  3349. Init = EmitNullConstant(T);
  3350. NeedsGlobalCtor = true;
  3351. } else {
  3352. ErrorUnsupported(D, "static initializer");
  3353. Init = llvm::UndefValue::get(getTypes().ConvertType(T));
  3354. }
  3355. } else {
  3356. // We don't need an initializer, so remove the entry for the delayed
  3357. // initializer position (just in case this entry was delayed) if we
  3358. // also don't need to register a destructor.
  3359. if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
  3360. DelayedCXXInitPosition.erase(D);
  3361. }
  3362. }
  3363. llvm::Type* InitType = Init->getType();
  3364. llvm::Constant *Entry =
  3365. GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
  3366. // Strip off a bitcast if we got one back.
  3367. if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
  3368. assert(CE->getOpcode() == llvm::Instruction::BitCast ||
  3369. CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
  3370. // All zero index gep.
  3371. CE->getOpcode() == llvm::Instruction::GetElementPtr);
  3372. Entry = CE->getOperand(0);
  3373. }
  3374. // Entry is now either a Function or GlobalVariable.
  3375. auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
  3376. // We have a definition after a declaration with the wrong type.
  3377. // We must make a new GlobalVariable* and update everything that used OldGV
  3378. // (a declaration or tentative definition) with the new GlobalVariable*
  3379. // (which will be a definition).
  3380. //
  3381. // This happens if there is a prototype for a global (e.g.
  3382. // "extern int x[];") and then a definition of a different type (e.g.
  3383. // "int x[10];"). This also happens when an initializer has a different type
  3384. // from the type of the global (this happens with unions).
  3385. if (!GV || GV->getType()->getElementType() != InitType ||
  3386. GV->getType()->getAddressSpace() !=
  3387. getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) {
  3388. // Move the old entry aside so that we'll create a new one.
  3389. Entry->setName(StringRef());
  3390. // Make a new global with the correct type, this is now guaranteed to work.
  3391. GV = cast<llvm::GlobalVariable>(
  3392. GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)));
  3393. // Replace all uses of the old global with the new global
  3394. llvm::Constant *NewPtrForOldDecl =
  3395. llvm::ConstantExpr::getBitCast(GV, Entry->getType());
  3396. Entry->replaceAllUsesWith(NewPtrForOldDecl);
  3397. // Erase the old global, since it is no longer used.
  3398. cast<llvm::GlobalValue>(Entry)->eraseFromParent();
  3399. }
  3400. MaybeHandleStaticInExternC(D, GV);
  3401. if (D->hasAttr<AnnotateAttr>())
  3402. AddGlobalAnnotations(D, GV);
  3403. // Set the llvm linkage type as appropriate.
  3404. llvm::GlobalValue::LinkageTypes Linkage =
  3405. getLLVMLinkageVarDefinition(D, GV->isConstant());
  3406. // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
  3407. // the device. [...]"
  3408. // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
  3409. // __device__, declares a variable that: [...]
  3410. // Is accessible from all the threads within the grid and from the host
  3411. // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
  3412. // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
  3413. if (GV && LangOpts.CUDA) {
  3414. if (LangOpts.CUDAIsDevice) {
  3415. if (Linkage != llvm::GlobalValue::InternalLinkage &&
  3416. (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()))
  3417. GV->setExternallyInitialized(true);
  3418. } else {
  3419. // Host-side shadows of external declarations of device-side
  3420. // global variables become internal definitions. These have to
  3421. // be internal in order to prevent name conflicts with global
  3422. // host variables with the same name in a different TUs.
  3423. if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() ||
  3424. D->hasAttr<HIPPinnedShadowAttr>()) {
  3425. Linkage = llvm::GlobalValue::InternalLinkage;
  3426. // Shadow variables and their properties must be registered
  3427. // with CUDA runtime.
  3428. unsigned Flags = 0;
  3429. if (!D->hasDefinition())
  3430. Flags |= CGCUDARuntime::ExternDeviceVar;
  3431. if (D->hasAttr<CUDAConstantAttr>())
  3432. Flags |= CGCUDARuntime::ConstantDeviceVar;
  3433. // Extern global variables will be registered in the TU where they are
  3434. // defined.
  3435. if (!D->hasExternalStorage())
  3436. getCUDARuntime().registerDeviceVar(D, *GV, Flags);
  3437. } else if (D->hasAttr<CUDASharedAttr>())
  3438. // __shared__ variables are odd. Shadows do get created, but
  3439. // they are not registered with the CUDA runtime, so they
  3440. // can't really be used to access their device-side
  3441. // counterparts. It's not clear yet whether it's nvcc's bug or
  3442. // a feature, but we've got to do the same for compatibility.
  3443. Linkage = llvm::GlobalValue::InternalLinkage;
  3444. }
  3445. }
  3446. if (!IsHIPPinnedShadowVar)
  3447. GV->setInitializer(Init);
  3448. if (emitter) emitter->finalize(GV);
  3449. // If it is safe to mark the global 'constant', do so now.
  3450. GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
  3451. isTypeConstant(D->getType(), true));
  3452. // If it is in a read-only section, mark it 'constant'.
  3453. if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
  3454. const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
  3455. if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
  3456. GV->setConstant(true);
  3457. }
  3458. GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
  3459. // On Darwin, if the normal linkage of a C++ thread_local variable is
  3460. // LinkOnce or Weak, we keep the normal linkage to prevent multiple
  3461. // copies within a linkage unit; otherwise, the backing variable has
  3462. // internal linkage and all accesses should just be calls to the
  3463. // Itanium-specified entry point, which has the normal linkage of the
  3464. // variable. This is to preserve the ability to change the implementation
  3465. // behind the scenes.
  3466. if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic &&
  3467. Context.getTargetInfo().getTriple().isOSDarwin() &&
  3468. !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) &&
  3469. !llvm::GlobalVariable::isWeakLinkage(Linkage))
  3470. Linkage = llvm::GlobalValue::InternalLinkage;
  3471. GV->setLinkage(Linkage);
  3472. if (D->hasAttr<DLLImportAttr>())
  3473. GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
  3474. else if (D->hasAttr<DLLExportAttr>())
  3475. GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
  3476. else
  3477. GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
  3478. if (Linkage == llvm::GlobalVariable::CommonLinkage) {
  3479. // common vars aren't constant even if declared const.
  3480. GV->setConstant(false);
  3481. // Tentative definition of global variables may be initialized with
  3482. // non-zero null pointers. In this case they should have weak linkage
  3483. // since common linkage must have zero initializer and must not have
  3484. // explicit section therefore cannot have non-zero initial value.
  3485. if (!GV->getInitializer()->isNullValue())
  3486. GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
  3487. }
  3488. setNonAliasAttributes(D, GV);
  3489. if (D->getTLSKind() && !GV->isThreadLocal()) {
  3490. if (D->getTLSKind() == VarDecl::TLS_Dynamic)
  3491. CXXThreadLocals.push_back(D);
  3492. setTLSMode(GV, *D);
  3493. }
  3494. maybeSetTrivialComdat(*D, *GV);
  3495. // Emit the initializer function if necessary.
  3496. if (NeedsGlobalCtor || NeedsGlobalDtor)
  3497. EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
  3498. SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
  3499. // Emit global variable debug information.
  3500. if (CGDebugInfo *DI = getModuleDebugInfo())
  3501. if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
  3502. DI->EmitGlobalVariable(GV, D);
  3503. }
  3504. static bool isVarDeclStrongDefinition(const ASTContext &Context,
  3505. CodeGenModule &CGM, const VarDecl *D,
  3506. bool NoCommon) {
  3507. // Don't give variables common linkage if -fno-common was specified unless it
  3508. // was overridden by a NoCommon attribute.
  3509. if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
  3510. return true;
  3511. // C11 6.9.2/2:
  3512. // A declaration of an identifier for an object that has file scope without
  3513. // an initializer, and without a storage-class specifier or with the
  3514. // storage-class specifier static, constitutes a tentative definition.
  3515. if (D->getInit() || D->hasExternalStorage())
  3516. return true;
  3517. // A variable cannot be both common and exist in a section.
  3518. if (D->hasAttr<SectionAttr>())
  3519. return true;
  3520. // A variable cannot be both common and exist in a section.
  3521. // We don't try to determine which is the right section in the front-end.
  3522. // If no specialized section name is applicable, it will resort to default.
  3523. if (D->hasAttr<PragmaClangBSSSectionAttr>() ||
  3524. D->hasAttr<PragmaClangDataSectionAttr>() ||
  3525. D->hasAttr<PragmaClangRodataSectionAttr>())
  3526. return true;
  3527. // Thread local vars aren't considered common linkage.
  3528. if (D->getTLSKind())
  3529. return true;
  3530. // Tentative definitions marked with WeakImportAttr are true definitions.
  3531. if (D->hasAttr<WeakImportAttr>())
  3532. return true;
  3533. // A variable cannot be both common and exist in a comdat.
  3534. if (shouldBeInCOMDAT(CGM, *D))
  3535. return true;
  3536. // Declarations with a required alignment do not have common linkage in MSVC
  3537. // mode.
  3538. if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  3539. if (D->hasAttr<AlignedAttr>())
  3540. return true;
  3541. QualType VarType = D->getType();
  3542. if (Context.isAlignmentRequired(VarType))
  3543. return true;
  3544. if (const auto *RT = VarType->getAs<RecordType>()) {
  3545. const RecordDecl *RD = RT->getDecl();
  3546. for (const FieldDecl *FD : RD->fields()) {
  3547. if (FD->isBitField())
  3548. continue;
  3549. if (FD->hasAttr<AlignedAttr>())
  3550. return true;
  3551. if (Context.isAlignmentRequired(FD->getType()))
  3552. return true;
  3553. }
  3554. }
  3555. }
  3556. // Microsoft's link.exe doesn't support alignments greater than 32 bytes for
  3557. // common symbols, so symbols with greater alignment requirements cannot be
  3558. // common.
  3559. // Other COFF linkers (ld.bfd and LLD) support arbitrary power-of-two
  3560. // alignments for common symbols via the aligncomm directive, so this
  3561. // restriction only applies to MSVC environments.
  3562. if (Context.getTargetInfo().getTriple().isKnownWindowsMSVCEnvironment() &&
  3563. Context.getTypeAlignIfKnown(D->getType()) >
  3564. Context.toBits(CharUnits::fromQuantity(32)))
  3565. return true;
  3566. return false;
  3567. }
  3568. llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
  3569. const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
  3570. if (Linkage == GVA_Internal)
  3571. return llvm::Function::InternalLinkage;
  3572. if (D->hasAttr<WeakAttr>()) {
  3573. if (IsConstantVariable)
  3574. return llvm::GlobalVariable::WeakODRLinkage;
  3575. else
  3576. return llvm::GlobalVariable::WeakAnyLinkage;
  3577. }
  3578. if (const auto *FD = D->getAsFunction())
  3579. if (FD->isMultiVersion() && Linkage == GVA_AvailableExternally)
  3580. return llvm::GlobalVariable::LinkOnceAnyLinkage;
  3581. // We are guaranteed to have a strong definition somewhere else,
  3582. // so we can use available_externally linkage.
  3583. if (Linkage == GVA_AvailableExternally)
  3584. return llvm::GlobalValue::AvailableExternallyLinkage;
  3585. // Note that Apple's kernel linker doesn't support symbol
  3586. // coalescing, so we need to avoid linkonce and weak linkages there.
  3587. // Normally, this means we just map to internal, but for explicit
  3588. // instantiations we'll map to external.
  3589. // In C++, the compiler has to emit a definition in every translation unit
  3590. // that references the function. We should use linkonce_odr because
  3591. // a) if all references in this translation unit are optimized away, we
  3592. // don't need to codegen it. b) if the function persists, it needs to be
  3593. // merged with other definitions. c) C++ has the ODR, so we know the
  3594. // definition is dependable.
  3595. if (Linkage == GVA_DiscardableODR)
  3596. return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
  3597. : llvm::Function::InternalLinkage;
  3598. // An explicit instantiation of a template has weak linkage, since
  3599. // explicit instantiations can occur in multiple translation units
  3600. // and must all be equivalent. However, we are not allowed to
  3601. // throw away these explicit instantiations.
  3602. //
  3603. // We don't currently support CUDA device code spread out across multiple TUs,
  3604. // so say that CUDA templates are either external (for kernels) or internal.
  3605. // This lets llvm perform aggressive inter-procedural optimizations.
  3606. if (Linkage == GVA_StrongODR) {
  3607. if (Context.getLangOpts().AppleKext)
  3608. return llvm::Function::ExternalLinkage;
  3609. if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice)
  3610. return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
  3611. : llvm::Function::InternalLinkage;
  3612. return llvm::Function::WeakODRLinkage;
  3613. }
  3614. // C++ doesn't have tentative definitions and thus cannot have common
  3615. // linkage.
  3616. if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
  3617. !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
  3618. CodeGenOpts.NoCommon))
  3619. return llvm::GlobalVariable::CommonLinkage;
  3620. // selectany symbols are externally visible, so use weak instead of
  3621. // linkonce. MSVC optimizes away references to const selectany globals, so
  3622. // all definitions should be the same and ODR linkage should be used.
  3623. // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
  3624. if (D->hasAttr<SelectAnyAttr>())
  3625. return llvm::GlobalVariable::WeakODRLinkage;
  3626. // Otherwise, we have strong external linkage.
  3627. assert(Linkage == GVA_StrongExternal);
  3628. return llvm::GlobalVariable::ExternalLinkage;
  3629. }
  3630. llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
  3631. const VarDecl *VD, bool IsConstant) {
  3632. GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
  3633. return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
  3634. }
  3635. /// Replace the uses of a function that was declared with a non-proto type.
  3636. /// We want to silently drop extra arguments from call sites
  3637. static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
  3638. llvm::Function *newFn) {
  3639. // Fast path.
  3640. if (old->use_empty()) return;
  3641. llvm::Type *newRetTy = newFn->getReturnType();
  3642. SmallVector<llvm::Value*, 4> newArgs;
  3643. SmallVector<llvm::OperandBundleDef, 1> newBundles;
  3644. for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
  3645. ui != ue; ) {
  3646. llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
  3647. llvm::User *user = use->getUser();
  3648. // Recognize and replace uses of bitcasts. Most calls to
  3649. // unprototyped functions will use bitcasts.
  3650. if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
  3651. if (bitcast->getOpcode() == llvm::Instruction::BitCast)
  3652. replaceUsesOfNonProtoConstant(bitcast, newFn);
  3653. continue;
  3654. }
  3655. // Recognize calls to the function.
  3656. llvm::CallBase *callSite = dyn_cast<llvm::CallBase>(user);
  3657. if (!callSite) continue;
  3658. if (!callSite->isCallee(&*use))
  3659. continue;
  3660. // If the return types don't match exactly, then we can't
  3661. // transform this call unless it's dead.
  3662. if (callSite->getType() != newRetTy && !callSite->use_empty())
  3663. continue;
  3664. // Get the call site's attribute list.
  3665. SmallVector<llvm::AttributeSet, 8> newArgAttrs;
  3666. llvm::AttributeList oldAttrs = callSite->getAttributes();
  3667. // If the function was passed too few arguments, don't transform.
  3668. unsigned newNumArgs = newFn->arg_size();
  3669. if (callSite->arg_size() < newNumArgs)
  3670. continue;
  3671. // If extra arguments were passed, we silently drop them.
  3672. // If any of the types mismatch, we don't transform.
  3673. unsigned argNo = 0;
  3674. bool dontTransform = false;
  3675. for (llvm::Argument &A : newFn->args()) {
  3676. if (callSite->getArgOperand(argNo)->getType() != A.getType()) {
  3677. dontTransform = true;
  3678. break;
  3679. }
  3680. // Add any parameter attributes.
  3681. newArgAttrs.push_back(oldAttrs.getParamAttributes(argNo));
  3682. argNo++;
  3683. }
  3684. if (dontTransform)
  3685. continue;
  3686. // Okay, we can transform this. Create the new call instruction and copy
  3687. // over the required information.
  3688. newArgs.append(callSite->arg_begin(), callSite->arg_begin() + argNo);
  3689. // Copy over any operand bundles.
  3690. callSite->getOperandBundlesAsDefs(newBundles);
  3691. llvm::CallBase *newCall;
  3692. if (dyn_cast<llvm::CallInst>(callSite)) {
  3693. newCall =
  3694. llvm::CallInst::Create(newFn, newArgs, newBundles, "", callSite);
  3695. } else {
  3696. auto *oldInvoke = cast<llvm::InvokeInst>(callSite);
  3697. newCall = llvm::InvokeInst::Create(newFn, oldInvoke->getNormalDest(),
  3698. oldInvoke->getUnwindDest(), newArgs,
  3699. newBundles, "", callSite);
  3700. }
  3701. newArgs.clear(); // for the next iteration
  3702. if (!newCall->getType()->isVoidTy())
  3703. newCall->takeName(callSite);
  3704. newCall->setAttributes(llvm::AttributeList::get(
  3705. newFn->getContext(), oldAttrs.getFnAttributes(),
  3706. oldAttrs.getRetAttributes(), newArgAttrs));
  3707. newCall->setCallingConv(callSite->getCallingConv());
  3708. // Finally, remove the old call, replacing any uses with the new one.
  3709. if (!callSite->use_empty())
  3710. callSite->replaceAllUsesWith(newCall);
  3711. // Copy debug location attached to CI.
  3712. if (callSite->getDebugLoc())
  3713. newCall->setDebugLoc(callSite->getDebugLoc());
  3714. callSite->eraseFromParent();
  3715. }
  3716. }
  3717. /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
  3718. /// implement a function with no prototype, e.g. "int foo() {}". If there are
  3719. /// existing call uses of the old function in the module, this adjusts them to
  3720. /// call the new function directly.
  3721. ///
  3722. /// This is not just a cleanup: the always_inline pass requires direct calls to
  3723. /// functions to be able to inline them. If there is a bitcast in the way, it
  3724. /// won't inline them. Instcombine normally deletes these calls, but it isn't
  3725. /// run at -O0.
  3726. static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
  3727. llvm::Function *NewFn) {
  3728. // If we're redefining a global as a function, don't transform it.
  3729. if (!isa<llvm::Function>(Old)) return;
  3730. replaceUsesOfNonProtoConstant(Old, NewFn);
  3731. }
  3732. void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
  3733. auto DK = VD->isThisDeclarationADefinition();
  3734. if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>())
  3735. return;
  3736. TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
  3737. // If we have a definition, this might be a deferred decl. If the
  3738. // instantiation is explicit, make sure we emit it at the end.
  3739. if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
  3740. GetAddrOfGlobalVar(VD);
  3741. EmitTopLevelDecl(VD);
  3742. }
  3743. void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
  3744. llvm::GlobalValue *GV) {
  3745. const auto *D = cast<FunctionDecl>(GD.getDecl());
  3746. // Compute the function info and LLVM type.
  3747. const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
  3748. llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
  3749. // Get or create the prototype for the function.
  3750. if (!GV || (GV->getType()->getElementType() != Ty))
  3751. GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
  3752. /*DontDefer=*/true,
  3753. ForDefinition));
  3754. // Already emitted.
  3755. if (!GV->isDeclaration())
  3756. return;
  3757. // We need to set linkage and visibility on the function before
  3758. // generating code for it because various parts of IR generation
  3759. // want to propagate this information down (e.g. to local static
  3760. // declarations).
  3761. auto *Fn = cast<llvm::Function>(GV);
  3762. setFunctionLinkage(GD, Fn);
  3763. // FIXME: this is redundant with part of setFunctionDefinitionAttributes
  3764. setGVProperties(Fn, GD);
  3765. MaybeHandleStaticInExternC(D, Fn);
  3766. maybeSetTrivialComdat(*D, *Fn);
  3767. CodeGenFunction(*this).GenerateCode(D, Fn, FI);
  3768. setNonAliasAttributes(GD, Fn);
  3769. SetLLVMFunctionAttributesForDefinition(D, Fn);
  3770. if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
  3771. AddGlobalCtor(Fn, CA->getPriority());
  3772. if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
  3773. AddGlobalDtor(Fn, DA->getPriority());
  3774. if (D->hasAttr<AnnotateAttr>())
  3775. AddGlobalAnnotations(D, Fn);
  3776. }
  3777. void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
  3778. const auto *D = cast<ValueDecl>(GD.getDecl());
  3779. const AliasAttr *AA = D->getAttr<AliasAttr>();
  3780. assert(AA && "Not an alias?");
  3781. StringRef MangledName = getMangledName(GD);
  3782. if (AA->getAliasee() == MangledName) {
  3783. Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
  3784. return;
  3785. }
  3786. // If there is a definition in the module, then it wins over the alias.
  3787. // This is dubious, but allow it to be safe. Just ignore the alias.
  3788. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  3789. if (Entry && !Entry->isDeclaration())
  3790. return;
  3791. Aliases.push_back(GD);
  3792. llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
  3793. // Create a reference to the named value. This ensures that it is emitted
  3794. // if a deferred decl.
  3795. llvm::Constant *Aliasee;
  3796. llvm::GlobalValue::LinkageTypes LT;
  3797. if (isa<llvm::FunctionType>(DeclTy)) {
  3798. Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
  3799. /*ForVTable=*/false);
  3800. LT = getFunctionLinkage(GD);
  3801. } else {
  3802. Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
  3803. llvm::PointerType::getUnqual(DeclTy),
  3804. /*D=*/nullptr);
  3805. LT = getLLVMLinkageVarDefinition(cast<VarDecl>(GD.getDecl()),
  3806. D->getType().isConstQualified());
  3807. }
  3808. // Create the new alias itself, but don't set a name yet.
  3809. auto *GA =
  3810. llvm::GlobalAlias::create(DeclTy, 0, LT, "", Aliasee, &getModule());
  3811. if (Entry) {
  3812. if (GA->getAliasee() == Entry) {
  3813. Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
  3814. return;
  3815. }
  3816. assert(Entry->isDeclaration());
  3817. // If there is a declaration in the module, then we had an extern followed
  3818. // by the alias, as in:
  3819. // extern int test6();
  3820. // ...
  3821. // int test6() __attribute__((alias("test7")));
  3822. //
  3823. // Remove it and replace uses of it with the alias.
  3824. GA->takeName(Entry);
  3825. Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
  3826. Entry->getType()));
  3827. Entry->eraseFromParent();
  3828. } else {
  3829. GA->setName(MangledName);
  3830. }
  3831. // Set attributes which are particular to an alias; this is a
  3832. // specialization of the attributes which may be set on a global
  3833. // variable/function.
  3834. if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
  3835. D->isWeakImported()) {
  3836. GA->setLinkage(llvm::Function::WeakAnyLinkage);
  3837. }
  3838. if (const auto *VD = dyn_cast<VarDecl>(D))
  3839. if (VD->getTLSKind())
  3840. setTLSMode(GA, *VD);
  3841. SetCommonAttributes(GD, GA);
  3842. }
  3843. void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
  3844. const auto *D = cast<ValueDecl>(GD.getDecl());
  3845. const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
  3846. assert(IFA && "Not an ifunc?");
  3847. StringRef MangledName = getMangledName(GD);
  3848. if (IFA->getResolver() == MangledName) {
  3849. Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
  3850. return;
  3851. }
  3852. // Report an error if some definition overrides ifunc.
  3853. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  3854. if (Entry && !Entry->isDeclaration()) {
  3855. GlobalDecl OtherGD;
  3856. if (lookupRepresentativeDecl(MangledName, OtherGD) &&
  3857. DiagnosedConflictingDefinitions.insert(GD).second) {
  3858. Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name)
  3859. << MangledName;
  3860. Diags.Report(OtherGD.getDecl()->getLocation(),
  3861. diag::note_previous_definition);
  3862. }
  3863. return;
  3864. }
  3865. Aliases.push_back(GD);
  3866. llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
  3867. llvm::Constant *Resolver =
  3868. GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD,
  3869. /*ForVTable=*/false);
  3870. llvm::GlobalIFunc *GIF =
  3871. llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
  3872. "", Resolver, &getModule());
  3873. if (Entry) {
  3874. if (GIF->getResolver() == Entry) {
  3875. Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
  3876. return;
  3877. }
  3878. assert(Entry->isDeclaration());
  3879. // If there is a declaration in the module, then we had an extern followed
  3880. // by the ifunc, as in:
  3881. // extern int test();
  3882. // ...
  3883. // int test() __attribute__((ifunc("resolver")));
  3884. //
  3885. // Remove it and replace uses of it with the ifunc.
  3886. GIF->takeName(Entry);
  3887. Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
  3888. Entry->getType()));
  3889. Entry->eraseFromParent();
  3890. } else
  3891. GIF->setName(MangledName);
  3892. SetCommonAttributes(GD, GIF);
  3893. }
  3894. llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
  3895. ArrayRef<llvm::Type*> Tys) {
  3896. return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
  3897. Tys);
  3898. }
  3899. static llvm::StringMapEntry<llvm::GlobalVariable *> &
  3900. GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
  3901. const StringLiteral *Literal, bool TargetIsLSB,
  3902. bool &IsUTF16, unsigned &StringLength) {
  3903. StringRef String = Literal->getString();
  3904. unsigned NumBytes = String.size();
  3905. // Check for simple case.
  3906. if (!Literal->containsNonAsciiOrNull()) {
  3907. StringLength = NumBytes;
  3908. return *Map.insert(std::make_pair(String, nullptr)).first;
  3909. }
  3910. // Otherwise, convert the UTF8 literals into a string of shorts.
  3911. IsUTF16 = true;
  3912. SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
  3913. const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
  3914. llvm::UTF16 *ToPtr = &ToBuf[0];
  3915. (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
  3916. ToPtr + NumBytes, llvm::strictConversion);
  3917. // ConvertUTF8toUTF16 returns the length in ToPtr.
  3918. StringLength = ToPtr - &ToBuf[0];
  3919. // Add an explicit null.
  3920. *ToPtr = 0;
  3921. return *Map.insert(std::make_pair(
  3922. StringRef(reinterpret_cast<const char *>(ToBuf.data()),
  3923. (StringLength + 1) * 2),
  3924. nullptr)).first;
  3925. }
  3926. ConstantAddress
  3927. CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
  3928. unsigned StringLength = 0;
  3929. bool isUTF16 = false;
  3930. llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
  3931. GetConstantCFStringEntry(CFConstantStringMap, Literal,
  3932. getDataLayout().isLittleEndian(), isUTF16,
  3933. StringLength);
  3934. if (auto *C = Entry.second)
  3935. return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
  3936. llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
  3937. llvm::Constant *Zeros[] = { Zero, Zero };
  3938. const ASTContext &Context = getContext();
  3939. const llvm::Triple &Triple = getTriple();
  3940. const auto CFRuntime = getLangOpts().CFRuntime;
  3941. const bool IsSwiftABI =
  3942. static_cast<unsigned>(CFRuntime) >=
  3943. static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift);
  3944. const bool IsSwift4_1 = CFRuntime == LangOptions::CoreFoundationABI::Swift4_1;
  3945. // If we don't already have it, get __CFConstantStringClassReference.
  3946. if (!CFConstantStringClassRef) {
  3947. const char *CFConstantStringClassName = "__CFConstantStringClassReference";
  3948. llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
  3949. Ty = llvm::ArrayType::get(Ty, 0);
  3950. switch (CFRuntime) {
  3951. default: break;
  3952. case LangOptions::CoreFoundationABI::Swift: LLVM_FALLTHROUGH;
  3953. case LangOptions::CoreFoundationABI::Swift5_0:
  3954. CFConstantStringClassName =
  3955. Triple.isOSDarwin() ? "$s15SwiftFoundation19_NSCFConstantStringCN"
  3956. : "$s10Foundation19_NSCFConstantStringCN";
  3957. Ty = IntPtrTy;
  3958. break;
  3959. case LangOptions::CoreFoundationABI::Swift4_2:
  3960. CFConstantStringClassName =
  3961. Triple.isOSDarwin() ? "$S15SwiftFoundation19_NSCFConstantStringCN"
  3962. : "$S10Foundation19_NSCFConstantStringCN";
  3963. Ty = IntPtrTy;
  3964. break;
  3965. case LangOptions::CoreFoundationABI::Swift4_1:
  3966. CFConstantStringClassName =
  3967. Triple.isOSDarwin() ? "__T015SwiftFoundation19_NSCFConstantStringCN"
  3968. : "__T010Foundation19_NSCFConstantStringCN";
  3969. Ty = IntPtrTy;
  3970. break;
  3971. }
  3972. llvm::Constant *C = CreateRuntimeVariable(Ty, CFConstantStringClassName);
  3973. if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) {
  3974. llvm::GlobalValue *GV = nullptr;
  3975. if ((GV = dyn_cast<llvm::GlobalValue>(C))) {
  3976. IdentifierInfo &II = Context.Idents.get(GV->getName());
  3977. TranslationUnitDecl *TUDecl = Context.getTranslationUnitDecl();
  3978. DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
  3979. const VarDecl *VD = nullptr;
  3980. for (const auto &Result : DC->lookup(&II))
  3981. if ((VD = dyn_cast<VarDecl>(Result)))
  3982. break;
  3983. if (Triple.isOSBinFormatELF()) {
  3984. if (!VD)
  3985. GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
  3986. } else {
  3987. GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
  3988. if (!VD || !VD->hasAttr<DLLExportAttr>())
  3989. GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
  3990. else
  3991. GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
  3992. }
  3993. setDSOLocal(GV);
  3994. }
  3995. }
  3996. // Decay array -> ptr
  3997. CFConstantStringClassRef =
  3998. IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(C, Ty)
  3999. : llvm::ConstantExpr::getGetElementPtr(Ty, C, Zeros);
  4000. }
  4001. QualType CFTy = Context.getCFConstantStringType();
  4002. auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
  4003. ConstantInitBuilder Builder(*this);
  4004. auto Fields = Builder.beginStruct(STy);
  4005. // Class pointer.
  4006. Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef));
  4007. // Flags.
  4008. if (IsSwiftABI) {
  4009. Fields.addInt(IntPtrTy, IsSwift4_1 ? 0x05 : 0x01);
  4010. Fields.addInt(Int64Ty, isUTF16 ? 0x07d0 : 0x07c8);
  4011. } else {
  4012. Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
  4013. }
  4014. // String pointer.
  4015. llvm::Constant *C = nullptr;
  4016. if (isUTF16) {
  4017. auto Arr = llvm::makeArrayRef(
  4018. reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
  4019. Entry.first().size() / 2);
  4020. C = llvm::ConstantDataArray::get(VMContext, Arr);
  4021. } else {
  4022. C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
  4023. }
  4024. // Note: -fwritable-strings doesn't make the backing store strings of
  4025. // CFStrings writable. (See <rdar://problem/10657500>)
  4026. auto *GV =
  4027. new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
  4028. llvm::GlobalValue::PrivateLinkage, C, ".str");
  4029. GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  4030. // Don't enforce the target's minimum global alignment, since the only use
  4031. // of the string is via this class initializer.
  4032. CharUnits Align = isUTF16 ? Context.getTypeAlignInChars(Context.ShortTy)
  4033. : Context.getTypeAlignInChars(Context.CharTy);
  4034. GV->setAlignment(Align.getQuantity());
  4035. // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
  4036. // Without it LLVM can merge the string with a non unnamed_addr one during
  4037. // LTO. Doing that changes the section it ends in, which surprises ld64.
  4038. if (Triple.isOSBinFormatMachO())
  4039. GV->setSection(isUTF16 ? "__TEXT,__ustring"
  4040. : "__TEXT,__cstring,cstring_literals");
  4041. // Make sure the literal ends up in .rodata to allow for safe ICF and for
  4042. // the static linker to adjust permissions to read-only later on.
  4043. else if (Triple.isOSBinFormatELF())
  4044. GV->setSection(".rodata");
  4045. // String.
  4046. llvm::Constant *Str =
  4047. llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
  4048. if (isUTF16)
  4049. // Cast the UTF16 string to the correct type.
  4050. Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy);
  4051. Fields.add(Str);
  4052. // String length.
  4053. llvm::IntegerType *LengthTy =
  4054. llvm::IntegerType::get(getModule().getContext(),
  4055. Context.getTargetInfo().getLongWidth());
  4056. if (IsSwiftABI) {
  4057. if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
  4058. CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
  4059. LengthTy = Int32Ty;
  4060. else
  4061. LengthTy = IntPtrTy;
  4062. }
  4063. Fields.addInt(LengthTy, StringLength);
  4064. // Swift ABI requires 8-byte alignment to ensure that the _Atomic(uint64_t) is
  4065. // properly aligned on 32-bit platforms.
  4066. CharUnits Alignment =
  4067. IsSwiftABI ? Context.toCharUnitsFromBits(64) : getPointerAlign();
  4068. // The struct.
  4069. GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
  4070. /*isConstant=*/false,
  4071. llvm::GlobalVariable::PrivateLinkage);
  4072. GV->addAttribute("objc_arc_inert");
  4073. switch (Triple.getObjectFormat()) {
  4074. case llvm::Triple::UnknownObjectFormat:
  4075. llvm_unreachable("unknown file format");
  4076. case llvm::Triple::XCOFF:
  4077. llvm_unreachable("XCOFF is not yet implemented");
  4078. case llvm::Triple::COFF:
  4079. case llvm::Triple::ELF:
  4080. case llvm::Triple::Wasm:
  4081. GV->setSection("cfstring");
  4082. break;
  4083. case llvm::Triple::MachO:
  4084. GV->setSection("__DATA,__cfstring");
  4085. break;
  4086. }
  4087. Entry.second = GV;
  4088. return ConstantAddress(GV, Alignment);
  4089. }
  4090. bool CodeGenModule::getExpressionLocationsEnabled() const {
  4091. return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
  4092. }
  4093. QualType CodeGenModule::getObjCFastEnumerationStateType() {
  4094. if (ObjCFastEnumerationStateType.isNull()) {
  4095. RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
  4096. D->startDefinition();
  4097. QualType FieldTypes[] = {
  4098. Context.UnsignedLongTy,
  4099. Context.getPointerType(Context.getObjCIdType()),
  4100. Context.getPointerType(Context.UnsignedLongTy),
  4101. Context.getConstantArrayType(Context.UnsignedLongTy,
  4102. llvm::APInt(32, 5), ArrayType::Normal, 0)
  4103. };
  4104. for (size_t i = 0; i < 4; ++i) {
  4105. FieldDecl *Field = FieldDecl::Create(Context,
  4106. D,
  4107. SourceLocation(),
  4108. SourceLocation(), nullptr,
  4109. FieldTypes[i], /*TInfo=*/nullptr,
  4110. /*BitWidth=*/nullptr,
  4111. /*Mutable=*/false,
  4112. ICIS_NoInit);
  4113. Field->setAccess(AS_public);
  4114. D->addDecl(Field);
  4115. }
  4116. D->completeDefinition();
  4117. ObjCFastEnumerationStateType = Context.getTagDeclType(D);
  4118. }
  4119. return ObjCFastEnumerationStateType;
  4120. }
  4121. llvm::Constant *
  4122. CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
  4123. assert(!E->getType()->isPointerType() && "Strings are always arrays");
  4124. // Don't emit it as the address of the string, emit the string data itself
  4125. // as an inline array.
  4126. if (E->getCharByteWidth() == 1) {
  4127. SmallString<64> Str(E->getString());
  4128. // Resize the string to the right size, which is indicated by its type.
  4129. const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
  4130. Str.resize(CAT->getSize().getZExtValue());
  4131. return llvm::ConstantDataArray::getString(VMContext, Str, false);
  4132. }
  4133. auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
  4134. llvm::Type *ElemTy = AType->getElementType();
  4135. unsigned NumElements = AType->getNumElements();
  4136. // Wide strings have either 2-byte or 4-byte elements.
  4137. if (ElemTy->getPrimitiveSizeInBits() == 16) {
  4138. SmallVector<uint16_t, 32> Elements;
  4139. Elements.reserve(NumElements);
  4140. for(unsigned i = 0, e = E->getLength(); i != e; ++i)
  4141. Elements.push_back(E->getCodeUnit(i));
  4142. Elements.resize(NumElements);
  4143. return llvm::ConstantDataArray::get(VMContext, Elements);
  4144. }
  4145. assert(ElemTy->getPrimitiveSizeInBits() == 32);
  4146. SmallVector<uint32_t, 32> Elements;
  4147. Elements.reserve(NumElements);
  4148. for(unsigned i = 0, e = E->getLength(); i != e; ++i)
  4149. Elements.push_back(E->getCodeUnit(i));
  4150. Elements.resize(NumElements);
  4151. return llvm::ConstantDataArray::get(VMContext, Elements);
  4152. }
  4153. static llvm::GlobalVariable *
  4154. GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
  4155. CodeGenModule &CGM, StringRef GlobalName,
  4156. CharUnits Alignment) {
  4157. unsigned AddrSpace = CGM.getContext().getTargetAddressSpace(
  4158. CGM.getStringLiteralAddressSpace());
  4159. llvm::Module &M = CGM.getModule();
  4160. // Create a global variable for this string
  4161. auto *GV = new llvm::GlobalVariable(
  4162. M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
  4163. nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
  4164. GV->setAlignment(Alignment.getQuantity());
  4165. GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  4166. if (GV->isWeakForLinker()) {
  4167. assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
  4168. GV->setComdat(M.getOrInsertComdat(GV->getName()));
  4169. }
  4170. CGM.setDSOLocal(GV);
  4171. return GV;
  4172. }
  4173. /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
  4174. /// constant array for the given string literal.
  4175. ConstantAddress
  4176. CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
  4177. StringRef Name) {
  4178. CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
  4179. llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
  4180. llvm::GlobalVariable **Entry = nullptr;
  4181. if (!LangOpts.WritableStrings) {
  4182. Entry = &ConstantStringMap[C];
  4183. if (auto GV = *Entry) {
  4184. if (Alignment.getQuantity() > GV->getAlignment())
  4185. GV->setAlignment(Alignment.getQuantity());
  4186. return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
  4187. Alignment);
  4188. }
  4189. }
  4190. SmallString<256> MangledNameBuffer;
  4191. StringRef GlobalVariableName;
  4192. llvm::GlobalValue::LinkageTypes LT;
  4193. // Mangle the string literal if that's how the ABI merges duplicate strings.
  4194. // Don't do it if they are writable, since we don't want writes in one TU to
  4195. // affect strings in another.
  4196. if (getCXXABI().getMangleContext().shouldMangleStringLiteral(S) &&
  4197. !LangOpts.WritableStrings) {
  4198. llvm::raw_svector_ostream Out(MangledNameBuffer);
  4199. getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
  4200. LT = llvm::GlobalValue::LinkOnceODRLinkage;
  4201. GlobalVariableName = MangledNameBuffer;
  4202. } else {
  4203. LT = llvm::GlobalValue::PrivateLinkage;
  4204. GlobalVariableName = Name;
  4205. }
  4206. auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
  4207. if (Entry)
  4208. *Entry = GV;
  4209. SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
  4210. QualType());
  4211. return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
  4212. Alignment);
  4213. }
  4214. /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
  4215. /// array for the given ObjCEncodeExpr node.
  4216. ConstantAddress
  4217. CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
  4218. std::string Str;
  4219. getContext().getObjCEncodingForType(E->getEncodedType(), Str);
  4220. return GetAddrOfConstantCString(Str);
  4221. }
  4222. /// GetAddrOfConstantCString - Returns a pointer to a character array containing
  4223. /// the literal and a terminating '\0' character.
  4224. /// The result has pointer to array type.
  4225. ConstantAddress CodeGenModule::GetAddrOfConstantCString(
  4226. const std::string &Str, const char *GlobalName) {
  4227. StringRef StrWithNull(Str.c_str(), Str.size() + 1);
  4228. CharUnits Alignment =
  4229. getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
  4230. llvm::Constant *C =
  4231. llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
  4232. // Don't share any string literals if strings aren't constant.
  4233. llvm::GlobalVariable **Entry = nullptr;
  4234. if (!LangOpts.WritableStrings) {
  4235. Entry = &ConstantStringMap[C];
  4236. if (auto GV = *Entry) {
  4237. if (Alignment.getQuantity() > GV->getAlignment())
  4238. GV->setAlignment(Alignment.getQuantity());
  4239. return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
  4240. Alignment);
  4241. }
  4242. }
  4243. // Get the default prefix if a name wasn't specified.
  4244. if (!GlobalName)
  4245. GlobalName = ".str";
  4246. // Create a global variable for this.
  4247. auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
  4248. GlobalName, Alignment);
  4249. if (Entry)
  4250. *Entry = GV;
  4251. return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
  4252. Alignment);
  4253. }
  4254. ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
  4255. const MaterializeTemporaryExpr *E, const Expr *Init) {
  4256. assert((E->getStorageDuration() == SD_Static ||
  4257. E->getStorageDuration() == SD_Thread) && "not a global temporary");
  4258. const auto *VD = cast<VarDecl>(E->getExtendingDecl());
  4259. // If we're not materializing a subobject of the temporary, keep the
  4260. // cv-qualifiers from the type of the MaterializeTemporaryExpr.
  4261. QualType MaterializedType = Init->getType();
  4262. if (Init == E->GetTemporaryExpr())
  4263. MaterializedType = E->getType();
  4264. CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
  4265. if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E])
  4266. return ConstantAddress(Slot, Align);
  4267. // FIXME: If an externally-visible declaration extends multiple temporaries,
  4268. // we need to give each temporary the same name in every translation unit (and
  4269. // we also need to make the temporaries externally-visible).
  4270. SmallString<256> Name;
  4271. llvm::raw_svector_ostream Out(Name);
  4272. getCXXABI().getMangleContext().mangleReferenceTemporary(
  4273. VD, E->getManglingNumber(), Out);
  4274. APValue *Value = nullptr;
  4275. if (E->getStorageDuration() == SD_Static) {
  4276. // We might have a cached constant initializer for this temporary. Note
  4277. // that this might have a different value from the value computed by
  4278. // evaluating the initializer if the surrounding constant expression
  4279. // modifies the temporary.
  4280. Value = getContext().getMaterializedTemporaryValue(E, false);
  4281. if (Value && Value->isAbsent())
  4282. Value = nullptr;
  4283. }
  4284. // Try evaluating it now, it might have a constant initializer.
  4285. Expr::EvalResult EvalResult;
  4286. if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
  4287. !EvalResult.hasSideEffects())
  4288. Value = &EvalResult.Val;
  4289. LangAS AddrSpace =
  4290. VD ? GetGlobalVarAddressSpace(VD) : MaterializedType.getAddressSpace();
  4291. Optional<ConstantEmitter> emitter;
  4292. llvm::Constant *InitialValue = nullptr;
  4293. bool Constant = false;
  4294. llvm::Type *Type;
  4295. if (Value) {
  4296. // The temporary has a constant initializer, use it.
  4297. emitter.emplace(*this);
  4298. InitialValue = emitter->emitForInitializer(*Value, AddrSpace,
  4299. MaterializedType);
  4300. Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
  4301. Type = InitialValue->getType();
  4302. } else {
  4303. // No initializer, the initialization will be provided when we
  4304. // initialize the declaration which performed lifetime extension.
  4305. Type = getTypes().ConvertTypeForMem(MaterializedType);
  4306. }
  4307. // Create a global variable for this lifetime-extended temporary.
  4308. llvm::GlobalValue::LinkageTypes Linkage =
  4309. getLLVMLinkageVarDefinition(VD, Constant);
  4310. if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
  4311. const VarDecl *InitVD;
  4312. if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
  4313. isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
  4314. // Temporaries defined inside a class get linkonce_odr linkage because the
  4315. // class can be defined in multiple translation units.
  4316. Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
  4317. } else {
  4318. // There is no need for this temporary to have external linkage if the
  4319. // VarDecl has external linkage.
  4320. Linkage = llvm::GlobalVariable::InternalLinkage;
  4321. }
  4322. }
  4323. auto TargetAS = getContext().getTargetAddressSpace(AddrSpace);
  4324. auto *GV = new llvm::GlobalVariable(
  4325. getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
  4326. /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
  4327. if (emitter) emitter->finalize(GV);
  4328. setGVProperties(GV, VD);
  4329. GV->setAlignment(Align.getQuantity());
  4330. if (supportsCOMDAT() && GV->isWeakForLinker())
  4331. GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
  4332. if (VD->getTLSKind())
  4333. setTLSMode(GV, *VD);
  4334. llvm::Constant *CV = GV;
  4335. if (AddrSpace != LangAS::Default)
  4336. CV = getTargetCodeGenInfo().performAddrSpaceCast(
  4337. *this, GV, AddrSpace, LangAS::Default,
  4338. Type->getPointerTo(
  4339. getContext().getTargetAddressSpace(LangAS::Default)));
  4340. MaterializedGlobalTemporaryMap[E] = CV;
  4341. return ConstantAddress(CV, Align);
  4342. }
  4343. /// EmitObjCPropertyImplementations - Emit information for synthesized
  4344. /// properties for an implementation.
  4345. void CodeGenModule::EmitObjCPropertyImplementations(const
  4346. ObjCImplementationDecl *D) {
  4347. for (const auto *PID : D->property_impls()) {
  4348. // Dynamic is just for type-checking.
  4349. if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
  4350. ObjCPropertyDecl *PD = PID->getPropertyDecl();
  4351. // Determine which methods need to be implemented, some may have
  4352. // been overridden. Note that ::isPropertyAccessor is not the method
  4353. // we want, that just indicates if the decl came from a
  4354. // property. What we want to know is if the method is defined in
  4355. // this implementation.
  4356. if (!D->getInstanceMethod(PD->getGetterName()))
  4357. CodeGenFunction(*this).GenerateObjCGetter(
  4358. const_cast<ObjCImplementationDecl *>(D), PID);
  4359. if (!PD->isReadOnly() &&
  4360. !D->getInstanceMethod(PD->getSetterName()))
  4361. CodeGenFunction(*this).GenerateObjCSetter(
  4362. const_cast<ObjCImplementationDecl *>(D), PID);
  4363. }
  4364. }
  4365. }
  4366. static bool needsDestructMethod(ObjCImplementationDecl *impl) {
  4367. const ObjCInterfaceDecl *iface = impl->getClassInterface();
  4368. for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
  4369. ivar; ivar = ivar->getNextIvar())
  4370. if (ivar->getType().isDestructedType())
  4371. return true;
  4372. return false;
  4373. }
  4374. static bool AllTrivialInitializers(CodeGenModule &CGM,
  4375. ObjCImplementationDecl *D) {
  4376. CodeGenFunction CGF(CGM);
  4377. for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
  4378. E = D->init_end(); B != E; ++B) {
  4379. CXXCtorInitializer *CtorInitExp = *B;
  4380. Expr *Init = CtorInitExp->getInit();
  4381. if (!CGF.isTrivialInitializer(Init))
  4382. return false;
  4383. }
  4384. return true;
  4385. }
  4386. /// EmitObjCIvarInitializations - Emit information for ivar initialization
  4387. /// for an implementation.
  4388. void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
  4389. // We might need a .cxx_destruct even if we don't have any ivar initializers.
  4390. if (needsDestructMethod(D)) {
  4391. IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
  4392. Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
  4393. ObjCMethodDecl *DTORMethod =
  4394. ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
  4395. cxxSelector, getContext().VoidTy, nullptr, D,
  4396. /*isInstance=*/true, /*isVariadic=*/false,
  4397. /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
  4398. /*isDefined=*/false, ObjCMethodDecl::Required);
  4399. D->addInstanceMethod(DTORMethod);
  4400. CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
  4401. D->setHasDestructors(true);
  4402. }
  4403. // If the implementation doesn't have any ivar initializers, we don't need
  4404. // a .cxx_construct.
  4405. if (D->getNumIvarInitializers() == 0 ||
  4406. AllTrivialInitializers(*this, D))
  4407. return;
  4408. IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
  4409. Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
  4410. // The constructor returns 'self'.
  4411. ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
  4412. D->getLocation(),
  4413. D->getLocation(),
  4414. cxxSelector,
  4415. getContext().getObjCIdType(),
  4416. nullptr, D, /*isInstance=*/true,
  4417. /*isVariadic=*/false,
  4418. /*isPropertyAccessor=*/true,
  4419. /*isImplicitlyDeclared=*/true,
  4420. /*isDefined=*/false,
  4421. ObjCMethodDecl::Required);
  4422. D->addInstanceMethod(CTORMethod);
  4423. CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
  4424. D->setHasNonZeroConstructors(true);
  4425. }
  4426. // EmitLinkageSpec - Emit all declarations in a linkage spec.
  4427. void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
  4428. if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
  4429. LSD->getLanguage() != LinkageSpecDecl::lang_cxx &&
  4430. LSD->getLanguage() != LinkageSpecDecl::lang_cxx_11 &&
  4431. LSD->getLanguage() != LinkageSpecDecl::lang_cxx_14) {
  4432. ErrorUnsupported(LSD, "linkage spec");
  4433. return;
  4434. }
  4435. EmitDeclContext(LSD);
  4436. }
  4437. void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
  4438. for (auto *I : DC->decls()) {
  4439. // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
  4440. // are themselves considered "top-level", so EmitTopLevelDecl on an
  4441. // ObjCImplDecl does not recursively visit them. We need to do that in
  4442. // case they're nested inside another construct (LinkageSpecDecl /
  4443. // ExportDecl) that does stop them from being considered "top-level".
  4444. if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
  4445. for (auto *M : OID->methods())
  4446. EmitTopLevelDecl(M);
  4447. }
  4448. EmitTopLevelDecl(I);
  4449. }
  4450. }
  4451. /// EmitTopLevelDecl - Emit code for a single top level declaration.
  4452. void CodeGenModule::EmitTopLevelDecl(Decl *D) {
  4453. // Ignore dependent declarations.
  4454. if (D->isTemplated())
  4455. return;
  4456. switch (D->getKind()) {
  4457. case Decl::CXXConversion:
  4458. case Decl::CXXMethod:
  4459. case Decl::Function:
  4460. EmitGlobal(cast<FunctionDecl>(D));
  4461. // Always provide some coverage mapping
  4462. // even for the functions that aren't emitted.
  4463. AddDeferredUnusedCoverageMapping(D);
  4464. break;
  4465. case Decl::CXXDeductionGuide:
  4466. // Function-like, but does not result in code emission.
  4467. break;
  4468. case Decl::Var:
  4469. case Decl::Decomposition:
  4470. case Decl::VarTemplateSpecialization:
  4471. EmitGlobal(cast<VarDecl>(D));
  4472. if (auto *DD = dyn_cast<DecompositionDecl>(D))
  4473. for (auto *B : DD->bindings())
  4474. if (auto *HD = B->getHoldingVar())
  4475. EmitGlobal(HD);
  4476. break;
  4477. // Indirect fields from global anonymous structs and unions can be
  4478. // ignored; only the actual variable requires IR gen support.
  4479. case Decl::IndirectField:
  4480. break;
  4481. // C++ Decls
  4482. case Decl::Namespace:
  4483. EmitDeclContext(cast<NamespaceDecl>(D));
  4484. break;
  4485. case Decl::ClassTemplateSpecialization: {
  4486. const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
  4487. if (DebugInfo &&
  4488. Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition &&
  4489. Spec->hasDefinition())
  4490. DebugInfo->completeTemplateDefinition(*Spec);
  4491. } LLVM_FALLTHROUGH;
  4492. case Decl::CXXRecord:
  4493. if (DebugInfo) {
  4494. if (auto *ES = D->getASTContext().getExternalSource())
  4495. if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
  4496. DebugInfo->completeUnusedClass(cast<CXXRecordDecl>(*D));
  4497. }
  4498. // Emit any static data members, they may be definitions.
  4499. for (auto *I : cast<CXXRecordDecl>(D)->decls())
  4500. if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
  4501. EmitTopLevelDecl(I);
  4502. break;
  4503. // No code generation needed.
  4504. case Decl::UsingShadow:
  4505. case Decl::ClassTemplate:
  4506. case Decl::VarTemplate:
  4507. case Decl::Concept:
  4508. case Decl::VarTemplatePartialSpecialization:
  4509. case Decl::FunctionTemplate:
  4510. case Decl::TypeAliasTemplate:
  4511. case Decl::Block:
  4512. case Decl::Empty:
  4513. case Decl::Binding:
  4514. break;
  4515. case Decl::Using: // using X; [C++]
  4516. if (CGDebugInfo *DI = getModuleDebugInfo())
  4517. DI->EmitUsingDecl(cast<UsingDecl>(*D));
  4518. return;
  4519. case Decl::NamespaceAlias:
  4520. if (CGDebugInfo *DI = getModuleDebugInfo())
  4521. DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
  4522. return;
  4523. case Decl::UsingDirective: // using namespace X; [C++]
  4524. if (CGDebugInfo *DI = getModuleDebugInfo())
  4525. DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
  4526. return;
  4527. case Decl::CXXConstructor:
  4528. getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
  4529. break;
  4530. case Decl::CXXDestructor:
  4531. getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
  4532. break;
  4533. case Decl::StaticAssert:
  4534. // Nothing to do.
  4535. break;
  4536. // Objective-C Decls
  4537. // Forward declarations, no (immediate) code generation.
  4538. case Decl::ObjCInterface:
  4539. case Decl::ObjCCategory:
  4540. break;
  4541. case Decl::ObjCProtocol: {
  4542. auto *Proto = cast<ObjCProtocolDecl>(D);
  4543. if (Proto->isThisDeclarationADefinition())
  4544. ObjCRuntime->GenerateProtocol(Proto);
  4545. break;
  4546. }
  4547. case Decl::ObjCCategoryImpl:
  4548. // Categories have properties but don't support synthesize so we
  4549. // can ignore them here.
  4550. ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
  4551. break;
  4552. case Decl::ObjCImplementation: {
  4553. auto *OMD = cast<ObjCImplementationDecl>(D);
  4554. EmitObjCPropertyImplementations(OMD);
  4555. EmitObjCIvarInitializations(OMD);
  4556. ObjCRuntime->GenerateClass(OMD);
  4557. // Emit global variable debug information.
  4558. if (CGDebugInfo *DI = getModuleDebugInfo())
  4559. if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
  4560. DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
  4561. OMD->getClassInterface()), OMD->getLocation());
  4562. break;
  4563. }
  4564. case Decl::ObjCMethod: {
  4565. auto *OMD = cast<ObjCMethodDecl>(D);
  4566. // If this is not a prototype, emit the body.
  4567. if (OMD->getBody())
  4568. CodeGenFunction(*this).GenerateObjCMethod(OMD);
  4569. break;
  4570. }
  4571. case Decl::ObjCCompatibleAlias:
  4572. ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
  4573. break;
  4574. case Decl::PragmaComment: {
  4575. const auto *PCD = cast<PragmaCommentDecl>(D);
  4576. switch (PCD->getCommentKind()) {
  4577. case PCK_Unknown:
  4578. llvm_unreachable("unexpected pragma comment kind");
  4579. case PCK_Linker:
  4580. AppendLinkerOptions(PCD->getArg());
  4581. break;
  4582. case PCK_Lib:
  4583. AddDependentLib(PCD->getArg());
  4584. break;
  4585. case PCK_Compiler:
  4586. case PCK_ExeStr:
  4587. case PCK_User:
  4588. break; // We ignore all of these.
  4589. }
  4590. break;
  4591. }
  4592. case Decl::PragmaDetectMismatch: {
  4593. const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
  4594. AddDetectMismatch(PDMD->getName(), PDMD->getValue());
  4595. break;
  4596. }
  4597. case Decl::LinkageSpec:
  4598. EmitLinkageSpec(cast<LinkageSpecDecl>(D));
  4599. break;
  4600. case Decl::FileScopeAsm: {
  4601. // File-scope asm is ignored during device-side CUDA compilation.
  4602. if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
  4603. break;
  4604. // File-scope asm is ignored during device-side OpenMP compilation.
  4605. if (LangOpts.OpenMPIsDevice)
  4606. break;
  4607. auto *AD = cast<FileScopeAsmDecl>(D);
  4608. getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
  4609. break;
  4610. }
  4611. case Decl::Import: {
  4612. auto *Import = cast<ImportDecl>(D);
  4613. // If we've already imported this module, we're done.
  4614. if (!ImportedModules.insert(Import->getImportedModule()))
  4615. break;
  4616. // Emit debug information for direct imports.
  4617. if (!Import->getImportedOwningModule()) {
  4618. if (CGDebugInfo *DI = getModuleDebugInfo())
  4619. DI->EmitImportDecl(*Import);
  4620. }
  4621. // Find all of the submodules and emit the module initializers.
  4622. llvm::SmallPtrSet<clang::Module *, 16> Visited;
  4623. SmallVector<clang::Module *, 16> Stack;
  4624. Visited.insert(Import->getImportedModule());
  4625. Stack.push_back(Import->getImportedModule());
  4626. while (!Stack.empty()) {
  4627. clang::Module *Mod = Stack.pop_back_val();
  4628. if (!EmittedModuleInitializers.insert(Mod).second)
  4629. continue;
  4630. for (auto *D : Context.getModuleInitializers(Mod))
  4631. EmitTopLevelDecl(D);
  4632. // Visit the submodules of this module.
  4633. for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
  4634. SubEnd = Mod->submodule_end();
  4635. Sub != SubEnd; ++Sub) {
  4636. // Skip explicit children; they need to be explicitly imported to emit
  4637. // the initializers.
  4638. if ((*Sub)->IsExplicit)
  4639. continue;
  4640. if (Visited.insert(*Sub).second)
  4641. Stack.push_back(*Sub);
  4642. }
  4643. }
  4644. break;
  4645. }
  4646. case Decl::Export:
  4647. EmitDeclContext(cast<ExportDecl>(D));
  4648. break;
  4649. case Decl::OMPThreadPrivate:
  4650. EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
  4651. break;
  4652. case Decl::OMPAllocate:
  4653. break;
  4654. case Decl::OMPDeclareReduction:
  4655. EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
  4656. break;
  4657. case Decl::OMPDeclareMapper:
  4658. EmitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(D));
  4659. break;
  4660. case Decl::OMPRequires:
  4661. EmitOMPRequiresDecl(cast<OMPRequiresDecl>(D));
  4662. break;
  4663. default:
  4664. // Make sure we handled everything we should, every other kind is a
  4665. // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
  4666. // function. Need to recode Decl::Kind to do that easily.
  4667. assert(isa<TypeDecl>(D) && "Unsupported decl kind");
  4668. break;
  4669. }
  4670. }
  4671. void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
  4672. // Do we need to generate coverage mapping?
  4673. if (!CodeGenOpts.CoverageMapping)
  4674. return;
  4675. switch (D->getKind()) {
  4676. case Decl::CXXConversion:
  4677. case Decl::CXXMethod:
  4678. case Decl::Function:
  4679. case Decl::ObjCMethod:
  4680. case Decl::CXXConstructor:
  4681. case Decl::CXXDestructor: {
  4682. if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
  4683. return;
  4684. SourceManager &SM = getContext().getSourceManager();
  4685. if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getBeginLoc()))
  4686. return;
  4687. auto I = DeferredEmptyCoverageMappingDecls.find(D);
  4688. if (I == DeferredEmptyCoverageMappingDecls.end())
  4689. DeferredEmptyCoverageMappingDecls[D] = true;
  4690. break;
  4691. }
  4692. default:
  4693. break;
  4694. };
  4695. }
  4696. void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
  4697. // Do we need to generate coverage mapping?
  4698. if (!CodeGenOpts.CoverageMapping)
  4699. return;
  4700. if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
  4701. if (Fn->isTemplateInstantiation())
  4702. ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
  4703. }
  4704. auto I = DeferredEmptyCoverageMappingDecls.find(D);
  4705. if (I == DeferredEmptyCoverageMappingDecls.end())
  4706. DeferredEmptyCoverageMappingDecls[D] = false;
  4707. else
  4708. I->second = false;
  4709. }
  4710. void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
  4711. // We call takeVector() here to avoid use-after-free.
  4712. // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because
  4713. // we deserialize function bodies to emit coverage info for them, and that
  4714. // deserializes more declarations. How should we handle that case?
  4715. for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
  4716. if (!Entry.second)
  4717. continue;
  4718. const Decl *D = Entry.first;
  4719. switch (D->getKind()) {
  4720. case Decl::CXXConversion:
  4721. case Decl::CXXMethod:
  4722. case Decl::Function:
  4723. case Decl::ObjCMethod: {
  4724. CodeGenPGO PGO(*this);
  4725. GlobalDecl GD(cast<FunctionDecl>(D));
  4726. PGO.emitEmptyCounterMapping(D, getMangledName(GD),
  4727. getFunctionLinkage(GD));
  4728. break;
  4729. }
  4730. case Decl::CXXConstructor: {
  4731. CodeGenPGO PGO(*this);
  4732. GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
  4733. PGO.emitEmptyCounterMapping(D, getMangledName(GD),
  4734. getFunctionLinkage(GD));
  4735. break;
  4736. }
  4737. case Decl::CXXDestructor: {
  4738. CodeGenPGO PGO(*this);
  4739. GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
  4740. PGO.emitEmptyCounterMapping(D, getMangledName(GD),
  4741. getFunctionLinkage(GD));
  4742. break;
  4743. }
  4744. default:
  4745. break;
  4746. };
  4747. }
  4748. }
  4749. /// Turns the given pointer into a constant.
  4750. static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
  4751. const void *Ptr) {
  4752. uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
  4753. llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
  4754. return llvm::ConstantInt::get(i64, PtrInt);
  4755. }
  4756. static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
  4757. llvm::NamedMDNode *&GlobalMetadata,
  4758. GlobalDecl D,
  4759. llvm::GlobalValue *Addr) {
  4760. if (!GlobalMetadata)
  4761. GlobalMetadata =
  4762. CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
  4763. // TODO: should we report variant information for ctors/dtors?
  4764. llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
  4765. llvm::ConstantAsMetadata::get(GetPointerConstant(
  4766. CGM.getLLVMContext(), D.getDecl()))};
  4767. GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
  4768. }
  4769. /// For each function which is declared within an extern "C" region and marked
  4770. /// as 'used', but has internal linkage, create an alias from the unmangled
  4771. /// name to the mangled name if possible. People expect to be able to refer
  4772. /// to such functions with an unmangled name from inline assembly within the
  4773. /// same translation unit.
  4774. void CodeGenModule::EmitStaticExternCAliases() {
  4775. if (!getTargetCodeGenInfo().shouldEmitStaticExternCAliases())
  4776. return;
  4777. for (auto &I : StaticExternCValues) {
  4778. IdentifierInfo *Name = I.first;
  4779. llvm::GlobalValue *Val = I.second;
  4780. if (Val && !getModule().getNamedValue(Name->getName()))
  4781. addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
  4782. }
  4783. }
  4784. bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
  4785. GlobalDecl &Result) const {
  4786. auto Res = Manglings.find(MangledName);
  4787. if (Res == Manglings.end())
  4788. return false;
  4789. Result = Res->getValue();
  4790. return true;
  4791. }
  4792. /// Emits metadata nodes associating all the global values in the
  4793. /// current module with the Decls they came from. This is useful for
  4794. /// projects using IR gen as a subroutine.
  4795. ///
  4796. /// Since there's currently no way to associate an MDNode directly
  4797. /// with an llvm::GlobalValue, we create a global named metadata
  4798. /// with the name 'clang.global.decl.ptrs'.
  4799. void CodeGenModule::EmitDeclMetadata() {
  4800. llvm::NamedMDNode *GlobalMetadata = nullptr;
  4801. for (auto &I : MangledDeclNames) {
  4802. llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
  4803. // Some mangled names don't necessarily have an associated GlobalValue
  4804. // in this module, e.g. if we mangled it for DebugInfo.
  4805. if (Addr)
  4806. EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
  4807. }
  4808. }
  4809. /// Emits metadata nodes for all the local variables in the current
  4810. /// function.
  4811. void CodeGenFunction::EmitDeclMetadata() {
  4812. if (LocalDeclMap.empty()) return;
  4813. llvm::LLVMContext &Context = getLLVMContext();
  4814. // Find the unique metadata ID for this name.
  4815. unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
  4816. llvm::NamedMDNode *GlobalMetadata = nullptr;
  4817. for (auto &I : LocalDeclMap) {
  4818. const Decl *D = I.first;
  4819. llvm::Value *Addr = I.second.getPointer();
  4820. if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
  4821. llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
  4822. Alloca->setMetadata(
  4823. DeclPtrKind, llvm::MDNode::get(
  4824. Context, llvm::ValueAsMetadata::getConstant(DAddr)));
  4825. } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
  4826. GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
  4827. EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
  4828. }
  4829. }
  4830. }
  4831. void CodeGenModule::EmitVersionIdentMetadata() {
  4832. llvm::NamedMDNode *IdentMetadata =
  4833. TheModule.getOrInsertNamedMetadata("llvm.ident");
  4834. std::string Version = getClangFullVersion();
  4835. llvm::LLVMContext &Ctx = TheModule.getContext();
  4836. llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
  4837. IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
  4838. }
  4839. void CodeGenModule::EmitCommandLineMetadata() {
  4840. llvm::NamedMDNode *CommandLineMetadata =
  4841. TheModule.getOrInsertNamedMetadata("llvm.commandline");
  4842. std::string CommandLine = getCodeGenOpts().RecordCommandLine;
  4843. llvm::LLVMContext &Ctx = TheModule.getContext();
  4844. llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)};
  4845. CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode));
  4846. }
  4847. void CodeGenModule::EmitTargetMetadata() {
  4848. // Warning, new MangledDeclNames may be appended within this loop.
  4849. // We rely on MapVector insertions adding new elements to the end
  4850. // of the container.
  4851. // FIXME: Move this loop into the one target that needs it, and only
  4852. // loop over those declarations for which we couldn't emit the target
  4853. // metadata when we emitted the declaration.
  4854. for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
  4855. auto Val = *(MangledDeclNames.begin() + I);
  4856. const Decl *D = Val.first.getDecl()->getMostRecentDecl();
  4857. llvm::GlobalValue *GV = GetGlobalValue(Val.second);
  4858. getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
  4859. }
  4860. }
  4861. void CodeGenModule::EmitCoverageFile() {
  4862. if (getCodeGenOpts().CoverageDataFile.empty() &&
  4863. getCodeGenOpts().CoverageNotesFile.empty())
  4864. return;
  4865. llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
  4866. if (!CUNode)
  4867. return;
  4868. llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
  4869. llvm::LLVMContext &Ctx = TheModule.getContext();
  4870. auto *CoverageDataFile =
  4871. llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
  4872. auto *CoverageNotesFile =
  4873. llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
  4874. for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
  4875. llvm::MDNode *CU = CUNode->getOperand(i);
  4876. llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
  4877. GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
  4878. }
  4879. }
  4880. llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
  4881. // Sema has checked that all uuid strings are of the form
  4882. // "12345678-1234-1234-1234-1234567890ab".
  4883. assert(Uuid.size() == 36);
  4884. for (unsigned i = 0; i < 36; ++i) {
  4885. if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
  4886. else assert(isHexDigit(Uuid[i]));
  4887. }
  4888. // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab".
  4889. const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
  4890. llvm::Constant *Field3[8];
  4891. for (unsigned Idx = 0; Idx < 8; ++Idx)
  4892. Field3[Idx] = llvm::ConstantInt::get(
  4893. Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
  4894. llvm::Constant *Fields[4] = {
  4895. llvm::ConstantInt::get(Int32Ty, Uuid.substr(0, 8), 16),
  4896. llvm::ConstantInt::get(Int16Ty, Uuid.substr(9, 4), 16),
  4897. llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
  4898. llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
  4899. };
  4900. return llvm::ConstantStruct::getAnon(Fields);
  4901. }
  4902. llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
  4903. bool ForEH) {
  4904. // Return a bogus pointer if RTTI is disabled, unless it's for EH.
  4905. // FIXME: should we even be calling this method if RTTI is disabled
  4906. // and it's not for EH?
  4907. if ((!ForEH && !getLangOpts().RTTI) || getLangOpts().CUDAIsDevice)
  4908. return llvm::Constant::getNullValue(Int8PtrTy);
  4909. if (ForEH && Ty->isObjCObjectPointerType() &&
  4910. LangOpts.ObjCRuntime.isGNUFamily())
  4911. return ObjCRuntime->GetEHType(Ty);
  4912. return getCXXABI().getAddrOfRTTIDescriptor(Ty);
  4913. }
  4914. void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
  4915. // Do not emit threadprivates in simd-only mode.
  4916. if (LangOpts.OpenMP && LangOpts.OpenMPSimd)
  4917. return;
  4918. for (auto RefExpr : D->varlists()) {
  4919. auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
  4920. bool PerformInit =
  4921. VD->getAnyInitializer() &&
  4922. !VD->getAnyInitializer()->isConstantInitializer(getContext(),
  4923. /*ForRef=*/false);
  4924. Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD));
  4925. if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
  4926. VD, Addr, RefExpr->getBeginLoc(), PerformInit))
  4927. CXXGlobalInits.push_back(InitFunction);
  4928. }
  4929. }
  4930. llvm::Metadata *
  4931. CodeGenModule::CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map,
  4932. StringRef Suffix) {
  4933. llvm::Metadata *&InternalId = Map[T.getCanonicalType()];
  4934. if (InternalId)
  4935. return InternalId;
  4936. if (isExternallyVisible(T->getLinkage())) {
  4937. std::string OutName;
  4938. llvm::raw_string_ostream Out(OutName);
  4939. getCXXABI().getMangleContext().mangleTypeName(T, Out);
  4940. Out << Suffix;
  4941. InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
  4942. } else {
  4943. InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
  4944. llvm::ArrayRef<llvm::Metadata *>());
  4945. }
  4946. return InternalId;
  4947. }
  4948. llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
  4949. return CreateMetadataIdentifierImpl(T, MetadataIdMap, "");
  4950. }
  4951. llvm::Metadata *
  4952. CodeGenModule::CreateMetadataIdentifierForVirtualMemPtrType(QualType T) {
  4953. return CreateMetadataIdentifierImpl(T, VirtualMetadataIdMap, ".virtual");
  4954. }
  4955. // Generalize pointer types to a void pointer with the qualifiers of the
  4956. // originally pointed-to type, e.g. 'const char *' and 'char * const *'
  4957. // generalize to 'const void *' while 'char *' and 'const char **' generalize to
  4958. // 'void *'.
  4959. static QualType GeneralizeType(ASTContext &Ctx, QualType Ty) {
  4960. if (!Ty->isPointerType())
  4961. return Ty;
  4962. return Ctx.getPointerType(
  4963. QualType(Ctx.VoidTy).withCVRQualifiers(
  4964. Ty->getPointeeType().getCVRQualifiers()));
  4965. }
  4966. // Apply type generalization to a FunctionType's return and argument types
  4967. static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty) {
  4968. if (auto *FnType = Ty->getAs<FunctionProtoType>()) {
  4969. SmallVector<QualType, 8> GeneralizedParams;
  4970. for (auto &Param : FnType->param_types())
  4971. GeneralizedParams.push_back(GeneralizeType(Ctx, Param));
  4972. return Ctx.getFunctionType(
  4973. GeneralizeType(Ctx, FnType->getReturnType()),
  4974. GeneralizedParams, FnType->getExtProtoInfo());
  4975. }
  4976. if (auto *FnType = Ty->getAs<FunctionNoProtoType>())
  4977. return Ctx.getFunctionNoProtoType(
  4978. GeneralizeType(Ctx, FnType->getReturnType()));
  4979. llvm_unreachable("Encountered unknown FunctionType");
  4980. }
  4981. llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) {
  4982. return CreateMetadataIdentifierImpl(GeneralizeFunctionType(getContext(), T),
  4983. GeneralizedMetadataIdMap, ".generalized");
  4984. }
  4985. /// Returns whether this module needs the "all-vtables" type identifier.
  4986. bool CodeGenModule::NeedAllVtablesTypeId() const {
  4987. // Returns true if at least one of vtable-based CFI checkers is enabled and
  4988. // is not in the trapping mode.
  4989. return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
  4990. !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
  4991. (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
  4992. !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
  4993. (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
  4994. !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
  4995. (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
  4996. !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
  4997. }
  4998. void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
  4999. CharUnits Offset,
  5000. const CXXRecordDecl *RD) {
  5001. llvm::Metadata *MD =
  5002. CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
  5003. VTable->addTypeMetadata(Offset.getQuantity(), MD);
  5004. if (CodeGenOpts.SanitizeCfiCrossDso)
  5005. if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
  5006. VTable->addTypeMetadata(Offset.getQuantity(),
  5007. llvm::ConstantAsMetadata::get(CrossDsoTypeId));
  5008. if (NeedAllVtablesTypeId()) {
  5009. llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
  5010. VTable->addTypeMetadata(Offset.getQuantity(), MD);
  5011. }
  5012. }
  5013. TargetAttr::ParsedTargetAttr CodeGenModule::filterFunctionTargetAttrs(const TargetAttr *TD) {
  5014. assert(TD != nullptr);
  5015. TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
  5016. ParsedAttr.Features.erase(
  5017. llvm::remove_if(ParsedAttr.Features,
  5018. [&](const std::string &Feat) {
  5019. return !Target.isValidFeatureName(
  5020. StringRef{Feat}.substr(1));
  5021. }),
  5022. ParsedAttr.Features.end());
  5023. return ParsedAttr;
  5024. }
  5025. // Fills in the supplied string map with the set of target features for the
  5026. // passed in function.
  5027. void CodeGenModule::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
  5028. GlobalDecl GD) {
  5029. StringRef TargetCPU = Target.getTargetOpts().CPU;
  5030. const FunctionDecl *FD = GD.getDecl()->getAsFunction();
  5031. if (const auto *TD = FD->getAttr<TargetAttr>()) {
  5032. TargetAttr::ParsedTargetAttr ParsedAttr = filterFunctionTargetAttrs(TD);
  5033. // Make a copy of the features as passed on the command line into the
  5034. // beginning of the additional features from the function to override.
  5035. ParsedAttr.Features.insert(ParsedAttr.Features.begin(),
  5036. Target.getTargetOpts().FeaturesAsWritten.begin(),
  5037. Target.getTargetOpts().FeaturesAsWritten.end());
  5038. if (ParsedAttr.Architecture != "" &&
  5039. Target.isValidCPUName(ParsedAttr.Architecture))
  5040. TargetCPU = ParsedAttr.Architecture;
  5041. // Now populate the feature map, first with the TargetCPU which is either
  5042. // the default or a new one from the target attribute string. Then we'll use
  5043. // the passed in features (FeaturesAsWritten) along with the new ones from
  5044. // the attribute.
  5045. Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
  5046. ParsedAttr.Features);
  5047. } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) {
  5048. llvm::SmallVector<StringRef, 32> FeaturesTmp;
  5049. Target.getCPUSpecificCPUDispatchFeatures(
  5050. SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp);
  5051. std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
  5052. Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU, Features);
  5053. } else {
  5054. Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
  5055. Target.getTargetOpts().Features);
  5056. }
  5057. }
  5058. llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
  5059. if (!SanStats)
  5060. SanStats = std::make_unique<llvm::SanitizerStatReport>(&getModule());
  5061. return *SanStats;
  5062. }
  5063. llvm::Value *
  5064. CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
  5065. CodeGenFunction &CGF) {
  5066. llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType());
  5067. auto SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr());
  5068. auto FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
  5069. return CGF.Builder.CreateCall(CreateRuntimeFunction(FTy,
  5070. "__translate_sampler_initializer"),
  5071. {C});
  5072. }