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