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