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