CGDecl.cpp revision 06d43684289bfcf3b2dbaf081aa861f76933d891
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 "CGOpenCLRuntime.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::TypeAliasTemplate:
56  case Decl::TemplateTemplateParm:
57  case Decl::ObjCMethod:
58  case Decl::ObjCCategory:
59  case Decl::ObjCProtocol:
60  case Decl::ObjCInterface:
61  case Decl::ObjCCategoryImpl:
62  case Decl::ObjCImplementation:
63  case Decl::ObjCProperty:
64  case Decl::ObjCCompatibleAlias:
65  case Decl::AccessSpec:
66  case Decl::LinkageSpec:
67  case Decl::ObjCPropertyImpl:
68  case Decl::FileScopeAsm:
69  case Decl::Friend:
70  case Decl::FriendTemplate:
71  case Decl::Block:
72  case Decl::ClassScopeFunctionSpecialization:
73    llvm_unreachable("Declaration 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  case Decl::Import:
86    // None of these decls require codegen support.
87    return;
88
89  case Decl::Var: {
90    const VarDecl &VD = cast<VarDecl>(D);
91    assert(VD.isLocalVarDecl() &&
92           "Should not see file-scope variables inside a function!");
93    return EmitVarDecl(VD);
94  }
95
96  case Decl::Typedef:      // typedef int X;
97  case Decl::TypeAlias: {  // using X = int; [C++0x]
98    const TypedefNameDecl &TD = cast<TypedefNameDecl>(D);
99    QualType Ty = TD.getUnderlyingType();
100
101    if (Ty->isVariablyModifiedType())
102      EmitVariablyModifiedType(Ty);
103  }
104  }
105}
106
107/// EmitVarDecl - This method handles emission of any variable declaration
108/// inside a function, including static vars etc.
109void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
110  switch (D.getStorageClass()) {
111  case SC_None:
112  case SC_Auto:
113  case SC_Register:
114    return EmitAutoVarDecl(D);
115  case SC_Static: {
116    llvm::GlobalValue::LinkageTypes Linkage =
117      llvm::GlobalValue::InternalLinkage;
118
119    // If the function definition has some sort of weak linkage, its
120    // static variables should also be weak so that they get properly
121    // uniqued.  We can't do this in C, though, because there's no
122    // standard way to agree on which variables are the same (i.e.
123    // there's no mangling).
124    if (getContext().getLangOpts().CPlusPlus)
125      if (llvm::GlobalValue::isWeakForLinker(CurFn->getLinkage()))
126        Linkage = CurFn->getLinkage();
127
128    return EmitStaticVarDecl(D, Linkage);
129  }
130  case SC_Extern:
131  case SC_PrivateExtern:
132    // Don't emit it now, allow it to be emitted lazily on its first use.
133    return;
134  case SC_OpenCLWorkGroupLocal:
135    return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D);
136  }
137
138  llvm_unreachable("Unknown storage class");
139}
140
141static std::string GetStaticDeclName(CodeGenFunction &CGF, const VarDecl &D,
142                                     const char *Separator) {
143  CodeGenModule &CGM = CGF.CGM;
144  if (CGF.getContext().getLangOpts().CPlusPlus) {
145    StringRef Name = CGM.getMangledName(&D);
146    return Name.str();
147  }
148
149  std::string ContextName;
150  if (!CGF.CurFuncDecl) {
151    // Better be in a block declared in global scope.
152    const NamedDecl *ND = cast<NamedDecl>(&D);
153    const DeclContext *DC = ND->getDeclContext();
154    if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC)) {
155      MangleBuffer Name;
156      CGM.getBlockMangledName(GlobalDecl(), Name, BD);
157      ContextName = Name.getString();
158    }
159    else
160      llvm_unreachable("Unknown context for block static var decl");
161  } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CGF.CurFuncDecl)) {
162    StringRef Name = CGM.getMangledName(FD);
163    ContextName = Name.str();
164  } else if (isa<ObjCMethodDecl>(CGF.CurFuncDecl))
165    ContextName = CGF.CurFn->getName();
166  else
167    llvm_unreachable("Unknown context for static var decl");
168
169  return ContextName + Separator + D.getNameAsString();
170}
171
172llvm::GlobalVariable *
173CodeGenFunction::CreateStaticVarDecl(const VarDecl &D,
174                                     const char *Separator,
175                                     llvm::GlobalValue::LinkageTypes Linkage) {
176  QualType Ty = D.getType();
177  assert(Ty->isConstantSizeType() && "VLAs can't be static");
178
179  // Use the label if the variable is renamed with the asm-label extension.
180  std::string Name;
181  if (D.hasAttr<AsmLabelAttr>())
182    Name = CGM.getMangledName(&D);
183  else
184    Name = GetStaticDeclName(*this, D, Separator);
185
186  llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(Ty);
187  llvm::GlobalVariable *GV =
188    new llvm::GlobalVariable(CGM.getModule(), LTy,
189                             Ty.isConstant(getContext()), Linkage,
190                             CGM.EmitNullConstant(D.getType()), Name, 0,
191                             llvm::GlobalVariable::NotThreadLocal,
192                             CGM.getContext().getTargetAddressSpace(Ty));
193  GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
194  if (Linkage != llvm::GlobalValue::InternalLinkage)
195    GV->setVisibility(CurFn->getVisibility());
196
197  if (D.isThreadSpecified())
198    CGM.setTLSMode(GV, D);
199
200  return GV;
201}
202
203/// hasNontrivialDestruction - Determine whether a type's destruction is
204/// non-trivial. If so, and the variable uses static initialization, we must
205/// register its destructor to run on exit.
206static bool hasNontrivialDestruction(QualType T) {
207  CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
208  return RD && !RD->hasTrivialDestructor();
209}
210
211/// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
212/// global variable that has already been created for it.  If the initializer
213/// has a different type than GV does, this may free GV and return a different
214/// one.  Otherwise it just returns GV.
215llvm::GlobalVariable *
216CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
217                                               llvm::GlobalVariable *GV) {
218  llvm::Constant *Init = CGM.EmitConstantInit(D, this);
219
220  // If constant emission failed, then this should be a C++ static
221  // initializer.
222  if (!Init) {
223    if (!getContext().getLangOpts().CPlusPlus)
224      CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
225    else if (Builder.GetInsertBlock()) {
226      // Since we have a static initializer, this global variable can't
227      // be constant.
228      GV->setConstant(false);
229
230      EmitCXXGuardedInit(D, GV, /*PerformInit*/true);
231    }
232    return GV;
233  }
234
235  // The initializer may differ in type from the global. Rewrite
236  // the global to match the initializer.  (We have to do this
237  // because some types, like unions, can't be completely represented
238  // in the LLVM type system.)
239  if (GV->getType()->getElementType() != Init->getType()) {
240    llvm::GlobalVariable *OldGV = GV;
241
242    GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
243                                  OldGV->isConstant(),
244                                  OldGV->getLinkage(), Init, "",
245                                  /*InsertBefore*/ OldGV,
246                                  OldGV->getThreadLocalMode(),
247                           CGM.getContext().getTargetAddressSpace(D.getType()));
248    GV->setVisibility(OldGV->getVisibility());
249
250    // Steal the name of the old global
251    GV->takeName(OldGV);
252
253    // Replace all uses of the old global with the new global
254    llvm::Constant *NewPtrForOldDecl =
255    llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
256    OldGV->replaceAllUsesWith(NewPtrForOldDecl);
257
258    // Erase the old global, since it is no longer used.
259    OldGV->eraseFromParent();
260  }
261
262  GV->setConstant(CGM.isTypeConstant(D.getType(), true));
263  GV->setInitializer(Init);
264
265  if (hasNontrivialDestruction(D.getType())) {
266    // We have a constant initializer, but a nontrivial destructor. We still
267    // need to perform a guarded "initialization" in order to register the
268    // destructor.
269    EmitCXXGuardedInit(D, GV, /*PerformInit*/false);
270  }
271
272  return GV;
273}
274
275void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
276                                      llvm::GlobalValue::LinkageTypes Linkage) {
277  llvm::Value *&DMEntry = LocalDeclMap[&D];
278  assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
279
280  // Check to see if we already have a global variable for this
281  // declaration.  This can happen when double-emitting function
282  // bodies, e.g. with complete and base constructors.
283  llvm::Constant *addr =
284    CGM.getStaticLocalDeclAddress(&D);
285
286  llvm::GlobalVariable *var;
287  if (addr) {
288    var = cast<llvm::GlobalVariable>(addr->stripPointerCasts());
289  } else {
290    addr = var = CreateStaticVarDecl(D, ".", Linkage);
291  }
292
293  // Store into LocalDeclMap before generating initializer to handle
294  // circular references.
295  DMEntry = addr;
296  CGM.setStaticLocalDeclAddress(&D, addr);
297
298  // We can't have a VLA here, but we can have a pointer to a VLA,
299  // even though that doesn't really make any sense.
300  // Make sure to evaluate VLA bounds now so that we have them for later.
301  if (D.getType()->isVariablyModifiedType())
302    EmitVariablyModifiedType(D.getType());
303
304  // Save the type in case adding the initializer forces a type change.
305  llvm::Type *expectedType = addr->getType();
306
307  // If this value has an initializer, emit it.
308  if (D.getInit())
309    var = AddInitializerToStaticVarDecl(D, var);
310
311  var->setAlignment(getContext().getDeclAlign(&D).getQuantity());
312
313  if (D.hasAttr<AnnotateAttr>())
314    CGM.AddGlobalAnnotations(&D, var);
315
316  if (const SectionAttr *SA = D.getAttr<SectionAttr>())
317    var->setSection(SA->getName());
318
319  if (D.hasAttr<UsedAttr>())
320    CGM.AddUsedGlobal(var);
321
322  // We may have to cast the constant because of the initializer
323  // mismatch above.
324  //
325  // FIXME: It is really dangerous to store this in the map; if anyone
326  // RAUW's the GV uses of this constant will be invalid.
327  llvm::Constant *castedAddr = llvm::ConstantExpr::getBitCast(var, expectedType);
328  DMEntry = castedAddr;
329  CGM.setStaticLocalDeclAddress(&D, castedAddr);
330
331  // Emit global variable debug descriptor for static vars.
332  CGDebugInfo *DI = getDebugInfo();
333  if (DI &&
334      CGM.getCodeGenOpts().DebugInfo >= CodeGenOptions::LimitedDebugInfo) {
335    DI->setLocation(D.getLocation());
336    DI->EmitGlobalVariable(var, &D);
337  }
338}
339
340namespace {
341  struct DestroyObject : EHScopeStack::Cleanup {
342    DestroyObject(llvm::Value *addr, QualType type,
343                  CodeGenFunction::Destroyer *destroyer,
344                  bool useEHCleanupForArray)
345      : addr(addr), type(type), destroyer(destroyer),
346        useEHCleanupForArray(useEHCleanupForArray) {}
347
348    llvm::Value *addr;
349    QualType type;
350    CodeGenFunction::Destroyer *destroyer;
351    bool useEHCleanupForArray;
352
353    void Emit(CodeGenFunction &CGF, Flags flags) {
354      // Don't use an EH cleanup recursively from an EH cleanup.
355      bool useEHCleanupForArray =
356        flags.isForNormalCleanup() && this->useEHCleanupForArray;
357
358      CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
359    }
360  };
361
362  struct DestroyNRVOVariable : EHScopeStack::Cleanup {
363    DestroyNRVOVariable(llvm::Value *addr,
364                        const CXXDestructorDecl *Dtor,
365                        llvm::Value *NRVOFlag)
366      : Dtor(Dtor), NRVOFlag(NRVOFlag), Loc(addr) {}
367
368    const CXXDestructorDecl *Dtor;
369    llvm::Value *NRVOFlag;
370    llvm::Value *Loc;
371
372    void Emit(CodeGenFunction &CGF, Flags flags) {
373      // Along the exceptions path we always execute the dtor.
374      bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
375
376      llvm::BasicBlock *SkipDtorBB = 0;
377      if (NRVO) {
378        // If we exited via NRVO, we skip the destructor call.
379        llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
380        SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
381        llvm::Value *DidNRVO = CGF.Builder.CreateLoad(NRVOFlag, "nrvo.val");
382        CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
383        CGF.EmitBlock(RunDtorBB);
384      }
385
386      CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
387                                /*ForVirtualBase=*/false, Loc);
388
389      if (NRVO) CGF.EmitBlock(SkipDtorBB);
390    }
391  };
392
393  struct CallStackRestore : EHScopeStack::Cleanup {
394    llvm::Value *Stack;
395    CallStackRestore(llvm::Value *Stack) : Stack(Stack) {}
396    void Emit(CodeGenFunction &CGF, Flags flags) {
397      llvm::Value *V = CGF.Builder.CreateLoad(Stack);
398      llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
399      CGF.Builder.CreateCall(F, V);
400    }
401  };
402
403  struct ExtendGCLifetime : EHScopeStack::Cleanup {
404    const VarDecl &Var;
405    ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
406
407    void Emit(CodeGenFunction &CGF, Flags flags) {
408      // Compute the address of the local variable, in case it's a
409      // byref or something.
410      DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
411                      Var.getType(), VK_LValue, SourceLocation());
412      llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE));
413      CGF.EmitExtendGCLifetime(value);
414    }
415  };
416
417  struct CallCleanupFunction : EHScopeStack::Cleanup {
418    llvm::Constant *CleanupFn;
419    const CGFunctionInfo &FnInfo;
420    const VarDecl &Var;
421
422    CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
423                        const VarDecl *Var)
424      : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
425
426    void Emit(CodeGenFunction &CGF, Flags flags) {
427      DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
428                      Var.getType(), VK_LValue, SourceLocation());
429      // Compute the address of the local variable, in case it's a byref
430      // or something.
431      llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getAddress();
432
433      // In some cases, the type of the function argument will be different from
434      // the type of the pointer. An example of this is
435      // void f(void* arg);
436      // __attribute__((cleanup(f))) void *g;
437      //
438      // To fix this we insert a bitcast here.
439      QualType ArgTy = FnInfo.arg_begin()->type;
440      llvm::Value *Arg =
441        CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
442
443      CallArgList Args;
444      Args.add(RValue::get(Arg),
445               CGF.getContext().getPointerType(Var.getType()));
446      CGF.EmitCall(FnInfo, CleanupFn, ReturnValueSlot(), Args);
447    }
448  };
449}
450
451/// EmitAutoVarWithLifetime - Does the setup required for an automatic
452/// variable with lifetime.
453static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
454                                    llvm::Value *addr,
455                                    Qualifiers::ObjCLifetime lifetime) {
456  switch (lifetime) {
457  case Qualifiers::OCL_None:
458    llvm_unreachable("present but none");
459
460  case Qualifiers::OCL_ExplicitNone:
461    // nothing to do
462    break;
463
464  case Qualifiers::OCL_Strong: {
465    CodeGenFunction::Destroyer *destroyer =
466      (var.hasAttr<ObjCPreciseLifetimeAttr>()
467       ? CodeGenFunction::destroyARCStrongPrecise
468       : CodeGenFunction::destroyARCStrongImprecise);
469
470    CleanupKind cleanupKind = CGF.getARCCleanupKind();
471    CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
472                    cleanupKind & EHCleanup);
473    break;
474  }
475  case Qualifiers::OCL_Autoreleasing:
476    // nothing to do
477    break;
478
479  case Qualifiers::OCL_Weak:
480    // __weak objects always get EH cleanups; otherwise, exceptions
481    // could cause really nasty crashes instead of mere leaks.
482    CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
483                    CodeGenFunction::destroyARCWeak,
484                    /*useEHCleanup*/ true);
485    break;
486  }
487}
488
489static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
490  if (const Expr *e = dyn_cast<Expr>(s)) {
491    // Skip the most common kinds of expressions that make
492    // hierarchy-walking expensive.
493    s = e = e->IgnoreParenCasts();
494
495    if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
496      return (ref->getDecl() == &var);
497    if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
498      const BlockDecl *block = be->getBlockDecl();
499      for (BlockDecl::capture_const_iterator i = block->capture_begin(),
500           e = block->capture_end(); i != e; ++i) {
501        if (i->getVariable() == &var)
502          return true;
503      }
504    }
505  }
506
507  for (Stmt::const_child_range children = s->children(); children; ++children)
508    // children might be null; as in missing decl or conditional of an if-stmt.
509    if ((*children) && isAccessedBy(var, *children))
510      return true;
511
512  return false;
513}
514
515static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
516  if (!decl) return false;
517  if (!isa<VarDecl>(decl)) return false;
518  const VarDecl *var = cast<VarDecl>(decl);
519  return isAccessedBy(*var, e);
520}
521
522static void drillIntoBlockVariable(CodeGenFunction &CGF,
523                                   LValue &lvalue,
524                                   const VarDecl *var) {
525  lvalue.setAddress(CGF.BuildBlockByrefAddress(lvalue.getAddress(), var));
526}
527
528void CodeGenFunction::EmitScalarInit(const Expr *init,
529                                     const ValueDecl *D,
530                                     LValue lvalue,
531                                     bool capturedByInit) {
532  Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
533  if (!lifetime) {
534    llvm::Value *value = EmitScalarExpr(init);
535    if (capturedByInit)
536      drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
537    EmitStoreThroughLValue(RValue::get(value), lvalue, true);
538    return;
539  }
540
541  // If we're emitting a value with lifetime, we have to do the
542  // initialization *before* we leave the cleanup scopes.
543  if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(init)) {
544    enterFullExpression(ewc);
545    init = ewc->getSubExpr();
546  }
547  CodeGenFunction::RunCleanupsScope Scope(*this);
548
549  // We have to maintain the illusion that the variable is
550  // zero-initialized.  If the variable might be accessed in its
551  // initializer, zero-initialize before running the initializer, then
552  // actually perform the initialization with an assign.
553  bool accessedByInit = false;
554  if (lifetime != Qualifiers::OCL_ExplicitNone)
555    accessedByInit = (capturedByInit || isAccessedBy(D, init));
556  if (accessedByInit) {
557    LValue tempLV = lvalue;
558    // Drill down to the __block object if necessary.
559    if (capturedByInit) {
560      // We can use a simple GEP for this because it can't have been
561      // moved yet.
562      tempLV.setAddress(Builder.CreateStructGEP(tempLV.getAddress(),
563                                   getByRefValueLLVMField(cast<VarDecl>(D))));
564    }
565
566    llvm::PointerType *ty
567      = cast<llvm::PointerType>(tempLV.getAddress()->getType());
568    ty = cast<llvm::PointerType>(ty->getElementType());
569
570    llvm::Value *zero = llvm::ConstantPointerNull::get(ty);
571
572    // If __weak, we want to use a barrier under certain conditions.
573    if (lifetime == Qualifiers::OCL_Weak)
574      EmitARCInitWeak(tempLV.getAddress(), zero);
575
576    // Otherwise just do a simple store.
577    else
578      EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
579  }
580
581  // Emit the initializer.
582  llvm::Value *value = 0;
583
584  switch (lifetime) {
585  case Qualifiers::OCL_None:
586    llvm_unreachable("present but none");
587
588  case Qualifiers::OCL_ExplicitNone:
589    // nothing to do
590    value = EmitScalarExpr(init);
591    break;
592
593  case Qualifiers::OCL_Strong: {
594    value = EmitARCRetainScalarExpr(init);
595    break;
596  }
597
598  case Qualifiers::OCL_Weak: {
599    // No way to optimize a producing initializer into this.  It's not
600    // worth optimizing for, because the value will immediately
601    // disappear in the common case.
602    value = EmitScalarExpr(init);
603
604    if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
605    if (accessedByInit)
606      EmitARCStoreWeak(lvalue.getAddress(), value, /*ignored*/ true);
607    else
608      EmitARCInitWeak(lvalue.getAddress(), value);
609    return;
610  }
611
612  case Qualifiers::OCL_Autoreleasing:
613    value = EmitARCRetainAutoreleaseScalarExpr(init);
614    break;
615  }
616
617  if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
618
619  // If the variable might have been accessed by its initializer, we
620  // might have to initialize with a barrier.  We have to do this for
621  // both __weak and __strong, but __weak got filtered out above.
622  if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
623    llvm::Value *oldValue = EmitLoadOfScalar(lvalue);
624    EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
625    EmitARCRelease(oldValue, /*precise*/ false);
626    return;
627  }
628
629  EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
630}
631
632/// EmitScalarInit - Initialize the given lvalue with the given object.
633void CodeGenFunction::EmitScalarInit(llvm::Value *init, LValue lvalue) {
634  Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
635  if (!lifetime)
636    return EmitStoreThroughLValue(RValue::get(init), lvalue, true);
637
638  switch (lifetime) {
639  case Qualifiers::OCL_None:
640    llvm_unreachable("present but none");
641
642  case Qualifiers::OCL_ExplicitNone:
643    // nothing to do
644    break;
645
646  case Qualifiers::OCL_Strong:
647    init = EmitARCRetain(lvalue.getType(), init);
648    break;
649
650  case Qualifiers::OCL_Weak:
651    // Initialize and then skip the primitive store.
652    EmitARCInitWeak(lvalue.getAddress(), init);
653    return;
654
655  case Qualifiers::OCL_Autoreleasing:
656    init = EmitARCRetainAutorelease(lvalue.getType(), init);
657    break;
658  }
659
660  EmitStoreOfScalar(init, lvalue, /* isInitialization */ true);
661}
662
663/// canEmitInitWithFewStoresAfterMemset - Decide whether we can emit the
664/// non-zero parts of the specified initializer with equal or fewer than
665/// NumStores scalar stores.
666static bool canEmitInitWithFewStoresAfterMemset(llvm::Constant *Init,
667                                                unsigned &NumStores) {
668  // Zero and Undef never requires any extra stores.
669  if (isa<llvm::ConstantAggregateZero>(Init) ||
670      isa<llvm::ConstantPointerNull>(Init) ||
671      isa<llvm::UndefValue>(Init))
672    return true;
673  if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
674      isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
675      isa<llvm::ConstantExpr>(Init))
676    return Init->isNullValue() || NumStores--;
677
678  // See if we can emit each element.
679  if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
680    for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
681      llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
682      if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
683        return false;
684    }
685    return true;
686  }
687
688  if (llvm::ConstantDataSequential *CDS =
689        dyn_cast<llvm::ConstantDataSequential>(Init)) {
690    for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
691      llvm::Constant *Elt = CDS->getElementAsConstant(i);
692      if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
693        return false;
694    }
695    return true;
696  }
697
698  // Anything else is hard and scary.
699  return false;
700}
701
702/// emitStoresForInitAfterMemset - For inits that
703/// canEmitInitWithFewStoresAfterMemset returned true for, emit the scalar
704/// stores that would be required.
705static void emitStoresForInitAfterMemset(llvm::Constant *Init, llvm::Value *Loc,
706                                         bool isVolatile, CGBuilderTy &Builder) {
707  assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) &&
708         "called emitStoresForInitAfterMemset for zero or undef value.");
709
710  if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
711      isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
712      isa<llvm::ConstantExpr>(Init)) {
713    Builder.CreateStore(Init, Loc, isVolatile);
714    return;
715  }
716
717  if (llvm::ConstantDataSequential *CDS =
718        dyn_cast<llvm::ConstantDataSequential>(Init)) {
719    for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
720      llvm::Constant *Elt = CDS->getElementAsConstant(i);
721
722      // If necessary, get a pointer to the element and emit it.
723      if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
724        emitStoresForInitAfterMemset(Elt, Builder.CreateConstGEP2_32(Loc, 0, i),
725                                     isVolatile, Builder);
726    }
727    return;
728  }
729
730  assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
731         "Unknown value type!");
732
733  for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
734    llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
735
736    // If necessary, get a pointer to the element and emit it.
737    if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
738      emitStoresForInitAfterMemset(Elt, Builder.CreateConstGEP2_32(Loc, 0, i),
739                                   isVolatile, Builder);
740  }
741}
742
743
744/// shouldUseMemSetPlusStoresToInitialize - Decide whether we should use memset
745/// plus some stores to initialize a local variable instead of using a memcpy
746/// from a constant global.  It is beneficial to use memset if the global is all
747/// zeros, or mostly zeros and large.
748static bool shouldUseMemSetPlusStoresToInitialize(llvm::Constant *Init,
749                                                  uint64_t GlobalSize) {
750  // If a global is all zeros, always use a memset.
751  if (isa<llvm::ConstantAggregateZero>(Init)) return true;
752
753
754  // If a non-zero global is <= 32 bytes, always use a memcpy.  If it is large,
755  // do it if it will require 6 or fewer scalar stores.
756  // TODO: Should budget depends on the size?  Avoiding a large global warrants
757  // plopping in more stores.
758  unsigned StoreBudget = 6;
759  uint64_t SizeLimit = 32;
760
761  return GlobalSize > SizeLimit &&
762         canEmitInitWithFewStoresAfterMemset(Init, StoreBudget);
763}
764
765
766/// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
767/// variable declaration with auto, register, or no storage class specifier.
768/// These turn into simple stack objects, or GlobalValues depending on target.
769void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
770  AutoVarEmission emission = EmitAutoVarAlloca(D);
771  EmitAutoVarInit(emission);
772  EmitAutoVarCleanups(emission);
773}
774
775/// EmitAutoVarAlloca - Emit the alloca and debug information for a
776/// local variable.  Does not emit initalization or destruction.
777CodeGenFunction::AutoVarEmission
778CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
779  QualType Ty = D.getType();
780
781  AutoVarEmission emission(D);
782
783  bool isByRef = D.hasAttr<BlocksAttr>();
784  emission.IsByRef = isByRef;
785
786  CharUnits alignment = getContext().getDeclAlign(&D);
787  emission.Alignment = alignment;
788
789  // If the type is variably-modified, emit all the VLA sizes for it.
790  if (Ty->isVariablyModifiedType())
791    EmitVariablyModifiedType(Ty);
792
793  llvm::Value *DeclPtr;
794  if (Ty->isConstantSizeType()) {
795    if (!Target.useGlobalsForAutomaticVariables()) {
796      bool NRVO = getContext().getLangOpts().ElideConstructors &&
797                  D.isNRVOVariable();
798
799      // If this value is a POD array or struct with a statically
800      // determinable constant initializer, there are optimizations we can do.
801      //
802      // TODO: We should constant-evaluate the initializer of any variable,
803      // as long as it is initialized by a constant expression. Currently,
804      // isConstantInitializer produces wrong answers for structs with
805      // reference or bitfield members, and a few other cases, and checking
806      // for POD-ness protects us from some of these.
807      if (D.getInit() &&
808          (Ty->isArrayType() || Ty->isRecordType()) &&
809          (Ty.isPODType(getContext()) ||
810           getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
811          D.getInit()->isConstantInitializer(getContext(), false)) {
812
813        // If the variable's a const type, and it's neither an NRVO
814        // candidate nor a __block variable and has no mutable members,
815        // emit it as a global instead.
816        if (CGM.getCodeGenOpts().MergeAllConstants && !NRVO && !isByRef &&
817            CGM.isTypeConstant(Ty, true)) {
818          EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
819
820          emission.Address = 0; // signal this condition to later callbacks
821          assert(emission.wasEmittedAsGlobal());
822          return emission;
823        }
824
825        // Otherwise, tell the initialization code that we're in this case.
826        emission.IsConstantAggregate = true;
827      }
828
829      // A normal fixed sized variable becomes an alloca in the entry block,
830      // unless it's an NRVO variable.
831      llvm::Type *LTy = ConvertTypeForMem(Ty);
832
833      if (NRVO) {
834        // The named return value optimization: allocate this variable in the
835        // return slot, so that we can elide the copy when returning this
836        // variable (C++0x [class.copy]p34).
837        DeclPtr = ReturnValue;
838
839        if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
840          if (!cast<CXXRecordDecl>(RecordTy->getDecl())->hasTrivialDestructor()) {
841            // Create a flag that is used to indicate when the NRVO was applied
842            // to this variable. Set it to zero to indicate that NRVO was not
843            // applied.
844            llvm::Value *Zero = Builder.getFalse();
845            llvm::Value *NRVOFlag = CreateTempAlloca(Zero->getType(), "nrvo");
846            EnsureInsertPoint();
847            Builder.CreateStore(Zero, NRVOFlag);
848
849            // Record the NRVO flag for this variable.
850            NRVOFlags[&D] = NRVOFlag;
851            emission.NRVOFlag = NRVOFlag;
852          }
853        }
854      } else {
855        if (isByRef)
856          LTy = BuildByRefType(&D);
857
858        llvm::AllocaInst *Alloc = CreateTempAlloca(LTy);
859        Alloc->setName(D.getName());
860
861        CharUnits allocaAlignment = alignment;
862        if (isByRef)
863          allocaAlignment = std::max(allocaAlignment,
864              getContext().toCharUnitsFromBits(Target.getPointerAlign(0)));
865        Alloc->setAlignment(allocaAlignment.getQuantity());
866        DeclPtr = Alloc;
867      }
868    } else {
869      // Targets that don't support recursion emit locals as globals.
870      const char *Class =
871        D.getStorageClass() == SC_Register ? ".reg." : ".auto.";
872      DeclPtr = CreateStaticVarDecl(D, Class,
873                                    llvm::GlobalValue::InternalLinkage);
874    }
875  } else {
876    EnsureInsertPoint();
877
878    if (!DidCallStackSave) {
879      // Save the stack.
880      llvm::Value *Stack = CreateTempAlloca(Int8PtrTy, "saved_stack");
881
882      llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
883      llvm::Value *V = Builder.CreateCall(F);
884
885      Builder.CreateStore(V, Stack);
886
887      DidCallStackSave = true;
888
889      // Push a cleanup block and restore the stack there.
890      // FIXME: in general circumstances, this should be an EH cleanup.
891      EHStack.pushCleanup<CallStackRestore>(NormalCleanup, Stack);
892    }
893
894    llvm::Value *elementCount;
895    QualType elementType;
896    llvm::tie(elementCount, elementType) = getVLASize(Ty);
897
898    llvm::Type *llvmTy = ConvertTypeForMem(elementType);
899
900    // Allocate memory for the array.
901    llvm::AllocaInst *vla = Builder.CreateAlloca(llvmTy, elementCount, "vla");
902    vla->setAlignment(alignment.getQuantity());
903
904    DeclPtr = vla;
905  }
906
907  llvm::Value *&DMEntry = LocalDeclMap[&D];
908  assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
909  DMEntry = DeclPtr;
910  emission.Address = DeclPtr;
911
912  // Emit debug info for local var declaration.
913  if (HaveInsertPoint())
914    if (CGDebugInfo *DI = getDebugInfo()) {
915      if (CGM.getCodeGenOpts().DebugInfo >= CodeGenOptions::LimitedDebugInfo) {
916        DI->setLocation(D.getLocation());
917        if (Target.useGlobalsForAutomaticVariables()) {
918          DI->EmitGlobalVariable(static_cast<llvm::GlobalVariable *>(DeclPtr),
919                                 &D);
920        } else
921          DI->EmitDeclareOfAutoVariable(&D, DeclPtr, Builder);
922      }
923    }
924
925  if (D.hasAttr<AnnotateAttr>())
926      EmitVarAnnotations(&D, emission.Address);
927
928  return emission;
929}
930
931/// Determines whether the given __block variable is potentially
932/// captured by the given expression.
933static bool isCapturedBy(const VarDecl &var, const Expr *e) {
934  // Skip the most common kinds of expressions that make
935  // hierarchy-walking expensive.
936  e = e->IgnoreParenCasts();
937
938  if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
939    const BlockDecl *block = be->getBlockDecl();
940    for (BlockDecl::capture_const_iterator i = block->capture_begin(),
941           e = block->capture_end(); i != e; ++i) {
942      if (i->getVariable() == &var)
943        return true;
944    }
945
946    // No need to walk into the subexpressions.
947    return false;
948  }
949
950  if (const StmtExpr *SE = dyn_cast<StmtExpr>(e)) {
951    const CompoundStmt *CS = SE->getSubStmt();
952    for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
953	   BE = CS->body_end(); BI != BE; ++BI)
954      if (Expr *E = dyn_cast<Expr>((*BI))) {
955        if (isCapturedBy(var, E))
956            return true;
957      }
958      else if (DeclStmt *DS = dyn_cast<DeclStmt>((*BI))) {
959          // special case declarations
960          for (DeclStmt::decl_iterator I = DS->decl_begin(), E = DS->decl_end();
961               I != E; ++I) {
962              if (VarDecl *VD = dyn_cast<VarDecl>((*I))) {
963                Expr *Init = VD->getInit();
964                if (Init && isCapturedBy(var, Init))
965                  return true;
966              }
967          }
968      }
969      else
970        // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
971        // Later, provide code to poke into statements for capture analysis.
972        return true;
973    return false;
974  }
975
976  for (Stmt::const_child_range children = e->children(); children; ++children)
977    if (isCapturedBy(var, cast<Expr>(*children)))
978      return true;
979
980  return false;
981}
982
983/// \brief Determine whether the given initializer is trivial in the sense
984/// that it requires no code to be generated.
985static bool isTrivialInitializer(const Expr *Init) {
986  if (!Init)
987    return true;
988
989  if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
990    if (CXXConstructorDecl *Constructor = Construct->getConstructor())
991      if (Constructor->isTrivial() &&
992          Constructor->isDefaultConstructor() &&
993          !Construct->requiresZeroInitialization())
994        return true;
995
996  return false;
997}
998void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
999  assert(emission.Variable && "emission was not valid!");
1000
1001  // If this was emitted as a global constant, we're done.
1002  if (emission.wasEmittedAsGlobal()) return;
1003
1004  const VarDecl &D = *emission.Variable;
1005  QualType type = D.getType();
1006
1007  // If this local has an initializer, emit it now.
1008  const Expr *Init = D.getInit();
1009
1010  // If we are at an unreachable point, we don't need to emit the initializer
1011  // unless it contains a label.
1012  if (!HaveInsertPoint()) {
1013    if (!Init || !ContainsLabel(Init)) return;
1014    EnsureInsertPoint();
1015  }
1016
1017  // Initialize the structure of a __block variable.
1018  if (emission.IsByRef)
1019    emitByrefStructureInit(emission);
1020
1021  if (isTrivialInitializer(Init))
1022    return;
1023
1024  CharUnits alignment = emission.Alignment;
1025
1026  // Check whether this is a byref variable that's potentially
1027  // captured and moved by its own initializer.  If so, we'll need to
1028  // emit the initializer first, then copy into the variable.
1029  bool capturedByInit = emission.IsByRef && isCapturedBy(D, Init);
1030
1031  llvm::Value *Loc =
1032    capturedByInit ? emission.Address : emission.getObjectAddress(*this);
1033
1034  llvm::Constant *constant = 0;
1035  if (emission.IsConstantAggregate) {
1036    assert(!capturedByInit && "constant init contains a capturing block?");
1037    constant = CGM.EmitConstantInit(D, this);
1038  }
1039
1040  if (!constant) {
1041    LValue lv = MakeAddrLValue(Loc, type, alignment);
1042    lv.setNonGC(true);
1043    return EmitExprAsInit(Init, &D, lv, capturedByInit);
1044  }
1045
1046  // If this is a simple aggregate initialization, we can optimize it
1047  // in various ways.
1048  bool isVolatile = type.isVolatileQualified();
1049
1050  llvm::Value *SizeVal =
1051    llvm::ConstantInt::get(IntPtrTy,
1052                           getContext().getTypeSizeInChars(type).getQuantity());
1053
1054  llvm::Type *BP = Int8PtrTy;
1055  if (Loc->getType() != BP)
1056    Loc = Builder.CreateBitCast(Loc, BP);
1057
1058  // If the initializer is all or mostly zeros, codegen with memset then do
1059  // a few stores afterward.
1060  if (shouldUseMemSetPlusStoresToInitialize(constant,
1061                CGM.getTargetData().getTypeAllocSize(constant->getType()))) {
1062    Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
1063                         alignment.getQuantity(), isVolatile);
1064    // Zero and undef don't require a stores.
1065    if (!constant->isNullValue() && !isa<llvm::UndefValue>(constant)) {
1066      Loc = Builder.CreateBitCast(Loc, constant->getType()->getPointerTo());
1067      emitStoresForInitAfterMemset(constant, Loc, isVolatile, Builder);
1068    }
1069  } else {
1070    // Otherwise, create a temporary global with the initializer then
1071    // memcpy from the global to the alloca.
1072    std::string Name = GetStaticDeclName(*this, D, ".");
1073    llvm::GlobalVariable *GV =
1074      new llvm::GlobalVariable(CGM.getModule(), constant->getType(), true,
1075                               llvm::GlobalValue::PrivateLinkage,
1076                               constant, Name);
1077    GV->setAlignment(alignment.getQuantity());
1078    GV->setUnnamedAddr(true);
1079
1080    llvm::Value *SrcPtr = GV;
1081    if (SrcPtr->getType() != BP)
1082      SrcPtr = Builder.CreateBitCast(SrcPtr, BP);
1083
1084    Builder.CreateMemCpy(Loc, SrcPtr, SizeVal, alignment.getQuantity(),
1085                         isVolatile);
1086  }
1087}
1088
1089/// Emit an expression as an initializer for a variable at the given
1090/// location.  The expression is not necessarily the normal
1091/// initializer for the variable, and the address is not necessarily
1092/// its normal location.
1093///
1094/// \param init the initializing expression
1095/// \param var the variable to act as if we're initializing
1096/// \param loc the address to initialize; its type is a pointer
1097///   to the LLVM mapping of the variable's type
1098/// \param alignment the alignment of the address
1099/// \param capturedByInit true if the variable is a __block variable
1100///   whose address is potentially changed by the initializer
1101void CodeGenFunction::EmitExprAsInit(const Expr *init,
1102                                     const ValueDecl *D,
1103                                     LValue lvalue,
1104                                     bool capturedByInit) {
1105  QualType type = D->getType();
1106
1107  if (type->isReferenceType()) {
1108    RValue rvalue = EmitReferenceBindingToExpr(init, D);
1109    if (capturedByInit)
1110      drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
1111    EmitStoreThroughLValue(rvalue, lvalue, true);
1112  } else if (!hasAggregateLLVMType(type)) {
1113    EmitScalarInit(init, D, lvalue, capturedByInit);
1114  } else if (type->isAnyComplexType()) {
1115    ComplexPairTy complex = EmitComplexExpr(init);
1116    if (capturedByInit)
1117      drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
1118    StoreComplexToAddr(complex, lvalue.getAddress(), lvalue.isVolatile());
1119  } else {
1120    // TODO: how can we delay here if D is captured by its initializer?
1121    EmitAggExpr(init, AggValueSlot::forLValue(lvalue,
1122                                              AggValueSlot::IsDestructed,
1123                                         AggValueSlot::DoesNotNeedGCBarriers,
1124                                              AggValueSlot::IsNotAliased));
1125    MaybeEmitStdInitializerListCleanup(lvalue.getAddress(), init);
1126  }
1127}
1128
1129/// Enter a destroy cleanup for the given local variable.
1130void CodeGenFunction::emitAutoVarTypeCleanup(
1131                            const CodeGenFunction::AutoVarEmission &emission,
1132                            QualType::DestructionKind dtorKind) {
1133  assert(dtorKind != QualType::DK_none);
1134
1135  // Note that for __block variables, we want to destroy the
1136  // original stack object, not the possibly forwarded object.
1137  llvm::Value *addr = emission.getObjectAddress(*this);
1138
1139  const VarDecl *var = emission.Variable;
1140  QualType type = var->getType();
1141
1142  CleanupKind cleanupKind = NormalAndEHCleanup;
1143  CodeGenFunction::Destroyer *destroyer = 0;
1144
1145  switch (dtorKind) {
1146  case QualType::DK_none:
1147    llvm_unreachable("no cleanup for trivially-destructible variable");
1148
1149  case QualType::DK_cxx_destructor:
1150    // If there's an NRVO flag on the emission, we need a different
1151    // cleanup.
1152    if (emission.NRVOFlag) {
1153      assert(!type->isArrayType());
1154      CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
1155      EHStack.pushCleanup<DestroyNRVOVariable>(cleanupKind, addr, dtor,
1156                                               emission.NRVOFlag);
1157      return;
1158    }
1159    break;
1160
1161  case QualType::DK_objc_strong_lifetime:
1162    // Suppress cleanups for pseudo-strong variables.
1163    if (var->isARCPseudoStrong()) return;
1164
1165    // Otherwise, consider whether to use an EH cleanup or not.
1166    cleanupKind = getARCCleanupKind();
1167
1168    // Use the imprecise destroyer by default.
1169    if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
1170      destroyer = CodeGenFunction::destroyARCStrongImprecise;
1171    break;
1172
1173  case QualType::DK_objc_weak_lifetime:
1174    break;
1175  }
1176
1177  // If we haven't chosen a more specific destroyer, use the default.
1178  if (!destroyer) destroyer = getDestroyer(dtorKind);
1179
1180  // Use an EH cleanup in array destructors iff the destructor itself
1181  // is being pushed as an EH cleanup.
1182  bool useEHCleanup = (cleanupKind & EHCleanup);
1183  EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
1184                                     useEHCleanup);
1185}
1186
1187void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
1188  assert(emission.Variable && "emission was not valid!");
1189
1190  // If this was emitted as a global constant, we're done.
1191  if (emission.wasEmittedAsGlobal()) return;
1192
1193  // If we don't have an insertion point, we're done.  Sema prevents
1194  // us from jumping into any of these scopes anyway.
1195  if (!HaveInsertPoint()) return;
1196
1197  const VarDecl &D = *emission.Variable;
1198
1199  // Check the type for a cleanup.
1200  if (QualType::DestructionKind dtorKind = D.getType().isDestructedType())
1201    emitAutoVarTypeCleanup(emission, dtorKind);
1202
1203  // In GC mode, honor objc_precise_lifetime.
1204  if (getLangOpts().getGC() != LangOptions::NonGC &&
1205      D.hasAttr<ObjCPreciseLifetimeAttr>()) {
1206    EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
1207  }
1208
1209  // Handle the cleanup attribute.
1210  if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
1211    const FunctionDecl *FD = CA->getFunctionDecl();
1212
1213    llvm::Constant *F = CGM.GetAddrOfFunction(FD);
1214    assert(F && "Could not find function!");
1215
1216    const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
1217    EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
1218  }
1219
1220  // If this is a block variable, call _Block_object_destroy
1221  // (on the unforwarded address).
1222  if (emission.IsByRef)
1223    enterByrefCleanup(emission);
1224}
1225
1226CodeGenFunction::Destroyer *
1227CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
1228  switch (kind) {
1229  case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
1230  case QualType::DK_cxx_destructor:
1231    return destroyCXXObject;
1232  case QualType::DK_objc_strong_lifetime:
1233    return destroyARCStrongPrecise;
1234  case QualType::DK_objc_weak_lifetime:
1235    return destroyARCWeak;
1236  }
1237  llvm_unreachable("Unknown DestructionKind");
1238}
1239
1240/// pushDestroy - Push the standard destructor for the given type.
1241void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
1242                                  llvm::Value *addr, QualType type) {
1243  assert(dtorKind && "cannot push destructor for trivial type");
1244
1245  CleanupKind cleanupKind = getCleanupKind(dtorKind);
1246  pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
1247              cleanupKind & EHCleanup);
1248}
1249
1250void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, llvm::Value *addr,
1251                                  QualType type, Destroyer *destroyer,
1252                                  bool useEHCleanupForArray) {
1253  pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
1254                                     destroyer, useEHCleanupForArray);
1255}
1256
1257/// emitDestroy - Immediately perform the destruction of the given
1258/// object.
1259///
1260/// \param addr - the address of the object; a type*
1261/// \param type - the type of the object; if an array type, all
1262///   objects are destroyed in reverse order
1263/// \param destroyer - the function to call to destroy individual
1264///   elements
1265/// \param useEHCleanupForArray - whether an EH cleanup should be
1266///   used when destroying array elements, in case one of the
1267///   destructions throws an exception
1268void CodeGenFunction::emitDestroy(llvm::Value *addr, QualType type,
1269                                  Destroyer *destroyer,
1270                                  bool useEHCleanupForArray) {
1271  const ArrayType *arrayType = getContext().getAsArrayType(type);
1272  if (!arrayType)
1273    return destroyer(*this, addr, type);
1274
1275  llvm::Value *begin = addr;
1276  llvm::Value *length = emitArrayLength(arrayType, type, begin);
1277
1278  // Normally we have to check whether the array is zero-length.
1279  bool checkZeroLength = true;
1280
1281  // But if the array length is constant, we can suppress that.
1282  if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
1283    // ...and if it's constant zero, we can just skip the entire thing.
1284    if (constLength->isZero()) return;
1285    checkZeroLength = false;
1286  }
1287
1288  llvm::Value *end = Builder.CreateInBoundsGEP(begin, length);
1289  emitArrayDestroy(begin, end, type, destroyer,
1290                   checkZeroLength, useEHCleanupForArray);
1291}
1292
1293/// emitArrayDestroy - Destroys all the elements of the given array,
1294/// beginning from last to first.  The array cannot be zero-length.
1295///
1296/// \param begin - a type* denoting the first element of the array
1297/// \param end - a type* denoting one past the end of the array
1298/// \param type - the element type of the array
1299/// \param destroyer - the function to call to destroy elements
1300/// \param useEHCleanup - whether to push an EH cleanup to destroy
1301///   the remaining elements in case the destruction of a single
1302///   element throws
1303void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
1304                                       llvm::Value *end,
1305                                       QualType type,
1306                                       Destroyer *destroyer,
1307                                       bool checkZeroLength,
1308                                       bool useEHCleanup) {
1309  assert(!type->isArrayType());
1310
1311  // The basic structure here is a do-while loop, because we don't
1312  // need to check for the zero-element case.
1313  llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
1314  llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
1315
1316  if (checkZeroLength) {
1317    llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
1318                                                "arraydestroy.isempty");
1319    Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
1320  }
1321
1322  // Enter the loop body, making that address the current address.
1323  llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1324  EmitBlock(bodyBB);
1325  llvm::PHINode *elementPast =
1326    Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
1327  elementPast->addIncoming(end, entryBB);
1328
1329  // Shift the address back by one element.
1330  llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
1331  llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne,
1332                                                   "arraydestroy.element");
1333
1334  if (useEHCleanup)
1335    pushRegularPartialArrayCleanup(begin, element, type, destroyer);
1336
1337  // Perform the actual destruction there.
1338  destroyer(*this, element, type);
1339
1340  if (useEHCleanup)
1341    PopCleanupBlock();
1342
1343  // Check whether we've reached the end.
1344  llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
1345  Builder.CreateCondBr(done, doneBB, bodyBB);
1346  elementPast->addIncoming(element, Builder.GetInsertBlock());
1347
1348  // Done.
1349  EmitBlock(doneBB);
1350}
1351
1352/// Perform partial array destruction as if in an EH cleanup.  Unlike
1353/// emitArrayDestroy, the element type here may still be an array type.
1354static void emitPartialArrayDestroy(CodeGenFunction &CGF,
1355                                    llvm::Value *begin, llvm::Value *end,
1356                                    QualType type,
1357                                    CodeGenFunction::Destroyer *destroyer) {
1358  // If the element type is itself an array, drill down.
1359  unsigned arrayDepth = 0;
1360  while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
1361    // VLAs don't require a GEP index to walk into.
1362    if (!isa<VariableArrayType>(arrayType))
1363      arrayDepth++;
1364    type = arrayType->getElementType();
1365  }
1366
1367  if (arrayDepth) {
1368    llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, arrayDepth+1);
1369
1370    SmallVector<llvm::Value*,4> gepIndices(arrayDepth, zero);
1371    begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin");
1372    end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend");
1373  }
1374
1375  // Destroy the array.  We don't ever need an EH cleanup because we
1376  // assume that we're in an EH cleanup ourselves, so a throwing
1377  // destructor causes an immediate terminate.
1378  CGF.emitArrayDestroy(begin, end, type, destroyer,
1379                       /*checkZeroLength*/ true, /*useEHCleanup*/ false);
1380}
1381
1382namespace {
1383  /// RegularPartialArrayDestroy - a cleanup which performs a partial
1384  /// array destroy where the end pointer is regularly determined and
1385  /// does not need to be loaded from a local.
1386  class RegularPartialArrayDestroy : public EHScopeStack::Cleanup {
1387    llvm::Value *ArrayBegin;
1388    llvm::Value *ArrayEnd;
1389    QualType ElementType;
1390    CodeGenFunction::Destroyer *Destroyer;
1391  public:
1392    RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
1393                               QualType elementType,
1394                               CodeGenFunction::Destroyer *destroyer)
1395      : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
1396        ElementType(elementType), Destroyer(destroyer) {}
1397
1398    void Emit(CodeGenFunction &CGF, Flags flags) {
1399      emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
1400                              ElementType, Destroyer);
1401    }
1402  };
1403
1404  /// IrregularPartialArrayDestroy - a cleanup which performs a
1405  /// partial array destroy where the end pointer is irregularly
1406  /// determined and must be loaded from a local.
1407  class IrregularPartialArrayDestroy : public EHScopeStack::Cleanup {
1408    llvm::Value *ArrayBegin;
1409    llvm::Value *ArrayEndPointer;
1410    QualType ElementType;
1411    CodeGenFunction::Destroyer *Destroyer;
1412  public:
1413    IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
1414                                 llvm::Value *arrayEndPointer,
1415                                 QualType elementType,
1416                                 CodeGenFunction::Destroyer *destroyer)
1417      : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
1418        ElementType(elementType), Destroyer(destroyer) {}
1419
1420    void Emit(CodeGenFunction &CGF, Flags flags) {
1421      llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
1422      emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
1423                              ElementType, Destroyer);
1424    }
1425  };
1426}
1427
1428/// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
1429/// already-constructed elements of the given array.  The cleanup
1430/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
1431///
1432/// \param elementType - the immediate element type of the array;
1433///   possibly still an array type
1434/// \param array - a value of type elementType*
1435/// \param destructionKind - the kind of destruction required
1436/// \param initializedElementCount - a value of type size_t* holding
1437///   the number of successfully-constructed elements
1438void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
1439                                                 llvm::Value *arrayEndPointer,
1440                                                       QualType elementType,
1441                                                       Destroyer *destroyer) {
1442  pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
1443                                                    arrayBegin, arrayEndPointer,
1444                                                    elementType, destroyer);
1445}
1446
1447/// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
1448/// already-constructed elements of the given array.  The cleanup
1449/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
1450///
1451/// \param elementType - the immediate element type of the array;
1452///   possibly still an array type
1453/// \param array - a value of type elementType*
1454/// \param destructionKind - the kind of destruction required
1455/// \param initializedElementCount - a value of type size_t* holding
1456///   the number of successfully-constructed elements
1457void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
1458                                                     llvm::Value *arrayEnd,
1459                                                     QualType elementType,
1460                                                     Destroyer *destroyer) {
1461  pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
1462                                                  arrayBegin, arrayEnd,
1463                                                  elementType, destroyer);
1464}
1465
1466namespace {
1467  /// A cleanup to perform a release of an object at the end of a
1468  /// function.  This is used to balance out the incoming +1 of a
1469  /// ns_consumed argument when we can't reasonably do that just by
1470  /// not doing the initial retain for a __block argument.
1471  struct ConsumeARCParameter : EHScopeStack::Cleanup {
1472    ConsumeARCParameter(llvm::Value *param) : Param(param) {}
1473
1474    llvm::Value *Param;
1475
1476    void Emit(CodeGenFunction &CGF, Flags flags) {
1477      CGF.EmitARCRelease(Param, /*precise*/ false);
1478    }
1479  };
1480}
1481
1482/// Emit an alloca (or GlobalValue depending on target)
1483/// for the specified parameter and set up LocalDeclMap.
1484void CodeGenFunction::EmitParmDecl(const VarDecl &D, llvm::Value *Arg,
1485                                   unsigned ArgNo) {
1486  // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
1487  assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
1488         "Invalid argument to EmitParmDecl");
1489
1490  Arg->setName(D.getName());
1491
1492  // Use better IR generation for certain implicit parameters.
1493  if (isa<ImplicitParamDecl>(D)) {
1494    // The only implicit argument a block has is its literal.
1495    if (BlockInfo) {
1496      LocalDeclMap[&D] = Arg;
1497
1498      if (CGDebugInfo *DI = getDebugInfo()) {
1499        if (CGM.getCodeGenOpts().DebugInfo >=
1500            CodeGenOptions::LimitedDebugInfo) {
1501          DI->setLocation(D.getLocation());
1502          DI->EmitDeclareOfBlockLiteralArgVariable(*BlockInfo, Arg, Builder);
1503        }
1504      }
1505
1506      return;
1507    }
1508  }
1509
1510  QualType Ty = D.getType();
1511
1512  llvm::Value *DeclPtr;
1513  // If this is an aggregate or variable sized value, reuse the input pointer.
1514  if (!Ty->isConstantSizeType() ||
1515      CodeGenFunction::hasAggregateLLVMType(Ty)) {
1516    DeclPtr = Arg;
1517  } else {
1518    // Otherwise, create a temporary to hold the value.
1519    llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty),
1520                                               D.getName() + ".addr");
1521    Alloc->setAlignment(getContext().getDeclAlign(&D).getQuantity());
1522    DeclPtr = Alloc;
1523
1524    bool doStore = true;
1525
1526    Qualifiers qs = Ty.getQualifiers();
1527
1528    if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
1529      // We honor __attribute__((ns_consumed)) for types with lifetime.
1530      // For __strong, it's handled by just skipping the initial retain;
1531      // otherwise we have to balance out the initial +1 with an extra
1532      // cleanup to do the release at the end of the function.
1533      bool isConsumed = D.hasAttr<NSConsumedAttr>();
1534
1535      // 'self' is always formally __strong, but if this is not an
1536      // init method then we don't want to retain it.
1537      if (D.isARCPseudoStrong()) {
1538        const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CurCodeDecl);
1539        assert(&D == method->getSelfDecl());
1540        assert(lt == Qualifiers::OCL_Strong);
1541        assert(qs.hasConst());
1542        assert(method->getMethodFamily() != OMF_init);
1543        (void) method;
1544        lt = Qualifiers::OCL_ExplicitNone;
1545      }
1546
1547      if (lt == Qualifiers::OCL_Strong) {
1548        if (!isConsumed)
1549          // Don't use objc_retainBlock for block pointers, because we
1550          // don't want to Block_copy something just because we got it
1551          // as a parameter.
1552          Arg = EmitARCRetainNonBlock(Arg);
1553      } else {
1554        // Push the cleanup for a consumed parameter.
1555        if (isConsumed)
1556          EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), Arg);
1557
1558        if (lt == Qualifiers::OCL_Weak) {
1559          EmitARCInitWeak(DeclPtr, Arg);
1560          doStore = false; // The weak init is a store, no need to do two.
1561        }
1562      }
1563
1564      // Enter the cleanup scope.
1565      EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
1566    }
1567
1568    // Store the initial value into the alloca.
1569    if (doStore) {
1570      LValue lv = MakeAddrLValue(DeclPtr, Ty,
1571                                 getContext().getDeclAlign(&D));
1572      EmitStoreOfScalar(Arg, lv, /* isInitialization */ true);
1573    }
1574  }
1575
1576  llvm::Value *&DMEntry = LocalDeclMap[&D];
1577  assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
1578  DMEntry = DeclPtr;
1579
1580  // Emit debug info for param declaration.
1581  if (CGDebugInfo *DI = getDebugInfo()) {
1582    if (CGM.getCodeGenOpts().DebugInfo >= CodeGenOptions::LimitedDebugInfo) {
1583      DI->EmitDeclareOfArgVariable(&D, DeclPtr, ArgNo, Builder);
1584    }
1585  }
1586
1587  if (D.hasAttr<AnnotateAttr>())
1588      EmitVarAnnotations(&D, DeclPtr);
1589}
1590