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