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