xref: /llvm-project/clang/lib/CodeGen/CodeGenModule.cpp (revision d8bb3aff76145e391a0df4be7591021d083bc258)
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 (isa<CXXMethodDecl>(D))
731     getVTables().EmitVTableRelatedData(GD);
732 
733   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
734     return EmitCXXConstructor(CD, GD.getCtorType());
735 
736   if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D))
737     return EmitCXXDestructor(DD, GD.getDtorType());
738 
739   if (isa<FunctionDecl>(D))
740     return EmitGlobalFunctionDefinition(GD);
741 
742   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
743     return EmitGlobalVarDefinition(VD);
744 
745   assert(0 && "Invalid argument to EmitGlobalDefinition()");
746 }
747 
748 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
749 /// module, create and return an llvm Function with the specified type. If there
750 /// is something in the module with the specified name, return it potentially
751 /// bitcasted to the right type.
752 ///
753 /// If D is non-null, it specifies a decl that correspond to this.  This is used
754 /// to set the attributes on the function when it is first created.
755 llvm::Constant *
756 CodeGenModule::GetOrCreateLLVMFunction(llvm::StringRef MangledName,
757                                        const llvm::Type *Ty,
758                                        GlobalDecl D) {
759   // Lookup the entry, lazily creating it if necessary.
760   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
761   if (Entry) {
762     if (WeakRefReferences.count(Entry)) {
763       const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl());
764       if (FD && !FD->hasAttr<WeakAttr>())
765         Entry->setLinkage(llvm::Function::ExternalLinkage);
766 
767       WeakRefReferences.erase(Entry);
768     }
769 
770     if (Entry->getType()->getElementType() == Ty)
771       return Entry;
772 
773     // Make sure the result is of the correct type.
774     const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
775     return llvm::ConstantExpr::getBitCast(Entry, PTy);
776   }
777 
778   // This function doesn't have a complete type (for example, the return
779   // type is an incomplete struct). Use a fake type instead, and make
780   // sure not to try to set attributes.
781   bool IsIncompleteFunction = false;
782 
783   const llvm::FunctionType *FTy;
784   if (isa<llvm::FunctionType>(Ty)) {
785     FTy = cast<llvm::FunctionType>(Ty);
786   } else {
787     FTy = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
788                                   std::vector<const llvm::Type*>(), false);
789     IsIncompleteFunction = true;
790   }
791   llvm::Function *F = llvm::Function::Create(FTy,
792                                              llvm::Function::ExternalLinkage,
793                                              MangledName, &getModule());
794   assert(F->getName() == MangledName && "name was uniqued!");
795   if (D.getDecl())
796     SetFunctionAttributes(D, F, IsIncompleteFunction);
797 
798   // This is the first use or definition of a mangled name.  If there is a
799   // deferred decl with this name, remember that we need to emit it at the end
800   // of the file.
801   llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
802   if (DDI != DeferredDecls.end()) {
803     // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
804     // list, and remove it from DeferredDecls (since we don't need it anymore).
805     DeferredDeclsToEmit.push_back(DDI->second);
806     DeferredDecls.erase(DDI);
807   } else if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl())) {
808     // If this the first reference to a C++ inline function in a class, queue up
809     // the deferred function body for emission.  These are not seen as
810     // top-level declarations.
811     if (FD->isThisDeclarationADefinition() && MayDeferGeneration(FD))
812       DeferredDeclsToEmit.push_back(D);
813     // A called constructor which has no definition or declaration need be
814     // synthesized.
815     else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
816       if (CD->isImplicit()) {
817         assert(CD->isUsed() && "Sema doesn't consider constructor as used.");
818         DeferredDeclsToEmit.push_back(D);
819       }
820     } else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD)) {
821       if (DD->isImplicit()) {
822         assert(DD->isUsed() && "Sema doesn't consider destructor as used.");
823         DeferredDeclsToEmit.push_back(D);
824       }
825     } else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
826       if (MD->isCopyAssignment() && MD->isImplicit()) {
827         assert(MD->isUsed() && "Sema doesn't consider CopyAssignment as used.");
828         DeferredDeclsToEmit.push_back(D);
829       }
830     }
831   }
832 
833   // Make sure the result is of the requested type.
834   if (!IsIncompleteFunction) {
835     assert(F->getType()->getElementType() == Ty);
836     return F;
837   }
838 
839   const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
840   return llvm::ConstantExpr::getBitCast(F, PTy);
841 }
842 
843 /// GetAddrOfFunction - Return the address of the given function.  If Ty is
844 /// non-null, then this function will use the specified type if it has to
845 /// create it (this occurs when we see a definition of the function).
846 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
847                                                  const llvm::Type *Ty) {
848   // If there was no specific requested type, just convert it now.
849   if (!Ty)
850     Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
851   MangleBuffer MangledName;
852   getMangledName(MangledName, GD);
853   return GetOrCreateLLVMFunction(MangledName, Ty, GD);
854 }
855 
856 /// CreateRuntimeFunction - Create a new runtime function with the specified
857 /// type and name.
858 llvm::Constant *
859 CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy,
860                                      llvm::StringRef Name) {
861   return GetOrCreateLLVMFunction(Name, FTy, GlobalDecl());
862 }
863 
864 static bool DeclIsConstantGlobal(ASTContext &Context, const VarDecl *D) {
865   if (!D->getType().isConstant(Context) && !D->getType()->isReferenceType())
866     return false;
867   if (Context.getLangOptions().CPlusPlus &&
868       Context.getBaseElementType(D->getType())->getAs<RecordType>()) {
869     // FIXME: We should do something fancier here!
870     return false;
871   }
872   return true;
873 }
874 
875 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
876 /// create and return an llvm GlobalVariable with the specified type.  If there
877 /// is something in the module with the specified name, return it potentially
878 /// bitcasted to the right type.
879 ///
880 /// If D is non-null, it specifies a decl that correspond to this.  This is used
881 /// to set the attributes on the global when it is first created.
882 llvm::Constant *
883 CodeGenModule::GetOrCreateLLVMGlobal(llvm::StringRef MangledName,
884                                      const llvm::PointerType *Ty,
885                                      const VarDecl *D) {
886   // Lookup the entry, lazily creating it if necessary.
887   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
888   if (Entry) {
889     if (WeakRefReferences.count(Entry)) {
890       if (D && !D->hasAttr<WeakAttr>())
891         Entry->setLinkage(llvm::Function::ExternalLinkage);
892 
893       WeakRefReferences.erase(Entry);
894     }
895 
896     if (Entry->getType() == Ty)
897       return Entry;
898 
899     // Make sure the result is of the correct type.
900     return llvm::ConstantExpr::getBitCast(Entry, Ty);
901   }
902 
903   // This is the first use or definition of a mangled name.  If there is a
904   // deferred decl with this name, remember that we need to emit it at the end
905   // of the file.
906   llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
907   if (DDI != DeferredDecls.end()) {
908     // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
909     // list, and remove it from DeferredDecls (since we don't need it anymore).
910     DeferredDeclsToEmit.push_back(DDI->second);
911     DeferredDecls.erase(DDI);
912   }
913 
914   llvm::GlobalVariable *GV =
915     new llvm::GlobalVariable(getModule(), Ty->getElementType(), false,
916                              llvm::GlobalValue::ExternalLinkage,
917                              0, MangledName, 0,
918                              false, Ty->getAddressSpace());
919 
920   // Handle things which are present even on external declarations.
921   if (D) {
922     // FIXME: This code is overly simple and should be merged with other global
923     // handling.
924     GV->setConstant(DeclIsConstantGlobal(Context, D));
925 
926     // FIXME: Merge with other attribute handling code.
927     if (D->getStorageClass() == VarDecl::PrivateExtern)
928       GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
929 
930     if (D->hasAttr<WeakAttr>() ||
931         D->hasAttr<WeakImportAttr>())
932       GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
933 
934     GV->setThreadLocal(D->isThreadSpecified());
935   }
936 
937   return GV;
938 }
939 
940 
941 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
942 /// given global variable.  If Ty is non-null and if the global doesn't exist,
943 /// then it will be greated with the specified type instead of whatever the
944 /// normal requested type would be.
945 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
946                                                   const llvm::Type *Ty) {
947   assert(D->hasGlobalStorage() && "Not a global variable");
948   QualType ASTTy = D->getType();
949   if (Ty == 0)
950     Ty = getTypes().ConvertTypeForMem(ASTTy);
951 
952   const llvm::PointerType *PTy =
953     llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
954 
955   MangleBuffer MangledName;
956   getMangledName(MangledName, D);
957   return GetOrCreateLLVMGlobal(MangledName, PTy, D);
958 }
959 
960 /// CreateRuntimeVariable - Create a new runtime global variable with the
961 /// specified type and name.
962 llvm::Constant *
963 CodeGenModule::CreateRuntimeVariable(const llvm::Type *Ty,
964                                      llvm::StringRef Name) {
965   return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0);
966 }
967 
968 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
969   assert(!D->getInit() && "Cannot emit definite definitions here!");
970 
971   if (MayDeferGeneration(D)) {
972     // If we have not seen a reference to this variable yet, place it
973     // into the deferred declarations table to be emitted if needed
974     // later.
975     MangleBuffer MangledName;
976     getMangledName(MangledName, D);
977     if (!GetGlobalValue(MangledName)) {
978       DeferredDecls[MangledName] = D;
979       return;
980     }
981   }
982 
983   // The tentative definition is the only definition.
984   EmitGlobalVarDefinition(D);
985 }
986 
987 llvm::GlobalVariable::LinkageTypes
988 CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
989   if (RD->isInAnonymousNamespace() || !RD->hasLinkage())
990     return llvm::GlobalVariable::InternalLinkage;
991 
992   if (const CXXMethodDecl *KeyFunction
993                                     = RD->getASTContext().getKeyFunction(RD)) {
994     // If this class has a key function, use that to determine the linkage of
995     // the vtable.
996     const FunctionDecl *Def = 0;
997     if (KeyFunction->getBody(Def))
998       KeyFunction = cast<CXXMethodDecl>(Def);
999 
1000     switch (KeyFunction->getTemplateSpecializationKind()) {
1001       case TSK_Undeclared:
1002       case TSK_ExplicitSpecialization:
1003         if (KeyFunction->isInlined())
1004           return llvm::GlobalVariable::WeakODRLinkage;
1005 
1006         return llvm::GlobalVariable::ExternalLinkage;
1007 
1008       case TSK_ImplicitInstantiation:
1009       case TSK_ExplicitInstantiationDefinition:
1010         return llvm::GlobalVariable::WeakODRLinkage;
1011 
1012       case TSK_ExplicitInstantiationDeclaration:
1013         // FIXME: Use available_externally linkage. However, this currently
1014         // breaks LLVM's build due to undefined symbols.
1015         //      return llvm::GlobalVariable::AvailableExternallyLinkage;
1016         return llvm::GlobalVariable::WeakODRLinkage;
1017     }
1018   }
1019 
1020   switch (RD->getTemplateSpecializationKind()) {
1021   case TSK_Undeclared:
1022   case TSK_ExplicitSpecialization:
1023   case TSK_ImplicitInstantiation:
1024   case TSK_ExplicitInstantiationDefinition:
1025     return llvm::GlobalVariable::WeakODRLinkage;
1026 
1027   case TSK_ExplicitInstantiationDeclaration:
1028     // FIXME: Use available_externally linkage. However, this currently
1029     // breaks LLVM's build due to undefined symbols.
1030     //   return llvm::GlobalVariable::AvailableExternallyLinkage;
1031     return llvm::GlobalVariable::WeakODRLinkage;
1032   }
1033 
1034   // Silence GCC warning.
1035   return llvm::GlobalVariable::WeakODRLinkage;
1036 }
1037 
1038 static CodeGenModule::GVALinkage
1039 GetLinkageForVariable(ASTContext &Context, const VarDecl *VD) {
1040   // If this is a static data member, compute the kind of template
1041   // specialization. Otherwise, this variable is not part of a
1042   // template.
1043   TemplateSpecializationKind TSK = TSK_Undeclared;
1044   if (VD->isStaticDataMember())
1045     TSK = VD->getTemplateSpecializationKind();
1046 
1047   Linkage L = VD->getLinkage();
1048   if (L == ExternalLinkage && Context.getLangOptions().CPlusPlus &&
1049       VD->getType()->getLinkage() == UniqueExternalLinkage)
1050     L = UniqueExternalLinkage;
1051 
1052   switch (L) {
1053   case NoLinkage:
1054   case InternalLinkage:
1055   case UniqueExternalLinkage:
1056     return CodeGenModule::GVA_Internal;
1057 
1058   case ExternalLinkage:
1059     switch (TSK) {
1060     case TSK_Undeclared:
1061     case TSK_ExplicitSpecialization:
1062       return CodeGenModule::GVA_StrongExternal;
1063 
1064     case TSK_ExplicitInstantiationDeclaration:
1065       llvm_unreachable("Variable should not be instantiated");
1066       // Fall through to treat this like any other instantiation.
1067 
1068     case TSK_ExplicitInstantiationDefinition:
1069       return CodeGenModule::GVA_ExplicitTemplateInstantiation;
1070 
1071     case TSK_ImplicitInstantiation:
1072       return CodeGenModule::GVA_TemplateInstantiation;
1073     }
1074   }
1075 
1076   return CodeGenModule::GVA_StrongExternal;
1077 }
1078 
1079 CharUnits CodeGenModule::GetTargetTypeStoreSize(const llvm::Type *Ty) const {
1080     return CharUnits::fromQuantity(
1081       TheTargetData.getTypeStoreSizeInBits(Ty) / Context.getCharWidth());
1082 }
1083 
1084 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
1085   llvm::Constant *Init = 0;
1086   QualType ASTTy = D->getType();
1087   bool NonConstInit = false;
1088 
1089   const Expr *InitExpr = D->getAnyInitializer();
1090 
1091   if (!InitExpr) {
1092     // This is a tentative definition; tentative definitions are
1093     // implicitly initialized with { 0 }.
1094     //
1095     // Note that tentative definitions are only emitted at the end of
1096     // a translation unit, so they should never have incomplete
1097     // type. In addition, EmitTentativeDefinition makes sure that we
1098     // never attempt to emit a tentative definition if a real one
1099     // exists. A use may still exists, however, so we still may need
1100     // to do a RAUW.
1101     assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
1102     Init = EmitNullConstant(D->getType());
1103   } else {
1104     Init = EmitConstantExpr(InitExpr, D->getType());
1105     if (!Init) {
1106       QualType T = InitExpr->getType();
1107       if (D->getType()->isReferenceType())
1108         T = D->getType();
1109 
1110       if (getLangOptions().CPlusPlus) {
1111         EmitCXXGlobalVarDeclInitFunc(D);
1112         Init = EmitNullConstant(T);
1113         NonConstInit = true;
1114       } else {
1115         ErrorUnsupported(D, "static initializer");
1116         Init = llvm::UndefValue::get(getTypes().ConvertType(T));
1117       }
1118     }
1119   }
1120 
1121   const llvm::Type* InitType = Init->getType();
1122   llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
1123 
1124   // Strip off a bitcast if we got one back.
1125   if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
1126     assert(CE->getOpcode() == llvm::Instruction::BitCast ||
1127            // all zero index gep.
1128            CE->getOpcode() == llvm::Instruction::GetElementPtr);
1129     Entry = CE->getOperand(0);
1130   }
1131 
1132   // Entry is now either a Function or GlobalVariable.
1133   llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
1134 
1135   // We have a definition after a declaration with the wrong type.
1136   // We must make a new GlobalVariable* and update everything that used OldGV
1137   // (a declaration or tentative definition) with the new GlobalVariable*
1138   // (which will be a definition).
1139   //
1140   // This happens if there is a prototype for a global (e.g.
1141   // "extern int x[];") and then a definition of a different type (e.g.
1142   // "int x[10];"). This also happens when an initializer has a different type
1143   // from the type of the global (this happens with unions).
1144   if (GV == 0 ||
1145       GV->getType()->getElementType() != InitType ||
1146       GV->getType()->getAddressSpace() != ASTTy.getAddressSpace()) {
1147 
1148     // Move the old entry aside so that we'll create a new one.
1149     Entry->setName(llvm::StringRef());
1150 
1151     // Make a new global with the correct type, this is now guaranteed to work.
1152     GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
1153 
1154     // Replace all uses of the old global with the new global
1155     llvm::Constant *NewPtrForOldDecl =
1156         llvm::ConstantExpr::getBitCast(GV, Entry->getType());
1157     Entry->replaceAllUsesWith(NewPtrForOldDecl);
1158 
1159     // Erase the old global, since it is no longer used.
1160     cast<llvm::GlobalValue>(Entry)->eraseFromParent();
1161   }
1162 
1163   if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
1164     SourceManager &SM = Context.getSourceManager();
1165     AddAnnotation(EmitAnnotateAttr(GV, AA,
1166                               SM.getInstantiationLineNumber(D->getLocation())));
1167   }
1168 
1169   GV->setInitializer(Init);
1170 
1171   // If it is safe to mark the global 'constant', do so now.
1172   GV->setConstant(false);
1173   if (!NonConstInit && DeclIsConstantGlobal(Context, D))
1174     GV->setConstant(true);
1175 
1176   GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
1177 
1178   // Set the llvm linkage type as appropriate.
1179   GVALinkage Linkage = GetLinkageForVariable(getContext(), D);
1180   if (Linkage == GVA_Internal)
1181     GV->setLinkage(llvm::Function::InternalLinkage);
1182   else if (D->hasAttr<DLLImportAttr>())
1183     GV->setLinkage(llvm::Function::DLLImportLinkage);
1184   else if (D->hasAttr<DLLExportAttr>())
1185     GV->setLinkage(llvm::Function::DLLExportLinkage);
1186   else if (D->hasAttr<WeakAttr>()) {
1187     if (GV->isConstant())
1188       GV->setLinkage(llvm::GlobalVariable::WeakODRLinkage);
1189     else
1190       GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
1191   } else if (Linkage == GVA_TemplateInstantiation ||
1192              Linkage == GVA_ExplicitTemplateInstantiation)
1193     // FIXME: It seems like we can provide more specific linkage here
1194     // (LinkOnceODR, WeakODR).
1195     GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
1196   else if (!getLangOptions().CPlusPlus && !CodeGenOpts.NoCommon &&
1197            !D->hasExternalStorage() && !D->getInit() &&
1198            !D->getAttr<SectionAttr>()) {
1199     GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
1200     // common vars aren't constant even if declared const.
1201     GV->setConstant(false);
1202   } else
1203     GV->setLinkage(llvm::GlobalVariable::ExternalLinkage);
1204 
1205   SetCommonAttributes(D, GV);
1206 
1207   // Emit global variable debug information.
1208   if (CGDebugInfo *DI = getDebugInfo()) {
1209     DI->setLocation(D->getLocation());
1210     DI->EmitGlobalVariable(GV, D);
1211   }
1212 }
1213 
1214 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
1215 /// implement a function with no prototype, e.g. "int foo() {}".  If there are
1216 /// existing call uses of the old function in the module, this adjusts them to
1217 /// call the new function directly.
1218 ///
1219 /// This is not just a cleanup: the always_inline pass requires direct calls to
1220 /// functions to be able to inline them.  If there is a bitcast in the way, it
1221 /// won't inline them.  Instcombine normally deletes these calls, but it isn't
1222 /// run at -O0.
1223 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
1224                                                       llvm::Function *NewFn) {
1225   // If we're redefining a global as a function, don't transform it.
1226   llvm::Function *OldFn = dyn_cast<llvm::Function>(Old);
1227   if (OldFn == 0) return;
1228 
1229   const llvm::Type *NewRetTy = NewFn->getReturnType();
1230   llvm::SmallVector<llvm::Value*, 4> ArgList;
1231 
1232   for (llvm::Value::use_iterator UI = OldFn->use_begin(), E = OldFn->use_end();
1233        UI != E; ) {
1234     // TODO: Do invokes ever occur in C code?  If so, we should handle them too.
1235     llvm::Value::use_iterator I = UI++; // Increment before the CI is erased.
1236     llvm::CallInst *CI = dyn_cast<llvm::CallInst>(*I);
1237     llvm::CallSite CS(CI);
1238     if (!CI || !CS.isCallee(I)) continue;
1239 
1240     // If the return types don't match exactly, and if the call isn't dead, then
1241     // we can't transform this call.
1242     if (CI->getType() != NewRetTy && !CI->use_empty())
1243       continue;
1244 
1245     // If the function was passed too few arguments, don't transform.  If extra
1246     // arguments were passed, we silently drop them.  If any of the types
1247     // mismatch, we don't transform.
1248     unsigned ArgNo = 0;
1249     bool DontTransform = false;
1250     for (llvm::Function::arg_iterator AI = NewFn->arg_begin(),
1251          E = NewFn->arg_end(); AI != E; ++AI, ++ArgNo) {
1252       if (CS.arg_size() == ArgNo ||
1253           CS.getArgument(ArgNo)->getType() != AI->getType()) {
1254         DontTransform = true;
1255         break;
1256       }
1257     }
1258     if (DontTransform)
1259       continue;
1260 
1261     // Okay, we can transform this.  Create the new call instruction and copy
1262     // over the required information.
1263     ArgList.append(CS.arg_begin(), CS.arg_begin() + ArgNo);
1264     llvm::CallInst *NewCall = llvm::CallInst::Create(NewFn, ArgList.begin(),
1265                                                      ArgList.end(), "", CI);
1266     ArgList.clear();
1267     if (!NewCall->getType()->isVoidTy())
1268       NewCall->takeName(CI);
1269     NewCall->setAttributes(CI->getAttributes());
1270     NewCall->setCallingConv(CI->getCallingConv());
1271 
1272     // Finally, remove the old call, replacing any uses with the new one.
1273     if (!CI->use_empty())
1274       CI->replaceAllUsesWith(NewCall);
1275 
1276     // Copy debug location attached to CI.
1277     if (!CI->getDebugLoc().isUnknown())
1278       NewCall->setDebugLoc(CI->getDebugLoc());
1279     CI->eraseFromParent();
1280   }
1281 }
1282 
1283 
1284 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) {
1285   const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
1286   const llvm::FunctionType *Ty = getTypes().GetFunctionType(GD);
1287   getMangleContext().mangleInitDiscriminator();
1288   // Get or create the prototype for the function.
1289   llvm::Constant *Entry = GetAddrOfFunction(GD, Ty);
1290 
1291   // Strip off a bitcast if we got one back.
1292   if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
1293     assert(CE->getOpcode() == llvm::Instruction::BitCast);
1294     Entry = CE->getOperand(0);
1295   }
1296 
1297 
1298   if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
1299     llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
1300 
1301     // If the types mismatch then we have to rewrite the definition.
1302     assert(OldFn->isDeclaration() &&
1303            "Shouldn't replace non-declaration");
1304 
1305     // F is the Function* for the one with the wrong type, we must make a new
1306     // Function* and update everything that used F (a declaration) with the new
1307     // Function* (which will be a definition).
1308     //
1309     // This happens if there is a prototype for a function
1310     // (e.g. "int f()") and then a definition of a different type
1311     // (e.g. "int f(int x)").  Move the old function aside so that it
1312     // doesn't interfere with GetAddrOfFunction.
1313     OldFn->setName(llvm::StringRef());
1314     llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
1315 
1316     // If this is an implementation of a function without a prototype, try to
1317     // replace any existing uses of the function (which may be calls) with uses
1318     // of the new function
1319     if (D->getType()->isFunctionNoProtoType()) {
1320       ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
1321       OldFn->removeDeadConstantUsers();
1322     }
1323 
1324     // Replace uses of F with the Function we will endow with a body.
1325     if (!Entry->use_empty()) {
1326       llvm::Constant *NewPtrForOldDecl =
1327         llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
1328       Entry->replaceAllUsesWith(NewPtrForOldDecl);
1329     }
1330 
1331     // Ok, delete the old function now, which is dead.
1332     OldFn->eraseFromParent();
1333 
1334     Entry = NewFn;
1335   }
1336 
1337   llvm::Function *Fn = cast<llvm::Function>(Entry);
1338 
1339   CodeGenFunction(*this).GenerateCode(D, Fn);
1340 
1341   SetFunctionDefinitionAttributes(D, Fn);
1342   SetLLVMFunctionAttributesForDefinition(D, Fn);
1343 
1344   if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
1345     AddGlobalCtor(Fn, CA->getPriority());
1346   if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
1347     AddGlobalDtor(Fn, DA->getPriority());
1348 }
1349 
1350 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
1351   const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
1352   const AliasAttr *AA = D->getAttr<AliasAttr>();
1353   assert(AA && "Not an alias?");
1354 
1355   MangleBuffer MangledName;
1356   getMangledName(MangledName, GD);
1357 
1358   // If there is a definition in the module, then it wins over the alias.
1359   // This is dubious, but allow it to be safe.  Just ignore the alias.
1360   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1361   if (Entry && !Entry->isDeclaration())
1362     return;
1363 
1364   const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
1365 
1366   // Create a reference to the named value.  This ensures that it is emitted
1367   // if a deferred decl.
1368   llvm::Constant *Aliasee;
1369   if (isa<llvm::FunctionType>(DeclTy))
1370     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl());
1371   else
1372     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
1373                                     llvm::PointerType::getUnqual(DeclTy), 0);
1374 
1375   // Create the new alias itself, but don't set a name yet.
1376   llvm::GlobalValue *GA =
1377     new llvm::GlobalAlias(Aliasee->getType(),
1378                           llvm::Function::ExternalLinkage,
1379                           "", Aliasee, &getModule());
1380 
1381   if (Entry) {
1382     assert(Entry->isDeclaration());
1383 
1384     // If there is a declaration in the module, then we had an extern followed
1385     // by the alias, as in:
1386     //   extern int test6();
1387     //   ...
1388     //   int test6() __attribute__((alias("test7")));
1389     //
1390     // Remove it and replace uses of it with the alias.
1391     GA->takeName(Entry);
1392 
1393     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
1394                                                           Entry->getType()));
1395     Entry->eraseFromParent();
1396   } else {
1397     GA->setName(MangledName.getString());
1398   }
1399 
1400   // Set attributes which are particular to an alias; this is a
1401   // specialization of the attributes which may be set on a global
1402   // variable/function.
1403   if (D->hasAttr<DLLExportAttr>()) {
1404     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1405       // The dllexport attribute is ignored for undefined symbols.
1406       if (FD->getBody())
1407         GA->setLinkage(llvm::Function::DLLExportLinkage);
1408     } else {
1409       GA->setLinkage(llvm::Function::DLLExportLinkage);
1410     }
1411   } else if (D->hasAttr<WeakAttr>() ||
1412              D->hasAttr<WeakRefAttr>() ||
1413              D->hasAttr<WeakImportAttr>()) {
1414     GA->setLinkage(llvm::Function::WeakAnyLinkage);
1415   }
1416 
1417   SetCommonAttributes(D, GA);
1418 }
1419 
1420 /// getBuiltinLibFunction - Given a builtin id for a function like
1421 /// "__builtin_fabsf", return a Function* for "fabsf".
1422 llvm::Value *CodeGenModule::getBuiltinLibFunction(const FunctionDecl *FD,
1423                                                   unsigned BuiltinID) {
1424   assert((Context.BuiltinInfo.isLibFunction(BuiltinID) ||
1425           Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) &&
1426          "isn't a lib fn");
1427 
1428   // Get the name, skip over the __builtin_ prefix (if necessary).
1429   const char *Name = Context.BuiltinInfo.GetName(BuiltinID);
1430   if (Context.BuiltinInfo.isLibFunction(BuiltinID))
1431     Name += 10;
1432 
1433   const llvm::FunctionType *Ty =
1434     cast<llvm::FunctionType>(getTypes().ConvertType(FD->getType()));
1435 
1436   return GetOrCreateLLVMFunction(Name, Ty, GlobalDecl(FD));
1437 }
1438 
1439 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
1440                                             unsigned NumTys) {
1441   return llvm::Intrinsic::getDeclaration(&getModule(),
1442                                          (llvm::Intrinsic::ID)IID, Tys, NumTys);
1443 }
1444 
1445 
1446 llvm::Function *CodeGenModule::getMemCpyFn(const llvm::Type *DestType,
1447                                            const llvm::Type *SrcType,
1448                                            const llvm::Type *SizeType) {
1449   const llvm::Type *ArgTypes[3] = {DestType, SrcType, SizeType };
1450   return getIntrinsic(llvm::Intrinsic::memcpy, ArgTypes, 3);
1451 }
1452 
1453 llvm::Function *CodeGenModule::getMemMoveFn(const llvm::Type *DestType,
1454                                             const llvm::Type *SrcType,
1455                                             const llvm::Type *SizeType) {
1456   const llvm::Type *ArgTypes[3] = {DestType, SrcType, SizeType };
1457   return getIntrinsic(llvm::Intrinsic::memmove, ArgTypes, 3);
1458 }
1459 
1460 llvm::Function *CodeGenModule::getMemSetFn(const llvm::Type *DestType,
1461                                            const llvm::Type *SizeType) {
1462   const llvm::Type *ArgTypes[2] = { DestType, SizeType };
1463   return getIntrinsic(llvm::Intrinsic::memset, ArgTypes, 2);
1464 }
1465 
1466 static llvm::StringMapEntry<llvm::Constant*> &
1467 GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
1468                          const StringLiteral *Literal,
1469                          bool TargetIsLSB,
1470                          bool &IsUTF16,
1471                          unsigned &StringLength) {
1472   unsigned NumBytes = Literal->getByteLength();
1473 
1474   // Check for simple case.
1475   if (!Literal->containsNonAsciiOrNull()) {
1476     StringLength = NumBytes;
1477     return Map.GetOrCreateValue(llvm::StringRef(Literal->getStrData(),
1478                                                 StringLength));
1479   }
1480 
1481   // Otherwise, convert the UTF8 literals into a byte string.
1482   llvm::SmallVector<UTF16, 128> ToBuf(NumBytes);
1483   const UTF8 *FromPtr = (UTF8 *)Literal->getStrData();
1484   UTF16 *ToPtr = &ToBuf[0];
1485 
1486   ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1487                                                &ToPtr, ToPtr + NumBytes,
1488                                                strictConversion);
1489 
1490   // Check for conversion failure.
1491   if (Result != conversionOK) {
1492     // FIXME: Have Sema::CheckObjCString() validate the UTF-8 string and remove
1493     // this duplicate code.
1494     assert(Result == sourceIllegal && "UTF-8 to UTF-16 conversion failed");
1495     StringLength = NumBytes;
1496     return Map.GetOrCreateValue(llvm::StringRef(Literal->getStrData(),
1497                                                 StringLength));
1498   }
1499 
1500   // ConvertUTF8toUTF16 returns the length in ToPtr.
1501   StringLength = ToPtr - &ToBuf[0];
1502 
1503   // Render the UTF-16 string into a byte array and convert to the target byte
1504   // order.
1505   //
1506   // FIXME: This isn't something we should need to do here.
1507   llvm::SmallString<128> AsBytes;
1508   AsBytes.reserve(StringLength * 2);
1509   for (unsigned i = 0; i != StringLength; ++i) {
1510     unsigned short Val = ToBuf[i];
1511     if (TargetIsLSB) {
1512       AsBytes.push_back(Val & 0xFF);
1513       AsBytes.push_back(Val >> 8);
1514     } else {
1515       AsBytes.push_back(Val >> 8);
1516       AsBytes.push_back(Val & 0xFF);
1517     }
1518   }
1519   // Append one extra null character, the second is automatically added by our
1520   // caller.
1521   AsBytes.push_back(0);
1522 
1523   IsUTF16 = true;
1524   return Map.GetOrCreateValue(llvm::StringRef(AsBytes.data(), AsBytes.size()));
1525 }
1526 
1527 llvm::Constant *
1528 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
1529   unsigned StringLength = 0;
1530   bool isUTF16 = false;
1531   llvm::StringMapEntry<llvm::Constant*> &Entry =
1532     GetConstantCFStringEntry(CFConstantStringMap, Literal,
1533                              getTargetData().isLittleEndian(),
1534                              isUTF16, StringLength);
1535 
1536   if (llvm::Constant *C = Entry.getValue())
1537     return C;
1538 
1539   llvm::Constant *Zero =
1540       llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext));
1541   llvm::Constant *Zeros[] = { Zero, Zero };
1542 
1543   // If we don't already have it, get __CFConstantStringClassReference.
1544   if (!CFConstantStringClassRef) {
1545     const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
1546     Ty = llvm::ArrayType::get(Ty, 0);
1547     llvm::Constant *GV = CreateRuntimeVariable(Ty,
1548                                            "__CFConstantStringClassReference");
1549     // Decay array -> ptr
1550     CFConstantStringClassRef =
1551       llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1552   }
1553 
1554   QualType CFTy = getContext().getCFConstantStringType();
1555 
1556   const llvm::StructType *STy =
1557     cast<llvm::StructType>(getTypes().ConvertType(CFTy));
1558 
1559   std::vector<llvm::Constant*> Fields(4);
1560 
1561   // Class pointer.
1562   Fields[0] = CFConstantStringClassRef;
1563 
1564   // Flags.
1565   const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
1566   Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
1567     llvm::ConstantInt::get(Ty, 0x07C8);
1568 
1569   // String pointer.
1570   llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str());
1571 
1572   llvm::GlobalValue::LinkageTypes Linkage;
1573   bool isConstant;
1574   if (isUTF16) {
1575     // FIXME: why do utf strings get "_" labels instead of "L" labels?
1576     Linkage = llvm::GlobalValue::InternalLinkage;
1577     // Note: -fwritable-strings doesn't make unicode CFStrings writable, but
1578     // does make plain ascii ones writable.
1579     isConstant = true;
1580   } else {
1581     Linkage = llvm::GlobalValue::PrivateLinkage;
1582     isConstant = !Features.WritableStrings;
1583   }
1584 
1585   llvm::GlobalVariable *GV =
1586     new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
1587                              ".str");
1588   if (isUTF16) {
1589     CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
1590     GV->setAlignment(Align.getQuantity());
1591   }
1592   Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1593 
1594   // String length.
1595   Ty = getTypes().ConvertType(getContext().LongTy);
1596   Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
1597 
1598   // The struct.
1599   C = llvm::ConstantStruct::get(STy, Fields);
1600   GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
1601                                 llvm::GlobalVariable::PrivateLinkage, C,
1602                                 "_unnamed_cfstring_");
1603   if (const char *Sect = getContext().Target.getCFStringSection())
1604     GV->setSection(Sect);
1605   Entry.setValue(GV);
1606 
1607   return GV;
1608 }
1609 
1610 llvm::Constant *
1611 CodeGenModule::GetAddrOfConstantNSString(const StringLiteral *Literal) {
1612   unsigned StringLength = 0;
1613   bool isUTF16 = false;
1614   llvm::StringMapEntry<llvm::Constant*> &Entry =
1615     GetConstantCFStringEntry(CFConstantStringMap, Literal,
1616                              getTargetData().isLittleEndian(),
1617                              isUTF16, StringLength);
1618 
1619   if (llvm::Constant *C = Entry.getValue())
1620     return C;
1621 
1622   llvm::Constant *Zero =
1623   llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext));
1624   llvm::Constant *Zeros[] = { Zero, Zero };
1625 
1626   // If we don't already have it, get _NSConstantStringClassReference.
1627   if (!NSConstantStringClassRef) {
1628     const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
1629     Ty = llvm::ArrayType::get(Ty, 0);
1630     llvm::Constant *GV = CreateRuntimeVariable(Ty,
1631                                         Features.ObjCNonFragileABI ?
1632                                         "OBJC_CLASS_$_NSConstantString" :
1633                                         "_NSConstantStringClassReference");
1634     // Decay array -> ptr
1635     NSConstantStringClassRef =
1636       llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1637   }
1638 
1639   QualType NSTy = getContext().getNSConstantStringType();
1640 
1641   const llvm::StructType *STy =
1642   cast<llvm::StructType>(getTypes().ConvertType(NSTy));
1643 
1644   std::vector<llvm::Constant*> Fields(3);
1645 
1646   // Class pointer.
1647   Fields[0] = NSConstantStringClassRef;
1648 
1649   // String pointer.
1650   llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str());
1651 
1652   llvm::GlobalValue::LinkageTypes Linkage;
1653   bool isConstant;
1654   if (isUTF16) {
1655     // FIXME: why do utf strings get "_" labels instead of "L" labels?
1656     Linkage = llvm::GlobalValue::InternalLinkage;
1657     // Note: -fwritable-strings doesn't make unicode NSStrings writable, but
1658     // does make plain ascii ones writable.
1659     isConstant = true;
1660   } else {
1661     Linkage = llvm::GlobalValue::PrivateLinkage;
1662     isConstant = !Features.WritableStrings;
1663   }
1664 
1665   llvm::GlobalVariable *GV =
1666   new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
1667                            ".str");
1668   if (isUTF16) {
1669     CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
1670     GV->setAlignment(Align.getQuantity());
1671   }
1672   Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1673 
1674   // String length.
1675   const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
1676   Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
1677 
1678   // The struct.
1679   C = llvm::ConstantStruct::get(STy, Fields);
1680   GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
1681                                 llvm::GlobalVariable::PrivateLinkage, C,
1682                                 "_unnamed_nsstring_");
1683   // FIXME. Fix section.
1684   if (const char *Sect =
1685         Features.ObjCNonFragileABI
1686           ? getContext().Target.getNSStringNonFragileABISection()
1687           : getContext().Target.getNSStringSection())
1688     GV->setSection(Sect);
1689   Entry.setValue(GV);
1690 
1691   return GV;
1692 }
1693 
1694 /// GetStringForStringLiteral - Return the appropriate bytes for a
1695 /// string literal, properly padded to match the literal type.
1696 std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
1697   const char *StrData = E->getStrData();
1698   unsigned Len = E->getByteLength();
1699 
1700   const ConstantArrayType *CAT =
1701     getContext().getAsConstantArrayType(E->getType());
1702   assert(CAT && "String isn't pointer or array!");
1703 
1704   // Resize the string to the right size.
1705   std::string Str(StrData, StrData+Len);
1706   uint64_t RealLen = CAT->getSize().getZExtValue();
1707 
1708   if (E->isWide())
1709     RealLen *= getContext().Target.getWCharWidth()/8;
1710 
1711   Str.resize(RealLen, '\0');
1712 
1713   return Str;
1714 }
1715 
1716 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
1717 /// constant array for the given string literal.
1718 llvm::Constant *
1719 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
1720   // FIXME: This can be more efficient.
1721   // FIXME: We shouldn't need to bitcast the constant in the wide string case.
1722   llvm::Constant *C = GetAddrOfConstantString(GetStringForStringLiteral(S));
1723   if (S->isWide()) {
1724     llvm::Type *DestTy =
1725         llvm::PointerType::getUnqual(getTypes().ConvertType(S->getType()));
1726     C = llvm::ConstantExpr::getBitCast(C, DestTy);
1727   }
1728   return C;
1729 }
1730 
1731 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
1732 /// array for the given ObjCEncodeExpr node.
1733 llvm::Constant *
1734 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
1735   std::string Str;
1736   getContext().getObjCEncodingForType(E->getEncodedType(), Str);
1737 
1738   return GetAddrOfConstantCString(Str);
1739 }
1740 
1741 
1742 /// GenerateWritableString -- Creates storage for a string literal.
1743 static llvm::Constant *GenerateStringLiteral(const std::string &str,
1744                                              bool constant,
1745                                              CodeGenModule &CGM,
1746                                              const char *GlobalName) {
1747   // Create Constant for this string literal. Don't add a '\0'.
1748   llvm::Constant *C =
1749       llvm::ConstantArray::get(CGM.getLLVMContext(), str, false);
1750 
1751   // Create a global variable for this string
1752   return new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant,
1753                                   llvm::GlobalValue::PrivateLinkage,
1754                                   C, GlobalName);
1755 }
1756 
1757 /// GetAddrOfConstantString - Returns a pointer to a character array
1758 /// containing the literal. This contents are exactly that of the
1759 /// given string, i.e. it will not be null terminated automatically;
1760 /// see GetAddrOfConstantCString. Note that whether the result is
1761 /// actually a pointer to an LLVM constant depends on
1762 /// Feature.WriteableStrings.
1763 ///
1764 /// The result has pointer to array type.
1765 llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str,
1766                                                        const char *GlobalName) {
1767   bool IsConstant = !Features.WritableStrings;
1768 
1769   // Get the default prefix if a name wasn't specified.
1770   if (!GlobalName)
1771     GlobalName = ".str";
1772 
1773   // Don't share any string literals if strings aren't constant.
1774   if (!IsConstant)
1775     return GenerateStringLiteral(str, false, *this, GlobalName);
1776 
1777   llvm::StringMapEntry<llvm::Constant *> &Entry =
1778     ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
1779 
1780   if (Entry.getValue())
1781     return Entry.getValue();
1782 
1783   // Create a global variable for this.
1784   llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName);
1785   Entry.setValue(C);
1786   return C;
1787 }
1788 
1789 /// GetAddrOfConstantCString - Returns a pointer to a character
1790 /// array containing the literal and a terminating '\-'
1791 /// character. The result has pointer to array type.
1792 llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str,
1793                                                         const char *GlobalName){
1794   return GetAddrOfConstantString(str + '\0', GlobalName);
1795 }
1796 
1797 /// EmitObjCPropertyImplementations - Emit information for synthesized
1798 /// properties for an implementation.
1799 void CodeGenModule::EmitObjCPropertyImplementations(const
1800                                                     ObjCImplementationDecl *D) {
1801   for (ObjCImplementationDecl::propimpl_iterator
1802          i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) {
1803     ObjCPropertyImplDecl *PID = *i;
1804 
1805     // Dynamic is just for type-checking.
1806     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1807       ObjCPropertyDecl *PD = PID->getPropertyDecl();
1808 
1809       // Determine which methods need to be implemented, some may have
1810       // been overridden. Note that ::isSynthesized is not the method
1811       // we want, that just indicates if the decl came from a
1812       // property. What we want to know is if the method is defined in
1813       // this implementation.
1814       if (!D->getInstanceMethod(PD->getGetterName()))
1815         CodeGenFunction(*this).GenerateObjCGetter(
1816                                  const_cast<ObjCImplementationDecl *>(D), PID);
1817       if (!PD->isReadOnly() &&
1818           !D->getInstanceMethod(PD->getSetterName()))
1819         CodeGenFunction(*this).GenerateObjCSetter(
1820                                  const_cast<ObjCImplementationDecl *>(D), PID);
1821     }
1822   }
1823 }
1824 
1825 /// EmitObjCIvarInitializations - Emit information for ivar initialization
1826 /// for an implementation.
1827 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
1828   if (!Features.NeXTRuntime || D->getNumIvarInitializers() == 0)
1829     return;
1830   DeclContext* DC = const_cast<DeclContext*>(dyn_cast<DeclContext>(D));
1831   assert(DC && "EmitObjCIvarInitializations - null DeclContext");
1832   IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
1833   Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
1834   ObjCMethodDecl *DTORMethod = ObjCMethodDecl::Create(getContext(),
1835                                                   D->getLocation(),
1836                                                   D->getLocation(), cxxSelector,
1837                                                   getContext().VoidTy, 0,
1838                                                   DC, true, false, true,
1839                                                   ObjCMethodDecl::Required);
1840   D->addInstanceMethod(DTORMethod);
1841   CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
1842 
1843   II = &getContext().Idents.get(".cxx_construct");
1844   cxxSelector = getContext().Selectors.getSelector(0, &II);
1845   // The constructor returns 'self'.
1846   ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
1847                                                 D->getLocation(),
1848                                                 D->getLocation(), cxxSelector,
1849                                                 getContext().getObjCIdType(), 0,
1850                                                 DC, true, false, true,
1851                                                 ObjCMethodDecl::Required);
1852   D->addInstanceMethod(CTORMethod);
1853   CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
1854 
1855 
1856 }
1857 
1858 /// EmitNamespace - Emit all declarations in a namespace.
1859 void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
1860   for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end();
1861        I != E; ++I)
1862     EmitTopLevelDecl(*I);
1863 }
1864 
1865 // EmitLinkageSpec - Emit all declarations in a linkage spec.
1866 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
1867   if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
1868       LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
1869     ErrorUnsupported(LSD, "linkage spec");
1870     return;
1871   }
1872 
1873   for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end();
1874        I != E; ++I)
1875     EmitTopLevelDecl(*I);
1876 }
1877 
1878 /// EmitTopLevelDecl - Emit code for a single top level declaration.
1879 void CodeGenModule::EmitTopLevelDecl(Decl *D) {
1880   // If an error has occurred, stop code generation, but continue
1881   // parsing and semantic analysis (to ensure all warnings and errors
1882   // are emitted).
1883   if (Diags.hasErrorOccurred())
1884     return;
1885 
1886   // Ignore dependent declarations.
1887   if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
1888     return;
1889 
1890   switch (D->getKind()) {
1891   case Decl::CXXConversion:
1892   case Decl::CXXMethod:
1893   case Decl::Function:
1894     // Skip function templates
1895     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate())
1896       return;
1897 
1898     EmitGlobal(cast<FunctionDecl>(D));
1899     break;
1900 
1901   case Decl::Var:
1902     EmitGlobal(cast<VarDecl>(D));
1903     break;
1904 
1905   // C++ Decls
1906   case Decl::Namespace:
1907     EmitNamespace(cast<NamespaceDecl>(D));
1908     break;
1909     // No code generation needed.
1910   case Decl::UsingShadow:
1911   case Decl::Using:
1912   case Decl::UsingDirective:
1913   case Decl::ClassTemplate:
1914   case Decl::FunctionTemplate:
1915   case Decl::NamespaceAlias:
1916     break;
1917   case Decl::CXXConstructor:
1918     // Skip function templates
1919     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate())
1920       return;
1921 
1922     EmitCXXConstructors(cast<CXXConstructorDecl>(D));
1923     break;
1924   case Decl::CXXDestructor:
1925     EmitCXXDestructors(cast<CXXDestructorDecl>(D));
1926     break;
1927 
1928   case Decl::StaticAssert:
1929     // Nothing to do.
1930     break;
1931 
1932   // Objective-C Decls
1933 
1934   // Forward declarations, no (immediate) code generation.
1935   case Decl::ObjCClass:
1936   case Decl::ObjCForwardProtocol:
1937   case Decl::ObjCCategory:
1938   case Decl::ObjCInterface:
1939     break;
1940 
1941   case Decl::ObjCProtocol:
1942     Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
1943     break;
1944 
1945   case Decl::ObjCCategoryImpl:
1946     // Categories have properties but don't support synthesize so we
1947     // can ignore them here.
1948     Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
1949     break;
1950 
1951   case Decl::ObjCImplementation: {
1952     ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
1953     EmitObjCPropertyImplementations(OMD);
1954     EmitObjCIvarInitializations(OMD);
1955     Runtime->GenerateClass(OMD);
1956     break;
1957   }
1958   case Decl::ObjCMethod: {
1959     ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
1960     // If this is not a prototype, emit the body.
1961     if (OMD->getBody())
1962       CodeGenFunction(*this).GenerateObjCMethod(OMD);
1963     break;
1964   }
1965   case Decl::ObjCCompatibleAlias:
1966     // compatibility-alias is a directive and has no code gen.
1967     break;
1968 
1969   case Decl::LinkageSpec:
1970     EmitLinkageSpec(cast<LinkageSpecDecl>(D));
1971     break;
1972 
1973   case Decl::FileScopeAsm: {
1974     FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
1975     llvm::StringRef AsmString = AD->getAsmString()->getString();
1976 
1977     const std::string &S = getModule().getModuleInlineAsm();
1978     if (S.empty())
1979       getModule().setModuleInlineAsm(AsmString);
1980     else
1981       getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
1982     break;
1983   }
1984 
1985   default:
1986     // Make sure we handled everything we should, every other kind is a
1987     // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
1988     // function. Need to recode Decl::Kind to do that easily.
1989     assert(isa<TypeDecl>(D) && "Unsupported decl kind");
1990   }
1991 }
1992