CodeGenModule.cpp 173 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623
  1. //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This coordinates the per-module state used while generating code.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "CodeGenModule.h"
  14. #include "CGBlocks.h"
  15. #include "CGCUDARuntime.h"
  16. #include "CGCXXABI.h"
  17. #include "CGCall.h"
  18. #include "CGDebugInfo.h"
  19. #include "CGObjCRuntime.h"
  20. #include "CGOpenCLRuntime.h"
  21. #include "CGOpenMPRuntime.h"
  22. #include "CGOpenMPRuntimeNVPTX.h"
  23. #include "CodeGenFunction.h"
  24. #include "CodeGenPGO.h"
  25. #include "ConstantEmitter.h"
  26. #include "CoverageMappingGen.h"
  27. #include "TargetInfo.h"
  28. #include "clang/AST/ASTContext.h"
  29. #include "clang/AST/CharUnits.h"
  30. #include "clang/AST/DeclCXX.h"
  31. #include "clang/AST/DeclObjC.h"
  32. #include "clang/AST/DeclTemplate.h"
  33. #include "clang/AST/Mangle.h"
  34. #include "clang/AST/RecordLayout.h"
  35. #include "clang/AST/RecursiveASTVisitor.h"
  36. #include "clang/Basic/Builtins.h"
  37. #include "clang/Basic/CharInfo.h"
  38. #include "clang/Basic/Diagnostic.h"
  39. #include "clang/Basic/Module.h"
  40. #include "clang/Basic/SourceManager.h"
  41. #include "clang/Basic/TargetInfo.h"
  42. #include "clang/Basic/Version.h"
  43. #include "clang/CodeGen/ConstantInitBuilder.h"
  44. #include "clang/Frontend/CodeGenOptions.h"
  45. #include "clang/Sema/SemaDiagnostic.h"
  46. #include "llvm/ADT/Triple.h"
  47. #include "llvm/Analysis/TargetLibraryInfo.h"
  48. #include "llvm/IR/CallSite.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/ProfileData/InstrProfReader.h"
  55. #include "llvm/Support/ConvertUTF.h"
  56. #include "llvm/Support/ErrorHandling.h"
  57. #include "llvm/Support/MD5.h"
  58. using namespace clang;
  59. using namespace CodeGen;
  60. static llvm::cl::opt<bool> LimitedCoverage(
  61. "limited-coverage-experimental", llvm::cl::ZeroOrMore,
  62. llvm::cl::desc("Emit limited coverage mapping information (experimental)"),
  63. llvm::cl::init(false));
  64. static const char AnnotationSection[] = "llvm.metadata";
  65. static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
  66. switch (CGM.getTarget().getCXXABI().getKind()) {
  67. case TargetCXXABI::GenericAArch64:
  68. case TargetCXXABI::GenericARM:
  69. case TargetCXXABI::iOS:
  70. case TargetCXXABI::iOS64:
  71. case TargetCXXABI::WatchOS:
  72. case TargetCXXABI::GenericMIPS:
  73. case TargetCXXABI::GenericItanium:
  74. case TargetCXXABI::WebAssembly:
  75. return CreateItaniumCXXABI(CGM);
  76. case TargetCXXABI::Microsoft:
  77. return CreateMicrosoftCXXABI(CGM);
  78. }
  79. llvm_unreachable("invalid C++ ABI kind");
  80. }
  81. CodeGenModule::CodeGenModule(ASTContext &C, const HeaderSearchOptions &HSO,
  82. const PreprocessorOptions &PPO,
  83. const CodeGenOptions &CGO, llvm::Module &M,
  84. DiagnosticsEngine &diags,
  85. CoverageSourceInfo *CoverageInfo)
  86. : Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO),
  87. PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
  88. Target(C.getTargetInfo()), ABI(createCXXABI(*this)),
  89. VMContext(M.getContext()), Types(*this), VTables(*this),
  90. SanitizerMD(new SanitizerMetadata(*this)) {
  91. // Initialize the type cache.
  92. llvm::LLVMContext &LLVMContext = M.getContext();
  93. VoidTy = llvm::Type::getVoidTy(LLVMContext);
  94. Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
  95. Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
  96. Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
  97. Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
  98. FloatTy = llvm::Type::getFloatTy(LLVMContext);
  99. DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
  100. PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
  101. PointerAlignInBytes =
  102. C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
  103. SizeSizeInBytes =
  104. C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity();
  105. IntAlignInBytes =
  106. C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity();
  107. IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
  108. IntPtrTy = llvm::IntegerType::get(LLVMContext,
  109. C.getTargetInfo().getMaxPointerWidth());
  110. Int8PtrTy = Int8Ty->getPointerTo(0);
  111. Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
  112. AllocaInt8PtrTy = Int8Ty->getPointerTo(
  113. M.getDataLayout().getAllocaAddrSpace());
  114. ASTAllocaAddressSpace = getTargetCodeGenInfo().getASTAllocaAddressSpace();
  115. RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
  116. BuiltinCC = getTargetCodeGenInfo().getABIInfo().getBuiltinCC();
  117. if (LangOpts.ObjC1)
  118. createObjCRuntime();
  119. if (LangOpts.OpenCL)
  120. createOpenCLRuntime();
  121. if (LangOpts.OpenMP)
  122. createOpenMPRuntime();
  123. if (LangOpts.CUDA)
  124. createCUDARuntime();
  125. // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
  126. if (LangOpts.Sanitize.has(SanitizerKind::Thread) ||
  127. (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
  128. TBAA.reset(new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(),
  129. getCXXABI().getMangleContext()));
  130. // If debug info or coverage generation is enabled, create the CGDebugInfo
  131. // object.
  132. if (CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo ||
  133. CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)
  134. DebugInfo.reset(new CGDebugInfo(*this));
  135. Block.GlobalUniqueCount = 0;
  136. if (C.getLangOpts().ObjC1)
  137. ObjCData.reset(new ObjCEntrypoints());
  138. if (CodeGenOpts.hasProfileClangUse()) {
  139. auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
  140. CodeGenOpts.ProfileInstrumentUsePath);
  141. if (auto E = ReaderOrErr.takeError()) {
  142. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  143. "Could not read profile %0: %1");
  144. llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) {
  145. getDiags().Report(DiagID) << CodeGenOpts.ProfileInstrumentUsePath
  146. << EI.message();
  147. });
  148. } else
  149. PGOReader = std::move(ReaderOrErr.get());
  150. }
  151. // If coverage mapping generation is enabled, create the
  152. // CoverageMappingModuleGen object.
  153. if (CodeGenOpts.CoverageMapping)
  154. CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
  155. }
  156. CodeGenModule::~CodeGenModule() {}
  157. void CodeGenModule::createObjCRuntime() {
  158. // This is just isGNUFamily(), but we want to force implementors of
  159. // new ABIs to decide how best to do this.
  160. switch (LangOpts.ObjCRuntime.getKind()) {
  161. case ObjCRuntime::GNUstep:
  162. case ObjCRuntime::GCC:
  163. case ObjCRuntime::ObjFW:
  164. ObjCRuntime.reset(CreateGNUObjCRuntime(*this));
  165. return;
  166. case ObjCRuntime::FragileMacOSX:
  167. case ObjCRuntime::MacOSX:
  168. case ObjCRuntime::iOS:
  169. case ObjCRuntime::WatchOS:
  170. ObjCRuntime.reset(CreateMacObjCRuntime(*this));
  171. return;
  172. }
  173. llvm_unreachable("bad runtime kind");
  174. }
  175. void CodeGenModule::createOpenCLRuntime() {
  176. OpenCLRuntime.reset(new CGOpenCLRuntime(*this));
  177. }
  178. void CodeGenModule::createOpenMPRuntime() {
  179. // Select a specialized code generation class based on the target, if any.
  180. // If it does not exist use the default implementation.
  181. switch (getTriple().getArch()) {
  182. case llvm::Triple::nvptx:
  183. case llvm::Triple::nvptx64:
  184. assert(getLangOpts().OpenMPIsDevice &&
  185. "OpenMP NVPTX is only prepared to deal with device code.");
  186. OpenMPRuntime.reset(new CGOpenMPRuntimeNVPTX(*this));
  187. break;
  188. default:
  189. OpenMPRuntime.reset(new CGOpenMPRuntime(*this));
  190. break;
  191. }
  192. }
  193. void CodeGenModule::createCUDARuntime() {
  194. CUDARuntime.reset(CreateNVCUDARuntime(*this));
  195. }
  196. void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
  197. Replacements[Name] = C;
  198. }
  199. void CodeGenModule::applyReplacements() {
  200. for (auto &I : Replacements) {
  201. StringRef MangledName = I.first();
  202. llvm::Constant *Replacement = I.second;
  203. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  204. if (!Entry)
  205. continue;
  206. auto *OldF = cast<llvm::Function>(Entry);
  207. auto *NewF = dyn_cast<llvm::Function>(Replacement);
  208. if (!NewF) {
  209. if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
  210. NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
  211. } else {
  212. auto *CE = cast<llvm::ConstantExpr>(Replacement);
  213. assert(CE->getOpcode() == llvm::Instruction::BitCast ||
  214. CE->getOpcode() == llvm::Instruction::GetElementPtr);
  215. NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
  216. }
  217. }
  218. // Replace old with new, but keep the old order.
  219. OldF->replaceAllUsesWith(Replacement);
  220. if (NewF) {
  221. NewF->removeFromParent();
  222. OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
  223. NewF);
  224. }
  225. OldF->eraseFromParent();
  226. }
  227. }
  228. void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) {
  229. GlobalValReplacements.push_back(std::make_pair(GV, C));
  230. }
  231. void CodeGenModule::applyGlobalValReplacements() {
  232. for (auto &I : GlobalValReplacements) {
  233. llvm::GlobalValue *GV = I.first;
  234. llvm::Constant *C = I.second;
  235. GV->replaceAllUsesWith(C);
  236. GV->eraseFromParent();
  237. }
  238. }
  239. // This is only used in aliases that we created and we know they have a
  240. // linear structure.
  241. static const llvm::GlobalObject *getAliasedGlobal(
  242. const llvm::GlobalIndirectSymbol &GIS) {
  243. llvm::SmallPtrSet<const llvm::GlobalIndirectSymbol*, 4> Visited;
  244. const llvm::Constant *C = &GIS;
  245. for (;;) {
  246. C = C->stripPointerCasts();
  247. if (auto *GO = dyn_cast<llvm::GlobalObject>(C))
  248. return GO;
  249. // stripPointerCasts will not walk over weak aliases.
  250. auto *GIS2 = dyn_cast<llvm::GlobalIndirectSymbol>(C);
  251. if (!GIS2)
  252. return nullptr;
  253. if (!Visited.insert(GIS2).second)
  254. return nullptr;
  255. C = GIS2->getIndirectSymbol();
  256. }
  257. }
  258. void CodeGenModule::checkAliases() {
  259. // Check if the constructed aliases are well formed. It is really unfortunate
  260. // that we have to do this in CodeGen, but we only construct mangled names
  261. // and aliases during codegen.
  262. bool Error = false;
  263. DiagnosticsEngine &Diags = getDiags();
  264. for (const GlobalDecl &GD : Aliases) {
  265. const auto *D = cast<ValueDecl>(GD.getDecl());
  266. SourceLocation Location;
  267. bool IsIFunc = D->hasAttr<IFuncAttr>();
  268. if (const Attr *A = D->getDefiningAttr())
  269. Location = A->getLocation();
  270. else
  271. llvm_unreachable("Not an alias or ifunc?");
  272. StringRef MangledName = getMangledName(GD);
  273. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  274. auto *Alias = cast<llvm::GlobalIndirectSymbol>(Entry);
  275. const llvm::GlobalValue *GV = getAliasedGlobal(*Alias);
  276. if (!GV) {
  277. Error = true;
  278. Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc;
  279. } else if (GV->isDeclaration()) {
  280. Error = true;
  281. Diags.Report(Location, diag::err_alias_to_undefined)
  282. << IsIFunc << IsIFunc;
  283. } else if (IsIFunc) {
  284. // Check resolver function type.
  285. llvm::FunctionType *FTy = dyn_cast<llvm::FunctionType>(
  286. GV->getType()->getPointerElementType());
  287. assert(FTy);
  288. if (!FTy->getReturnType()->isPointerTy())
  289. Diags.Report(Location, diag::err_ifunc_resolver_return);
  290. if (FTy->getNumParams())
  291. Diags.Report(Location, diag::err_ifunc_resolver_params);
  292. }
  293. llvm::Constant *Aliasee = Alias->getIndirectSymbol();
  294. llvm::GlobalValue *AliaseeGV;
  295. if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
  296. AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
  297. else
  298. AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
  299. if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
  300. StringRef AliasSection = SA->getName();
  301. if (AliasSection != AliaseeGV->getSection())
  302. Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
  303. << AliasSection << IsIFunc << IsIFunc;
  304. }
  305. // We have to handle alias to weak aliases in here. LLVM itself disallows
  306. // this since the object semantics would not match the IL one. For
  307. // compatibility with gcc we implement it by just pointing the alias
  308. // to its aliasee's aliasee. We also warn, since the user is probably
  309. // expecting the link to be weak.
  310. if (auto GA = dyn_cast<llvm::GlobalIndirectSymbol>(AliaseeGV)) {
  311. if (GA->isInterposable()) {
  312. Diags.Report(Location, diag::warn_alias_to_weak_alias)
  313. << GV->getName() << GA->getName() << IsIFunc;
  314. Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
  315. GA->getIndirectSymbol(), Alias->getType());
  316. Alias->setIndirectSymbol(Aliasee);
  317. }
  318. }
  319. }
  320. if (!Error)
  321. return;
  322. for (const GlobalDecl &GD : Aliases) {
  323. StringRef MangledName = getMangledName(GD);
  324. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  325. auto *Alias = dyn_cast<llvm::GlobalIndirectSymbol>(Entry);
  326. Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
  327. Alias->eraseFromParent();
  328. }
  329. }
  330. void CodeGenModule::clear() {
  331. DeferredDeclsToEmit.clear();
  332. if (OpenMPRuntime)
  333. OpenMPRuntime->clear();
  334. }
  335. void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags,
  336. StringRef MainFile) {
  337. if (!hasDiagnostics())
  338. return;
  339. if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
  340. if (MainFile.empty())
  341. MainFile = "<stdin>";
  342. Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
  343. } else {
  344. if (Mismatched > 0)
  345. Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched;
  346. if (Missing > 0)
  347. Diags.Report(diag::warn_profile_data_missing) << Visited << Missing;
  348. }
  349. }
  350. void CodeGenModule::Release() {
  351. EmitDeferred();
  352. EmitVTablesOpportunistically();
  353. applyGlobalValReplacements();
  354. applyReplacements();
  355. checkAliases();
  356. EmitCXXGlobalInitFunc();
  357. EmitCXXGlobalDtorFunc();
  358. EmitCXXThreadLocalInitFunc();
  359. if (ObjCRuntime)
  360. if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
  361. AddGlobalCtor(ObjCInitFunction);
  362. if (Context.getLangOpts().CUDA && !Context.getLangOpts().CUDAIsDevice &&
  363. CUDARuntime) {
  364. if (llvm::Function *CudaCtorFunction = CUDARuntime->makeModuleCtorFunction())
  365. AddGlobalCtor(CudaCtorFunction);
  366. if (llvm::Function *CudaDtorFunction = CUDARuntime->makeModuleDtorFunction())
  367. AddGlobalDtor(CudaDtorFunction);
  368. }
  369. if (OpenMPRuntime)
  370. if (llvm::Function *OpenMPRegistrationFunction =
  371. OpenMPRuntime->emitRegistrationFunction()) {
  372. auto ComdatKey = OpenMPRegistrationFunction->hasComdat() ?
  373. OpenMPRegistrationFunction : nullptr;
  374. AddGlobalCtor(OpenMPRegistrationFunction, 0, ComdatKey);
  375. }
  376. if (PGOReader) {
  377. getModule().setProfileSummary(PGOReader->getSummary().getMD(VMContext));
  378. if (PGOStats.hasDiagnostics())
  379. PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
  380. }
  381. EmitCtorList(GlobalCtors, "llvm.global_ctors");
  382. EmitCtorList(GlobalDtors, "llvm.global_dtors");
  383. EmitGlobalAnnotations();
  384. EmitStaticExternCAliases();
  385. EmitDeferredUnusedCoverageMappings();
  386. if (CoverageMapping)
  387. CoverageMapping->emit();
  388. if (CodeGenOpts.SanitizeCfiCrossDso) {
  389. CodeGenFunction(*this).EmitCfiCheckFail();
  390. CodeGenFunction(*this).EmitCfiCheckStub();
  391. }
  392. emitAtAvailableLinkGuard();
  393. emitLLVMUsed();
  394. if (SanStats)
  395. SanStats->finish();
  396. if (CodeGenOpts.Autolink &&
  397. (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
  398. EmitModuleLinkOptions();
  399. }
  400. // Record mregparm value now so it is visible through rest of codegen.
  401. if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
  402. getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters",
  403. CodeGenOpts.NumRegisterParameters);
  404. if (CodeGenOpts.DwarfVersion) {
  405. // We actually want the latest version when there are conflicts.
  406. // We can change from Warning to Latest if such mode is supported.
  407. getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version",
  408. CodeGenOpts.DwarfVersion);
  409. }
  410. if (CodeGenOpts.EmitCodeView) {
  411. // Indicate that we want CodeView in the metadata.
  412. getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1);
  413. }
  414. if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
  415. // We don't support LTO with 2 with different StrictVTablePointers
  416. // FIXME: we could support it by stripping all the information introduced
  417. // by StrictVTablePointers.
  418. getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1);
  419. llvm::Metadata *Ops[2] = {
  420. llvm::MDString::get(VMContext, "StrictVTablePointers"),
  421. llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
  422. llvm::Type::getInt32Ty(VMContext), 1))};
  423. getModule().addModuleFlag(llvm::Module::Require,
  424. "StrictVTablePointersRequirement",
  425. llvm::MDNode::get(VMContext, Ops));
  426. }
  427. if (DebugInfo)
  428. // We support a single version in the linked module. The LLVM
  429. // parser will drop debug info with a different version number
  430. // (and warn about it, too).
  431. getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
  432. llvm::DEBUG_METADATA_VERSION);
  433. // We need to record the widths of enums and wchar_t, so that we can generate
  434. // the correct build attributes in the ARM backend. wchar_size is also used by
  435. // TargetLibraryInfo.
  436. uint64_t WCharWidth =
  437. Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
  438. getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
  439. llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
  440. if ( Arch == llvm::Triple::arm
  441. || Arch == llvm::Triple::armeb
  442. || Arch == llvm::Triple::thumb
  443. || Arch == llvm::Triple::thumbeb) {
  444. // The minimum width of an enum in bytes
  445. uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
  446. getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
  447. }
  448. if (CodeGenOpts.SanitizeCfiCrossDso) {
  449. // Indicate that we want cross-DSO control flow integrity checks.
  450. getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1);
  451. }
  452. if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) {
  453. // Indicate whether __nvvm_reflect should be configured to flush denormal
  454. // floating point values to 0. (This corresponds to its "__CUDA_FTZ"
  455. // property.)
  456. getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz",
  457. LangOpts.CUDADeviceFlushDenormalsToZero ? 1 : 0);
  458. }
  459. // Emit OpenCL specific module metadata: OpenCL/SPIR version.
  460. if (LangOpts.OpenCL) {
  461. EmitOpenCLMetadata();
  462. // Emit SPIR version.
  463. if (getTriple().getArch() == llvm::Triple::spir ||
  464. getTriple().getArch() == llvm::Triple::spir64) {
  465. // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the
  466. // opencl.spir.version named metadata.
  467. llvm::Metadata *SPIRVerElts[] = {
  468. llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
  469. Int32Ty, LangOpts.OpenCLVersion / 100)),
  470. llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
  471. Int32Ty, (LangOpts.OpenCLVersion / 100 > 1) ? 0 : 2))};
  472. llvm::NamedMDNode *SPIRVerMD =
  473. TheModule.getOrInsertNamedMetadata("opencl.spir.version");
  474. llvm::LLVMContext &Ctx = TheModule.getContext();
  475. SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
  476. }
  477. }
  478. if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
  479. assert(PLevel < 3 && "Invalid PIC Level");
  480. getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel));
  481. if (Context.getLangOpts().PIE)
  482. getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel));
  483. }
  484. SimplifyPersonality();
  485. if (getCodeGenOpts().EmitDeclMetadata)
  486. EmitDeclMetadata();
  487. if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
  488. EmitCoverageFile();
  489. if (DebugInfo)
  490. DebugInfo->finalize();
  491. EmitVersionIdentMetadata();
  492. EmitTargetMetadata();
  493. }
  494. void CodeGenModule::EmitOpenCLMetadata() {
  495. // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the
  496. // opencl.ocl.version named metadata node.
  497. llvm::Metadata *OCLVerElts[] = {
  498. llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
  499. Int32Ty, LangOpts.OpenCLVersion / 100)),
  500. llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
  501. Int32Ty, (LangOpts.OpenCLVersion % 100) / 10))};
  502. llvm::NamedMDNode *OCLVerMD =
  503. TheModule.getOrInsertNamedMetadata("opencl.ocl.version");
  504. llvm::LLVMContext &Ctx = TheModule.getContext();
  505. OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
  506. }
  507. void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
  508. // Make sure that this type is translated.
  509. Types.UpdateCompletedType(TD);
  510. }
  511. void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) {
  512. // Make sure that this type is translated.
  513. Types.RefreshTypeCacheForClass(RD);
  514. }
  515. llvm::MDNode *CodeGenModule::getTBAATypeInfo(QualType QTy) {
  516. if (!TBAA)
  517. return nullptr;
  518. return TBAA->getTypeInfo(QTy);
  519. }
  520. TBAAAccessInfo CodeGenModule::getTBAAAccessInfo(QualType AccessType) {
  521. return TBAAAccessInfo(getTBAATypeInfo(AccessType));
  522. }
  523. TBAAAccessInfo CodeGenModule::getTBAAVTablePtrAccessInfo() {
  524. if (!TBAA)
  525. return TBAAAccessInfo();
  526. return TBAA->getVTablePtrAccessInfo();
  527. }
  528. llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
  529. if (!TBAA)
  530. return nullptr;
  531. return TBAA->getTBAAStructInfo(QTy);
  532. }
  533. llvm::MDNode *CodeGenModule::getTBAABaseTypeInfo(QualType QTy) {
  534. if (!TBAA)
  535. return nullptr;
  536. return TBAA->getBaseTypeInfo(QTy);
  537. }
  538. llvm::MDNode *CodeGenModule::getTBAAAccessTagInfo(TBAAAccessInfo Info) {
  539. if (!TBAA)
  540. return nullptr;
  541. return TBAA->getAccessTagInfo(Info);
  542. }
  543. TBAAAccessInfo CodeGenModule::getTBAAMayAliasAccessInfo() {
  544. if (!TBAA)
  545. return TBAAAccessInfo();
  546. return TBAA->getMayAliasAccessInfo();
  547. }
  548. TBAAAccessInfo CodeGenModule::mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo,
  549. TBAAAccessInfo TargetInfo) {
  550. if (!TBAA)
  551. return TBAAAccessInfo();
  552. return TBAA->mergeTBAAInfoForCast(SourceInfo, TargetInfo);
  553. }
  554. void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst,
  555. TBAAAccessInfo TBAAInfo) {
  556. if (llvm::MDNode *Tag = getTBAAAccessTagInfo(TBAAInfo))
  557. Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag);
  558. }
  559. void CodeGenModule::DecorateInstructionWithInvariantGroup(
  560. llvm::Instruction *I, const CXXRecordDecl *RD) {
  561. I->setMetadata(llvm::LLVMContext::MD_invariant_group,
  562. llvm::MDNode::get(getLLVMContext(), {}));
  563. }
  564. void CodeGenModule::Error(SourceLocation loc, StringRef message) {
  565. unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
  566. getDiags().Report(Context.getFullLoc(loc), diagID) << message;
  567. }
  568. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  569. /// specified stmt yet.
  570. void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
  571. unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
  572. "cannot compile this %0 yet");
  573. std::string Msg = Type;
  574. getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
  575. << Msg << S->getSourceRange();
  576. }
  577. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  578. /// specified decl yet.
  579. void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
  580. unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
  581. "cannot compile this %0 yet");
  582. std::string Msg = Type;
  583. getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
  584. }
  585. llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
  586. return llvm::ConstantInt::get(SizeTy, size.getQuantity());
  587. }
  588. void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
  589. const NamedDecl *D) const {
  590. // Internal definitions always have default visibility.
  591. if (GV->hasLocalLinkage()) {
  592. GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
  593. return;
  594. }
  595. // Set visibility for definitions.
  596. LinkageInfo LV = D->getLinkageAndVisibility();
  597. if (LV.isVisibilityExplicit() || !GV->hasAvailableExternallyLinkage())
  598. GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
  599. }
  600. static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
  601. return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
  602. .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
  603. .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
  604. .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
  605. .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
  606. }
  607. static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
  608. CodeGenOptions::TLSModel M) {
  609. switch (M) {
  610. case CodeGenOptions::GeneralDynamicTLSModel:
  611. return llvm::GlobalVariable::GeneralDynamicTLSModel;
  612. case CodeGenOptions::LocalDynamicTLSModel:
  613. return llvm::GlobalVariable::LocalDynamicTLSModel;
  614. case CodeGenOptions::InitialExecTLSModel:
  615. return llvm::GlobalVariable::InitialExecTLSModel;
  616. case CodeGenOptions::LocalExecTLSModel:
  617. return llvm::GlobalVariable::LocalExecTLSModel;
  618. }
  619. llvm_unreachable("Invalid TLS model!");
  620. }
  621. void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
  622. assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
  623. llvm::GlobalValue::ThreadLocalMode TLM;
  624. TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
  625. // Override the TLS model if it is explicitly specified.
  626. if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
  627. TLM = GetLLVMTLSModel(Attr->getModel());
  628. }
  629. GV->setThreadLocalMode(TLM);
  630. }
  631. StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
  632. GlobalDecl CanonicalGD = GD.getCanonicalDecl();
  633. // Some ABIs don't have constructor variants. Make sure that base and
  634. // complete constructors get mangled the same.
  635. if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) {
  636. if (!getTarget().getCXXABI().hasConstructorVariants()) {
  637. CXXCtorType OrigCtorType = GD.getCtorType();
  638. assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete);
  639. if (OrigCtorType == Ctor_Base)
  640. CanonicalGD = GlobalDecl(CD, Ctor_Complete);
  641. }
  642. }
  643. auto FoundName = MangledDeclNames.find(CanonicalGD);
  644. if (FoundName != MangledDeclNames.end())
  645. return FoundName->second;
  646. const auto *ND = cast<NamedDecl>(GD.getDecl());
  647. SmallString<256> Buffer;
  648. StringRef Str;
  649. if (getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
  650. llvm::raw_svector_ostream Out(Buffer);
  651. if (const auto *D = dyn_cast<CXXConstructorDecl>(ND))
  652. getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
  653. else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND))
  654. getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
  655. else
  656. getCXXABI().getMangleContext().mangleName(ND, Out);
  657. Str = Out.str();
  658. } else {
  659. IdentifierInfo *II = ND->getIdentifier();
  660. assert(II && "Attempt to mangle unnamed decl.");
  661. const auto *FD = dyn_cast<FunctionDecl>(ND);
  662. if (FD &&
  663. FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) {
  664. llvm::raw_svector_ostream Out(Buffer);
  665. Out << "__regcall3__" << II->getName();
  666. Str = Out.str();
  667. } else {
  668. Str = II->getName();
  669. }
  670. }
  671. // Keep the first result in the case of a mangling collision.
  672. auto Result = Manglings.insert(std::make_pair(Str, GD));
  673. return MangledDeclNames[CanonicalGD] = Result.first->first();
  674. }
  675. StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
  676. const BlockDecl *BD) {
  677. MangleContext &MangleCtx = getCXXABI().getMangleContext();
  678. const Decl *D = GD.getDecl();
  679. SmallString<256> Buffer;
  680. llvm::raw_svector_ostream Out(Buffer);
  681. if (!D)
  682. MangleCtx.mangleGlobalBlock(BD,
  683. dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
  684. else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
  685. MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
  686. else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
  687. MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
  688. else
  689. MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
  690. auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
  691. return Result.first->first();
  692. }
  693. llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
  694. return getModule().getNamedValue(Name);
  695. }
  696. /// AddGlobalCtor - Add a function to the list that will be called before
  697. /// main() runs.
  698. void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
  699. llvm::Constant *AssociatedData) {
  700. // FIXME: Type coercion of void()* types.
  701. GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
  702. }
  703. /// AddGlobalDtor - Add a function to the list that will be called
  704. /// when the module is unloaded.
  705. void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) {
  706. // FIXME: Type coercion of void()* types.
  707. GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
  708. }
  709. void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) {
  710. if (Fns.empty()) return;
  711. // Ctor function type is void()*.
  712. llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
  713. llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
  714. // Get the type of a ctor entry, { i32, void ()*, i8* }.
  715. llvm::StructType *CtorStructTy = llvm::StructType::get(
  716. Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy);
  717. // Construct the constructor and destructor arrays.
  718. ConstantInitBuilder builder(*this);
  719. auto ctors = builder.beginArray(CtorStructTy);
  720. for (const auto &I : Fns) {
  721. auto ctor = ctors.beginStruct(CtorStructTy);
  722. ctor.addInt(Int32Ty, I.Priority);
  723. ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy));
  724. if (I.AssociatedData)
  725. ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy));
  726. else
  727. ctor.addNullPointer(VoidPtrTy);
  728. ctor.finishAndAddTo(ctors);
  729. }
  730. auto list =
  731. ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(),
  732. /*constant*/ false,
  733. llvm::GlobalValue::AppendingLinkage);
  734. // The LTO linker doesn't seem to like it when we set an alignment
  735. // on appending variables. Take it off as a workaround.
  736. list->setAlignment(0);
  737. Fns.clear();
  738. }
  739. llvm::GlobalValue::LinkageTypes
  740. CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
  741. const auto *D = cast<FunctionDecl>(GD.getDecl());
  742. GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
  743. if (isa<CXXDestructorDecl>(D) &&
  744. getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
  745. GD.getDtorType())) {
  746. // Destructor variants in the Microsoft C++ ABI are always internal or
  747. // linkonce_odr thunks emitted on an as-needed basis.
  748. return Linkage == GVA_Internal ? llvm::GlobalValue::InternalLinkage
  749. : llvm::GlobalValue::LinkOnceODRLinkage;
  750. }
  751. if (isa<CXXConstructorDecl>(D) &&
  752. cast<CXXConstructorDecl>(D)->isInheritingConstructor() &&
  753. Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  754. // Our approach to inheriting constructors is fundamentally different from
  755. // that used by the MS ABI, so keep our inheriting constructor thunks
  756. // internal rather than trying to pick an unambiguous mangling for them.
  757. return llvm::GlobalValue::InternalLinkage;
  758. }
  759. return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false);
  760. }
  761. void CodeGenModule::setFunctionDLLStorageClass(GlobalDecl GD, llvm::Function *F) {
  762. const auto *FD = cast<FunctionDecl>(GD.getDecl());
  763. if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(FD)) {
  764. if (getCXXABI().useThunkForDtorVariant(Dtor, GD.getDtorType())) {
  765. // Don't dllexport/import destructor thunks.
  766. F->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
  767. return;
  768. }
  769. }
  770. if (FD->hasAttr<DLLImportAttr>())
  771. F->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
  772. else if (FD->hasAttr<DLLExportAttr>())
  773. F->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
  774. else
  775. F->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
  776. }
  777. llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) {
  778. llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
  779. if (!MDS) return nullptr;
  780. return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString()));
  781. }
  782. void CodeGenModule::setFunctionDefinitionAttributes(const FunctionDecl *D,
  783. llvm::Function *F) {
  784. setNonAliasAttributes(D, F);
  785. }
  786. void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
  787. const CGFunctionInfo &Info,
  788. llvm::Function *F) {
  789. unsigned CallingConv;
  790. llvm::AttributeList PAL;
  791. ConstructAttributeList(F->getName(), Info, D, PAL, CallingConv, false);
  792. F->setAttributes(PAL);
  793. F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
  794. }
  795. /// Determines whether the language options require us to model
  796. /// unwind exceptions. We treat -fexceptions as mandating this
  797. /// except under the fragile ObjC ABI with only ObjC exceptions
  798. /// enabled. This means, for example, that C with -fexceptions
  799. /// enables this.
  800. static bool hasUnwindExceptions(const LangOptions &LangOpts) {
  801. // If exceptions are completely disabled, obviously this is false.
  802. if (!LangOpts.Exceptions) return false;
  803. // If C++ exceptions are enabled, this is true.
  804. if (LangOpts.CXXExceptions) return true;
  805. // If ObjC exceptions are enabled, this depends on the ABI.
  806. if (LangOpts.ObjCExceptions) {
  807. return LangOpts.ObjCRuntime.hasUnwindExceptions();
  808. }
  809. return true;
  810. }
  811. void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
  812. llvm::Function *F) {
  813. llvm::AttrBuilder B;
  814. if (CodeGenOpts.UnwindTables)
  815. B.addAttribute(llvm::Attribute::UWTable);
  816. if (!hasUnwindExceptions(LangOpts))
  817. B.addAttribute(llvm::Attribute::NoUnwind);
  818. if (LangOpts.getStackProtector() == LangOptions::SSPOn)
  819. B.addAttribute(llvm::Attribute::StackProtect);
  820. else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
  821. B.addAttribute(llvm::Attribute::StackProtectStrong);
  822. else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
  823. B.addAttribute(llvm::Attribute::StackProtectReq);
  824. if (!D) {
  825. // If we don't have a declaration to control inlining, the function isn't
  826. // explicitly marked as alwaysinline for semantic reasons, and inlining is
  827. // disabled, mark the function as noinline.
  828. if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
  829. CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining)
  830. B.addAttribute(llvm::Attribute::NoInline);
  831. F->addAttributes(llvm::AttributeList::FunctionIndex, B);
  832. return;
  833. }
  834. // Track whether we need to add the optnone LLVM attribute,
  835. // starting with the default for this optimization level.
  836. bool ShouldAddOptNone =
  837. !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
  838. // We can't add optnone in the following cases, it won't pass the verifier.
  839. ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>();
  840. ShouldAddOptNone &= !F->hasFnAttribute(llvm::Attribute::AlwaysInline);
  841. ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>();
  842. if (ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) {
  843. B.addAttribute(llvm::Attribute::OptimizeNone);
  844. // OptimizeNone implies noinline; we should not be inlining such functions.
  845. B.addAttribute(llvm::Attribute::NoInline);
  846. assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
  847. "OptimizeNone and AlwaysInline on same function!");
  848. // We still need to handle naked functions even though optnone subsumes
  849. // much of their semantics.
  850. if (D->hasAttr<NakedAttr>())
  851. B.addAttribute(llvm::Attribute::Naked);
  852. // OptimizeNone wins over OptimizeForSize and MinSize.
  853. F->removeFnAttr(llvm::Attribute::OptimizeForSize);
  854. F->removeFnAttr(llvm::Attribute::MinSize);
  855. } else if (D->hasAttr<NakedAttr>()) {
  856. // Naked implies noinline: we should not be inlining such functions.
  857. B.addAttribute(llvm::Attribute::Naked);
  858. B.addAttribute(llvm::Attribute::NoInline);
  859. } else if (D->hasAttr<NoDuplicateAttr>()) {
  860. B.addAttribute(llvm::Attribute::NoDuplicate);
  861. } else if (D->hasAttr<NoInlineAttr>()) {
  862. B.addAttribute(llvm::Attribute::NoInline);
  863. } else if (D->hasAttr<AlwaysInlineAttr>() &&
  864. !F->hasFnAttribute(llvm::Attribute::NoInline)) {
  865. // (noinline wins over always_inline, and we can't specify both in IR)
  866. B.addAttribute(llvm::Attribute::AlwaysInline);
  867. } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) {
  868. // If we're not inlining, then force everything that isn't always_inline to
  869. // carry an explicit noinline attribute.
  870. if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
  871. B.addAttribute(llvm::Attribute::NoInline);
  872. } else {
  873. // Otherwise, propagate the inline hint attribute and potentially use its
  874. // absence to mark things as noinline.
  875. if (auto *FD = dyn_cast<FunctionDecl>(D)) {
  876. if (any_of(FD->redecls(), [&](const FunctionDecl *Redecl) {
  877. return Redecl->isInlineSpecified();
  878. })) {
  879. B.addAttribute(llvm::Attribute::InlineHint);
  880. } else if (CodeGenOpts.getInlining() ==
  881. CodeGenOptions::OnlyHintInlining &&
  882. !FD->isInlined() &&
  883. !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
  884. B.addAttribute(llvm::Attribute::NoInline);
  885. }
  886. }
  887. }
  888. // Add other optimization related attributes if we are optimizing this
  889. // function.
  890. if (!D->hasAttr<OptimizeNoneAttr>()) {
  891. if (D->hasAttr<ColdAttr>()) {
  892. if (!ShouldAddOptNone)
  893. B.addAttribute(llvm::Attribute::OptimizeForSize);
  894. B.addAttribute(llvm::Attribute::Cold);
  895. }
  896. if (D->hasAttr<MinSizeAttr>())
  897. B.addAttribute(llvm::Attribute::MinSize);
  898. }
  899. F->addAttributes(llvm::AttributeList::FunctionIndex, B);
  900. unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
  901. if (alignment)
  902. F->setAlignment(alignment);
  903. // Some C++ ABIs require 2-byte alignment for member functions, in order to
  904. // reserve a bit for differentiating between virtual and non-virtual member
  905. // functions. If the current target's C++ ABI requires this and this is a
  906. // member function, set its alignment accordingly.
  907. if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
  908. if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
  909. F->setAlignment(2);
  910. }
  911. // In the cross-dso CFI mode, we want !type attributes on definitions only.
  912. if (CodeGenOpts.SanitizeCfiCrossDso)
  913. if (auto *FD = dyn_cast<FunctionDecl>(D))
  914. CreateFunctionTypeMetadata(FD, F);
  915. }
  916. void CodeGenModule::SetCommonAttributes(const Decl *D,
  917. llvm::GlobalValue *GV) {
  918. if (const auto *ND = dyn_cast_or_null<NamedDecl>(D))
  919. setGlobalVisibility(GV, ND);
  920. else
  921. GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
  922. if (D && D->hasAttr<UsedAttr>())
  923. addUsedGlobal(GV);
  924. }
  925. void CodeGenModule::setAliasAttributes(const Decl *D,
  926. llvm::GlobalValue *GV) {
  927. SetCommonAttributes(D, GV);
  928. // Process the dllexport attribute based on whether the original definition
  929. // (not necessarily the aliasee) was exported.
  930. if (D->hasAttr<DLLExportAttr>())
  931. GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
  932. }
  933. void CodeGenModule::setNonAliasAttributes(const Decl *D,
  934. llvm::GlobalObject *GO) {
  935. SetCommonAttributes(D, GO);
  936. if (D) {
  937. if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
  938. if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>())
  939. GV->addAttribute("bss-section", SA->getName());
  940. if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>())
  941. GV->addAttribute("data-section", SA->getName());
  942. if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>())
  943. GV->addAttribute("rodata-section", SA->getName());
  944. }
  945. if (auto *F = dyn_cast<llvm::Function>(GO)) {
  946. if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>())
  947. if (!D->getAttr<SectionAttr>())
  948. F->addFnAttr("implicit-section-name", SA->getName());
  949. }
  950. if (const SectionAttr *SA = D->getAttr<SectionAttr>())
  951. GO->setSection(SA->getName());
  952. }
  953. getTargetCodeGenInfo().setTargetAttributes(D, GO, *this, ForDefinition);
  954. }
  955. void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
  956. llvm::Function *F,
  957. const CGFunctionInfo &FI) {
  958. SetLLVMFunctionAttributes(D, FI, F);
  959. SetLLVMFunctionAttributesForDefinition(D, F);
  960. F->setLinkage(llvm::Function::InternalLinkage);
  961. setNonAliasAttributes(D, F);
  962. }
  963. static void setLinkageAndVisibilityForGV(llvm::GlobalValue *GV,
  964. const NamedDecl *ND) {
  965. // Set linkage and visibility in case we never see a definition.
  966. LinkageInfo LV = ND->getLinkageAndVisibility();
  967. if (!isExternallyVisible(LV.getLinkage())) {
  968. // Don't set internal linkage on declarations.
  969. } else {
  970. if (ND->hasAttr<DLLImportAttr>()) {
  971. GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
  972. GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
  973. } else if (ND->hasAttr<DLLExportAttr>()) {
  974. GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
  975. } else if (ND->hasAttr<WeakAttr>() || ND->isWeakImported()) {
  976. // "extern_weak" is overloaded in LLVM; we probably should have
  977. // separate linkage types for this.
  978. GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
  979. }
  980. // Set visibility on a declaration only if it's explicit.
  981. if (LV.isVisibilityExplicit())
  982. GV->setVisibility(CodeGenModule::GetLLVMVisibility(LV.getVisibility()));
  983. }
  984. }
  985. void CodeGenModule::CreateFunctionTypeMetadata(const FunctionDecl *FD,
  986. llvm::Function *F) {
  987. // Only if we are checking indirect calls.
  988. if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
  989. return;
  990. // Non-static class methods are handled via vtable pointer checks elsewhere.
  991. if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
  992. return;
  993. // Additionally, if building with cross-DSO support...
  994. if (CodeGenOpts.SanitizeCfiCrossDso) {
  995. // Skip available_externally functions. They won't be codegen'ed in the
  996. // current module anyway.
  997. if (getContext().GetGVALinkageForFunction(FD) == GVA_AvailableExternally)
  998. return;
  999. }
  1000. llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType());
  1001. F->addTypeMetadata(0, MD);
  1002. // Emit a hash-based bit set entry for cross-DSO calls.
  1003. if (CodeGenOpts.SanitizeCfiCrossDso)
  1004. if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
  1005. F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
  1006. }
  1007. void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
  1008. bool IsIncompleteFunction,
  1009. bool IsThunk,
  1010. ForDefinition_t IsForDefinition) {
  1011. if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
  1012. // If this is an intrinsic function, set the function's attributes
  1013. // to the intrinsic's attributes.
  1014. F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
  1015. return;
  1016. }
  1017. const auto *FD = cast<FunctionDecl>(GD.getDecl());
  1018. if (!IsIncompleteFunction) {
  1019. SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
  1020. // Setup target-specific attributes.
  1021. if (!IsForDefinition)
  1022. getTargetCodeGenInfo().setTargetAttributes(FD, F, *this,
  1023. NotForDefinition);
  1024. }
  1025. // Add the Returned attribute for "this", except for iOS 5 and earlier
  1026. // where substantial code, including the libstdc++ dylib, was compiled with
  1027. // GCC and does not actually return "this".
  1028. if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
  1029. !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) {
  1030. assert(!F->arg_empty() &&
  1031. F->arg_begin()->getType()
  1032. ->canLosslesslyBitCastTo(F->getReturnType()) &&
  1033. "unexpected this return");
  1034. F->addAttribute(1, llvm::Attribute::Returned);
  1035. }
  1036. // Only a few attributes are set on declarations; these may later be
  1037. // overridden by a definition.
  1038. setLinkageAndVisibilityForGV(F, FD);
  1039. if (FD->getAttr<PragmaClangTextSectionAttr>()) {
  1040. F->addFnAttr("implicit-section-name");
  1041. }
  1042. if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
  1043. F->setSection(SA->getName());
  1044. if (FD->isReplaceableGlobalAllocationFunction()) {
  1045. // A replaceable global allocation function does not act like a builtin by
  1046. // default, only if it is invoked by a new-expression or delete-expression.
  1047. F->addAttribute(llvm::AttributeList::FunctionIndex,
  1048. llvm::Attribute::NoBuiltin);
  1049. // A sane operator new returns a non-aliasing pointer.
  1050. // FIXME: Also add NonNull attribute to the return value
  1051. // for the non-nothrow forms?
  1052. auto Kind = FD->getDeclName().getCXXOverloadedOperator();
  1053. if (getCodeGenOpts().AssumeSaneOperatorNew &&
  1054. (Kind == OO_New || Kind == OO_Array_New))
  1055. F->addAttribute(llvm::AttributeList::ReturnIndex,
  1056. llvm::Attribute::NoAlias);
  1057. }
  1058. if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
  1059. F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  1060. else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
  1061. if (MD->isVirtual())
  1062. F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  1063. // Don't emit entries for function declarations in the cross-DSO mode. This
  1064. // is handled with better precision by the receiving DSO.
  1065. if (!CodeGenOpts.SanitizeCfiCrossDso)
  1066. CreateFunctionTypeMetadata(FD, F);
  1067. }
  1068. void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
  1069. assert(!GV->isDeclaration() &&
  1070. "Only globals with definition can force usage.");
  1071. LLVMUsed.emplace_back(GV);
  1072. }
  1073. void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
  1074. assert(!GV->isDeclaration() &&
  1075. "Only globals with definition can force usage.");
  1076. LLVMCompilerUsed.emplace_back(GV);
  1077. }
  1078. static void emitUsed(CodeGenModule &CGM, StringRef Name,
  1079. std::vector<llvm::WeakTrackingVH> &List) {
  1080. // Don't create llvm.used if there is no need.
  1081. if (List.empty())
  1082. return;
  1083. // Convert List to what ConstantArray needs.
  1084. SmallVector<llvm::Constant*, 8> UsedArray;
  1085. UsedArray.resize(List.size());
  1086. for (unsigned i = 0, e = List.size(); i != e; ++i) {
  1087. UsedArray[i] =
  1088. llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
  1089. cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
  1090. }
  1091. if (UsedArray.empty())
  1092. return;
  1093. llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
  1094. auto *GV = new llvm::GlobalVariable(
  1095. CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
  1096. llvm::ConstantArray::get(ATy, UsedArray), Name);
  1097. GV->setSection("llvm.metadata");
  1098. }
  1099. void CodeGenModule::emitLLVMUsed() {
  1100. emitUsed(*this, "llvm.used", LLVMUsed);
  1101. emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
  1102. }
  1103. void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
  1104. auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
  1105. LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
  1106. }
  1107. void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
  1108. llvm::SmallString<32> Opt;
  1109. getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
  1110. auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
  1111. LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
  1112. }
  1113. void CodeGenModule::AddDependentLib(StringRef Lib) {
  1114. llvm::SmallString<24> Opt;
  1115. getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
  1116. auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
  1117. LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
  1118. }
  1119. /// \brief Add link options implied by the given module, including modules
  1120. /// it depends on, using a postorder walk.
  1121. static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
  1122. SmallVectorImpl<llvm::MDNode *> &Metadata,
  1123. llvm::SmallPtrSet<Module *, 16> &Visited) {
  1124. // Import this module's parent.
  1125. if (Mod->Parent && Visited.insert(Mod->Parent).second) {
  1126. addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
  1127. }
  1128. // Import this module's dependencies.
  1129. for (unsigned I = Mod->Imports.size(); I > 0; --I) {
  1130. if (Visited.insert(Mod->Imports[I - 1]).second)
  1131. addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
  1132. }
  1133. // Add linker options to link against the libraries/frameworks
  1134. // described by this module.
  1135. llvm::LLVMContext &Context = CGM.getLLVMContext();
  1136. for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
  1137. // Link against a framework. Frameworks are currently Darwin only, so we
  1138. // don't to ask TargetCodeGenInfo for the spelling of the linker option.
  1139. if (Mod->LinkLibraries[I-1].IsFramework) {
  1140. llvm::Metadata *Args[2] = {
  1141. llvm::MDString::get(Context, "-framework"),
  1142. llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)};
  1143. Metadata.push_back(llvm::MDNode::get(Context, Args));
  1144. continue;
  1145. }
  1146. // Link against a library.
  1147. llvm::SmallString<24> Opt;
  1148. CGM.getTargetCodeGenInfo().getDependentLibraryOption(
  1149. Mod->LinkLibraries[I-1].Library, Opt);
  1150. auto *OptString = llvm::MDString::get(Context, Opt);
  1151. Metadata.push_back(llvm::MDNode::get(Context, OptString));
  1152. }
  1153. }
  1154. void CodeGenModule::EmitModuleLinkOptions() {
  1155. // Collect the set of all of the modules we want to visit to emit link
  1156. // options, which is essentially the imported modules and all of their
  1157. // non-explicit child modules.
  1158. llvm::SetVector<clang::Module *> LinkModules;
  1159. llvm::SmallPtrSet<clang::Module *, 16> Visited;
  1160. SmallVector<clang::Module *, 16> Stack;
  1161. // Seed the stack with imported modules.
  1162. for (Module *M : ImportedModules) {
  1163. // Do not add any link flags when an implementation TU of a module imports
  1164. // a header of that same module.
  1165. if (M->getTopLevelModuleName() == getLangOpts().CurrentModule &&
  1166. !getLangOpts().isCompilingModule())
  1167. continue;
  1168. if (Visited.insert(M).second)
  1169. Stack.push_back(M);
  1170. }
  1171. // Find all of the modules to import, making a little effort to prune
  1172. // non-leaf modules.
  1173. while (!Stack.empty()) {
  1174. clang::Module *Mod = Stack.pop_back_val();
  1175. bool AnyChildren = false;
  1176. // Visit the submodules of this module.
  1177. for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
  1178. SubEnd = Mod->submodule_end();
  1179. Sub != SubEnd; ++Sub) {
  1180. // Skip explicit children; they need to be explicitly imported to be
  1181. // linked against.
  1182. if ((*Sub)->IsExplicit)
  1183. continue;
  1184. if (Visited.insert(*Sub).second) {
  1185. Stack.push_back(*Sub);
  1186. AnyChildren = true;
  1187. }
  1188. }
  1189. // We didn't find any children, so add this module to the list of
  1190. // modules to link against.
  1191. if (!AnyChildren) {
  1192. LinkModules.insert(Mod);
  1193. }
  1194. }
  1195. // Add link options for all of the imported modules in reverse topological
  1196. // order. We don't do anything to try to order import link flags with respect
  1197. // to linker options inserted by things like #pragma comment().
  1198. SmallVector<llvm::MDNode *, 16> MetadataArgs;
  1199. Visited.clear();
  1200. for (Module *M : LinkModules)
  1201. if (Visited.insert(M).second)
  1202. addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
  1203. std::reverse(MetadataArgs.begin(), MetadataArgs.end());
  1204. LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
  1205. // Add the linker options metadata flag.
  1206. auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options");
  1207. for (auto *MD : LinkerOptionsMetadata)
  1208. NMD->addOperand(MD);
  1209. }
  1210. void CodeGenModule::EmitDeferred() {
  1211. // Emit code for any potentially referenced deferred decls. Since a
  1212. // previously unused static decl may become used during the generation of code
  1213. // for a static function, iterate until no changes are made.
  1214. if (!DeferredVTables.empty()) {
  1215. EmitDeferredVTables();
  1216. // Emitting a vtable doesn't directly cause more vtables to
  1217. // become deferred, although it can cause functions to be
  1218. // emitted that then need those vtables.
  1219. assert(DeferredVTables.empty());
  1220. }
  1221. // Stop if we're out of both deferred vtables and deferred declarations.
  1222. if (DeferredDeclsToEmit.empty())
  1223. return;
  1224. // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
  1225. // work, it will not interfere with this.
  1226. std::vector<GlobalDecl> CurDeclsToEmit;
  1227. CurDeclsToEmit.swap(DeferredDeclsToEmit);
  1228. for (GlobalDecl &D : CurDeclsToEmit) {
  1229. // We should call GetAddrOfGlobal with IsForDefinition set to true in order
  1230. // to get GlobalValue with exactly the type we need, not something that
  1231. // might had been created for another decl with the same mangled name but
  1232. // different type.
  1233. llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
  1234. GetAddrOfGlobal(D, ForDefinition));
  1235. // In case of different address spaces, we may still get a cast, even with
  1236. // IsForDefinition equal to true. Query mangled names table to get
  1237. // GlobalValue.
  1238. if (!GV)
  1239. GV = GetGlobalValue(getMangledName(D));
  1240. // Make sure GetGlobalValue returned non-null.
  1241. assert(GV);
  1242. // Check to see if we've already emitted this. This is necessary
  1243. // for a couple of reasons: first, decls can end up in the
  1244. // deferred-decls queue multiple times, and second, decls can end
  1245. // up with definitions in unusual ways (e.g. by an extern inline
  1246. // function acquiring a strong function redefinition). Just
  1247. // ignore these cases.
  1248. if (!GV->isDeclaration())
  1249. continue;
  1250. // Otherwise, emit the definition and move on to the next one.
  1251. EmitGlobalDefinition(D, GV);
  1252. // If we found out that we need to emit more decls, do that recursively.
  1253. // This has the advantage that the decls are emitted in a DFS and related
  1254. // ones are close together, which is convenient for testing.
  1255. if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
  1256. EmitDeferred();
  1257. assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
  1258. }
  1259. }
  1260. }
  1261. void CodeGenModule::EmitVTablesOpportunistically() {
  1262. // Try to emit external vtables as available_externally if they have emitted
  1263. // all inlined virtual functions. It runs after EmitDeferred() and therefore
  1264. // is not allowed to create new references to things that need to be emitted
  1265. // lazily. Note that it also uses fact that we eagerly emitting RTTI.
  1266. assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
  1267. && "Only emit opportunistic vtables with optimizations");
  1268. for (const CXXRecordDecl *RD : OpportunisticVTables) {
  1269. assert(getVTables().isVTableExternal(RD) &&
  1270. "This queue should only contain external vtables");
  1271. if (getCXXABI().canSpeculativelyEmitVTable(RD))
  1272. VTables.GenerateClassData(RD);
  1273. }
  1274. OpportunisticVTables.clear();
  1275. }
  1276. void CodeGenModule::EmitGlobalAnnotations() {
  1277. if (Annotations.empty())
  1278. return;
  1279. // Create a new global variable for the ConstantStruct in the Module.
  1280. llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
  1281. Annotations[0]->getType(), Annotations.size()), Annotations);
  1282. auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
  1283. llvm::GlobalValue::AppendingLinkage,
  1284. Array, "llvm.global.annotations");
  1285. gv->setSection(AnnotationSection);
  1286. }
  1287. llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
  1288. llvm::Constant *&AStr = AnnotationStrings[Str];
  1289. if (AStr)
  1290. return AStr;
  1291. // Not found yet, create a new global.
  1292. llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
  1293. auto *gv =
  1294. new llvm::GlobalVariable(getModule(), s->getType(), true,
  1295. llvm::GlobalValue::PrivateLinkage, s, ".str");
  1296. gv->setSection(AnnotationSection);
  1297. gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  1298. AStr = gv;
  1299. return gv;
  1300. }
  1301. llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
  1302. SourceManager &SM = getContext().getSourceManager();
  1303. PresumedLoc PLoc = SM.getPresumedLoc(Loc);
  1304. if (PLoc.isValid())
  1305. return EmitAnnotationString(PLoc.getFilename());
  1306. return EmitAnnotationString(SM.getBufferName(Loc));
  1307. }
  1308. llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
  1309. SourceManager &SM = getContext().getSourceManager();
  1310. PresumedLoc PLoc = SM.getPresumedLoc(L);
  1311. unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
  1312. SM.getExpansionLineNumber(L);
  1313. return llvm::ConstantInt::get(Int32Ty, LineNo);
  1314. }
  1315. llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
  1316. const AnnotateAttr *AA,
  1317. SourceLocation L) {
  1318. // Get the globals for file name, annotation, and the line number.
  1319. llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
  1320. *UnitGV = EmitAnnotationUnit(L),
  1321. *LineNoCst = EmitAnnotationLineNo(L);
  1322. // Create the ConstantStruct for the global annotation.
  1323. llvm::Constant *Fields[4] = {
  1324. llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
  1325. llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
  1326. llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
  1327. LineNoCst
  1328. };
  1329. return llvm::ConstantStruct::getAnon(Fields);
  1330. }
  1331. void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
  1332. llvm::GlobalValue *GV) {
  1333. assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
  1334. // Get the struct elements for these annotations.
  1335. for (const auto *I : D->specific_attrs<AnnotateAttr>())
  1336. Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
  1337. }
  1338. bool CodeGenModule::isInSanitizerBlacklist(SanitizerMask Kind,
  1339. llvm::Function *Fn,
  1340. SourceLocation Loc) const {
  1341. const auto &SanitizerBL = getContext().getSanitizerBlacklist();
  1342. // Blacklist by function name.
  1343. if (SanitizerBL.isBlacklistedFunction(Kind, Fn->getName()))
  1344. return true;
  1345. // Blacklist by location.
  1346. if (Loc.isValid())
  1347. return SanitizerBL.isBlacklistedLocation(Kind, Loc);
  1348. // If location is unknown, this may be a compiler-generated function. Assume
  1349. // it's located in the main file.
  1350. auto &SM = Context.getSourceManager();
  1351. if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
  1352. return SanitizerBL.isBlacklistedFile(Kind, MainFile->getName());
  1353. }
  1354. return false;
  1355. }
  1356. bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV,
  1357. SourceLocation Loc, QualType Ty,
  1358. StringRef Category) const {
  1359. // For now globals can be blacklisted only in ASan and KASan.
  1360. const SanitizerMask EnabledAsanMask = LangOpts.Sanitize.Mask &
  1361. (SanitizerKind::Address | SanitizerKind::KernelAddress);
  1362. if (!EnabledAsanMask)
  1363. return false;
  1364. const auto &SanitizerBL = getContext().getSanitizerBlacklist();
  1365. if (SanitizerBL.isBlacklistedGlobal(EnabledAsanMask, GV->getName(), Category))
  1366. return true;
  1367. if (SanitizerBL.isBlacklistedLocation(EnabledAsanMask, Loc, Category))
  1368. return true;
  1369. // Check global type.
  1370. if (!Ty.isNull()) {
  1371. // Drill down the array types: if global variable of a fixed type is
  1372. // blacklisted, we also don't instrument arrays of them.
  1373. while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
  1374. Ty = AT->getElementType();
  1375. Ty = Ty.getCanonicalType().getUnqualifiedType();
  1376. // We allow to blacklist only record types (classes, structs etc.)
  1377. if (Ty->isRecordType()) {
  1378. std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
  1379. if (SanitizerBL.isBlacklistedType(EnabledAsanMask, TypeStr, Category))
  1380. return true;
  1381. }
  1382. }
  1383. return false;
  1384. }
  1385. bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
  1386. StringRef Category) const {
  1387. if (!LangOpts.XRayInstrument)
  1388. return false;
  1389. const auto &XRayFilter = getContext().getXRayFilter();
  1390. using ImbueAttr = XRayFunctionFilter::ImbueAttribute;
  1391. auto Attr = XRayFunctionFilter::ImbueAttribute::NONE;
  1392. if (Loc.isValid())
  1393. Attr = XRayFilter.shouldImbueLocation(Loc, Category);
  1394. if (Attr == ImbueAttr::NONE)
  1395. Attr = XRayFilter.shouldImbueFunction(Fn->getName());
  1396. switch (Attr) {
  1397. case ImbueAttr::NONE:
  1398. return false;
  1399. case ImbueAttr::ALWAYS:
  1400. Fn->addFnAttr("function-instrument", "xray-always");
  1401. break;
  1402. case ImbueAttr::ALWAYS_ARG1:
  1403. Fn->addFnAttr("function-instrument", "xray-always");
  1404. Fn->addFnAttr("xray-log-args", "1");
  1405. break;
  1406. case ImbueAttr::NEVER:
  1407. Fn->addFnAttr("function-instrument", "xray-never");
  1408. break;
  1409. }
  1410. return true;
  1411. }
  1412. bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
  1413. // Never defer when EmitAllDecls is specified.
  1414. if (LangOpts.EmitAllDecls)
  1415. return true;
  1416. return getContext().DeclMustBeEmitted(Global);
  1417. }
  1418. bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
  1419. if (const auto *FD = dyn_cast<FunctionDecl>(Global))
  1420. if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  1421. // Implicit template instantiations may change linkage if they are later
  1422. // explicitly instantiated, so they should not be emitted eagerly.
  1423. return false;
  1424. if (const auto *VD = dyn_cast<VarDecl>(Global))
  1425. if (Context.getInlineVariableDefinitionKind(VD) ==
  1426. ASTContext::InlineVariableDefinitionKind::WeakUnknown)
  1427. // A definition of an inline constexpr static data member may change
  1428. // linkage later if it's redeclared outside the class.
  1429. return false;
  1430. // If OpenMP is enabled and threadprivates must be generated like TLS, delay
  1431. // codegen for global variables, because they may be marked as threadprivate.
  1432. if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
  1433. getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global))
  1434. return false;
  1435. return true;
  1436. }
  1437. ConstantAddress CodeGenModule::GetAddrOfUuidDescriptor(
  1438. const CXXUuidofExpr* E) {
  1439. // Sema has verified that IIDSource has a __declspec(uuid()), and that its
  1440. // well-formed.
  1441. StringRef Uuid = E->getUuidStr();
  1442. std::string Name = "_GUID_" + Uuid.lower();
  1443. std::replace(Name.begin(), Name.end(), '-', '_');
  1444. // The UUID descriptor should be pointer aligned.
  1445. CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes);
  1446. // Look for an existing global.
  1447. if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
  1448. return ConstantAddress(GV, Alignment);
  1449. llvm::Constant *Init = EmitUuidofInitializer(Uuid);
  1450. assert(Init && "failed to initialize as constant");
  1451. auto *GV = new llvm::GlobalVariable(
  1452. getModule(), Init->getType(),
  1453. /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
  1454. if (supportsCOMDAT())
  1455. GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
  1456. return ConstantAddress(GV, Alignment);
  1457. }
  1458. ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
  1459. const AliasAttr *AA = VD->getAttr<AliasAttr>();
  1460. assert(AA && "No alias?");
  1461. CharUnits Alignment = getContext().getDeclAlign(VD);
  1462. llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
  1463. // See if there is already something with the target's name in the module.
  1464. llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
  1465. if (Entry) {
  1466. unsigned AS = getContext().getTargetAddressSpace(VD->getType());
  1467. auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
  1468. return ConstantAddress(Ptr, Alignment);
  1469. }
  1470. llvm::Constant *Aliasee;
  1471. if (isa<llvm::FunctionType>(DeclTy))
  1472. Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
  1473. GlobalDecl(cast<FunctionDecl>(VD)),
  1474. /*ForVTable=*/false);
  1475. else
  1476. Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
  1477. llvm::PointerType::getUnqual(DeclTy),
  1478. nullptr);
  1479. auto *F = cast<llvm::GlobalValue>(Aliasee);
  1480. F->setLinkage(llvm::Function::ExternalWeakLinkage);
  1481. WeakRefReferences.insert(F);
  1482. return ConstantAddress(Aliasee, Alignment);
  1483. }
  1484. void CodeGenModule::EmitGlobal(GlobalDecl GD) {
  1485. const auto *Global = cast<ValueDecl>(GD.getDecl());
  1486. // Weak references don't produce any output by themselves.
  1487. if (Global->hasAttr<WeakRefAttr>())
  1488. return;
  1489. // If this is an alias definition (which otherwise looks like a declaration)
  1490. // emit it now.
  1491. if (Global->hasAttr<AliasAttr>())
  1492. return EmitAliasDefinition(GD);
  1493. // IFunc like an alias whose value is resolved at runtime by calling resolver.
  1494. if (Global->hasAttr<IFuncAttr>())
  1495. return emitIFuncDefinition(GD);
  1496. // If this is CUDA, be selective about which declarations we emit.
  1497. if (LangOpts.CUDA) {
  1498. if (LangOpts.CUDAIsDevice) {
  1499. if (!Global->hasAttr<CUDADeviceAttr>() &&
  1500. !Global->hasAttr<CUDAGlobalAttr>() &&
  1501. !Global->hasAttr<CUDAConstantAttr>() &&
  1502. !Global->hasAttr<CUDASharedAttr>())
  1503. return;
  1504. } else {
  1505. // We need to emit host-side 'shadows' for all global
  1506. // device-side variables because the CUDA runtime needs their
  1507. // size and host-side address in order to provide access to
  1508. // their device-side incarnations.
  1509. // So device-only functions are the only things we skip.
  1510. if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() &&
  1511. Global->hasAttr<CUDADeviceAttr>())
  1512. return;
  1513. assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
  1514. "Expected Variable or Function");
  1515. }
  1516. }
  1517. if (LangOpts.OpenMP) {
  1518. // If this is OpenMP device, check if it is legal to emit this global
  1519. // normally.
  1520. if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
  1521. return;
  1522. if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
  1523. if (MustBeEmitted(Global))
  1524. EmitOMPDeclareReduction(DRD);
  1525. return;
  1526. }
  1527. }
  1528. // Ignore declarations, they will be emitted on their first use.
  1529. if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
  1530. // Forward declarations are emitted lazily on first use.
  1531. if (!FD->doesThisDeclarationHaveABody()) {
  1532. if (!FD->doesDeclarationForceExternallyVisibleDefinition())
  1533. return;
  1534. StringRef MangledName = getMangledName(GD);
  1535. // Compute the function info and LLVM type.
  1536. const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
  1537. llvm::Type *Ty = getTypes().GetFunctionType(FI);
  1538. GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
  1539. /*DontDefer=*/false);
  1540. return;
  1541. }
  1542. } else {
  1543. const auto *VD = cast<VarDecl>(Global);
  1544. assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
  1545. // We need to emit device-side global CUDA variables even if a
  1546. // variable does not have a definition -- we still need to define
  1547. // host-side shadow for it.
  1548. bool MustEmitForCuda = LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
  1549. !VD->hasDefinition() &&
  1550. (VD->hasAttr<CUDAConstantAttr>() ||
  1551. VD->hasAttr<CUDADeviceAttr>());
  1552. if (!MustEmitForCuda &&
  1553. VD->isThisDeclarationADefinition() != VarDecl::Definition &&
  1554. !Context.isMSStaticDataMemberInlineDefinition(VD)) {
  1555. // If this declaration may have caused an inline variable definition to
  1556. // change linkage, make sure that it's emitted.
  1557. if (Context.getInlineVariableDefinitionKind(VD) ==
  1558. ASTContext::InlineVariableDefinitionKind::Strong)
  1559. GetAddrOfGlobalVar(VD);
  1560. return;
  1561. }
  1562. }
  1563. // Defer code generation to first use when possible, e.g. if this is an inline
  1564. // function. If the global must always be emitted, do it eagerly if possible
  1565. // to benefit from cache locality.
  1566. if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
  1567. // Emit the definition if it can't be deferred.
  1568. EmitGlobalDefinition(GD);
  1569. return;
  1570. }
  1571. // If we're deferring emission of a C++ variable with an
  1572. // initializer, remember the order in which it appeared in the file.
  1573. if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
  1574. cast<VarDecl>(Global)->hasInit()) {
  1575. DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
  1576. CXXGlobalInits.push_back(nullptr);
  1577. }
  1578. StringRef MangledName = getMangledName(GD);
  1579. if (GetGlobalValue(MangledName) != nullptr) {
  1580. // The value has already been used and should therefore be emitted.
  1581. addDeferredDeclToEmit(GD);
  1582. } else if (MustBeEmitted(Global)) {
  1583. // The value must be emitted, but cannot be emitted eagerly.
  1584. assert(!MayBeEmittedEagerly(Global));
  1585. addDeferredDeclToEmit(GD);
  1586. } else {
  1587. // Otherwise, remember that we saw a deferred decl with this name. The
  1588. // first use of the mangled name will cause it to move into
  1589. // DeferredDeclsToEmit.
  1590. DeferredDecls[MangledName] = GD;
  1591. }
  1592. }
  1593. // Check if T is a class type with a destructor that's not dllimport.
  1594. static bool HasNonDllImportDtor(QualType T) {
  1595. if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>())
  1596. if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
  1597. if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
  1598. return true;
  1599. return false;
  1600. }
  1601. namespace {
  1602. struct FunctionIsDirectlyRecursive :
  1603. public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
  1604. const StringRef Name;
  1605. const Builtin::Context &BI;
  1606. bool Result;
  1607. FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
  1608. Name(N), BI(C), Result(false) {
  1609. }
  1610. typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
  1611. bool TraverseCallExpr(CallExpr *E) {
  1612. const FunctionDecl *FD = E->getDirectCallee();
  1613. if (!FD)
  1614. return true;
  1615. AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
  1616. if (Attr && Name == Attr->getLabel()) {
  1617. Result = true;
  1618. return false;
  1619. }
  1620. unsigned BuiltinID = FD->getBuiltinID();
  1621. if (!BuiltinID || !BI.isLibFunction(BuiltinID))
  1622. return true;
  1623. StringRef BuiltinName = BI.getName(BuiltinID);
  1624. if (BuiltinName.startswith("__builtin_") &&
  1625. Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
  1626. Result = true;
  1627. return false;
  1628. }
  1629. return true;
  1630. }
  1631. };
  1632. // Make sure we're not referencing non-imported vars or functions.
  1633. struct DLLImportFunctionVisitor
  1634. : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
  1635. bool SafeToInline = true;
  1636. bool shouldVisitImplicitCode() const { return true; }
  1637. bool VisitVarDecl(VarDecl *VD) {
  1638. if (VD->getTLSKind()) {
  1639. // A thread-local variable cannot be imported.
  1640. SafeToInline = false;
  1641. return SafeToInline;
  1642. }
  1643. // A variable definition might imply a destructor call.
  1644. if (VD->isThisDeclarationADefinition())
  1645. SafeToInline = !HasNonDllImportDtor(VD->getType());
  1646. return SafeToInline;
  1647. }
  1648. bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
  1649. if (const auto *D = E->getTemporary()->getDestructor())
  1650. SafeToInline = D->hasAttr<DLLImportAttr>();
  1651. return SafeToInline;
  1652. }
  1653. bool VisitDeclRefExpr(DeclRefExpr *E) {
  1654. ValueDecl *VD = E->getDecl();
  1655. if (isa<FunctionDecl>(VD))
  1656. SafeToInline = VD->hasAttr<DLLImportAttr>();
  1657. else if (VarDecl *V = dyn_cast<VarDecl>(VD))
  1658. SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
  1659. return SafeToInline;
  1660. }
  1661. bool VisitCXXConstructExpr(CXXConstructExpr *E) {
  1662. SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
  1663. return SafeToInline;
  1664. }
  1665. bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
  1666. CXXMethodDecl *M = E->getMethodDecl();
  1667. if (!M) {
  1668. // Call through a pointer to member function. This is safe to inline.
  1669. SafeToInline = true;
  1670. } else {
  1671. SafeToInline = M->hasAttr<DLLImportAttr>();
  1672. }
  1673. return SafeToInline;
  1674. }
  1675. bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
  1676. SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
  1677. return SafeToInline;
  1678. }
  1679. bool VisitCXXNewExpr(CXXNewExpr *E) {
  1680. SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
  1681. return SafeToInline;
  1682. }
  1683. };
  1684. }
  1685. // isTriviallyRecursive - Check if this function calls another
  1686. // decl that, because of the asm attribute or the other decl being a builtin,
  1687. // ends up pointing to itself.
  1688. bool
  1689. CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
  1690. StringRef Name;
  1691. if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
  1692. // asm labels are a special kind of mangling we have to support.
  1693. AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
  1694. if (!Attr)
  1695. return false;
  1696. Name = Attr->getLabel();
  1697. } else {
  1698. Name = FD->getName();
  1699. }
  1700. FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
  1701. Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
  1702. return Walker.Result;
  1703. }
  1704. bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
  1705. if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
  1706. return true;
  1707. const auto *F = cast<FunctionDecl>(GD.getDecl());
  1708. if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
  1709. return false;
  1710. if (F->hasAttr<DLLImportAttr>()) {
  1711. // Check whether it would be safe to inline this dllimport function.
  1712. DLLImportFunctionVisitor Visitor;
  1713. Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
  1714. if (!Visitor.SafeToInline)
  1715. return false;
  1716. if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
  1717. // Implicit destructor invocations aren't captured in the AST, so the
  1718. // check above can't see them. Check for them manually here.
  1719. for (const Decl *Member : Dtor->getParent()->decls())
  1720. if (isa<FieldDecl>(Member))
  1721. if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType()))
  1722. return false;
  1723. for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
  1724. if (HasNonDllImportDtor(B.getType()))
  1725. return false;
  1726. }
  1727. }
  1728. // PR9614. Avoid cases where the source code is lying to us. An available
  1729. // externally function should have an equivalent function somewhere else,
  1730. // but a function that calls itself is clearly not equivalent to the real
  1731. // implementation.
  1732. // This happens in glibc's btowc and in some configure checks.
  1733. return !isTriviallyRecursive(F);
  1734. }
  1735. bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
  1736. return CodeGenOpts.OptimizationLevel > 0;
  1737. }
  1738. void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
  1739. const auto *D = cast<ValueDecl>(GD.getDecl());
  1740. PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
  1741. Context.getSourceManager(),
  1742. "Generating code for declaration");
  1743. if (isa<FunctionDecl>(D)) {
  1744. // At -O0, don't generate IR for functions with available_externally
  1745. // linkage.
  1746. if (!shouldEmitFunction(GD))
  1747. return;
  1748. if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
  1749. // Make sure to emit the definition(s) before we emit the thunks.
  1750. // This is necessary for the generation of certain thunks.
  1751. if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method))
  1752. ABI->emitCXXStructor(CD, getFromCtorType(GD.getCtorType()));
  1753. else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method))
  1754. ABI->emitCXXStructor(DD, getFromDtorType(GD.getDtorType()));
  1755. else
  1756. EmitGlobalFunctionDefinition(GD, GV);
  1757. if (Method->isVirtual())
  1758. getVTables().EmitThunks(GD);
  1759. return;
  1760. }
  1761. return EmitGlobalFunctionDefinition(GD, GV);
  1762. }
  1763. if (const auto *VD = dyn_cast<VarDecl>(D))
  1764. return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
  1765. llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
  1766. }
  1767. static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
  1768. llvm::Function *NewFn);
  1769. /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
  1770. /// module, create and return an llvm Function with the specified type. If there
  1771. /// is something in the module with the specified name, return it potentially
  1772. /// bitcasted to the right type.
  1773. ///
  1774. /// If D is non-null, it specifies a decl that correspond to this. This is used
  1775. /// to set the attributes on the function when it is first created.
  1776. llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
  1777. StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable,
  1778. bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs,
  1779. ForDefinition_t IsForDefinition) {
  1780. const Decl *D = GD.getDecl();
  1781. // Lookup the entry, lazily creating it if necessary.
  1782. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  1783. if (Entry) {
  1784. if (WeakRefReferences.erase(Entry)) {
  1785. const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
  1786. if (FD && !FD->hasAttr<WeakAttr>())
  1787. Entry->setLinkage(llvm::Function::ExternalLinkage);
  1788. }
  1789. // Handle dropped DLL attributes.
  1790. if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
  1791. Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
  1792. // If there are two attempts to define the same mangled name, issue an
  1793. // error.
  1794. if (IsForDefinition && !Entry->isDeclaration()) {
  1795. GlobalDecl OtherGD;
  1796. // Check that GD is not yet in DiagnosedConflictingDefinitions is required
  1797. // to make sure that we issue an error only once.
  1798. if (lookupRepresentativeDecl(MangledName, OtherGD) &&
  1799. (GD.getCanonicalDecl().getDecl() !=
  1800. OtherGD.getCanonicalDecl().getDecl()) &&
  1801. DiagnosedConflictingDefinitions.insert(GD).second) {
  1802. getDiags().Report(D->getLocation(),
  1803. diag::err_duplicate_mangled_name);
  1804. getDiags().Report(OtherGD.getDecl()->getLocation(),
  1805. diag::note_previous_definition);
  1806. }
  1807. }
  1808. if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
  1809. (Entry->getType()->getElementType() == Ty)) {
  1810. return Entry;
  1811. }
  1812. // Make sure the result is of the correct type.
  1813. // (If function is requested for a definition, we always need to create a new
  1814. // function, not just return a bitcast.)
  1815. if (!IsForDefinition)
  1816. return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
  1817. }
  1818. // This function doesn't have a complete type (for example, the return
  1819. // type is an incomplete struct). Use a fake type instead, and make
  1820. // sure not to try to set attributes.
  1821. bool IsIncompleteFunction = false;
  1822. llvm::FunctionType *FTy;
  1823. if (isa<llvm::FunctionType>(Ty)) {
  1824. FTy = cast<llvm::FunctionType>(Ty);
  1825. } else {
  1826. FTy = llvm::FunctionType::get(VoidTy, false);
  1827. IsIncompleteFunction = true;
  1828. }
  1829. llvm::Function *F =
  1830. llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
  1831. Entry ? StringRef() : MangledName, &getModule());
  1832. // If we already created a function with the same mangled name (but different
  1833. // type) before, take its name and add it to the list of functions to be
  1834. // replaced with F at the end of CodeGen.
  1835. //
  1836. // This happens if there is a prototype for a function (e.g. "int f()") and
  1837. // then a definition of a different type (e.g. "int f(int x)").
  1838. if (Entry) {
  1839. F->takeName(Entry);
  1840. // This might be an implementation of a function without a prototype, in
  1841. // which case, try to do special replacement of calls which match the new
  1842. // prototype. The really key thing here is that we also potentially drop
  1843. // arguments from the call site so as to make a direct call, which makes the
  1844. // inliner happier and suppresses a number of optimizer warnings (!) about
  1845. // dropping arguments.
  1846. if (!Entry->use_empty()) {
  1847. ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
  1848. Entry->removeDeadConstantUsers();
  1849. }
  1850. llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
  1851. F, Entry->getType()->getElementType()->getPointerTo());
  1852. addGlobalValReplacement(Entry, BC);
  1853. }
  1854. assert(F->getName() == MangledName && "name was uniqued!");
  1855. if (D)
  1856. SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk,
  1857. IsForDefinition);
  1858. if (ExtraAttrs.hasAttributes(llvm::AttributeList::FunctionIndex)) {
  1859. llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex);
  1860. F->addAttributes(llvm::AttributeList::FunctionIndex, B);
  1861. }
  1862. if (!DontDefer) {
  1863. // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
  1864. // each other bottoming out with the base dtor. Therefore we emit non-base
  1865. // dtors on usage, even if there is no dtor definition in the TU.
  1866. if (D && isa<CXXDestructorDecl>(D) &&
  1867. getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
  1868. GD.getDtorType()))
  1869. addDeferredDeclToEmit(GD);
  1870. // This is the first use or definition of a mangled name. If there is a
  1871. // deferred decl with this name, remember that we need to emit it at the end
  1872. // of the file.
  1873. auto DDI = DeferredDecls.find(MangledName);
  1874. if (DDI != DeferredDecls.end()) {
  1875. // Move the potentially referenced deferred decl to the
  1876. // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
  1877. // don't need it anymore).
  1878. addDeferredDeclToEmit(DDI->second);
  1879. DeferredDecls.erase(DDI);
  1880. // Otherwise, there are cases we have to worry about where we're
  1881. // using a declaration for which we must emit a definition but where
  1882. // we might not find a top-level definition:
  1883. // - member functions defined inline in their classes
  1884. // - friend functions defined inline in some class
  1885. // - special member functions with implicit definitions
  1886. // If we ever change our AST traversal to walk into class methods,
  1887. // this will be unnecessary.
  1888. //
  1889. // We also don't emit a definition for a function if it's going to be an
  1890. // entry in a vtable, unless it's already marked as used.
  1891. } else if (getLangOpts().CPlusPlus && D) {
  1892. // Look for a declaration that's lexically in a record.
  1893. for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
  1894. FD = FD->getPreviousDecl()) {
  1895. if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
  1896. if (FD->doesThisDeclarationHaveABody()) {
  1897. addDeferredDeclToEmit(GD.getWithDecl(FD));
  1898. break;
  1899. }
  1900. }
  1901. }
  1902. }
  1903. }
  1904. // Make sure the result is of the requested type.
  1905. if (!IsIncompleteFunction) {
  1906. assert(F->getType()->getElementType() == Ty);
  1907. return F;
  1908. }
  1909. llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
  1910. return llvm::ConstantExpr::getBitCast(F, PTy);
  1911. }
  1912. /// GetAddrOfFunction - Return the address of the given function. If Ty is
  1913. /// non-null, then this function will use the specified type if it has to
  1914. /// create it (this occurs when we see a definition of the function).
  1915. llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
  1916. llvm::Type *Ty,
  1917. bool ForVTable,
  1918. bool DontDefer,
  1919. ForDefinition_t IsForDefinition) {
  1920. // If there was no specific requested type, just convert it now.
  1921. if (!Ty) {
  1922. const auto *FD = cast<FunctionDecl>(GD.getDecl());
  1923. auto CanonTy = Context.getCanonicalType(FD->getType());
  1924. Ty = getTypes().ConvertFunctionType(CanonTy, FD);
  1925. }
  1926. StringRef MangledName = getMangledName(GD);
  1927. return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
  1928. /*IsThunk=*/false, llvm::AttributeList(),
  1929. IsForDefinition);
  1930. }
  1931. static const FunctionDecl *
  1932. GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
  1933. TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
  1934. DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
  1935. IdentifierInfo &CII = C.Idents.get(Name);
  1936. for (const auto &Result : DC->lookup(&CII))
  1937. if (const auto FD = dyn_cast<FunctionDecl>(Result))
  1938. return FD;
  1939. if (!C.getLangOpts().CPlusPlus)
  1940. return nullptr;
  1941. // Demangle the premangled name from getTerminateFn()
  1942. IdentifierInfo &CXXII =
  1943. (Name == "_ZSt9terminatev" || Name == "\01?terminate@@YAXXZ")
  1944. ? C.Idents.get("terminate")
  1945. : C.Idents.get(Name);
  1946. for (const auto &N : {"__cxxabiv1", "std"}) {
  1947. IdentifierInfo &NS = C.Idents.get(N);
  1948. for (const auto &Result : DC->lookup(&NS)) {
  1949. NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
  1950. if (auto LSD = dyn_cast<LinkageSpecDecl>(Result))
  1951. for (const auto &Result : LSD->lookup(&NS))
  1952. if ((ND = dyn_cast<NamespaceDecl>(Result)))
  1953. break;
  1954. if (ND)
  1955. for (const auto &Result : ND->lookup(&CXXII))
  1956. if (const auto *FD = dyn_cast<FunctionDecl>(Result))
  1957. return FD;
  1958. }
  1959. }
  1960. return nullptr;
  1961. }
  1962. /// CreateRuntimeFunction - Create a new runtime function with the specified
  1963. /// type and name.
  1964. llvm::Constant *
  1965. CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
  1966. llvm::AttributeList ExtraAttrs,
  1967. bool Local) {
  1968. llvm::Constant *C =
  1969. GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
  1970. /*DontDefer=*/false, /*IsThunk=*/false,
  1971. ExtraAttrs);
  1972. if (auto *F = dyn_cast<llvm::Function>(C)) {
  1973. if (F->empty()) {
  1974. F->setCallingConv(getRuntimeCC());
  1975. if (!Local && getTriple().isOSBinFormatCOFF() &&
  1976. !getCodeGenOpts().LTOVisibilityPublicStd) {
  1977. const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
  1978. if (!FD || FD->hasAttr<DLLImportAttr>()) {
  1979. F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
  1980. F->setLinkage(llvm::GlobalValue::ExternalLinkage);
  1981. }
  1982. }
  1983. }
  1984. }
  1985. return C;
  1986. }
  1987. /// CreateBuiltinFunction - Create a new builtin function with the specified
  1988. /// type and name.
  1989. llvm::Constant *
  1990. CodeGenModule::CreateBuiltinFunction(llvm::FunctionType *FTy, StringRef Name,
  1991. llvm::AttributeList ExtraAttrs) {
  1992. llvm::Constant *C =
  1993. GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
  1994. /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs);
  1995. if (auto *F = dyn_cast<llvm::Function>(C))
  1996. if (F->empty())
  1997. F->setCallingConv(getBuiltinCC());
  1998. return C;
  1999. }
  2000. /// isTypeConstant - Determine whether an object of this type can be emitted
  2001. /// as a constant.
  2002. ///
  2003. /// If ExcludeCtor is true, the duration when the object's constructor runs
  2004. /// will not be considered. The caller will need to verify that the object is
  2005. /// not written to during its construction.
  2006. bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
  2007. if (!Ty.isConstant(Context) && !Ty->isReferenceType())
  2008. return false;
  2009. if (Context.getLangOpts().CPlusPlus) {
  2010. if (const CXXRecordDecl *Record
  2011. = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
  2012. return ExcludeCtor && !Record->hasMutableFields() &&
  2013. Record->hasTrivialDestructor();
  2014. }
  2015. return true;
  2016. }
  2017. /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
  2018. /// create and return an llvm GlobalVariable with the specified type. If there
  2019. /// is something in the module with the specified name, return it potentially
  2020. /// bitcasted to the right type.
  2021. ///
  2022. /// If D is non-null, it specifies a decl that correspond to this. This is used
  2023. /// to set the attributes on the global when it is first created.
  2024. ///
  2025. /// If IsForDefinition is true, it is guranteed that an actual global with
  2026. /// type Ty will be returned, not conversion of a variable with the same
  2027. /// mangled name but some other type.
  2028. llvm::Constant *
  2029. CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
  2030. llvm::PointerType *Ty,
  2031. const VarDecl *D,
  2032. ForDefinition_t IsForDefinition) {
  2033. // Lookup the entry, lazily creating it if necessary.
  2034. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  2035. if (Entry) {
  2036. if (WeakRefReferences.erase(Entry)) {
  2037. if (D && !D->hasAttr<WeakAttr>())
  2038. Entry->setLinkage(llvm::Function::ExternalLinkage);
  2039. }
  2040. // Handle dropped DLL attributes.
  2041. if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
  2042. Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
  2043. if (Entry->getType() == Ty)
  2044. return Entry;
  2045. // If there are two attempts to define the same mangled name, issue an
  2046. // error.
  2047. if (IsForDefinition && !Entry->isDeclaration()) {
  2048. GlobalDecl OtherGD;
  2049. const VarDecl *OtherD;
  2050. // Check that D is not yet in DiagnosedConflictingDefinitions is required
  2051. // to make sure that we issue an error only once.
  2052. if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
  2053. (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
  2054. (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
  2055. OtherD->hasInit() &&
  2056. DiagnosedConflictingDefinitions.insert(D).second) {
  2057. getDiags().Report(D->getLocation(),
  2058. diag::err_duplicate_mangled_name);
  2059. getDiags().Report(OtherGD.getDecl()->getLocation(),
  2060. diag::note_previous_definition);
  2061. }
  2062. }
  2063. // Make sure the result is of the correct type.
  2064. if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
  2065. return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
  2066. // (If global is requested for a definition, we always need to create a new
  2067. // global, not just return a bitcast.)
  2068. if (!IsForDefinition)
  2069. return llvm::ConstantExpr::getBitCast(Entry, Ty);
  2070. }
  2071. auto AddrSpace = GetGlobalVarAddressSpace(D);
  2072. auto TargetAddrSpace = getContext().getTargetAddressSpace(AddrSpace);
  2073. auto *GV = new llvm::GlobalVariable(
  2074. getModule(), Ty->getElementType(), false,
  2075. llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
  2076. llvm::GlobalVariable::NotThreadLocal, TargetAddrSpace);
  2077. // If we already created a global with the same mangled name (but different
  2078. // type) before, take its name and remove it from its parent.
  2079. if (Entry) {
  2080. GV->takeName(Entry);
  2081. if (!Entry->use_empty()) {
  2082. llvm::Constant *NewPtrForOldDecl =
  2083. llvm::ConstantExpr::getBitCast(GV, Entry->getType());
  2084. Entry->replaceAllUsesWith(NewPtrForOldDecl);
  2085. }
  2086. Entry->eraseFromParent();
  2087. }
  2088. // This is the first use or definition of a mangled name. If there is a
  2089. // deferred decl with this name, remember that we need to emit it at the end
  2090. // of the file.
  2091. auto DDI = DeferredDecls.find(MangledName);
  2092. if (DDI != DeferredDecls.end()) {
  2093. // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
  2094. // list, and remove it from DeferredDecls (since we don't need it anymore).
  2095. addDeferredDeclToEmit(DDI->second);
  2096. DeferredDecls.erase(DDI);
  2097. }
  2098. // Handle things which are present even on external declarations.
  2099. if (D) {
  2100. // FIXME: This code is overly simple and should be merged with other global
  2101. // handling.
  2102. GV->setConstant(isTypeConstant(D->getType(), false));
  2103. GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
  2104. setLinkageAndVisibilityForGV(GV, D);
  2105. if (D->getTLSKind()) {
  2106. if (D->getTLSKind() == VarDecl::TLS_Dynamic)
  2107. CXXThreadLocals.push_back(D);
  2108. setTLSMode(GV, *D);
  2109. }
  2110. // If required by the ABI, treat declarations of static data members with
  2111. // inline initializers as definitions.
  2112. if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
  2113. EmitGlobalVarDefinition(D);
  2114. }
  2115. // Emit section information for extern variables.
  2116. if (D->hasExternalStorage()) {
  2117. if (const SectionAttr *SA = D->getAttr<SectionAttr>())
  2118. GV->setSection(SA->getName());
  2119. }
  2120. // Handle XCore specific ABI requirements.
  2121. if (getTriple().getArch() == llvm::Triple::xcore &&
  2122. D->getLanguageLinkage() == CLanguageLinkage &&
  2123. D->getType().isConstant(Context) &&
  2124. isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
  2125. GV->setSection(".cp.rodata");
  2126. // Check if we a have a const declaration with an initializer, we may be
  2127. // able to emit it as available_externally to expose it's value to the
  2128. // optimizer.
  2129. if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
  2130. D->getType().isConstQualified() && !GV->hasInitializer() &&
  2131. !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) {
  2132. const auto *Record =
  2133. Context.getBaseElementType(D->getType())->getAsCXXRecordDecl();
  2134. bool HasMutableFields = Record && Record->hasMutableFields();
  2135. if (!HasMutableFields) {
  2136. const VarDecl *InitDecl;
  2137. const Expr *InitExpr = D->getAnyInitializer(InitDecl);
  2138. if (InitExpr) {
  2139. ConstantEmitter emitter(*this);
  2140. llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl);
  2141. if (Init) {
  2142. auto *InitType = Init->getType();
  2143. if (GV->getType()->getElementType() != InitType) {
  2144. // The type of the initializer does not match the definition.
  2145. // This happens when an initializer has a different type from
  2146. // the type of the global (because of padding at the end of a
  2147. // structure for instance).
  2148. GV->setName(StringRef());
  2149. // Make a new global with the correct type, this is now guaranteed
  2150. // to work.
  2151. auto *NewGV = cast<llvm::GlobalVariable>(
  2152. GetAddrOfGlobalVar(D, InitType, IsForDefinition));
  2153. // Erase the old global, since it is no longer used.
  2154. cast<llvm::GlobalValue>(GV)->eraseFromParent();
  2155. GV = NewGV;
  2156. } else {
  2157. GV->setInitializer(Init);
  2158. GV->setConstant(true);
  2159. GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
  2160. }
  2161. emitter.finalize(GV);
  2162. }
  2163. }
  2164. }
  2165. }
  2166. }
  2167. auto ExpectedAS =
  2168. D ? D->getType().getAddressSpace()
  2169. : static_cast<unsigned>(LangOpts.OpenCL ? LangAS::opencl_global
  2170. : LangAS::Default);
  2171. assert(getContext().getTargetAddressSpace(ExpectedAS) ==
  2172. Ty->getPointerAddressSpace());
  2173. if (AddrSpace != ExpectedAS)
  2174. return getTargetCodeGenInfo().performAddrSpaceCast(*this, GV, AddrSpace,
  2175. ExpectedAS, Ty);
  2176. return GV;
  2177. }
  2178. llvm::Constant *
  2179. CodeGenModule::GetAddrOfGlobal(GlobalDecl GD,
  2180. ForDefinition_t IsForDefinition) {
  2181. const Decl *D = GD.getDecl();
  2182. if (isa<CXXConstructorDecl>(D))
  2183. return getAddrOfCXXStructor(cast<CXXConstructorDecl>(D),
  2184. getFromCtorType(GD.getCtorType()),
  2185. /*FnInfo=*/nullptr, /*FnType=*/nullptr,
  2186. /*DontDefer=*/false, IsForDefinition);
  2187. else if (isa<CXXDestructorDecl>(D))
  2188. return getAddrOfCXXStructor(cast<CXXDestructorDecl>(D),
  2189. getFromDtorType(GD.getDtorType()),
  2190. /*FnInfo=*/nullptr, /*FnType=*/nullptr,
  2191. /*DontDefer=*/false, IsForDefinition);
  2192. else if (isa<CXXMethodDecl>(D)) {
  2193. auto FInfo = &getTypes().arrangeCXXMethodDeclaration(
  2194. cast<CXXMethodDecl>(D));
  2195. auto Ty = getTypes().GetFunctionType(*FInfo);
  2196. return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
  2197. IsForDefinition);
  2198. } else if (isa<FunctionDecl>(D)) {
  2199. const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
  2200. llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
  2201. return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
  2202. IsForDefinition);
  2203. } else
  2204. return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr,
  2205. IsForDefinition);
  2206. }
  2207. llvm::GlobalVariable *
  2208. CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
  2209. llvm::Type *Ty,
  2210. llvm::GlobalValue::LinkageTypes Linkage) {
  2211. llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
  2212. llvm::GlobalVariable *OldGV = nullptr;
  2213. if (GV) {
  2214. // Check if the variable has the right type.
  2215. if (GV->getType()->getElementType() == Ty)
  2216. return GV;
  2217. // Because C++ name mangling, the only way we can end up with an already
  2218. // existing global with the same name is if it has been declared extern "C".
  2219. assert(GV->isDeclaration() && "Declaration has wrong type!");
  2220. OldGV = GV;
  2221. }
  2222. // Create a new variable.
  2223. GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
  2224. Linkage, nullptr, Name);
  2225. if (OldGV) {
  2226. // Replace occurrences of the old variable if needed.
  2227. GV->takeName(OldGV);
  2228. if (!OldGV->use_empty()) {
  2229. llvm::Constant *NewPtrForOldDecl =
  2230. llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
  2231. OldGV->replaceAllUsesWith(NewPtrForOldDecl);
  2232. }
  2233. OldGV->eraseFromParent();
  2234. }
  2235. if (supportsCOMDAT() && GV->isWeakForLinker() &&
  2236. !GV->hasAvailableExternallyLinkage())
  2237. GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
  2238. return GV;
  2239. }
  2240. /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
  2241. /// given global variable. If Ty is non-null and if the global doesn't exist,
  2242. /// then it will be created with the specified type instead of whatever the
  2243. /// normal requested type would be. If IsForDefinition is true, it is guranteed
  2244. /// that an actual global with type Ty will be returned, not conversion of a
  2245. /// variable with the same mangled name but some other type.
  2246. llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
  2247. llvm::Type *Ty,
  2248. ForDefinition_t IsForDefinition) {
  2249. assert(D->hasGlobalStorage() && "Not a global variable");
  2250. QualType ASTTy = D->getType();
  2251. if (!Ty)
  2252. Ty = getTypes().ConvertTypeForMem(ASTTy);
  2253. llvm::PointerType *PTy =
  2254. llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
  2255. StringRef MangledName = getMangledName(D);
  2256. return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition);
  2257. }
  2258. /// CreateRuntimeVariable - Create a new runtime global variable with the
  2259. /// specified type and name.
  2260. llvm::Constant *
  2261. CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
  2262. StringRef Name) {
  2263. return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr);
  2264. }
  2265. void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
  2266. assert(!D->getInit() && "Cannot emit definite definitions here!");
  2267. StringRef MangledName = getMangledName(D);
  2268. llvm::GlobalValue *GV = GetGlobalValue(MangledName);
  2269. // We already have a definition, not declaration, with the same mangled name.
  2270. // Emitting of declaration is not required (and actually overwrites emitted
  2271. // definition).
  2272. if (GV && !GV->isDeclaration())
  2273. return;
  2274. // If we have not seen a reference to this variable yet, place it into the
  2275. // deferred declarations table to be emitted if needed later.
  2276. if (!MustBeEmitted(D) && !GV) {
  2277. DeferredDecls[MangledName] = D;
  2278. return;
  2279. }
  2280. // The tentative definition is the only definition.
  2281. EmitGlobalVarDefinition(D);
  2282. }
  2283. CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
  2284. return Context.toCharUnitsFromBits(
  2285. getDataLayout().getTypeStoreSizeInBits(Ty));
  2286. }
  2287. unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) {
  2288. unsigned AddrSpace;
  2289. if (LangOpts.OpenCL) {
  2290. AddrSpace = D ? D->getType().getAddressSpace()
  2291. : static_cast<unsigned>(LangAS::opencl_global);
  2292. assert(AddrSpace == LangAS::opencl_global ||
  2293. AddrSpace == LangAS::opencl_constant ||
  2294. AddrSpace == LangAS::opencl_local ||
  2295. AddrSpace >= LangAS::FirstTargetAddressSpace);
  2296. return AddrSpace;
  2297. }
  2298. if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
  2299. if (D && D->hasAttr<CUDAConstantAttr>())
  2300. return LangAS::cuda_constant;
  2301. else if (D && D->hasAttr<CUDASharedAttr>())
  2302. return LangAS::cuda_shared;
  2303. else
  2304. return LangAS::cuda_device;
  2305. }
  2306. return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D);
  2307. }
  2308. template<typename SomeDecl>
  2309. void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
  2310. llvm::GlobalValue *GV) {
  2311. if (!getLangOpts().CPlusPlus)
  2312. return;
  2313. // Must have 'used' attribute, or else inline assembly can't rely on
  2314. // the name existing.
  2315. if (!D->template hasAttr<UsedAttr>())
  2316. return;
  2317. // Must have internal linkage and an ordinary name.
  2318. if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
  2319. return;
  2320. // Must be in an extern "C" context. Entities declared directly within
  2321. // a record are not extern "C" even if the record is in such a context.
  2322. const SomeDecl *First = D->getFirstDecl();
  2323. if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
  2324. return;
  2325. // OK, this is an internal linkage entity inside an extern "C" linkage
  2326. // specification. Make a note of that so we can give it the "expected"
  2327. // mangled name if nothing else is using that name.
  2328. std::pair<StaticExternCMap::iterator, bool> R =
  2329. StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
  2330. // If we have multiple internal linkage entities with the same name
  2331. // in extern "C" regions, none of them gets that name.
  2332. if (!R.second)
  2333. R.first->second = nullptr;
  2334. }
  2335. static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
  2336. if (!CGM.supportsCOMDAT())
  2337. return false;
  2338. if (D.hasAttr<SelectAnyAttr>())
  2339. return true;
  2340. GVALinkage Linkage;
  2341. if (auto *VD = dyn_cast<VarDecl>(&D))
  2342. Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
  2343. else
  2344. Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
  2345. switch (Linkage) {
  2346. case GVA_Internal:
  2347. case GVA_AvailableExternally:
  2348. case GVA_StrongExternal:
  2349. return false;
  2350. case GVA_DiscardableODR:
  2351. case GVA_StrongODR:
  2352. return true;
  2353. }
  2354. llvm_unreachable("No such linkage");
  2355. }
  2356. void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
  2357. llvm::GlobalObject &GO) {
  2358. if (!shouldBeInCOMDAT(*this, D))
  2359. return;
  2360. GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
  2361. }
  2362. /// Pass IsTentative as true if you want to create a tentative definition.
  2363. void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
  2364. bool IsTentative) {
  2365. // OpenCL global variables of sampler type are translated to function calls,
  2366. // therefore no need to be translated.
  2367. QualType ASTTy = D->getType();
  2368. if (getLangOpts().OpenCL && ASTTy->isSamplerT())
  2369. return;
  2370. llvm::Constant *Init = nullptr;
  2371. CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
  2372. bool NeedsGlobalCtor = false;
  2373. bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
  2374. const VarDecl *InitDecl;
  2375. const Expr *InitExpr = D->getAnyInitializer(InitDecl);
  2376. Optional<ConstantEmitter> emitter;
  2377. // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
  2378. // as part of their declaration." Sema has already checked for
  2379. // error cases, so we just need to set Init to UndefValue.
  2380. if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
  2381. D->hasAttr<CUDASharedAttr>())
  2382. Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy));
  2383. else if (!InitExpr) {
  2384. // This is a tentative definition; tentative definitions are
  2385. // implicitly initialized with { 0 }.
  2386. //
  2387. // Note that tentative definitions are only emitted at the end of
  2388. // a translation unit, so they should never have incomplete
  2389. // type. In addition, EmitTentativeDefinition makes sure that we
  2390. // never attempt to emit a tentative definition if a real one
  2391. // exists. A use may still exists, however, so we still may need
  2392. // to do a RAUW.
  2393. assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
  2394. Init = EmitNullConstant(D->getType());
  2395. } else {
  2396. initializedGlobalDecl = GlobalDecl(D);
  2397. emitter.emplace(*this);
  2398. Init = emitter->tryEmitForInitializer(*InitDecl);
  2399. if (!Init) {
  2400. QualType T = InitExpr->getType();
  2401. if (D->getType()->isReferenceType())
  2402. T = D->getType();
  2403. if (getLangOpts().CPlusPlus) {
  2404. Init = EmitNullConstant(T);
  2405. NeedsGlobalCtor = true;
  2406. } else {
  2407. ErrorUnsupported(D, "static initializer");
  2408. Init = llvm::UndefValue::get(getTypes().ConvertType(T));
  2409. }
  2410. } else {
  2411. // We don't need an initializer, so remove the entry for the delayed
  2412. // initializer position (just in case this entry was delayed) if we
  2413. // also don't need to register a destructor.
  2414. if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
  2415. DelayedCXXInitPosition.erase(D);
  2416. }
  2417. }
  2418. llvm::Type* InitType = Init->getType();
  2419. llvm::Constant *Entry =
  2420. GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
  2421. // Strip off a bitcast if we got one back.
  2422. if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
  2423. assert(CE->getOpcode() == llvm::Instruction::BitCast ||
  2424. CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
  2425. // All zero index gep.
  2426. CE->getOpcode() == llvm::Instruction::GetElementPtr);
  2427. Entry = CE->getOperand(0);
  2428. }
  2429. // Entry is now either a Function or GlobalVariable.
  2430. auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
  2431. // We have a definition after a declaration with the wrong type.
  2432. // We must make a new GlobalVariable* and update everything that used OldGV
  2433. // (a declaration or tentative definition) with the new GlobalVariable*
  2434. // (which will be a definition).
  2435. //
  2436. // This happens if there is a prototype for a global (e.g.
  2437. // "extern int x[];") and then a definition of a different type (e.g.
  2438. // "int x[10];"). This also happens when an initializer has a different type
  2439. // from the type of the global (this happens with unions).
  2440. if (!GV || GV->getType()->getElementType() != InitType ||
  2441. GV->getType()->getAddressSpace() !=
  2442. getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) {
  2443. // Move the old entry aside so that we'll create a new one.
  2444. Entry->setName(StringRef());
  2445. // Make a new global with the correct type, this is now guaranteed to work.
  2446. GV = cast<llvm::GlobalVariable>(
  2447. GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)));
  2448. // Replace all uses of the old global with the new global
  2449. llvm::Constant *NewPtrForOldDecl =
  2450. llvm::ConstantExpr::getBitCast(GV, Entry->getType());
  2451. Entry->replaceAllUsesWith(NewPtrForOldDecl);
  2452. // Erase the old global, since it is no longer used.
  2453. cast<llvm::GlobalValue>(Entry)->eraseFromParent();
  2454. }
  2455. MaybeHandleStaticInExternC(D, GV);
  2456. if (D->hasAttr<AnnotateAttr>())
  2457. AddGlobalAnnotations(D, GV);
  2458. // Set the llvm linkage type as appropriate.
  2459. llvm::GlobalValue::LinkageTypes Linkage =
  2460. getLLVMLinkageVarDefinition(D, GV->isConstant());
  2461. // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
  2462. // the device. [...]"
  2463. // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
  2464. // __device__, declares a variable that: [...]
  2465. // Is accessible from all the threads within the grid and from the host
  2466. // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
  2467. // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
  2468. if (GV && LangOpts.CUDA) {
  2469. if (LangOpts.CUDAIsDevice) {
  2470. if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>())
  2471. GV->setExternallyInitialized(true);
  2472. } else {
  2473. // Host-side shadows of external declarations of device-side
  2474. // global variables become internal definitions. These have to
  2475. // be internal in order to prevent name conflicts with global
  2476. // host variables with the same name in a different TUs.
  2477. if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) {
  2478. Linkage = llvm::GlobalValue::InternalLinkage;
  2479. // Shadow variables and their properties must be registered
  2480. // with CUDA runtime.
  2481. unsigned Flags = 0;
  2482. if (!D->hasDefinition())
  2483. Flags |= CGCUDARuntime::ExternDeviceVar;
  2484. if (D->hasAttr<CUDAConstantAttr>())
  2485. Flags |= CGCUDARuntime::ConstantDeviceVar;
  2486. getCUDARuntime().registerDeviceVar(*GV, Flags);
  2487. } else if (D->hasAttr<CUDASharedAttr>())
  2488. // __shared__ variables are odd. Shadows do get created, but
  2489. // they are not registered with the CUDA runtime, so they
  2490. // can't really be used to access their device-side
  2491. // counterparts. It's not clear yet whether it's nvcc's bug or
  2492. // a feature, but we've got to do the same for compatibility.
  2493. Linkage = llvm::GlobalValue::InternalLinkage;
  2494. }
  2495. }
  2496. GV->setInitializer(Init);
  2497. if (emitter) emitter->finalize(GV);
  2498. // If it is safe to mark the global 'constant', do so now.
  2499. GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
  2500. isTypeConstant(D->getType(), true));
  2501. // If it is in a read-only section, mark it 'constant'.
  2502. if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
  2503. const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
  2504. if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
  2505. GV->setConstant(true);
  2506. }
  2507. GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
  2508. // On Darwin, if the normal linkage of a C++ thread_local variable is
  2509. // LinkOnce or Weak, we keep the normal linkage to prevent multiple
  2510. // copies within a linkage unit; otherwise, the backing variable has
  2511. // internal linkage and all accesses should just be calls to the
  2512. // Itanium-specified entry point, which has the normal linkage of the
  2513. // variable. This is to preserve the ability to change the implementation
  2514. // behind the scenes.
  2515. if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic &&
  2516. Context.getTargetInfo().getTriple().isOSDarwin() &&
  2517. !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) &&
  2518. !llvm::GlobalVariable::isWeakLinkage(Linkage))
  2519. Linkage = llvm::GlobalValue::InternalLinkage;
  2520. GV->setLinkage(Linkage);
  2521. if (D->hasAttr<DLLImportAttr>())
  2522. GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
  2523. else if (D->hasAttr<DLLExportAttr>())
  2524. GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
  2525. else
  2526. GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
  2527. if (Linkage == llvm::GlobalVariable::CommonLinkage) {
  2528. // common vars aren't constant even if declared const.
  2529. GV->setConstant(false);
  2530. // Tentative definition of global variables may be initialized with
  2531. // non-zero null pointers. In this case they should have weak linkage
  2532. // since common linkage must have zero initializer and must not have
  2533. // explicit section therefore cannot have non-zero initial value.
  2534. if (!GV->getInitializer()->isNullValue())
  2535. GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
  2536. }
  2537. setNonAliasAttributes(D, GV);
  2538. if (D->getTLSKind() && !GV->isThreadLocal()) {
  2539. if (D->getTLSKind() == VarDecl::TLS_Dynamic)
  2540. CXXThreadLocals.push_back(D);
  2541. setTLSMode(GV, *D);
  2542. }
  2543. maybeSetTrivialComdat(*D, *GV);
  2544. // Emit the initializer function if necessary.
  2545. if (NeedsGlobalCtor || NeedsGlobalDtor)
  2546. EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
  2547. SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
  2548. // Emit global variable debug information.
  2549. if (CGDebugInfo *DI = getModuleDebugInfo())
  2550. if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
  2551. DI->EmitGlobalVariable(GV, D);
  2552. }
  2553. static bool isVarDeclStrongDefinition(const ASTContext &Context,
  2554. CodeGenModule &CGM, const VarDecl *D,
  2555. bool NoCommon) {
  2556. // Don't give variables common linkage if -fno-common was specified unless it
  2557. // was overridden by a NoCommon attribute.
  2558. if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
  2559. return true;
  2560. // C11 6.9.2/2:
  2561. // A declaration of an identifier for an object that has file scope without
  2562. // an initializer, and without a storage-class specifier or with the
  2563. // storage-class specifier static, constitutes a tentative definition.
  2564. if (D->getInit() || D->hasExternalStorage())
  2565. return true;
  2566. // A variable cannot be both common and exist in a section.
  2567. if (D->hasAttr<SectionAttr>())
  2568. return true;
  2569. // A variable cannot be both common and exist in a section.
  2570. // We dont try to determine which is the right section in the front-end.
  2571. // If no specialized section name is applicable, it will resort to default.
  2572. if (D->hasAttr<PragmaClangBSSSectionAttr>() ||
  2573. D->hasAttr<PragmaClangDataSectionAttr>() ||
  2574. D->hasAttr<PragmaClangRodataSectionAttr>())
  2575. return true;
  2576. // Thread local vars aren't considered common linkage.
  2577. if (D->getTLSKind())
  2578. return true;
  2579. // Tentative definitions marked with WeakImportAttr are true definitions.
  2580. if (D->hasAttr<WeakImportAttr>())
  2581. return true;
  2582. // A variable cannot be both common and exist in a comdat.
  2583. if (shouldBeInCOMDAT(CGM, *D))
  2584. return true;
  2585. // Declarations with a required alignment do not have common linkage in MSVC
  2586. // mode.
  2587. if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  2588. if (D->hasAttr<AlignedAttr>())
  2589. return true;
  2590. QualType VarType = D->getType();
  2591. if (Context.isAlignmentRequired(VarType))
  2592. return true;
  2593. if (const auto *RT = VarType->getAs<RecordType>()) {
  2594. const RecordDecl *RD = RT->getDecl();
  2595. for (const FieldDecl *FD : RD->fields()) {
  2596. if (FD->isBitField())
  2597. continue;
  2598. if (FD->hasAttr<AlignedAttr>())
  2599. return true;
  2600. if (Context.isAlignmentRequired(FD->getType()))
  2601. return true;
  2602. }
  2603. }
  2604. }
  2605. return false;
  2606. }
  2607. llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
  2608. const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
  2609. if (Linkage == GVA_Internal)
  2610. return llvm::Function::InternalLinkage;
  2611. if (D->hasAttr<WeakAttr>()) {
  2612. if (IsConstantVariable)
  2613. return llvm::GlobalVariable::WeakODRLinkage;
  2614. else
  2615. return llvm::GlobalVariable::WeakAnyLinkage;
  2616. }
  2617. // We are guaranteed to have a strong definition somewhere else,
  2618. // so we can use available_externally linkage.
  2619. if (Linkage == GVA_AvailableExternally)
  2620. return llvm::GlobalValue::AvailableExternallyLinkage;
  2621. // Note that Apple's kernel linker doesn't support symbol
  2622. // coalescing, so we need to avoid linkonce and weak linkages there.
  2623. // Normally, this means we just map to internal, but for explicit
  2624. // instantiations we'll map to external.
  2625. // In C++, the compiler has to emit a definition in every translation unit
  2626. // that references the function. We should use linkonce_odr because
  2627. // a) if all references in this translation unit are optimized away, we
  2628. // don't need to codegen it. b) if the function persists, it needs to be
  2629. // merged with other definitions. c) C++ has the ODR, so we know the
  2630. // definition is dependable.
  2631. if (Linkage == GVA_DiscardableODR)
  2632. return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
  2633. : llvm::Function::InternalLinkage;
  2634. // An explicit instantiation of a template has weak linkage, since
  2635. // explicit instantiations can occur in multiple translation units
  2636. // and must all be equivalent. However, we are not allowed to
  2637. // throw away these explicit instantiations.
  2638. //
  2639. // We don't currently support CUDA device code spread out across multiple TUs,
  2640. // so say that CUDA templates are either external (for kernels) or internal.
  2641. // This lets llvm perform aggressive inter-procedural optimizations.
  2642. if (Linkage == GVA_StrongODR) {
  2643. if (Context.getLangOpts().AppleKext)
  2644. return llvm::Function::ExternalLinkage;
  2645. if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice)
  2646. return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
  2647. : llvm::Function::InternalLinkage;
  2648. return llvm::Function::WeakODRLinkage;
  2649. }
  2650. // C++ doesn't have tentative definitions and thus cannot have common
  2651. // linkage.
  2652. if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
  2653. !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
  2654. CodeGenOpts.NoCommon))
  2655. return llvm::GlobalVariable::CommonLinkage;
  2656. // selectany symbols are externally visible, so use weak instead of
  2657. // linkonce. MSVC optimizes away references to const selectany globals, so
  2658. // all definitions should be the same and ODR linkage should be used.
  2659. // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
  2660. if (D->hasAttr<SelectAnyAttr>())
  2661. return llvm::GlobalVariable::WeakODRLinkage;
  2662. // Otherwise, we have strong external linkage.
  2663. assert(Linkage == GVA_StrongExternal);
  2664. return llvm::GlobalVariable::ExternalLinkage;
  2665. }
  2666. llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
  2667. const VarDecl *VD, bool IsConstant) {
  2668. GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
  2669. return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
  2670. }
  2671. /// Replace the uses of a function that was declared with a non-proto type.
  2672. /// We want to silently drop extra arguments from call sites
  2673. static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
  2674. llvm::Function *newFn) {
  2675. // Fast path.
  2676. if (old->use_empty()) return;
  2677. llvm::Type *newRetTy = newFn->getReturnType();
  2678. SmallVector<llvm::Value*, 4> newArgs;
  2679. SmallVector<llvm::OperandBundleDef, 1> newBundles;
  2680. for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
  2681. ui != ue; ) {
  2682. llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
  2683. llvm::User *user = use->getUser();
  2684. // Recognize and replace uses of bitcasts. Most calls to
  2685. // unprototyped functions will use bitcasts.
  2686. if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
  2687. if (bitcast->getOpcode() == llvm::Instruction::BitCast)
  2688. replaceUsesOfNonProtoConstant(bitcast, newFn);
  2689. continue;
  2690. }
  2691. // Recognize calls to the function.
  2692. llvm::CallSite callSite(user);
  2693. if (!callSite) continue;
  2694. if (!callSite.isCallee(&*use)) continue;
  2695. // If the return types don't match exactly, then we can't
  2696. // transform this call unless it's dead.
  2697. if (callSite->getType() != newRetTy && !callSite->use_empty())
  2698. continue;
  2699. // Get the call site's attribute list.
  2700. SmallVector<llvm::AttributeSet, 8> newArgAttrs;
  2701. llvm::AttributeList oldAttrs = callSite.getAttributes();
  2702. // If the function was passed too few arguments, don't transform.
  2703. unsigned newNumArgs = newFn->arg_size();
  2704. if (callSite.arg_size() < newNumArgs) continue;
  2705. // If extra arguments were passed, we silently drop them.
  2706. // If any of the types mismatch, we don't transform.
  2707. unsigned argNo = 0;
  2708. bool dontTransform = false;
  2709. for (llvm::Argument &A : newFn->args()) {
  2710. if (callSite.getArgument(argNo)->getType() != A.getType()) {
  2711. dontTransform = true;
  2712. break;
  2713. }
  2714. // Add any parameter attributes.
  2715. newArgAttrs.push_back(oldAttrs.getParamAttributes(argNo));
  2716. argNo++;
  2717. }
  2718. if (dontTransform)
  2719. continue;
  2720. // Okay, we can transform this. Create the new call instruction and copy
  2721. // over the required information.
  2722. newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
  2723. // Copy over any operand bundles.
  2724. callSite.getOperandBundlesAsDefs(newBundles);
  2725. llvm::CallSite newCall;
  2726. if (callSite.isCall()) {
  2727. newCall = llvm::CallInst::Create(newFn, newArgs, newBundles, "",
  2728. callSite.getInstruction());
  2729. } else {
  2730. auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction());
  2731. newCall = llvm::InvokeInst::Create(newFn,
  2732. oldInvoke->getNormalDest(),
  2733. oldInvoke->getUnwindDest(),
  2734. newArgs, newBundles, "",
  2735. callSite.getInstruction());
  2736. }
  2737. newArgs.clear(); // for the next iteration
  2738. if (!newCall->getType()->isVoidTy())
  2739. newCall->takeName(callSite.getInstruction());
  2740. newCall.setAttributes(llvm::AttributeList::get(
  2741. newFn->getContext(), oldAttrs.getFnAttributes(),
  2742. oldAttrs.getRetAttributes(), newArgAttrs));
  2743. newCall.setCallingConv(callSite.getCallingConv());
  2744. // Finally, remove the old call, replacing any uses with the new one.
  2745. if (!callSite->use_empty())
  2746. callSite->replaceAllUsesWith(newCall.getInstruction());
  2747. // Copy debug location attached to CI.
  2748. if (callSite->getDebugLoc())
  2749. newCall->setDebugLoc(callSite->getDebugLoc());
  2750. callSite->eraseFromParent();
  2751. }
  2752. }
  2753. /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
  2754. /// implement a function with no prototype, e.g. "int foo() {}". If there are
  2755. /// existing call uses of the old function in the module, this adjusts them to
  2756. /// call the new function directly.
  2757. ///
  2758. /// This is not just a cleanup: the always_inline pass requires direct calls to
  2759. /// functions to be able to inline them. If there is a bitcast in the way, it
  2760. /// won't inline them. Instcombine normally deletes these calls, but it isn't
  2761. /// run at -O0.
  2762. static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
  2763. llvm::Function *NewFn) {
  2764. // If we're redefining a global as a function, don't transform it.
  2765. if (!isa<llvm::Function>(Old)) return;
  2766. replaceUsesOfNonProtoConstant(Old, NewFn);
  2767. }
  2768. void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
  2769. auto DK = VD->isThisDeclarationADefinition();
  2770. if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>())
  2771. return;
  2772. TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
  2773. // If we have a definition, this might be a deferred decl. If the
  2774. // instantiation is explicit, make sure we emit it at the end.
  2775. if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
  2776. GetAddrOfGlobalVar(VD);
  2777. EmitTopLevelDecl(VD);
  2778. }
  2779. void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
  2780. llvm::GlobalValue *GV) {
  2781. const auto *D = cast<FunctionDecl>(GD.getDecl());
  2782. // Compute the function info and LLVM type.
  2783. const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
  2784. llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
  2785. // Get or create the prototype for the function.
  2786. if (!GV || (GV->getType()->getElementType() != Ty))
  2787. GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
  2788. /*DontDefer=*/true,
  2789. ForDefinition));
  2790. // Already emitted.
  2791. if (!GV->isDeclaration())
  2792. return;
  2793. // We need to set linkage and visibility on the function before
  2794. // generating code for it because various parts of IR generation
  2795. // want to propagate this information down (e.g. to local static
  2796. // declarations).
  2797. auto *Fn = cast<llvm::Function>(GV);
  2798. setFunctionLinkage(GD, Fn);
  2799. setFunctionDLLStorageClass(GD, Fn);
  2800. // FIXME: this is redundant with part of setFunctionDefinitionAttributes
  2801. setGlobalVisibility(Fn, D);
  2802. MaybeHandleStaticInExternC(D, Fn);
  2803. maybeSetTrivialComdat(*D, *Fn);
  2804. CodeGenFunction(*this).GenerateCode(D, Fn, FI);
  2805. setFunctionDefinitionAttributes(D, Fn);
  2806. SetLLVMFunctionAttributesForDefinition(D, Fn);
  2807. if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
  2808. AddGlobalCtor(Fn, CA->getPriority());
  2809. if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
  2810. AddGlobalDtor(Fn, DA->getPriority());
  2811. if (D->hasAttr<AnnotateAttr>())
  2812. AddGlobalAnnotations(D, Fn);
  2813. }
  2814. void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
  2815. const auto *D = cast<ValueDecl>(GD.getDecl());
  2816. const AliasAttr *AA = D->getAttr<AliasAttr>();
  2817. assert(AA && "Not an alias?");
  2818. StringRef MangledName = getMangledName(GD);
  2819. if (AA->getAliasee() == MangledName) {
  2820. Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
  2821. return;
  2822. }
  2823. // If there is a definition in the module, then it wins over the alias.
  2824. // This is dubious, but allow it to be safe. Just ignore the alias.
  2825. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  2826. if (Entry && !Entry->isDeclaration())
  2827. return;
  2828. Aliases.push_back(GD);
  2829. llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
  2830. // Create a reference to the named value. This ensures that it is emitted
  2831. // if a deferred decl.
  2832. llvm::Constant *Aliasee;
  2833. if (isa<llvm::FunctionType>(DeclTy))
  2834. Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
  2835. /*ForVTable=*/false);
  2836. else
  2837. Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
  2838. llvm::PointerType::getUnqual(DeclTy),
  2839. /*D=*/nullptr);
  2840. // Create the new alias itself, but don't set a name yet.
  2841. auto *GA = llvm::GlobalAlias::create(
  2842. DeclTy, 0, llvm::Function::ExternalLinkage, "", Aliasee, &getModule());
  2843. if (Entry) {
  2844. if (GA->getAliasee() == Entry) {
  2845. Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
  2846. return;
  2847. }
  2848. assert(Entry->isDeclaration());
  2849. // If there is a declaration in the module, then we had an extern followed
  2850. // by the alias, as in:
  2851. // extern int test6();
  2852. // ...
  2853. // int test6() __attribute__((alias("test7")));
  2854. //
  2855. // Remove it and replace uses of it with the alias.
  2856. GA->takeName(Entry);
  2857. Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
  2858. Entry->getType()));
  2859. Entry->eraseFromParent();
  2860. } else {
  2861. GA->setName(MangledName);
  2862. }
  2863. // Set attributes which are particular to an alias; this is a
  2864. // specialization of the attributes which may be set on a global
  2865. // variable/function.
  2866. if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
  2867. D->isWeakImported()) {
  2868. GA->setLinkage(llvm::Function::WeakAnyLinkage);
  2869. }
  2870. if (const auto *VD = dyn_cast<VarDecl>(D))
  2871. if (VD->getTLSKind())
  2872. setTLSMode(GA, *VD);
  2873. setAliasAttributes(D, GA);
  2874. }
  2875. void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
  2876. const auto *D = cast<ValueDecl>(GD.getDecl());
  2877. const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
  2878. assert(IFA && "Not an ifunc?");
  2879. StringRef MangledName = getMangledName(GD);
  2880. if (IFA->getResolver() == MangledName) {
  2881. Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
  2882. return;
  2883. }
  2884. // Report an error if some definition overrides ifunc.
  2885. llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
  2886. if (Entry && !Entry->isDeclaration()) {
  2887. GlobalDecl OtherGD;
  2888. if (lookupRepresentativeDecl(MangledName, OtherGD) &&
  2889. DiagnosedConflictingDefinitions.insert(GD).second) {
  2890. Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name);
  2891. Diags.Report(OtherGD.getDecl()->getLocation(),
  2892. diag::note_previous_definition);
  2893. }
  2894. return;
  2895. }
  2896. Aliases.push_back(GD);
  2897. llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
  2898. llvm::Constant *Resolver =
  2899. GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD,
  2900. /*ForVTable=*/false);
  2901. llvm::GlobalIFunc *GIF =
  2902. llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
  2903. "", Resolver, &getModule());
  2904. if (Entry) {
  2905. if (GIF->getResolver() == Entry) {
  2906. Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
  2907. return;
  2908. }
  2909. assert(Entry->isDeclaration());
  2910. // If there is a declaration in the module, then we had an extern followed
  2911. // by the ifunc, as in:
  2912. // extern int test();
  2913. // ...
  2914. // int test() __attribute__((ifunc("resolver")));
  2915. //
  2916. // Remove it and replace uses of it with the ifunc.
  2917. GIF->takeName(Entry);
  2918. Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
  2919. Entry->getType()));
  2920. Entry->eraseFromParent();
  2921. } else
  2922. GIF->setName(MangledName);
  2923. SetCommonAttributes(D, GIF);
  2924. }
  2925. llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
  2926. ArrayRef<llvm::Type*> Tys) {
  2927. return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
  2928. Tys);
  2929. }
  2930. static llvm::StringMapEntry<llvm::GlobalVariable *> &
  2931. GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
  2932. const StringLiteral *Literal, bool TargetIsLSB,
  2933. bool &IsUTF16, unsigned &StringLength) {
  2934. StringRef String = Literal->getString();
  2935. unsigned NumBytes = String.size();
  2936. // Check for simple case.
  2937. if (!Literal->containsNonAsciiOrNull()) {
  2938. StringLength = NumBytes;
  2939. return *Map.insert(std::make_pair(String, nullptr)).first;
  2940. }
  2941. // Otherwise, convert the UTF8 literals into a string of shorts.
  2942. IsUTF16 = true;
  2943. SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
  2944. const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
  2945. llvm::UTF16 *ToPtr = &ToBuf[0];
  2946. (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
  2947. ToPtr + NumBytes, llvm::strictConversion);
  2948. // ConvertUTF8toUTF16 returns the length in ToPtr.
  2949. StringLength = ToPtr - &ToBuf[0];
  2950. // Add an explicit null.
  2951. *ToPtr = 0;
  2952. return *Map.insert(std::make_pair(
  2953. StringRef(reinterpret_cast<const char *>(ToBuf.data()),
  2954. (StringLength + 1) * 2),
  2955. nullptr)).first;
  2956. }
  2957. ConstantAddress
  2958. CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
  2959. unsigned StringLength = 0;
  2960. bool isUTF16 = false;
  2961. llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
  2962. GetConstantCFStringEntry(CFConstantStringMap, Literal,
  2963. getDataLayout().isLittleEndian(), isUTF16,
  2964. StringLength);
  2965. if (auto *C = Entry.second)
  2966. return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
  2967. llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
  2968. llvm::Constant *Zeros[] = { Zero, Zero };
  2969. // If we don't already have it, get __CFConstantStringClassReference.
  2970. if (!CFConstantStringClassRef) {
  2971. llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
  2972. Ty = llvm::ArrayType::get(Ty, 0);
  2973. llvm::Constant *GV =
  2974. CreateRuntimeVariable(Ty, "__CFConstantStringClassReference");
  2975. if (getTriple().isOSBinFormatCOFF()) {
  2976. IdentifierInfo &II = getContext().Idents.get(GV->getName());
  2977. TranslationUnitDecl *TUDecl = getContext().getTranslationUnitDecl();
  2978. DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
  2979. llvm::GlobalValue *CGV = cast<llvm::GlobalValue>(GV);
  2980. const VarDecl *VD = nullptr;
  2981. for (const auto &Result : DC->lookup(&II))
  2982. if ((VD = dyn_cast<VarDecl>(Result)))
  2983. break;
  2984. if (!VD || !VD->hasAttr<DLLExportAttr>()) {
  2985. CGV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
  2986. CGV->setLinkage(llvm::GlobalValue::ExternalLinkage);
  2987. } else {
  2988. CGV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
  2989. CGV->setLinkage(llvm::GlobalValue::ExternalLinkage);
  2990. }
  2991. }
  2992. // Decay array -> ptr
  2993. CFConstantStringClassRef =
  2994. llvm::ConstantExpr::getGetElementPtr(Ty, GV, Zeros);
  2995. }
  2996. QualType CFTy = getContext().getCFConstantStringType();
  2997. auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
  2998. ConstantInitBuilder Builder(*this);
  2999. auto Fields = Builder.beginStruct(STy);
  3000. // Class pointer.
  3001. Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef));
  3002. // Flags.
  3003. Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
  3004. // String pointer.
  3005. llvm::Constant *C = nullptr;
  3006. if (isUTF16) {
  3007. auto Arr = llvm::makeArrayRef(
  3008. reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
  3009. Entry.first().size() / 2);
  3010. C = llvm::ConstantDataArray::get(VMContext, Arr);
  3011. } else {
  3012. C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
  3013. }
  3014. // Note: -fwritable-strings doesn't make the backing store strings of
  3015. // CFStrings writable. (See <rdar://problem/10657500>)
  3016. auto *GV =
  3017. new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
  3018. llvm::GlobalValue::PrivateLinkage, C, ".str");
  3019. GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  3020. // Don't enforce the target's minimum global alignment, since the only use
  3021. // of the string is via this class initializer.
  3022. CharUnits Align = isUTF16
  3023. ? getContext().getTypeAlignInChars(getContext().ShortTy)
  3024. : getContext().getTypeAlignInChars(getContext().CharTy);
  3025. GV->setAlignment(Align.getQuantity());
  3026. // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
  3027. // Without it LLVM can merge the string with a non unnamed_addr one during
  3028. // LTO. Doing that changes the section it ends in, which surprises ld64.
  3029. if (getTriple().isOSBinFormatMachO())
  3030. GV->setSection(isUTF16 ? "__TEXT,__ustring"
  3031. : "__TEXT,__cstring,cstring_literals");
  3032. // String.
  3033. llvm::Constant *Str =
  3034. llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
  3035. if (isUTF16)
  3036. // Cast the UTF16 string to the correct type.
  3037. Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy);
  3038. Fields.add(Str);
  3039. // String length.
  3040. auto Ty = getTypes().ConvertType(getContext().LongTy);
  3041. Fields.addInt(cast<llvm::IntegerType>(Ty), StringLength);
  3042. CharUnits Alignment = getPointerAlign();
  3043. // The struct.
  3044. GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
  3045. /*isConstant=*/false,
  3046. llvm::GlobalVariable::PrivateLinkage);
  3047. switch (getTriple().getObjectFormat()) {
  3048. case llvm::Triple::UnknownObjectFormat:
  3049. llvm_unreachable("unknown file format");
  3050. case llvm::Triple::COFF:
  3051. case llvm::Triple::ELF:
  3052. case llvm::Triple::Wasm:
  3053. GV->setSection("cfstring");
  3054. break;
  3055. case llvm::Triple::MachO:
  3056. GV->setSection("__DATA,__cfstring");
  3057. break;
  3058. }
  3059. Entry.second = GV;
  3060. return ConstantAddress(GV, Alignment);
  3061. }
  3062. bool CodeGenModule::getExpressionLocationsEnabled() const {
  3063. return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
  3064. }
  3065. QualType CodeGenModule::getObjCFastEnumerationStateType() {
  3066. if (ObjCFastEnumerationStateType.isNull()) {
  3067. RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
  3068. D->startDefinition();
  3069. QualType FieldTypes[] = {
  3070. Context.UnsignedLongTy,
  3071. Context.getPointerType(Context.getObjCIdType()),
  3072. Context.getPointerType(Context.UnsignedLongTy),
  3073. Context.getConstantArrayType(Context.UnsignedLongTy,
  3074. llvm::APInt(32, 5), ArrayType::Normal, 0)
  3075. };
  3076. for (size_t i = 0; i < 4; ++i) {
  3077. FieldDecl *Field = FieldDecl::Create(Context,
  3078. D,
  3079. SourceLocation(),
  3080. SourceLocation(), nullptr,
  3081. FieldTypes[i], /*TInfo=*/nullptr,
  3082. /*BitWidth=*/nullptr,
  3083. /*Mutable=*/false,
  3084. ICIS_NoInit);
  3085. Field->setAccess(AS_public);
  3086. D->addDecl(Field);
  3087. }
  3088. D->completeDefinition();
  3089. ObjCFastEnumerationStateType = Context.getTagDeclType(D);
  3090. }
  3091. return ObjCFastEnumerationStateType;
  3092. }
  3093. llvm::Constant *
  3094. CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
  3095. assert(!E->getType()->isPointerType() && "Strings are always arrays");
  3096. // Don't emit it as the address of the string, emit the string data itself
  3097. // as an inline array.
  3098. if (E->getCharByteWidth() == 1) {
  3099. SmallString<64> Str(E->getString());
  3100. // Resize the string to the right size, which is indicated by its type.
  3101. const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
  3102. Str.resize(CAT->getSize().getZExtValue());
  3103. return llvm::ConstantDataArray::getString(VMContext, Str, false);
  3104. }
  3105. auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
  3106. llvm::Type *ElemTy = AType->getElementType();
  3107. unsigned NumElements = AType->getNumElements();
  3108. // Wide strings have either 2-byte or 4-byte elements.
  3109. if (ElemTy->getPrimitiveSizeInBits() == 16) {
  3110. SmallVector<uint16_t, 32> Elements;
  3111. Elements.reserve(NumElements);
  3112. for(unsigned i = 0, e = E->getLength(); i != e; ++i)
  3113. Elements.push_back(E->getCodeUnit(i));
  3114. Elements.resize(NumElements);
  3115. return llvm::ConstantDataArray::get(VMContext, Elements);
  3116. }
  3117. assert(ElemTy->getPrimitiveSizeInBits() == 32);
  3118. SmallVector<uint32_t, 32> Elements;
  3119. Elements.reserve(NumElements);
  3120. for(unsigned i = 0, e = E->getLength(); i != e; ++i)
  3121. Elements.push_back(E->getCodeUnit(i));
  3122. Elements.resize(NumElements);
  3123. return llvm::ConstantDataArray::get(VMContext, Elements);
  3124. }
  3125. static llvm::GlobalVariable *
  3126. GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
  3127. CodeGenModule &CGM, StringRef GlobalName,
  3128. CharUnits Alignment) {
  3129. // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
  3130. unsigned AddrSpace = 0;
  3131. if (CGM.getLangOpts().OpenCL)
  3132. AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
  3133. llvm::Module &M = CGM.getModule();
  3134. // Create a global variable for this string
  3135. auto *GV = new llvm::GlobalVariable(
  3136. M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
  3137. nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
  3138. GV->setAlignment(Alignment.getQuantity());
  3139. GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  3140. if (GV->isWeakForLinker()) {
  3141. assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
  3142. GV->setComdat(M.getOrInsertComdat(GV->getName()));
  3143. }
  3144. return GV;
  3145. }
  3146. /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
  3147. /// constant array for the given string literal.
  3148. ConstantAddress
  3149. CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
  3150. StringRef Name) {
  3151. CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
  3152. llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
  3153. llvm::GlobalVariable **Entry = nullptr;
  3154. if (!LangOpts.WritableStrings) {
  3155. Entry = &ConstantStringMap[C];
  3156. if (auto GV = *Entry) {
  3157. if (Alignment.getQuantity() > GV->getAlignment())
  3158. GV->setAlignment(Alignment.getQuantity());
  3159. return ConstantAddress(GV, Alignment);
  3160. }
  3161. }
  3162. SmallString<256> MangledNameBuffer;
  3163. StringRef GlobalVariableName;
  3164. llvm::GlobalValue::LinkageTypes LT;
  3165. // Mangle the string literal if the ABI allows for it. However, we cannot
  3166. // do this if we are compiling with ASan or -fwritable-strings because they
  3167. // rely on strings having normal linkage.
  3168. if (!LangOpts.WritableStrings &&
  3169. !LangOpts.Sanitize.has(SanitizerKind::Address) &&
  3170. getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) {
  3171. llvm::raw_svector_ostream Out(MangledNameBuffer);
  3172. getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
  3173. LT = llvm::GlobalValue::LinkOnceODRLinkage;
  3174. GlobalVariableName = MangledNameBuffer;
  3175. } else {
  3176. LT = llvm::GlobalValue::PrivateLinkage;
  3177. GlobalVariableName = Name;
  3178. }
  3179. auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
  3180. if (Entry)
  3181. *Entry = GV;
  3182. SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
  3183. QualType());
  3184. return ConstantAddress(GV, Alignment);
  3185. }
  3186. /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
  3187. /// array for the given ObjCEncodeExpr node.
  3188. ConstantAddress
  3189. CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
  3190. std::string Str;
  3191. getContext().getObjCEncodingForType(E->getEncodedType(), Str);
  3192. return GetAddrOfConstantCString(Str);
  3193. }
  3194. /// GetAddrOfConstantCString - Returns a pointer to a character array containing
  3195. /// the literal and a terminating '\0' character.
  3196. /// The result has pointer to array type.
  3197. ConstantAddress CodeGenModule::GetAddrOfConstantCString(
  3198. const std::string &Str, const char *GlobalName) {
  3199. StringRef StrWithNull(Str.c_str(), Str.size() + 1);
  3200. CharUnits Alignment =
  3201. getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
  3202. llvm::Constant *C =
  3203. llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
  3204. // Don't share any string literals if strings aren't constant.
  3205. llvm::GlobalVariable **Entry = nullptr;
  3206. if (!LangOpts.WritableStrings) {
  3207. Entry = &ConstantStringMap[C];
  3208. if (auto GV = *Entry) {
  3209. if (Alignment.getQuantity() > GV->getAlignment())
  3210. GV->setAlignment(Alignment.getQuantity());
  3211. return ConstantAddress(GV, Alignment);
  3212. }
  3213. }
  3214. // Get the default prefix if a name wasn't specified.
  3215. if (!GlobalName)
  3216. GlobalName = ".str";
  3217. // Create a global variable for this.
  3218. auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
  3219. GlobalName, Alignment);
  3220. if (Entry)
  3221. *Entry = GV;
  3222. return ConstantAddress(GV, Alignment);
  3223. }
  3224. ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
  3225. const MaterializeTemporaryExpr *E, const Expr *Init) {
  3226. assert((E->getStorageDuration() == SD_Static ||
  3227. E->getStorageDuration() == SD_Thread) && "not a global temporary");
  3228. const auto *VD = cast<VarDecl>(E->getExtendingDecl());
  3229. // If we're not materializing a subobject of the temporary, keep the
  3230. // cv-qualifiers from the type of the MaterializeTemporaryExpr.
  3231. QualType MaterializedType = Init->getType();
  3232. if (Init == E->GetTemporaryExpr())
  3233. MaterializedType = E->getType();
  3234. CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
  3235. if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E])
  3236. return ConstantAddress(Slot, Align);
  3237. // FIXME: If an externally-visible declaration extends multiple temporaries,
  3238. // we need to give each temporary the same name in every translation unit (and
  3239. // we also need to make the temporaries externally-visible).
  3240. SmallString<256> Name;
  3241. llvm::raw_svector_ostream Out(Name);
  3242. getCXXABI().getMangleContext().mangleReferenceTemporary(
  3243. VD, E->getManglingNumber(), Out);
  3244. APValue *Value = nullptr;
  3245. if (E->getStorageDuration() == SD_Static) {
  3246. // We might have a cached constant initializer for this temporary. Note
  3247. // that this might have a different value from the value computed by
  3248. // evaluating the initializer if the surrounding constant expression
  3249. // modifies the temporary.
  3250. Value = getContext().getMaterializedTemporaryValue(E, false);
  3251. if (Value && Value->isUninit())
  3252. Value = nullptr;
  3253. }
  3254. // Try evaluating it now, it might have a constant initializer.
  3255. Expr::EvalResult EvalResult;
  3256. if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
  3257. !EvalResult.hasSideEffects())
  3258. Value = &EvalResult.Val;
  3259. unsigned AddrSpace =
  3260. VD ? GetGlobalVarAddressSpace(VD) : MaterializedType.getAddressSpace();
  3261. Optional<ConstantEmitter> emitter;
  3262. llvm::Constant *InitialValue = nullptr;
  3263. bool Constant = false;
  3264. llvm::Type *Type;
  3265. if (Value) {
  3266. // The temporary has a constant initializer, use it.
  3267. emitter.emplace(*this);
  3268. InitialValue = emitter->emitForInitializer(*Value, AddrSpace,
  3269. MaterializedType);
  3270. Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
  3271. Type = InitialValue->getType();
  3272. } else {
  3273. // No initializer, the initialization will be provided when we
  3274. // initialize the declaration which performed lifetime extension.
  3275. Type = getTypes().ConvertTypeForMem(MaterializedType);
  3276. }
  3277. // Create a global variable for this lifetime-extended temporary.
  3278. llvm::GlobalValue::LinkageTypes Linkage =
  3279. getLLVMLinkageVarDefinition(VD, Constant);
  3280. if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
  3281. const VarDecl *InitVD;
  3282. if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
  3283. isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
  3284. // Temporaries defined inside a class get linkonce_odr linkage because the
  3285. // class can be defined in multipe translation units.
  3286. Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
  3287. } else {
  3288. // There is no need for this temporary to have external linkage if the
  3289. // VarDecl has external linkage.
  3290. Linkage = llvm::GlobalVariable::InternalLinkage;
  3291. }
  3292. }
  3293. auto TargetAS = getContext().getTargetAddressSpace(AddrSpace);
  3294. auto *GV = new llvm::GlobalVariable(
  3295. getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
  3296. /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
  3297. if (emitter) emitter->finalize(GV);
  3298. setGlobalVisibility(GV, VD);
  3299. GV->setAlignment(Align.getQuantity());
  3300. if (supportsCOMDAT() && GV->isWeakForLinker())
  3301. GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
  3302. if (VD->getTLSKind())
  3303. setTLSMode(GV, *VD);
  3304. llvm::Constant *CV = GV;
  3305. if (AddrSpace != LangAS::Default)
  3306. CV = getTargetCodeGenInfo().performAddrSpaceCast(
  3307. *this, GV, AddrSpace, LangAS::Default,
  3308. Type->getPointerTo(
  3309. getContext().getTargetAddressSpace(LangAS::Default)));
  3310. MaterializedGlobalTemporaryMap[E] = CV;
  3311. return ConstantAddress(CV, Align);
  3312. }
  3313. /// EmitObjCPropertyImplementations - Emit information for synthesized
  3314. /// properties for an implementation.
  3315. void CodeGenModule::EmitObjCPropertyImplementations(const
  3316. ObjCImplementationDecl *D) {
  3317. for (const auto *PID : D->property_impls()) {
  3318. // Dynamic is just for type-checking.
  3319. if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
  3320. ObjCPropertyDecl *PD = PID->getPropertyDecl();
  3321. // Determine which methods need to be implemented, some may have
  3322. // been overridden. Note that ::isPropertyAccessor is not the method
  3323. // we want, that just indicates if the decl came from a
  3324. // property. What we want to know is if the method is defined in
  3325. // this implementation.
  3326. if (!D->getInstanceMethod(PD->getGetterName()))
  3327. CodeGenFunction(*this).GenerateObjCGetter(
  3328. const_cast<ObjCImplementationDecl *>(D), PID);
  3329. if (!PD->isReadOnly() &&
  3330. !D->getInstanceMethod(PD->getSetterName()))
  3331. CodeGenFunction(*this).GenerateObjCSetter(
  3332. const_cast<ObjCImplementationDecl *>(D), PID);
  3333. }
  3334. }
  3335. }
  3336. static bool needsDestructMethod(ObjCImplementationDecl *impl) {
  3337. const ObjCInterfaceDecl *iface = impl->getClassInterface();
  3338. for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
  3339. ivar; ivar = ivar->getNextIvar())
  3340. if (ivar->getType().isDestructedType())
  3341. return true;
  3342. return false;
  3343. }
  3344. static bool AllTrivialInitializers(CodeGenModule &CGM,
  3345. ObjCImplementationDecl *D) {
  3346. CodeGenFunction CGF(CGM);
  3347. for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
  3348. E = D->init_end(); B != E; ++B) {
  3349. CXXCtorInitializer *CtorInitExp = *B;
  3350. Expr *Init = CtorInitExp->getInit();
  3351. if (!CGF.isTrivialInitializer(Init))
  3352. return false;
  3353. }
  3354. return true;
  3355. }
  3356. /// EmitObjCIvarInitializations - Emit information for ivar initialization
  3357. /// for an implementation.
  3358. void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
  3359. // We might need a .cxx_destruct even if we don't have any ivar initializers.
  3360. if (needsDestructMethod(D)) {
  3361. IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
  3362. Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
  3363. ObjCMethodDecl *DTORMethod =
  3364. ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
  3365. cxxSelector, getContext().VoidTy, nullptr, D,
  3366. /*isInstance=*/true, /*isVariadic=*/false,
  3367. /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
  3368. /*isDefined=*/false, ObjCMethodDecl::Required);
  3369. D->addInstanceMethod(DTORMethod);
  3370. CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
  3371. D->setHasDestructors(true);
  3372. }
  3373. // If the implementation doesn't have any ivar initializers, we don't need
  3374. // a .cxx_construct.
  3375. if (D->getNumIvarInitializers() == 0 ||
  3376. AllTrivialInitializers(*this, D))
  3377. return;
  3378. IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
  3379. Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
  3380. // The constructor returns 'self'.
  3381. ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
  3382. D->getLocation(),
  3383. D->getLocation(),
  3384. cxxSelector,
  3385. getContext().getObjCIdType(),
  3386. nullptr, D, /*isInstance=*/true,
  3387. /*isVariadic=*/false,
  3388. /*isPropertyAccessor=*/true,
  3389. /*isImplicitlyDeclared=*/true,
  3390. /*isDefined=*/false,
  3391. ObjCMethodDecl::Required);
  3392. D->addInstanceMethod(CTORMethod);
  3393. CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
  3394. D->setHasNonZeroConstructors(true);
  3395. }
  3396. // EmitLinkageSpec - Emit all declarations in a linkage spec.
  3397. void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
  3398. if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
  3399. LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
  3400. ErrorUnsupported(LSD, "linkage spec");
  3401. return;
  3402. }
  3403. EmitDeclContext(LSD);
  3404. }
  3405. void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
  3406. for (auto *I : DC->decls()) {
  3407. // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
  3408. // are themselves considered "top-level", so EmitTopLevelDecl on an
  3409. // ObjCImplDecl does not recursively visit them. We need to do that in
  3410. // case they're nested inside another construct (LinkageSpecDecl /
  3411. // ExportDecl) that does stop them from being considered "top-level".
  3412. if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
  3413. for (auto *M : OID->methods())
  3414. EmitTopLevelDecl(M);
  3415. }
  3416. EmitTopLevelDecl(I);
  3417. }
  3418. }
  3419. /// EmitTopLevelDecl - Emit code for a single top level declaration.
  3420. void CodeGenModule::EmitTopLevelDecl(Decl *D) {
  3421. // Ignore dependent declarations.
  3422. if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
  3423. return;
  3424. switch (D->getKind()) {
  3425. case Decl::CXXConversion:
  3426. case Decl::CXXMethod:
  3427. case Decl::Function:
  3428. // Skip function templates
  3429. if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
  3430. cast<FunctionDecl>(D)->isLateTemplateParsed())
  3431. return;
  3432. EmitGlobal(cast<FunctionDecl>(D));
  3433. // Always provide some coverage mapping
  3434. // even for the functions that aren't emitted.
  3435. AddDeferredUnusedCoverageMapping(D);
  3436. break;
  3437. case Decl::CXXDeductionGuide:
  3438. // Function-like, but does not result in code emission.
  3439. break;
  3440. case Decl::Var:
  3441. case Decl::Decomposition:
  3442. // Skip variable templates
  3443. if (cast<VarDecl>(D)->getDescribedVarTemplate())
  3444. return;
  3445. LLVM_FALLTHROUGH;
  3446. case Decl::VarTemplateSpecialization:
  3447. EmitGlobal(cast<VarDecl>(D));
  3448. if (auto *DD = dyn_cast<DecompositionDecl>(D))
  3449. for (auto *B : DD->bindings())
  3450. if (auto *HD = B->getHoldingVar())
  3451. EmitGlobal(HD);
  3452. break;
  3453. // Indirect fields from global anonymous structs and unions can be
  3454. // ignored; only the actual variable requires IR gen support.
  3455. case Decl::IndirectField:
  3456. break;
  3457. // C++ Decls
  3458. case Decl::Namespace:
  3459. EmitDeclContext(cast<NamespaceDecl>(D));
  3460. break;
  3461. case Decl::CXXRecord:
  3462. if (DebugInfo) {
  3463. if (auto *ES = D->getASTContext().getExternalSource())
  3464. if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
  3465. DebugInfo->completeUnusedClass(cast<CXXRecordDecl>(*D));
  3466. }
  3467. // Emit any static data members, they may be definitions.
  3468. for (auto *I : cast<CXXRecordDecl>(D)->decls())
  3469. if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
  3470. EmitTopLevelDecl(I);
  3471. break;
  3472. // No code generation needed.
  3473. case Decl::UsingShadow:
  3474. case Decl::ClassTemplate:
  3475. case Decl::VarTemplate:
  3476. case Decl::VarTemplatePartialSpecialization:
  3477. case Decl::FunctionTemplate:
  3478. case Decl::TypeAliasTemplate:
  3479. case Decl::Block:
  3480. case Decl::Empty:
  3481. break;
  3482. case Decl::Using: // using X; [C++]
  3483. if (CGDebugInfo *DI = getModuleDebugInfo())
  3484. DI->EmitUsingDecl(cast<UsingDecl>(*D));
  3485. return;
  3486. case Decl::NamespaceAlias:
  3487. if (CGDebugInfo *DI = getModuleDebugInfo())
  3488. DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
  3489. return;
  3490. case Decl::UsingDirective: // using namespace X; [C++]
  3491. if (CGDebugInfo *DI = getModuleDebugInfo())
  3492. DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
  3493. return;
  3494. case Decl::CXXConstructor:
  3495. // Skip function templates
  3496. if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
  3497. cast<FunctionDecl>(D)->isLateTemplateParsed())
  3498. return;
  3499. getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
  3500. break;
  3501. case Decl::CXXDestructor:
  3502. if (cast<FunctionDecl>(D)->isLateTemplateParsed())
  3503. return;
  3504. getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
  3505. break;
  3506. case Decl::StaticAssert:
  3507. // Nothing to do.
  3508. break;
  3509. // Objective-C Decls
  3510. // Forward declarations, no (immediate) code generation.
  3511. case Decl::ObjCInterface:
  3512. case Decl::ObjCCategory:
  3513. break;
  3514. case Decl::ObjCProtocol: {
  3515. auto *Proto = cast<ObjCProtocolDecl>(D);
  3516. if (Proto->isThisDeclarationADefinition())
  3517. ObjCRuntime->GenerateProtocol(Proto);
  3518. break;
  3519. }
  3520. case Decl::ObjCCategoryImpl:
  3521. // Categories have properties but don't support synthesize so we
  3522. // can ignore them here.
  3523. ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
  3524. break;
  3525. case Decl::ObjCImplementation: {
  3526. auto *OMD = cast<ObjCImplementationDecl>(D);
  3527. EmitObjCPropertyImplementations(OMD);
  3528. EmitObjCIvarInitializations(OMD);
  3529. ObjCRuntime->GenerateClass(OMD);
  3530. // Emit global variable debug information.
  3531. if (CGDebugInfo *DI = getModuleDebugInfo())
  3532. if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
  3533. DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
  3534. OMD->getClassInterface()), OMD->getLocation());
  3535. break;
  3536. }
  3537. case Decl::ObjCMethod: {
  3538. auto *OMD = cast<ObjCMethodDecl>(D);
  3539. // If this is not a prototype, emit the body.
  3540. if (OMD->getBody())
  3541. CodeGenFunction(*this).GenerateObjCMethod(OMD);
  3542. break;
  3543. }
  3544. case Decl::ObjCCompatibleAlias:
  3545. ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
  3546. break;
  3547. case Decl::PragmaComment: {
  3548. const auto *PCD = cast<PragmaCommentDecl>(D);
  3549. switch (PCD->getCommentKind()) {
  3550. case PCK_Unknown:
  3551. llvm_unreachable("unexpected pragma comment kind");
  3552. case PCK_Linker:
  3553. AppendLinkerOptions(PCD->getArg());
  3554. break;
  3555. case PCK_Lib:
  3556. AddDependentLib(PCD->getArg());
  3557. break;
  3558. case PCK_Compiler:
  3559. case PCK_ExeStr:
  3560. case PCK_User:
  3561. break; // We ignore all of these.
  3562. }
  3563. break;
  3564. }
  3565. case Decl::PragmaDetectMismatch: {
  3566. const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
  3567. AddDetectMismatch(PDMD->getName(), PDMD->getValue());
  3568. break;
  3569. }
  3570. case Decl::LinkageSpec:
  3571. EmitLinkageSpec(cast<LinkageSpecDecl>(D));
  3572. break;
  3573. case Decl::FileScopeAsm: {
  3574. // File-scope asm is ignored during device-side CUDA compilation.
  3575. if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
  3576. break;
  3577. // File-scope asm is ignored during device-side OpenMP compilation.
  3578. if (LangOpts.OpenMPIsDevice)
  3579. break;
  3580. auto *AD = cast<FileScopeAsmDecl>(D);
  3581. getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
  3582. break;
  3583. }
  3584. case Decl::Import: {
  3585. auto *Import = cast<ImportDecl>(D);
  3586. // If we've already imported this module, we're done.
  3587. if (!ImportedModules.insert(Import->getImportedModule()))
  3588. break;
  3589. // Emit debug information for direct imports.
  3590. if (!Import->getImportedOwningModule()) {
  3591. if (CGDebugInfo *DI = getModuleDebugInfo())
  3592. DI->EmitImportDecl(*Import);
  3593. }
  3594. // Find all of the submodules and emit the module initializers.
  3595. llvm::SmallPtrSet<clang::Module *, 16> Visited;
  3596. SmallVector<clang::Module *, 16> Stack;
  3597. Visited.insert(Import->getImportedModule());
  3598. Stack.push_back(Import->getImportedModule());
  3599. while (!Stack.empty()) {
  3600. clang::Module *Mod = Stack.pop_back_val();
  3601. if (!EmittedModuleInitializers.insert(Mod).second)
  3602. continue;
  3603. for (auto *D : Context.getModuleInitializers(Mod))
  3604. EmitTopLevelDecl(D);
  3605. // Visit the submodules of this module.
  3606. for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
  3607. SubEnd = Mod->submodule_end();
  3608. Sub != SubEnd; ++Sub) {
  3609. // Skip explicit children; they need to be explicitly imported to emit
  3610. // the initializers.
  3611. if ((*Sub)->IsExplicit)
  3612. continue;
  3613. if (Visited.insert(*Sub).second)
  3614. Stack.push_back(*Sub);
  3615. }
  3616. }
  3617. break;
  3618. }
  3619. case Decl::Export:
  3620. EmitDeclContext(cast<ExportDecl>(D));
  3621. break;
  3622. case Decl::OMPThreadPrivate:
  3623. EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
  3624. break;
  3625. case Decl::ClassTemplateSpecialization: {
  3626. const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
  3627. if (DebugInfo &&
  3628. Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition &&
  3629. Spec->hasDefinition())
  3630. DebugInfo->completeTemplateDefinition(*Spec);
  3631. break;
  3632. }
  3633. case Decl::OMPDeclareReduction:
  3634. EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
  3635. break;
  3636. default:
  3637. // Make sure we handled everything we should, every other kind is a
  3638. // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
  3639. // function. Need to recode Decl::Kind to do that easily.
  3640. assert(isa<TypeDecl>(D) && "Unsupported decl kind");
  3641. break;
  3642. }
  3643. }
  3644. void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
  3645. // Do we need to generate coverage mapping?
  3646. if (!CodeGenOpts.CoverageMapping)
  3647. return;
  3648. switch (D->getKind()) {
  3649. case Decl::CXXConversion:
  3650. case Decl::CXXMethod:
  3651. case Decl::Function:
  3652. case Decl::ObjCMethod:
  3653. case Decl::CXXConstructor:
  3654. case Decl::CXXDestructor: {
  3655. if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
  3656. return;
  3657. SourceManager &SM = getContext().getSourceManager();
  3658. if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getLocStart()))
  3659. return;
  3660. auto I = DeferredEmptyCoverageMappingDecls.find(D);
  3661. if (I == DeferredEmptyCoverageMappingDecls.end())
  3662. DeferredEmptyCoverageMappingDecls[D] = true;
  3663. break;
  3664. }
  3665. default:
  3666. break;
  3667. };
  3668. }
  3669. void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
  3670. // Do we need to generate coverage mapping?
  3671. if (!CodeGenOpts.CoverageMapping)
  3672. return;
  3673. if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
  3674. if (Fn->isTemplateInstantiation())
  3675. ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
  3676. }
  3677. auto I = DeferredEmptyCoverageMappingDecls.find(D);
  3678. if (I == DeferredEmptyCoverageMappingDecls.end())
  3679. DeferredEmptyCoverageMappingDecls[D] = false;
  3680. else
  3681. I->second = false;
  3682. }
  3683. void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
  3684. std::vector<const Decl *> DeferredDecls;
  3685. for (const auto &I : DeferredEmptyCoverageMappingDecls) {
  3686. if (!I.second)
  3687. continue;
  3688. DeferredDecls.push_back(I.first);
  3689. }
  3690. // Sort the declarations by their location to make sure that the tests get a
  3691. // predictable order for the coverage mapping for the unused declarations.
  3692. if (CodeGenOpts.DumpCoverageMapping)
  3693. std::sort(DeferredDecls.begin(), DeferredDecls.end(),
  3694. [] (const Decl *LHS, const Decl *RHS) {
  3695. return LHS->getLocStart() < RHS->getLocStart();
  3696. });
  3697. for (const auto *D : DeferredDecls) {
  3698. switch (D->getKind()) {
  3699. case Decl::CXXConversion:
  3700. case Decl::CXXMethod:
  3701. case Decl::Function:
  3702. case Decl::ObjCMethod: {
  3703. CodeGenPGO PGO(*this);
  3704. GlobalDecl GD(cast<FunctionDecl>(D));
  3705. PGO.emitEmptyCounterMapping(D, getMangledName(GD),
  3706. getFunctionLinkage(GD));
  3707. break;
  3708. }
  3709. case Decl::CXXConstructor: {
  3710. CodeGenPGO PGO(*this);
  3711. GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
  3712. PGO.emitEmptyCounterMapping(D, getMangledName(GD),
  3713. getFunctionLinkage(GD));
  3714. break;
  3715. }
  3716. case Decl::CXXDestructor: {
  3717. CodeGenPGO PGO(*this);
  3718. GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
  3719. PGO.emitEmptyCounterMapping(D, getMangledName(GD),
  3720. getFunctionLinkage(GD));
  3721. break;
  3722. }
  3723. default:
  3724. break;
  3725. };
  3726. }
  3727. }
  3728. /// Turns the given pointer into a constant.
  3729. static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
  3730. const void *Ptr) {
  3731. uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
  3732. llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
  3733. return llvm::ConstantInt::get(i64, PtrInt);
  3734. }
  3735. static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
  3736. llvm::NamedMDNode *&GlobalMetadata,
  3737. GlobalDecl D,
  3738. llvm::GlobalValue *Addr) {
  3739. if (!GlobalMetadata)
  3740. GlobalMetadata =
  3741. CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
  3742. // TODO: should we report variant information for ctors/dtors?
  3743. llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
  3744. llvm::ConstantAsMetadata::get(GetPointerConstant(
  3745. CGM.getLLVMContext(), D.getDecl()))};
  3746. GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
  3747. }
  3748. /// For each function which is declared within an extern "C" region and marked
  3749. /// as 'used', but has internal linkage, create an alias from the unmangled
  3750. /// name to the mangled name if possible. People expect to be able to refer
  3751. /// to such functions with an unmangled name from inline assembly within the
  3752. /// same translation unit.
  3753. void CodeGenModule::EmitStaticExternCAliases() {
  3754. // Don't do anything if we're generating CUDA device code -- the NVPTX
  3755. // assembly target doesn't support aliases.
  3756. if (Context.getTargetInfo().getTriple().isNVPTX())
  3757. return;
  3758. for (auto &I : StaticExternCValues) {
  3759. IdentifierInfo *Name = I.first;
  3760. llvm::GlobalValue *Val = I.second;
  3761. if (Val && !getModule().getNamedValue(Name->getName()))
  3762. addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
  3763. }
  3764. }
  3765. bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
  3766. GlobalDecl &Result) const {
  3767. auto Res = Manglings.find(MangledName);
  3768. if (Res == Manglings.end())
  3769. return false;
  3770. Result = Res->getValue();
  3771. return true;
  3772. }
  3773. /// Emits metadata nodes associating all the global values in the
  3774. /// current module with the Decls they came from. This is useful for
  3775. /// projects using IR gen as a subroutine.
  3776. ///
  3777. /// Since there's currently no way to associate an MDNode directly
  3778. /// with an llvm::GlobalValue, we create a global named metadata
  3779. /// with the name 'clang.global.decl.ptrs'.
  3780. void CodeGenModule::EmitDeclMetadata() {
  3781. llvm::NamedMDNode *GlobalMetadata = nullptr;
  3782. for (auto &I : MangledDeclNames) {
  3783. llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
  3784. // Some mangled names don't necessarily have an associated GlobalValue
  3785. // in this module, e.g. if we mangled it for DebugInfo.
  3786. if (Addr)
  3787. EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
  3788. }
  3789. }
  3790. /// Emits metadata nodes for all the local variables in the current
  3791. /// function.
  3792. void CodeGenFunction::EmitDeclMetadata() {
  3793. if (LocalDeclMap.empty()) return;
  3794. llvm::LLVMContext &Context = getLLVMContext();
  3795. // Find the unique metadata ID for this name.
  3796. unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
  3797. llvm::NamedMDNode *GlobalMetadata = nullptr;
  3798. for (auto &I : LocalDeclMap) {
  3799. const Decl *D = I.first;
  3800. llvm::Value *Addr = I.second.getPointer();
  3801. if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
  3802. llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
  3803. Alloca->setMetadata(
  3804. DeclPtrKind, llvm::MDNode::get(
  3805. Context, llvm::ValueAsMetadata::getConstant(DAddr)));
  3806. } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
  3807. GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
  3808. EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
  3809. }
  3810. }
  3811. }
  3812. void CodeGenModule::EmitVersionIdentMetadata() {
  3813. llvm::NamedMDNode *IdentMetadata =
  3814. TheModule.getOrInsertNamedMetadata("llvm.ident");
  3815. std::string Version = getClangFullVersion();
  3816. llvm::LLVMContext &Ctx = TheModule.getContext();
  3817. llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
  3818. IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
  3819. }
  3820. void CodeGenModule::EmitTargetMetadata() {
  3821. // Warning, new MangledDeclNames may be appended within this loop.
  3822. // We rely on MapVector insertions adding new elements to the end
  3823. // of the container.
  3824. // FIXME: Move this loop into the one target that needs it, and only
  3825. // loop over those declarations for which we couldn't emit the target
  3826. // metadata when we emitted the declaration.
  3827. for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
  3828. auto Val = *(MangledDeclNames.begin() + I);
  3829. const Decl *D = Val.first.getDecl()->getMostRecentDecl();
  3830. llvm::GlobalValue *GV = GetGlobalValue(Val.second);
  3831. getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
  3832. }
  3833. }
  3834. void CodeGenModule::EmitCoverageFile() {
  3835. if (getCodeGenOpts().CoverageDataFile.empty() &&
  3836. getCodeGenOpts().CoverageNotesFile.empty())
  3837. return;
  3838. llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
  3839. if (!CUNode)
  3840. return;
  3841. llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
  3842. llvm::LLVMContext &Ctx = TheModule.getContext();
  3843. auto *CoverageDataFile =
  3844. llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
  3845. auto *CoverageNotesFile =
  3846. llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
  3847. for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
  3848. llvm::MDNode *CU = CUNode->getOperand(i);
  3849. llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
  3850. GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
  3851. }
  3852. }
  3853. llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
  3854. // Sema has checked that all uuid strings are of the form
  3855. // "12345678-1234-1234-1234-1234567890ab".
  3856. assert(Uuid.size() == 36);
  3857. for (unsigned i = 0; i < 36; ++i) {
  3858. if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
  3859. else assert(isHexDigit(Uuid[i]));
  3860. }
  3861. // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab".
  3862. const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
  3863. llvm::Constant *Field3[8];
  3864. for (unsigned Idx = 0; Idx < 8; ++Idx)
  3865. Field3[Idx] = llvm::ConstantInt::get(
  3866. Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
  3867. llvm::Constant *Fields[4] = {
  3868. llvm::ConstantInt::get(Int32Ty, Uuid.substr(0, 8), 16),
  3869. llvm::ConstantInt::get(Int16Ty, Uuid.substr(9, 4), 16),
  3870. llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
  3871. llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
  3872. };
  3873. return llvm::ConstantStruct::getAnon(Fields);
  3874. }
  3875. llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
  3876. bool ForEH) {
  3877. // Return a bogus pointer if RTTI is disabled, unless it's for EH.
  3878. // FIXME: should we even be calling this method if RTTI is disabled
  3879. // and it's not for EH?
  3880. if (!ForEH && !getLangOpts().RTTI)
  3881. return llvm::Constant::getNullValue(Int8PtrTy);
  3882. if (ForEH && Ty->isObjCObjectPointerType() &&
  3883. LangOpts.ObjCRuntime.isGNUFamily())
  3884. return ObjCRuntime->GetEHType(Ty);
  3885. return getCXXABI().getAddrOfRTTIDescriptor(Ty);
  3886. }
  3887. void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
  3888. for (auto RefExpr : D->varlists()) {
  3889. auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
  3890. bool PerformInit =
  3891. VD->getAnyInitializer() &&
  3892. !VD->getAnyInitializer()->isConstantInitializer(getContext(),
  3893. /*ForRef=*/false);
  3894. Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD));
  3895. if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
  3896. VD, Addr, RefExpr->getLocStart(), PerformInit))
  3897. CXXGlobalInits.push_back(InitFunction);
  3898. }
  3899. }
  3900. llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
  3901. llvm::Metadata *&InternalId = MetadataIdMap[T.getCanonicalType()];
  3902. if (InternalId)
  3903. return InternalId;
  3904. if (isExternallyVisible(T->getLinkage())) {
  3905. std::string OutName;
  3906. llvm::raw_string_ostream Out(OutName);
  3907. getCXXABI().getMangleContext().mangleTypeName(T, Out);
  3908. InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
  3909. } else {
  3910. InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
  3911. llvm::ArrayRef<llvm::Metadata *>());
  3912. }
  3913. return InternalId;
  3914. }
  3915. /// Returns whether this module needs the "all-vtables" type identifier.
  3916. bool CodeGenModule::NeedAllVtablesTypeId() const {
  3917. // Returns true if at least one of vtable-based CFI checkers is enabled and
  3918. // is not in the trapping mode.
  3919. return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
  3920. !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
  3921. (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
  3922. !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
  3923. (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
  3924. !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
  3925. (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
  3926. !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
  3927. }
  3928. void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
  3929. CharUnits Offset,
  3930. const CXXRecordDecl *RD) {
  3931. llvm::Metadata *MD =
  3932. CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
  3933. VTable->addTypeMetadata(Offset.getQuantity(), MD);
  3934. if (CodeGenOpts.SanitizeCfiCrossDso)
  3935. if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
  3936. VTable->addTypeMetadata(Offset.getQuantity(),
  3937. llvm::ConstantAsMetadata::get(CrossDsoTypeId));
  3938. if (NeedAllVtablesTypeId()) {
  3939. llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
  3940. VTable->addTypeMetadata(Offset.getQuantity(), MD);
  3941. }
  3942. }
  3943. // Fills in the supplied string map with the set of target features for the
  3944. // passed in function.
  3945. void CodeGenModule::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
  3946. const FunctionDecl *FD) {
  3947. StringRef TargetCPU = Target.getTargetOpts().CPU;
  3948. if (const auto *TD = FD->getAttr<TargetAttr>()) {
  3949. // If we have a TargetAttr build up the feature map based on that.
  3950. TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
  3951. // Make a copy of the features as passed on the command line into the
  3952. // beginning of the additional features from the function to override.
  3953. ParsedAttr.Features.insert(ParsedAttr.Features.begin(),
  3954. Target.getTargetOpts().FeaturesAsWritten.begin(),
  3955. Target.getTargetOpts().FeaturesAsWritten.end());
  3956. if (ParsedAttr.Architecture != "")
  3957. TargetCPU = ParsedAttr.Architecture ;
  3958. // Now populate the feature map, first with the TargetCPU which is either
  3959. // the default or a new one from the target attribute string. Then we'll use
  3960. // the passed in features (FeaturesAsWritten) along with the new ones from
  3961. // the attribute.
  3962. Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
  3963. ParsedAttr.Features);
  3964. } else {
  3965. Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
  3966. Target.getTargetOpts().Features);
  3967. }
  3968. }
  3969. llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
  3970. if (!SanStats)
  3971. SanStats = llvm::make_unique<llvm::SanitizerStatReport>(&getModule());
  3972. return *SanStats;
  3973. }
  3974. llvm::Value *
  3975. CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
  3976. CodeGenFunction &CGF) {
  3977. llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType());
  3978. auto SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr());
  3979. auto FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
  3980. return CGF.Builder.CreateCall(CreateRuntimeFunction(FTy,
  3981. "__translate_sampler_initializer"),
  3982. {C});
  3983. }