xref: /llvm-project/clang/lib/CodeGen/CodeGenModule.cpp (revision 6098e62d568886d8af093527e71a1fc11f023bf9)
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 "CGDebugInfo.h"
15 #include "CodeGenModule.h"
16 #include "CodeGenFunction.h"
17 #include "CGCall.h"
18 #include "CGObjCRuntime.h"
19 #include "Mangle.h"
20 #include "clang/AST/ASTContext.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/DeclCXX.h"
23 #include "clang/Basic/Diagnostic.h"
24 #include "clang/Basic/SourceManager.h"
25 #include "clang/Basic/TargetInfo.h"
26 #include "llvm/CallingConv.h"
27 #include "llvm/Module.h"
28 #include "llvm/Intrinsics.h"
29 #include "llvm/Target/TargetData.h"
30 using namespace clang;
31 using namespace CodeGen;
32 
33 
34 CodeGenModule::CodeGenModule(ASTContext &C, const LangOptions &LO,
35                              llvm::Module &M, const llvm::TargetData &TD,
36                              Diagnostic &diags, bool GenerateDebugInfo)
37   : BlockModule(C, M, TD, Types, *this), Context(C), Features(LO), TheModule(M),
38     TheTargetData(TD), Diags(diags), Types(C, M, TD), Runtime(0),
39     MemCpyFn(0), MemMoveFn(0), MemSetFn(0), CFConstantStringClassRef(0) {
40 
41   if (Features.ObjC1) {
42     if (Features.NeXTRuntime) {
43       Runtime = Features.ObjCNonFragileABI ? CreateMacNonFragileABIObjCRuntime(*this)
44                                        : CreateMacObjCRuntime(*this);
45     } else {
46       Runtime = CreateGNUObjCRuntime(*this);
47     }
48   }
49 
50   // If debug info generation is enabled, create the CGDebugInfo object.
51   DebugInfo = GenerateDebugInfo ? new CGDebugInfo(this) : 0;
52 }
53 
54 CodeGenModule::~CodeGenModule() {
55   delete Runtime;
56   delete DebugInfo;
57 }
58 
59 void CodeGenModule::Release() {
60   EmitDeferred();
61   EmitAliases();
62   if (Runtime)
63     if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction())
64       AddGlobalCtor(ObjCInitFunction);
65   EmitCtorList(GlobalCtors, "llvm.global_ctors");
66   EmitCtorList(GlobalDtors, "llvm.global_dtors");
67   EmitAnnotations();
68   EmitLLVMUsed();
69   BindRuntimeGlobals();
70 }
71 
72 void CodeGenModule::BindRuntimeGlobals() {
73   // Deal with protecting runtime function names.
74   for (unsigned i = 0, e = RuntimeGlobals.size(); i < e; ++i) {
75     llvm::GlobalValue *GV = RuntimeGlobals[i].first;
76     const std::string &Name = RuntimeGlobals[i].second;
77 
78     // Discard unused runtime declarations.
79     if (GV->isDeclaration() && GV->use_empty()) {
80       GV->eraseFromParent();
81       continue;
82     }
83 
84     // See if there is a conflict against a function.
85     llvm::GlobalValue *Conflict = TheModule.getNamedValue(Name);
86     if (Conflict) {
87       // Decide which version to take. If the conflict is a definition
88       // we are forced to take that, otherwise assume the runtime
89       // knows best.
90 
91       // FIXME: This will fail phenomenally when the conflict is the
92       // wrong type of value. Just bail on it for now. This should
93       // really reuse something inside the LLVM Linker code.
94       assert(GV->getValueID() == Conflict->getValueID() &&
95              "Unable to resolve conflict between globals of different types.");
96       if (!Conflict->isDeclaration()) {
97         llvm::Value *Casted =
98           llvm::ConstantExpr::getBitCast(Conflict, GV->getType());
99         GV->replaceAllUsesWith(Casted);
100         GV->eraseFromParent();
101       } else {
102         GV->takeName(Conflict);
103         llvm::Value *Casted =
104           llvm::ConstantExpr::getBitCast(GV, Conflict->getType());
105         Conflict->replaceAllUsesWith(Casted);
106         Conflict->eraseFromParent();
107       }
108     } else
109       GV->setName(Name);
110   }
111 }
112 
113 /// ErrorUnsupported - Print out an error that codegen doesn't support the
114 /// specified stmt yet.
115 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
116                                      bool OmitOnError) {
117   if (OmitOnError && getDiags().hasErrorOccurred())
118     return;
119   unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
120                                                "cannot compile this %0 yet");
121   std::string Msg = Type;
122   getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
123     << Msg << S->getSourceRange();
124 }
125 
126 /// ErrorUnsupported - Print out an error that codegen doesn't support the
127 /// specified decl yet.
128 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
129                                      bool OmitOnError) {
130   if (OmitOnError && getDiags().hasErrorOccurred())
131     return;
132   unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
133                                                "cannot compile this %0 yet");
134   std::string Msg = Type;
135   getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
136 }
137 
138 /// setGlobalVisibility - Set the visibility for the given LLVM
139 /// GlobalValue according to the given clang AST visibility value.
140 static void setGlobalVisibility(llvm::GlobalValue *GV,
141                                 VisibilityAttr::VisibilityTypes Vis) {
142   switch (Vis) {
143   default: assert(0 && "Unknown visibility!");
144   case VisibilityAttr::DefaultVisibility:
145     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
146     break;
147   case VisibilityAttr::HiddenVisibility:
148     GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
149     break;
150   case VisibilityAttr::ProtectedVisibility:
151     GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
152     break;
153   }
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 /// FIXME: Returning an IdentifierInfo* here is a total hack. We
163 /// really need some kind of string abstraction that either stores a
164 /// mangled name or stores an IdentifierInfo*. This will require
165 /// changes to the GlobalDeclMap, too. (I disagree, I think what we
166 /// actually need is for Sema to provide some notion of which Decls
167 /// refer to the same semantic decl. We shouldn't need to mangle the
168 /// names and see what comes out the same to figure this out. - DWD)
169 ///
170 /// FIXME: Performance here is going to be terribly until we start
171 /// caching mangled names. However, we should fix the problem above
172 /// first.
173 const char *CodeGenModule::getMangledName(const NamedDecl *ND) {
174   // In C, functions with no attributes never need to be mangled. Fastpath them.
175   if (!getLangOptions().CPlusPlus && !ND->hasAttrs()) {
176     assert(ND->getIdentifier() && "Attempt to mangle unnamed decl.");
177     return ND->getIdentifier()->getName();
178   }
179 
180   llvm::SmallString<256> Name;
181   llvm::raw_svector_ostream Out(Name);
182   if (!mangleName(ND, Context, Out)) {
183     assert(ND->getIdentifier() && "Attempt to mangle unnamed decl.");
184     return ND->getIdentifier()->getName();
185   }
186 
187   Name += '\0';
188   return MangledNames.GetOrCreateValue(Name.begin(), Name.end())
189            .getKeyData();
190 }
191 
192 /// AddGlobalCtor - Add a function to the list that will be called before
193 /// main() runs.
194 void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
195   // FIXME: Type coercion of void()* types.
196   GlobalCtors.push_back(std::make_pair(Ctor, Priority));
197 }
198 
199 /// AddGlobalDtor - Add a function to the list that will be called
200 /// when the module is unloaded.
201 void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
202   // FIXME: Type coercion of void()* types.
203   GlobalDtors.push_back(std::make_pair(Dtor, Priority));
204 }
205 
206 void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
207   // Ctor function type is void()*.
208   llvm::FunctionType* CtorFTy =
209     llvm::FunctionType::get(llvm::Type::VoidTy,
210                             std::vector<const llvm::Type*>(),
211                             false);
212   llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
213 
214   // Get the type of a ctor entry, { i32, void ()* }.
215   llvm::StructType* CtorStructTy =
216     llvm::StructType::get(llvm::Type::Int32Ty,
217                           llvm::PointerType::getUnqual(CtorFTy), NULL);
218 
219   // Construct the constructor and destructor arrays.
220   std::vector<llvm::Constant*> Ctors;
221   for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
222     std::vector<llvm::Constant*> S;
223     S.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, I->second, false));
224     S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
225     Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
226   }
227 
228   if (!Ctors.empty()) {
229     llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
230     new llvm::GlobalVariable(AT, false,
231                              llvm::GlobalValue::AppendingLinkage,
232                              llvm::ConstantArray::get(AT, Ctors),
233                              GlobalName,
234                              &TheModule);
235   }
236 }
237 
238 void CodeGenModule::EmitAnnotations() {
239   if (Annotations.empty())
240     return;
241 
242   // Create a new global variable for the ConstantStruct in the Module.
243   llvm::Constant *Array =
244   llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
245                                                 Annotations.size()),
246                            Annotations);
247   llvm::GlobalValue *gv =
248   new llvm::GlobalVariable(Array->getType(), false,
249                            llvm::GlobalValue::AppendingLinkage, Array,
250                            "llvm.global.annotations", &TheModule);
251   gv->setSection("llvm.metadata");
252 }
253 
254 void CodeGenModule::SetGlobalValueAttributes(const Decl *D,
255                                              bool IsInternal,
256                                              bool IsInline,
257                                              llvm::GlobalValue *GV,
258                                              bool ForDefinition) {
259   // FIXME: Set up linkage and many other things.  Note, this is a simple
260   // approximation of what we really want.
261   if (!ForDefinition) {
262     // Only a few attributes are set on declarations.
263     if (D->getAttr<DLLImportAttr>()) {
264       // The dllimport attribute is overridden by a subsequent declaration as
265       // dllexport.
266       if (!D->getAttr<DLLExportAttr>()) {
267         // dllimport attribute can be applied only to function decls, not to
268         // definitions.
269         if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
270           if (!FD->getBody())
271             GV->setLinkage(llvm::Function::DLLImportLinkage);
272         } else
273           GV->setLinkage(llvm::Function::DLLImportLinkage);
274       }
275     } else if (D->getAttr<WeakAttr>() ||
276                D->getAttr<WeakImportAttr>()) {
277       // "extern_weak" is overloaded in LLVM; we probably should have
278       // separate linkage types for this.
279       GV->setLinkage(llvm::Function::ExternalWeakLinkage);
280    }
281   } else {
282     if (IsInternal) {
283       GV->setLinkage(llvm::Function::InternalLinkage);
284     } else {
285       if (D->getAttr<DLLExportAttr>()) {
286         if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
287           // The dllexport attribute is ignored for undefined symbols.
288           if (FD->getBody())
289             GV->setLinkage(llvm::Function::DLLExportLinkage);
290         } else
291           GV->setLinkage(llvm::Function::DLLExportLinkage);
292       } else if (D->getAttr<WeakAttr>() || D->getAttr<WeakImportAttr>() ||
293                  IsInline)
294         GV->setLinkage(llvm::Function::WeakAnyLinkage);
295     }
296   }
297 
298   // FIXME: Figure out the relative priority of the attribute,
299   // -fvisibility, and private_extern.
300   if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
301     setGlobalVisibility(GV, attr->getVisibility());
302   // FIXME: else handle -fvisibility
303 
304   // Prefaced with special LLVM marker to indicate that the name
305   // should not be munged.
306   if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>())
307     GV->setName("\01" + ALA->getLabel());
308 
309   if (const SectionAttr *SA = D->getAttr<SectionAttr>())
310     GV->setSection(SA->getName());
311 
312   // Only add to llvm.used when we see a definition, otherwise we
313   // might add multiple times or risk the value being replaced by a
314   // subsequent RAUW.
315   if (ForDefinition) {
316     if (D->getAttr<UsedAttr>())
317       AddUsedGlobal(GV);
318   }
319 }
320 
321 void CodeGenModule::SetFunctionAttributes(const Decl *D,
322                                           const CGFunctionInfo &Info,
323                                           llvm::Function *F) {
324   AttributeListType AttributeList;
325   ConstructAttributeList(Info, D, AttributeList);
326 
327   F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
328                                         AttributeList.size()));
329 
330   // Set the appropriate calling convention for the Function.
331   if (D->getAttr<FastCallAttr>())
332     F->setCallingConv(llvm::CallingConv::X86_FastCall);
333 
334   if (D->getAttr<StdCallAttr>())
335     F->setCallingConv(llvm::CallingConv::X86_StdCall);
336 }
337 
338 /// SetFunctionAttributesForDefinition - Set function attributes
339 /// specific to a function definition.
340 void CodeGenModule::SetFunctionAttributesForDefinition(const Decl *D,
341                                                        llvm::Function *F) {
342   if (isa<ObjCMethodDecl>(D)) {
343     SetGlobalValueAttributes(D, true, false, F, true);
344   } else {
345     const FunctionDecl *FD = cast<FunctionDecl>(D);
346     SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static,
347                              FD->isInline(), F, true);
348   }
349 
350   if (!Features.Exceptions && !Features.ObjCNonFragileABI)
351     F->addFnAttr(llvm::Attribute::NoUnwind);
352 
353   if (D->getAttr<AlwaysInlineAttr>())
354     F->addFnAttr(llvm::Attribute::AlwaysInline);
355 
356   if (D->getAttr<NoinlineAttr>())
357     F->addFnAttr(llvm::Attribute::NoInline);
358 }
359 
360 void CodeGenModule::SetMethodAttributes(const ObjCMethodDecl *MD,
361                                         llvm::Function *F) {
362   SetFunctionAttributes(MD, getTypes().getFunctionInfo(MD), F);
363 
364   SetFunctionAttributesForDefinition(MD, F);
365 }
366 
367 void CodeGenModule::SetFunctionAttributes(const FunctionDecl *FD,
368                                           llvm::Function *F) {
369   SetFunctionAttributes(FD, getTypes().getFunctionInfo(FD), F);
370 
371   SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static,
372                            FD->isInline(), F, false);
373 }
374 
375 
376 void CodeGenModule::EmitAliases() {
377   for (unsigned i = 0, e = Aliases.size(); i != e; ++i) {
378     const ValueDecl *D = Aliases[i];
379     const AliasAttr *AA = D->getAttr<AliasAttr>();
380 
381     // This is something of a hack, if the FunctionDecl got overridden
382     // then its attributes will be moved to the new declaration. In
383     // this case the current decl has no alias attribute, but we will
384     // eventually see it.
385     if (!AA)
386       continue;
387 
388     const std::string& aliaseeName = AA->getAliasee();
389     llvm::GlobalValue *aliasee = getModule().getNamedValue(aliaseeName);
390     if (!aliasee) {
391       // FIXME: This isn't unsupported, this is just an error, which
392       // sema should catch, but...
393       ErrorUnsupported(D, "alias referencing a missing function");
394       continue;
395     }
396 
397     llvm::GlobalValue *GA =
398       new llvm::GlobalAlias(aliasee->getType(),
399                             llvm::Function::ExternalLinkage,
400                             getMangledName(D), aliasee,
401                             &getModule());
402 
403     llvm::GlobalValue *&Entry = GlobalDeclMap[getMangledName(D)];
404     if (Entry) {
405       // If we created a dummy function for this then replace it.
406       GA->takeName(Entry);
407 
408       llvm::Value *Casted =
409         llvm::ConstantExpr::getBitCast(GA, Entry->getType());
410       Entry->replaceAllUsesWith(Casted);
411       Entry->eraseFromParent();
412 
413       Entry = GA;
414     }
415 
416     // Alias should never be internal or inline.
417     SetGlobalValueAttributes(D, false, false, GA, true);
418   }
419 }
420 
421 void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
422   assert(!GV->isDeclaration() &&
423          "Only globals with definition can force usage.");
424   llvm::Type *i8PTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
425   LLVMUsed.push_back(llvm::ConstantExpr::getBitCast(GV, i8PTy));
426 }
427 
428 void CodeGenModule::EmitLLVMUsed() {
429   // Don't create llvm.used if there is no need.
430   if (LLVMUsed.empty())
431     return;
432 
433   llvm::ArrayType *ATy = llvm::ArrayType::get(LLVMUsed[0]->getType(),
434                                               LLVMUsed.size());
435   llvm::GlobalVariable *GV =
436     new llvm::GlobalVariable(ATy, false,
437                              llvm::GlobalValue::AppendingLinkage,
438                              llvm::ConstantArray::get(ATy, LLVMUsed),
439                              "llvm.used", &getModule());
440 
441   GV->setSection("llvm.metadata");
442 }
443 
444 void CodeGenModule::EmitDeferred() {
445   // Emit code for any deferred decl which was used.  Since a
446   // previously unused static decl may become used during the
447   // generation of code for a static function, iterate until no
448   // changes are made.
449   bool Changed;
450   do {
451     Changed = false;
452 
453     for (std::list<const ValueDecl*>::iterator i = DeferredDecls.begin(),
454          e = DeferredDecls.end(); i != e; ) {
455       const ValueDecl *D = *i;
456 
457       // Check if we have used a decl with the same name
458       // FIXME: The AST should have some sort of aggregate decls or
459       // global symbol map.
460       // FIXME: This is missing some important cases. For example, we
461       // need to check for uses in an alias.
462       if (!GlobalDeclMap.count(getMangledName(D))) {
463         ++i;
464         continue;
465       }
466 
467       // Emit the definition.
468       EmitGlobalDefinition(D);
469 
470       // Erase the used decl from the list.
471       i = DeferredDecls.erase(i);
472 
473       // Remember that we made a change.
474       Changed = true;
475     }
476   } while (Changed);
477 }
478 
479 /// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
480 /// annotation information for a given GlobalValue.  The annotation struct is
481 /// {i8 *, i8 *, i8 *, i32}.  The first field is a constant expression, the
482 /// GlobalValue being annotated.  The second field is the constant string
483 /// created from the AnnotateAttr's annotation.  The third field is a constant
484 /// string containing the name of the translation unit.  The fourth field is
485 /// the line number in the file of the annotated value declaration.
486 ///
487 /// FIXME: this does not unique the annotation string constants, as llvm-gcc
488 ///        appears to.
489 ///
490 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
491                                                 const AnnotateAttr *AA,
492                                                 unsigned LineNo) {
493   llvm::Module *M = &getModule();
494 
495   // get [N x i8] constants for the annotation string, and the filename string
496   // which are the 2nd and 3rd elements of the global annotation structure.
497   const llvm::Type *SBP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
498   llvm::Constant *anno = llvm::ConstantArray::get(AA->getAnnotation(), true);
499   llvm::Constant *unit = llvm::ConstantArray::get(M->getModuleIdentifier(),
500                                                   true);
501 
502   // Get the two global values corresponding to the ConstantArrays we just
503   // created to hold the bytes of the strings.
504   llvm::GlobalValue *annoGV =
505   new llvm::GlobalVariable(anno->getType(), false,
506                            llvm::GlobalValue::InternalLinkage, anno,
507                            GV->getName() + ".str", M);
508   // translation unit name string, emitted into the llvm.metadata section.
509   llvm::GlobalValue *unitGV =
510   new llvm::GlobalVariable(unit->getType(), false,
511                            llvm::GlobalValue::InternalLinkage, unit, ".str", M);
512 
513   // Create the ConstantStruct that is the global annotion.
514   llvm::Constant *Fields[4] = {
515     llvm::ConstantExpr::getBitCast(GV, SBP),
516     llvm::ConstantExpr::getBitCast(annoGV, SBP),
517     llvm::ConstantExpr::getBitCast(unitGV, SBP),
518     llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo)
519   };
520   return llvm::ConstantStruct::get(Fields, 4, false);
521 }
522 
523 bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
524   // Never defer when EmitAllDecls is specified or the decl has
525   // attribute used.
526   if (Features.EmitAllDecls || Global->getAttr<UsedAttr>())
527     return false;
528 
529   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
530     // Constructors and destructors should never be deferred.
531     if (FD->getAttr<ConstructorAttr>() || FD->getAttr<DestructorAttr>())
532       return false;
533 
534     if (FD->getStorageClass() != FunctionDecl::Static)
535       return false;
536   } else {
537     const VarDecl *VD = cast<VarDecl>(Global);
538     assert(VD->isFileVarDecl() && "Invalid decl.");
539 
540     if (VD->getStorageClass() != VarDecl::Static)
541       return false;
542   }
543 
544   return true;
545 }
546 
547 void CodeGenModule::EmitGlobal(const ValueDecl *Global) {
548   // Aliases are deferred until code for everything else has been
549   // emitted.
550   if (Global->getAttr<AliasAttr>()) {
551     Aliases.push_back(Global);
552     return;
553   }
554 
555   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
556     // Forward declarations are emitted lazily on first use.
557     if (!FD->isThisDeclarationADefinition())
558       return;
559   } else {
560     const VarDecl *VD = cast<VarDecl>(Global);
561     assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
562 
563     // Forward declarations are emitted lazily on first use.
564     if (!VD->getInit() && VD->hasExternalStorage())
565       return;
566   }
567 
568   // Defer code generation when possible.
569   if (MayDeferGeneration(Global)) {
570     DeferredDecls.push_back(Global);
571     return;
572   }
573 
574   // Otherwise emit the definition.
575   EmitGlobalDefinition(Global);
576 }
577 
578 void CodeGenModule::EmitGlobalDefinition(const ValueDecl *D) {
579   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
580     EmitGlobalFunctionDefinition(FD);
581   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
582     EmitGlobalVarDefinition(VD);
583   } else {
584     assert(0 && "Invalid argument to EmitGlobalDefinition()");
585   }
586 }
587 
588  llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D) {
589   assert(D->hasGlobalStorage() && "Not a global variable");
590 
591   QualType ASTTy = D->getType();
592   const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
593   const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
594 
595   // Lookup the entry, lazily creating it if necessary.
596   llvm::GlobalValue *&Entry = GlobalDeclMap[getMangledName(D)];
597   if (!Entry) {
598     llvm::GlobalVariable *GV =
599       new llvm::GlobalVariable(Ty, false,
600                                llvm::GlobalValue::ExternalLinkage,
601                                0, getMangledName(D), &getModule(),
602                                0, ASTTy.getAddressSpace());
603     Entry = GV;
604 
605     // Handle things which are present even on external declarations.
606 
607     // FIXME: This code is overly simple and should be merged with
608     // other global handling.
609 
610     GV->setConstant(D->getType().isConstant(Context));
611 
612     // FIXME: Merge with other attribute handling code.
613 
614     if (D->getStorageClass() == VarDecl::PrivateExtern)
615       setGlobalVisibility(GV, VisibilityAttr::HiddenVisibility);
616 
617     if (D->getAttr<WeakAttr>() || D->getAttr<WeakImportAttr>())
618       GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
619 
620     if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
621       // Prefaced with special LLVM marker to indicate that the name
622       // should not be munged.
623       GV->setName("\01" + ALA->getLabel());
624     }
625   }
626 
627   // Make sure the result is of the correct type.
628   return llvm::ConstantExpr::getBitCast(Entry, PTy);
629 }
630 
631 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
632   llvm::Constant *Init = 0;
633   QualType ASTTy = D->getType();
634   const llvm::Type *VarTy = getTypes().ConvertTypeForMem(ASTTy);
635 
636   if (D->getInit() == 0) {
637     // This is a tentative definition; tentative definitions are
638     // implicitly initialized with { 0 }
639     const llvm::Type* InitTy;
640     if (ASTTy->isIncompleteArrayType()) {
641       // An incomplete array is normally [ TYPE x 0 ], but we need
642       // to fix it to [ TYPE x 1 ].
643       const llvm::ArrayType* ATy = cast<llvm::ArrayType>(VarTy);
644       InitTy = llvm::ArrayType::get(ATy->getElementType(), 1);
645     } else {
646       InitTy = VarTy;
647     }
648     Init = llvm::Constant::getNullValue(InitTy);
649   } else {
650     Init = EmitConstantExpr(D->getInit());
651     if (!Init) {
652       ErrorUnsupported(D, "static initializer");
653       QualType T = D->getInit()->getType();
654       Init = llvm::UndefValue::get(getTypes().ConvertType(T));
655     }
656   }
657   const llvm::Type* InitType = Init->getType();
658 
659   llvm::GlobalValue *&Entry = GlobalDeclMap[getMangledName(D)];
660   llvm::GlobalVariable *GV = cast_or_null<llvm::GlobalVariable>(Entry);
661 
662   if (!GV) {
663     GV = new llvm::GlobalVariable(InitType, false,
664                                   llvm::GlobalValue::ExternalLinkage,
665                                   0, getMangledName(D),
666                                   &getModule(), 0, ASTTy.getAddressSpace());
667 
668   } else if (GV->hasInitializer() && !GV->getInitializer()->isNullValue()) {
669     // If we already have this global and it has an initializer, then
670     // we are in the rare situation where we emitted the defining
671     // declaration of the global and are now being asked to emit a
672     // definition which would be common. This occurs, for example, in
673     // the following situation because statics can be emitted out of
674     // order:
675     //
676     //  static int x;
677     //  static int *y = &x;
678     //  static int x = 10;
679     //  int **z = &y;
680     //
681     // Bail here so we don't blow away the definition. Note that if we
682     // can't distinguish here if we emitted a definition with a null
683     // initializer, but this case is safe.
684     assert(!D->getInit() && "Emitting multiple definitions of a decl!");
685     return;
686 
687   } else if (GV->getType() !=
688              llvm::PointerType::get(InitType, ASTTy.getAddressSpace())) {
689     // We have a definition after a prototype with the wrong type.
690     // We must make a new GlobalVariable* and update everything that used OldGV
691     // (a declaration or tentative definition) with the new GlobalVariable*
692     // (which will be a definition).
693     //
694     // This happens if there is a prototype for a global (e.g. "extern int x[];")
695     // and then a definition of a different type (e.g. "int x[10];"). This also
696     // happens when an initializer has a different type from the type of the
697     // global (this happens with unions).
698     //
699     // FIXME: This also ends up happening if there's a definition followed by
700     // a tentative definition!  (Although Sema rejects that construct
701     // at the moment.)
702 
703     // Save the old global
704     llvm::GlobalVariable *OldGV = GV;
705 
706     // Make a new global with the correct type
707     GV = new llvm::GlobalVariable(InitType, false,
708                                   llvm::GlobalValue::ExternalLinkage,
709                                   0, getMangledName(D),
710                                   &getModule(), 0, ASTTy.getAddressSpace());
711     // Steal the name of the old global
712     GV->takeName(OldGV);
713 
714     // Replace all uses of the old global with the new global
715     llvm::Constant *NewPtrForOldDecl =
716         llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
717     OldGV->replaceAllUsesWith(NewPtrForOldDecl);
718 
719     // Erase the old global, since it is no longer used.
720     OldGV->eraseFromParent();
721   }
722 
723   Entry = GV;
724 
725   if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
726     SourceManager &SM = Context.getSourceManager();
727     AddAnnotation(EmitAnnotateAttr(GV, AA,
728                               SM.getInstantiationLineNumber(D->getLocation())));
729   }
730 
731   GV->setInitializer(Init);
732   GV->setConstant(D->getType().isConstant(Context));
733   GV->setAlignment(getContext().getDeclAlignInBytes(D));
734 
735   if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
736     setGlobalVisibility(GV, attr->getVisibility());
737   // FIXME: else handle -fvisibility
738 
739   if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
740     // Prefaced with special LLVM marker to indicate that the name
741     // should not be munged.
742     GV->setName("\01" + ALA->getLabel());
743   }
744 
745   // Set the llvm linkage type as appropriate.
746   if (D->getStorageClass() == VarDecl::Static)
747     GV->setLinkage(llvm::Function::InternalLinkage);
748   else if (D->getAttr<DLLImportAttr>())
749     GV->setLinkage(llvm::Function::DLLImportLinkage);
750   else if (D->getAttr<DLLExportAttr>())
751     GV->setLinkage(llvm::Function::DLLExportLinkage);
752   else if (D->getAttr<WeakAttr>() || D->getAttr<WeakImportAttr>())
753     GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
754   else {
755     // FIXME: This isn't right.  This should handle common linkage and other
756     // stuff.
757     switch (D->getStorageClass()) {
758     case VarDecl::Static: assert(0 && "This case handled above");
759     case VarDecl::Auto:
760     case VarDecl::Register:
761       assert(0 && "Can't have auto or register globals");
762     case VarDecl::None:
763       if (!D->getInit())
764         GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
765       else
766         GV->setLinkage(llvm::GlobalVariable::ExternalLinkage);
767       break;
768     case VarDecl::Extern:
769       // FIXME: common
770       break;
771 
772     case VarDecl::PrivateExtern:
773       GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
774       // FIXME: common
775       break;
776     }
777   }
778 
779   if (const SectionAttr *SA = D->getAttr<SectionAttr>())
780     GV->setSection(SA->getName());
781 
782   if (D->getAttr<UsedAttr>())
783     AddUsedGlobal(GV);
784 
785   // Emit global variable debug information.
786   CGDebugInfo *DI = getDebugInfo();
787   if(DI) {
788     DI->setLocation(D->getLocation());
789     DI->EmitGlobalVariable(GV, D);
790   }
791 }
792 
793 llvm::GlobalValue *
794 CodeGenModule::EmitForwardFunctionDefinition(const FunctionDecl *D,
795                                              const llvm::Type *Ty) {
796   bool DoSetAttributes = true;
797   if (!Ty) {
798     Ty = getTypes().ConvertType(D->getType());
799     if (!isa<llvm::FunctionType>(Ty)) {
800       // This function doesn't have a complete type (for example, the return
801       // type is an incomplete struct). Use a fake type instead, and make
802       // sure not to try to set attributes.
803       Ty = llvm::FunctionType::get(llvm::Type::VoidTy,
804                                    std::vector<const llvm::Type*>(), false);
805       DoSetAttributes = false;
806     }
807   }
808   llvm::Function *F = llvm::Function::Create(cast<llvm::FunctionType>(Ty),
809                                              llvm::Function::ExternalLinkage,
810                                              getMangledName(D),
811                                              &getModule());
812   if (DoSetAttributes)
813     SetFunctionAttributes(D, F);
814   return F;
815 }
816 
817 llvm::Constant *CodeGenModule::GetAddrOfFunction(const FunctionDecl *D) {
818   QualType ASTTy = D->getType();
819   const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
820   const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
821 
822   // Lookup the entry, lazily creating it if necessary.
823   llvm::GlobalValue *&Entry = GlobalDeclMap[getMangledName(D)];
824   if (!Entry)
825     Entry = EmitForwardFunctionDefinition(D, 0);
826 
827   if (Entry->getType() != PTy)
828     return llvm::ConstantExpr::getBitCast(Entry, PTy);
829   return Entry;
830 }
831 
832 void CodeGenModule::EmitGlobalFunctionDefinition(const FunctionDecl *D) {
833   const llvm::FunctionType *Ty =
834     cast<llvm::FunctionType>(getTypes().ConvertType(D->getType()));
835 
836   // As a special case, make sure that definitions of K&R function
837   // "type foo()" aren't declared as varargs (which forces the backend
838   // to do unnecessary work).
839   if (Ty->isVarArg() && Ty->getNumParams() == 0 && Ty->isVarArg())
840     Ty = llvm::FunctionType::get(Ty->getReturnType(),
841                                  std::vector<const llvm::Type*>(),
842                                  false);
843 
844   llvm::GlobalValue *&Entry = GlobalDeclMap[getMangledName(D)];
845   if (!Entry) {
846     Entry = EmitForwardFunctionDefinition(D, Ty);
847   } else {
848     // If the types mismatch then we have to rewrite the definition.
849     if (Entry->getType() != llvm::PointerType::getUnqual(Ty)) {
850       // Otherwise, we have a definition after a prototype with the
851       // wrong type.  F is the Function* for the one with the wrong
852       // type, we must make a new Function* and update everything that
853       // used F (a declaration) with the new Function* (which will be
854       // a definition).
855       //
856       // This happens if there is a prototype for a function
857       // (e.g. "int f()") and then a definition of a different type
858       // (e.g. "int f(int x)").  Start by making a new function of the
859       // correct type, RAUW, then steal the name.
860       llvm::GlobalValue *NewFn = EmitForwardFunctionDefinition(D, Ty);
861       NewFn->takeName(Entry);
862 
863       // Replace uses of F with the Function we will endow with a body.
864       llvm::Constant *NewPtrForOldDecl =
865         llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
866       Entry->replaceAllUsesWith(NewPtrForOldDecl);
867 
868       // Ok, delete the old function now, which is dead.
869       assert(Entry->isDeclaration() && "Shouldn't replace non-declaration");
870       Entry->eraseFromParent();
871 
872       Entry = NewFn;
873     }
874   }
875 
876   llvm::Function *Fn = cast<llvm::Function>(Entry);
877   CodeGenFunction(*this).GenerateCode(D, Fn);
878 
879   SetFunctionAttributesForDefinition(D, Fn);
880 
881   if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) {
882     AddGlobalCtor(Fn, CA->getPriority());
883   } else if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) {
884     AddGlobalDtor(Fn, DA->getPriority());
885   }
886 }
887 
888 llvm::Function *
889 CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy,
890                                      const std::string &Name) {
891   llvm::Function *Fn = llvm::Function::Create(FTy,
892                                               llvm::Function::ExternalLinkage,
893                                               "", &TheModule);
894   RuntimeGlobals.push_back(std::make_pair(Fn, Name));
895   return Fn;
896 }
897 
898 llvm::GlobalVariable *
899 CodeGenModule::CreateRuntimeVariable(const llvm::Type *Ty,
900                                      const std::string &Name) {
901   llvm::GlobalVariable *GV =
902     new llvm::GlobalVariable(Ty, /*Constant=*/false,
903                              llvm::GlobalValue::ExternalLinkage,
904                              0, "", &TheModule);
905   RuntimeGlobals.push_back(std::make_pair(GV, Name));
906   return GV;
907 }
908 
909 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
910   // Make sure that this type is translated.
911   Types.UpdateCompletedType(TD);
912 }
913 
914 
915 /// getBuiltinLibFunction
916 llvm::Value *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
917   if (BuiltinID > BuiltinFunctions.size())
918     BuiltinFunctions.resize(BuiltinID);
919 
920   // Cache looked up functions.  Since builtin id #0 is invalid we don't reserve
921   // a slot for it.
922   assert(BuiltinID && "Invalid Builtin ID");
923   llvm::Value *&FunctionSlot = BuiltinFunctions[BuiltinID-1];
924   if (FunctionSlot)
925     return FunctionSlot;
926 
927   assert((Context.BuiltinInfo.isLibFunction(BuiltinID) ||
928           Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) &&
929          "isn't a lib fn");
930 
931   // Get the name, skip over the __builtin_ prefix (if necessary).
932   const char *Name = Context.BuiltinInfo.GetName(BuiltinID);
933   if (Context.BuiltinInfo.isLibFunction(BuiltinID))
934     Name += 10;
935 
936   // Get the type for the builtin.
937   Builtin::Context::GetBuiltinTypeError Error;
938   QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context, Error);
939   assert(Error == Builtin::Context::GE_None && "Can't get builtin type");
940 
941   const llvm::FunctionType *Ty =
942     cast<llvm::FunctionType>(getTypes().ConvertType(Type));
943 
944   // FIXME: This has a serious problem with code like this:
945   //  void abs() {}
946   //    ... __builtin_abs(x);
947   // The two versions of abs will collide.  The fix is for the builtin to win,
948   // and for the existing one to be turned into a constantexpr cast of the
949   // builtin.  In the case where the existing one is a static function, it
950   // should just be renamed.
951   if (llvm::Function *Existing = getModule().getFunction(Name)) {
952     if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
953       return FunctionSlot = Existing;
954     assert(Existing == 0 && "FIXME: Name collision");
955   }
956 
957   llvm::GlobalValue *&ExistingFn =
958     GlobalDeclMap[getContext().Idents.get(Name).getName()];
959   assert(!ExistingFn && "Asking for the same builtin multiple times?");
960 
961   // FIXME: param attributes for sext/zext etc.
962   return FunctionSlot = ExistingFn =
963     llvm::Function::Create(Ty, llvm::Function::ExternalLinkage, Name,
964                            &getModule());
965 }
966 
967 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
968                                             unsigned NumTys) {
969   return llvm::Intrinsic::getDeclaration(&getModule(),
970                                          (llvm::Intrinsic::ID)IID, Tys, NumTys);
971 }
972 
973 llvm::Function *CodeGenModule::getMemCpyFn() {
974   if (MemCpyFn) return MemCpyFn;
975   const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
976   return MemCpyFn = getIntrinsic(llvm::Intrinsic::memcpy, &IntPtr, 1);
977 }
978 
979 llvm::Function *CodeGenModule::getMemMoveFn() {
980   if (MemMoveFn) return MemMoveFn;
981   const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
982   return MemMoveFn = getIntrinsic(llvm::Intrinsic::memmove, &IntPtr, 1);
983 }
984 
985 llvm::Function *CodeGenModule::getMemSetFn() {
986   if (MemSetFn) return MemSetFn;
987   const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
988   return MemSetFn = getIntrinsic(llvm::Intrinsic::memset, &IntPtr, 1);
989 }
990 
991 static void appendFieldAndPadding(CodeGenModule &CGM,
992                                   std::vector<llvm::Constant*>& Fields,
993                                   FieldDecl *FieldD, FieldDecl *NextFieldD,
994                                   llvm::Constant* Field,
995                                   RecordDecl* RD, const llvm::StructType *STy)
996 {
997   // Append the field.
998   Fields.push_back(Field);
999 
1000   int StructFieldNo = CGM.getTypes().getLLVMFieldNo(FieldD);
1001 
1002   int NextStructFieldNo;
1003   if (!NextFieldD) {
1004     NextStructFieldNo = STy->getNumElements();
1005   } else {
1006     NextStructFieldNo = CGM.getTypes().getLLVMFieldNo(NextFieldD);
1007   }
1008 
1009   // Append padding
1010   for (int i = StructFieldNo + 1; i < NextStructFieldNo; i++) {
1011     llvm::Constant *C =
1012       llvm::Constant::getNullValue(STy->getElementType(StructFieldNo + 1));
1013 
1014     Fields.push_back(C);
1015   }
1016 }
1017 
1018 // We still need to work out the details of handling UTF-16.
1019 // See: <rdr://2996215>
1020 llvm::Constant *CodeGenModule::
1021 GetAddrOfConstantCFString(const std::string &str) {
1022   llvm::StringMapEntry<llvm::Constant *> &Entry =
1023     CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
1024 
1025   if (Entry.getValue())
1026     return Entry.getValue();
1027 
1028   llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
1029   llvm::Constant *Zeros[] = { Zero, Zero };
1030 
1031   if (!CFConstantStringClassRef) {
1032     const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
1033     Ty = llvm::ArrayType::get(Ty, 0);
1034 
1035     // FIXME: This is fairly broken if
1036     // __CFConstantStringClassReference is already defined, in that it
1037     // will get renamed and the user will most likely see an opaque
1038     // error message. This is a general issue with relying on
1039     // particular names.
1040     llvm::GlobalVariable *GV =
1041       new llvm::GlobalVariable(Ty, false,
1042                                llvm::GlobalVariable::ExternalLinkage, 0,
1043                                "__CFConstantStringClassReference",
1044                                &getModule());
1045 
1046     // Decay array -> ptr
1047     CFConstantStringClassRef =
1048       llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1049   }
1050 
1051   QualType CFTy = getContext().getCFConstantStringType();
1052   RecordDecl *CFRD = CFTy->getAsRecordType()->getDecl();
1053 
1054   const llvm::StructType *STy =
1055     cast<llvm::StructType>(getTypes().ConvertType(CFTy));
1056 
1057   std::vector<llvm::Constant*> Fields;
1058   RecordDecl::field_iterator Field = CFRD->field_begin();
1059 
1060   // Class pointer.
1061   FieldDecl *CurField = *Field++;
1062   FieldDecl *NextField = *Field++;
1063   appendFieldAndPadding(*this, Fields, CurField, NextField,
1064                         CFConstantStringClassRef, CFRD, STy);
1065 
1066   // Flags.
1067   CurField = NextField;
1068   NextField = *Field++;
1069   const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
1070   appendFieldAndPadding(*this, Fields, CurField, NextField,
1071                         llvm::ConstantInt::get(Ty, 0x07C8), CFRD, STy);
1072 
1073   // String pointer.
1074   CurField = NextField;
1075   NextField = *Field++;
1076   llvm::Constant *C = llvm::ConstantArray::get(str);
1077   C = new llvm::GlobalVariable(C->getType(), true,
1078                                llvm::GlobalValue::InternalLinkage,
1079                                C, ".str", &getModule());
1080   appendFieldAndPadding(*this, Fields, CurField, NextField,
1081                         llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2),
1082                         CFRD, STy);
1083 
1084   // String length.
1085   CurField = NextField;
1086   NextField = 0;
1087   Ty = getTypes().ConvertType(getContext().LongTy);
1088   appendFieldAndPadding(*this, Fields, CurField, NextField,
1089                         llvm::ConstantInt::get(Ty, str.length()), CFRD, STy);
1090 
1091   // The struct.
1092   C = llvm::ConstantStruct::get(STy, Fields);
1093   llvm::GlobalVariable *GV =
1094     new llvm::GlobalVariable(C->getType(), true,
1095                              llvm::GlobalVariable::InternalLinkage,
1096                              C, "", &getModule());
1097 
1098   GV->setSection("__DATA,__cfstring");
1099   Entry.setValue(GV);
1100 
1101   return GV;
1102 }
1103 
1104 /// GetStringForStringLiteral - Return the appropriate bytes for a
1105 /// string literal, properly padded to match the literal type.
1106 std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
1107   const char *StrData = E->getStrData();
1108   unsigned Len = E->getByteLength();
1109 
1110   const ConstantArrayType *CAT =
1111     getContext().getAsConstantArrayType(E->getType());
1112   assert(CAT && "String isn't pointer or array!");
1113 
1114   // Resize the string to the right size.
1115   std::string Str(StrData, StrData+Len);
1116   uint64_t RealLen = CAT->getSize().getZExtValue();
1117 
1118   if (E->isWide())
1119     RealLen *= getContext().Target.getWCharWidth()/8;
1120 
1121   Str.resize(RealLen, '\0');
1122 
1123   return Str;
1124 }
1125 
1126 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
1127 /// constant array for the given string literal.
1128 llvm::Constant *
1129 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
1130   // FIXME: This can be more efficient.
1131   return GetAddrOfConstantString(GetStringForStringLiteral(S));
1132 }
1133 
1134 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
1135 /// array for the given ObjCEncodeExpr node.
1136 llvm::Constant *
1137 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
1138   std::string Str;
1139   getContext().getObjCEncodingForType(E->getEncodedType(), Str);
1140 
1141   return GetAddrOfConstantCString(Str);
1142 }
1143 
1144 
1145 /// GenerateWritableString -- Creates storage for a string literal.
1146 static llvm::Constant *GenerateStringLiteral(const std::string &str,
1147                                              bool constant,
1148                                              CodeGenModule &CGM,
1149                                              const char *GlobalName) {
1150   // Create Constant for this string literal. Don't add a '\0'.
1151   llvm::Constant *C = llvm::ConstantArray::get(str, false);
1152 
1153   // Create a global variable for this string
1154   return new llvm::GlobalVariable(C->getType(), constant,
1155                                   llvm::GlobalValue::InternalLinkage,
1156                                   C, GlobalName ? GlobalName : ".str",
1157                                   &CGM.getModule());
1158 }
1159 
1160 /// GetAddrOfConstantString - Returns a pointer to a character array
1161 /// containing the literal. This contents are exactly that of the
1162 /// given string, i.e. it will not be null terminated automatically;
1163 /// see GetAddrOfConstantCString. Note that whether the result is
1164 /// actually a pointer to an LLVM constant depends on
1165 /// Feature.WriteableStrings.
1166 ///
1167 /// The result has pointer to array type.
1168 llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str,
1169                                                        const char *GlobalName) {
1170   // Don't share any string literals if writable-strings is turned on.
1171   if (Features.WritableStrings)
1172     return GenerateStringLiteral(str, false, *this, GlobalName);
1173 
1174   llvm::StringMapEntry<llvm::Constant *> &Entry =
1175   ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
1176 
1177   if (Entry.getValue())
1178     return Entry.getValue();
1179 
1180   // Create a global variable for this.
1181   llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName);
1182   Entry.setValue(C);
1183   return C;
1184 }
1185 
1186 /// GetAddrOfConstantCString - Returns a pointer to a character
1187 /// array containing the literal and a terminating '\-'
1188 /// character. The result has pointer to array type.
1189 llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str,
1190                                                         const char *GlobalName){
1191   return GetAddrOfConstantString(str + '\0', GlobalName);
1192 }
1193 
1194 /// EmitObjCPropertyImplementations - Emit information for synthesized
1195 /// properties for an implementation.
1196 void CodeGenModule::EmitObjCPropertyImplementations(const
1197                                                     ObjCImplementationDecl *D) {
1198   for (ObjCImplementationDecl::propimpl_iterator i = D->propimpl_begin(),
1199          e = D->propimpl_end(); i != e; ++i) {
1200     ObjCPropertyImplDecl *PID = *i;
1201 
1202     // Dynamic is just for type-checking.
1203     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1204       ObjCPropertyDecl *PD = PID->getPropertyDecl();
1205 
1206       // Determine which methods need to be implemented, some may have
1207       // been overridden. Note that ::isSynthesized is not the method
1208       // we want, that just indicates if the decl came from a
1209       // property. What we want to know is if the method is defined in
1210       // this implementation.
1211       if (!D->getInstanceMethod(PD->getGetterName()))
1212         CodeGenFunction(*this).GenerateObjCGetter(
1213                                  const_cast<ObjCImplementationDecl *>(D), PID);
1214       if (!PD->isReadOnly() &&
1215           !D->getInstanceMethod(PD->getSetterName()))
1216         CodeGenFunction(*this).GenerateObjCSetter(
1217                                  const_cast<ObjCImplementationDecl *>(D), PID);
1218     }
1219   }
1220 }
1221 
1222 /// EmitTopLevelDecl - Emit code for a single top level declaration.
1223 void CodeGenModule::EmitTopLevelDecl(Decl *D) {
1224   // If an error has occurred, stop code generation, but continue
1225   // parsing and semantic analysis (to ensure all warnings and errors
1226   // are emitted).
1227   if (Diags.hasErrorOccurred())
1228     return;
1229 
1230   switch (D->getKind()) {
1231   case Decl::Function:
1232   case Decl::Var:
1233     EmitGlobal(cast<ValueDecl>(D));
1234     break;
1235 
1236   case Decl::Namespace:
1237     ErrorUnsupported(D, "namespace");
1238     break;
1239 
1240     // Objective-C Decls
1241 
1242   // Forward declarations, no (immediate) code generation.
1243   case Decl::ObjCClass:
1244   case Decl::ObjCForwardProtocol:
1245     break;
1246 
1247   case Decl::ObjCProtocol:
1248   case Decl::ObjCCategory:
1249   case Decl::ObjCInterface: {
1250     ObjCContainerDecl *OCD = cast<ObjCContainerDecl>(D);
1251     for (ObjCContainerDecl::tuvar_iterator i = OCD->tuvar_begin(),
1252          e = OCD->tuvar_end(); i != e; ++i) {
1253         VarDecl *VD = *i;
1254         EmitGlobal(VD);
1255     }
1256     if (D->getKind() == Decl::ObjCProtocol)
1257       Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
1258     break;
1259   }
1260 
1261   case Decl::ObjCCategoryImpl:
1262     // Categories have properties but don't support synthesize so we
1263     // can ignore them here.
1264 
1265     Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
1266     break;
1267 
1268   case Decl::ObjCImplementation: {
1269     ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
1270     EmitObjCPropertyImplementations(OMD);
1271     Runtime->GenerateClass(OMD);
1272     break;
1273   }
1274   case Decl::ObjCMethod: {
1275     ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
1276     // If this is not a prototype, emit the body.
1277     if (OMD->getBody())
1278       CodeGenFunction(*this).GenerateObjCMethod(OMD);
1279     break;
1280   }
1281   case Decl::ObjCCompatibleAlias:
1282     // compatibility-alias is a directive and has no code gen.
1283     break;
1284 
1285   case Decl::LinkageSpec: {
1286     LinkageSpecDecl *LSD = cast<LinkageSpecDecl>(D);
1287     if (LSD->getLanguage() == LinkageSpecDecl::lang_cxx)
1288       ErrorUnsupported(LSD, "linkage spec");
1289     // FIXME: implement C++ linkage, C linkage works mostly by C
1290     // language reuse already.
1291     break;
1292   }
1293 
1294   case Decl::FileScopeAsm: {
1295     FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
1296     std::string AsmString(AD->getAsmString()->getStrData(),
1297                           AD->getAsmString()->getByteLength());
1298 
1299     const std::string &S = getModule().getModuleInlineAsm();
1300     if (S.empty())
1301       getModule().setModuleInlineAsm(AsmString);
1302     else
1303       getModule().setModuleInlineAsm(S + '\n' + AsmString);
1304     break;
1305   }
1306 
1307   default:
1308     // Make sure we handled everything we should, every other kind is
1309     // a non-top-level decl.  FIXME: Would be nice to have an
1310     // isTopLevelDeclKind function. Need to recode Decl::Kind to do
1311     // that easily.
1312     assert(isa<TypeDecl>(D) && "Unsupported decl kind");
1313   }
1314 }
1315