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