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