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