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