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