CodeGenModule.cpp 136 KB

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