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