xref: /llvm-project/clang/lib/CodeGen/CodeGenModule.cpp (revision 6dfdf8c97a79b14ecca3aba0bc1aff612cd62226)
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   DebugInfo = GenerateDebugInfo ? new CGDebugInfo(this) : 0;
46 }
47 
48 CodeGenModule::~CodeGenModule() {
49   delete Runtime;
50   delete DebugInfo;
51 }
52 
53 void CodeGenModule::Release() {
54   EmitStatics();
55   llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction();
56   if (ObjCInitFunction)
57     AddGlobalCtor(ObjCInitFunction);
58   EmitCtorList(GlobalCtors, "llvm.global_ctors");
59   EmitCtorList(GlobalDtors, "llvm.global_dtors");
60   EmitAnnotations();
61   // Run the verifier to check that the generated code is consistent.
62   assert(!verifyModule(TheModule));
63 }
64 
65 /// WarnUnsupported - Print out a warning that codegen doesn't support the
66 /// specified stmt yet.
67 void CodeGenModule::WarnUnsupported(const Stmt *S, const char *Type) {
68   unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Warning,
69                                                "cannot codegen this %0 yet");
70   SourceRange Range = S->getSourceRange();
71   std::string Msg = Type;
72   getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID,
73                     &Msg, 1, &Range, 1);
74 }
75 
76 /// WarnUnsupported - Print out a warning that codegen doesn't support the
77 /// specified decl yet.
78 void CodeGenModule::WarnUnsupported(const Decl *D, const char *Type) {
79   unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Warning,
80                                                "cannot codegen this %0 yet");
81   std::string Msg = Type;
82   getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID,
83                     &Msg, 1);
84 }
85 
86 /// setVisibility - Set the visibility for the given LLVM GlobalValue
87 /// according to the given clang AST visibility value.
88 void CodeGenModule::setVisibility(llvm::GlobalValue *GV,
89                                   VisibilityAttr::VisibilityTypes Vis) {
90   switch (Vis) {
91   default: assert(0 && "Unknown visibility!");
92   case VisibilityAttr::DefaultVisibility:
93     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
94     break;
95   case VisibilityAttr::HiddenVisibility:
96     GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
97     break;
98   case VisibilityAttr::ProtectedVisibility:
99     GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
100     break;
101   }
102 }
103 
104 /// AddGlobalCtor - Add a function to the list that will be called before
105 /// main() runs.
106 void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
107   // TODO: Type coercion of void()* types.
108   GlobalCtors.push_back(std::make_pair(Ctor, Priority));
109 }
110 
111 /// AddGlobalDtor - Add a function to the list that will be called
112 /// when the module is unloaded.
113 void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
114   // TODO: Type coercion of void()* types.
115   GlobalDtors.push_back(std::make_pair(Dtor, Priority));
116 }
117 
118 void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
119   // Ctor function type is void()*.
120   llvm::FunctionType* CtorFTy =
121     llvm::FunctionType::get(llvm::Type::VoidTy,
122                             std::vector<const llvm::Type*>(),
123                             false);
124   llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
125 
126   // Get the type of a ctor entry, { i32, void ()* }.
127   llvm::StructType* CtorStructTy =
128     llvm::StructType::get(llvm::Type::Int32Ty,
129                           llvm::PointerType::getUnqual(CtorFTy), NULL);
130 
131   // Construct the constructor and destructor arrays.
132   std::vector<llvm::Constant*> Ctors;
133   for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
134     std::vector<llvm::Constant*> S;
135     S.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, I->second, false));
136     S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
137     Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
138   }
139 
140   if (!Ctors.empty()) {
141     llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
142     new llvm::GlobalVariable(AT, false,
143                              llvm::GlobalValue::AppendingLinkage,
144                              llvm::ConstantArray::get(AT, Ctors),
145                              GlobalName,
146                              &TheModule);
147   }
148 }
149 
150 void CodeGenModule::EmitAnnotations() {
151   if (Annotations.empty())
152     return;
153 
154   // Create a new global variable for the ConstantStruct in the Module.
155   llvm::Constant *Array =
156   llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
157                                                 Annotations.size()),
158                            Annotations);
159   llvm::GlobalValue *gv =
160   new llvm::GlobalVariable(Array->getType(), false,
161                            llvm::GlobalValue::AppendingLinkage, Array,
162                            "llvm.global.annotations", &TheModule);
163   gv->setSection("llvm.metadata");
164 }
165 
166 bool hasAggregateLLVMType(QualType T) {
167   return !T->isRealType() && !T->isPointerLikeType() &&
168          !T->isVoidType() && !T->isVectorType() && !T->isFunctionType();
169 }
170 
171 void CodeGenModule::SetGlobalValueAttributes(const FunctionDecl *FD,
172                                              llvm::GlobalValue *GV) {
173   // TODO: Set up linkage and many other things.  Note, this is a simple
174   // approximation of what we really want.
175   if (FD->getStorageClass() == FunctionDecl::Static)
176     GV->setLinkage(llvm::Function::InternalLinkage);
177   else if (FD->getAttr<DLLImportAttr>())
178     GV->setLinkage(llvm::Function::DLLImportLinkage);
179   else if (FD->getAttr<DLLExportAttr>())
180     GV->setLinkage(llvm::Function::DLLExportLinkage);
181   else if (FD->getAttr<WeakAttr>() || FD->isInline())
182     GV->setLinkage(llvm::Function::WeakLinkage);
183 
184   if (const VisibilityAttr *attr = FD->getAttr<VisibilityAttr>())
185     CodeGenModule::setVisibility(GV, attr->getVisibility());
186   // FIXME: else handle -fvisibility
187 
188   if (const AsmLabelAttr *ALA = FD->getAttr<AsmLabelAttr>()) {
189     // Prefaced with special LLVM marker to indicate that the name
190     // should not be munged.
191     GV->setName("\01" + ALA->getLabel());
192   }
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 (!GlobalDeclMap.count(D->getName()))
410         continue;
411 
412       // Emit the definition.
413       EmitGlobalDefinition(D);
414 
415       // Erase the used decl from the list.
416       StaticDecls[i] = StaticDecls.back();
417       StaticDecls.pop_back();
418       --i;
419       --e;
420 
421       // Remember that we made a change.
422       Changed = true;
423     }
424   } while (Changed);
425 }
426 
427 /// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
428 /// annotation information for a given GlobalValue.  The annotation struct is
429 /// {i8 *, i8 *, i8 *, i32}.  The first field is a constant expression, the
430 /// GlobalValue being annotated.  The second field is the constant string
431 /// created from the AnnotateAttr's annotation.  The third field is a constant
432 /// string containing the name of the translation unit.  The fourth field is
433 /// the line number in the file of the annotated value declaration.
434 ///
435 /// FIXME: this does not unique the annotation string constants, as llvm-gcc
436 ///        appears to.
437 ///
438 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
439                                                 const AnnotateAttr *AA,
440                                                 unsigned LineNo) {
441   llvm::Module *M = &getModule();
442 
443   // get [N x i8] constants for the annotation string, and the filename string
444   // which are the 2nd and 3rd elements of the global annotation structure.
445   const llvm::Type *SBP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
446   llvm::Constant *anno = llvm::ConstantArray::get(AA->getAnnotation(), true);
447   llvm::Constant *unit = llvm::ConstantArray::get(M->getModuleIdentifier(),
448                                                   true);
449 
450   // Get the two global values corresponding to the ConstantArrays we just
451   // created to hold the bytes of the strings.
452   llvm::GlobalValue *annoGV =
453   new llvm::GlobalVariable(anno->getType(), false,
454                            llvm::GlobalValue::InternalLinkage, anno,
455                            GV->getName() + ".str", M);
456   // translation unit name string, emitted into the llvm.metadata section.
457   llvm::GlobalValue *unitGV =
458   new llvm::GlobalVariable(unit->getType(), false,
459                            llvm::GlobalValue::InternalLinkage, unit, ".str", M);
460 
461   // Create the ConstantStruct that is the global annotion.
462   llvm::Constant *Fields[4] = {
463     llvm::ConstantExpr::getBitCast(GV, SBP),
464     llvm::ConstantExpr::getBitCast(annoGV, SBP),
465     llvm::ConstantExpr::getBitCast(unitGV, SBP),
466     llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo)
467   };
468   return llvm::ConstantStruct::get(Fields, 4, false);
469 }
470 
471 void CodeGenModule::EmitGlobal(const ValueDecl *Global) {
472   bool isDef, isStatic;
473 
474   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
475     isDef = (FD->isThisDeclarationADefinition() ||
476              FD->getAttr<AliasAttr>());
477     isStatic = FD->getStorageClass() == FunctionDecl::Static;
478   } else if (const VarDecl *VD = cast<VarDecl>(Global)) {
479     assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
480 
481     isDef = !(VD->getStorageClass() == VarDecl::Extern && VD->getInit() == 0);
482     isStatic = VD->getStorageClass() == VarDecl::Static;
483   } else {
484     assert(0 && "Invalid argument to EmitGlobal");
485     return;
486   }
487 
488   // Forward declarations are emitted lazily on first use.
489   if (!isDef)
490     return;
491 
492   // If the global is a static, defer code generation until later so
493   // we can easily omit unused statics.
494   if (isStatic) {
495     StaticDecls.push_back(Global);
496     return;
497   }
498 
499   // Otherwise emit the definition.
500   EmitGlobalDefinition(Global);
501 }
502 
503 void CodeGenModule::EmitGlobalDefinition(const ValueDecl *D) {
504   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
505     EmitGlobalFunctionDefinition(FD);
506   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
507     EmitGlobalVarDefinition(VD);
508   } else {
509     assert(0 && "Invalid argument to EmitGlobalDefinition()");
510   }
511 }
512 
513  llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D) {
514   assert(D->hasGlobalStorage() && "Not a global variable");
515 
516   QualType ASTTy = D->getType();
517   const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
518   const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
519 
520   // Lookup the entry, lazily creating it if necessary.
521   llvm::GlobalValue *&Entry = GlobalDeclMap[D->getName()];
522   if (!Entry)
523     Entry = new llvm::GlobalVariable(Ty, false,
524                                      llvm::GlobalValue::ExternalLinkage,
525                                      0, D->getName(), &getModule(), 0,
526                                      ASTTy.getAddressSpace());
527 
528   // Make sure the result is of the correct type.
529   return llvm::ConstantExpr::getBitCast(Entry, PTy);
530 }
531 
532 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
533   llvm::Constant *Init = 0;
534   QualType ASTTy = D->getType();
535   const llvm::Type *VarTy = getTypes().ConvertTypeForMem(ASTTy);
536 
537   if (D->getInit() == 0) {
538     // This is a tentative definition; tentative definitions are
539     // implicitly initialized with { 0 }
540     const llvm::Type* InitTy;
541     if (ASTTy->isIncompleteArrayType()) {
542       // An incomplete array is normally [ TYPE x 0 ], but we need
543       // to fix it to [ TYPE x 1 ].
544       const llvm::ArrayType* ATy = cast<llvm::ArrayType>(VarTy);
545       InitTy = llvm::ArrayType::get(ATy->getElementType(), 1);
546     } else {
547       InitTy = VarTy;
548     }
549     Init = llvm::Constant::getNullValue(InitTy);
550   } else {
551     Init = EmitConstantExpr(D->getInit());
552   }
553   const llvm::Type* InitType = Init->getType();
554 
555   llvm::GlobalValue *&Entry = GlobalDeclMap[D->getName()];
556   llvm::GlobalVariable *GV = cast_or_null<llvm::GlobalVariable>(Entry);
557 
558   if (!GV) {
559     GV = new llvm::GlobalVariable(InitType, false,
560                                   llvm::GlobalValue::ExternalLinkage,
561                                   0, D->getName(), &getModule(), 0,
562                                   ASTTy.getAddressSpace());
563   } else if (GV->getType() !=
564              llvm::PointerType::get(InitType, ASTTy.getAddressSpace())) {
565     // We have a definition after a prototype with the wrong type.
566     // We must make a new GlobalVariable* and update everything that used OldGV
567     // (a declaration or tentative definition) with the new GlobalVariable*
568     // (which will be a definition).
569     //
570     // This happens if there is a prototype for a global (e.g. "extern int x[];")
571     // and then a definition of a different type (e.g. "int x[10];"). This also
572     // happens when an initializer has a different type from the type of the
573     // global (this happens with unions).
574     //
575     // FIXME: This also ends up happening if there's a definition followed by
576     // a tentative definition!  (Although Sema rejects that construct
577     // at the moment.)
578 
579     // Save the old global
580     llvm::GlobalVariable *OldGV = GV;
581 
582     // Make a new global with the correct type
583     GV = new llvm::GlobalVariable(InitType, false,
584                                   llvm::GlobalValue::ExternalLinkage,
585                                   0, D->getName(), &getModule(), 0,
586                                   ASTTy.getAddressSpace());
587     // Steal the name of the old global
588     GV->takeName(OldGV);
589 
590     // Replace all uses of the old global with the new global
591     llvm::Constant *NewPtrForOldDecl =
592         llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
593     OldGV->replaceAllUsesWith(NewPtrForOldDecl);
594 
595     // Erase the old global, since it is no longer used.
596     OldGV->eraseFromParent();
597   }
598 
599   Entry = GV;
600 
601   if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
602     SourceManager &SM = Context.getSourceManager();
603     AddAnnotation(EmitAnnotateAttr(GV, AA,
604                                    SM.getLogicalLineNumber(D->getLocation())));
605   }
606 
607   GV->setInitializer(Init);
608 
609   // FIXME: This is silly; getTypeAlign should just work for incomplete arrays
610   unsigned Align;
611   if (const IncompleteArrayType* IAT =
612         Context.getAsIncompleteArrayType(D->getType()))
613     Align = Context.getTypeAlign(IAT->getElementType());
614   else
615     Align = Context.getTypeAlign(D->getType());
616   if (const AlignedAttr* AA = D->getAttr<AlignedAttr>()) {
617     Align = std::max(Align, AA->getAlignment());
618   }
619   GV->setAlignment(Align / 8);
620 
621   if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
622     setVisibility(GV, attr->getVisibility());
623   // FIXME: else handle -fvisibility
624 
625   if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
626     // Prefaced with special LLVM marker to indicate that the name
627     // should not be munged.
628     GV->setName("\01" + ALA->getLabel());
629   }
630 
631   // Set the llvm linkage type as appropriate.
632   if (D->getStorageClass() == VarDecl::Static)
633     GV->setLinkage(llvm::Function::InternalLinkage);
634   else if (D->getAttr<DLLImportAttr>())
635     GV->setLinkage(llvm::Function::DLLImportLinkage);
636   else if (D->getAttr<DLLExportAttr>())
637     GV->setLinkage(llvm::Function::DLLExportLinkage);
638   else if (D->getAttr<WeakAttr>())
639     GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
640   else {
641     // FIXME: This isn't right.  This should handle common linkage and other
642     // stuff.
643     switch (D->getStorageClass()) {
644     case VarDecl::Static: assert(0 && "This case handled above");
645     case VarDecl::Auto:
646     case VarDecl::Register:
647       assert(0 && "Can't have auto or register globals");
648     case VarDecl::None:
649       if (!D->getInit())
650         GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
651       break;
652     case VarDecl::Extern:
653     case VarDecl::PrivateExtern:
654       // todo: common
655       break;
656     }
657   }
658 
659   // Emit global variable debug information.
660   CGDebugInfo *DI = getDebugInfo();
661   if(DI) {
662     if(D->getLocation().isValid())
663       DI->setLocation(D->getLocation());
664     DI->EmitGlobalVariable(GV, D);
665   }
666 }
667 
668 llvm::GlobalValue *
669 CodeGenModule::EmitForwardFunctionDefinition(const FunctionDecl *D) {
670   // FIXME: param attributes for sext/zext etc.
671   if (const AliasAttr *AA = D->getAttr<AliasAttr>()) {
672     assert(!D->getBody() && "Unexpected alias attr on function with body.");
673 
674     const std::string& aliaseeName = AA->getAliasee();
675     llvm::Function *aliasee = getModule().getFunction(aliaseeName);
676     llvm::GlobalValue *alias = new llvm::GlobalAlias(aliasee->getType(),
677                                               llvm::Function::ExternalLinkage,
678                                                      D->getName(),
679                                                      aliasee,
680                                                      &getModule());
681     SetGlobalValueAttributes(D, alias);
682     return alias;
683   } else {
684     const llvm::Type *Ty = getTypes().ConvertType(D->getType());
685     const llvm::FunctionType *FTy = cast<llvm::FunctionType>(Ty);
686     llvm::Function *F = llvm::Function::Create(FTy,
687                                                llvm::Function::ExternalLinkage,
688                                                D->getName(), &getModule());
689 
690     SetFunctionAttributes(D, F, FTy);
691     return F;
692   }
693 }
694 
695 llvm::Constant *CodeGenModule::GetAddrOfFunction(const FunctionDecl *D) {
696   QualType ASTTy = D->getType();
697   const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
698   const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
699 
700   // Lookup the entry, lazily creating it if necessary.
701   llvm::GlobalValue *&Entry = GlobalDeclMap[D->getName()];
702   if (!Entry)
703     Entry = EmitForwardFunctionDefinition(D);
704 
705   return llvm::ConstantExpr::getBitCast(Entry, PTy);
706 }
707 
708 void CodeGenModule::EmitGlobalFunctionDefinition(const FunctionDecl *D) {
709   llvm::GlobalValue *&Entry = GlobalDeclMap[D->getName()];
710   if (!Entry) {
711     Entry = EmitForwardFunctionDefinition(D);
712   } else {
713     // If the types mismatch then we have to rewrite the definition.
714     const llvm::Type *Ty = getTypes().ConvertType(D->getType());
715     if (Entry->getType() != llvm::PointerType::getUnqual(Ty)) {
716       // Otherwise, we have a definition after a prototype with the wrong type.
717       // F is the Function* for the one with the wrong type, we must make a new
718       // Function* and update everything that used F (a declaration) with the new
719       // Function* (which will be a definition).
720       //
721       // This happens if there is a prototype for a function (e.g. "int f()") and
722       // then a definition of a different type (e.g. "int f(int x)").  Start by
723       // making a new function of the correct type, RAUW, then steal the name.
724       llvm::GlobalValue *NewFn = EmitForwardFunctionDefinition(D);
725       NewFn->takeName(Entry);
726 
727       // Replace uses of F with the Function we will endow with a body.
728       llvm::Constant *NewPtrForOldDecl =
729         llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
730       Entry->replaceAllUsesWith(NewPtrForOldDecl);
731 
732       // Ok, delete the old function now, which is dead.
733       // FIXME: Add GlobalValue->eraseFromParent().
734       assert(Entry->isDeclaration() && "Shouldn't replace non-declaration");
735       if (llvm::Function *F = dyn_cast<llvm::Function>(Entry)) {
736         F->eraseFromParent();
737       } else if (llvm::GlobalAlias *GA = dyn_cast<llvm::GlobalAlias>(Entry)) {
738         GA->eraseFromParent();
739       } else {
740         assert(0 && "Invalid global variable type.");
741       }
742 
743       Entry = NewFn;
744     }
745   }
746 
747   if (D->getAttr<AliasAttr>()) {
748     ;
749   } else {
750     llvm::Function *Fn = cast<llvm::Function>(Entry);
751     CodeGenFunction(*this).GenerateCode(D, Fn);
752 
753     if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) {
754       AddGlobalCtor(Fn, CA->getPriority());
755     } else if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) {
756       AddGlobalDtor(Fn, DA->getPriority());
757     }
758   }
759 }
760 
761 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
762   // Make sure that this type is translated.
763   Types.UpdateCompletedType(TD);
764 }
765 
766 
767 /// getBuiltinLibFunction
768 llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
769   if (BuiltinID > BuiltinFunctions.size())
770     BuiltinFunctions.resize(BuiltinID);
771 
772   // Cache looked up functions.  Since builtin id #0 is invalid we don't reserve
773   // a slot for it.
774   assert(BuiltinID && "Invalid Builtin ID");
775   llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID-1];
776   if (FunctionSlot)
777     return FunctionSlot;
778 
779   assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn");
780 
781   // Get the name, skip over the __builtin_ prefix.
782   const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10;
783 
784   // Get the type for the builtin.
785   QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context);
786   const llvm::FunctionType *Ty =
787     cast<llvm::FunctionType>(getTypes().ConvertType(Type));
788 
789   // FIXME: This has a serious problem with code like this:
790   //  void abs() {}
791   //    ... __builtin_abs(x);
792   // The two versions of abs will collide.  The fix is for the builtin to win,
793   // and for the existing one to be turned into a constantexpr cast of the
794   // builtin.  In the case where the existing one is a static function, it
795   // should just be renamed.
796   if (llvm::Function *Existing = getModule().getFunction(Name)) {
797     if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
798       return FunctionSlot = Existing;
799     assert(Existing == 0 && "FIXME: Name collision");
800   }
801 
802   // FIXME: param attributes for sext/zext etc.
803   return FunctionSlot =
804     llvm::Function::Create(Ty, llvm::Function::ExternalLinkage, Name,
805                            &getModule());
806 }
807 
808 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
809                                             unsigned NumTys) {
810   return llvm::Intrinsic::getDeclaration(&getModule(),
811                                          (llvm::Intrinsic::ID)IID, Tys, NumTys);
812 }
813 
814 llvm::Function *CodeGenModule::getMemCpyFn() {
815   if (MemCpyFn) return MemCpyFn;
816   llvm::Intrinsic::ID IID;
817   switch (Context.Target.getPointerWidth(0)) {
818   default: assert(0 && "Unknown ptr width");
819   case 32: IID = llvm::Intrinsic::memcpy_i32; break;
820   case 64: IID = llvm::Intrinsic::memcpy_i64; break;
821   }
822   return MemCpyFn = getIntrinsic(IID);
823 }
824 
825 llvm::Function *CodeGenModule::getMemMoveFn() {
826   if (MemMoveFn) return MemMoveFn;
827   llvm::Intrinsic::ID IID;
828   switch (Context.Target.getPointerWidth(0)) {
829   default: assert(0 && "Unknown ptr width");
830   case 32: IID = llvm::Intrinsic::memmove_i32; break;
831   case 64: IID = llvm::Intrinsic::memmove_i64; break;
832   }
833   return MemMoveFn = getIntrinsic(IID);
834 }
835 
836 llvm::Function *CodeGenModule::getMemSetFn() {
837   if (MemSetFn) return MemSetFn;
838   llvm::Intrinsic::ID IID;
839   switch (Context.Target.getPointerWidth(0)) {
840   default: assert(0 && "Unknown ptr width");
841   case 32: IID = llvm::Intrinsic::memset_i32; break;
842   case 64: IID = llvm::Intrinsic::memset_i64; break;
843   }
844   return MemSetFn = getIntrinsic(IID);
845 }
846 
847 // FIXME: This needs moving into an Apple Objective-C runtime class
848 llvm::Constant *CodeGenModule::
849 GetAddrOfConstantCFString(const std::string &str) {
850   llvm::StringMapEntry<llvm::Constant *> &Entry =
851     CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
852 
853   if (Entry.getValue())
854     return Entry.getValue();
855 
856   std::vector<llvm::Constant*> Fields;
857 
858   if (!CFConstantStringClassRef) {
859     const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
860     Ty = llvm::ArrayType::get(Ty, 0);
861 
862     CFConstantStringClassRef =
863       new llvm::GlobalVariable(Ty, false,
864                                llvm::GlobalVariable::ExternalLinkage, 0,
865                                "__CFConstantStringClassReference",
866                                &getModule());
867   }
868 
869   // Class pointer.
870   llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
871   llvm::Constant *Zeros[] = { Zero, Zero };
872   llvm::Constant *C =
873     llvm::ConstantExpr::getGetElementPtr(CFConstantStringClassRef, Zeros, 2);
874   Fields.push_back(C);
875 
876   // Flags.
877   const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
878   Fields.push_back(llvm::ConstantInt::get(Ty, 1992));
879 
880   // String pointer.
881   C = llvm::ConstantArray::get(str);
882   C = new llvm::GlobalVariable(C->getType(), true,
883                                llvm::GlobalValue::InternalLinkage,
884                                C, ".str", &getModule());
885 
886   C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
887   Fields.push_back(C);
888 
889   // String length.
890   Ty = getTypes().ConvertType(getContext().LongTy);
891   Fields.push_back(llvm::ConstantInt::get(Ty, str.length()));
892 
893   // The struct.
894   Ty = getTypes().ConvertType(getContext().getCFConstantStringType());
895   C = llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Fields);
896   llvm::GlobalVariable *GV =
897     new llvm::GlobalVariable(C->getType(), true,
898                              llvm::GlobalVariable::InternalLinkage,
899                              C, "", &getModule());
900   GV->setSection("__DATA,__cfstring");
901   Entry.setValue(GV);
902   return GV;
903 }
904 
905 /// getStringForStringLiteral - Return the appropriate bytes for a
906 /// string literal, properly padded to match the literal type.
907 std::string CodeGenModule::getStringForStringLiteral(const StringLiteral *E) {
908   assert(!E->isWide() && "FIXME: Wide strings not supported yet!");
909   const char *StrData = E->getStrData();
910   unsigned Len = E->getByteLength();
911 
912   const ConstantArrayType *CAT =
913     getContext().getAsConstantArrayType(E->getType());
914   assert(CAT && "String isn't pointer or array!");
915 
916   // Resize the string to the right size
917   // FIXME: What about wchar_t strings?
918   std::string Str(StrData, StrData+Len);
919   uint64_t RealLen = CAT->getSize().getZExtValue();
920   Str.resize(RealLen, '\0');
921 
922   return Str;
923 }
924 
925 /// GenerateWritableString -- Creates storage for a string literal.
926 static llvm::Constant *GenerateStringLiteral(const std::string &str,
927                                              bool constant,
928                                              CodeGenModule &CGM) {
929   // Create Constant for this string literal
930   llvm::Constant *C = llvm::ConstantArray::get(str);
931 
932   // Create a global variable for this string
933   C = new llvm::GlobalVariable(C->getType(), constant,
934                                llvm::GlobalValue::InternalLinkage,
935                                C, ".str", &CGM.getModule());
936   return C;
937 }
938 
939 /// CodeGenModule::GetAddrOfConstantString -- returns a pointer to the character
940 /// array containing the literal.  The result is pointer to array type.
941 llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str) {
942   // Don't share any string literals if writable-strings is turned on.
943   if (Features.WritableStrings)
944     return GenerateStringLiteral(str, false, *this);
945 
946   llvm::StringMapEntry<llvm::Constant *> &Entry =
947   ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
948 
949   if (Entry.getValue())
950       return Entry.getValue();
951 
952   // Create a global variable for this.
953   llvm::Constant *C = GenerateStringLiteral(str, true, *this);
954   Entry.setValue(C);
955   return C;
956 }
957