CodeGenModule.cpp 162 KB

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