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