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