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