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