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