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