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