CGDecl.cpp revision 71e38c48609b3502d24a47d39a21f1e73402a0e1
1//===--- CGDecl.cpp - Emit LLVM Code for declarations ---------------------===//
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 contains code to emit Decl nodes as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CGDebugInfo.h"
15#include "CodeGenFunction.h"
16#include "CodeGenModule.h"
17#include "clang/AST/ASTContext.h"
18#include "clang/AST/Decl.h"
19#include "clang/AST/DeclObjC.h"
20#include "clang/Basic/SourceManager.h"
21#include "clang/Basic/TargetInfo.h"
22#include "llvm/GlobalVariable.h"
23#include "llvm/Intrinsics.h"
24#include "llvm/Type.h"
25using namespace clang;
26using namespace CodeGen;
27
28
29void CodeGenFunction::EmitDecl(const Decl &D) {
30  switch (D.getKind()) {
31  default: assert(0 && "Unknown decl kind!");
32  case Decl::ParmVar:
33    assert(0 && "Parmdecls should not be in declstmts!");
34  case Decl::Typedef:   // typedef int X;
35  case Decl::Function:  // void X();
36  case Decl::Record:    // struct/union/class X;
37  case Decl::Enum:      // enum X;
38  case Decl::EnumConstant: // enum ? { X = ? }
39  case Decl::CXXRecord: // struct/union/class X; [C++]
40    // None of these decls require codegen support.
41    return;
42
43  case Decl::Var: {
44    const VarDecl &VD = cast<VarDecl>(D);
45    assert(VD.isBlockVarDecl() &&
46           "Should not see file-scope variables inside a function!");
47    return EmitBlockVarDecl(VD);
48  }
49  }
50}
51
52/// EmitBlockVarDecl - This method handles emission of any variable declaration
53/// inside a function, including static vars etc.
54void CodeGenFunction::EmitBlockVarDecl(const VarDecl &D) {
55  switch (D.getStorageClass()) {
56  case VarDecl::Static:
57    return EmitStaticBlockVarDecl(D);
58  case VarDecl::Extern:
59    // Don't emit it now, allow it to be emitted lazily on its first use.
60    return;
61  default:
62    assert((D.getStorageClass() == VarDecl::None ||
63            D.getStorageClass() == VarDecl::Auto ||
64            D.getStorageClass() == VarDecl::Register) &&
65           "Unknown storage class");
66    return EmitLocalBlockVarDecl(D);
67  }
68}
69
70llvm::GlobalValue *
71CodeGenFunction::GenerateStaticBlockVarDecl(const VarDecl &D,
72                                            bool NoInit,
73                                            const char *Separator) {
74  QualType Ty = D.getType();
75  assert(Ty->isConstantSizeType() && "VLAs can't be static");
76
77  const llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(Ty);
78  llvm::Constant *Init = 0;
79  if ((D.getInit() == 0) || NoInit) {
80    Init = llvm::Constant::getNullValue(LTy);
81  } else {
82    if (D.getInit()->isConstantExpr(getContext(), 0))
83      Init = CGM.EmitConstantExpr(D.getInit(), this);
84    else {
85      assert(getContext().getLangOptions().CPlusPlus &&
86             "only C++ supports non-constant static initializers!");
87      return GenerateStaticCXXBlockVarDecl(D);
88    }
89  }
90
91  assert(Init && "Unable to create initialiser for static decl");
92
93  std::string ContextName;
94  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CurFuncDecl))
95    ContextName = FD->getNameAsString();
96  else if (isa<ObjCMethodDecl>(CurFuncDecl))
97    ContextName = std::string(CurFn->getNameStart(),
98                              CurFn->getNameStart() + CurFn->getNameLen());
99  else
100    assert(0 && "Unknown context for block var decl");
101
102  llvm::GlobalValue *GV =
103    new llvm::GlobalVariable(Init->getType(), false,
104                             llvm::GlobalValue::InternalLinkage,
105                             Init, ContextName + Separator +D.getNameAsString(),
106                             &CGM.getModule(), 0, Ty.getAddressSpace());
107
108  return GV;
109}
110
111void CodeGenFunction::EmitStaticBlockVarDecl(const VarDecl &D) {
112
113  llvm::Value *&DMEntry = LocalDeclMap[&D];
114  assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
115
116  llvm::GlobalValue *GV = GenerateStaticBlockVarDecl(D, false, ".");
117
118  if (const AnnotateAttr *AA = D.getAttr<AnnotateAttr>()) {
119    SourceManager &SM = CGM.getContext().getSourceManager();
120    llvm::Constant *Ann =
121      CGM.EmitAnnotateAttr(GV, AA, SM.getLogicalLineNumber(D.getLocation()));
122    CGM.AddAnnotation(Ann);
123  }
124
125  const llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(D.getType());
126  const llvm::Type *LPtrTy =
127    llvm::PointerType::get(LTy, D.getType().getAddressSpace());
128  DMEntry = llvm::ConstantExpr::getBitCast(GV, LPtrTy);
129
130  // Emit global variable debug descriptor for static vars.
131  CGDebugInfo *DI = CGM.getDebugInfo();
132  if(DI) {
133    DI->setLocation(D.getLocation());
134    DI->EmitGlobalVariable(static_cast<llvm::GlobalVariable *>(GV), &D);
135  }
136
137}
138
139/// EmitLocalBlockVarDecl - Emit code and set up an entry in LocalDeclMap for a
140/// variable declaration with auto, register, or no storage class specifier.
141/// These turn into simple stack objects, or GlobalValues depending on target.
142void CodeGenFunction::EmitLocalBlockVarDecl(const VarDecl &D) {
143  QualType Ty = D.getType();
144
145  llvm::Value *DeclPtr;
146  if (Ty->isConstantSizeType()) {
147    if (!Target.useGlobalsForAutomaticVariables()) {
148      // A normal fixed sized variable becomes an alloca in the entry block.
149      const llvm::Type *LTy = ConvertType(Ty);
150      llvm::AllocaInst *Alloc =
151        CreateTempAlloca(LTy, D.getIdentifier()->getName());
152      unsigned align = getContext().getTypeAlign(Ty);
153      if (const AlignedAttr* AA = D.getAttr<AlignedAttr>())
154        align = std::max(align, AA->getAlignment());
155      Alloc->setAlignment(align >> 3);
156      DeclPtr = Alloc;
157    } else {
158      // Targets that don't support recursion emit locals as globals.
159      const char *Class =
160        D.getStorageClass() == VarDecl::Register ? ".reg." : ".auto.";
161      DeclPtr = GenerateStaticBlockVarDecl(D, true, Class);
162    }
163  } else if (1) {
164    // FIXME: The code below is disabled because is causes a regression in the
165    // testsuite.
166    CGM.ErrorUnsupported(&D, "variable-length array");
167
168    const llvm::Type *LTy = ConvertType(Ty);
169    llvm::AllocaInst *Alloc =
170      CreateTempAlloca(LTy, D.getIdentifier()->getName());
171    DeclPtr = Alloc;
172  } else {
173    const VariableArrayType *VAT = getContext().getAsVariableArrayType(Ty);
174
175    if (!StackSaveValues.back()) {
176      // Save the stack.
177      const llvm::Type *LTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
178      llvm::Value *Stack = CreateTempAlloca(LTy, "saved_stack");
179
180      llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
181      llvm::Value *V = Builder.CreateCall(F);
182
183      Builder.CreateStore(V, Stack);
184
185      StackSaveValues.back() = Stack;
186    }
187    // Get the element type.
188    const llvm::Type *LElemTy = ConvertType(Ty);
189    const llvm::Type *LElemPtrTy =
190      llvm::PointerType::get(LElemTy, D.getType().getAddressSpace());
191
192    llvm::Value *VLASize = GetVLASize(VAT);
193
194    // Allocate memory for the array.
195    llvm::Value *VLA = Builder.CreateAlloca(llvm::Type::Int8Ty, VLASize, "vla");
196    VLA = Builder.CreateBitCast(VLA, LElemPtrTy, "tmp");
197
198    llvm::AllocaInst *Alloc =
199      CreateTempAlloca(LElemPtrTy, D.getIdentifier()->getName());
200
201    // FIXME: Volatile?
202    Builder.CreateStore(VLA, Alloc);
203
204    DeclPtr = Alloc;
205  }
206
207  llvm::Value *&DMEntry = LocalDeclMap[&D];
208  assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
209  DMEntry = DeclPtr;
210
211  // Emit debug info for local var declaration.
212  if (CGDebugInfo *DI = CGM.getDebugInfo()) {
213    DI->setLocation(D.getLocation());
214    DI->EmitDeclareOfAutoVariable(&D, DeclPtr, Builder);
215  }
216
217  // If this local has an initializer, emit it now.
218  if (const Expr *Init = D.getInit()) {
219    if (!hasAggregateLLVMType(Init->getType())) {
220      llvm::Value *V = EmitScalarExpr(Init);
221      Builder.CreateStore(V, DeclPtr, D.getType().isVolatileQualified());
222    } else if (Init->getType()->isAnyComplexType()) {
223      EmitComplexExprIntoAddr(Init, DeclPtr, D.getType().isVolatileQualified());
224    } else {
225      EmitAggExpr(Init, DeclPtr, D.getType().isVolatileQualified());
226    }
227  }
228}
229
230/// Emit an alloca (or GlobalValue depending on target)
231/// for the specified parameter and set up LocalDeclMap.
232void CodeGenFunction::EmitParmDecl(const VarDecl &D, llvm::Value *Arg) {
233  // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
234  assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
235         "Invalid argument to EmitParmDecl");
236  QualType Ty = D.getType();
237
238  llvm::Value *DeclPtr;
239  if (!Ty->isConstantSizeType()) {
240    // Variable sized values always are passed by-reference.
241    DeclPtr = Arg;
242  } else if (Target.useGlobalsForAutomaticVariables()) {
243    DeclPtr = GenerateStaticBlockVarDecl(D, true, ".arg.");
244  } else {
245    // A fixed sized single-value variable becomes an alloca in the entry block.
246    const llvm::Type *LTy = ConvertType(Ty);
247    if (LTy->isSingleValueType()) {
248      // TODO: Alignment
249      std::string Name = D.getNameAsString();
250      Name += ".addr";
251      DeclPtr = CreateTempAlloca(LTy, Name.c_str());
252
253      // Store the initial value into the alloca.
254      Builder.CreateStore(Arg, DeclPtr,Ty.isVolatileQualified());
255    } else {
256      // Otherwise, if this is an aggregate, just use the input pointer.
257      DeclPtr = Arg;
258    }
259    Arg->setName(D.getNameAsString());
260  }
261
262  llvm::Value *&DMEntry = LocalDeclMap[&D];
263  assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
264  DMEntry = DeclPtr;
265
266  // Emit debug info for param declaration.
267  if (CGDebugInfo *DI = CGM.getDebugInfo()) {
268    DI->setLocation(D.getLocation());
269    DI->EmitDeclareOfArgVariable(&D, DeclPtr, Builder);
270  }
271}
272
273