CGDecl.cpp revision 56ebe5082da7411fb37479e230b52735f77cff35
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/Target/TargetData.h"
25#include "llvm/Type.h"
26using namespace clang;
27using namespace CodeGen;
28
29
30void CodeGenFunction::EmitDecl(const Decl &D) {
31  switch (D.getKind()) {
32  default: assert(0 && "Unknown decl kind!");
33  case Decl::ParmVar:
34    assert(0 && "Parmdecls should not be in declstmts!");
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  case Decl::Typedef: {   // typedef int X;
51    const TypedefDecl &TD = cast<TypedefDecl>(D);
52    QualType Ty = TD.getUnderlyingType();
53
54    if (Ty->isVariablyModifiedType())
55      EmitVLASize(Ty);
56  }
57  }
58}
59
60/// EmitBlockVarDecl - This method handles emission of any variable declaration
61/// inside a function, including static vars etc.
62void CodeGenFunction::EmitBlockVarDecl(const VarDecl &D) {
63  if (D.hasAttr<AsmLabelAttr>())
64    CGM.ErrorUnsupported(&D, "__asm__");
65
66  switch (D.getStorageClass()) {
67  case VarDecl::None:
68  case VarDecl::Auto:
69  case VarDecl::Register:
70    return EmitLocalBlockVarDecl(D);
71  case VarDecl::Static:
72    return EmitStaticBlockVarDecl(D);
73  case VarDecl::Extern:
74  case VarDecl::PrivateExtern:
75    // Don't emit it now, allow it to be emitted lazily on its first use.
76    return;
77  }
78
79  assert(0 && "Unknown storage class");
80}
81
82llvm::GlobalVariable *
83CodeGenFunction::CreateStaticBlockVarDecl(const VarDecl &D,
84                                          const char *Separator,
85                                          llvm::GlobalValue::LinkageTypes
86                                          Linkage) {
87  QualType Ty = D.getType();
88  assert(Ty->isConstantSizeType() && "VLAs can't be static");
89
90  std::string Name;
91  if (getContext().getLangOptions().CPlusPlus) {
92    Name = CGM.getMangledName(&D);
93  } else {
94    std::string ContextName;
95    if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CurFuncDecl))
96      ContextName = CGM.getMangledName(FD);
97    else if (isa<ObjCMethodDecl>(CurFuncDecl))
98      ContextName = std::string(CurFn->getNameStart(),
99                                CurFn->getNameStart() + CurFn->getNameLen());
100    else
101      assert(0 && "Unknown context for block var decl");
102
103    Name = ContextName + Separator + D.getNameAsString();
104  }
105
106  const llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(Ty);
107  return new llvm::GlobalVariable(LTy, Ty.isConstant(getContext()), Linkage,
108                                  llvm::Constant::getNullValue(LTy), Name,
109                                  &CGM.getModule(), D.isThreadSpecified(),
110                                  Ty.getAddressSpace());
111}
112
113void CodeGenFunction::EmitStaticBlockVarDecl(const VarDecl &D) {
114
115  llvm::Value *&DMEntry = LocalDeclMap[&D];
116  assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
117
118  llvm::GlobalVariable *GV =
119    CreateStaticBlockVarDecl(D, ".", llvm::GlobalValue::InternalLinkage);
120
121  // Store into LocalDeclMap before generating initializer to handle
122  // circular references.
123  DMEntry = GV;
124
125  if (D.getInit()) {
126    llvm::Constant *Init = CGM.EmitConstantExpr(D.getInit(), D.getType(), this);
127
128    // If constant emission failed, then this should be a C++ static
129    // initializer.
130    if (!Init) {
131      if (!getContext().getLangOptions().CPlusPlus)
132        CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
133      else
134        GenerateStaticCXXBlockVarDeclInit(D, GV);
135    } else {
136      // The initializer may differ in type from the global. Rewrite
137      // the global to match the initializer.  (We have to do this
138      // because some types, like unions, can't be completely represented
139      // in the LLVM type system.)
140      if (GV->getType() != Init->getType()) {
141        llvm::GlobalVariable *OldGV = GV;
142
143        GV = new llvm::GlobalVariable(Init->getType(), OldGV->isConstant(),
144                                      OldGV->getLinkage(), Init, "",
145                                      &CGM.getModule(), D.isThreadSpecified(),
146                                      D.getType().getAddressSpace());
147
148        // Steal the name of the old global
149        GV->takeName(OldGV);
150
151        // Replace all uses of the old global with the new global
152        llvm::Constant *NewPtrForOldDecl =
153          llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
154        OldGV->replaceAllUsesWith(NewPtrForOldDecl);
155
156        // Erase the old global, since it is no longer used.
157        OldGV->eraseFromParent();
158      }
159
160      GV->setInitializer(Init);
161    }
162  }
163
164  // FIXME: Merge attribute handling.
165  if (const AnnotateAttr *AA = D.getAttr<AnnotateAttr>()) {
166    SourceManager &SM = CGM.getContext().getSourceManager();
167    llvm::Constant *Ann =
168      CGM.EmitAnnotateAttr(GV, AA,
169                           SM.getInstantiationLineNumber(D.getLocation()));
170    CGM.AddAnnotation(Ann);
171  }
172
173  if (const SectionAttr *SA = D.getAttr<SectionAttr>())
174    GV->setSection(SA->getName());
175
176  if (D.hasAttr<UsedAttr>())
177    CGM.AddUsedGlobal(GV);
178
179  // We may have to cast the constant because of the initializer
180  // mismatch above.
181  //
182  // FIXME: It is really dangerous to store this in the map; if anyone
183  // RAUW's the GV uses of this constant will be invalid.
184  const llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(D.getType());
185  const llvm::Type *LPtrTy =
186    llvm::PointerType::get(LTy, D.getType().getAddressSpace());
187  DMEntry = llvm::ConstantExpr::getBitCast(GV, LPtrTy);
188
189  // Emit global variable debug descriptor for static vars.
190  CGDebugInfo *DI = getDebugInfo();
191  if (DI) {
192    DI->setLocation(D.getLocation());
193    DI->EmitGlobalVariable(static_cast<llvm::GlobalVariable *>(GV), &D);
194  }
195}
196
197/// BuildByRefType - This routine changes a __block variable declared as T x
198///   into:
199///
200///      struct {
201///        void *__isa;
202///        void *__forwarding;
203///        int32_t __flags;
204///        int32_t __size;
205///        void *__copy_helper;
206///        void *__destroy_helper;
207///        T x;
208///      } x
209///
210/// Align is the alignment needed in bytes for x.
211const llvm::Type *CodeGenFunction::BuildByRefType(QualType Ty,
212                                                  uint64_t Align) {
213  const llvm::Type *LTy = ConvertType(Ty);
214  bool needsCopyDispose = BlockRequiresCopying(Ty);
215  std::vector<const llvm::Type *> Types(needsCopyDispose*2+5);
216  const llvm::PointerType *PtrToInt8Ty
217    = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
218  Types[0] = PtrToInt8Ty;
219  Types[1] = PtrToInt8Ty;
220  Types[2] = llvm::Type::Int32Ty;
221  Types[3] = llvm::Type::Int32Ty;
222  if (needsCopyDispose) {
223    Types[4] = PtrToInt8Ty;
224    Types[5] = PtrToInt8Ty;
225  }
226  // FIXME: Align this on at least an Align boundary.
227  Types[needsCopyDispose*2 + 4] = LTy;
228  return llvm::StructType::get(Types, false);
229}
230
231/// EmitLocalBlockVarDecl - Emit code and set up an entry in LocalDeclMap for a
232/// variable declaration with auto, register, or no storage class specifier.
233/// These turn into simple stack objects, or GlobalValues depending on target.
234void CodeGenFunction::EmitLocalBlockVarDecl(const VarDecl &D) {
235  QualType Ty = D.getType();
236  bool isByRef = D.hasAttr<BlocksAttr>();
237  bool needsDispose = false;
238
239  llvm::Value *DeclPtr;
240  if (Ty->isConstantSizeType()) {
241    if (!Target.useGlobalsForAutomaticVariables()) {
242      // A normal fixed sized variable becomes an alloca in the entry block.
243      const llvm::Type *LTy = ConvertTypeForMem(Ty);
244      if (isByRef)
245        LTy = BuildByRefType(Ty, getContext().getDeclAlignInBytes(&D));
246      llvm::AllocaInst *Alloc = CreateTempAlloca(LTy);
247      Alloc->setName(D.getNameAsString().c_str());
248
249      if (isByRef)
250        Alloc->setAlignment(std::max(getContext().getDeclAlignInBytes(&D),
251                                     unsigned(Target.getPointerAlign(0) / 8)));
252      else
253        Alloc->setAlignment(getContext().getDeclAlignInBytes(&D));
254      DeclPtr = Alloc;
255    } else {
256      // Targets that don't support recursion emit locals as globals.
257      const char *Class =
258        D.getStorageClass() == VarDecl::Register ? ".reg." : ".auto.";
259      DeclPtr = CreateStaticBlockVarDecl(D, Class,
260                                         llvm::GlobalValue
261                                         ::InternalLinkage);
262    }
263
264    if (Ty->isVariablyModifiedType())
265      EmitVLASize(Ty);
266  } else {
267    if (!DidCallStackSave) {
268      // Save the stack.
269      const llvm::Type *LTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
270      llvm::Value *Stack = CreateTempAlloca(LTy, "saved_stack");
271
272      llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
273      llvm::Value *V = Builder.CreateCall(F);
274
275      Builder.CreateStore(V, Stack);
276
277      DidCallStackSave = true;
278
279      {
280        // Push a cleanup block and restore the stack there.
281        CleanupScope scope(*this);
282
283        V = Builder.CreateLoad(Stack, "tmp");
284        llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
285        Builder.CreateCall(F, V);
286      }
287    }
288
289    // Get the element type.
290    const llvm::Type *LElemTy = ConvertTypeForMem(Ty);
291    const llvm::Type *LElemPtrTy =
292      llvm::PointerType::get(LElemTy, D.getType().getAddressSpace());
293
294    llvm::Value *VLASize = EmitVLASize(Ty);
295
296    // Downcast the VLA size expression
297    VLASize = Builder.CreateIntCast(VLASize, llvm::Type::Int32Ty, false, "tmp");
298
299    // Allocate memory for the array.
300    llvm::Value *VLA = Builder.CreateAlloca(llvm::Type::Int8Ty, VLASize, "vla");
301    DeclPtr = Builder.CreateBitCast(VLA, LElemPtrTy, "tmp");
302  }
303
304  llvm::Value *&DMEntry = LocalDeclMap[&D];
305  assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
306  DMEntry = DeclPtr;
307
308  // Emit debug info for local var declaration.
309  if (CGDebugInfo *DI = getDebugInfo()) {
310    DI->setLocation(D.getLocation());
311    if (isByRef) {
312      llvm::Value *Loc;
313      bool needsCopyDispose = BlockRequiresCopying(Ty);
314      // FIXME: I think we need to indirect through the forwarding pointer first
315      Loc = Builder.CreateStructGEP(DeclPtr, needsCopyDispose*2+4, "x");
316      DI->EmitDeclareOfAutoVariable(&D, Loc, Builder);
317    } else
318      DI->EmitDeclareOfAutoVariable(&D, DeclPtr, Builder);
319  }
320
321  // If this local has an initializer, emit it now.
322  if (const Expr *Init = D.getInit()) {
323    llvm::Value *Loc = DeclPtr;
324    if (isByRef) {
325      bool needsCopyDispose = BlockRequiresCopying(Ty);
326      Loc = Builder.CreateStructGEP(DeclPtr, needsCopyDispose*2+4, "x");
327    }
328    if (!hasAggregateLLVMType(Init->getType())) {
329      llvm::Value *V = EmitScalarExpr(Init);
330      EmitStoreOfScalar(V, Loc, D.getType().isVolatileQualified());
331    } else if (Init->getType()->isAnyComplexType()) {
332      EmitComplexExprIntoAddr(Init, Loc, D.getType().isVolatileQualified());
333    } else {
334      EmitAggExpr(Init, Loc, D.getType().isVolatileQualified());
335    }
336  }
337  if (isByRef) {
338    const llvm::PointerType *PtrToInt8Ty
339      = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
340
341    llvm::Value *isa_field = Builder.CreateStructGEP(DeclPtr, 0);
342    llvm::Value *forwarding_field = Builder.CreateStructGEP(DeclPtr, 1);
343    llvm::Value *flags_field = Builder.CreateStructGEP(DeclPtr, 2);
344    llvm::Value *size_field = Builder.CreateStructGEP(DeclPtr, 3);
345    llvm::Value *V;
346    int flag = 0;
347    int flags = 0;
348
349    needsDispose = true;
350
351    if (Ty->isBlockPointerType()) {
352      flag |= BLOCK_FIELD_IS_BLOCK;
353      flags |= BLOCK_HAS_COPY_DISPOSE;
354    } else if (BlockRequiresCopying(Ty)) {
355      flag |= BLOCK_FIELD_IS_OBJECT;
356      flags |= BLOCK_HAS_COPY_DISPOSE;
357    }
358
359    // FIXME: Someone double check this.
360    if (Ty.isObjCGCWeak())
361      flag |= BLOCK_FIELD_IS_WEAK;
362
363    int isa = 0;
364    if (flag&BLOCK_FIELD_IS_WEAK)
365      isa = 1;
366    V = llvm::ConstantInt::get(llvm::Type::Int32Ty, isa);
367    V = Builder.CreateIntToPtr(V, PtrToInt8Ty, "isa");
368    Builder.CreateStore(V, isa_field);
369
370    V = Builder.CreateBitCast(DeclPtr, PtrToInt8Ty, "forwarding");
371    Builder.CreateStore(V, forwarding_field);
372
373    V = llvm::ConstantInt::get(llvm::Type::Int32Ty, flags);
374    Builder.CreateStore(V, flags_field);
375
376    const llvm::Type *V1;
377    V1 = cast<llvm::PointerType>(DeclPtr->getType())->getElementType();
378    V = llvm::ConstantInt::get(llvm::Type::Int32Ty,
379                               (CGM.getTargetData().getTypeStoreSizeInBits(V1)
380                                / 8));
381    Builder.CreateStore(V, size_field);
382
383    if (flags & BLOCK_HAS_COPY_DISPOSE) {
384      BlockHasCopyDispose = true;
385      llvm::Value *copy_helper = Builder.CreateStructGEP(DeclPtr, 4);
386      Builder.CreateStore(BuildbyrefCopyHelper(DeclPtr->getType(), flag),
387                          copy_helper);
388
389      llvm::Value *destroy_helper = Builder.CreateStructGEP(DeclPtr, 5);
390      Builder.CreateStore(BuildbyrefDestroyHelper(DeclPtr->getType(), flag),
391                          destroy_helper);
392    }
393  }
394
395  // Handle the cleanup attribute
396  if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
397    const FunctionDecl *FD = CA->getFunctionDecl();
398
399    llvm::Constant* F = CGM.GetAddrOfFunction(FD);
400    assert(F && "Could not find function!");
401
402    CleanupScope scope(*this);
403
404    CallArgList Args;
405    Args.push_back(std::make_pair(RValue::get(DeclPtr),
406                                  getContext().getPointerType(D.getType())));
407
408    EmitCall(CGM.getTypes().getFunctionInfo(FD), F, Args);
409  }
410
411  if (needsDispose && CGM.getLangOptions().getGCMode() != LangOptions::GCOnly) {
412    CleanupScope scope(*this);
413    llvm::Value *V = Builder.CreateStructGEP(DeclPtr, 1, "forwarding");
414    V = Builder.CreateLoad(V, false);
415    BuildBlockRelease(V);
416  }
417}
418
419/// Emit an alloca (or GlobalValue depending on target)
420/// for the specified parameter and set up LocalDeclMap.
421void CodeGenFunction::EmitParmDecl(const VarDecl &D, llvm::Value *Arg) {
422  // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
423  assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
424         "Invalid argument to EmitParmDecl");
425  QualType Ty = D.getType();
426
427  llvm::Value *DeclPtr;
428  if (!Ty->isConstantSizeType()) {
429    // Variable sized values always are passed by-reference.
430    DeclPtr = Arg;
431  } else {
432    // A fixed sized single-value variable becomes an alloca in the entry block.
433    const llvm::Type *LTy = ConvertTypeForMem(Ty);
434    if (LTy->isSingleValueType()) {
435      // TODO: Alignment
436      std::string Name = D.getNameAsString();
437      Name += ".addr";
438      DeclPtr = CreateTempAlloca(LTy);
439      DeclPtr->setName(Name.c_str());
440
441      // Store the initial value into the alloca.
442      EmitStoreOfScalar(Arg, DeclPtr, Ty.isVolatileQualified());
443    } else {
444      // Otherwise, if this is an aggregate, just use the input pointer.
445      DeclPtr = Arg;
446    }
447    Arg->setName(D.getNameAsString());
448  }
449
450  llvm::Value *&DMEntry = LocalDeclMap[&D];
451  assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
452  DMEntry = DeclPtr;
453
454  // Emit debug info for param declaration.
455  if (CGDebugInfo *DI = getDebugInfo()) {
456    DI->setLocation(D.getLocation());
457    DI->EmitDeclareOfArgVariable(&D, DeclPtr, Builder);
458  }
459}
460
461