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::GlobalValue *OldVal,
480                                          llvm::GlobalValue *NewVal) {
481   for (llvm::DenseMap<const Decl*, llvm::GlobalValue*>::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   QualType ASTTy = D->getType();
532   const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
533   const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
534 
535   // See if it is already in the map.
536   llvm::GlobalValue *&Entry = GlobalDeclMap[D];
537 
538   // If not look for an existing global (if this decl shadows another
539   // one) or lazily create a forward declaration.
540   if (!Entry) {
541     // Check to see if the global already exists.
542     llvm::GlobalVariable *GV = getModule().getGlobalVariable(D->getName(), true);
543 
544     // Create it if not.
545     if (!GV)
546       GV = new llvm::GlobalVariable(Ty, false,
547                                     llvm::GlobalValue::ExternalLinkage,
548                                     0, D->getName(), &getModule(), 0,
549                                     ASTTy.getAddressSpace());
550 
551     // Cache the entry.
552     Entry = GV;
553   }
554 
555   // Make sure the result is of the correct type.
556   return llvm::ConstantExpr::getBitCast(Entry, PTy);
557 }
558 
559 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
560   llvm::Constant *Init = 0;
561   QualType ASTTy = D->getType();
562   const llvm::Type *VarTy = getTypes().ConvertTypeForMem(ASTTy);
563 
564   if (D->getInit() == 0) {
565     // This is a tentative definition; tentative definitions are
566     // implicitly initialized with { 0 }
567     const llvm::Type* InitTy;
568     if (ASTTy->isIncompleteArrayType()) {
569       // An incomplete array is normally [ TYPE x 0 ], but we need
570       // to fix it to [ TYPE x 1 ].
571       const llvm::ArrayType* ATy = cast<llvm::ArrayType>(VarTy);
572       InitTy = llvm::ArrayType::get(ATy->getElementType(), 1);
573     } else {
574       InitTy = VarTy;
575     }
576     Init = llvm::Constant::getNullValue(InitTy);
577   } else {
578     Init = EmitConstantExpr(D->getInit());
579   }
580   const llvm::Type* InitType = Init->getType();
581 
582   llvm::GlobalVariable *GV = getModule().getGlobalVariable(D->getName(), true);
583 
584   if (!GV) {
585     GV = new llvm::GlobalVariable(InitType, false,
586                                   llvm::GlobalValue::ExternalLinkage,
587                                   0, D->getName(), &getModule(), 0,
588                                   ASTTy.getAddressSpace());
589   } else if (GV->getType()->getElementType() != InitType ||
590              GV->getType()->getAddressSpace() != ASTTy.getAddressSpace()) {
591     // We have a definition after a prototype with the wrong type.
592     // We must make a new GlobalVariable* and update everything that used OldGV
593     // (a declaration or tentative definition) with the new GlobalVariable*
594     // (which will be a definition).
595     //
596     // This happens if there is a prototype for a global (e.g. "extern int x[];")
597     // and then a definition of a different type (e.g. "int x[10];"). This also
598     // happens when an initializer has a different type from the type of the
599     // global (this happens with unions).
600     //
601     // FIXME: This also ends up happening if there's a definition followed by
602     // a tentative definition!  (Although Sema rejects that construct
603     // at the moment.)
604 
605     // Save the old global
606     llvm::GlobalVariable *OldGV = GV;
607 
608     // Make a new global with the correct type
609     GV = new llvm::GlobalVariable(InitType, false,
610                                   llvm::GlobalValue::ExternalLinkage,
611                                   0, D->getName(), &getModule(), 0,
612                                   ASTTy.getAddressSpace());
613     // Steal the name of the old global
614     GV->takeName(OldGV);
615 
616     // Replace all uses of the old global with the new global
617     llvm::Constant *NewPtrForOldDecl =
618         llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
619     OldGV->replaceAllUsesWith(NewPtrForOldDecl);
620     // Make sure we don't keep around any stale references to globals
621     // FIXME: This is really slow; we need a better way to walk all
622     // the decls with the same name
623     ReplaceMapValuesWith(OldGV, GV);
624 
625     // Erase the old global, since it is no longer used.
626     OldGV->eraseFromParent();
627   }
628 
629   GlobalDeclMap[D] = GV;
630 
631   if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
632     SourceManager &SM = Context.getSourceManager();
633     AddAnnotation(EmitAnnotateAttr(GV, AA,
634                                    SM.getLogicalLineNumber(D->getLocation())));
635   }
636 
637   GV->setInitializer(Init);
638 
639   // FIXME: This is silly; getTypeAlign should just work for incomplete arrays
640   unsigned Align;
641   if (const IncompleteArrayType* IAT = D->getType()->getAsIncompleteArrayType())
642     Align = Context.getTypeAlign(IAT->getElementType());
643   else
644     Align = Context.getTypeAlign(D->getType());
645   if (const AlignedAttr* AA = D->getAttr<AlignedAttr>()) {
646     Align = std::max(Align, AA->getAlignment());
647   }
648   GV->setAlignment(Align / 8);
649 
650   if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
651     setVisibility(GV, attr->getVisibility());
652   // FIXME: else handle -fvisibility
653 
654   // Set the llvm linkage type as appropriate.
655   if (D->getStorageClass() == VarDecl::Static)
656     GV->setLinkage(llvm::Function::InternalLinkage);
657   else if (D->getAttr<DLLImportAttr>())
658     GV->setLinkage(llvm::Function::DLLImportLinkage);
659   else if (D->getAttr<DLLExportAttr>())
660     GV->setLinkage(llvm::Function::DLLExportLinkage);
661   else if (D->getAttr<WeakAttr>())
662     GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
663   else {
664     // FIXME: This isn't right.  This should handle common linkage and other
665     // stuff.
666     switch (D->getStorageClass()) {
667     case VarDecl::Static: assert(0 && "This case handled above");
668     case VarDecl::Auto:
669     case VarDecl::Register:
670       assert(0 && "Can't have auto or register globals");
671     case VarDecl::None:
672       if (!D->getInit())
673         GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
674       break;
675     case VarDecl::Extern:
676     case VarDecl::PrivateExtern:
677       // todo: common
678       break;
679     }
680   }
681 
682   // Emit global variable debug information.
683   CGDebugInfo *DI = getDebugInfo();
684   if(DI) {
685     if(D->getLocation().isValid())
686       DI->setLocation(D->getLocation());
687     DI->EmitGlobalVariable(GV, D);
688   }
689 }
690 
691 llvm::GlobalValue *
692 CodeGenModule::EmitForwardFunctionDefinition(const FunctionDecl *D) {
693   // FIXME: param attributes for sext/zext etc.
694   if (const AliasAttr *AA = D->getAttr<AliasAttr>()) {
695     assert(!D->getBody() && "Unexpected alias attr on function with body.");
696 
697     const std::string& aliaseeName = AA->getAliasee();
698     llvm::Function *aliasee = getModule().getFunction(aliaseeName);
699     llvm::GlobalValue *alias = new llvm::GlobalAlias(aliasee->getType(),
700                                               llvm::Function::ExternalLinkage,
701                                                      D->getName(),
702                                                      aliasee,
703                                                      &getModule());
704     SetGlobalValueAttributes(D, alias);
705     return alias;
706   } else {
707     const llvm::Type *Ty = getTypes().ConvertType(D->getType());
708     const llvm::FunctionType *FTy = cast<llvm::FunctionType>(Ty);
709     llvm::Function *F = llvm::Function::Create(FTy,
710                                                llvm::Function::ExternalLinkage,
711                                                D->getName(), &getModule());
712 
713     SetFunctionAttributes(D, F, FTy);
714     return F;
715   }
716 }
717 
718 llvm::Constant *CodeGenModule::GetAddrOfFunction(const FunctionDecl *D) {
719   QualType ASTTy = D->getType();
720   const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
721   const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
722 
723   // See if it is already in the map.
724   llvm::GlobalValue *&Entry = GlobalDeclMap[D];
725 
726   // If not look for an existing global (if this decl shadows another
727   // one) or lazily create a forward declaration.
728   if (!Entry) {
729     // Check to see if the global already exists.
730     llvm::GlobalValue *GV = getModule().getFunction(D->getName());
731 
732     // Create it if not.
733     if (!GV)
734       GV = EmitForwardFunctionDefinition(D);
735 
736     // Cache the entry.
737     Entry = GV;
738   }
739 
740   return llvm::ConstantExpr::getBitCast(Entry, PTy);
741 }
742 
743 void CodeGenModule::EmitGlobalFunctionDefinition(const FunctionDecl *D) {
744   llvm::GlobalValue *&Entry = GlobalDeclMap[D];
745 
746   const llvm::Type *Ty = getTypes().ConvertType(D->getType());
747   const llvm::FunctionType *FTy = cast<llvm::FunctionType>(Ty);
748 
749   // Check to see if the function already exists.
750   llvm::Function *F = getModule().getFunction(D->getName());
751 
752   // If it doesn't already exist, just create and return an entry.
753   if (F == 0) {
754     Entry = EmitForwardFunctionDefinition(D);
755   } else {
756     // If the pointer type matches, just return it.
757     llvm::Type *PFTy = llvm::PointerType::getUnqual(Ty);
758     if (PFTy == F->getType()) {
759       Entry = F;
760     } else {
761       // Otherwise, we have a definition after a prototype with the wrong type.
762       // F is the Function* for the one with the wrong type, we must make a new
763       // Function* and update everything that used F (a declaration) with the new
764       // Function* (which will be a definition).
765       //
766       // This happens if there is a prototype for a function (e.g. "int f()") and
767       // then a definition of a different type (e.g. "int f(int x)").  Start by
768       // making a new function of the correct type, RAUW, then steal the name.
769       llvm::Function *NewFn = llvm::Function::Create(FTy,
770                                                      llvm::Function::ExternalLinkage,
771                                                      "", &getModule());
772       NewFn->takeName(F);
773 
774       // Replace uses of F with the Function we will endow with a body.
775       llvm::Constant *NewPtrForOldDecl =
776         llvm::ConstantExpr::getBitCast(NewFn, F->getType());
777       F->replaceAllUsesWith(NewPtrForOldDecl);
778 
779       // FIXME: Update the globaldeclmap for the previous decl of this name.  We
780       // really want a way to walk all of these, but we don't have it yet.  This
781       // is incredibly slow!
782       ReplaceMapValuesWith(F, NewFn);
783 
784       // Ok, delete the old function now, which is dead.
785       assert(F->isDeclaration() && "Shouldn't replace non-declaration");
786       F->eraseFromParent();
787 
788       SetFunctionAttributes(D, NewFn, FTy);
789       // Return the new function which has the right type.
790       Entry = NewFn;
791     }
792   }
793 
794   if (D->getAttr<AliasAttr>()) {
795     ;
796   } else {
797     llvm::Function *Fn = cast<llvm::Function>(Entry);
798     CodeGenFunction(*this).GenerateCode(D, Fn);
799   }
800 }
801 
802 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
803   // Make sure that this type is translated.
804   Types.UpdateCompletedType(TD);
805 }
806 
807 
808 /// getBuiltinLibFunction
809 llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
810   if (BuiltinID > BuiltinFunctions.size())
811     BuiltinFunctions.resize(BuiltinID);
812 
813   // Cache looked up functions.  Since builtin id #0 is invalid we don't reserve
814   // a slot for it.
815   assert(BuiltinID && "Invalid Builtin ID");
816   llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID-1];
817   if (FunctionSlot)
818     return FunctionSlot;
819 
820   assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn");
821 
822   // Get the name, skip over the __builtin_ prefix.
823   const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10;
824 
825   // Get the type for the builtin.
826   QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context);
827   const llvm::FunctionType *Ty =
828     cast<llvm::FunctionType>(getTypes().ConvertType(Type));
829 
830   // FIXME: This has a serious problem with code like this:
831   //  void abs() {}
832   //    ... __builtin_abs(x);
833   // The two versions of abs will collide.  The fix is for the builtin to win,
834   // and for the existing one to be turned into a constantexpr cast of the
835   // builtin.  In the case where the existing one is a static function, it
836   // should just be renamed.
837   if (llvm::Function *Existing = getModule().getFunction(Name)) {
838     if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
839       return FunctionSlot = Existing;
840     assert(Existing == 0 && "FIXME: Name collision");
841   }
842 
843   // FIXME: param attributes for sext/zext etc.
844   return FunctionSlot =
845     llvm::Function::Create(Ty, llvm::Function::ExternalLinkage, Name,
846                            &getModule());
847 }
848 
849 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
850                                             unsigned NumTys) {
851   return llvm::Intrinsic::getDeclaration(&getModule(),
852                                          (llvm::Intrinsic::ID)IID, Tys, NumTys);
853 }
854 
855 llvm::Function *CodeGenModule::getMemCpyFn() {
856   if (MemCpyFn) return MemCpyFn;
857   llvm::Intrinsic::ID IID;
858   switch (Context.Target.getPointerWidth(0)) {
859   default: assert(0 && "Unknown ptr width");
860   case 32: IID = llvm::Intrinsic::memcpy_i32; break;
861   case 64: IID = llvm::Intrinsic::memcpy_i64; break;
862   }
863   return MemCpyFn = getIntrinsic(IID);
864 }
865 
866 llvm::Function *CodeGenModule::getMemMoveFn() {
867   if (MemMoveFn) return MemMoveFn;
868   llvm::Intrinsic::ID IID;
869   switch (Context.Target.getPointerWidth(0)) {
870   default: assert(0 && "Unknown ptr width");
871   case 32: IID = llvm::Intrinsic::memmove_i32; break;
872   case 64: IID = llvm::Intrinsic::memmove_i64; break;
873   }
874   return MemMoveFn = getIntrinsic(IID);
875 }
876 
877 llvm::Function *CodeGenModule::getMemSetFn() {
878   if (MemSetFn) return MemSetFn;
879   llvm::Intrinsic::ID IID;
880   switch (Context.Target.getPointerWidth(0)) {
881   default: assert(0 && "Unknown ptr width");
882   case 32: IID = llvm::Intrinsic::memset_i32; break;
883   case 64: IID = llvm::Intrinsic::memset_i64; break;
884   }
885   return MemSetFn = getIntrinsic(IID);
886 }
887 
888 // FIXME: This needs moving into an Apple Objective-C runtime class
889 llvm::Constant *CodeGenModule::
890 GetAddrOfConstantCFString(const std::string &str) {
891   llvm::StringMapEntry<llvm::Constant *> &Entry =
892     CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
893 
894   if (Entry.getValue())
895     return Entry.getValue();
896 
897   std::vector<llvm::Constant*> Fields;
898 
899   if (!CFConstantStringClassRef) {
900     const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
901     Ty = llvm::ArrayType::get(Ty, 0);
902 
903     CFConstantStringClassRef =
904       new llvm::GlobalVariable(Ty, false,
905                                llvm::GlobalVariable::ExternalLinkage, 0,
906                                "__CFConstantStringClassReference",
907                                &getModule());
908   }
909 
910   // Class pointer.
911   llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
912   llvm::Constant *Zeros[] = { Zero, Zero };
913   llvm::Constant *C =
914     llvm::ConstantExpr::getGetElementPtr(CFConstantStringClassRef, Zeros, 2);
915   Fields.push_back(C);
916 
917   // Flags.
918   const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
919   Fields.push_back(llvm::ConstantInt::get(Ty, 1992));
920 
921   // String pointer.
922   C = llvm::ConstantArray::get(str);
923   C = new llvm::GlobalVariable(C->getType(), true,
924                                llvm::GlobalValue::InternalLinkage,
925                                C, ".str", &getModule());
926 
927   C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
928   Fields.push_back(C);
929 
930   // String length.
931   Ty = getTypes().ConvertType(getContext().LongTy);
932   Fields.push_back(llvm::ConstantInt::get(Ty, str.length()));
933 
934   // The struct.
935   Ty = getTypes().ConvertType(getContext().getCFConstantStringType());
936   C = llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Fields);
937   llvm::GlobalVariable *GV =
938     new llvm::GlobalVariable(C->getType(), true,
939                              llvm::GlobalVariable::InternalLinkage,
940                              C, "", &getModule());
941   GV->setSection("__DATA,__cfstring");
942   Entry.setValue(GV);
943   return GV;
944 }
945 
946 /// GenerateWritableString -- Creates storage for a string literal.
947 static llvm::Constant *GenerateStringLiteral(const std::string &str,
948                                              bool constant,
949                                              CodeGenModule &CGM) {
950   // Create Constant for this string literal
951   llvm::Constant *C=llvm::ConstantArray::get(str);
952 
953   // Create a global variable for this string
954   C = new llvm::GlobalVariable(C->getType(), constant,
955                                llvm::GlobalValue::InternalLinkage,
956                                C, ".str", &CGM.getModule());
957   return C;
958 }
959 
960 /// CodeGenModule::GetAddrOfConstantString -- returns a pointer to the character
961 /// array containing the literal.  The result is pointer to array type.
962 llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str) {
963   // Don't share any string literals if writable-strings is turned on.
964   if (Features.WritableStrings)
965     return GenerateStringLiteral(str, false, *this);
966 
967   llvm::StringMapEntry<llvm::Constant *> &Entry =
968   ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
969 
970   if (Entry.getValue())
971       return Entry.getValue();
972 
973   // Create a global variable for this.
974   llvm::Constant *C = GenerateStringLiteral(str, true, *this);
975   Entry.setValue(C);
976   return C;
977 }
978