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