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