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