xref: /llvm-project/clang/lib/CodeGen/CodeGenModule.cpp (revision 5a6b6987dcb4592427f4f3fcee9b7ce5dd3ba4fe)
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 "CGDebugInfo.h"
16 #include "CodeGenFunction.h"
17 #include "CodeGenTBAA.h"
18 #include "CGCall.h"
19 #include "CGCXXABI.h"
20 #include "CGObjCRuntime.h"
21 #include "TargetInfo.h"
22 #include "clang/Frontend/CodeGenOptions.h"
23 #include "clang/AST/ASTContext.h"
24 #include "clang/AST/CharUnits.h"
25 #include "clang/AST/DeclObjC.h"
26 #include "clang/AST/DeclCXX.h"
27 #include "clang/AST/DeclTemplate.h"
28 #include "clang/AST/Mangle.h"
29 #include "clang/AST/RecordLayout.h"
30 #include "clang/Basic/Builtins.h"
31 #include "clang/Basic/Diagnostic.h"
32 #include "clang/Basic/SourceManager.h"
33 #include "clang/Basic/TargetInfo.h"
34 #include "clang/Basic/ConvertUTF.h"
35 #include "llvm/CallingConv.h"
36 #include "llvm/Module.h"
37 #include "llvm/Intrinsics.h"
38 #include "llvm/LLVMContext.h"
39 #include "llvm/ADT/Triple.h"
40 #include "llvm/Target/Mangler.h"
41 #include "llvm/Target/TargetData.h"
42 #include "llvm/Support/CallSite.h"
43 #include "llvm/Support/ErrorHandling.h"
44 using namespace clang;
45 using namespace CodeGen;
46 
47 static const char AnnotationSection[] = "llvm.metadata";
48 
49 static CGCXXABI &createCXXABI(CodeGenModule &CGM) {
50   switch (CGM.getContext().getTargetInfo().getCXXABI()) {
51   case CXXABI_ARM: return *CreateARMCXXABI(CGM);
52   case CXXABI_Itanium: return *CreateItaniumCXXABI(CGM);
53   case CXXABI_Microsoft: return *CreateMicrosoftCXXABI(CGM);
54   }
55 
56   llvm_unreachable("invalid C++ ABI kind");
57   return *CreateItaniumCXXABI(CGM);
58 }
59 
60 
61 CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO,
62                              llvm::Module &M, const llvm::TargetData &TD,
63                              Diagnostic &diags)
64   : Context(C), Features(C.getLangOptions()), CodeGenOpts(CGO), TheModule(M),
65     TheTargetData(TD), TheTargetCodeGenInfo(0), Diags(diags),
66     ABI(createCXXABI(*this)),
67     Types(C, M, TD, getTargetCodeGenInfo().getABIInfo(), ABI, CGO),
68     TBAA(0),
69     VTables(*this), ObjCRuntime(0), DebugInfo(0), ARCData(0), RRData(0),
70     CFConstantStringClassRef(0), ConstantStringClassRef(0),
71     NSConstantStringType(0),
72     VMContext(M.getContext()),
73     NSConcreteGlobalBlock(0), NSConcreteStackBlock(0),
74     BlockObjectAssign(0), BlockObjectDispose(0),
75     BlockDescriptorType(0), GenericBlockLiteralType(0) {
76   if (Features.ObjC1)
77      createObjCRuntime();
78 
79   // Enable TBAA unless it's suppressed.
80   if (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0)
81     TBAA = new CodeGenTBAA(Context, VMContext, getLangOptions(),
82                            ABI.getMangleContext());
83 
84   // If debug info or coverage generation is enabled, create the CGDebugInfo
85   // object.
86   if (CodeGenOpts.DebugInfo || CodeGenOpts.EmitGcovArcs ||
87       CodeGenOpts.EmitGcovNotes)
88     DebugInfo = new CGDebugInfo(*this);
89 
90   Block.GlobalUniqueCount = 0;
91 
92   if (C.getLangOptions().ObjCAutoRefCount)
93     ARCData = new ARCEntrypoints();
94   RRData = new RREntrypoints();
95 
96   // Initialize the type cache.
97   llvm::LLVMContext &LLVMContext = M.getContext();
98   VoidTy = llvm::Type::getVoidTy(LLVMContext);
99   Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
100   Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
101   Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
102   PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
103   PointerAlignInBytes =
104     C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
105   IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
106   IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits);
107   Int8PtrTy = Int8Ty->getPointerTo(0);
108   Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
109 }
110 
111 CodeGenModule::~CodeGenModule() {
112   delete ObjCRuntime;
113   delete &ABI;
114   delete TBAA;
115   delete DebugInfo;
116   delete ARCData;
117   delete RRData;
118 }
119 
120 void CodeGenModule::createObjCRuntime() {
121   if (!Features.NeXTRuntime)
122     ObjCRuntime = CreateGNUObjCRuntime(*this);
123   else
124     ObjCRuntime = CreateMacObjCRuntime(*this);
125 }
126 
127 void CodeGenModule::Release() {
128   EmitDeferred();
129   EmitCXXGlobalInitFunc();
130   EmitCXXGlobalDtorFunc();
131   if (ObjCRuntime)
132     if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
133       AddGlobalCtor(ObjCInitFunction);
134   EmitCtorList(GlobalCtors, "llvm.global_ctors");
135   EmitCtorList(GlobalDtors, "llvm.global_dtors");
136   EmitGlobalAnnotations();
137   EmitLLVMUsed();
138 
139   SimplifyPersonality();
140 
141   if (getCodeGenOpts().EmitDeclMetadata)
142     EmitDeclMetadata();
143 
144   if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
145     EmitCoverageFile();
146 
147   if (DebugInfo)
148     DebugInfo->finalize();
149 }
150 
151 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
152   // Make sure that this type is translated.
153   Types.UpdateCompletedType(TD);
154   if (DebugInfo)
155     DebugInfo->UpdateCompletedType(TD);
156 }
157 
158 llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
159   if (!TBAA)
160     return 0;
161   return TBAA->getTBAAInfo(QTy);
162 }
163 
164 void CodeGenModule::DecorateInstruction(llvm::Instruction *Inst,
165                                         llvm::MDNode *TBAAInfo) {
166   Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
167 }
168 
169 bool CodeGenModule::isTargetDarwin() const {
170   return getContext().getTargetInfo().getTriple().isOSDarwin();
171 }
172 
173 void CodeGenModule::Error(SourceLocation loc, StringRef error) {
174   unsigned diagID = getDiags().getCustomDiagID(Diagnostic::Error, error);
175   getDiags().Report(Context.getFullLoc(loc), diagID);
176 }
177 
178 /// ErrorUnsupported - Print out an error that codegen doesn't support the
179 /// specified stmt yet.
180 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
181                                      bool OmitOnError) {
182   if (OmitOnError && getDiags().hasErrorOccurred())
183     return;
184   unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
185                                                "cannot compile this %0 yet");
186   std::string Msg = Type;
187   getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
188     << Msg << S->getSourceRange();
189 }
190 
191 /// ErrorUnsupported - Print out an error that codegen doesn't support the
192 /// specified decl yet.
193 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
194                                      bool OmitOnError) {
195   if (OmitOnError && getDiags().hasErrorOccurred())
196     return;
197   unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
198                                                "cannot compile this %0 yet");
199   std::string Msg = Type;
200   getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
201 }
202 
203 llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
204   return llvm::ConstantInt::get(SizeTy, size.getQuantity());
205 }
206 
207 void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
208                                         const NamedDecl *D) const {
209   // Internal definitions always have default visibility.
210   if (GV->hasLocalLinkage()) {
211     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
212     return;
213   }
214 
215   // Set visibility for definitions.
216   NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
217   if (LV.visibilityExplicit() || !GV->hasAvailableExternallyLinkage())
218     GV->setVisibility(GetLLVMVisibility(LV.visibility()));
219 }
220 
221 /// Set the symbol visibility of type information (vtable and RTTI)
222 /// associated with the given type.
223 void CodeGenModule::setTypeVisibility(llvm::GlobalValue *GV,
224                                       const CXXRecordDecl *RD,
225                                       TypeVisibilityKind TVK) const {
226   setGlobalVisibility(GV, RD);
227 
228   if (!CodeGenOpts.HiddenWeakVTables)
229     return;
230 
231   // We never want to drop the visibility for RTTI names.
232   if (TVK == TVK_ForRTTIName)
233     return;
234 
235   // We want to drop the visibility to hidden for weak type symbols.
236   // This isn't possible if there might be unresolved references
237   // elsewhere that rely on this symbol being visible.
238 
239   // This should be kept roughly in sync with setThunkVisibility
240   // in CGVTables.cpp.
241 
242   // Preconditions.
243   if (GV->getLinkage() != llvm::GlobalVariable::LinkOnceODRLinkage ||
244       GV->getVisibility() != llvm::GlobalVariable::DefaultVisibility)
245     return;
246 
247   // Don't override an explicit visibility attribute.
248   if (RD->getExplicitVisibility())
249     return;
250 
251   switch (RD->getTemplateSpecializationKind()) {
252   // We have to disable the optimization if this is an EI definition
253   // because there might be EI declarations in other shared objects.
254   case TSK_ExplicitInstantiationDefinition:
255   case TSK_ExplicitInstantiationDeclaration:
256     return;
257 
258   // Every use of a non-template class's type information has to emit it.
259   case TSK_Undeclared:
260     break;
261 
262   // In theory, implicit instantiations can ignore the possibility of
263   // an explicit instantiation declaration because there necessarily
264   // must be an EI definition somewhere with default visibility.  In
265   // practice, it's possible to have an explicit instantiation for
266   // an arbitrary template class, and linkers aren't necessarily able
267   // to deal with mixed-visibility symbols.
268   case TSK_ExplicitSpecialization:
269   case TSK_ImplicitInstantiation:
270     if (!CodeGenOpts.HiddenWeakTemplateVTables)
271       return;
272     break;
273   }
274 
275   // If there's a key function, there may be translation units
276   // that don't have the key function's definition.  But ignore
277   // this if we're emitting RTTI under -fno-rtti.
278   if (!(TVK != TVK_ForRTTI) || Features.RTTI) {
279     if (Context.getKeyFunction(RD))
280       return;
281   }
282 
283   // Otherwise, drop the visibility to hidden.
284   GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
285   GV->setUnnamedAddr(true);
286 }
287 
288 StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
289   const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
290 
291   StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()];
292   if (!Str.empty())
293     return Str;
294 
295   if (!getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
296     IdentifierInfo *II = ND->getIdentifier();
297     assert(II && "Attempt to mangle unnamed decl.");
298 
299     Str = II->getName();
300     return Str;
301   }
302 
303   llvm::SmallString<256> Buffer;
304   llvm::raw_svector_ostream Out(Buffer);
305   if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND))
306     getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
307   else if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND))
308     getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
309   else if (const BlockDecl *BD = dyn_cast<BlockDecl>(ND))
310     getCXXABI().getMangleContext().mangleBlock(BD, Out);
311   else
312     getCXXABI().getMangleContext().mangleName(ND, Out);
313 
314   // Allocate space for the mangled name.
315   Out.flush();
316   size_t Length = Buffer.size();
317   char *Name = MangledNamesAllocator.Allocate<char>(Length);
318   std::copy(Buffer.begin(), Buffer.end(), Name);
319 
320   Str = StringRef(Name, Length);
321 
322   return Str;
323 }
324 
325 void CodeGenModule::getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer,
326                                         const BlockDecl *BD) {
327   MangleContext &MangleCtx = getCXXABI().getMangleContext();
328   const Decl *D = GD.getDecl();
329   llvm::raw_svector_ostream Out(Buffer.getBuffer());
330   if (D == 0)
331     MangleCtx.mangleGlobalBlock(BD, Out);
332   else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
333     MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
334   else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D))
335     MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
336   else
337     MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
338 }
339 
340 llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
341   return getModule().getNamedValue(Name);
342 }
343 
344 /// AddGlobalCtor - Add a function to the list that will be called before
345 /// main() runs.
346 void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
347   // FIXME: Type coercion of void()* types.
348   GlobalCtors.push_back(std::make_pair(Ctor, Priority));
349 }
350 
351 /// AddGlobalDtor - Add a function to the list that will be called
352 /// when the module is unloaded.
353 void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
354   // FIXME: Type coercion of void()* types.
355   GlobalDtors.push_back(std::make_pair(Dtor, Priority));
356 }
357 
358 void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
359   // Ctor function type is void()*.
360   llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
361   llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
362 
363   // Get the type of a ctor entry, { i32, void ()* }.
364   llvm::StructType *CtorStructTy =
365     llvm::StructType::get(llvm::Type::getInt32Ty(VMContext),
366                           llvm::PointerType::getUnqual(CtorFTy), NULL);
367 
368   // Construct the constructor and destructor arrays.
369   std::vector<llvm::Constant*> Ctors;
370   for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
371     std::vector<llvm::Constant*> S;
372     S.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
373                 I->second, false));
374     S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
375     Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
376   }
377 
378   if (!Ctors.empty()) {
379     llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
380     new llvm::GlobalVariable(TheModule, AT, false,
381                              llvm::GlobalValue::AppendingLinkage,
382                              llvm::ConstantArray::get(AT, Ctors),
383                              GlobalName);
384   }
385 }
386 
387 llvm::GlobalValue::LinkageTypes
388 CodeGenModule::getFunctionLinkage(const FunctionDecl *D) {
389   GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
390 
391   if (Linkage == GVA_Internal)
392     return llvm::Function::InternalLinkage;
393 
394   if (D->hasAttr<DLLExportAttr>())
395     return llvm::Function::DLLExportLinkage;
396 
397   if (D->hasAttr<WeakAttr>())
398     return llvm::Function::WeakAnyLinkage;
399 
400   // In C99 mode, 'inline' functions are guaranteed to have a strong
401   // definition somewhere else, so we can use available_externally linkage.
402   if (Linkage == GVA_C99Inline)
403     return llvm::Function::AvailableExternallyLinkage;
404 
405   // In C++, the compiler has to emit a definition in every translation unit
406   // that references the function.  We should use linkonce_odr because
407   // a) if all references in this translation unit are optimized away, we
408   // don't need to codegen it.  b) if the function persists, it needs to be
409   // merged with other definitions. c) C++ has the ODR, so we know the
410   // definition is dependable.
411   if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
412     return !Context.getLangOptions().AppleKext
413              ? llvm::Function::LinkOnceODRLinkage
414              : llvm::Function::InternalLinkage;
415 
416   // An explicit instantiation of a template has weak linkage, since
417   // explicit instantiations can occur in multiple translation units
418   // and must all be equivalent. However, we are not allowed to
419   // throw away these explicit instantiations.
420   if (Linkage == GVA_ExplicitTemplateInstantiation)
421     return !Context.getLangOptions().AppleKext
422              ? llvm::Function::WeakODRLinkage
423              : llvm::Function::InternalLinkage;
424 
425   // Otherwise, we have strong external linkage.
426   assert(Linkage == GVA_StrongExternal);
427   return llvm::Function::ExternalLinkage;
428 }
429 
430 
431 /// SetFunctionDefinitionAttributes - Set attributes for a global.
432 ///
433 /// FIXME: This is currently only done for aliases and functions, but not for
434 /// variables (these details are set in EmitGlobalVarDefinition for variables).
435 void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D,
436                                                     llvm::GlobalValue *GV) {
437   SetCommonAttributes(D, GV);
438 }
439 
440 void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
441                                               const CGFunctionInfo &Info,
442                                               llvm::Function *F) {
443   unsigned CallingConv;
444   AttributeListType AttributeList;
445   ConstructAttributeList(Info, D, AttributeList, CallingConv);
446   F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
447                                           AttributeList.size()));
448   F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
449 }
450 
451 void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
452                                                            llvm::Function *F) {
453   if (CodeGenOpts.UnwindTables)
454     F->setHasUWTable();
455 
456   if (!Features.Exceptions && !Features.ObjCNonFragileABI)
457     F->addFnAttr(llvm::Attribute::NoUnwind);
458 
459   if (D->hasAttr<NakedAttr>()) {
460     // Naked implies noinline: we should not be inlining such functions.
461     F->addFnAttr(llvm::Attribute::Naked);
462     F->addFnAttr(llvm::Attribute::NoInline);
463   }
464 
465   if (D->hasAttr<NoInlineAttr>())
466     F->addFnAttr(llvm::Attribute::NoInline);
467 
468   // (noinline wins over always_inline, and we can't specify both in IR)
469   if (D->hasAttr<AlwaysInlineAttr>() &&
470       !F->hasFnAttr(llvm::Attribute::NoInline))
471     F->addFnAttr(llvm::Attribute::AlwaysInline);
472 
473   if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
474     F->setUnnamedAddr(true);
475 
476   if (Features.getStackProtectorMode() == LangOptions::SSPOn)
477     F->addFnAttr(llvm::Attribute::StackProtect);
478   else if (Features.getStackProtectorMode() == LangOptions::SSPReq)
479     F->addFnAttr(llvm::Attribute::StackProtectReq);
480 
481   unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
482   if (alignment)
483     F->setAlignment(alignment);
484 
485   // C++ ABI requires 2-byte alignment for member functions.
486   if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
487     F->setAlignment(2);
488 }
489 
490 void CodeGenModule::SetCommonAttributes(const Decl *D,
491                                         llvm::GlobalValue *GV) {
492   if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
493     setGlobalVisibility(GV, ND);
494   else
495     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
496 
497   if (D->hasAttr<UsedAttr>())
498     AddUsedGlobal(GV);
499 
500   if (const SectionAttr *SA = D->getAttr<SectionAttr>())
501     GV->setSection(SA->getName());
502 
503   getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this);
504 }
505 
506 void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
507                                                   llvm::Function *F,
508                                                   const CGFunctionInfo &FI) {
509   SetLLVMFunctionAttributes(D, FI, F);
510   SetLLVMFunctionAttributesForDefinition(D, F);
511 
512   F->setLinkage(llvm::Function::InternalLinkage);
513 
514   SetCommonAttributes(D, F);
515 }
516 
517 void CodeGenModule::SetFunctionAttributes(GlobalDecl GD,
518                                           llvm::Function *F,
519                                           bool IsIncompleteFunction) {
520   if (unsigned IID = F->getIntrinsicID()) {
521     // If this is an intrinsic function, set the function's attributes
522     // to the intrinsic's attributes.
523     F->setAttributes(llvm::Intrinsic::getAttributes((llvm::Intrinsic::ID)IID));
524     return;
525   }
526 
527   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
528 
529   if (!IsIncompleteFunction)
530     SetLLVMFunctionAttributes(FD, getTypes().getFunctionInfo(GD), F);
531 
532   // Only a few attributes are set on declarations; these may later be
533   // overridden by a definition.
534 
535   if (FD->hasAttr<DLLImportAttr>()) {
536     F->setLinkage(llvm::Function::DLLImportLinkage);
537   } else if (FD->hasAttr<WeakAttr>() ||
538              FD->isWeakImported()) {
539     // "extern_weak" is overloaded in LLVM; we probably should have
540     // separate linkage types for this.
541     F->setLinkage(llvm::Function::ExternalWeakLinkage);
542   } else {
543     F->setLinkage(llvm::Function::ExternalLinkage);
544 
545     NamedDecl::LinkageInfo LV = FD->getLinkageAndVisibility();
546     if (LV.linkage() == ExternalLinkage && LV.visibilityExplicit()) {
547       F->setVisibility(GetLLVMVisibility(LV.visibility()));
548     }
549   }
550 
551   if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
552     F->setSection(SA->getName());
553 }
554 
555 void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
556   assert(!GV->isDeclaration() &&
557          "Only globals with definition can force usage.");
558   LLVMUsed.push_back(GV);
559 }
560 
561 void CodeGenModule::EmitLLVMUsed() {
562   // Don't create llvm.used if there is no need.
563   if (LLVMUsed.empty())
564     return;
565 
566   llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(VMContext);
567 
568   // Convert LLVMUsed to what ConstantArray needs.
569   std::vector<llvm::Constant*> UsedArray;
570   UsedArray.resize(LLVMUsed.size());
571   for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) {
572     UsedArray[i] =
573      llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]),
574                                       i8PTy);
575   }
576 
577   if (UsedArray.empty())
578     return;
579   llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, UsedArray.size());
580 
581   llvm::GlobalVariable *GV =
582     new llvm::GlobalVariable(getModule(), ATy, false,
583                              llvm::GlobalValue::AppendingLinkage,
584                              llvm::ConstantArray::get(ATy, UsedArray),
585                              "llvm.used");
586 
587   GV->setSection("llvm.metadata");
588 }
589 
590 void CodeGenModule::EmitDeferred() {
591   // Emit code for any potentially referenced deferred decls.  Since a
592   // previously unused static decl may become used during the generation of code
593   // for a static function, iterate until no changes are made.
594 
595   while (!DeferredDeclsToEmit.empty() || !DeferredVTables.empty()) {
596     if (!DeferredVTables.empty()) {
597       const CXXRecordDecl *RD = DeferredVTables.back();
598       DeferredVTables.pop_back();
599       getVTables().GenerateClassData(getVTableLinkage(RD), RD);
600       continue;
601     }
602 
603     GlobalDecl D = DeferredDeclsToEmit.back();
604     DeferredDeclsToEmit.pop_back();
605 
606     // Check to see if we've already emitted this.  This is necessary
607     // for a couple of reasons: first, decls can end up in the
608     // deferred-decls queue multiple times, and second, decls can end
609     // up with definitions in unusual ways (e.g. by an extern inline
610     // function acquiring a strong function redefinition).  Just
611     // ignore these cases.
612     //
613     // TODO: That said, looking this up multiple times is very wasteful.
614     StringRef Name = getMangledName(D);
615     llvm::GlobalValue *CGRef = GetGlobalValue(Name);
616     assert(CGRef && "Deferred decl wasn't referenced?");
617 
618     if (!CGRef->isDeclaration())
619       continue;
620 
621     // GlobalAlias::isDeclaration() defers to the aliasee, but for our
622     // purposes an alias counts as a definition.
623     if (isa<llvm::GlobalAlias>(CGRef))
624       continue;
625 
626     // Otherwise, emit the definition and move on to the next one.
627     EmitGlobalDefinition(D);
628   }
629 }
630 
631 void CodeGenModule::EmitGlobalAnnotations() {
632   if (Annotations.empty())
633     return;
634 
635   // Create a new global variable for the ConstantStruct in the Module.
636   llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
637     Annotations[0]->getType(), Annotations.size()), Annotations);
638   llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(),
639     Array->getType(), false, llvm::GlobalValue::AppendingLinkage, Array,
640     "llvm.global.annotations");
641   gv->setSection(AnnotationSection);
642 }
643 
644 llvm::Constant *CodeGenModule::EmitAnnotationString(llvm::StringRef Str) {
645   llvm::StringMap<llvm::Constant*>::iterator i = AnnotationStrings.find(Str);
646   if (i != AnnotationStrings.end())
647     return i->second;
648 
649   // Not found yet, create a new global.
650   llvm::Constant *s = llvm::ConstantArray::get(getLLVMContext(), Str, true);
651   llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(), s->getType(),
652     true, llvm::GlobalValue::PrivateLinkage, s, ".str");
653   gv->setSection(AnnotationSection);
654   gv->setUnnamedAddr(true);
655   AnnotationStrings[Str] = gv;
656   return gv;
657 }
658 
659 llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
660   SourceManager &SM = getContext().getSourceManager();
661   PresumedLoc PLoc = SM.getPresumedLoc(Loc);
662   if (PLoc.isValid())
663     return EmitAnnotationString(PLoc.getFilename());
664   return EmitAnnotationString(SM.getBufferName(Loc));
665 }
666 
667 llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
668   SourceManager &SM = getContext().getSourceManager();
669   PresumedLoc PLoc = SM.getPresumedLoc(L);
670   unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
671     SM.getExpansionLineNumber(L);
672   return llvm::ConstantInt::get(Int32Ty, LineNo);
673 }
674 
675 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
676                                                 const AnnotateAttr *AA,
677                                                 SourceLocation L) {
678   // Get the globals for file name, annotation, and the line number.
679   llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
680                  *UnitGV = EmitAnnotationUnit(L),
681                  *LineNoCst = EmitAnnotationLineNo(L);
682 
683   // Create the ConstantStruct for the global annotation.
684   llvm::Constant *Fields[4] = {
685     llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
686     llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
687     llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
688     LineNoCst
689   };
690   return llvm::ConstantStruct::getAnon(Fields);
691 }
692 
693 void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
694                                          llvm::GlobalValue *GV) {
695   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
696   // Get the struct elements for these annotations.
697   for (specific_attr_iterator<AnnotateAttr>
698        ai = D->specific_attr_begin<AnnotateAttr>(),
699        ae = D->specific_attr_end<AnnotateAttr>(); ai != ae; ++ai)
700     Annotations.push_back(EmitAnnotateAttr(GV, *ai, D->getLocation()));
701 }
702 
703 bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
704   // Never defer when EmitAllDecls is specified.
705   if (Features.EmitAllDecls)
706     return false;
707 
708   return !getContext().DeclMustBeEmitted(Global);
709 }
710 
711 llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
712   const AliasAttr *AA = VD->getAttr<AliasAttr>();
713   assert(AA && "No alias?");
714 
715   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
716 
717   // See if there is already something with the target's name in the module.
718   llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
719 
720   llvm::Constant *Aliasee;
721   if (isa<llvm::FunctionType>(DeclTy))
722     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl(),
723                                       /*ForVTable=*/false);
724   else
725     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
726                                     llvm::PointerType::getUnqual(DeclTy), 0);
727   if (!Entry) {
728     llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee);
729     F->setLinkage(llvm::Function::ExternalWeakLinkage);
730     WeakRefReferences.insert(F);
731   }
732 
733   return Aliasee;
734 }
735 
736 void CodeGenModule::EmitGlobal(GlobalDecl GD) {
737   const ValueDecl *Global = cast<ValueDecl>(GD.getDecl());
738 
739   // Weak references don't produce any output by themselves.
740   if (Global->hasAttr<WeakRefAttr>())
741     return;
742 
743   // If this is an alias definition (which otherwise looks like a declaration)
744   // emit it now.
745   if (Global->hasAttr<AliasAttr>())
746     return EmitAliasDefinition(GD);
747 
748   // Ignore declarations, they will be emitted on their first use.
749   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
750     // Forward declarations are emitted lazily on first use.
751     if (!FD->doesThisDeclarationHaveABody()) {
752       if (!FD->doesDeclarationForceExternallyVisibleDefinition())
753         return;
754 
755       const FunctionDecl *InlineDefinition = 0;
756       FD->getBody(InlineDefinition);
757 
758       StringRef MangledName = getMangledName(GD);
759       llvm::StringMap<GlobalDecl>::iterator DDI =
760           DeferredDecls.find(MangledName);
761       if (DDI != DeferredDecls.end())
762         DeferredDecls.erase(DDI);
763       EmitGlobalDefinition(InlineDefinition);
764       return;
765     }
766   } else {
767     const VarDecl *VD = cast<VarDecl>(Global);
768     assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
769 
770     if (VD->isThisDeclarationADefinition() != VarDecl::Definition)
771       return;
772   }
773 
774   // Defer code generation when possible if this is a static definition, inline
775   // function etc.  These we only want to emit if they are used.
776   if (!MayDeferGeneration(Global)) {
777     // Emit the definition if it can't be deferred.
778     EmitGlobalDefinition(GD);
779     return;
780   }
781 
782   // If we're deferring emission of a C++ variable with an
783   // initializer, remember the order in which it appeared in the file.
784   if (getLangOptions().CPlusPlus && isa<VarDecl>(Global) &&
785       cast<VarDecl>(Global)->hasInit()) {
786     DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
787     CXXGlobalInits.push_back(0);
788   }
789 
790   // If the value has already been used, add it directly to the
791   // DeferredDeclsToEmit list.
792   StringRef MangledName = getMangledName(GD);
793   if (GetGlobalValue(MangledName))
794     DeferredDeclsToEmit.push_back(GD);
795   else {
796     // Otherwise, remember that we saw a deferred decl with this name.  The
797     // first use of the mangled name will cause it to move into
798     // DeferredDeclsToEmit.
799     DeferredDecls[MangledName] = GD;
800   }
801 }
802 
803 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) {
804   const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
805 
806   PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
807                                  Context.getSourceManager(),
808                                  "Generating code for declaration");
809 
810   if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
811     // At -O0, don't generate IR for functions with available_externally
812     // linkage.
813     if (CodeGenOpts.OptimizationLevel == 0 &&
814         !Function->hasAttr<AlwaysInlineAttr>() &&
815         getFunctionLinkage(Function)
816                                   == llvm::Function::AvailableExternallyLinkage)
817       return;
818 
819     if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
820       // Make sure to emit the definition(s) before we emit the thunks.
821       // This is necessary for the generation of certain thunks.
822       if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
823         EmitCXXConstructor(CD, GD.getCtorType());
824       else if (const CXXDestructorDecl *DD =dyn_cast<CXXDestructorDecl>(Method))
825         EmitCXXDestructor(DD, GD.getDtorType());
826       else
827         EmitGlobalFunctionDefinition(GD);
828 
829       if (Method->isVirtual())
830         getVTables().EmitThunks(GD);
831 
832       return;
833     }
834 
835     return EmitGlobalFunctionDefinition(GD);
836   }
837 
838   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
839     return EmitGlobalVarDefinition(VD);
840 
841   assert(0 && "Invalid argument to EmitGlobalDefinition()");
842 }
843 
844 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
845 /// module, create and return an llvm Function with the specified type. If there
846 /// is something in the module with the specified name, return it potentially
847 /// bitcasted to the right type.
848 ///
849 /// If D is non-null, it specifies a decl that correspond to this.  This is used
850 /// to set the attributes on the function when it is first created.
851 llvm::Constant *
852 CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName,
853                                        llvm::Type *Ty,
854                                        GlobalDecl D, bool ForVTable,
855                                        llvm::Attributes ExtraAttrs) {
856   // Lookup the entry, lazily creating it if necessary.
857   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
858   if (Entry) {
859     if (WeakRefReferences.count(Entry)) {
860       const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl());
861       if (FD && !FD->hasAttr<WeakAttr>())
862         Entry->setLinkage(llvm::Function::ExternalLinkage);
863 
864       WeakRefReferences.erase(Entry);
865     }
866 
867     if (Entry->getType()->getElementType() == Ty)
868       return Entry;
869 
870     // Make sure the result is of the correct type.
871     return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
872   }
873 
874   // This function doesn't have a complete type (for example, the return
875   // type is an incomplete struct). Use a fake type instead, and make
876   // sure not to try to set attributes.
877   bool IsIncompleteFunction = false;
878 
879   llvm::FunctionType *FTy;
880   if (isa<llvm::FunctionType>(Ty)) {
881     FTy = cast<llvm::FunctionType>(Ty);
882   } else {
883     FTy = llvm::FunctionType::get(VoidTy, false);
884     IsIncompleteFunction = true;
885   }
886 
887   llvm::Function *F = llvm::Function::Create(FTy,
888                                              llvm::Function::ExternalLinkage,
889                                              MangledName, &getModule());
890   assert(F->getName() == MangledName && "name was uniqued!");
891   if (D.getDecl())
892     SetFunctionAttributes(D, F, IsIncompleteFunction);
893   if (ExtraAttrs != llvm::Attribute::None)
894     F->addFnAttr(ExtraAttrs);
895 
896   // This is the first use or definition of a mangled name.  If there is a
897   // deferred decl with this name, remember that we need to emit it at the end
898   // of the file.
899   llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
900   if (DDI != DeferredDecls.end()) {
901     // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
902     // list, and remove it from DeferredDecls (since we don't need it anymore).
903     DeferredDeclsToEmit.push_back(DDI->second);
904     DeferredDecls.erase(DDI);
905 
906   // Otherwise, there are cases we have to worry about where we're
907   // using a declaration for which we must emit a definition but where
908   // we might not find a top-level definition:
909   //   - member functions defined inline in their classes
910   //   - friend functions defined inline in some class
911   //   - special member functions with implicit definitions
912   // If we ever change our AST traversal to walk into class methods,
913   // this will be unnecessary.
914   //
915   // We also don't emit a definition for a function if it's going to be an entry
916   // in a vtable, unless it's already marked as used.
917   } else if (getLangOptions().CPlusPlus && D.getDecl()) {
918     // Look for a declaration that's lexically in a record.
919     const FunctionDecl *FD = cast<FunctionDecl>(D.getDecl());
920     do {
921       if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
922         if (FD->isImplicit() && !ForVTable) {
923           assert(FD->isUsed() && "Sema didn't mark implicit function as used!");
924           DeferredDeclsToEmit.push_back(D.getWithDecl(FD));
925           break;
926         } else if (FD->doesThisDeclarationHaveABody()) {
927           DeferredDeclsToEmit.push_back(D.getWithDecl(FD));
928           break;
929         }
930       }
931       FD = FD->getPreviousDeclaration();
932     } while (FD);
933   }
934 
935   // Make sure the result is of the requested type.
936   if (!IsIncompleteFunction) {
937     assert(F->getType()->getElementType() == Ty);
938     return F;
939   }
940 
941   llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
942   return llvm::ConstantExpr::getBitCast(F, PTy);
943 }
944 
945 /// GetAddrOfFunction - Return the address of the given function.  If Ty is
946 /// non-null, then this function will use the specified type if it has to
947 /// create it (this occurs when we see a definition of the function).
948 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
949                                                  llvm::Type *Ty,
950                                                  bool ForVTable) {
951   // If there was no specific requested type, just convert it now.
952   if (!Ty)
953     Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
954 
955   StringRef MangledName = getMangledName(GD);
956   return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable);
957 }
958 
959 /// CreateRuntimeFunction - Create a new runtime function with the specified
960 /// type and name.
961 llvm::Constant *
962 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy,
963                                      StringRef Name,
964                                      llvm::Attributes ExtraAttrs) {
965   return GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
966                                  ExtraAttrs);
967 }
968 
969 static bool DeclIsConstantGlobal(ASTContext &Context, const VarDecl *D,
970                                  bool ConstantInit) {
971   if (!D->getType().isConstant(Context) && !D->getType()->isReferenceType())
972     return false;
973 
974   if (Context.getLangOptions().CPlusPlus) {
975     if (const RecordType *Record
976           = Context.getBaseElementType(D->getType())->getAs<RecordType>())
977       return ConstantInit &&
978              cast<CXXRecordDecl>(Record->getDecl())->isPOD() &&
979              !cast<CXXRecordDecl>(Record->getDecl())->hasMutableFields();
980   }
981 
982   return true;
983 }
984 
985 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
986 /// create and return an llvm GlobalVariable with the specified type.  If there
987 /// is something in the module with the specified name, return it potentially
988 /// bitcasted to the right type.
989 ///
990 /// If D is non-null, it specifies a decl that correspond to this.  This is used
991 /// to set the attributes on the global when it is first created.
992 llvm::Constant *
993 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
994                                      llvm::PointerType *Ty,
995                                      const VarDecl *D,
996                                      bool UnnamedAddr) {
997   // Lookup the entry, lazily creating it if necessary.
998   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
999   if (Entry) {
1000     if (WeakRefReferences.count(Entry)) {
1001       if (D && !D->hasAttr<WeakAttr>())
1002         Entry->setLinkage(llvm::Function::ExternalLinkage);
1003 
1004       WeakRefReferences.erase(Entry);
1005     }
1006 
1007     if (UnnamedAddr)
1008       Entry->setUnnamedAddr(true);
1009 
1010     if (Entry->getType() == Ty)
1011       return Entry;
1012 
1013     // Make sure the result is of the correct type.
1014     return llvm::ConstantExpr::getBitCast(Entry, Ty);
1015   }
1016 
1017   // This is the first use or definition of a mangled name.  If there is a
1018   // deferred decl with this name, remember that we need to emit it at the end
1019   // of the file.
1020   llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
1021   if (DDI != DeferredDecls.end()) {
1022     // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
1023     // list, and remove it from DeferredDecls (since we don't need it anymore).
1024     DeferredDeclsToEmit.push_back(DDI->second);
1025     DeferredDecls.erase(DDI);
1026   }
1027 
1028   llvm::GlobalVariable *GV =
1029     new llvm::GlobalVariable(getModule(), Ty->getElementType(), false,
1030                              llvm::GlobalValue::ExternalLinkage,
1031                              0, MangledName, 0,
1032                              false, Ty->getAddressSpace());
1033 
1034   // Handle things which are present even on external declarations.
1035   if (D) {
1036     // FIXME: This code is overly simple and should be merged with other global
1037     // handling.
1038     GV->setConstant(DeclIsConstantGlobal(Context, D, false));
1039 
1040     // Set linkage and visibility in case we never see a definition.
1041     NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
1042     if (LV.linkage() != ExternalLinkage) {
1043       // Don't set internal linkage on declarations.
1044     } else {
1045       if (D->hasAttr<DLLImportAttr>())
1046         GV->setLinkage(llvm::GlobalValue::DLLImportLinkage);
1047       else if (D->hasAttr<WeakAttr>() || D->isWeakImported())
1048         GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
1049 
1050       // Set visibility on a declaration only if it's explicit.
1051       if (LV.visibilityExplicit())
1052         GV->setVisibility(GetLLVMVisibility(LV.visibility()));
1053     }
1054 
1055     GV->setThreadLocal(D->isThreadSpecified());
1056   }
1057 
1058   return GV;
1059 }
1060 
1061 
1062 llvm::GlobalVariable *
1063 CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
1064                                       llvm::Type *Ty,
1065                                       llvm::GlobalValue::LinkageTypes Linkage) {
1066   llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
1067   llvm::GlobalVariable *OldGV = 0;
1068 
1069 
1070   if (GV) {
1071     // Check if the variable has the right type.
1072     if (GV->getType()->getElementType() == Ty)
1073       return GV;
1074 
1075     // Because C++ name mangling, the only way we can end up with an already
1076     // existing global with the same name is if it has been declared extern "C".
1077       assert(GV->isDeclaration() && "Declaration has wrong type!");
1078     OldGV = GV;
1079   }
1080 
1081   // Create a new variable.
1082   GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
1083                                 Linkage, 0, Name);
1084 
1085   if (OldGV) {
1086     // Replace occurrences of the old variable if needed.
1087     GV->takeName(OldGV);
1088 
1089     if (!OldGV->use_empty()) {
1090       llvm::Constant *NewPtrForOldDecl =
1091       llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
1092       OldGV->replaceAllUsesWith(NewPtrForOldDecl);
1093     }
1094 
1095     OldGV->eraseFromParent();
1096   }
1097 
1098   return GV;
1099 }
1100 
1101 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
1102 /// given global variable.  If Ty is non-null and if the global doesn't exist,
1103 /// then it will be greated with the specified type instead of whatever the
1104 /// normal requested type would be.
1105 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
1106                                                   llvm::Type *Ty) {
1107   assert(D->hasGlobalStorage() && "Not a global variable");
1108   QualType ASTTy = D->getType();
1109   if (Ty == 0)
1110     Ty = getTypes().ConvertTypeForMem(ASTTy);
1111 
1112   llvm::PointerType *PTy =
1113     llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
1114 
1115   StringRef MangledName = getMangledName(D);
1116   return GetOrCreateLLVMGlobal(MangledName, PTy, D);
1117 }
1118 
1119 /// CreateRuntimeVariable - Create a new runtime global variable with the
1120 /// specified type and name.
1121 llvm::Constant *
1122 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
1123                                      StringRef Name) {
1124   return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0,
1125                                true);
1126 }
1127 
1128 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
1129   assert(!D->getInit() && "Cannot emit definite definitions here!");
1130 
1131   if (MayDeferGeneration(D)) {
1132     // If we have not seen a reference to this variable yet, place it
1133     // into the deferred declarations table to be emitted if needed
1134     // later.
1135     StringRef MangledName = getMangledName(D);
1136     if (!GetGlobalValue(MangledName)) {
1137       DeferredDecls[MangledName] = D;
1138       return;
1139     }
1140   }
1141 
1142   // The tentative definition is the only definition.
1143   EmitGlobalVarDefinition(D);
1144 }
1145 
1146 void CodeGenModule::EmitVTable(CXXRecordDecl *Class, bool DefinitionRequired) {
1147   if (DefinitionRequired)
1148     getVTables().GenerateClassData(getVTableLinkage(Class), Class);
1149 }
1150 
1151 llvm::GlobalVariable::LinkageTypes
1152 CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
1153   if (RD->getLinkage() != ExternalLinkage)
1154     return llvm::GlobalVariable::InternalLinkage;
1155 
1156   if (const CXXMethodDecl *KeyFunction
1157                                     = RD->getASTContext().getKeyFunction(RD)) {
1158     // If this class has a key function, use that to determine the linkage of
1159     // the vtable.
1160     const FunctionDecl *Def = 0;
1161     if (KeyFunction->hasBody(Def))
1162       KeyFunction = cast<CXXMethodDecl>(Def);
1163 
1164     switch (KeyFunction->getTemplateSpecializationKind()) {
1165       case TSK_Undeclared:
1166       case TSK_ExplicitSpecialization:
1167         // When compiling with optimizations turned on, we emit all vtables,
1168         // even if the key function is not defined in the current translation
1169         // unit. If this is the case, use available_externally linkage.
1170         if (!Def && CodeGenOpts.OptimizationLevel)
1171           return llvm::GlobalVariable::AvailableExternallyLinkage;
1172 
1173         if (KeyFunction->isInlined())
1174           return !Context.getLangOptions().AppleKext ?
1175                    llvm::GlobalVariable::LinkOnceODRLinkage :
1176                    llvm::Function::InternalLinkage;
1177 
1178         return llvm::GlobalVariable::ExternalLinkage;
1179 
1180       case TSK_ImplicitInstantiation:
1181         return !Context.getLangOptions().AppleKext ?
1182                  llvm::GlobalVariable::LinkOnceODRLinkage :
1183                  llvm::Function::InternalLinkage;
1184 
1185       case TSK_ExplicitInstantiationDefinition:
1186         return !Context.getLangOptions().AppleKext ?
1187                  llvm::GlobalVariable::WeakODRLinkage :
1188                  llvm::Function::InternalLinkage;
1189 
1190       case TSK_ExplicitInstantiationDeclaration:
1191         // FIXME: Use available_externally linkage. However, this currently
1192         // breaks LLVM's build due to undefined symbols.
1193         //      return llvm::GlobalVariable::AvailableExternallyLinkage;
1194         return !Context.getLangOptions().AppleKext ?
1195                  llvm::GlobalVariable::LinkOnceODRLinkage :
1196                  llvm::Function::InternalLinkage;
1197     }
1198   }
1199 
1200   if (Context.getLangOptions().AppleKext)
1201     return llvm::Function::InternalLinkage;
1202 
1203   switch (RD->getTemplateSpecializationKind()) {
1204   case TSK_Undeclared:
1205   case TSK_ExplicitSpecialization:
1206   case TSK_ImplicitInstantiation:
1207     // FIXME: Use available_externally linkage. However, this currently
1208     // breaks LLVM's build due to undefined symbols.
1209     //   return llvm::GlobalVariable::AvailableExternallyLinkage;
1210   case TSK_ExplicitInstantiationDeclaration:
1211     return llvm::GlobalVariable::LinkOnceODRLinkage;
1212 
1213   case TSK_ExplicitInstantiationDefinition:
1214       return llvm::GlobalVariable::WeakODRLinkage;
1215   }
1216 
1217   // Silence GCC warning.
1218   return llvm::GlobalVariable::LinkOnceODRLinkage;
1219 }
1220 
1221 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
1222     return Context.toCharUnitsFromBits(
1223       TheTargetData.getTypeStoreSizeInBits(Ty));
1224 }
1225 
1226 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
1227   llvm::Constant *Init = 0;
1228   QualType ASTTy = D->getType();
1229   bool NonConstInit = false;
1230 
1231   const Expr *InitExpr = D->getAnyInitializer();
1232 
1233   if (!InitExpr) {
1234     // This is a tentative definition; tentative definitions are
1235     // implicitly initialized with { 0 }.
1236     //
1237     // Note that tentative definitions are only emitted at the end of
1238     // a translation unit, so they should never have incomplete
1239     // type. In addition, EmitTentativeDefinition makes sure that we
1240     // never attempt to emit a tentative definition if a real one
1241     // exists. A use may still exists, however, so we still may need
1242     // to do a RAUW.
1243     assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
1244     Init = EmitNullConstant(D->getType());
1245   } else {
1246     Init = EmitConstantExpr(InitExpr, D->getType());
1247     if (!Init) {
1248       QualType T = InitExpr->getType();
1249       if (D->getType()->isReferenceType())
1250         T = D->getType();
1251 
1252       if (getLangOptions().CPlusPlus) {
1253         Init = EmitNullConstant(T);
1254         NonConstInit = true;
1255       } else {
1256         ErrorUnsupported(D, "static initializer");
1257         Init = llvm::UndefValue::get(getTypes().ConvertType(T));
1258       }
1259     } else {
1260       // We don't need an initializer, so remove the entry for the delayed
1261       // initializer position (just in case this entry was delayed).
1262       if (getLangOptions().CPlusPlus)
1263         DelayedCXXInitPosition.erase(D);
1264     }
1265   }
1266 
1267   llvm::Type* InitType = Init->getType();
1268   llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
1269 
1270   // Strip off a bitcast if we got one back.
1271   if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
1272     assert(CE->getOpcode() == llvm::Instruction::BitCast ||
1273            // all zero index gep.
1274            CE->getOpcode() == llvm::Instruction::GetElementPtr);
1275     Entry = CE->getOperand(0);
1276   }
1277 
1278   // Entry is now either a Function or GlobalVariable.
1279   llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
1280 
1281   // We have a definition after a declaration with the wrong type.
1282   // We must make a new GlobalVariable* and update everything that used OldGV
1283   // (a declaration or tentative definition) with the new GlobalVariable*
1284   // (which will be a definition).
1285   //
1286   // This happens if there is a prototype for a global (e.g.
1287   // "extern int x[];") and then a definition of a different type (e.g.
1288   // "int x[10];"). This also happens when an initializer has a different type
1289   // from the type of the global (this happens with unions).
1290   if (GV == 0 ||
1291       GV->getType()->getElementType() != InitType ||
1292       GV->getType()->getAddressSpace() !=
1293         getContext().getTargetAddressSpace(ASTTy)) {
1294 
1295     // Move the old entry aside so that we'll create a new one.
1296     Entry->setName(StringRef());
1297 
1298     // Make a new global with the correct type, this is now guaranteed to work.
1299     GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
1300 
1301     // Replace all uses of the old global with the new global
1302     llvm::Constant *NewPtrForOldDecl =
1303         llvm::ConstantExpr::getBitCast(GV, Entry->getType());
1304     Entry->replaceAllUsesWith(NewPtrForOldDecl);
1305 
1306     // Erase the old global, since it is no longer used.
1307     cast<llvm::GlobalValue>(Entry)->eraseFromParent();
1308   }
1309 
1310   if (D->hasAttr<AnnotateAttr>())
1311     AddGlobalAnnotations(D, GV);
1312 
1313   GV->setInitializer(Init);
1314 
1315   // If it is safe to mark the global 'constant', do so now.
1316   GV->setConstant(false);
1317   if (!NonConstInit && DeclIsConstantGlobal(Context, D, true))
1318     GV->setConstant(true);
1319 
1320   GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
1321 
1322   // Set the llvm linkage type as appropriate.
1323   llvm::GlobalValue::LinkageTypes Linkage =
1324     GetLLVMLinkageVarDefinition(D, GV);
1325   GV->setLinkage(Linkage);
1326   if (Linkage == llvm::GlobalVariable::CommonLinkage)
1327     // common vars aren't constant even if declared const.
1328     GV->setConstant(false);
1329 
1330   SetCommonAttributes(D, GV);
1331 
1332   // Emit the initializer function if necessary.
1333   if (NonConstInit)
1334     EmitCXXGlobalVarDeclInitFunc(D, GV);
1335 
1336   // Emit global variable debug information.
1337   if (CGDebugInfo *DI = getModuleDebugInfo()) {
1338     DI->setLocation(D->getLocation());
1339     DI->EmitGlobalVariable(GV, D);
1340   }
1341 }
1342 
1343 llvm::GlobalValue::LinkageTypes
1344 CodeGenModule::GetLLVMLinkageVarDefinition(const VarDecl *D,
1345                                            llvm::GlobalVariable *GV) {
1346   GVALinkage Linkage = getContext().GetGVALinkageForVariable(D);
1347   if (Linkage == GVA_Internal)
1348     return llvm::Function::InternalLinkage;
1349   else if (D->hasAttr<DLLImportAttr>())
1350     return llvm::Function::DLLImportLinkage;
1351   else if (D->hasAttr<DLLExportAttr>())
1352     return llvm::Function::DLLExportLinkage;
1353   else if (D->hasAttr<WeakAttr>()) {
1354     if (GV->isConstant())
1355       return llvm::GlobalVariable::WeakODRLinkage;
1356     else
1357       return llvm::GlobalVariable::WeakAnyLinkage;
1358   } else if (Linkage == GVA_TemplateInstantiation ||
1359              Linkage == GVA_ExplicitTemplateInstantiation)
1360     return llvm::GlobalVariable::WeakODRLinkage;
1361   else if (!getLangOptions().CPlusPlus &&
1362            ((!CodeGenOpts.NoCommon && !D->getAttr<NoCommonAttr>()) ||
1363              D->getAttr<CommonAttr>()) &&
1364            !D->hasExternalStorage() && !D->getInit() &&
1365            !D->getAttr<SectionAttr>() && !D->isThreadSpecified() &&
1366            !D->getAttr<WeakImportAttr>()) {
1367     // Thread local vars aren't considered common linkage.
1368     return llvm::GlobalVariable::CommonLinkage;
1369   }
1370   return llvm::GlobalVariable::ExternalLinkage;
1371 }
1372 
1373 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
1374 /// implement a function with no prototype, e.g. "int foo() {}".  If there are
1375 /// existing call uses of the old function in the module, this adjusts them to
1376 /// call the new function directly.
1377 ///
1378 /// This is not just a cleanup: the always_inline pass requires direct calls to
1379 /// functions to be able to inline them.  If there is a bitcast in the way, it
1380 /// won't inline them.  Instcombine normally deletes these calls, but it isn't
1381 /// run at -O0.
1382 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
1383                                                       llvm::Function *NewFn) {
1384   // If we're redefining a global as a function, don't transform it.
1385   llvm::Function *OldFn = dyn_cast<llvm::Function>(Old);
1386   if (OldFn == 0) return;
1387 
1388   llvm::Type *NewRetTy = NewFn->getReturnType();
1389   SmallVector<llvm::Value*, 4> ArgList;
1390 
1391   for (llvm::Value::use_iterator UI = OldFn->use_begin(), E = OldFn->use_end();
1392        UI != E; ) {
1393     // TODO: Do invokes ever occur in C code?  If so, we should handle them too.
1394     llvm::Value::use_iterator I = UI++; // Increment before the CI is erased.
1395     llvm::CallInst *CI = dyn_cast<llvm::CallInst>(*I);
1396     if (!CI) continue; // FIXME: when we allow Invoke, just do CallSite CS(*I)
1397     llvm::CallSite CS(CI);
1398     if (!CI || !CS.isCallee(I)) continue;
1399 
1400     // If the return types don't match exactly, and if the call isn't dead, then
1401     // we can't transform this call.
1402     if (CI->getType() != NewRetTy && !CI->use_empty())
1403       continue;
1404 
1405     // Get the attribute list.
1406     llvm::SmallVector<llvm::AttributeWithIndex, 8> AttrVec;
1407     llvm::AttrListPtr AttrList = CI->getAttributes();
1408 
1409     // Get any return attributes.
1410     llvm::Attributes RAttrs = AttrList.getRetAttributes();
1411 
1412     // Add the return attributes.
1413     if (RAttrs)
1414       AttrVec.push_back(llvm::AttributeWithIndex::get(0, RAttrs));
1415 
1416     // If the function was passed too few arguments, don't transform.  If extra
1417     // arguments were passed, we silently drop them.  If any of the types
1418     // mismatch, we don't transform.
1419     unsigned ArgNo = 0;
1420     bool DontTransform = false;
1421     for (llvm::Function::arg_iterator AI = NewFn->arg_begin(),
1422          E = NewFn->arg_end(); AI != E; ++AI, ++ArgNo) {
1423       if (CS.arg_size() == ArgNo ||
1424           CS.getArgument(ArgNo)->getType() != AI->getType()) {
1425         DontTransform = true;
1426         break;
1427       }
1428 
1429       // Add any parameter attributes.
1430       if (llvm::Attributes PAttrs = AttrList.getParamAttributes(ArgNo + 1))
1431         AttrVec.push_back(llvm::AttributeWithIndex::get(ArgNo + 1, PAttrs));
1432     }
1433     if (DontTransform)
1434       continue;
1435 
1436     if (llvm::Attributes FnAttrs =  AttrList.getFnAttributes())
1437       AttrVec.push_back(llvm::AttributeWithIndex::get(~0, FnAttrs));
1438 
1439     // Okay, we can transform this.  Create the new call instruction and copy
1440     // over the required information.
1441     ArgList.append(CS.arg_begin(), CS.arg_begin() + ArgNo);
1442     llvm::CallInst *NewCall = llvm::CallInst::Create(NewFn, ArgList, "", CI);
1443     ArgList.clear();
1444     if (!NewCall->getType()->isVoidTy())
1445       NewCall->takeName(CI);
1446     NewCall->setAttributes(llvm::AttrListPtr::get(AttrVec.begin(),
1447                                                   AttrVec.end()));
1448     NewCall->setCallingConv(CI->getCallingConv());
1449 
1450     // Finally, remove the old call, replacing any uses with the new one.
1451     if (!CI->use_empty())
1452       CI->replaceAllUsesWith(NewCall);
1453 
1454     // Copy debug location attached to CI.
1455     if (!CI->getDebugLoc().isUnknown())
1456       NewCall->setDebugLoc(CI->getDebugLoc());
1457     CI->eraseFromParent();
1458   }
1459 }
1460 
1461 
1462 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) {
1463   const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
1464 
1465   // Compute the function info and LLVM type.
1466   const CGFunctionInfo &FI = getTypes().getFunctionInfo(GD);
1467   bool variadic = false;
1468   if (const FunctionProtoType *fpt = D->getType()->getAs<FunctionProtoType>())
1469     variadic = fpt->isVariadic();
1470   llvm::FunctionType *Ty = getTypes().GetFunctionType(FI, variadic);
1471 
1472   // Get or create the prototype for the function.
1473   llvm::Constant *Entry = GetAddrOfFunction(GD, Ty);
1474 
1475   // Strip off a bitcast if we got one back.
1476   if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
1477     assert(CE->getOpcode() == llvm::Instruction::BitCast);
1478     Entry = CE->getOperand(0);
1479   }
1480 
1481 
1482   if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
1483     llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
1484 
1485     // If the types mismatch then we have to rewrite the definition.
1486     assert(OldFn->isDeclaration() &&
1487            "Shouldn't replace non-declaration");
1488 
1489     // F is the Function* for the one with the wrong type, we must make a new
1490     // Function* and update everything that used F (a declaration) with the new
1491     // Function* (which will be a definition).
1492     //
1493     // This happens if there is a prototype for a function
1494     // (e.g. "int f()") and then a definition of a different type
1495     // (e.g. "int f(int x)").  Move the old function aside so that it
1496     // doesn't interfere with GetAddrOfFunction.
1497     OldFn->setName(StringRef());
1498     llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
1499 
1500     // If this is an implementation of a function without a prototype, try to
1501     // replace any existing uses of the function (which may be calls) with uses
1502     // of the new function
1503     if (D->getType()->isFunctionNoProtoType()) {
1504       ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
1505       OldFn->removeDeadConstantUsers();
1506     }
1507 
1508     // Replace uses of F with the Function we will endow with a body.
1509     if (!Entry->use_empty()) {
1510       llvm::Constant *NewPtrForOldDecl =
1511         llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
1512       Entry->replaceAllUsesWith(NewPtrForOldDecl);
1513     }
1514 
1515     // Ok, delete the old function now, which is dead.
1516     OldFn->eraseFromParent();
1517 
1518     Entry = NewFn;
1519   }
1520 
1521   // We need to set linkage and visibility on the function before
1522   // generating code for it because various parts of IR generation
1523   // want to propagate this information down (e.g. to local static
1524   // declarations).
1525   llvm::Function *Fn = cast<llvm::Function>(Entry);
1526   setFunctionLinkage(D, Fn);
1527 
1528   // FIXME: this is redundant with part of SetFunctionDefinitionAttributes
1529   setGlobalVisibility(Fn, D);
1530 
1531   CodeGenFunction(*this).GenerateCode(D, Fn, FI);
1532 
1533   SetFunctionDefinitionAttributes(D, Fn);
1534   SetLLVMFunctionAttributesForDefinition(D, Fn);
1535 
1536   if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
1537     AddGlobalCtor(Fn, CA->getPriority());
1538   if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
1539     AddGlobalDtor(Fn, DA->getPriority());
1540   if (D->hasAttr<AnnotateAttr>())
1541     AddGlobalAnnotations(D, Fn);
1542 }
1543 
1544 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
1545   const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
1546   const AliasAttr *AA = D->getAttr<AliasAttr>();
1547   assert(AA && "Not an alias?");
1548 
1549   StringRef MangledName = getMangledName(GD);
1550 
1551   // If there is a definition in the module, then it wins over the alias.
1552   // This is dubious, but allow it to be safe.  Just ignore the alias.
1553   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1554   if (Entry && !Entry->isDeclaration())
1555     return;
1556 
1557   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
1558 
1559   // Create a reference to the named value.  This ensures that it is emitted
1560   // if a deferred decl.
1561   llvm::Constant *Aliasee;
1562   if (isa<llvm::FunctionType>(DeclTy))
1563     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl(),
1564                                       /*ForVTable=*/false);
1565   else
1566     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
1567                                     llvm::PointerType::getUnqual(DeclTy), 0);
1568 
1569   // Create the new alias itself, but don't set a name yet.
1570   llvm::GlobalValue *GA =
1571     new llvm::GlobalAlias(Aliasee->getType(),
1572                           llvm::Function::ExternalLinkage,
1573                           "", Aliasee, &getModule());
1574 
1575   if (Entry) {
1576     assert(Entry->isDeclaration());
1577 
1578     // If there is a declaration in the module, then we had an extern followed
1579     // by the alias, as in:
1580     //   extern int test6();
1581     //   ...
1582     //   int test6() __attribute__((alias("test7")));
1583     //
1584     // Remove it and replace uses of it with the alias.
1585     GA->takeName(Entry);
1586 
1587     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
1588                                                           Entry->getType()));
1589     Entry->eraseFromParent();
1590   } else {
1591     GA->setName(MangledName);
1592   }
1593 
1594   // Set attributes which are particular to an alias; this is a
1595   // specialization of the attributes which may be set on a global
1596   // variable/function.
1597   if (D->hasAttr<DLLExportAttr>()) {
1598     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1599       // The dllexport attribute is ignored for undefined symbols.
1600       if (FD->hasBody())
1601         GA->setLinkage(llvm::Function::DLLExportLinkage);
1602     } else {
1603       GA->setLinkage(llvm::Function::DLLExportLinkage);
1604     }
1605   } else if (D->hasAttr<WeakAttr>() ||
1606              D->hasAttr<WeakRefAttr>() ||
1607              D->isWeakImported()) {
1608     GA->setLinkage(llvm::Function::WeakAnyLinkage);
1609   }
1610 
1611   SetCommonAttributes(D, GA);
1612 }
1613 
1614 /// getBuiltinLibFunction - Given a builtin id for a function like
1615 /// "__builtin_fabsf", return a Function* for "fabsf".
1616 llvm::Value *CodeGenModule::getBuiltinLibFunction(const FunctionDecl *FD,
1617                                                   unsigned BuiltinID) {
1618   assert((Context.BuiltinInfo.isLibFunction(BuiltinID) ||
1619           Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) &&
1620          "isn't a lib fn");
1621 
1622   // Get the name, skip over the __builtin_ prefix (if necessary).
1623   StringRef Name;
1624   GlobalDecl D(FD);
1625 
1626   // If the builtin has been declared explicitly with an assembler label,
1627   // use the mangled name. This differs from the plain label on platforms
1628   // that prefix labels.
1629   if (FD->hasAttr<AsmLabelAttr>())
1630     Name = getMangledName(D);
1631   else if (Context.BuiltinInfo.isLibFunction(BuiltinID))
1632     Name = Context.BuiltinInfo.GetName(BuiltinID) + 10;
1633   else
1634     Name = Context.BuiltinInfo.GetName(BuiltinID);
1635 
1636 
1637   llvm::FunctionType *Ty =
1638     cast<llvm::FunctionType>(getTypes().ConvertType(FD->getType()));
1639 
1640   return GetOrCreateLLVMFunction(Name, Ty, D, /*ForVTable=*/false);
1641 }
1642 
1643 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
1644                                             ArrayRef<llvm::Type*> Tys) {
1645   return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
1646                                          Tys);
1647 }
1648 
1649 static llvm::StringMapEntry<llvm::Constant*> &
1650 GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
1651                          const StringLiteral *Literal,
1652                          bool TargetIsLSB,
1653                          bool &IsUTF16,
1654                          unsigned &StringLength) {
1655   StringRef String = Literal->getString();
1656   unsigned NumBytes = String.size();
1657 
1658   // Check for simple case.
1659   if (!Literal->containsNonAsciiOrNull()) {
1660     StringLength = NumBytes;
1661     return Map.GetOrCreateValue(String);
1662   }
1663 
1664   // Otherwise, convert the UTF8 literals into a byte string.
1665   SmallVector<UTF16, 128> ToBuf(NumBytes);
1666   const UTF8 *FromPtr = (UTF8 *)String.data();
1667   UTF16 *ToPtr = &ToBuf[0];
1668 
1669   (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1670                            &ToPtr, ToPtr + NumBytes,
1671                            strictConversion);
1672 
1673   // ConvertUTF8toUTF16 returns the length in ToPtr.
1674   StringLength = ToPtr - &ToBuf[0];
1675 
1676   // Render the UTF-16 string into a byte array and convert to the target byte
1677   // order.
1678   //
1679   // FIXME: This isn't something we should need to do here.
1680   llvm::SmallString<128> AsBytes;
1681   AsBytes.reserve(StringLength * 2);
1682   for (unsigned i = 0; i != StringLength; ++i) {
1683     unsigned short Val = ToBuf[i];
1684     if (TargetIsLSB) {
1685       AsBytes.push_back(Val & 0xFF);
1686       AsBytes.push_back(Val >> 8);
1687     } else {
1688       AsBytes.push_back(Val >> 8);
1689       AsBytes.push_back(Val & 0xFF);
1690     }
1691   }
1692   // Append one extra null character, the second is automatically added by our
1693   // caller.
1694   AsBytes.push_back(0);
1695 
1696   IsUTF16 = true;
1697   return Map.GetOrCreateValue(StringRef(AsBytes.data(), AsBytes.size()));
1698 }
1699 
1700 static llvm::StringMapEntry<llvm::Constant*> &
1701 GetConstantStringEntry(llvm::StringMap<llvm::Constant*> &Map,
1702 		       const StringLiteral *Literal,
1703 		       unsigned &StringLength)
1704 {
1705 	StringRef String = Literal->getString();
1706 	StringLength = String.size();
1707 	return Map.GetOrCreateValue(String);
1708 }
1709 
1710 llvm::Constant *
1711 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
1712   unsigned StringLength = 0;
1713   bool isUTF16 = false;
1714   llvm::StringMapEntry<llvm::Constant*> &Entry =
1715     GetConstantCFStringEntry(CFConstantStringMap, Literal,
1716                              getTargetData().isLittleEndian(),
1717                              isUTF16, StringLength);
1718 
1719   if (llvm::Constant *C = Entry.getValue())
1720     return C;
1721 
1722   llvm::Constant *Zero =
1723       llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext));
1724   llvm::Constant *Zeros[] = { Zero, Zero };
1725 
1726   // If we don't already have it, get __CFConstantStringClassReference.
1727   if (!CFConstantStringClassRef) {
1728     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
1729     Ty = llvm::ArrayType::get(Ty, 0);
1730     llvm::Constant *GV = CreateRuntimeVariable(Ty,
1731                                            "__CFConstantStringClassReference");
1732     // Decay array -> ptr
1733     CFConstantStringClassRef =
1734       llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
1735   }
1736 
1737   QualType CFTy = getContext().getCFConstantStringType();
1738 
1739   llvm::StructType *STy =
1740     cast<llvm::StructType>(getTypes().ConvertType(CFTy));
1741 
1742   std::vector<llvm::Constant*> Fields(4);
1743 
1744   // Class pointer.
1745   Fields[0] = CFConstantStringClassRef;
1746 
1747   // Flags.
1748   llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
1749   Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
1750     llvm::ConstantInt::get(Ty, 0x07C8);
1751 
1752   // String pointer.
1753   llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str());
1754 
1755   llvm::GlobalValue::LinkageTypes Linkage;
1756   bool isConstant;
1757   if (isUTF16) {
1758     // FIXME: why do utf strings get "_" labels instead of "L" labels?
1759     Linkage = llvm::GlobalValue::InternalLinkage;
1760     // Note: -fwritable-strings doesn't make unicode CFStrings writable, but
1761     // does make plain ascii ones writable.
1762     isConstant = true;
1763   } else {
1764     // FIXME: With OS X ld 123.2 (xcode 4) and LTO we would get a linker error
1765     // when using private linkage. It is not clear if this is a bug in ld
1766     // or a reasonable new restriction.
1767     Linkage = llvm::GlobalValue::LinkerPrivateLinkage;
1768     isConstant = !Features.WritableStrings;
1769   }
1770 
1771   llvm::GlobalVariable *GV =
1772     new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
1773                              ".str");
1774   GV->setUnnamedAddr(true);
1775   if (isUTF16) {
1776     CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
1777     GV->setAlignment(Align.getQuantity());
1778   } else {
1779     CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
1780     GV->setAlignment(Align.getQuantity());
1781   }
1782   Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
1783 
1784   // String length.
1785   Ty = getTypes().ConvertType(getContext().LongTy);
1786   Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
1787 
1788   // The struct.
1789   C = llvm::ConstantStruct::get(STy, Fields);
1790   GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
1791                                 llvm::GlobalVariable::PrivateLinkage, C,
1792                                 "_unnamed_cfstring_");
1793   if (const char *Sect = getContext().getTargetInfo().getCFStringSection())
1794     GV->setSection(Sect);
1795   Entry.setValue(GV);
1796 
1797   return GV;
1798 }
1799 
1800 static RecordDecl *
1801 CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
1802                  DeclContext *DC, IdentifierInfo *Id) {
1803   SourceLocation Loc;
1804   if (Ctx.getLangOptions().CPlusPlus)
1805     return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
1806   else
1807     return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
1808 }
1809 
1810 llvm::Constant *
1811 CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
1812   unsigned StringLength = 0;
1813   llvm::StringMapEntry<llvm::Constant*> &Entry =
1814     GetConstantStringEntry(CFConstantStringMap, Literal, StringLength);
1815 
1816   if (llvm::Constant *C = Entry.getValue())
1817     return C;
1818 
1819   llvm::Constant *Zero =
1820   llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext));
1821   llvm::Constant *Zeros[] = { Zero, Zero };
1822 
1823   // If we don't already have it, get _NSConstantStringClassReference.
1824   if (!ConstantStringClassRef) {
1825     std::string StringClass(getLangOptions().ObjCConstantStringClass);
1826     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
1827     llvm::Constant *GV;
1828     if (Features.ObjCNonFragileABI) {
1829       std::string str =
1830         StringClass.empty() ? "OBJC_CLASS_$_NSConstantString"
1831                             : "OBJC_CLASS_$_" + StringClass;
1832       GV = getObjCRuntime().GetClassGlobal(str);
1833       // Make sure the result is of the correct type.
1834       llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
1835       ConstantStringClassRef =
1836         llvm::ConstantExpr::getBitCast(GV, PTy);
1837     } else {
1838       std::string str =
1839         StringClass.empty() ? "_NSConstantStringClassReference"
1840                             : "_" + StringClass + "ClassReference";
1841       llvm::Type *PTy = llvm::ArrayType::get(Ty, 0);
1842       GV = CreateRuntimeVariable(PTy, str);
1843       // Decay array -> ptr
1844       ConstantStringClassRef =
1845         llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
1846     }
1847   }
1848 
1849   if (!NSConstantStringType) {
1850     // Construct the type for a constant NSString.
1851     RecordDecl *D = CreateRecordDecl(Context, TTK_Struct,
1852                                      Context.getTranslationUnitDecl(),
1853                                    &Context.Idents.get("__builtin_NSString"));
1854     D->startDefinition();
1855 
1856     QualType FieldTypes[3];
1857 
1858     // const int *isa;
1859     FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst());
1860     // const char *str;
1861     FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst());
1862     // unsigned int length;
1863     FieldTypes[2] = Context.UnsignedIntTy;
1864 
1865     // Create fields
1866     for (unsigned i = 0; i < 3; ++i) {
1867       FieldDecl *Field = FieldDecl::Create(Context, D,
1868                                            SourceLocation(),
1869                                            SourceLocation(), 0,
1870                                            FieldTypes[i], /*TInfo=*/0,
1871                                            /*BitWidth=*/0,
1872                                            /*Mutable=*/false,
1873                                            /*HasInit=*/false);
1874       Field->setAccess(AS_public);
1875       D->addDecl(Field);
1876     }
1877 
1878     D->completeDefinition();
1879     QualType NSTy = Context.getTagDeclType(D);
1880     NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy));
1881   }
1882 
1883   std::vector<llvm::Constant*> Fields(3);
1884 
1885   // Class pointer.
1886   Fields[0] = ConstantStringClassRef;
1887 
1888   // String pointer.
1889   llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str());
1890 
1891   llvm::GlobalValue::LinkageTypes Linkage;
1892   bool isConstant;
1893   Linkage = llvm::GlobalValue::PrivateLinkage;
1894   isConstant = !Features.WritableStrings;
1895 
1896   llvm::GlobalVariable *GV =
1897   new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
1898                            ".str");
1899   GV->setUnnamedAddr(true);
1900   CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
1901   GV->setAlignment(Align.getQuantity());
1902   Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
1903 
1904   // String length.
1905   llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
1906   Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
1907 
1908   // The struct.
1909   C = llvm::ConstantStruct::get(NSConstantStringType, Fields);
1910   GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
1911                                 llvm::GlobalVariable::PrivateLinkage, C,
1912                                 "_unnamed_nsstring_");
1913   // FIXME. Fix section.
1914   if (const char *Sect =
1915         Features.ObjCNonFragileABI
1916           ? getContext().getTargetInfo().getNSStringNonFragileABISection()
1917           : getContext().getTargetInfo().getNSStringSection())
1918     GV->setSection(Sect);
1919   Entry.setValue(GV);
1920 
1921   return GV;
1922 }
1923 
1924 QualType CodeGenModule::getObjCFastEnumerationStateType() {
1925   if (ObjCFastEnumerationStateType.isNull()) {
1926     RecordDecl *D = CreateRecordDecl(Context, TTK_Struct,
1927                                      Context.getTranslationUnitDecl(),
1928                       &Context.Idents.get("__objcFastEnumerationState"));
1929     D->startDefinition();
1930 
1931     QualType FieldTypes[] = {
1932       Context.UnsignedLongTy,
1933       Context.getPointerType(Context.getObjCIdType()),
1934       Context.getPointerType(Context.UnsignedLongTy),
1935       Context.getConstantArrayType(Context.UnsignedLongTy,
1936                            llvm::APInt(32, 5), ArrayType::Normal, 0)
1937     };
1938 
1939     for (size_t i = 0; i < 4; ++i) {
1940       FieldDecl *Field = FieldDecl::Create(Context,
1941                                            D,
1942                                            SourceLocation(),
1943                                            SourceLocation(), 0,
1944                                            FieldTypes[i], /*TInfo=*/0,
1945                                            /*BitWidth=*/0,
1946                                            /*Mutable=*/false,
1947                                            /*HasInit=*/false);
1948       Field->setAccess(AS_public);
1949       D->addDecl(Field);
1950     }
1951 
1952     D->completeDefinition();
1953     ObjCFastEnumerationStateType = Context.getTagDeclType(D);
1954   }
1955 
1956   return ObjCFastEnumerationStateType;
1957 }
1958 
1959 /// GetStringForStringLiteral - Return the appropriate bytes for a
1960 /// string literal, properly padded to match the literal type.
1961 std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
1962   const ASTContext &Context = getContext();
1963   const ConstantArrayType *CAT =
1964     Context.getAsConstantArrayType(E->getType());
1965   assert(CAT && "String isn't pointer or array!");
1966 
1967   // Resize the string to the right size.
1968   uint64_t RealLen = CAT->getSize().getZExtValue();
1969 
1970   switch (E->getKind()) {
1971   case StringLiteral::Ascii:
1972   case StringLiteral::UTF8:
1973     break;
1974   case StringLiteral::Wide:
1975     RealLen *= Context.getTargetInfo().getWCharWidth() / Context.getCharWidth();
1976     break;
1977   case StringLiteral::UTF16:
1978     RealLen *= Context.getTargetInfo().getChar16Width() / Context.getCharWidth();
1979     break;
1980   case StringLiteral::UTF32:
1981     RealLen *= Context.getTargetInfo().getChar32Width() / Context.getCharWidth();
1982     break;
1983   }
1984 
1985   std::string Str = E->getString().str();
1986   Str.resize(RealLen, '\0');
1987 
1988   return Str;
1989 }
1990 
1991 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
1992 /// constant array for the given string literal.
1993 llvm::Constant *
1994 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
1995   // FIXME: This can be more efficient.
1996   // FIXME: We shouldn't need to bitcast the constant in the wide string case.
1997   CharUnits Align = getContext().getTypeAlignInChars(S->getType());
1998   llvm::Constant *C = GetAddrOfConstantString(GetStringForStringLiteral(S),
1999                                               /* GlobalName */ 0,
2000                                               Align.getQuantity());
2001   if (S->isWide() || S->isUTF16() || S->isUTF32()) {
2002     llvm::Type *DestTy =
2003         llvm::PointerType::getUnqual(getTypes().ConvertType(S->getType()));
2004     C = llvm::ConstantExpr::getBitCast(C, DestTy);
2005   }
2006   return C;
2007 }
2008 
2009 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
2010 /// array for the given ObjCEncodeExpr node.
2011 llvm::Constant *
2012 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
2013   std::string Str;
2014   getContext().getObjCEncodingForType(E->getEncodedType(), Str);
2015 
2016   return GetAddrOfConstantCString(Str);
2017 }
2018 
2019 
2020 /// GenerateWritableString -- Creates storage for a string literal.
2021 static llvm::GlobalVariable *GenerateStringLiteral(StringRef str,
2022                                              bool constant,
2023                                              CodeGenModule &CGM,
2024                                              const char *GlobalName,
2025                                              unsigned Alignment) {
2026   // Create Constant for this string literal. Don't add a '\0'.
2027   llvm::Constant *C =
2028       llvm::ConstantArray::get(CGM.getLLVMContext(), str, false);
2029 
2030   // Create a global variable for this string
2031   llvm::GlobalVariable *GV =
2032     new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant,
2033                              llvm::GlobalValue::PrivateLinkage,
2034                              C, GlobalName);
2035   GV->setAlignment(Alignment);
2036   GV->setUnnamedAddr(true);
2037   return GV;
2038 }
2039 
2040 /// GetAddrOfConstantString - Returns a pointer to a character array
2041 /// containing the literal. This contents are exactly that of the
2042 /// given string, i.e. it will not be null terminated automatically;
2043 /// see GetAddrOfConstantCString. Note that whether the result is
2044 /// actually a pointer to an LLVM constant depends on
2045 /// Feature.WriteableStrings.
2046 ///
2047 /// The result has pointer to array type.
2048 llvm::Constant *CodeGenModule::GetAddrOfConstantString(StringRef Str,
2049                                                        const char *GlobalName,
2050                                                        unsigned Alignment) {
2051   bool IsConstant = !Features.WritableStrings;
2052 
2053   // Get the default prefix if a name wasn't specified.
2054   if (!GlobalName)
2055     GlobalName = ".str";
2056 
2057   // Don't share any string literals if strings aren't constant.
2058   if (!IsConstant)
2059     return GenerateStringLiteral(Str, false, *this, GlobalName, Alignment);
2060 
2061   llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
2062     ConstantStringMap.GetOrCreateValue(Str);
2063 
2064   if (llvm::GlobalVariable *GV = Entry.getValue()) {
2065     if (Alignment > GV->getAlignment()) {
2066       GV->setAlignment(Alignment);
2067     }
2068     return GV;
2069   }
2070 
2071   // Create a global variable for this.
2072   llvm::GlobalVariable *GV = GenerateStringLiteral(Str, true, *this, GlobalName, Alignment);
2073   Entry.setValue(GV);
2074   return GV;
2075 }
2076 
2077 /// GetAddrOfConstantCString - Returns a pointer to a character
2078 /// array containing the literal and a terminating '\0'
2079 /// character. The result has pointer to array type.
2080 llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &Str,
2081                                                         const char *GlobalName,
2082                                                         unsigned Alignment) {
2083   StringRef StrWithNull(Str.c_str(), Str.size() + 1);
2084   return GetAddrOfConstantString(StrWithNull, GlobalName, Alignment);
2085 }
2086 
2087 /// EmitObjCPropertyImplementations - Emit information for synthesized
2088 /// properties for an implementation.
2089 void CodeGenModule::EmitObjCPropertyImplementations(const
2090                                                     ObjCImplementationDecl *D) {
2091   for (ObjCImplementationDecl::propimpl_iterator
2092          i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) {
2093     ObjCPropertyImplDecl *PID = *i;
2094 
2095     // Dynamic is just for type-checking.
2096     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
2097       ObjCPropertyDecl *PD = PID->getPropertyDecl();
2098 
2099       // Determine which methods need to be implemented, some may have
2100       // been overridden. Note that ::isSynthesized is not the method
2101       // we want, that just indicates if the decl came from a
2102       // property. What we want to know is if the method is defined in
2103       // this implementation.
2104       if (!D->getInstanceMethod(PD->getGetterName()))
2105         CodeGenFunction(*this).GenerateObjCGetter(
2106                                  const_cast<ObjCImplementationDecl *>(D), PID);
2107       if (!PD->isReadOnly() &&
2108           !D->getInstanceMethod(PD->getSetterName()))
2109         CodeGenFunction(*this).GenerateObjCSetter(
2110                                  const_cast<ObjCImplementationDecl *>(D), PID);
2111     }
2112   }
2113 }
2114 
2115 static bool needsDestructMethod(ObjCImplementationDecl *impl) {
2116   const ObjCInterfaceDecl *iface = impl->getClassInterface();
2117   for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
2118        ivar; ivar = ivar->getNextIvar())
2119     if (ivar->getType().isDestructedType())
2120       return true;
2121 
2122   return false;
2123 }
2124 
2125 /// EmitObjCIvarInitializations - Emit information for ivar initialization
2126 /// for an implementation.
2127 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
2128   // We might need a .cxx_destruct even if we don't have any ivar initializers.
2129   if (needsDestructMethod(D)) {
2130     IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
2131     Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
2132     ObjCMethodDecl *DTORMethod =
2133       ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
2134                              cxxSelector, getContext().VoidTy, 0, D,
2135                              /*isInstance=*/true, /*isVariadic=*/false,
2136                           /*isSynthesized=*/true, /*isImplicitlyDeclared=*/true,
2137                              /*isDefined=*/false, ObjCMethodDecl::Required);
2138     D->addInstanceMethod(DTORMethod);
2139     CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
2140     D->setHasCXXStructors(true);
2141   }
2142 
2143   // If the implementation doesn't have any ivar initializers, we don't need
2144   // a .cxx_construct.
2145   if (D->getNumIvarInitializers() == 0)
2146     return;
2147 
2148   IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
2149   Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
2150   // The constructor returns 'self'.
2151   ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
2152                                                 D->getLocation(),
2153                                                 D->getLocation(), cxxSelector,
2154                                                 getContext().getObjCIdType(), 0,
2155                                                 D, /*isInstance=*/true,
2156                                                 /*isVariadic=*/false,
2157                                                 /*isSynthesized=*/true,
2158                                                 /*isImplicitlyDeclared=*/true,
2159                                                 /*isDefined=*/false,
2160                                                 ObjCMethodDecl::Required);
2161   D->addInstanceMethod(CTORMethod);
2162   CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
2163   D->setHasCXXStructors(true);
2164 }
2165 
2166 /// EmitNamespace - Emit all declarations in a namespace.
2167 void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
2168   for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end();
2169        I != E; ++I)
2170     EmitTopLevelDecl(*I);
2171 }
2172 
2173 // EmitLinkageSpec - Emit all declarations in a linkage spec.
2174 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
2175   if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
2176       LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
2177     ErrorUnsupported(LSD, "linkage spec");
2178     return;
2179   }
2180 
2181   for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end();
2182        I != E; ++I)
2183     EmitTopLevelDecl(*I);
2184 }
2185 
2186 /// EmitTopLevelDecl - Emit code for a single top level declaration.
2187 void CodeGenModule::EmitTopLevelDecl(Decl *D) {
2188   // If an error has occurred, stop code generation, but continue
2189   // parsing and semantic analysis (to ensure all warnings and errors
2190   // are emitted).
2191   if (Diags.hasErrorOccurred())
2192     return;
2193 
2194   // Ignore dependent declarations.
2195   if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
2196     return;
2197 
2198   switch (D->getKind()) {
2199   case Decl::CXXConversion:
2200   case Decl::CXXMethod:
2201   case Decl::Function:
2202     // Skip function templates
2203     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
2204         cast<FunctionDecl>(D)->isLateTemplateParsed())
2205       return;
2206 
2207     EmitGlobal(cast<FunctionDecl>(D));
2208     break;
2209 
2210   case Decl::Var:
2211     EmitGlobal(cast<VarDecl>(D));
2212     break;
2213 
2214   // Indirect fields from global anonymous structs and unions can be
2215   // ignored; only the actual variable requires IR gen support.
2216   case Decl::IndirectField:
2217     break;
2218 
2219   // C++ Decls
2220   case Decl::Namespace:
2221     EmitNamespace(cast<NamespaceDecl>(D));
2222     break;
2223     // No code generation needed.
2224   case Decl::UsingShadow:
2225   case Decl::Using:
2226   case Decl::UsingDirective:
2227   case Decl::ClassTemplate:
2228   case Decl::FunctionTemplate:
2229   case Decl::TypeAliasTemplate:
2230   case Decl::NamespaceAlias:
2231   case Decl::Block:
2232     break;
2233   case Decl::CXXConstructor:
2234     // Skip function templates
2235     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
2236         cast<FunctionDecl>(D)->isLateTemplateParsed())
2237       return;
2238 
2239     EmitCXXConstructors(cast<CXXConstructorDecl>(D));
2240     break;
2241   case Decl::CXXDestructor:
2242     if (cast<FunctionDecl>(D)->isLateTemplateParsed())
2243       return;
2244     EmitCXXDestructors(cast<CXXDestructorDecl>(D));
2245     break;
2246 
2247   case Decl::StaticAssert:
2248     // Nothing to do.
2249     break;
2250 
2251   // Objective-C Decls
2252 
2253   // Forward declarations, no (immediate) code generation.
2254   case Decl::ObjCClass:
2255   case Decl::ObjCForwardProtocol:
2256   case Decl::ObjCInterface:
2257     break;
2258 
2259   case Decl::ObjCCategory: {
2260     ObjCCategoryDecl *CD = cast<ObjCCategoryDecl>(D);
2261     if (CD->IsClassExtension() && CD->hasSynthBitfield())
2262       Context.ResetObjCLayout(CD->getClassInterface());
2263     break;
2264   }
2265 
2266   case Decl::ObjCProtocol:
2267     ObjCRuntime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
2268     break;
2269 
2270   case Decl::ObjCCategoryImpl:
2271     // Categories have properties but don't support synthesize so we
2272     // can ignore them here.
2273     ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
2274     break;
2275 
2276   case Decl::ObjCImplementation: {
2277     ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
2278     if (Features.ObjCNonFragileABI2 && OMD->hasSynthBitfield())
2279       Context.ResetObjCLayout(OMD->getClassInterface());
2280     EmitObjCPropertyImplementations(OMD);
2281     EmitObjCIvarInitializations(OMD);
2282     ObjCRuntime->GenerateClass(OMD);
2283     break;
2284   }
2285   case Decl::ObjCMethod: {
2286     ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
2287     // If this is not a prototype, emit the body.
2288     if (OMD->getBody())
2289       CodeGenFunction(*this).GenerateObjCMethod(OMD);
2290     break;
2291   }
2292   case Decl::ObjCCompatibleAlias:
2293     // compatibility-alias is a directive and has no code gen.
2294     break;
2295 
2296   case Decl::LinkageSpec:
2297     EmitLinkageSpec(cast<LinkageSpecDecl>(D));
2298     break;
2299 
2300   case Decl::FileScopeAsm: {
2301     FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
2302     StringRef AsmString = AD->getAsmString()->getString();
2303 
2304     const std::string &S = getModule().getModuleInlineAsm();
2305     if (S.empty())
2306       getModule().setModuleInlineAsm(AsmString);
2307     else if (*--S.end() == '\n')
2308       getModule().setModuleInlineAsm(S + AsmString.str());
2309     else
2310       getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
2311     break;
2312   }
2313 
2314   default:
2315     // Make sure we handled everything we should, every other kind is a
2316     // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
2317     // function. Need to recode Decl::Kind to do that easily.
2318     assert(isa<TypeDecl>(D) && "Unsupported decl kind");
2319   }
2320 }
2321 
2322 /// Turns the given pointer into a constant.
2323 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
2324                                           const void *Ptr) {
2325   uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
2326   llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
2327   return llvm::ConstantInt::get(i64, PtrInt);
2328 }
2329 
2330 static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
2331                                    llvm::NamedMDNode *&GlobalMetadata,
2332                                    GlobalDecl D,
2333                                    llvm::GlobalValue *Addr) {
2334   if (!GlobalMetadata)
2335     GlobalMetadata =
2336       CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
2337 
2338   // TODO: should we report variant information for ctors/dtors?
2339   llvm::Value *Ops[] = {
2340     Addr,
2341     GetPointerConstant(CGM.getLLVMContext(), D.getDecl())
2342   };
2343   GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2344 }
2345 
2346 /// Emits metadata nodes associating all the global values in the
2347 /// current module with the Decls they came from.  This is useful for
2348 /// projects using IR gen as a subroutine.
2349 ///
2350 /// Since there's currently no way to associate an MDNode directly
2351 /// with an llvm::GlobalValue, we create a global named metadata
2352 /// with the name 'clang.global.decl.ptrs'.
2353 void CodeGenModule::EmitDeclMetadata() {
2354   llvm::NamedMDNode *GlobalMetadata = 0;
2355 
2356   // StaticLocalDeclMap
2357   for (llvm::DenseMap<GlobalDecl,StringRef>::iterator
2358          I = MangledDeclNames.begin(), E = MangledDeclNames.end();
2359        I != E; ++I) {
2360     llvm::GlobalValue *Addr = getModule().getNamedValue(I->second);
2361     EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr);
2362   }
2363 }
2364 
2365 /// Emits metadata nodes for all the local variables in the current
2366 /// function.
2367 void CodeGenFunction::EmitDeclMetadata() {
2368   if (LocalDeclMap.empty()) return;
2369 
2370   llvm::LLVMContext &Context = getLLVMContext();
2371 
2372   // Find the unique metadata ID for this name.
2373   unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
2374 
2375   llvm::NamedMDNode *GlobalMetadata = 0;
2376 
2377   for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator
2378          I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) {
2379     const Decl *D = I->first;
2380     llvm::Value *Addr = I->second;
2381 
2382     if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
2383       llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
2384       Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, DAddr));
2385     } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
2386       GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
2387       EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
2388     }
2389   }
2390 }
2391 
2392 void CodeGenModule::EmitCoverageFile() {
2393   if (!getCodeGenOpts().CoverageFile.empty()) {
2394     if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) {
2395       llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
2396       llvm::LLVMContext &Ctx = TheModule.getContext();
2397       llvm::MDString *CoverageFile =
2398           llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile);
2399       for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
2400         llvm::MDNode *CU = CUNode->getOperand(i);
2401         llvm::Value *node[] = { CoverageFile, CU };
2402         llvm::MDNode *N = llvm::MDNode::get(Ctx, node);
2403         GCov->addOperand(N);
2404       }
2405     }
2406   }
2407 }
2408