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