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