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 "clang/AST/ASTContext.h"
18 #include "clang/AST/Decl.h"
19 #include "clang/Basic/Diagnostic.h"
20 #include "clang/Basic/LangOptions.h"
21 #include "clang/Basic/SourceManager.h"
22 #include "clang/Basic/TargetInfo.h"
23 #include "llvm/CallingConv.h"
24 #include "llvm/Constants.h"
25 #include "llvm/DerivedTypes.h"
26 #include "llvm/Module.h"
27 #include "llvm/Intrinsics.h"
28 #include "llvm/Target/TargetData.h"
29 #include "llvm/Analysis/Verifier.h"
30 #include <algorithm>
31 using namespace clang;
32 using namespace CodeGen;
33 
34 
35 CodeGenModule::CodeGenModule(ASTContext &C, const LangOptions &LO,
36                              llvm::Module &M, const llvm::TargetData &TD,
37                              Diagnostic &diags, bool GenerateDebugInfo)
38   : Context(C), Features(LO), TheModule(M), TheTargetData(TD), Diags(diags),
39     Types(C, M, TD), MemCpyFn(0), MemMoveFn(0), MemSetFn(0),
40     CFConstantStringClassRef(0) {
41   //TODO: Make this selectable at runtime
42   Runtime = CreateObjCRuntime(*this);
43 
44   // If debug info generation is enabled, create the CGDebugInfo object.
45   if (GenerateDebugInfo)
46     DebugInfo = new CGDebugInfo(this);
47   else
48     DebugInfo = NULL;
49 }
50 
51 CodeGenModule::~CodeGenModule() {
52   EmitStatics();
53   llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction();
54   if (ObjCInitFunction)
55     AddGlobalCtor(ObjCInitFunction);
56   EmitGlobalCtors();
57   EmitAnnotations();
58   delete Runtime;
59   delete DebugInfo;
60   // Run the verifier to check that the generated code is consistent.
61   assert(!verifyModule(TheModule));
62 }
63 
64 /// WarnUnsupported - Print out a warning that codegen doesn't support the
65 /// specified stmt yet.
66 void CodeGenModule::WarnUnsupported(const Stmt *S, const char *Type) {
67   unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Warning,
68                                                "cannot codegen this %0 yet");
69   SourceRange Range = S->getSourceRange();
70   std::string Msg = Type;
71   getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID,
72                     &Msg, 1, &Range, 1);
73 }
74 
75 /// WarnUnsupported - Print out a warning that codegen doesn't support the
76 /// specified decl yet.
77 void CodeGenModule::WarnUnsupported(const Decl *D, const char *Type) {
78   unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Warning,
79                                                "cannot codegen this %0 yet");
80   std::string Msg = Type;
81   getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID,
82                     &Msg, 1);
83 }
84 
85 /// setVisibility - Set the visibility for the given LLVM GlobalValue
86 /// according to the given clang AST visibility value.
87 void CodeGenModule::setVisibility(llvm::GlobalValue *GV,
88                                   VisibilityAttr::VisibilityTypes Vis) {
89   switch (Vis) {
90   default: assert(0 && "Unknown visibility!");
91   case VisibilityAttr::DefaultVisibility:
92     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
93     break;
94   case VisibilityAttr::HiddenVisibility:
95     GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
96     break;
97   case VisibilityAttr::ProtectedVisibility:
98     GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
99     break;
100   }
101 }
102 
103 /// AddGlobalCtor - Add a function to the list that will be called before
104 /// main() runs.
105 void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor) {
106   // TODO: Type coercion of void()* types.
107   GlobalCtors.push_back(Ctor);
108 }
109 
110 /// EmitGlobalCtors - Generates the array of contsturctor functions to be
111 /// called on module load, if any have been registered with AddGlobalCtor.
112 void CodeGenModule::EmitGlobalCtors() {
113   if (GlobalCtors.empty()) return;
114 
115   // Get the type of @llvm.global_ctors
116   std::vector<const llvm::Type*> CtorFields;
117   CtorFields.push_back(llvm::IntegerType::get(32));
118   // Constructor function type
119   std::vector<const llvm::Type*> VoidArgs;
120   llvm::FunctionType* CtorFuncTy =
121     llvm::FunctionType::get(llvm::Type::VoidTy, VoidArgs, false);
122 
123   // i32, function type pair
124   const llvm::Type *FPType = llvm::PointerType::getUnqual(CtorFuncTy);
125   llvm::StructType* CtorStructTy =
126   llvm::StructType::get(llvm::Type::Int32Ty, FPType, NULL);
127   // Array of fields
128   llvm::ArrayType* GlobalCtorsTy =
129     llvm::ArrayType::get(CtorStructTy, GlobalCtors.size());
130 
131   // Define the global variable
132   llvm::GlobalVariable *GlobalCtorsVal =
133     new llvm::GlobalVariable(GlobalCtorsTy, false,
134                              llvm::GlobalValue::AppendingLinkage,
135                              (llvm::Constant*)0, "llvm.global_ctors",
136                              &TheModule);
137 
138   // Populate the array
139   std::vector<llvm::Constant*> CtorValues;
140   llvm::Constant *MagicNumber =
141     llvm::ConstantInt::get(llvm::Type::Int32Ty, 65535, false);
142   std::vector<llvm::Constant*> StructValues;
143   for (std::vector<llvm::Constant*>::iterator I = GlobalCtors.begin(),
144        E = GlobalCtors.end(); I != E; ++I) {
145     StructValues.clear();
146     StructValues.push_back(MagicNumber);
147     StructValues.push_back(*I);
148 
149     CtorValues.push_back(llvm::ConstantStruct::get(CtorStructTy, StructValues));
150   }
151 
152   GlobalCtorsVal->setInitializer(llvm::ConstantArray::get(GlobalCtorsTy,
153                                                           CtorValues));
154 }
155 
156 void CodeGenModule::EmitAnnotations() {
157   if (Annotations.empty())
158     return;
159 
160   // Create a new global variable for the ConstantStruct in the Module.
161   llvm::Constant *Array =
162   llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
163                                                 Annotations.size()),
164                            Annotations);
165   llvm::GlobalValue *gv =
166   new llvm::GlobalVariable(Array->getType(), false,
167                            llvm::GlobalValue::AppendingLinkage, Array,
168                            "llvm.global.annotations", &TheModule);
169   gv->setSection("llvm.metadata");
170 }
171 
172 bool hasAggregateLLVMType(QualType T) {
173   return !T->isRealType() && !T->isPointerLikeType() &&
174          !T->isVoidType() && !T->isVectorType() && !T->isFunctionType();
175 }
176 
177 void CodeGenModule::SetGlobalValueAttributes(const FunctionDecl *FD,
178                                              llvm::GlobalValue *GV) {
179   // TODO: Set up linkage and many other things.  Note, this is a simple
180   // approximation of what we really want.
181   if (FD->getStorageClass() == FunctionDecl::Static)
182     GV->setLinkage(llvm::Function::InternalLinkage);
183   else if (FD->getAttr<DLLImportAttr>())
184     GV->setLinkage(llvm::Function::DLLImportLinkage);
185   else if (FD->getAttr<DLLExportAttr>())
186     GV->setLinkage(llvm::Function::DLLExportLinkage);
187   else if (FD->getAttr<WeakAttr>() || FD->isInline())
188     GV->setLinkage(llvm::Function::WeakLinkage);
189 
190   if (const VisibilityAttr *attr = FD->getAttr<VisibilityAttr>())
191     CodeGenModule::setVisibility(GV, attr->getVisibility());
192   // FIXME: else handle -fvisibility
193 }
194 
195 void CodeGenModule::SetFunctionAttributes(const FunctionDecl *FD,
196                                           llvm::Function *F,
197                                           const llvm::FunctionType *FTy) {
198   unsigned FuncAttrs = 0;
199   if (FD->getAttr<NoThrowAttr>())
200     FuncAttrs |= llvm::ParamAttr::NoUnwind;
201   if (FD->getAttr<NoReturnAttr>())
202     FuncAttrs |= llvm::ParamAttr::NoReturn;
203 
204   llvm::SmallVector<llvm::ParamAttrsWithIndex, 8> ParamAttrList;
205   if (FuncAttrs)
206     ParamAttrList.push_back(llvm::ParamAttrsWithIndex::get(0, FuncAttrs));
207   // Note that there is parallel code in CodeGenFunction::EmitCallExpr
208   bool AggregateReturn = hasAggregateLLVMType(FD->getResultType());
209   if (AggregateReturn)
210     ParamAttrList.push_back(
211         llvm::ParamAttrsWithIndex::get(1, llvm::ParamAttr::StructRet));
212   unsigned increment = AggregateReturn ? 2 : 1;
213   const FunctionTypeProto* FTP = dyn_cast<FunctionTypeProto>(FD->getType());
214   if (FTP) {
215     for (unsigned i = 0; i < FTP->getNumArgs(); i++) {
216       QualType ParamType = FTP->getArgType(i);
217       unsigned ParamAttrs = 0;
218       if (ParamType->isRecordType())
219         ParamAttrs |= llvm::ParamAttr::ByVal;
220       if (ParamType->isSignedIntegerType() &&
221           ParamType->isPromotableIntegerType())
222         ParamAttrs |= llvm::ParamAttr::SExt;
223       if (ParamType->isUnsignedIntegerType() &&
224           ParamType->isPromotableIntegerType())
225         ParamAttrs |= llvm::ParamAttr::ZExt;
226       if (ParamAttrs)
227         ParamAttrList.push_back(llvm::ParamAttrsWithIndex::get(i + increment,
228                                                                ParamAttrs));
229     }
230   }
231 
232   F->setParamAttrs(llvm::PAListPtr::get(ParamAttrList.begin(),
233                                         ParamAttrList.size()));
234 
235   // Set the appropriate calling convention for the Function.
236   if (FD->getAttr<FastCallAttr>())
237     F->setCallingConv(llvm::CallingConv::Fast);
238 
239   SetGlobalValueAttributes(FD, F);
240 }
241 
242 void CodeGenModule::EmitObjCMethod(const ObjCMethodDecl *OMD) {
243   // If this is not a prototype, emit the body.
244   if (OMD->getBody())
245     CodeGenFunction(*this).GenerateObjCMethod(OMD);
246 }
247 void CodeGenModule::EmitObjCProtocolImplementation(const ObjCProtocolDecl *PD){
248   llvm::SmallVector<std::string, 16> Protocols;
249   for (ObjCProtocolDecl::protocol_iterator PI = PD->protocol_begin(),
250        E = PD->protocol_end(); PI != E; ++PI)
251     Protocols.push_back((*PI)->getName());
252   llvm::SmallVector<llvm::Constant*, 16> InstanceMethodNames;
253   llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
254   for (ObjCProtocolDecl::instmeth_iterator iter = PD->instmeth_begin(),
255        E = PD->instmeth_end(); iter != E; iter++) {
256     std::string TypeStr;
257     Context.getObjCEncodingForMethodDecl(*iter, TypeStr);
258     InstanceMethodNames.push_back(
259         GetAddrOfConstantString((*iter)->getSelector().getName()));
260     InstanceMethodTypes.push_back(GetAddrOfConstantString(TypeStr));
261   }
262   // Collect information about class methods:
263   llvm::SmallVector<llvm::Constant*, 16> ClassMethodNames;
264   llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
265   for (ObjCProtocolDecl::classmeth_iterator iter = PD->classmeth_begin(),
266       endIter = PD->classmeth_end() ; iter != endIter ; iter++) {
267     std::string TypeStr;
268     Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
269     ClassMethodNames.push_back(
270         GetAddrOfConstantString((*iter)->getSelector().getName()));
271     ClassMethodTypes.push_back(GetAddrOfConstantString(TypeStr));
272   }
273   Runtime->GenerateProtocol(PD->getName(), Protocols, InstanceMethodNames,
274       InstanceMethodTypes, ClassMethodNames, ClassMethodTypes);
275 }
276 
277 void CodeGenModule::EmitObjCCategoryImpl(const ObjCCategoryImplDecl *OCD) {
278 
279   // Collect information about instance methods
280   llvm::SmallVector<Selector, 16> InstanceMethodSels;
281   llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
282   for (ObjCCategoryDecl::instmeth_iterator iter = OCD->instmeth_begin(),
283       endIter = OCD->instmeth_end() ; iter != endIter ; iter++) {
284     InstanceMethodSels.push_back((*iter)->getSelector());
285     std::string TypeStr;
286     Context.getObjCEncodingForMethodDecl(*iter,TypeStr);
287     InstanceMethodTypes.push_back(GetAddrOfConstantString(TypeStr));
288   }
289 
290   // Collect information about class methods
291   llvm::SmallVector<Selector, 16> ClassMethodSels;
292   llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
293   for (ObjCCategoryDecl::classmeth_iterator iter = OCD->classmeth_begin(),
294       endIter = OCD->classmeth_end() ; iter != endIter ; iter++) {
295     ClassMethodSels.push_back((*iter)->getSelector());
296     std::string TypeStr;
297     Context.getObjCEncodingForMethodDecl(*iter,TypeStr);
298     ClassMethodTypes.push_back(GetAddrOfConstantString(TypeStr));
299   }
300 
301   // Collect the names of referenced protocols
302   llvm::SmallVector<std::string, 16> Protocols;
303   const ObjCInterfaceDecl *ClassDecl = OCD->getClassInterface();
304   const ObjCList<ObjCProtocolDecl> &Protos =ClassDecl->getReferencedProtocols();
305   for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
306        E = Protos.end(); I != E; ++I)
307     Protocols.push_back((*I)->getName());
308 
309   // Generate the category
310   Runtime->GenerateCategory(OCD->getClassInterface()->getName(),
311       OCD->getName(), InstanceMethodSels, InstanceMethodTypes,
312       ClassMethodSels, ClassMethodTypes, Protocols);
313 }
314 
315 void CodeGenModule::EmitObjCClassImplementation(
316     const ObjCImplementationDecl *OID) {
317   // Get the superclass name.
318   const ObjCInterfaceDecl * SCDecl = OID->getClassInterface()->getSuperClass();
319   const char * SCName = NULL;
320   if (SCDecl) {
321     SCName = SCDecl->getName();
322   }
323 
324   // Get the class name
325   ObjCInterfaceDecl * ClassDecl = (ObjCInterfaceDecl*)OID->getClassInterface();
326   const char * ClassName = ClassDecl->getName();
327 
328   // Get the size of instances.  For runtimes that support late-bound instances
329   // this should probably be something different (size just of instance
330   // varaibles in this class, not superclasses?).
331   int instanceSize = 0;
332   const llvm::Type *ObjTy;
333   if (!Runtime->LateBoundIVars()) {
334     ObjTy = getTypes().ConvertType(Context.getObjCInterfaceType(ClassDecl));
335     instanceSize = TheTargetData.getABITypeSize(ObjTy);
336   }
337 
338   // Collect information about instance variables.
339   llvm::SmallVector<llvm::Constant*, 16> IvarNames;
340   llvm::SmallVector<llvm::Constant*, 16> IvarTypes;
341   llvm::SmallVector<llvm::Constant*, 16> IvarOffsets;
342   const llvm::StructLayout *Layout =
343     TheTargetData.getStructLayout(cast<llvm::StructType>(ObjTy));
344   ObjTy = llvm::PointerType::getUnqual(ObjTy);
345   for (ObjCInterfaceDecl::ivar_iterator iter = ClassDecl->ivar_begin(),
346       endIter = ClassDecl->ivar_end() ; iter != endIter ; iter++) {
347       // Store the name
348       IvarNames.push_back(GetAddrOfConstantString((*iter)->getName()));
349       // Get the type encoding for this ivar
350       std::string TypeStr;
351       llvm::SmallVector<const RecordType *, 8> EncodingRecordTypes;
352       Context.getObjCEncodingForType((*iter)->getType(), TypeStr,
353                                      EncodingRecordTypes);
354       IvarTypes.push_back(GetAddrOfConstantString(TypeStr));
355       // Get the offset
356       int offset =
357         (int)Layout->getElementOffset(getTypes().getLLVMFieldNo(*iter));
358       IvarOffsets.push_back(
359           llvm::ConstantInt::get(llvm::Type::Int32Ty, offset));
360   }
361 
362   // Collect information about instance methods
363   llvm::SmallVector<Selector, 16> InstanceMethodSels;
364   llvm::SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
365   for (ObjCImplementationDecl::instmeth_iterator iter = OID->instmeth_begin(),
366       endIter = OID->instmeth_end() ; iter != endIter ; iter++) {
367     InstanceMethodSels.push_back((*iter)->getSelector());
368     std::string TypeStr;
369     Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
370     InstanceMethodTypes.push_back(GetAddrOfConstantString(TypeStr));
371   }
372 
373   // Collect information about class methods
374   llvm::SmallVector<Selector, 16> ClassMethodSels;
375   llvm::SmallVector<llvm::Constant*, 16> ClassMethodTypes;
376   for (ObjCImplementationDecl::classmeth_iterator iter = OID->classmeth_begin(),
377       endIter = OID->classmeth_end() ; iter != endIter ; iter++) {
378     ClassMethodSels.push_back((*iter)->getSelector());
379     std::string TypeStr;
380     Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
381     ClassMethodTypes.push_back(GetAddrOfConstantString(TypeStr));
382   }
383   // Collect the names of referenced protocols
384   llvm::SmallVector<std::string, 16> Protocols;
385   const ObjCList<ObjCProtocolDecl> &Protos =ClassDecl->getReferencedProtocols();
386   for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
387        E = Protos.end(); I != E; ++I)
388     Protocols.push_back((*I)->getName());
389 
390   // Generate the category
391   Runtime->GenerateClass(ClassName, SCName, instanceSize, IvarNames, IvarTypes,
392                          IvarOffsets, InstanceMethodSels, InstanceMethodTypes,
393                          ClassMethodSels, ClassMethodTypes, Protocols);
394 }
395 
396 void CodeGenModule::EmitStatics() {
397   // Emit code for each used static decl encountered.  Since a previously unused
398   // static decl may become used during the generation of code for a static
399   // function, iterate until no changes are made.
400   bool Changed;
401   do {
402     Changed = false;
403     for (unsigned i = 0, e = StaticDecls.size(); i != e; ++i) {
404       const ValueDecl *D = StaticDecls[i];
405 
406       // Check if we have used a decl with the same name
407       // FIXME: The AST should have some sort of aggregate decls or
408       // global symbol map.
409       if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
410         if (!getModule().getFunction(FD->getName()))
411           continue;
412       } else {
413         if (!getModule().getNamedGlobal(cast<VarDecl>(D)->getName()))
414           continue;
415       }
416 
417       // Emit the definition.
418       EmitGlobalDefinition(D);
419 
420       // Erase the used decl from the list.
421       StaticDecls[i] = StaticDecls.back();
422       StaticDecls.pop_back();
423       --i;
424       --e;
425 
426       // Remember that we made a change.
427       Changed = true;
428     }
429   } while (Changed);
430 }
431 
432 /// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
433 /// annotation information for a given GlobalValue.  The annotation struct is
434 /// {i8 *, i8 *, i8 *, i32}.  The first field is a constant expression, the
435 /// GlobalValue being annotated.  The second filed is thee constant string
436 /// created from the AnnotateAttr's annotation.  The third field is a constant
437 /// string containing the name of the translation unit.  The fourth field is
438 /// the line number in the file of the annotated value declaration.
439 ///
440 /// FIXME: this does not unique the annotation string constants, as llvm-gcc
441 ///        appears to.
442 ///
443 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
444                                                 const AnnotateAttr *AA,
445                                                 unsigned LineNo) {
446   llvm::Module *M = &getModule();
447 
448   // get [N x i8] constants for the annotation string, and the filename string
449   // which are the 2nd and 3rd elements of the global annotation structure.
450   const llvm::Type *SBP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
451   llvm::Constant *anno = llvm::ConstantArray::get(AA->getAnnotation(), true);
452   llvm::Constant *unit = llvm::ConstantArray::get(M->getModuleIdentifier(),
453                                                   true);
454 
455   // Get the two global values corresponding to the ConstantArrays we just
456   // created to hold the bytes of the strings.
457   llvm::GlobalValue *annoGV =
458   new llvm::GlobalVariable(anno->getType(), false,
459                            llvm::GlobalValue::InternalLinkage, anno,
460                            GV->getName() + ".str", M);
461   // translation unit name string, emitted into the llvm.metadata section.
462   llvm::GlobalValue *unitGV =
463   new llvm::GlobalVariable(unit->getType(), false,
464                            llvm::GlobalValue::InternalLinkage, unit, ".str", M);
465 
466   // Create the ConstantStruct that is the global annotion.
467   llvm::Constant *Fields[4] = {
468     llvm::ConstantExpr::getBitCast(GV, SBP),
469     llvm::ConstantExpr::getBitCast(annoGV, SBP),
470     llvm::ConstantExpr::getBitCast(unitGV, SBP),
471     llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo)
472   };
473   return llvm::ConstantStruct::get(Fields, 4, false);
474 }
475 
476 /// ReplaceMapValuesWith - This is a really slow and bad function that
477 /// searches for any entries in GlobalDeclMap that point to OldVal, changing
478 /// them to point to NewVal.  This is badbadbad, FIXME!
479 void CodeGenModule::ReplaceMapValuesWith(llvm::Constant *OldVal,
480                                          llvm::Constant *NewVal) {
481   for (llvm::DenseMap<const Decl*, llvm::Constant*>::iterator
482        I = GlobalDeclMap.begin(), E = GlobalDeclMap.end(); I != E; ++I)
483     if (I->second == OldVal) I->second = NewVal;
484 }
485 
486 void CodeGenModule::EmitGlobal(const ValueDecl *Global) {
487   bool isDef, isStatic;
488 
489   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
490     isDef = (FD->isThisDeclarationADefinition() ||
491              FD->getAttr<AliasAttr>());
492     isStatic = FD->getStorageClass() == FunctionDecl::Static;
493   } else if (const VarDecl *VD = cast<VarDecl>(Global)) {
494     assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
495 
496     isDef = !(VD->getStorageClass() == VarDecl::Extern && VD->getInit() == 0);
497     isStatic = VD->getStorageClass() == VarDecl::Static;
498   } else {
499     assert(0 && "Invalid argument to EmitGlobal");
500     return;
501   }
502 
503   // Forward declarations are emitted lazily on first use.
504   if (!isDef)
505     return;
506 
507   // If the global is a static, defer code generation until later so
508   // we can easily omit unused statics.
509   if (isStatic) {
510     StaticDecls.push_back(Global);
511     return;
512   }
513 
514   // Otherwise emit the definition.
515   EmitGlobalDefinition(Global);
516 }
517 
518 void CodeGenModule::EmitGlobalDefinition(const ValueDecl *D) {
519   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
520     EmitGlobalFunctionDefinition(FD);
521   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
522     EmitGlobalVarDefinition(VD);
523   } else {
524     assert(0 && "Invalid argument to EmitGlobalDefinition()");
525   }
526 }
527 
528 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D) {
529   assert(D->hasGlobalStorage() && "Not a global variable");
530 
531   // See if it is already in the map.
532   llvm::Constant *&Entry = GlobalDeclMap[D];
533   if (Entry) return Entry;
534 
535   QualType ASTTy = D->getType();
536   const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
537 
538   // Check to see if the global already exists.
539   llvm::GlobalVariable *GV = getModule().getGlobalVariable(D->getName(), true);
540 
541   // If it doesn't already exist, just create and return an entry.
542   if (GV == 0) {
543     return Entry = new llvm::GlobalVariable(Ty, false,
544                                             llvm::GlobalValue::ExternalLinkage,
545                                             0, D->getName(), &getModule(), 0,
546                                             ASTTy.getAddressSpace());
547   }
548 
549   // Otherwise, it already exists; return the existing version
550   llvm::PointerType *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
551   return Entry = llvm::ConstantExpr::getBitCast(GV, PTy);
552 }
553 
554 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
555   llvm::Constant *Init = 0;
556   QualType ASTTy = D->getType();
557   const llvm::Type *VarTy = getTypes().ConvertTypeForMem(ASTTy);
558   const llvm::Type *VarPtrTy =
559       llvm::PointerType::get(VarTy, ASTTy.getAddressSpace());
560 
561   if (D->getInit() == 0) {
562     // This is a tentative definition; tentative definitions are
563     // implicitly initialized with { 0 }
564     const llvm::Type* InitTy;
565     if (ASTTy->isIncompleteArrayType()) {
566       // An incomplete array is normally [ TYPE x 0 ], but we need
567       // to fix it to [ TYPE x 1 ].
568       const llvm::ArrayType* ATy = cast<llvm::ArrayType>(VarTy);
569       InitTy = llvm::ArrayType::get(ATy->getElementType(), 1);
570     } else {
571       InitTy = VarTy;
572     }
573     Init = llvm::Constant::getNullValue(InitTy);
574   } else {
575     Init = EmitConstantExpr(D->getInit());
576   }
577   const llvm::Type* InitType = Init->getType();
578 
579   llvm::GlobalVariable *GV = getModule().getGlobalVariable(D->getName(), true);
580 
581   if (!GV) {
582     GV = new llvm::GlobalVariable(InitType, false,
583                                   llvm::GlobalValue::ExternalLinkage,
584                                   0, D->getName(), &getModule(), 0,
585                                   ASTTy.getAddressSpace());
586   } else if (GV->getType()->getElementType() != InitType ||
587              GV->getType()->getAddressSpace() != ASTTy.getAddressSpace()) {
588     // We have a definition after a prototype with the wrong type.
589     // We must make a new GlobalVariable* and update everything that used OldGV
590     // (a declaration or tentative definition) with the new GlobalVariable*
591     // (which will be a definition).
592     //
593     // This happens if there is a prototype for a global (e.g. "extern int x[];")
594     // and then a definition of a different type (e.g. "int x[10];"). This also
595     // happens when an initializer has a different type from the type of the
596     // global (this happens with unions).
597     //
598     // FIXME: This also ends up happening if there's a definition followed by
599     // a tentative definition!  (Although Sema rejects that construct
600     // at the moment.)
601 
602     // Save the old global
603     llvm::GlobalVariable *OldGV = GV;
604 
605     // Make a new global with the correct type
606     GV = new llvm::GlobalVariable(InitType, false,
607                                   llvm::GlobalValue::ExternalLinkage,
608                                   0, D->getName(), &getModule(), 0,
609                                   ASTTy.getAddressSpace());
610     // Steal the name of the old global
611     GV->takeName(OldGV);
612 
613     // Replace all uses of the old global with the new global
614     llvm::Constant *NewPtrForOldDecl =
615         llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
616     OldGV->replaceAllUsesWith(NewPtrForOldDecl);
617     // Make sure we don't keep around any stale references to globals
618     // FIXME: This is really slow; we need a better way to walk all
619     // the decls with the same name
620     ReplaceMapValuesWith(OldGV, NewPtrForOldDecl);
621 
622     // Erase the old global, since it is no longer used.
623     OldGV->eraseFromParent();
624   }
625 
626   GlobalDeclMap[D] = llvm::ConstantExpr::getBitCast(GV, VarPtrTy);
627 
628   if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
629     SourceManager &SM = Context.getSourceManager();
630     AddAnnotation(EmitAnnotateAttr(GV, AA,
631                                    SM.getLogicalLineNumber(D->getLocation())));
632   }
633 
634   GV->setInitializer(Init);
635 
636   // FIXME: This is silly; getTypeAlign should just work for incomplete arrays
637   unsigned Align;
638   if (const IncompleteArrayType* IAT = D->getType()->getAsIncompleteArrayType())
639     Align = Context.getTypeAlign(IAT->getElementType());
640   else
641     Align = Context.getTypeAlign(D->getType());
642   if (const AlignedAttr* AA = D->getAttr<AlignedAttr>()) {
643     Align = std::max(Align, AA->getAlignment());
644   }
645   GV->setAlignment(Align / 8);
646 
647   if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
648     setVisibility(GV, attr->getVisibility());
649   // FIXME: else handle -fvisibility
650 
651   // Set the llvm linkage type as appropriate.
652   if (D->getStorageClass() == VarDecl::Static)
653     GV->setLinkage(llvm::Function::InternalLinkage);
654   else if (D->getAttr<DLLImportAttr>())
655     GV->setLinkage(llvm::Function::DLLImportLinkage);
656   else if (D->getAttr<DLLExportAttr>())
657     GV->setLinkage(llvm::Function::DLLExportLinkage);
658   else if (D->getAttr<WeakAttr>())
659     GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
660   else {
661     // FIXME: This isn't right.  This should handle common linkage and other
662     // stuff.
663     switch (D->getStorageClass()) {
664     case VarDecl::Static: assert(0 && "This case handled above");
665     case VarDecl::Auto:
666     case VarDecl::Register:
667       assert(0 && "Can't have auto or register globals");
668     case VarDecl::None:
669       if (!D->getInit())
670         GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
671       break;
672     case VarDecl::Extern:
673     case VarDecl::PrivateExtern:
674       // todo: common
675       break;
676     }
677   }
678 
679   // Emit global variable debug information.
680   CGDebugInfo *DI = getDebugInfo();
681   if(DI) {
682     if(D->getLocation().isValid())
683       DI->setLocation(D->getLocation());
684     DI->EmitGlobalVariable(GV, D);
685   }
686 }
687 
688 llvm::GlobalValue *
689 CodeGenModule::EmitForwardFunctionDefinition(const FunctionDecl *D) {
690   // FIXME: param attributes for sext/zext etc.
691   if (const AliasAttr *AA = D->getAttr<AliasAttr>()) {
692     assert(!D->getBody() && "Unexpected alias attr on function with body.");
693 
694     const std::string& aliaseeName = AA->getAliasee();
695     llvm::Function *aliasee = getModule().getFunction(aliaseeName);
696     llvm::GlobalValue *alias = new llvm::GlobalAlias(aliasee->getType(),
697                                               llvm::Function::ExternalLinkage,
698                                                      D->getName(),
699                                                      aliasee,
700                                                      &getModule());
701     SetGlobalValueAttributes(D, alias);
702     return alias;
703   } else {
704     const llvm::Type *Ty = getTypes().ConvertType(D->getType());
705     const llvm::FunctionType *FTy = cast<llvm::FunctionType>(Ty);
706     llvm::Function *F = llvm::Function::Create(FTy,
707                                                llvm::Function::ExternalLinkage,
708                                                D->getName(), &getModule());
709 
710     SetFunctionAttributes(D, F, FTy);
711     return F;
712   }
713 }
714 
715 llvm::Constant *CodeGenModule::GetAddrOfFunction(const FunctionDecl *D) {
716   // See if it is already in the map.  If so, just return it.
717   llvm::Constant *&Entry = GlobalDeclMap[D];
718   if (Entry) return Entry;
719 
720   // Check to see if the function already exists; this occurs when
721   // this decl shadows a previous one. If it exists we bitcast it to
722   // the proper type for this decl and return.
723   llvm::Function *F = getModule().getFunction(D->getName());
724   if (F) {
725     const llvm::Type *Ty = getTypes().ConvertType(D->getType());
726     llvm::Type *PFTy = llvm::PointerType::getUnqual(Ty);
727     return Entry = llvm::ConstantExpr::getBitCast(F, PFTy);
728   }
729 
730   // It doesn't exist; create and return an entry.
731   return Entry = EmitForwardFunctionDefinition(D);
732 }
733 
734 void CodeGenModule::EmitGlobalFunctionDefinition(const FunctionDecl *D) {
735   llvm::Constant *&Entry = GlobalDeclMap[D];
736 
737   const llvm::Type *Ty = getTypes().ConvertType(D->getType());
738   const llvm::FunctionType *FTy = cast<llvm::FunctionType>(Ty);
739 
740   // Check to see if the function already exists.
741   llvm::Function *F = getModule().getFunction(D->getName());
742 
743   // If it doesn't already exist, just create and return an entry.
744   if (F == 0) {
745     Entry = EmitForwardFunctionDefinition(D);
746   } else {
747     // If the pointer type matches, just return it.
748     llvm::Type *PFTy = llvm::PointerType::getUnqual(Ty);
749     if (PFTy == F->getType()) {
750       Entry = F;
751     } else {
752       // Otherwise, we have a definition after a prototype with the wrong type.
753       // F is the Function* for the one with the wrong type, we must make a new
754       // Function* and update everything that used F (a declaration) with the new
755       // Function* (which will be a definition).
756       //
757       // This happens if there is a prototype for a function (e.g. "int f()") and
758       // then a definition of a different type (e.g. "int f(int x)").  Start by
759       // making a new function of the correct type, RAUW, then steal the name.
760       llvm::Function *NewFn = llvm::Function::Create(FTy,
761                                                      llvm::Function::ExternalLinkage,
762                                                      "", &getModule());
763       NewFn->takeName(F);
764 
765       // Replace uses of F with the Function we will endow with a body.
766       llvm::Constant *NewPtrForOldDecl =
767         llvm::ConstantExpr::getBitCast(NewFn, F->getType());
768       F->replaceAllUsesWith(NewPtrForOldDecl);
769 
770       // FIXME: Update the globaldeclmap for the previous decl of this name.  We
771       // really want a way to walk all of these, but we don't have it yet.  This
772       // is incredibly slow!
773       ReplaceMapValuesWith(F, NewPtrForOldDecl);
774 
775       // Ok, delete the old function now, which is dead.
776       assert(F->isDeclaration() && "Shouldn't replace non-declaration");
777       F->eraseFromParent();
778 
779       SetFunctionAttributes(D, NewFn, FTy);
780       // Return the new function which has the right type.
781       Entry = NewFn;
782     }
783   }
784 
785   if (D->getAttr<AliasAttr>()) {
786     ;
787   } else {
788     llvm::Function *Fn = cast<llvm::Function>(Entry);
789     CodeGenFunction(*this).GenerateCode(D, Fn);
790   }
791 }
792 
793 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
794   // Make sure that this type is translated.
795   Types.UpdateCompletedType(TD);
796 }
797 
798 
799 /// getBuiltinLibFunction
800 llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
801   if (BuiltinID > BuiltinFunctions.size())
802     BuiltinFunctions.resize(BuiltinID);
803 
804   // Cache looked up functions.  Since builtin id #0 is invalid we don't reserve
805   // a slot for it.
806   assert(BuiltinID && "Invalid Builtin ID");
807   llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID-1];
808   if (FunctionSlot)
809     return FunctionSlot;
810 
811   assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn");
812 
813   // Get the name, skip over the __builtin_ prefix.
814   const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10;
815 
816   // Get the type for the builtin.
817   QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context);
818   const llvm::FunctionType *Ty =
819     cast<llvm::FunctionType>(getTypes().ConvertType(Type));
820 
821   // FIXME: This has a serious problem with code like this:
822   //  void abs() {}
823   //    ... __builtin_abs(x);
824   // The two versions of abs will collide.  The fix is for the builtin to win,
825   // and for the existing one to be turned into a constantexpr cast of the
826   // builtin.  In the case where the existing one is a static function, it
827   // should just be renamed.
828   if (llvm::Function *Existing = getModule().getFunction(Name)) {
829     if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
830       return FunctionSlot = Existing;
831     assert(Existing == 0 && "FIXME: Name collision");
832   }
833 
834   // FIXME: param attributes for sext/zext etc.
835   return FunctionSlot =
836     llvm::Function::Create(Ty, llvm::Function::ExternalLinkage, Name,
837                            &getModule());
838 }
839 
840 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
841                                             unsigned NumTys) {
842   return llvm::Intrinsic::getDeclaration(&getModule(),
843                                          (llvm::Intrinsic::ID)IID, Tys, NumTys);
844 }
845 
846 llvm::Function *CodeGenModule::getMemCpyFn() {
847   if (MemCpyFn) return MemCpyFn;
848   llvm::Intrinsic::ID IID;
849   switch (Context.Target.getPointerWidth(0)) {
850   default: assert(0 && "Unknown ptr width");
851   case 32: IID = llvm::Intrinsic::memcpy_i32; break;
852   case 64: IID = llvm::Intrinsic::memcpy_i64; break;
853   }
854   return MemCpyFn = getIntrinsic(IID);
855 }
856 
857 llvm::Function *CodeGenModule::getMemMoveFn() {
858   if (MemMoveFn) return MemMoveFn;
859   llvm::Intrinsic::ID IID;
860   switch (Context.Target.getPointerWidth(0)) {
861   default: assert(0 && "Unknown ptr width");
862   case 32: IID = llvm::Intrinsic::memmove_i32; break;
863   case 64: IID = llvm::Intrinsic::memmove_i64; break;
864   }
865   return MemMoveFn = getIntrinsic(IID);
866 }
867 
868 llvm::Function *CodeGenModule::getMemSetFn() {
869   if (MemSetFn) return MemSetFn;
870   llvm::Intrinsic::ID IID;
871   switch (Context.Target.getPointerWidth(0)) {
872   default: assert(0 && "Unknown ptr width");
873   case 32: IID = llvm::Intrinsic::memset_i32; break;
874   case 64: IID = llvm::Intrinsic::memset_i64; break;
875   }
876   return MemSetFn = getIntrinsic(IID);
877 }
878 
879 // FIXME: This needs moving into an Apple Objective-C runtime class
880 llvm::Constant *CodeGenModule::
881 GetAddrOfConstantCFString(const std::string &str) {
882   llvm::StringMapEntry<llvm::Constant *> &Entry =
883     CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
884 
885   if (Entry.getValue())
886     return Entry.getValue();
887 
888   std::vector<llvm::Constant*> Fields;
889 
890   if (!CFConstantStringClassRef) {
891     const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
892     Ty = llvm::ArrayType::get(Ty, 0);
893 
894     CFConstantStringClassRef =
895       new llvm::GlobalVariable(Ty, false,
896                                llvm::GlobalVariable::ExternalLinkage, 0,
897                                "__CFConstantStringClassReference",
898                                &getModule());
899   }
900 
901   // Class pointer.
902   llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
903   llvm::Constant *Zeros[] = { Zero, Zero };
904   llvm::Constant *C =
905     llvm::ConstantExpr::getGetElementPtr(CFConstantStringClassRef, Zeros, 2);
906   Fields.push_back(C);
907 
908   // Flags.
909   const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
910   Fields.push_back(llvm::ConstantInt::get(Ty, 1992));
911 
912   // String pointer.
913   C = llvm::ConstantArray::get(str);
914   C = new llvm::GlobalVariable(C->getType(), true,
915                                llvm::GlobalValue::InternalLinkage,
916                                C, ".str", &getModule());
917 
918   C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
919   Fields.push_back(C);
920 
921   // String length.
922   Ty = getTypes().ConvertType(getContext().LongTy);
923   Fields.push_back(llvm::ConstantInt::get(Ty, str.length()));
924 
925   // The struct.
926   Ty = getTypes().ConvertType(getContext().getCFConstantStringType());
927   C = llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Fields);
928   llvm::GlobalVariable *GV =
929     new llvm::GlobalVariable(C->getType(), true,
930                              llvm::GlobalVariable::InternalLinkage,
931                              C, "", &getModule());
932   GV->setSection("__DATA,__cfstring");
933   Entry.setValue(GV);
934   return GV;
935 }
936 
937 /// GenerateWritableString -- Creates storage for a string literal.
938 static llvm::Constant *GenerateStringLiteral(const std::string &str,
939                                              bool constant,
940                                              CodeGenModule &CGM) {
941   // Create Constant for this string literal
942   llvm::Constant *C=llvm::ConstantArray::get(str);
943 
944   // Create a global variable for this string
945   C = new llvm::GlobalVariable(C->getType(), constant,
946                                llvm::GlobalValue::InternalLinkage,
947                                C, ".str", &CGM.getModule());
948   return C;
949 }
950 
951 /// CodeGenModule::GetAddrOfConstantString -- returns a pointer to the character
952 /// array containing the literal.  The result is pointer to array type.
953 llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str) {
954   // Don't share any string literals if writable-strings is turned on.
955   if (Features.WritableStrings)
956     return GenerateStringLiteral(str, false, *this);
957 
958   llvm::StringMapEntry<llvm::Constant *> &Entry =
959   ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
960 
961   if (Entry.getValue())
962       return Entry.getValue();
963 
964   // Create a global variable for this.
965   llvm::Constant *C = GenerateStringLiteral(str, true, *this);
966   Entry.setValue(C);
967   return C;
968 }
969