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 /// WarnUnsupported - Print out a warning that codegen doesn't support the
69 /// specified stmt yet.
70 void CodeGenModule::WarnUnsupported(const Stmt *S, const char *Type) {
71   unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Warning,
72                                                "cannot codegen this %0 yet");
73   SourceRange Range = S->getSourceRange();
74   std::string Msg = Type;
75   getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID,
76                     &Msg, 1, &Range, 1);
77 }
78 
79 /// WarnUnsupported - Print out a warning that codegen doesn't support the
80 /// specified decl yet.
81 void CodeGenModule::WarnUnsupported(const Decl *D, const char *Type) {
82   unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Warning,
83                                                "cannot codegen this %0 yet");
84   std::string Msg = Type;
85   getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID,
86                     &Msg, 1);
87 }
88 
89 /// setVisibility - Set the visibility for the given LLVM GlobalValue
90 /// according to the given clang AST visibility value.
91 void CodeGenModule::setVisibility(llvm::GlobalValue *GV,
92                                   VisibilityAttr::VisibilityTypes Vis) {
93   switch (Vis) {
94   default: assert(0 && "Unknown visibility!");
95   case VisibilityAttr::DefaultVisibility:
96     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
97     break;
98   case VisibilityAttr::HiddenVisibility:
99     GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
100     break;
101   case VisibilityAttr::ProtectedVisibility:
102     GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
103     break;
104   }
105 }
106 
107 /// AddGlobalCtor - Add a function to the list that will be called before
108 /// main() runs.
109 void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
110   // TODO: Type coercion of void()* types.
111   GlobalCtors.push_back(std::make_pair(Ctor, Priority));
112 }
113 
114 /// AddGlobalDtor - Add a function to the list that will be called
115 /// when the module is unloaded.
116 void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
117   // TODO: Type coercion of void()* types.
118   GlobalDtors.push_back(std::make_pair(Dtor, Priority));
119 }
120 
121 void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
122   // Ctor function type is void()*.
123   llvm::FunctionType* CtorFTy =
124     llvm::FunctionType::get(llvm::Type::VoidTy,
125                             std::vector<const llvm::Type*>(),
126                             false);
127   llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
128 
129   // Get the type of a ctor entry, { i32, void ()* }.
130   llvm::StructType* CtorStructTy =
131     llvm::StructType::get(llvm::Type::Int32Ty,
132                           llvm::PointerType::getUnqual(CtorFTy), NULL);
133 
134   // Construct the constructor and destructor arrays.
135   std::vector<llvm::Constant*> Ctors;
136   for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
137     std::vector<llvm::Constant*> S;
138     S.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, I->second, false));
139     S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
140     Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
141   }
142 
143   if (!Ctors.empty()) {
144     llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
145     new llvm::GlobalVariable(AT, false,
146                              llvm::GlobalValue::AppendingLinkage,
147                              llvm::ConstantArray::get(AT, Ctors),
148                              GlobalName,
149                              &TheModule);
150   }
151 }
152 
153 void CodeGenModule::EmitAnnotations() {
154   if (Annotations.empty())
155     return;
156 
157   // Create a new global variable for the ConstantStruct in the Module.
158   llvm::Constant *Array =
159   llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
160                                                 Annotations.size()),
161                            Annotations);
162   llvm::GlobalValue *gv =
163   new llvm::GlobalVariable(Array->getType(), false,
164                            llvm::GlobalValue::AppendingLinkage, Array,
165                            "llvm.global.annotations", &TheModule);
166   gv->setSection("llvm.metadata");
167 }
168 
169 bool hasAggregateLLVMType(QualType T) {
170   return !T->isRealType() && !T->isPointerLikeType() &&
171          !T->isVoidType() && !T->isVectorType() && !T->isFunctionType();
172 }
173 
174 void CodeGenModule::SetGlobalValueAttributes(const FunctionDecl *FD,
175                                              llvm::GlobalValue *GV) {
176   // TODO: Set up linkage and many other things.  Note, this is a simple
177   // approximation of what we really want.
178   if (FD->getStorageClass() == FunctionDecl::Static)
179     GV->setLinkage(llvm::Function::InternalLinkage);
180   else if (FD->getAttr<DLLImportAttr>())
181     GV->setLinkage(llvm::Function::DLLImportLinkage);
182   else if (FD->getAttr<DLLExportAttr>())
183     GV->setLinkage(llvm::Function::DLLExportLinkage);
184   else if (FD->getAttr<WeakAttr>() || FD->isInline())
185     GV->setLinkage(llvm::Function::WeakLinkage);
186 
187   if (const VisibilityAttr *attr = FD->getAttr<VisibilityAttr>())
188     CodeGenModule::setVisibility(GV, attr->getVisibility());
189   // FIXME: else handle -fvisibility
190 
191   if (const AsmLabelAttr *ALA = FD->getAttr<AsmLabelAttr>()) {
192     // Prefaced with special LLVM marker to indicate that the name
193     // should not be munged.
194     GV->setName("\01" + ALA->getLabel());
195   }
196 }
197 
198 void CodeGenModule::SetFunctionAttributes(const FunctionDecl *FD,
199                                           llvm::Function *F,
200                                           const llvm::FunctionType *FTy) {
201   unsigned FuncAttrs = 0;
202   if (FD->getAttr<NoThrowAttr>())
203     FuncAttrs |= llvm::ParamAttr::NoUnwind;
204   if (FD->getAttr<NoReturnAttr>())
205     FuncAttrs |= llvm::ParamAttr::NoReturn;
206 
207   llvm::SmallVector<llvm::ParamAttrsWithIndex, 8> ParamAttrList;
208   if (FuncAttrs)
209     ParamAttrList.push_back(llvm::ParamAttrsWithIndex::get(0, FuncAttrs));
210   // Note that there is parallel code in CodeGenFunction::EmitCallExpr
211   bool AggregateReturn = hasAggregateLLVMType(FD->getResultType());
212   if (AggregateReturn)
213     ParamAttrList.push_back(
214         llvm::ParamAttrsWithIndex::get(1, llvm::ParamAttr::StructRet));
215   unsigned increment = AggregateReturn ? 2 : 1;
216   const FunctionTypeProto* FTP = dyn_cast<FunctionTypeProto>(FD->getType());
217   if (FTP) {
218     for (unsigned i = 0; i < FTP->getNumArgs(); i++) {
219       QualType ParamType = FTP->getArgType(i);
220       unsigned ParamAttrs = 0;
221       if (ParamType->isRecordType())
222         ParamAttrs |= llvm::ParamAttr::ByVal;
223       if (ParamType->isSignedIntegerType() &&
224           ParamType->isPromotableIntegerType())
225         ParamAttrs |= llvm::ParamAttr::SExt;
226       if (ParamType->isUnsignedIntegerType() &&
227           ParamType->isPromotableIntegerType())
228         ParamAttrs |= llvm::ParamAttr::ZExt;
229       if (ParamAttrs)
230         ParamAttrList.push_back(llvm::ParamAttrsWithIndex::get(i + increment,
231                                                                ParamAttrs));
232     }
233   }
234 
235   F->setParamAttrs(llvm::PAListPtr::get(ParamAttrList.begin(),
236                                         ParamAttrList.size()));
237 
238   // Set the appropriate calling convention for the Function.
239   if (FD->getAttr<FastCallAttr>())
240     F->setCallingConv(llvm::CallingConv::Fast);
241 
242   SetGlobalValueAttributes(FD, F);
243 }
244 
245 void CodeGenModule::EmitObjCMethod(const ObjCMethodDecl *OMD) {
246   // If this is not a prototype, emit the body.
247   if (OMD->getBody())
248     CodeGenFunction(*this).GenerateObjCMethod(OMD);
249 }
250 void CodeGenModule::EmitObjCProtocolImplementation(const ObjCProtocolDecl *PD){
251   Runtime->GenerateProtocol(PD);
252 }
253 
254 void CodeGenModule::EmitObjCCategoryImpl(const ObjCCategoryImplDecl *OCD) {
255   Runtime->GenerateCategory(OCD);
256 }
257 
258 void
259 CodeGenModule::EmitObjCClassImplementation(const ObjCImplementationDecl *OID) {
260   Runtime->GenerateClass(OID);
261 }
262 
263 void CodeGenModule::EmitStatics() {
264   // Emit code for each used static decl encountered.  Since a previously unused
265   // static decl may become used during the generation of code for a static
266   // function, iterate until no changes are made.
267   bool Changed;
268   do {
269     Changed = false;
270     for (unsigned i = 0, e = StaticDecls.size(); i != e; ++i) {
271       const ValueDecl *D = StaticDecls[i];
272 
273       // Check if we have used a decl with the same name
274       // FIXME: The AST should have some sort of aggregate decls or
275       // global symbol map.
276       if (!GlobalDeclMap.count(D->getName()))
277         continue;
278 
279       // Emit the definition.
280       EmitGlobalDefinition(D);
281 
282       // Erase the used decl from the list.
283       StaticDecls[i] = StaticDecls.back();
284       StaticDecls.pop_back();
285       --i;
286       --e;
287 
288       // Remember that we made a change.
289       Changed = true;
290     }
291   } while (Changed);
292 }
293 
294 /// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
295 /// annotation information for a given GlobalValue.  The annotation struct is
296 /// {i8 *, i8 *, i8 *, i32}.  The first field is a constant expression, the
297 /// GlobalValue being annotated.  The second field is the constant string
298 /// created from the AnnotateAttr's annotation.  The third field is a constant
299 /// string containing the name of the translation unit.  The fourth field is
300 /// the line number in the file of the annotated value declaration.
301 ///
302 /// FIXME: this does not unique the annotation string constants, as llvm-gcc
303 ///        appears to.
304 ///
305 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
306                                                 const AnnotateAttr *AA,
307                                                 unsigned LineNo) {
308   llvm::Module *M = &getModule();
309 
310   // get [N x i8] constants for the annotation string, and the filename string
311   // which are the 2nd and 3rd elements of the global annotation structure.
312   const llvm::Type *SBP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
313   llvm::Constant *anno = llvm::ConstantArray::get(AA->getAnnotation(), true);
314   llvm::Constant *unit = llvm::ConstantArray::get(M->getModuleIdentifier(),
315                                                   true);
316 
317   // Get the two global values corresponding to the ConstantArrays we just
318   // created to hold the bytes of the strings.
319   llvm::GlobalValue *annoGV =
320   new llvm::GlobalVariable(anno->getType(), false,
321                            llvm::GlobalValue::InternalLinkage, anno,
322                            GV->getName() + ".str", M);
323   // translation unit name string, emitted into the llvm.metadata section.
324   llvm::GlobalValue *unitGV =
325   new llvm::GlobalVariable(unit->getType(), false,
326                            llvm::GlobalValue::InternalLinkage, unit, ".str", M);
327 
328   // Create the ConstantStruct that is the global annotion.
329   llvm::Constant *Fields[4] = {
330     llvm::ConstantExpr::getBitCast(GV, SBP),
331     llvm::ConstantExpr::getBitCast(annoGV, SBP),
332     llvm::ConstantExpr::getBitCast(unitGV, SBP),
333     llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo)
334   };
335   return llvm::ConstantStruct::get(Fields, 4, false);
336 }
337 
338 void CodeGenModule::EmitGlobal(const ValueDecl *Global) {
339   bool isDef, isStatic;
340 
341   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
342     isDef = (FD->isThisDeclarationADefinition() ||
343              FD->getAttr<AliasAttr>());
344     isStatic = FD->getStorageClass() == FunctionDecl::Static;
345   } else if (const VarDecl *VD = cast<VarDecl>(Global)) {
346     assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
347 
348     isDef = !(VD->getStorageClass() == VarDecl::Extern && VD->getInit() == 0);
349     isStatic = VD->getStorageClass() == VarDecl::Static;
350   } else {
351     assert(0 && "Invalid argument to EmitGlobal");
352     return;
353   }
354 
355   // Forward declarations are emitted lazily on first use.
356   if (!isDef)
357     return;
358 
359   // If the global is a static, defer code generation until later so
360   // we can easily omit unused statics.
361   if (isStatic) {
362     StaticDecls.push_back(Global);
363     return;
364   }
365 
366   // Otherwise emit the definition.
367   EmitGlobalDefinition(Global);
368 }
369 
370 void CodeGenModule::EmitGlobalDefinition(const ValueDecl *D) {
371   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
372     EmitGlobalFunctionDefinition(FD);
373   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
374     EmitGlobalVarDefinition(VD);
375   } else {
376     assert(0 && "Invalid argument to EmitGlobalDefinition()");
377   }
378 }
379 
380  llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D) {
381   assert(D->hasGlobalStorage() && "Not a global variable");
382 
383   QualType ASTTy = D->getType();
384   const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
385   const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
386 
387   // Lookup the entry, lazily creating it if necessary.
388   llvm::GlobalValue *&Entry = GlobalDeclMap[D->getName()];
389   if (!Entry)
390     Entry = new llvm::GlobalVariable(Ty, false,
391                                      llvm::GlobalValue::ExternalLinkage,
392                                      0, D->getName(), &getModule(), 0,
393                                      ASTTy.getAddressSpace());
394 
395   // Make sure the result is of the correct type.
396   return llvm::ConstantExpr::getBitCast(Entry, PTy);
397 }
398 
399 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
400   llvm::Constant *Init = 0;
401   QualType ASTTy = D->getType();
402   const llvm::Type *VarTy = getTypes().ConvertTypeForMem(ASTTy);
403 
404   if (D->getInit() == 0) {
405     // This is a tentative definition; tentative definitions are
406     // implicitly initialized with { 0 }
407     const llvm::Type* InitTy;
408     if (ASTTy->isIncompleteArrayType()) {
409       // An incomplete array is normally [ TYPE x 0 ], but we need
410       // to fix it to [ TYPE x 1 ].
411       const llvm::ArrayType* ATy = cast<llvm::ArrayType>(VarTy);
412       InitTy = llvm::ArrayType::get(ATy->getElementType(), 1);
413     } else {
414       InitTy = VarTy;
415     }
416     Init = llvm::Constant::getNullValue(InitTy);
417   } else {
418     Init = EmitConstantExpr(D->getInit());
419   }
420   const llvm::Type* InitType = Init->getType();
421 
422   llvm::GlobalValue *&Entry = GlobalDeclMap[D->getName()];
423   llvm::GlobalVariable *GV = cast_or_null<llvm::GlobalVariable>(Entry);
424 
425   if (!GV) {
426     GV = new llvm::GlobalVariable(InitType, false,
427                                   llvm::GlobalValue::ExternalLinkage,
428                                   0, D->getName(), &getModule(), 0,
429                                   ASTTy.getAddressSpace());
430   } else if (GV->getType() !=
431              llvm::PointerType::get(InitType, ASTTy.getAddressSpace())) {
432     // We have a definition after a prototype with the wrong type.
433     // We must make a new GlobalVariable* and update everything that used OldGV
434     // (a declaration or tentative definition) with the new GlobalVariable*
435     // (which will be a definition).
436     //
437     // This happens if there is a prototype for a global (e.g. "extern int x[];")
438     // and then a definition of a different type (e.g. "int x[10];"). This also
439     // happens when an initializer has a different type from the type of the
440     // global (this happens with unions).
441     //
442     // FIXME: This also ends up happening if there's a definition followed by
443     // a tentative definition!  (Although Sema rejects that construct
444     // at the moment.)
445 
446     // Save the old global
447     llvm::GlobalVariable *OldGV = GV;
448 
449     // Make a new global with the correct type
450     GV = new llvm::GlobalVariable(InitType, false,
451                                   llvm::GlobalValue::ExternalLinkage,
452                                   0, D->getName(), &getModule(), 0,
453                                   ASTTy.getAddressSpace());
454     // Steal the name of the old global
455     GV->takeName(OldGV);
456 
457     // Replace all uses of the old global with the new global
458     llvm::Constant *NewPtrForOldDecl =
459         llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
460     OldGV->replaceAllUsesWith(NewPtrForOldDecl);
461 
462     // Erase the old global, since it is no longer used.
463     OldGV->eraseFromParent();
464   }
465 
466   Entry = GV;
467 
468   if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
469     SourceManager &SM = Context.getSourceManager();
470     AddAnnotation(EmitAnnotateAttr(GV, AA,
471                                    SM.getLogicalLineNumber(D->getLocation())));
472   }
473 
474   GV->setInitializer(Init);
475 
476   // FIXME: This is silly; getTypeAlign should just work for incomplete arrays
477   unsigned Align;
478   if (const IncompleteArrayType* IAT =
479         Context.getAsIncompleteArrayType(D->getType()))
480     Align = Context.getTypeAlign(IAT->getElementType());
481   else
482     Align = Context.getTypeAlign(D->getType());
483   if (const AlignedAttr* AA = D->getAttr<AlignedAttr>()) {
484     Align = std::max(Align, AA->getAlignment());
485   }
486   GV->setAlignment(Align / 8);
487 
488   if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
489     setVisibility(GV, attr->getVisibility());
490   // FIXME: else handle -fvisibility
491 
492   if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
493     // Prefaced with special LLVM marker to indicate that the name
494     // should not be munged.
495     GV->setName("\01" + ALA->getLabel());
496   }
497 
498   // Set the llvm linkage type as appropriate.
499   if (D->getStorageClass() == VarDecl::Static)
500     GV->setLinkage(llvm::Function::InternalLinkage);
501   else if (D->getAttr<DLLImportAttr>())
502     GV->setLinkage(llvm::Function::DLLImportLinkage);
503   else if (D->getAttr<DLLExportAttr>())
504     GV->setLinkage(llvm::Function::DLLExportLinkage);
505   else if (D->getAttr<WeakAttr>())
506     GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
507   else {
508     // FIXME: This isn't right.  This should handle common linkage and other
509     // stuff.
510     switch (D->getStorageClass()) {
511     case VarDecl::Static: assert(0 && "This case handled above");
512     case VarDecl::Auto:
513     case VarDecl::Register:
514       assert(0 && "Can't have auto or register globals");
515     case VarDecl::None:
516       if (!D->getInit())
517         GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
518       break;
519     case VarDecl::Extern:
520     case VarDecl::PrivateExtern:
521       // todo: common
522       break;
523     }
524   }
525 
526   // Emit global variable debug information.
527   CGDebugInfo *DI = getDebugInfo();
528   if(DI) {
529     if(D->getLocation().isValid())
530       DI->setLocation(D->getLocation());
531     DI->EmitGlobalVariable(GV, D);
532   }
533 }
534 
535 llvm::GlobalValue *
536 CodeGenModule::EmitForwardFunctionDefinition(const FunctionDecl *D) {
537   // FIXME: param attributes for sext/zext etc.
538   if (const AliasAttr *AA = D->getAttr<AliasAttr>()) {
539     assert(!D->getBody() && "Unexpected alias attr on function with body.");
540 
541     const std::string& aliaseeName = AA->getAliasee();
542     llvm::Function *aliasee = getModule().getFunction(aliaseeName);
543     llvm::GlobalValue *alias = new llvm::GlobalAlias(aliasee->getType(),
544                                               llvm::Function::ExternalLinkage,
545                                                      D->getName(),
546                                                      aliasee,
547                                                      &getModule());
548     SetGlobalValueAttributes(D, alias);
549     return alias;
550   } else {
551     const llvm::Type *Ty = getTypes().ConvertType(D->getType());
552     const llvm::FunctionType *FTy = cast<llvm::FunctionType>(Ty);
553     llvm::Function *F = llvm::Function::Create(FTy,
554                                                llvm::Function::ExternalLinkage,
555                                                D->getName(), &getModule());
556 
557     SetFunctionAttributes(D, F, FTy);
558     return F;
559   }
560 }
561 
562 llvm::Constant *CodeGenModule::GetAddrOfFunction(const FunctionDecl *D) {
563   QualType ASTTy = D->getType();
564   const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
565   const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
566 
567   // Lookup the entry, lazily creating it if necessary.
568   llvm::GlobalValue *&Entry = GlobalDeclMap[D->getName()];
569   if (!Entry)
570     Entry = EmitForwardFunctionDefinition(D);
571 
572   return llvm::ConstantExpr::getBitCast(Entry, PTy);
573 }
574 
575 void CodeGenModule::EmitGlobalFunctionDefinition(const FunctionDecl *D) {
576   llvm::GlobalValue *&Entry = GlobalDeclMap[D->getName()];
577   if (!Entry) {
578     Entry = EmitForwardFunctionDefinition(D);
579   } else {
580     // If the types mismatch then we have to rewrite the definition.
581     const llvm::Type *Ty = getTypes().ConvertType(D->getType());
582     if (Entry->getType() != llvm::PointerType::getUnqual(Ty)) {
583       // Otherwise, we have a definition after a prototype with the wrong type.
584       // F is the Function* for the one with the wrong type, we must make a new
585       // Function* and update everything that used F (a declaration) with the new
586       // Function* (which will be a definition).
587       //
588       // This happens if there is a prototype for a function (e.g. "int f()") and
589       // then a definition of a different type (e.g. "int f(int x)").  Start by
590       // making a new function of the correct type, RAUW, then steal the name.
591       llvm::GlobalValue *NewFn = EmitForwardFunctionDefinition(D);
592       NewFn->takeName(Entry);
593 
594       // Replace uses of F with the Function we will endow with a body.
595       llvm::Constant *NewPtrForOldDecl =
596         llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
597       Entry->replaceAllUsesWith(NewPtrForOldDecl);
598 
599       // Ok, delete the old function now, which is dead.
600       // FIXME: Add GlobalValue->eraseFromParent().
601       assert(Entry->isDeclaration() && "Shouldn't replace non-declaration");
602       if (llvm::Function *F = dyn_cast<llvm::Function>(Entry)) {
603         F->eraseFromParent();
604       } else if (llvm::GlobalAlias *GA = dyn_cast<llvm::GlobalAlias>(Entry)) {
605         GA->eraseFromParent();
606       } else {
607         assert(0 && "Invalid global variable type.");
608       }
609 
610       Entry = NewFn;
611     }
612   }
613 
614   if (D->getAttr<AliasAttr>()) {
615     ;
616   } else {
617     llvm::Function *Fn = cast<llvm::Function>(Entry);
618     CodeGenFunction(*this).GenerateCode(D, Fn);
619 
620     // Set attributes specific to definition.
621     // FIXME: This needs to be cleaned up by clearly emitting the
622     // declaration / definition at separate times.
623     if (!Features.Exceptions)
624       Fn->addParamAttr(0, llvm::ParamAttr::NoUnwind);
625 
626     if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) {
627       AddGlobalCtor(Fn, CA->getPriority());
628     } else if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) {
629       AddGlobalDtor(Fn, DA->getPriority());
630     }
631   }
632 }
633 
634 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
635   // Make sure that this type is translated.
636   Types.UpdateCompletedType(TD);
637 }
638 
639 
640 /// getBuiltinLibFunction
641 llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
642   if (BuiltinID > BuiltinFunctions.size())
643     BuiltinFunctions.resize(BuiltinID);
644 
645   // Cache looked up functions.  Since builtin id #0 is invalid we don't reserve
646   // a slot for it.
647   assert(BuiltinID && "Invalid Builtin ID");
648   llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID-1];
649   if (FunctionSlot)
650     return FunctionSlot;
651 
652   assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn");
653 
654   // Get the name, skip over the __builtin_ prefix.
655   const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10;
656 
657   // Get the type for the builtin.
658   QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context);
659   const llvm::FunctionType *Ty =
660     cast<llvm::FunctionType>(getTypes().ConvertType(Type));
661 
662   // FIXME: This has a serious problem with code like this:
663   //  void abs() {}
664   //    ... __builtin_abs(x);
665   // The two versions of abs will collide.  The fix is for the builtin to win,
666   // and for the existing one to be turned into a constantexpr cast of the
667   // builtin.  In the case where the existing one is a static function, it
668   // should just be renamed.
669   if (llvm::Function *Existing = getModule().getFunction(Name)) {
670     if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
671       return FunctionSlot = Existing;
672     assert(Existing == 0 && "FIXME: Name collision");
673   }
674 
675   // FIXME: param attributes for sext/zext etc.
676   return FunctionSlot =
677     llvm::Function::Create(Ty, llvm::Function::ExternalLinkage, Name,
678                            &getModule());
679 }
680 
681 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
682                                             unsigned NumTys) {
683   return llvm::Intrinsic::getDeclaration(&getModule(),
684                                          (llvm::Intrinsic::ID)IID, Tys, NumTys);
685 }
686 
687 llvm::Function *CodeGenModule::getMemCpyFn() {
688   if (MemCpyFn) return MemCpyFn;
689   llvm::Intrinsic::ID IID;
690   switch (Context.Target.getPointerWidth(0)) {
691   default: assert(0 && "Unknown ptr width");
692   case 32: IID = llvm::Intrinsic::memcpy_i32; break;
693   case 64: IID = llvm::Intrinsic::memcpy_i64; break;
694   }
695   return MemCpyFn = getIntrinsic(IID);
696 }
697 
698 llvm::Function *CodeGenModule::getMemMoveFn() {
699   if (MemMoveFn) return MemMoveFn;
700   llvm::Intrinsic::ID IID;
701   switch (Context.Target.getPointerWidth(0)) {
702   default: assert(0 && "Unknown ptr width");
703   case 32: IID = llvm::Intrinsic::memmove_i32; break;
704   case 64: IID = llvm::Intrinsic::memmove_i64; break;
705   }
706   return MemMoveFn = getIntrinsic(IID);
707 }
708 
709 llvm::Function *CodeGenModule::getMemSetFn() {
710   if (MemSetFn) return MemSetFn;
711   llvm::Intrinsic::ID IID;
712   switch (Context.Target.getPointerWidth(0)) {
713   default: assert(0 && "Unknown ptr width");
714   case 32: IID = llvm::Intrinsic::memset_i32; break;
715   case 64: IID = llvm::Intrinsic::memset_i64; break;
716   }
717   return MemSetFn = getIntrinsic(IID);
718 }
719 
720 // FIXME: This needs moving into an Apple Objective-C runtime class
721 llvm::Constant *CodeGenModule::
722 GetAddrOfConstantCFString(const std::string &str) {
723   llvm::StringMapEntry<llvm::Constant *> &Entry =
724     CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
725 
726   if (Entry.getValue())
727     return Entry.getValue();
728 
729   std::vector<llvm::Constant*> Fields;
730 
731   if (!CFConstantStringClassRef) {
732     const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
733     Ty = llvm::ArrayType::get(Ty, 0);
734 
735     CFConstantStringClassRef =
736       new llvm::GlobalVariable(Ty, false,
737                                llvm::GlobalVariable::ExternalLinkage, 0,
738                                "__CFConstantStringClassReference",
739                                &getModule());
740   }
741 
742   // Class pointer.
743   llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
744   llvm::Constant *Zeros[] = { Zero, Zero };
745   llvm::Constant *C =
746     llvm::ConstantExpr::getGetElementPtr(CFConstantStringClassRef, Zeros, 2);
747   Fields.push_back(C);
748 
749   // Flags.
750   const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
751   Fields.push_back(llvm::ConstantInt::get(Ty, 1992));
752 
753   // String pointer.
754   C = llvm::ConstantArray::get(str);
755   C = new llvm::GlobalVariable(C->getType(), true,
756                                llvm::GlobalValue::InternalLinkage,
757                                C, ".str", &getModule());
758 
759   C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
760   Fields.push_back(C);
761 
762   // String length.
763   Ty = getTypes().ConvertType(getContext().LongTy);
764   Fields.push_back(llvm::ConstantInt::get(Ty, str.length()));
765 
766   // The struct.
767   Ty = getTypes().ConvertType(getContext().getCFConstantStringType());
768   C = llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Fields);
769   llvm::GlobalVariable *GV =
770     new llvm::GlobalVariable(C->getType(), true,
771                              llvm::GlobalVariable::InternalLinkage,
772                              C, "", &getModule());
773   GV->setSection("__DATA,__cfstring");
774   Entry.setValue(GV);
775   return GV;
776 }
777 
778 /// GetStringForStringLiteral - Return the appropriate bytes for a
779 /// string literal, properly padded to match the literal type.
780 std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
781   assert(!E->isWide() && "FIXME: Wide strings not supported yet!");
782   const char *StrData = E->getStrData();
783   unsigned Len = E->getByteLength();
784 
785   const ConstantArrayType *CAT =
786     getContext().getAsConstantArrayType(E->getType());
787   assert(CAT && "String isn't pointer or array!");
788 
789   // Resize the string to the right size
790   // FIXME: What about wchar_t strings?
791   std::string Str(StrData, StrData+Len);
792   uint64_t RealLen = CAT->getSize().getZExtValue();
793   Str.resize(RealLen, '\0');
794 
795   return Str;
796 }
797 
798 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
799 /// constant array for the given string literal.
800 llvm::Constant *
801 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
802   // FIXME: This can be more efficient.
803   return GetAddrOfConstantString(GetStringForStringLiteral(S));
804 }
805 
806 /// GenerateWritableString -- Creates storage for a string literal.
807 static llvm::Constant *GenerateStringLiteral(const std::string &str,
808                                              bool constant,
809                                              CodeGenModule &CGM) {
810   // Create Constant for this string literal. Don't add a '\0'.
811   llvm::Constant *C = llvm::ConstantArray::get(str, false);
812 
813   // Create a global variable for this string
814   C = new llvm::GlobalVariable(C->getType(), constant,
815                                llvm::GlobalValue::InternalLinkage,
816                                C, ".str", &CGM.getModule());
817 
818   return C;
819 }
820 
821 /// GetAddrOfConstantString - Returns a pointer to a character array
822 /// containing the literal. This contents are exactly that of the
823 /// given string, i.e. it will not be null terminated automatically;
824 /// see GetAddrOfConstantCString. Note that whether the result is
825 /// actually a pointer to an LLVM constant depends on
826 /// Feature.WriteableStrings.
827 ///
828 /// The result has pointer to array type.
829 llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str) {
830   // Don't share any string literals if writable-strings is turned on.
831   if (Features.WritableStrings)
832     return GenerateStringLiteral(str, false, *this);
833 
834   llvm::StringMapEntry<llvm::Constant *> &Entry =
835   ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
836 
837   if (Entry.getValue())
838       return Entry.getValue();
839 
840   // Create a global variable for this.
841   llvm::Constant *C = GenerateStringLiteral(str, true, *this);
842   Entry.setValue(C);
843   return C;
844 }
845 
846 /// GetAddrOfConstantCString - Returns a pointer to a character
847 /// array containing the literal and a terminating '\-'
848 /// character. The result has pointer to array type.
849 llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str) {
850   return GetAddrOfConstantString(str + "\0");
851 }
852