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