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