xref: /llvm-project/clang/lib/CodeGen/CodeGenModule.cpp (revision 683fe4fc4c72703ed1c4ba4c8af7667b148d802c)
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/CallSite.h"
39 #include "llvm/Support/ErrorHandling.h"
40 using namespace clang;
41 using namespace CodeGen;
42 
43 
44 CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO,
45                              llvm::Module &M, const llvm::TargetData &TD,
46                              Diagnostic &diags)
47   : BlockModule(C, M, TD, Types, *this), Context(C),
48     Features(C.getLangOptions()), CodeGenOpts(CGO), TheModule(M),
49     TheTargetData(TD), TheTargetCodeGenInfo(0), Diags(diags),
50     Types(C, M, TD, getTargetCodeGenInfo().getABIInfo()),
51     MangleCtx(C, diags), VTables(*this), Runtime(0),
52     CFConstantStringClassRef(0),
53     VMContext(M.getContext()) {
54 
55   if (!Features.ObjC1)
56     Runtime = 0;
57   else if (!Features.NeXTRuntime)
58     Runtime = CreateGNUObjCRuntime(*this);
59   else if (Features.ObjCNonFragileABI)
60     Runtime = CreateMacNonFragileABIObjCRuntime(*this);
61   else
62     Runtime = CreateMacObjCRuntime(*this);
63 
64   // If debug info generation is enabled, create the CGDebugInfo object.
65   DebugInfo = CodeGenOpts.DebugInfo ? new CGDebugInfo(*this) : 0;
66 }
67 
68 CodeGenModule::~CodeGenModule() {
69   delete Runtime;
70   delete DebugInfo;
71 }
72 
73 void CodeGenModule::createObjCRuntime() {
74   if (!Features.NeXTRuntime)
75     Runtime = CreateGNUObjCRuntime(*this);
76   else if (Features.ObjCNonFragileABI)
77     Runtime = CreateMacNonFragileABIObjCRuntime(*this);
78   else
79     Runtime = CreateMacObjCRuntime(*this);
80 }
81 
82 void CodeGenModule::Release() {
83   EmitDeferred();
84   EmitCXXGlobalInitFunc();
85   EmitCXXGlobalDtorFunc();
86   if (Runtime)
87     if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction())
88       AddGlobalCtor(ObjCInitFunction);
89   EmitCtorList(GlobalCtors, "llvm.global_ctors");
90   EmitCtorList(GlobalDtors, "llvm.global_dtors");
91   EmitAnnotations();
92   EmitLLVMUsed();
93 }
94 
95 bool CodeGenModule::isTargetDarwin() const {
96   return getContext().Target.getTriple().getOS() == llvm::Triple::Darwin;
97 }
98 
99 /// ErrorUnsupported - Print out an error that codegen doesn't support the
100 /// specified stmt yet.
101 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
102                                      bool OmitOnError) {
103   if (OmitOnError && getDiags().hasErrorOccurred())
104     return;
105   unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
106                                                "cannot compile this %0 yet");
107   std::string Msg = Type;
108   getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
109     << Msg << S->getSourceRange();
110 }
111 
112 /// ErrorUnsupported - Print out an error that codegen doesn't support the
113 /// specified decl yet.
114 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
115                                      bool OmitOnError) {
116   if (OmitOnError && getDiags().hasErrorOccurred())
117     return;
118   unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
119                                                "cannot compile this %0 yet");
120   std::string Msg = Type;
121   getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
122 }
123 
124 LangOptions::VisibilityMode
125 CodeGenModule::getDeclVisibilityMode(const Decl *D) const {
126   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
127     if (VD->getStorageClass() == VarDecl::PrivateExtern)
128       return LangOptions::Hidden;
129 
130   if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>()) {
131     switch (attr->getVisibility()) {
132     default: assert(0 && "Unknown visibility!");
133     case VisibilityAttr::DefaultVisibility:
134       return LangOptions::Default;
135     case VisibilityAttr::HiddenVisibility:
136       return LangOptions::Hidden;
137     case VisibilityAttr::ProtectedVisibility:
138       return LangOptions::Protected;
139     }
140   }
141 
142   // This decl should have the same visibility as its parent.
143   if (const DeclContext *DC = D->getDeclContext())
144     return getDeclVisibilityMode(cast<Decl>(DC));
145 
146   return getLangOptions().getVisibilityMode();
147 }
148 
149 void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
150                                         const Decl *D) const {
151   // Internal definitions always have default visibility.
152   if (GV->hasLocalLinkage()) {
153     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
154     return;
155   }
156 
157   switch (getDeclVisibilityMode(D)) {
158   default: assert(0 && "Unknown visibility!");
159   case LangOptions::Default:
160     return GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
161   case LangOptions::Hidden:
162     return GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
163   case LangOptions::Protected:
164     return GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
165   }
166 }
167 
168 void CodeGenModule::getMangledName(MangleBuffer &Buffer, GlobalDecl GD) {
169   const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
170 
171   if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND))
172     return getMangledCXXCtorName(Buffer, D, GD.getCtorType());
173   if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND))
174     return getMangledCXXDtorName(Buffer, D, GD.getDtorType());
175 
176   return getMangledName(Buffer, ND);
177 }
178 
179 /// \brief Retrieves the mangled name for the given declaration.
180 ///
181 /// If the given declaration requires a mangled name, returns an
182 /// const char* containing the mangled name.  Otherwise, returns
183 /// the unmangled name.
184 ///
185 void CodeGenModule::getMangledName(MangleBuffer &Buffer,
186                                    const NamedDecl *ND) {
187   if (!getMangleContext().shouldMangleDeclName(ND)) {
188     assert(ND->getIdentifier() && "Attempt to mangle unnamed decl.");
189     Buffer.setString(ND->getNameAsCString());
190     return;
191   }
192 
193   getMangleContext().mangleName(ND, Buffer.getBuffer());
194 }
195 
196 llvm::GlobalValue *CodeGenModule::GetGlobalValue(llvm::StringRef Name) {
197   return getModule().getNamedValue(Name);
198 }
199 
200 /// AddGlobalCtor - Add a function to the list that will be called before
201 /// main() runs.
202 void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
203   // FIXME: Type coercion of void()* types.
204   GlobalCtors.push_back(std::make_pair(Ctor, Priority));
205 }
206 
207 /// AddGlobalDtor - Add a function to the list that will be called
208 /// when the module is unloaded.
209 void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
210   // FIXME: Type coercion of void()* types.
211   GlobalDtors.push_back(std::make_pair(Dtor, Priority));
212 }
213 
214 void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
215   // Ctor function type is void()*.
216   llvm::FunctionType* CtorFTy =
217     llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
218                             std::vector<const llvm::Type*>(),
219                             false);
220   llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
221 
222   // Get the type of a ctor entry, { i32, void ()* }.
223   llvm::StructType* CtorStructTy =
224     llvm::StructType::get(VMContext, llvm::Type::getInt32Ty(VMContext),
225                           llvm::PointerType::getUnqual(CtorFTy), NULL);
226 
227   // Construct the constructor and destructor arrays.
228   std::vector<llvm::Constant*> Ctors;
229   for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
230     std::vector<llvm::Constant*> S;
231     S.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
232                 I->second, false));
233     S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
234     Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
235   }
236 
237   if (!Ctors.empty()) {
238     llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
239     new llvm::GlobalVariable(TheModule, AT, false,
240                              llvm::GlobalValue::AppendingLinkage,
241                              llvm::ConstantArray::get(AT, Ctors),
242                              GlobalName);
243   }
244 }
245 
246 void CodeGenModule::EmitAnnotations() {
247   if (Annotations.empty())
248     return;
249 
250   // Create a new global variable for the ConstantStruct in the Module.
251   llvm::Constant *Array =
252   llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
253                                                 Annotations.size()),
254                            Annotations);
255   llvm::GlobalValue *gv =
256   new llvm::GlobalVariable(TheModule, Array->getType(), false,
257                            llvm::GlobalValue::AppendingLinkage, Array,
258                            "llvm.global.annotations");
259   gv->setSection("llvm.metadata");
260 }
261 
262 static CodeGenModule::GVALinkage
263 GetLinkageForFunction(ASTContext &Context, const FunctionDecl *FD,
264                       const LangOptions &Features) {
265   CodeGenModule::GVALinkage External = CodeGenModule::GVA_StrongExternal;
266 
267   Linkage L = FD->getLinkage();
268   if (L == ExternalLinkage && Context.getLangOptions().CPlusPlus &&
269       FD->getType()->getLinkage() == UniqueExternalLinkage)
270     L = UniqueExternalLinkage;
271 
272   switch (L) {
273   case NoLinkage:
274   case InternalLinkage:
275   case UniqueExternalLinkage:
276     return CodeGenModule::GVA_Internal;
277 
278   case ExternalLinkage:
279     switch (FD->getTemplateSpecializationKind()) {
280     case TSK_Undeclared:
281     case TSK_ExplicitSpecialization:
282       External = CodeGenModule::GVA_StrongExternal;
283       break;
284 
285     case TSK_ExplicitInstantiationDefinition:
286       return CodeGenModule::GVA_ExplicitTemplateInstantiation;
287 
288     case TSK_ExplicitInstantiationDeclaration:
289     case TSK_ImplicitInstantiation:
290       External = CodeGenModule::GVA_TemplateInstantiation;
291       break;
292     }
293   }
294 
295   if (!FD->isInlined())
296     return External;
297 
298   if (!Features.CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
299     // GNU or C99 inline semantics. Determine whether this symbol should be
300     // externally visible.
301     if (FD->isInlineDefinitionExternallyVisible())
302       return External;
303 
304     // C99 inline semantics, where the symbol is not externally visible.
305     return CodeGenModule::GVA_C99Inline;
306   }
307 
308   // C++0x [temp.explicit]p9:
309   //   [ Note: The intent is that an inline function that is the subject of
310   //   an explicit instantiation declaration will still be implicitly
311   //   instantiated when used so that the body can be considered for
312   //   inlining, but that no out-of-line copy of the inline function would be
313   //   generated in the translation unit. -- end note ]
314   if (FD->getTemplateSpecializationKind()
315                                        == TSK_ExplicitInstantiationDeclaration)
316     return CodeGenModule::GVA_C99Inline;
317 
318   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
319     const CXXRecordDecl *RD = MD->getParent();
320     if (MD->isVirtual() &&
321 	CodeGenVTables::isKeyFunctionInAnotherTU(Context, RD))
322       return CodeGenModule::GVA_C99Inline;
323   }
324 
325   return CodeGenModule::GVA_CXXInline;
326 }
327 
328 llvm::GlobalValue::LinkageTypes
329 CodeGenModule::getFunctionLinkage(const FunctionDecl *D) {
330   GVALinkage Linkage = GetLinkageForFunction(getContext(), D, Features);
331 
332   if (Linkage == GVA_Internal) {
333     return llvm::Function::InternalLinkage;
334   } else if (D->hasAttr<DLLExportAttr>()) {
335     return llvm::Function::DLLExportLinkage;
336   } else if (D->hasAttr<WeakAttr>()) {
337     return llvm::Function::WeakAnyLinkage;
338   } else if (Linkage == GVA_C99Inline) {
339     // In C99 mode, 'inline' functions are guaranteed to have a strong
340     // definition somewhere else, so we can use available_externally linkage.
341     return llvm::Function::AvailableExternallyLinkage;
342   } else if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation) {
343     // In C++, the compiler has to emit a definition in every translation unit
344     // that references the function.  We should use linkonce_odr because
345     // a) if all references in this translation unit are optimized away, we
346     // don't need to codegen it.  b) if the function persists, it needs to be
347     // merged with other definitions. c) C++ has the ODR, so we know the
348     // definition is dependable.
349     return llvm::Function::LinkOnceODRLinkage;
350   } else if (Linkage == GVA_ExplicitTemplateInstantiation) {
351     // An explicit instantiation of a template has weak linkage, since
352     // explicit instantiations can occur in multiple translation units
353     // and must all be equivalent. However, we are not allowed to
354     // throw away these explicit instantiations.
355     return llvm::Function::WeakODRLinkage;
356   } else {
357     assert(Linkage == GVA_StrongExternal);
358     // Otherwise, we have strong external linkage.
359     return llvm::Function::ExternalLinkage;
360   }
361 }
362 
363 
364 /// SetFunctionDefinitionAttributes - Set attributes for a global.
365 ///
366 /// FIXME: This is currently only done for aliases and functions, but not for
367 /// variables (these details are set in EmitGlobalVarDefinition for variables).
368 void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D,
369                                                     llvm::GlobalValue *GV) {
370   GV->setLinkage(getFunctionLinkage(D));
371   SetCommonAttributes(D, GV);
372 }
373 
374 void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
375                                               const CGFunctionInfo &Info,
376                                               llvm::Function *F) {
377   unsigned CallingConv;
378   AttributeListType AttributeList;
379   ConstructAttributeList(Info, D, AttributeList, CallingConv);
380   F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
381                                           AttributeList.size()));
382   F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
383 }
384 
385 void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
386                                                            llvm::Function *F) {
387   if (!Features.Exceptions && !Features.ObjCNonFragileABI)
388     F->addFnAttr(llvm::Attribute::NoUnwind);
389 
390   if (D->hasAttr<AlwaysInlineAttr>())
391     F->addFnAttr(llvm::Attribute::AlwaysInline);
392 
393   if (D->hasAttr<NoInlineAttr>())
394     F->addFnAttr(llvm::Attribute::NoInline);
395 
396   if (Features.getStackProtectorMode() == LangOptions::SSPOn)
397     F->addFnAttr(llvm::Attribute::StackProtect);
398   else if (Features.getStackProtectorMode() == LangOptions::SSPReq)
399     F->addFnAttr(llvm::Attribute::StackProtectReq);
400 
401   if (const AlignedAttr *AA = D->getAttr<AlignedAttr>()) {
402     unsigned width = Context.Target.getCharWidth();
403     F->setAlignment(AA->getAlignment() / width);
404     while ((AA = AA->getNext<AlignedAttr>()))
405       F->setAlignment(std::max(F->getAlignment(), AA->getAlignment() / width));
406   }
407   // C++ ABI requires 2-byte alignment for member functions.
408   if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
409     F->setAlignment(2);
410 }
411 
412 void CodeGenModule::SetCommonAttributes(const Decl *D,
413                                         llvm::GlobalValue *GV) {
414   setGlobalVisibility(GV, D);
415 
416   if (D->hasAttr<UsedAttr>())
417     AddUsedGlobal(GV);
418 
419   if (const SectionAttr *SA = D->getAttr<SectionAttr>())
420     GV->setSection(SA->getName());
421 
422   getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this);
423 }
424 
425 void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
426                                                   llvm::Function *F,
427                                                   const CGFunctionInfo &FI) {
428   SetLLVMFunctionAttributes(D, FI, F);
429   SetLLVMFunctionAttributesForDefinition(D, F);
430 
431   F->setLinkage(llvm::Function::InternalLinkage);
432 
433   SetCommonAttributes(D, F);
434 }
435 
436 void CodeGenModule::SetFunctionAttributes(GlobalDecl GD,
437                                           llvm::Function *F,
438                                           bool IsIncompleteFunction) {
439   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
440 
441   if (!IsIncompleteFunction)
442     SetLLVMFunctionAttributes(FD, getTypes().getFunctionInfo(GD), F);
443 
444   // Only a few attributes are set on declarations; these may later be
445   // overridden by a definition.
446 
447   if (FD->hasAttr<DLLImportAttr>()) {
448     F->setLinkage(llvm::Function::DLLImportLinkage);
449   } else if (FD->hasAttr<WeakAttr>() ||
450              FD->hasAttr<WeakImportAttr>()) {
451     // "extern_weak" is overloaded in LLVM; we probably should have
452     // separate linkage types for this.
453     F->setLinkage(llvm::Function::ExternalWeakLinkage);
454   } else {
455     F->setLinkage(llvm::Function::ExternalLinkage);
456   }
457 
458   if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
459     F->setSection(SA->getName());
460 }
461 
462 void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
463   assert(!GV->isDeclaration() &&
464          "Only globals with definition can force usage.");
465   LLVMUsed.push_back(GV);
466 }
467 
468 void CodeGenModule::EmitLLVMUsed() {
469   // Don't create llvm.used if there is no need.
470   if (LLVMUsed.empty())
471     return;
472 
473   const llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(VMContext);
474 
475   // Convert LLVMUsed to what ConstantArray needs.
476   std::vector<llvm::Constant*> UsedArray;
477   UsedArray.resize(LLVMUsed.size());
478   for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) {
479     UsedArray[i] =
480      llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]),
481                                       i8PTy);
482   }
483 
484   if (UsedArray.empty())
485     return;
486   llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, UsedArray.size());
487 
488   llvm::GlobalVariable *GV =
489     new llvm::GlobalVariable(getModule(), ATy, false,
490                              llvm::GlobalValue::AppendingLinkage,
491                              llvm::ConstantArray::get(ATy, UsedArray),
492                              "llvm.used");
493 
494   GV->setSection("llvm.metadata");
495 }
496 
497 void CodeGenModule::EmitDeferred() {
498   // Emit code for any potentially referenced deferred decls.  Since a
499   // previously unused static decl may become used during the generation of code
500   // for a static function, iterate until no  changes are made.
501 
502   while (!DeferredDeclsToEmit.empty() || !DeferredVTables.empty()) {
503     if (!DeferredVTables.empty()) {
504       const CXXRecordDecl *RD = DeferredVTables.back();
505       DeferredVTables.pop_back();
506       getVTables().GenerateClassData(getVTableLinkage(RD), RD);
507       continue;
508     }
509 
510     GlobalDecl D = DeferredDeclsToEmit.back();
511     DeferredDeclsToEmit.pop_back();
512 
513     // Look it up to see if it was defined with a stronger definition (e.g. an
514     // extern inline function with a strong function redefinition).  If so,
515     // just ignore the deferred decl.
516     MangleBuffer Name;
517     getMangledName(Name, D);
518     llvm::GlobalValue *CGRef = GetGlobalValue(Name);
519     assert(CGRef && "Deferred decl wasn't referenced?");
520 
521     if (!CGRef->isDeclaration())
522       continue;
523 
524     // Otherwise, emit the definition and move on to the next one.
525     EmitGlobalDefinition(D);
526   }
527 }
528 
529 /// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
530 /// annotation information for a given GlobalValue.  The annotation struct is
531 /// {i8 *, i8 *, i8 *, i32}.  The first field is a constant expression, the
532 /// GlobalValue being annotated.  The second field is the constant string
533 /// created from the AnnotateAttr's annotation.  The third field is a constant
534 /// string containing the name of the translation unit.  The fourth field is
535 /// the line number in the file of the annotated value declaration.
536 ///
537 /// FIXME: this does not unique the annotation string constants, as llvm-gcc
538 ///        appears to.
539 ///
540 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
541                                                 const AnnotateAttr *AA,
542                                                 unsigned LineNo) {
543   llvm::Module *M = &getModule();
544 
545   // get [N x i8] constants for the annotation string, and the filename string
546   // which are the 2nd and 3rd elements of the global annotation structure.
547   const llvm::Type *SBP = llvm::Type::getInt8PtrTy(VMContext);
548   llvm::Constant *anno = llvm::ConstantArray::get(VMContext,
549                                                   AA->getAnnotation(), true);
550   llvm::Constant *unit = llvm::ConstantArray::get(VMContext,
551                                                   M->getModuleIdentifier(),
552                                                   true);
553 
554   // Get the two global values corresponding to the ConstantArrays we just
555   // created to hold the bytes of the strings.
556   llvm::GlobalValue *annoGV =
557     new llvm::GlobalVariable(*M, anno->getType(), false,
558                              llvm::GlobalValue::PrivateLinkage, anno,
559                              GV->getName());
560   // translation unit name string, emitted into the llvm.metadata section.
561   llvm::GlobalValue *unitGV =
562     new llvm::GlobalVariable(*M, unit->getType(), false,
563                              llvm::GlobalValue::PrivateLinkage, unit,
564                              ".str");
565 
566   // Create the ConstantStruct for the global annotation.
567   llvm::Constant *Fields[4] = {
568     llvm::ConstantExpr::getBitCast(GV, SBP),
569     llvm::ConstantExpr::getBitCast(annoGV, SBP),
570     llvm::ConstantExpr::getBitCast(unitGV, SBP),
571     llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), LineNo)
572   };
573   return llvm::ConstantStruct::get(VMContext, Fields, 4, false);
574 }
575 
576 bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
577   // Never defer when EmitAllDecls is specified or the decl has
578   // attribute used.
579   if (Features.EmitAllDecls || Global->hasAttr<UsedAttr>())
580     return false;
581 
582   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
583     // Constructors and destructors should never be deferred.
584     if (FD->hasAttr<ConstructorAttr>() ||
585         FD->hasAttr<DestructorAttr>())
586       return false;
587 
588     // The key function for a class must never be deferred.
589     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Global)) {
590       const CXXRecordDecl *RD = MD->getParent();
591       if (MD->isOutOfLine() && RD->isDynamicClass()) {
592         const CXXMethodDecl *KeyFunction = getContext().getKeyFunction(RD);
593         if (KeyFunction &&
594             KeyFunction->getCanonicalDecl() == MD->getCanonicalDecl())
595           return false;
596       }
597     }
598 
599     GVALinkage Linkage = GetLinkageForFunction(getContext(), FD, Features);
600 
601     // static, static inline, always_inline, and extern inline functions can
602     // always be deferred.  Normal inline functions can be deferred in C99/C++.
603     // Implicit template instantiations can also be deferred in C++.
604     if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
605         Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
606       return true;
607     return false;
608   }
609 
610   const VarDecl *VD = cast<VarDecl>(Global);
611   assert(VD->isFileVarDecl() && "Invalid decl");
612 
613   // We never want to defer structs that have non-trivial constructors or
614   // destructors.
615 
616   // FIXME: Handle references.
617   if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
618     if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
619       if (!RD->hasTrivialConstructor() || !RD->hasTrivialDestructor())
620         return false;
621     }
622   }
623 
624   // Static data may be deferred, but out-of-line static data members
625   // cannot be.
626   Linkage L = VD->getLinkage();
627   if (L == ExternalLinkage && getContext().getLangOptions().CPlusPlus &&
628       VD->getType()->getLinkage() == UniqueExternalLinkage)
629     L = UniqueExternalLinkage;
630 
631   switch (L) {
632   case NoLinkage:
633   case InternalLinkage:
634   case UniqueExternalLinkage:
635     // Initializer has side effects?
636     if (VD->getInit() && VD->getInit()->HasSideEffects(Context))
637       return false;
638     return !(VD->isStaticDataMember() && VD->isOutOfLine());
639 
640   case ExternalLinkage:
641     break;
642   }
643 
644   return false;
645 }
646 
647 llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
648   const AliasAttr *AA = VD->getAttr<AliasAttr>();
649   assert(AA && "No alias?");
650 
651   const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
652 
653   // See if there is already something with the target's name in the module.
654   llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
655 
656   llvm::Constant *Aliasee;
657   if (isa<llvm::FunctionType>(DeclTy))
658     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl());
659   else
660     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
661                                     llvm::PointerType::getUnqual(DeclTy), 0);
662   if (!Entry) {
663     llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee);
664     F->setLinkage(llvm::Function::ExternalWeakLinkage);
665     WeakRefReferences.insert(F);
666   }
667 
668   return Aliasee;
669 }
670 
671 void CodeGenModule::EmitGlobal(GlobalDecl GD) {
672   const ValueDecl *Global = cast<ValueDecl>(GD.getDecl());
673 
674   // Weak references don't produce any output by themselves.
675   if (Global->hasAttr<WeakRefAttr>())
676     return;
677 
678   // If this is an alias definition (which otherwise looks like a declaration)
679   // emit it now.
680   if (Global->hasAttr<AliasAttr>())
681     return EmitAliasDefinition(GD);
682 
683   // Ignore declarations, they will be emitted on their first use.
684   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
685     // Forward declarations are emitted lazily on first use.
686     if (!FD->isThisDeclarationADefinition())
687       return;
688   } else {
689     const VarDecl *VD = cast<VarDecl>(Global);
690     assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
691 
692     if (VD->isThisDeclarationADefinition() != VarDecl::Definition)
693       return;
694   }
695 
696   // Defer code generation when possible if this is a static definition, inline
697   // function etc.  These we only want to emit if they are used.
698   if (!MayDeferGeneration(Global)) {
699     // Emit the definition if it can't be deferred.
700     EmitGlobalDefinition(GD);
701     return;
702   }
703 
704   // If the value has already been used, add it directly to the
705   // DeferredDeclsToEmit list.
706   MangleBuffer MangledName;
707   getMangledName(MangledName, GD);
708   if (GetGlobalValue(MangledName))
709     DeferredDeclsToEmit.push_back(GD);
710   else {
711     // Otherwise, remember that we saw a deferred decl with this name.  The
712     // first use of the mangled name will cause it to move into
713     // DeferredDeclsToEmit.
714     DeferredDecls[MangledName] = GD;
715   }
716 }
717 
718 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) {
719   const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
720 
721   PrettyStackTraceDecl CrashInfo((ValueDecl *)D, D->getLocation(),
722                                  Context.getSourceManager(),
723                                  "Generating code for declaration");
724 
725   if (isa<CXXMethodDecl>(D))
726     getVTables().EmitVTableRelatedData(GD);
727 
728   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
729     return EmitCXXConstructor(CD, GD.getCtorType());
730 
731   if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D))
732     return EmitCXXDestructor(DD, GD.getDtorType());
733 
734   if (isa<FunctionDecl>(D))
735     return EmitGlobalFunctionDefinition(GD);
736 
737   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
738     return EmitGlobalVarDefinition(VD);
739 
740   assert(0 && "Invalid argument to EmitGlobalDefinition()");
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     llvm::Value::use_iterator I = UI++; // Increment before the CI is erased.
1218     llvm::CallInst *CI = dyn_cast<llvm::CallInst>(*I);
1219     llvm::CallSite CS(CI);
1220     if (!CI || !CS.isCallee(I)) continue;
1221 
1222     // If the return types don't match exactly, and if the call isn't dead, then
1223     // we can't transform this call.
1224     if (CI->getType() != NewRetTy && !CI->use_empty())
1225       continue;
1226 
1227     // If the function was passed too few arguments, don't transform.  If extra
1228     // arguments were passed, we silently drop them.  If any of the types
1229     // mismatch, we don't transform.
1230     unsigned ArgNo = 0;
1231     bool DontTransform = false;
1232     for (llvm::Function::arg_iterator AI = NewFn->arg_begin(),
1233          E = NewFn->arg_end(); AI != E; ++AI, ++ArgNo) {
1234       if (CS.arg_size() == ArgNo ||
1235           CS.getArgument(ArgNo)->getType() != AI->getType()) {
1236         DontTransform = true;
1237         break;
1238       }
1239     }
1240     if (DontTransform)
1241       continue;
1242 
1243     // Okay, we can transform this.  Create the new call instruction and copy
1244     // over the required information.
1245     ArgList.append(CS.arg_begin(), CS.arg_begin() + ArgNo);
1246     llvm::CallInst *NewCall = llvm::CallInst::Create(NewFn, ArgList.begin(),
1247                                                      ArgList.end(), "", CI);
1248     ArgList.clear();
1249     if (!NewCall->getType()->isVoidTy())
1250       NewCall->takeName(CI);
1251     NewCall->setAttributes(CI->getAttributes());
1252     NewCall->setCallingConv(CI->getCallingConv());
1253 
1254     // Finally, remove the old call, replacing any uses with the new one.
1255     if (!CI->use_empty())
1256       CI->replaceAllUsesWith(NewCall);
1257 
1258     // Copy debug location attached to CI.
1259     if (!CI->getDebugLoc().isUnknown())
1260       NewCall->setDebugLoc(CI->getDebugLoc());
1261     CI->eraseFromParent();
1262   }
1263 }
1264 
1265 
1266 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) {
1267   const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
1268   const llvm::FunctionType *Ty = getTypes().GetFunctionType(GD);
1269   getMangleContext().mangleInitDiscriminator();
1270   // Get or create the prototype for the function.
1271   llvm::Constant *Entry = GetAddrOfFunction(GD, Ty);
1272 
1273   // Strip off a bitcast if we got one back.
1274   if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
1275     assert(CE->getOpcode() == llvm::Instruction::BitCast);
1276     Entry = CE->getOperand(0);
1277   }
1278 
1279 
1280   if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
1281     llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
1282 
1283     // If the types mismatch then we have to rewrite the definition.
1284     assert(OldFn->isDeclaration() &&
1285            "Shouldn't replace non-declaration");
1286 
1287     // F is the Function* for the one with the wrong type, we must make a new
1288     // Function* and update everything that used F (a declaration) with the new
1289     // Function* (which will be a definition).
1290     //
1291     // This happens if there is a prototype for a function
1292     // (e.g. "int f()") and then a definition of a different type
1293     // (e.g. "int f(int x)").  Move the old function aside so that it
1294     // doesn't interfere with GetAddrOfFunction.
1295     OldFn->setName(llvm::StringRef());
1296     llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
1297 
1298     // If this is an implementation of a function without a prototype, try to
1299     // replace any existing uses of the function (which may be calls) with uses
1300     // of the new function
1301     if (D->getType()->isFunctionNoProtoType()) {
1302       ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
1303       OldFn->removeDeadConstantUsers();
1304     }
1305 
1306     // Replace uses of F with the Function we will endow with a body.
1307     if (!Entry->use_empty()) {
1308       llvm::Constant *NewPtrForOldDecl =
1309         llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
1310       Entry->replaceAllUsesWith(NewPtrForOldDecl);
1311     }
1312 
1313     // Ok, delete the old function now, which is dead.
1314     OldFn->eraseFromParent();
1315 
1316     Entry = NewFn;
1317   }
1318 
1319   llvm::Function *Fn = cast<llvm::Function>(Entry);
1320 
1321   CodeGenFunction(*this).GenerateCode(D, Fn);
1322 
1323   SetFunctionDefinitionAttributes(D, Fn);
1324   SetLLVMFunctionAttributesForDefinition(D, Fn);
1325 
1326   if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
1327     AddGlobalCtor(Fn, CA->getPriority());
1328   if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
1329     AddGlobalDtor(Fn, DA->getPriority());
1330 }
1331 
1332 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
1333   const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
1334   const AliasAttr *AA = D->getAttr<AliasAttr>();
1335   assert(AA && "Not an alias?");
1336 
1337   MangleBuffer MangledName;
1338   getMangledName(MangledName, GD);
1339 
1340   // If there is a definition in the module, then it wins over the alias.
1341   // This is dubious, but allow it to be safe.  Just ignore the alias.
1342   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1343   if (Entry && !Entry->isDeclaration())
1344     return;
1345 
1346   const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
1347 
1348   // Create a reference to the named value.  This ensures that it is emitted
1349   // if a deferred decl.
1350   llvm::Constant *Aliasee;
1351   if (isa<llvm::FunctionType>(DeclTy))
1352     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl());
1353   else
1354     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
1355                                     llvm::PointerType::getUnqual(DeclTy), 0);
1356 
1357   // Create the new alias itself, but don't set a name yet.
1358   llvm::GlobalValue *GA =
1359     new llvm::GlobalAlias(Aliasee->getType(),
1360                           llvm::Function::ExternalLinkage,
1361                           "", Aliasee, &getModule());
1362 
1363   if (Entry) {
1364     assert(Entry->isDeclaration());
1365 
1366     // If there is a declaration in the module, then we had an extern followed
1367     // by the alias, as in:
1368     //   extern int test6();
1369     //   ...
1370     //   int test6() __attribute__((alias("test7")));
1371     //
1372     // Remove it and replace uses of it with the alias.
1373     GA->takeName(Entry);
1374 
1375     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
1376                                                           Entry->getType()));
1377     Entry->eraseFromParent();
1378   } else {
1379     GA->setName(MangledName.getString());
1380   }
1381 
1382   // Set attributes which are particular to an alias; this is a
1383   // specialization of the attributes which may be set on a global
1384   // variable/function.
1385   if (D->hasAttr<DLLExportAttr>()) {
1386     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1387       // The dllexport attribute is ignored for undefined symbols.
1388       if (FD->getBody())
1389         GA->setLinkage(llvm::Function::DLLExportLinkage);
1390     } else {
1391       GA->setLinkage(llvm::Function::DLLExportLinkage);
1392     }
1393   } else if (D->hasAttr<WeakAttr>() ||
1394              D->hasAttr<WeakRefAttr>() ||
1395              D->hasAttr<WeakImportAttr>()) {
1396     GA->setLinkage(llvm::Function::WeakAnyLinkage);
1397   }
1398 
1399   SetCommonAttributes(D, GA);
1400 }
1401 
1402 /// getBuiltinLibFunction - Given a builtin id for a function like
1403 /// "__builtin_fabsf", return a Function* for "fabsf".
1404 llvm::Value *CodeGenModule::getBuiltinLibFunction(const FunctionDecl *FD,
1405                                                   unsigned BuiltinID) {
1406   assert((Context.BuiltinInfo.isLibFunction(BuiltinID) ||
1407           Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) &&
1408          "isn't a lib fn");
1409 
1410   // Get the name, skip over the __builtin_ prefix (if necessary).
1411   const char *Name = Context.BuiltinInfo.GetName(BuiltinID);
1412   if (Context.BuiltinInfo.isLibFunction(BuiltinID))
1413     Name += 10;
1414 
1415   const llvm::FunctionType *Ty =
1416     cast<llvm::FunctionType>(getTypes().ConvertType(FD->getType()));
1417 
1418   return GetOrCreateLLVMFunction(Name, Ty, GlobalDecl(FD));
1419 }
1420 
1421 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
1422                                             unsigned NumTys) {
1423   return llvm::Intrinsic::getDeclaration(&getModule(),
1424                                          (llvm::Intrinsic::ID)IID, Tys, NumTys);
1425 }
1426 
1427 
1428 llvm::Function *CodeGenModule::getMemCpyFn(const llvm::Type *DestType,
1429                                            const llvm::Type *SrcType,
1430                                            const llvm::Type *SizeType) {
1431   const llvm::Type *ArgTypes[3] = {DestType, SrcType, SizeType };
1432   return getIntrinsic(llvm::Intrinsic::memcpy, ArgTypes, 3);
1433 }
1434 
1435 llvm::Function *CodeGenModule::getMemMoveFn(const llvm::Type *DestType,
1436                                             const llvm::Type *SrcType,
1437                                             const llvm::Type *SizeType) {
1438   const llvm::Type *ArgTypes[3] = {DestType, SrcType, SizeType };
1439   return getIntrinsic(llvm::Intrinsic::memmove, ArgTypes, 3);
1440 }
1441 
1442 llvm::Function *CodeGenModule::getMemSetFn(const llvm::Type *DestType,
1443                                            const llvm::Type *SizeType) {
1444   const llvm::Type *ArgTypes[2] = { DestType, SizeType };
1445   return getIntrinsic(llvm::Intrinsic::memset, ArgTypes, 2);
1446 }
1447 
1448 static llvm::StringMapEntry<llvm::Constant*> &
1449 GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
1450                          const StringLiteral *Literal,
1451                          bool TargetIsLSB,
1452                          bool &IsUTF16,
1453                          unsigned &StringLength) {
1454   unsigned NumBytes = Literal->getByteLength();
1455 
1456   // Check for simple case.
1457   if (!Literal->containsNonAsciiOrNull()) {
1458     StringLength = NumBytes;
1459     return Map.GetOrCreateValue(llvm::StringRef(Literal->getStrData(),
1460                                                 StringLength));
1461   }
1462 
1463   // Otherwise, convert the UTF8 literals into a byte string.
1464   llvm::SmallVector<UTF16, 128> ToBuf(NumBytes);
1465   const UTF8 *FromPtr = (UTF8 *)Literal->getStrData();
1466   UTF16 *ToPtr = &ToBuf[0];
1467 
1468   ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1469                                                &ToPtr, ToPtr + NumBytes,
1470                                                strictConversion);
1471 
1472   // Check for conversion failure.
1473   if (Result != conversionOK) {
1474     // FIXME: Have Sema::CheckObjCString() validate the UTF-8 string and remove
1475     // this duplicate code.
1476     assert(Result == sourceIllegal && "UTF-8 to UTF-16 conversion failed");
1477     StringLength = NumBytes;
1478     return Map.GetOrCreateValue(llvm::StringRef(Literal->getStrData(),
1479                                                 StringLength));
1480   }
1481 
1482   // ConvertUTF8toUTF16 returns the length in ToPtr.
1483   StringLength = ToPtr - &ToBuf[0];
1484 
1485   // Render the UTF-16 string into a byte array and convert to the target byte
1486   // order.
1487   //
1488   // FIXME: This isn't something we should need to do here.
1489   llvm::SmallString<128> AsBytes;
1490   AsBytes.reserve(StringLength * 2);
1491   for (unsigned i = 0; i != StringLength; ++i) {
1492     unsigned short Val = ToBuf[i];
1493     if (TargetIsLSB) {
1494       AsBytes.push_back(Val & 0xFF);
1495       AsBytes.push_back(Val >> 8);
1496     } else {
1497       AsBytes.push_back(Val >> 8);
1498       AsBytes.push_back(Val & 0xFF);
1499     }
1500   }
1501   // Append one extra null character, the second is automatically added by our
1502   // caller.
1503   AsBytes.push_back(0);
1504 
1505   IsUTF16 = true;
1506   return Map.GetOrCreateValue(llvm::StringRef(AsBytes.data(), AsBytes.size()));
1507 }
1508 
1509 llvm::Constant *
1510 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
1511   unsigned StringLength = 0;
1512   bool isUTF16 = false;
1513   llvm::StringMapEntry<llvm::Constant*> &Entry =
1514     GetConstantCFStringEntry(CFConstantStringMap, Literal,
1515                              getTargetData().isLittleEndian(),
1516                              isUTF16, StringLength);
1517 
1518   if (llvm::Constant *C = Entry.getValue())
1519     return C;
1520 
1521   llvm::Constant *Zero =
1522       llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext));
1523   llvm::Constant *Zeros[] = { Zero, Zero };
1524 
1525   // If we don't already have it, get __CFConstantStringClassReference.
1526   if (!CFConstantStringClassRef) {
1527     const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
1528     Ty = llvm::ArrayType::get(Ty, 0);
1529     llvm::Constant *GV = CreateRuntimeVariable(Ty,
1530                                            "__CFConstantStringClassReference");
1531     // Decay array -> ptr
1532     CFConstantStringClassRef =
1533       llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1534   }
1535 
1536   QualType CFTy = getContext().getCFConstantStringType();
1537 
1538   const llvm::StructType *STy =
1539     cast<llvm::StructType>(getTypes().ConvertType(CFTy));
1540 
1541   std::vector<llvm::Constant*> Fields(4);
1542 
1543   // Class pointer.
1544   Fields[0] = CFConstantStringClassRef;
1545 
1546   // Flags.
1547   const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
1548   Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
1549     llvm::ConstantInt::get(Ty, 0x07C8);
1550 
1551   // String pointer.
1552   llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str());
1553 
1554   llvm::GlobalValue::LinkageTypes Linkage;
1555   bool isConstant;
1556   if (isUTF16) {
1557     // FIXME: why do utf strings get "_" labels instead of "L" labels?
1558     Linkage = llvm::GlobalValue::InternalLinkage;
1559     // Note: -fwritable-strings doesn't make unicode CFStrings writable, but
1560     // does make plain ascii ones writable.
1561     isConstant = true;
1562   } else {
1563     Linkage = llvm::GlobalValue::PrivateLinkage;
1564     isConstant = !Features.WritableStrings;
1565   }
1566 
1567   llvm::GlobalVariable *GV =
1568     new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
1569                              ".str");
1570   if (isUTF16) {
1571     CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
1572     GV->setAlignment(Align.getQuantity());
1573   }
1574   Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1575 
1576   // String length.
1577   Ty = getTypes().ConvertType(getContext().LongTy);
1578   Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
1579 
1580   // The struct.
1581   C = llvm::ConstantStruct::get(STy, Fields);
1582   GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
1583                                 llvm::GlobalVariable::PrivateLinkage, C,
1584                                 "_unnamed_cfstring_");
1585   if (const char *Sect = getContext().Target.getCFStringSection())
1586     GV->setSection(Sect);
1587   Entry.setValue(GV);
1588 
1589   return GV;
1590 }
1591 
1592 /// GetStringForStringLiteral - Return the appropriate bytes for a
1593 /// string literal, properly padded to match the literal type.
1594 std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
1595   const char *StrData = E->getStrData();
1596   unsigned Len = E->getByteLength();
1597 
1598   const ConstantArrayType *CAT =
1599     getContext().getAsConstantArrayType(E->getType());
1600   assert(CAT && "String isn't pointer or array!");
1601 
1602   // Resize the string to the right size.
1603   std::string Str(StrData, StrData+Len);
1604   uint64_t RealLen = CAT->getSize().getZExtValue();
1605 
1606   if (E->isWide())
1607     RealLen *= getContext().Target.getWCharWidth()/8;
1608 
1609   Str.resize(RealLen, '\0');
1610 
1611   return Str;
1612 }
1613 
1614 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
1615 /// constant array for the given string literal.
1616 llvm::Constant *
1617 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
1618   // FIXME: This can be more efficient.
1619   // FIXME: We shouldn't need to bitcast the constant in the wide string case.
1620   llvm::Constant *C = GetAddrOfConstantString(GetStringForStringLiteral(S));
1621   if (S->isWide()) {
1622     llvm::Type *DestTy =
1623         llvm::PointerType::getUnqual(getTypes().ConvertType(S->getType()));
1624     C = llvm::ConstantExpr::getBitCast(C, DestTy);
1625   }
1626   return C;
1627 }
1628 
1629 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
1630 /// array for the given ObjCEncodeExpr node.
1631 llvm::Constant *
1632 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
1633   std::string Str;
1634   getContext().getObjCEncodingForType(E->getEncodedType(), Str);
1635 
1636   return GetAddrOfConstantCString(Str);
1637 }
1638 
1639 
1640 /// GenerateWritableString -- Creates storage for a string literal.
1641 static llvm::Constant *GenerateStringLiteral(const std::string &str,
1642                                              bool constant,
1643                                              CodeGenModule &CGM,
1644                                              const char *GlobalName) {
1645   // Create Constant for this string literal. Don't add a '\0'.
1646   llvm::Constant *C =
1647       llvm::ConstantArray::get(CGM.getLLVMContext(), str, false);
1648 
1649   // Create a global variable for this string
1650   return new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant,
1651                                   llvm::GlobalValue::PrivateLinkage,
1652                                   C, GlobalName);
1653 }
1654 
1655 /// GetAddrOfConstantString - Returns a pointer to a character array
1656 /// containing the literal. This contents are exactly that of the
1657 /// given string, i.e. it will not be null terminated automatically;
1658 /// see GetAddrOfConstantCString. Note that whether the result is
1659 /// actually a pointer to an LLVM constant depends on
1660 /// Feature.WriteableStrings.
1661 ///
1662 /// The result has pointer to array type.
1663 llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str,
1664                                                        const char *GlobalName) {
1665   bool IsConstant = !Features.WritableStrings;
1666 
1667   // Get the default prefix if a name wasn't specified.
1668   if (!GlobalName)
1669     GlobalName = ".str";
1670 
1671   // Don't share any string literals if strings aren't constant.
1672   if (!IsConstant)
1673     return GenerateStringLiteral(str, false, *this, GlobalName);
1674 
1675   llvm::StringMapEntry<llvm::Constant *> &Entry =
1676     ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
1677 
1678   if (Entry.getValue())
1679     return Entry.getValue();
1680 
1681   // Create a global variable for this.
1682   llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName);
1683   Entry.setValue(C);
1684   return C;
1685 }
1686 
1687 /// GetAddrOfConstantCString - Returns a pointer to a character
1688 /// array containing the literal and a terminating '\-'
1689 /// character. The result has pointer to array type.
1690 llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str,
1691                                                         const char *GlobalName){
1692   return GetAddrOfConstantString(str + '\0', GlobalName);
1693 }
1694 
1695 /// EmitObjCPropertyImplementations - Emit information for synthesized
1696 /// properties for an implementation.
1697 void CodeGenModule::EmitObjCPropertyImplementations(const
1698                                                     ObjCImplementationDecl *D) {
1699   for (ObjCImplementationDecl::propimpl_iterator
1700          i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) {
1701     ObjCPropertyImplDecl *PID = *i;
1702 
1703     // Dynamic is just for type-checking.
1704     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1705       ObjCPropertyDecl *PD = PID->getPropertyDecl();
1706 
1707       // Determine which methods need to be implemented, some may have
1708       // been overridden. Note that ::isSynthesized is not the method
1709       // we want, that just indicates if the decl came from a
1710       // property. What we want to know is if the method is defined in
1711       // this implementation.
1712       if (!D->getInstanceMethod(PD->getGetterName()))
1713         CodeGenFunction(*this).GenerateObjCGetter(
1714                                  const_cast<ObjCImplementationDecl *>(D), PID);
1715       if (!PD->isReadOnly() &&
1716           !D->getInstanceMethod(PD->getSetterName()))
1717         CodeGenFunction(*this).GenerateObjCSetter(
1718                                  const_cast<ObjCImplementationDecl *>(D), PID);
1719     }
1720   }
1721 }
1722 
1723 /// EmitNamespace - Emit all declarations in a namespace.
1724 void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
1725   for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end();
1726        I != E; ++I)
1727     EmitTopLevelDecl(*I);
1728 }
1729 
1730 // EmitLinkageSpec - Emit all declarations in a linkage spec.
1731 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
1732   if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
1733       LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
1734     ErrorUnsupported(LSD, "linkage spec");
1735     return;
1736   }
1737 
1738   for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end();
1739        I != E; ++I)
1740     EmitTopLevelDecl(*I);
1741 }
1742 
1743 /// EmitTopLevelDecl - Emit code for a single top level declaration.
1744 void CodeGenModule::EmitTopLevelDecl(Decl *D) {
1745   // If an error has occurred, stop code generation, but continue
1746   // parsing and semantic analysis (to ensure all warnings and errors
1747   // are emitted).
1748   if (Diags.hasErrorOccurred())
1749     return;
1750 
1751   // Ignore dependent declarations.
1752   if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
1753     return;
1754 
1755   switch (D->getKind()) {
1756   case Decl::CXXConversion:
1757   case Decl::CXXMethod:
1758   case Decl::Function:
1759     // Skip function templates
1760     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate())
1761       return;
1762 
1763     EmitGlobal(cast<FunctionDecl>(D));
1764     break;
1765 
1766   case Decl::Var:
1767     EmitGlobal(cast<VarDecl>(D));
1768     break;
1769 
1770   // C++ Decls
1771   case Decl::Namespace:
1772     EmitNamespace(cast<NamespaceDecl>(D));
1773     break;
1774     // No code generation needed.
1775   case Decl::UsingShadow:
1776   case Decl::Using:
1777   case Decl::UsingDirective:
1778   case Decl::ClassTemplate:
1779   case Decl::FunctionTemplate:
1780   case Decl::NamespaceAlias:
1781     break;
1782   case Decl::CXXConstructor:
1783     // Skip function templates
1784     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate())
1785       return;
1786 
1787     EmitCXXConstructors(cast<CXXConstructorDecl>(D));
1788     break;
1789   case Decl::CXXDestructor:
1790     EmitCXXDestructors(cast<CXXDestructorDecl>(D));
1791     break;
1792 
1793   case Decl::StaticAssert:
1794     // Nothing to do.
1795     break;
1796 
1797   // Objective-C Decls
1798 
1799   // Forward declarations, no (immediate) code generation.
1800   case Decl::ObjCClass:
1801   case Decl::ObjCForwardProtocol:
1802   case Decl::ObjCCategory:
1803   case Decl::ObjCInterface:
1804     break;
1805 
1806   case Decl::ObjCProtocol:
1807     Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
1808     break;
1809 
1810   case Decl::ObjCCategoryImpl:
1811     // Categories have properties but don't support synthesize so we
1812     // can ignore them here.
1813     Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
1814     break;
1815 
1816   case Decl::ObjCImplementation: {
1817     ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
1818     EmitObjCPropertyImplementations(OMD);
1819     Runtime->GenerateClass(OMD);
1820     break;
1821   }
1822   case Decl::ObjCMethod: {
1823     ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
1824     // If this is not a prototype, emit the body.
1825     if (OMD->getBody())
1826       CodeGenFunction(*this).GenerateObjCMethod(OMD);
1827     break;
1828   }
1829   case Decl::ObjCCompatibleAlias:
1830     // compatibility-alias is a directive and has no code gen.
1831     break;
1832 
1833   case Decl::LinkageSpec:
1834     EmitLinkageSpec(cast<LinkageSpecDecl>(D));
1835     break;
1836 
1837   case Decl::FileScopeAsm: {
1838     FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
1839     llvm::StringRef AsmString = AD->getAsmString()->getString();
1840 
1841     const std::string &S = getModule().getModuleInlineAsm();
1842     if (S.empty())
1843       getModule().setModuleInlineAsm(AsmString);
1844     else
1845       getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
1846     break;
1847   }
1848 
1849   default:
1850     // Make sure we handled everything we should, every other kind is a
1851     // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
1852     // function. Need to recode Decl::Kind to do that easily.
1853     assert(isa<TypeDecl>(D) && "Unsupported decl kind");
1854   }
1855 }
1856