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