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