CodeGenModule.cpp 130 KB

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