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