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