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