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