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