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