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