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