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