CodeGenModule.cpp 161 KB

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