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