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