CGDecl.cpp revision b6bbcc9995186799a60ce17d0c1acff31601653a
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/CharUnits.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/DeclObjC.h"
21#include "clang/Basic/SourceManager.h"
22#include "clang/Basic/TargetInfo.h"
23#include "clang/Frontend/CodeGenOptions.h"
24#include "llvm/GlobalVariable.h"
25#include "llvm/Intrinsics.h"
26#include "llvm/Target/TargetData.h"
27#include "llvm/Type.h"
28using namespace clang;
29using namespace CodeGen;
30
31
32void CodeGenFunction::EmitDecl(const Decl &D) {
33  switch (D.getKind()) {
34  case Decl::TranslationUnit:
35  case Decl::Namespace:
36  case Decl::UnresolvedUsingTypename:
37  case Decl::ClassTemplateSpecialization:
38  case Decl::ClassTemplatePartialSpecialization:
39  case Decl::TemplateTypeParm:
40  case Decl::UnresolvedUsingValue:
41  case Decl::NonTypeTemplateParm:
42  case Decl::CXXMethod:
43  case Decl::CXXConstructor:
44  case Decl::CXXDestructor:
45  case Decl::CXXConversion:
46  case Decl::Field:
47  case Decl::ObjCIvar:
48  case Decl::ObjCAtDefsField:
49  case Decl::ParmVar:
50  case Decl::ImplicitParam:
51  case Decl::ClassTemplate:
52  case Decl::FunctionTemplate:
53  case Decl::TemplateTemplateParm:
54  case Decl::ObjCMethod:
55  case Decl::ObjCCategory:
56  case Decl::ObjCProtocol:
57  case Decl::ObjCInterface:
58  case Decl::ObjCCategoryImpl:
59  case Decl::ObjCImplementation:
60  case Decl::ObjCProperty:
61  case Decl::ObjCCompatibleAlias:
62  case Decl::AccessSpec:
63  case Decl::LinkageSpec:
64  case Decl::ObjCPropertyImpl:
65  case Decl::ObjCClass:
66  case Decl::ObjCForwardProtocol:
67  case Decl::FileScopeAsm:
68  case Decl::Friend:
69  case Decl::FriendTemplate:
70  case Decl::Block:
71
72    assert(0 && "Declaration not should not be in declstmts!");
73  case Decl::Function:  // void X();
74  case Decl::Record:    // struct/union/class X;
75  case Decl::Enum:      // enum X;
76  case Decl::EnumConstant: // enum ? { X = ? }
77  case Decl::CXXRecord: // struct/union/class X; [C++]
78  case Decl::Using:          // using X; [C++]
79  case Decl::UsingShadow:
80  case Decl::UsingDirective: // using namespace X; [C++]
81  case Decl::NamespaceAlias:
82  case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
83    // None of these decls require codegen support.
84    return;
85
86  case Decl::Var: {
87    const VarDecl &VD = cast<VarDecl>(D);
88    assert(VD.isLocalVarDecl() &&
89           "Should not see file-scope variables inside a function!");
90    return EmitVarDecl(VD);
91  }
92
93  case Decl::Typedef: {   // typedef int X;
94    const TypedefDecl &TD = cast<TypedefDecl>(D);
95    QualType Ty = TD.getUnderlyingType();
96
97    if (Ty->isVariablyModifiedType())
98      EmitVLASize(Ty);
99  }
100  }
101}
102
103/// EmitVarDecl - This method handles emission of any variable declaration
104/// inside a function, including static vars etc.
105void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
106  if (D.hasAttr<AsmLabelAttr>())
107    CGM.ErrorUnsupported(&D, "__asm__");
108
109  switch (D.getStorageClass()) {
110  case SC_None:
111  case SC_Auto:
112  case SC_Register:
113    return EmitAutoVarDecl(D);
114  case SC_Static: {
115    llvm::GlobalValue::LinkageTypes Linkage =
116      llvm::GlobalValue::InternalLinkage;
117
118    // If the function definition has some sort of weak linkage, its
119    // static variables should also be weak so that they get properly
120    // uniqued.  We can't do this in C, though, because there's no
121    // standard way to agree on which variables are the same (i.e.
122    // there's no mangling).
123    if (getContext().getLangOptions().CPlusPlus)
124      if (llvm::GlobalValue::isWeakForLinker(CurFn->getLinkage()))
125        Linkage = CurFn->getLinkage();
126
127    return EmitStaticVarDecl(D, Linkage);
128  }
129  case SC_Extern:
130  case SC_PrivateExtern:
131    // Don't emit it now, allow it to be emitted lazily on its first use.
132    return;
133  }
134
135  assert(0 && "Unknown storage class");
136}
137
138static std::string GetStaticDeclName(CodeGenFunction &CGF, const VarDecl &D,
139                                     const char *Separator) {
140  CodeGenModule &CGM = CGF.CGM;
141  if (CGF.getContext().getLangOptions().CPlusPlus) {
142    llvm::StringRef Name = CGM.getMangledName(&D);
143    return Name.str();
144  }
145
146  std::string ContextName;
147  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CGF.CurFuncDecl)) {
148    llvm::StringRef Name = CGM.getMangledName(FD);
149    ContextName = Name.str();
150  } else if (isa<ObjCMethodDecl>(CGF.CurFuncDecl))
151    ContextName = CGF.CurFn->getName();
152  else
153    // FIXME: What about in a block??
154    assert(0 && "Unknown context for block var decl");
155
156  return ContextName + Separator + D.getNameAsString();
157}
158
159llvm::GlobalVariable *
160CodeGenFunction::CreateStaticVarDecl(const VarDecl &D,
161                                     const char *Separator,
162                                     llvm::GlobalValue::LinkageTypes Linkage) {
163  QualType Ty = D.getType();
164  assert(Ty->isConstantSizeType() && "VLAs can't be static");
165
166  std::string Name = GetStaticDeclName(*this, D, Separator);
167
168  const llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(Ty);
169  llvm::GlobalVariable *GV =
170    new llvm::GlobalVariable(CGM.getModule(), LTy,
171                             Ty.isConstant(getContext()), Linkage,
172                             CGM.EmitNullConstant(D.getType()), Name, 0,
173                             D.isThreadSpecified(), Ty.getAddressSpace());
174  GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
175  return GV;
176}
177
178/// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
179/// global variable that has already been created for it.  If the initializer
180/// has a different type than GV does, this may free GV and return a different
181/// one.  Otherwise it just returns GV.
182llvm::GlobalVariable *
183CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
184                                               llvm::GlobalVariable *GV) {
185  llvm::Constant *Init = CGM.EmitConstantExpr(D.getInit(), D.getType(), this);
186
187  // If constant emission failed, then this should be a C++ static
188  // initializer.
189  if (!Init) {
190    if (!getContext().getLangOptions().CPlusPlus)
191      CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
192    else if (Builder.GetInsertBlock()) {
193      // Since we have a static initializer, this global variable can't
194      // be constant.
195      GV->setConstant(false);
196
197      EmitCXXStaticLocalInit(D, GV);
198    }
199    return GV;
200  }
201
202  // The initializer may differ in type from the global. Rewrite
203  // the global to match the initializer.  (We have to do this
204  // because some types, like unions, can't be completely represented
205  // in the LLVM type system.)
206  if (GV->getType()->getElementType() != Init->getType()) {
207    llvm::GlobalVariable *OldGV = GV;
208
209    GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
210                                  OldGV->isConstant(),
211                                  OldGV->getLinkage(), Init, "",
212                                  0, D.isThreadSpecified(),
213                                  D.getType().getAddressSpace());
214
215    // Steal the name of the old global
216    GV->takeName(OldGV);
217
218    // Replace all uses of the old global with the new global
219    llvm::Constant *NewPtrForOldDecl =
220    llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
221    OldGV->replaceAllUsesWith(NewPtrForOldDecl);
222
223    // Erase the old global, since it is no longer used.
224    OldGV->eraseFromParent();
225  }
226
227  GV->setInitializer(Init);
228  return GV;
229}
230
231void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
232                                      llvm::GlobalValue::LinkageTypes Linkage) {
233  llvm::Value *&DMEntry = LocalDeclMap[&D];
234  assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
235
236  llvm::GlobalVariable *GV = CreateStaticVarDecl(D, ".", Linkage);
237
238  // Store into LocalDeclMap before generating initializer to handle
239  // circular references.
240  DMEntry = GV;
241
242  // We can't have a VLA here, but we can have a pointer to a VLA,
243  // even though that doesn't really make any sense.
244  // Make sure to evaluate VLA bounds now so that we have them for later.
245  if (D.getType()->isVariablyModifiedType())
246    EmitVLASize(D.getType());
247
248  // Local static block variables must be treated as globals as they may be
249  // referenced in their RHS initializer block-literal expresion.
250  CGM.setStaticLocalDeclAddress(&D, GV);
251
252  // If this value has an initializer, emit it.
253  if (D.getInit())
254    GV = AddInitializerToStaticVarDecl(D, GV);
255
256  GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
257
258  // FIXME: Merge attribute handling.
259  if (const AnnotateAttr *AA = D.getAttr<AnnotateAttr>()) {
260    SourceManager &SM = CGM.getContext().getSourceManager();
261    llvm::Constant *Ann =
262      CGM.EmitAnnotateAttr(GV, AA,
263                           SM.getInstantiationLineNumber(D.getLocation()));
264    CGM.AddAnnotation(Ann);
265  }
266
267  if (const SectionAttr *SA = D.getAttr<SectionAttr>())
268    GV->setSection(SA->getName());
269
270  if (D.hasAttr<UsedAttr>())
271    CGM.AddUsedGlobal(GV);
272
273  // We may have to cast the constant because of the initializer
274  // mismatch above.
275  //
276  // FIXME: It is really dangerous to store this in the map; if anyone
277  // RAUW's the GV uses of this constant will be invalid.
278  const llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(D.getType());
279  const llvm::Type *LPtrTy =
280    llvm::PointerType::get(LTy, D.getType().getAddressSpace());
281  DMEntry = llvm::ConstantExpr::getBitCast(GV, LPtrTy);
282
283  // Emit global variable debug descriptor for static vars.
284  CGDebugInfo *DI = getDebugInfo();
285  if (DI) {
286    DI->setLocation(D.getLocation());
287    DI->EmitGlobalVariable(static_cast<llvm::GlobalVariable *>(GV), &D);
288  }
289}
290
291unsigned CodeGenFunction::getByRefValueLLVMField(const ValueDecl *VD) const {
292  assert(ByRefValueInfo.count(VD) && "Did not find value!");
293
294  return ByRefValueInfo.find(VD)->second.second;
295}
296
297/// BuildByRefType - This routine changes a __block variable declared as T x
298///   into:
299///
300///      struct {
301///        void *__isa;
302///        void *__forwarding;
303///        int32_t __flags;
304///        int32_t __size;
305///        void *__copy_helper;       // only if needed
306///        void *__destroy_helper;    // only if needed
307///        char padding[X];           // only if needed
308///        T x;
309///      } x
310///
311const llvm::Type *CodeGenFunction::BuildByRefType(const ValueDecl *D) {
312  std::pair<const llvm::Type *, unsigned> &Info = ByRefValueInfo[D];
313  if (Info.first)
314    return Info.first;
315
316  QualType Ty = D->getType();
317
318  std::vector<const llvm::Type *> Types;
319
320  const llvm::PointerType *Int8PtrTy = llvm::Type::getInt8PtrTy(VMContext);
321
322  llvm::PATypeHolder ByRefTypeHolder = llvm::OpaqueType::get(VMContext);
323
324  // void *__isa;
325  Types.push_back(Int8PtrTy);
326
327  // void *__forwarding;
328  Types.push_back(llvm::PointerType::getUnqual(ByRefTypeHolder));
329
330  // int32_t __flags;
331  Types.push_back(Int32Ty);
332
333  // int32_t __size;
334  Types.push_back(Int32Ty);
335
336  bool HasCopyAndDispose = BlockRequiresCopying(Ty);
337  if (HasCopyAndDispose) {
338    /// void *__copy_helper;
339    Types.push_back(Int8PtrTy);
340
341    /// void *__destroy_helper;
342    Types.push_back(Int8PtrTy);
343  }
344
345  bool Packed = false;
346  CharUnits Align = getContext().getDeclAlign(D);
347  if (Align > CharUnits::fromQuantity(Target.getPointerAlign(0) / 8)) {
348    // We have to insert padding.
349
350    // The struct above has 2 32-bit integers.
351    unsigned CurrentOffsetInBytes = 4 * 2;
352
353    // And either 2 or 4 pointers.
354    CurrentOffsetInBytes += (HasCopyAndDispose ? 4 : 2) *
355      CGM.getTargetData().getTypeAllocSize(Int8PtrTy);
356
357    // Align the offset.
358    unsigned AlignedOffsetInBytes =
359      llvm::RoundUpToAlignment(CurrentOffsetInBytes, Align.getQuantity());
360
361    unsigned NumPaddingBytes = AlignedOffsetInBytes - CurrentOffsetInBytes;
362    if (NumPaddingBytes > 0) {
363      const llvm::Type *Ty = llvm::Type::getInt8Ty(VMContext);
364      // FIXME: We need a sema error for alignment larger than the minimum of
365      // the maximal stack alignmint and the alignment of malloc on the system.
366      if (NumPaddingBytes > 1)
367        Ty = llvm::ArrayType::get(Ty, NumPaddingBytes);
368
369      Types.push_back(Ty);
370
371      // We want a packed struct.
372      Packed = true;
373    }
374  }
375
376  // T x;
377  Types.push_back(ConvertTypeForMem(Ty));
378
379  const llvm::Type *T = llvm::StructType::get(VMContext, Types, Packed);
380
381  cast<llvm::OpaqueType>(ByRefTypeHolder.get())->refineAbstractTypeTo(T);
382  CGM.getModule().addTypeName("struct.__block_byref_" + D->getNameAsString(),
383                              ByRefTypeHolder.get());
384
385  Info.first = ByRefTypeHolder.get();
386
387  Info.second = Types.size() - 1;
388
389  return Info.first;
390}
391
392namespace {
393  struct CallArrayDtor : EHScopeStack::Cleanup {
394    CallArrayDtor(const CXXDestructorDecl *Dtor,
395                  const ConstantArrayType *Type,
396                  llvm::Value *Loc)
397      : Dtor(Dtor), Type(Type), Loc(Loc) {}
398
399    const CXXDestructorDecl *Dtor;
400    const ConstantArrayType *Type;
401    llvm::Value *Loc;
402
403    void Emit(CodeGenFunction &CGF, bool IsForEH) {
404      QualType BaseElementTy = CGF.getContext().getBaseElementType(Type);
405      const llvm::Type *BasePtr = CGF.ConvertType(BaseElementTy);
406      BasePtr = llvm::PointerType::getUnqual(BasePtr);
407      llvm::Value *BaseAddrPtr = CGF.Builder.CreateBitCast(Loc, BasePtr);
408      CGF.EmitCXXAggrDestructorCall(Dtor, Type, BaseAddrPtr);
409    }
410  };
411
412  struct CallVarDtor : EHScopeStack::Cleanup {
413    CallVarDtor(const CXXDestructorDecl *Dtor,
414                llvm::Value *NRVOFlag,
415                llvm::Value *Loc)
416      : Dtor(Dtor), NRVOFlag(NRVOFlag), Loc(Loc) {}
417
418    const CXXDestructorDecl *Dtor;
419    llvm::Value *NRVOFlag;
420    llvm::Value *Loc;
421
422    void Emit(CodeGenFunction &CGF, bool IsForEH) {
423      // Along the exceptions path we always execute the dtor.
424      bool NRVO = !IsForEH && NRVOFlag;
425
426      llvm::BasicBlock *SkipDtorBB = 0;
427      if (NRVO) {
428        // If we exited via NRVO, we skip the destructor call.
429        llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
430        SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
431        llvm::Value *DidNRVO = CGF.Builder.CreateLoad(NRVOFlag, "nrvo.val");
432        CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
433        CGF.EmitBlock(RunDtorBB);
434      }
435
436      CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
437                                /*ForVirtualBase=*/false, Loc);
438
439      if (NRVO) CGF.EmitBlock(SkipDtorBB);
440    }
441  };
442}
443
444namespace {
445  struct CallStackRestore : EHScopeStack::Cleanup {
446    llvm::Value *Stack;
447    CallStackRestore(llvm::Value *Stack) : Stack(Stack) {}
448    void Emit(CodeGenFunction &CGF, bool IsForEH) {
449      llvm::Value *V = CGF.Builder.CreateLoad(Stack, "tmp");
450      llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
451      CGF.Builder.CreateCall(F, V);
452    }
453  };
454
455  struct CallCleanupFunction : EHScopeStack::Cleanup {
456    llvm::Constant *CleanupFn;
457    const CGFunctionInfo &FnInfo;
458    llvm::Value *Addr;
459    const VarDecl &Var;
460
461    CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
462                        llvm::Value *Addr, const VarDecl *Var)
463      : CleanupFn(CleanupFn), FnInfo(*Info), Addr(Addr), Var(*Var) {}
464
465    void Emit(CodeGenFunction &CGF, bool IsForEH) {
466      // In some cases, the type of the function argument will be different from
467      // the type of the pointer. An example of this is
468      // void f(void* arg);
469      // __attribute__((cleanup(f))) void *g;
470      //
471      // To fix this we insert a bitcast here.
472      QualType ArgTy = FnInfo.arg_begin()->type;
473      llvm::Value *Arg =
474        CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
475
476      CallArgList Args;
477      Args.push_back(std::make_pair(RValue::get(Arg),
478                            CGF.getContext().getPointerType(Var.getType())));
479      CGF.EmitCall(FnInfo, CleanupFn, ReturnValueSlot(), Args);
480    }
481  };
482
483  struct CallBlockRelease : EHScopeStack::Cleanup {
484    llvm::Value *Addr;
485    CallBlockRelease(llvm::Value *Addr) : Addr(Addr) {}
486
487    void Emit(CodeGenFunction &CGF, bool IsForEH) {
488      llvm::Value *V = CGF.Builder.CreateStructGEP(Addr, 1, "forwarding");
489      V = CGF.Builder.CreateLoad(V);
490      CGF.BuildBlockRelease(V);
491    }
492  };
493}
494
495/// EmitLocalVarDecl - Emit code and set up an entry in LocalDeclMap for a
496/// variable declaration with auto, register, or no storage class specifier.
497/// These turn into simple stack objects, or GlobalValues depending on target.
498void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D,
499                                      SpecialInitFn *SpecialInit) {
500  QualType Ty = D.getType();
501  unsigned Alignment = getContext().getDeclAlign(&D).getQuantity();
502  bool isByRef = D.hasAttr<BlocksAttr>();
503  bool needsDispose = false;
504  CharUnits Align = CharUnits::Zero();
505  bool IsSimpleConstantInitializer = false;
506
507  bool NRVO = false;
508  llvm::Value *NRVOFlag = 0;
509  llvm::Value *DeclPtr;
510  if (Ty->isConstantSizeType()) {
511    if (!Target.useGlobalsForAutomaticVariables()) {
512      NRVO = getContext().getLangOptions().ElideConstructors &&
513             D.isNRVOVariable();
514      // If this value is an array or struct, is POD, and if the initializer is
515      // a staticly determinable constant, try to optimize it (unless the NRVO
516      // is already optimizing this).
517      if (!NRVO && D.getInit() && !isByRef &&
518          (Ty->isArrayType() || Ty->isRecordType()) &&
519          Ty->isPODType() &&
520          D.getInit()->isConstantInitializer(getContext(), false)) {
521        // If this variable is marked 'const', emit the value as a global.
522        if (CGM.getCodeGenOpts().MergeAllConstants &&
523            Ty.isConstant(getContext())) {
524          EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
525          return;
526        }
527
528        IsSimpleConstantInitializer = true;
529      }
530
531      // A normal fixed sized variable becomes an alloca in the entry block,
532      // unless it's an NRVO variable.
533      const llvm::Type *LTy = ConvertTypeForMem(Ty);
534
535      if (NRVO) {
536        // The named return value optimization: allocate this variable in the
537        // return slot, so that we can elide the copy when returning this
538        // variable (C++0x [class.copy]p34).
539        DeclPtr = ReturnValue;
540
541        if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
542          if (!cast<CXXRecordDecl>(RecordTy->getDecl())->hasTrivialDestructor()) {
543            // Create a flag that is used to indicate when the NRVO was applied
544            // to this variable. Set it to zero to indicate that NRVO was not
545            // applied.
546            const llvm::Type *BoolTy = llvm::Type::getInt1Ty(VMContext);
547            llvm::Value *Zero = llvm::ConstantInt::get(BoolTy, 0);
548            NRVOFlag = CreateTempAlloca(BoolTy, "nrvo");
549            Builder.CreateStore(Zero, NRVOFlag);
550
551            // Record the NRVO flag for this variable.
552            NRVOFlags[&D] = NRVOFlag;
553          }
554        }
555      } else {
556        if (isByRef)
557          LTy = BuildByRefType(&D);
558
559        llvm::AllocaInst *Alloc = CreateTempAlloca(LTy);
560        Alloc->setName(D.getNameAsString());
561
562        Align = getContext().getDeclAlign(&D);
563        if (isByRef)
564          Align = std::max(Align,
565              CharUnits::fromQuantity(Target.getPointerAlign(0) / 8));
566        Alloc->setAlignment(Align.getQuantity());
567        DeclPtr = Alloc;
568      }
569    } else {
570      // Targets that don't support recursion emit locals as globals.
571      const char *Class =
572        D.getStorageClass() == SC_Register ? ".reg." : ".auto.";
573      DeclPtr = CreateStaticVarDecl(D, Class,
574                                    llvm::GlobalValue::InternalLinkage);
575    }
576
577    // FIXME: Can this happen?
578    if (Ty->isVariablyModifiedType())
579      EmitVLASize(Ty);
580  } else {
581    EnsureInsertPoint();
582
583    if (!DidCallStackSave) {
584      // Save the stack.
585      const llvm::Type *LTy = llvm::Type::getInt8PtrTy(VMContext);
586      llvm::Value *Stack = CreateTempAlloca(LTy, "saved_stack");
587
588      llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
589      llvm::Value *V = Builder.CreateCall(F);
590
591      Builder.CreateStore(V, Stack);
592
593      DidCallStackSave = true;
594
595      // Push a cleanup block and restore the stack there.
596      EHStack.pushCleanup<CallStackRestore>(NormalCleanup, Stack);
597    }
598
599    // Get the element type.
600    const llvm::Type *LElemTy = ConvertTypeForMem(Ty);
601    const llvm::Type *LElemPtrTy =
602      llvm::PointerType::get(LElemTy, Ty.getAddressSpace());
603
604    llvm::Value *VLASize = EmitVLASize(Ty);
605
606    // Allocate memory for the array.
607    llvm::AllocaInst *VLA =
608      Builder.CreateAlloca(llvm::Type::getInt8Ty(VMContext), VLASize, "vla");
609    VLA->setAlignment(getContext().getDeclAlign(&D).getQuantity());
610
611    DeclPtr = Builder.CreateBitCast(VLA, LElemPtrTy, "tmp");
612  }
613
614  llvm::Value *&DMEntry = LocalDeclMap[&D];
615  assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
616  DMEntry = DeclPtr;
617
618  // Emit debug info for local var declaration.
619  if (CGDebugInfo *DI = getDebugInfo()) {
620    assert(HaveInsertPoint() && "Unexpected unreachable point!");
621
622    DI->setLocation(D.getLocation());
623    if (Target.useGlobalsForAutomaticVariables()) {
624      DI->EmitGlobalVariable(static_cast<llvm::GlobalVariable *>(DeclPtr), &D);
625    } else
626      DI->EmitDeclareOfAutoVariable(&D, DeclPtr, Builder);
627  }
628
629  // If this local has an initializer, emit it now.
630  const Expr *Init = D.getInit();
631
632  // If we are at an unreachable point, we don't need to emit the initializer
633  // unless it contains a label.
634  if (!HaveInsertPoint()) {
635    if (!ContainsLabel(Init))
636      Init = 0;
637    else
638      EnsureInsertPoint();
639  }
640
641  if (isByRef) {
642    const llvm::PointerType *PtrToInt8Ty = llvm::Type::getInt8PtrTy(VMContext);
643
644    EnsureInsertPoint();
645    llvm::Value *isa_field = Builder.CreateStructGEP(DeclPtr, 0);
646    llvm::Value *forwarding_field = Builder.CreateStructGEP(DeclPtr, 1);
647    llvm::Value *flags_field = Builder.CreateStructGEP(DeclPtr, 2);
648    llvm::Value *size_field = Builder.CreateStructGEP(DeclPtr, 3);
649    llvm::Value *V;
650    int flag = 0;
651    int flags = 0;
652
653    needsDispose = true;
654
655    if (Ty->isBlockPointerType()) {
656      flag |= BLOCK_FIELD_IS_BLOCK;
657      flags |= BLOCK_HAS_COPY_DISPOSE;
658    } else if (BlockRequiresCopying(Ty)) {
659      flag |= BLOCK_FIELD_IS_OBJECT;
660      flags |= BLOCK_HAS_COPY_DISPOSE;
661    }
662
663    // FIXME: Someone double check this.
664    if (Ty.isObjCGCWeak())
665      flag |= BLOCK_FIELD_IS_WEAK;
666
667    int isa = 0;
668    if (flag&BLOCK_FIELD_IS_WEAK)
669      isa = 1;
670    V = llvm::ConstantInt::get(Int32Ty, isa);
671    V = Builder.CreateIntToPtr(V, PtrToInt8Ty, "isa");
672    Builder.CreateStore(V, isa_field);
673
674    Builder.CreateStore(DeclPtr, forwarding_field);
675
676    V = llvm::ConstantInt::get(Int32Ty, flags);
677    Builder.CreateStore(V, flags_field);
678
679    const llvm::Type *V1;
680    V1 = cast<llvm::PointerType>(DeclPtr->getType())->getElementType();
681    V = llvm::ConstantInt::get(Int32Ty,
682                               CGM.GetTargetTypeStoreSize(V1).getQuantity());
683    Builder.CreateStore(V, size_field);
684
685    if (flags & BLOCK_HAS_COPY_DISPOSE) {
686      BlockHasCopyDispose = true;
687      llvm::Value *copy_helper = Builder.CreateStructGEP(DeclPtr, 4);
688      Builder.CreateStore(BuildbyrefCopyHelper(DeclPtr->getType(), flag,
689                                               Align.getQuantity()),
690                          copy_helper);
691
692      llvm::Value *destroy_helper = Builder.CreateStructGEP(DeclPtr, 5);
693      Builder.CreateStore(BuildbyrefDestroyHelper(DeclPtr->getType(), flag,
694                                                  Align.getQuantity()),
695                          destroy_helper);
696    }
697  }
698
699  if (SpecialInit) {
700    SpecialInit(*this, D, DeclPtr);
701  } else if (Init) {
702    llvm::Value *Loc = DeclPtr;
703    if (isByRef)
704      Loc = Builder.CreateStructGEP(DeclPtr, getByRefValueLLVMField(&D),
705                                    D.getNameAsString());
706
707    bool isVolatile = getContext().getCanonicalType(Ty).isVolatileQualified();
708
709    // If the initializer was a simple constant initializer, we can optimize it
710    // in various ways.
711    if (IsSimpleConstantInitializer) {
712      llvm::Constant *Init = CGM.EmitConstantExpr(D.getInit(), Ty,this);
713      assert(Init != 0 && "Wasn't a simple constant init?");
714
715      llvm::Value *AlignVal =
716      llvm::ConstantInt::get(Int32Ty, Align.getQuantity());
717      const llvm::Type *IntPtr =
718      llvm::IntegerType::get(VMContext, LLVMPointerWidth);
719      llvm::Value *SizeVal =
720      llvm::ConstantInt::get(IntPtr,
721                             getContext().getTypeSizeInChars(Ty).getQuantity());
722
723      const llvm::Type *BP = llvm::Type::getInt8PtrTy(VMContext);
724      if (Loc->getType() != BP)
725        Loc = Builder.CreateBitCast(Loc, BP, "tmp");
726
727      llvm::Value *NotVolatile =
728        llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), 0);
729
730      // If the initializer is all zeros, codegen with memset.
731      if (isa<llvm::ConstantAggregateZero>(Init)) {
732        llvm::Value *Zero =
733          llvm::ConstantInt::get(llvm::Type::getInt8Ty(VMContext), 0);
734        Builder.CreateCall5(CGM.getMemSetFn(Loc->getType(), SizeVal->getType()),
735                            Loc, Zero, SizeVal, AlignVal, NotVolatile);
736      } else {
737        // Otherwise, create a temporary global with the initializer then
738        // memcpy from the global to the alloca.
739        std::string Name = GetStaticDeclName(*this, D, ".");
740        llvm::GlobalVariable *GV =
741        new llvm::GlobalVariable(CGM.getModule(), Init->getType(), true,
742                                 llvm::GlobalValue::InternalLinkage,
743                                 Init, Name, 0, false, 0);
744        GV->setAlignment(Align.getQuantity());
745
746        llvm::Value *SrcPtr = GV;
747        if (SrcPtr->getType() != BP)
748          SrcPtr = Builder.CreateBitCast(SrcPtr, BP, "tmp");
749
750        Builder.CreateCall5(CGM.getMemCpyFn(Loc->getType(), SrcPtr->getType(),
751                                            SizeVal->getType()),
752                            Loc, SrcPtr, SizeVal, AlignVal, NotVolatile);
753      }
754    } else if (Ty->isReferenceType()) {
755      RValue RV = EmitReferenceBindingToExpr(Init, &D);
756      EmitStoreOfScalar(RV.getScalarVal(), Loc, false, Alignment, Ty);
757    } else if (!hasAggregateLLVMType(Init->getType())) {
758      llvm::Value *V = EmitScalarExpr(Init);
759      EmitStoreOfScalar(V, Loc, isVolatile, Alignment, Ty);
760    } else if (Init->getType()->isAnyComplexType()) {
761      EmitComplexExprIntoAddr(Init, Loc, isVolatile);
762    } else {
763      EmitAggExpr(Init, AggValueSlot::forAddr(Loc, isVolatile, true));
764    }
765  }
766
767  // Handle CXX destruction of variables.
768  QualType DtorTy(Ty);
769  while (const ArrayType *Array = getContext().getAsArrayType(DtorTy))
770    DtorTy = getContext().getBaseElementType(Array);
771  if (const RecordType *RT = DtorTy->getAs<RecordType>())
772    if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
773      if (!ClassDecl->hasTrivialDestructor()) {
774        // Note: We suppress the destructor call when the corresponding NRVO
775        // flag has been set.
776        llvm::Value *Loc = DeclPtr;
777        if (isByRef)
778          Loc = Builder.CreateStructGEP(DeclPtr, getByRefValueLLVMField(&D),
779                                        D.getNameAsString());
780
781        const CXXDestructorDecl *D = ClassDecl->getDestructor();
782        assert(D && "EmitLocalBlockVarDecl - destructor is nul");
783
784        if (const ConstantArrayType *Array =
785              getContext().getAsConstantArrayType(Ty)) {
786          EHStack.pushCleanup<CallArrayDtor>(NormalAndEHCleanup,
787                                             D, Array, Loc);
788        } else {
789          EHStack.pushCleanup<CallVarDtor>(NormalAndEHCleanup,
790                                           D, NRVOFlag, Loc);
791        }
792      }
793  }
794
795  // Handle the cleanup attribute
796  if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
797    const FunctionDecl *FD = CA->getFunctionDecl();
798
799    llvm::Constant* F = CGM.GetAddrOfFunction(FD);
800    assert(F && "Could not find function!");
801
802    const CGFunctionInfo &Info = CGM.getTypes().getFunctionInfo(FD);
803    EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup,
804                                             F, &Info, DeclPtr, &D);
805  }
806
807  // If this is a block variable, clean it up.
808  if (needsDispose && CGM.getLangOptions().getGCMode() != LangOptions::GCOnly)
809    EHStack.pushCleanup<CallBlockRelease>(NormalAndEHCleanup, DeclPtr);
810}
811
812/// Emit an alloca (or GlobalValue depending on target)
813/// for the specified parameter and set up LocalDeclMap.
814void CodeGenFunction::EmitParmDecl(const VarDecl &D, llvm::Value *Arg) {
815  // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
816  assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
817         "Invalid argument to EmitParmDecl");
818  QualType Ty = D.getType();
819  CanQualType CTy = getContext().getCanonicalType(Ty);
820
821  llvm::Value *DeclPtr;
822  // If this is an aggregate or variable sized value, reuse the input pointer.
823  if (!Ty->isConstantSizeType() ||
824      CodeGenFunction::hasAggregateLLVMType(Ty)) {
825    DeclPtr = Arg;
826  } else {
827    // Otherwise, create a temporary to hold the value.
828    DeclPtr = CreateMemTemp(Ty, D.getName() + ".addr");
829
830    // Store the initial value into the alloca.
831    unsigned Alignment = getContext().getDeclAlign(&D).getQuantity();
832    EmitStoreOfScalar(Arg, DeclPtr, CTy.isVolatileQualified(), Alignment, Ty);
833  }
834  Arg->setName(D.getName());
835
836  llvm::Value *&DMEntry = LocalDeclMap[&D];
837  assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
838  DMEntry = DeclPtr;
839
840  // Emit debug info for param declaration.
841  if (CGDebugInfo *DI = getDebugInfo()) {
842    DI->setLocation(D.getLocation());
843    DI->EmitDeclareOfArgVariable(&D, DeclPtr, Builder);
844  }
845}
846