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