1 //===--- CGDecl.cpp - Emit LLVM Code for declarations ---------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This contains code to emit Decl nodes as LLVM code.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "CGBlocks.h"
14 #include "CGCXXABI.h"
15 #include "CGCleanup.h"
16 #include "CGDebugInfo.h"
17 #include "CGOpenCLRuntime.h"
18 #include "CGOpenMPRuntime.h"
19 #include "CodeGenFunction.h"
20 #include "CodeGenModule.h"
21 #include "ConstantEmitter.h"
22 #include "PatternInit.h"
23 #include "TargetInfo.h"
24 #include "clang/AST/ASTContext.h"
25 #include "clang/AST/Attr.h"
26 #include "clang/AST/CharUnits.h"
27 #include "clang/AST/Decl.h"
28 #include "clang/AST/DeclObjC.h"
29 #include "clang/AST/DeclOpenMP.h"
30 #include "clang/Basic/CodeGenOptions.h"
31 #include "clang/Basic/SourceManager.h"
32 #include "clang/Basic/TargetInfo.h"
33 #include "clang/CodeGen/CGFunctionInfo.h"
34 #include "clang/Sema/Sema.h"
35 #include "llvm/Analysis/ValueTracking.h"
36 #include "llvm/IR/DataLayout.h"
37 #include "llvm/IR/GlobalVariable.h"
38 #include "llvm/IR/Intrinsics.h"
39 #include "llvm/IR/Type.h"
40 
41 using namespace clang;
42 using namespace CodeGen;
43 
44 static_assert(clang::Sema::MaximumAlignment <= llvm::Value::MaximumAlignment,
45               "Clang max alignment greater than what LLVM supports?");
46 
47 void CodeGenFunction::EmitDecl(const Decl &D) {
48   switch (D.getKind()) {
49   case Decl::BuiltinTemplate:
50   case Decl::TranslationUnit:
51   case Decl::ExternCContext:
52   case Decl::Namespace:
53   case Decl::UnresolvedUsingTypename:
54   case Decl::ClassTemplateSpecialization:
55   case Decl::ClassTemplatePartialSpecialization:
56   case Decl::VarTemplateSpecialization:
57   case Decl::VarTemplatePartialSpecialization:
58   case Decl::TemplateTypeParm:
59   case Decl::UnresolvedUsingValue:
60   case Decl::NonTypeTemplateParm:
61   case Decl::CXXDeductionGuide:
62   case Decl::CXXMethod:
63   case Decl::CXXConstructor:
64   case Decl::CXXDestructor:
65   case Decl::CXXConversion:
66   case Decl::Field:
67   case Decl::MSProperty:
68   case Decl::IndirectField:
69   case Decl::ObjCIvar:
70   case Decl::ObjCAtDefsField:
71   case Decl::ParmVar:
72   case Decl::ImplicitParam:
73   case Decl::ClassTemplate:
74   case Decl::VarTemplate:
75   case Decl::FunctionTemplate:
76   case Decl::TypeAliasTemplate:
77   case Decl::TemplateTemplateParm:
78   case Decl::ObjCMethod:
79   case Decl::ObjCCategory:
80   case Decl::ObjCProtocol:
81   case Decl::ObjCInterface:
82   case Decl::ObjCCategoryImpl:
83   case Decl::ObjCImplementation:
84   case Decl::ObjCProperty:
85   case Decl::ObjCCompatibleAlias:
86   case Decl::PragmaComment:
87   case Decl::PragmaDetectMismatch:
88   case Decl::AccessSpec:
89   case Decl::LinkageSpec:
90   case Decl::Export:
91   case Decl::ObjCPropertyImpl:
92   case Decl::FileScopeAsm:
93   case Decl::Friend:
94   case Decl::FriendTemplate:
95   case Decl::Block:
96   case Decl::Captured:
97   case Decl::ClassScopeFunctionSpecialization:
98   case Decl::UsingShadow:
99   case Decl::ConstructorUsingShadow:
100   case Decl::ObjCTypeParam:
101   case Decl::Binding:
102     llvm_unreachable("Declaration should not be in declstmts!");
103   case Decl::Function:  // void X();
104   case Decl::Record:    // struct/union/class X;
105   case Decl::Enum:      // enum X;
106   case Decl::EnumConstant: // enum ? { X = ? }
107   case Decl::CXXRecord: // struct/union/class X; [C++]
108   case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
109   case Decl::Label:        // __label__ x;
110   case Decl::Import:
111   case Decl::OMPThreadPrivate:
112   case Decl::OMPAllocate:
113   case Decl::OMPCapturedExpr:
114   case Decl::OMPRequires:
115   case Decl::Empty:
116   case Decl::Concept:
117   case Decl::LifetimeExtendedTemporary:
118   case Decl::RequiresExprBody:
119     // None of these decls require codegen support.
120     return;
121 
122   case Decl::NamespaceAlias:
123     if (CGDebugInfo *DI = getDebugInfo())
124         DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(D));
125     return;
126   case Decl::Using:          // using X; [C++]
127     if (CGDebugInfo *DI = getDebugInfo())
128         DI->EmitUsingDecl(cast<UsingDecl>(D));
129     return;
130   case Decl::UsingPack:
131     for (auto *Using : cast<UsingPackDecl>(D).expansions())
132       EmitDecl(*Using);
133     return;
134   case Decl::UsingDirective: // using namespace X; [C++]
135     if (CGDebugInfo *DI = getDebugInfo())
136       DI->EmitUsingDirective(cast<UsingDirectiveDecl>(D));
137     return;
138   case Decl::Var:
139   case Decl::Decomposition: {
140     const VarDecl &VD = cast<VarDecl>(D);
141     assert(VD.isLocalVarDecl() &&
142            "Should not see file-scope variables inside a function!");
143     EmitVarDecl(VD);
144     if (auto *DD = dyn_cast<DecompositionDecl>(&VD))
145       for (auto *B : DD->bindings())
146         if (auto *HD = B->getHoldingVar())
147           EmitVarDecl(*HD);
148     return;
149   }
150 
151   case Decl::OMPDeclareReduction:
152     return CGM.EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(&D), this);
153 
154   case Decl::OMPDeclareMapper:
155     return CGM.EmitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(&D), this);
156 
157   case Decl::Typedef:      // typedef int X;
158   case Decl::TypeAlias: {  // using X = int; [C++0x]
159     const TypedefNameDecl &TD = cast<TypedefNameDecl>(D);
160     QualType Ty = TD.getUnderlyingType();
161 
162     if (Ty->isVariablyModifiedType())
163       EmitVariablyModifiedType(Ty);
164 
165     return;
166   }
167   }
168 }
169 
170 /// EmitVarDecl - This method handles emission of any variable declaration
171 /// inside a function, including static vars etc.
172 void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
173   if (D.hasExternalStorage())
174     // Don't emit it now, allow it to be emitted lazily on its first use.
175     return;
176 
177   // Some function-scope variable does not have static storage but still
178   // needs to be emitted like a static variable, e.g. a function-scope
179   // variable in constant address space in OpenCL.
180   if (D.getStorageDuration() != SD_Automatic) {
181     // Static sampler variables translated to function calls.
182     if (D.getType()->isSamplerT())
183       return;
184 
185     llvm::GlobalValue::LinkageTypes Linkage =
186         CGM.getLLVMLinkageVarDefinition(&D, /*IsConstant=*/false);
187 
188     // FIXME: We need to force the emission/use of a guard variable for
189     // some variables even if we can constant-evaluate them because
190     // we can't guarantee every translation unit will constant-evaluate them.
191 
192     return EmitStaticVarDecl(D, Linkage);
193   }
194 
195   if (D.getType().getAddressSpace() == LangAS::opencl_local)
196     return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D);
197 
198   assert(D.hasLocalStorage());
199   return EmitAutoVarDecl(D);
200 }
201 
202 static std::string getStaticDeclName(CodeGenModule &CGM, const VarDecl &D) {
203   if (CGM.getLangOpts().CPlusPlus)
204     return CGM.getMangledName(&D).str();
205 
206   // If this isn't C++, we don't need a mangled name, just a pretty one.
207   assert(!D.isExternallyVisible() && "name shouldn't matter");
208   std::string ContextName;
209   const DeclContext *DC = D.getDeclContext();
210   if (auto *CD = dyn_cast<CapturedDecl>(DC))
211     DC = cast<DeclContext>(CD->getNonClosureContext());
212   if (const auto *FD = dyn_cast<FunctionDecl>(DC))
213     ContextName = std::string(CGM.getMangledName(FD));
214   else if (const auto *BD = dyn_cast<BlockDecl>(DC))
215     ContextName = std::string(CGM.getBlockMangledName(GlobalDecl(), BD));
216   else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(DC))
217     ContextName = OMD->getSelector().getAsString();
218   else
219     llvm_unreachable("Unknown context for static var decl");
220 
221   ContextName += "." + D.getNameAsString();
222   return ContextName;
223 }
224 
225 llvm::Constant *CodeGenModule::getOrCreateStaticVarDecl(
226     const VarDecl &D, llvm::GlobalValue::LinkageTypes Linkage) {
227   // In general, we don't always emit static var decls once before we reference
228   // them. It is possible to reference them before emitting the function that
229   // contains them, and it is possible to emit the containing function multiple
230   // times.
231   if (llvm::Constant *ExistingGV = StaticLocalDeclMap[&D])
232     return ExistingGV;
233 
234   QualType Ty = D.getType();
235   assert(Ty->isConstantSizeType() && "VLAs can't be static");
236 
237   // Use the label if the variable is renamed with the asm-label extension.
238   std::string Name;
239   if (D.hasAttr<AsmLabelAttr>())
240     Name = std::string(getMangledName(&D));
241   else
242     Name = getStaticDeclName(*this, D);
243 
244   llvm::Type *LTy = getTypes().ConvertTypeForMem(Ty);
245   LangAS AS = GetGlobalVarAddressSpace(&D);
246   unsigned TargetAS = getContext().getTargetAddressSpace(AS);
247 
248   // OpenCL variables in local address space and CUDA shared
249   // variables cannot have an initializer.
250   llvm::Constant *Init = nullptr;
251   if (Ty.getAddressSpace() == LangAS::opencl_local ||
252       D.hasAttr<CUDASharedAttr>() || D.hasAttr<LoaderUninitializedAttr>())
253     Init = llvm::UndefValue::get(LTy);
254   else
255     Init = EmitNullConstant(Ty);
256 
257   llvm::GlobalVariable *GV = new llvm::GlobalVariable(
258       getModule(), LTy, Ty.isConstant(getContext()), Linkage, Init, Name,
259       nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
260   GV->setAlignment(getContext().getDeclAlign(&D).getAsAlign());
261 
262   if (supportsCOMDAT() && GV->isWeakForLinker())
263     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
264 
265   if (D.getTLSKind())
266     setTLSMode(GV, D);
267 
268   setGVProperties(GV, &D);
269 
270   // Make sure the result is of the correct type.
271   LangAS ExpectedAS = Ty.getAddressSpace();
272   llvm::Constant *Addr = GV;
273   if (AS != ExpectedAS) {
274     Addr = getTargetCodeGenInfo().performAddrSpaceCast(
275         *this, GV, AS, ExpectedAS,
276         LTy->getPointerTo(getContext().getTargetAddressSpace(ExpectedAS)));
277   }
278 
279   setStaticLocalDeclAddress(&D, Addr);
280 
281   // Ensure that the static local gets initialized by making sure the parent
282   // function gets emitted eventually.
283   const Decl *DC = cast<Decl>(D.getDeclContext());
284 
285   // We can't name blocks or captured statements directly, so try to emit their
286   // parents.
287   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC)) {
288     DC = DC->getNonClosureContext();
289     // FIXME: Ensure that global blocks get emitted.
290     if (!DC)
291       return Addr;
292   }
293 
294   GlobalDecl GD;
295   if (const auto *CD = dyn_cast<CXXConstructorDecl>(DC))
296     GD = GlobalDecl(CD, Ctor_Base);
297   else if (const auto *DD = dyn_cast<CXXDestructorDecl>(DC))
298     GD = GlobalDecl(DD, Dtor_Base);
299   else if (const auto *FD = dyn_cast<FunctionDecl>(DC))
300     GD = GlobalDecl(FD);
301   else {
302     // Don't do anything for Obj-C method decls or global closures. We should
303     // never defer them.
304     assert(isa<ObjCMethodDecl>(DC) && "unexpected parent code decl");
305   }
306   if (GD.getDecl()) {
307     // Disable emission of the parent function for the OpenMP device codegen.
308     CGOpenMPRuntime::DisableAutoDeclareTargetRAII NoDeclTarget(*this);
309     (void)GetAddrOfGlobal(GD);
310   }
311 
312   return Addr;
313 }
314 
315 /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
316 /// global variable that has already been created for it.  If the initializer
317 /// has a different type than GV does, this may free GV and return a different
318 /// one.  Otherwise it just returns GV.
319 llvm::GlobalVariable *
320 CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
321                                                llvm::GlobalVariable *GV) {
322   ConstantEmitter emitter(*this);
323   llvm::Constant *Init = emitter.tryEmitForInitializer(D);
324 
325   // If constant emission failed, then this should be a C++ static
326   // initializer.
327   if (!Init) {
328     if (!getLangOpts().CPlusPlus)
329       CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
330     else if (HaveInsertPoint()) {
331       // Since we have a static initializer, this global variable can't
332       // be constant.
333       GV->setConstant(false);
334 
335       EmitCXXGuardedInit(D, GV, /*PerformInit*/true);
336     }
337     return GV;
338   }
339 
340   // The initializer may differ in type from the global. Rewrite
341   // the global to match the initializer.  (We have to do this
342   // because some types, like unions, can't be completely represented
343   // in the LLVM type system.)
344   if (GV->getValueType() != Init->getType()) {
345     llvm::GlobalVariable *OldGV = GV;
346 
347     GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
348                                   OldGV->isConstant(),
349                                   OldGV->getLinkage(), Init, "",
350                                   /*InsertBefore*/ OldGV,
351                                   OldGV->getThreadLocalMode(),
352                            CGM.getContext().getTargetAddressSpace(D.getType()));
353     GV->setVisibility(OldGV->getVisibility());
354     GV->setDSOLocal(OldGV->isDSOLocal());
355     GV->setComdat(OldGV->getComdat());
356 
357     // Steal the name of the old global
358     GV->takeName(OldGV);
359 
360     // Replace all uses of the old global with the new global
361     llvm::Constant *NewPtrForOldDecl =
362     llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
363     OldGV->replaceAllUsesWith(NewPtrForOldDecl);
364 
365     // Erase the old global, since it is no longer used.
366     OldGV->eraseFromParent();
367   }
368 
369   GV->setConstant(CGM.isTypeConstant(D.getType(), true));
370   GV->setInitializer(Init);
371 
372   emitter.finalize(GV);
373 
374   if (D.needsDestruction(getContext()) == QualType::DK_cxx_destructor &&
375       HaveInsertPoint()) {
376     // We have a constant initializer, but a nontrivial destructor. We still
377     // need to perform a guarded "initialization" in order to register the
378     // destructor.
379     EmitCXXGuardedInit(D, GV, /*PerformInit*/false);
380   }
381 
382   return GV;
383 }
384 
385 void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
386                                       llvm::GlobalValue::LinkageTypes Linkage) {
387   // Check to see if we already have a global variable for this
388   // declaration.  This can happen when double-emitting function
389   // bodies, e.g. with complete and base constructors.
390   llvm::Constant *addr = CGM.getOrCreateStaticVarDecl(D, Linkage);
391   CharUnits alignment = getContext().getDeclAlign(&D);
392 
393   // Store into LocalDeclMap before generating initializer to handle
394   // circular references.
395   setAddrOfLocalVar(&D, Address(addr, alignment));
396 
397   // We can't have a VLA here, but we can have a pointer to a VLA,
398   // even though that doesn't really make any sense.
399   // Make sure to evaluate VLA bounds now so that we have them for later.
400   if (D.getType()->isVariablyModifiedType())
401     EmitVariablyModifiedType(D.getType());
402 
403   // Save the type in case adding the initializer forces a type change.
404   llvm::Type *expectedType = addr->getType();
405 
406   llvm::GlobalVariable *var =
407     cast<llvm::GlobalVariable>(addr->stripPointerCasts());
408 
409   // CUDA's local and local static __shared__ variables should not
410   // have any non-empty initializers. This is ensured by Sema.
411   // Whatever initializer such variable may have when it gets here is
412   // a no-op and should not be emitted.
413   bool isCudaSharedVar = getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
414                          D.hasAttr<CUDASharedAttr>();
415   // If this value has an initializer, emit it.
416   if (D.getInit() && !isCudaSharedVar)
417     var = AddInitializerToStaticVarDecl(D, var);
418 
419   var->setAlignment(alignment.getAsAlign());
420 
421   if (D.hasAttr<AnnotateAttr>())
422     CGM.AddGlobalAnnotations(&D, var);
423 
424   if (auto *SA = D.getAttr<PragmaClangBSSSectionAttr>())
425     var->addAttribute("bss-section", SA->getName());
426   if (auto *SA = D.getAttr<PragmaClangDataSectionAttr>())
427     var->addAttribute("data-section", SA->getName());
428   if (auto *SA = D.getAttr<PragmaClangRodataSectionAttr>())
429     var->addAttribute("rodata-section", SA->getName());
430   if (auto *SA = D.getAttr<PragmaClangRelroSectionAttr>())
431     var->addAttribute("relro-section", SA->getName());
432 
433   if (const SectionAttr *SA = D.getAttr<SectionAttr>())
434     var->setSection(SA->getName());
435 
436   if (D.hasAttr<UsedAttr>())
437     CGM.addUsedGlobal(var);
438 
439   // We may have to cast the constant because of the initializer
440   // mismatch above.
441   //
442   // FIXME: It is really dangerous to store this in the map; if anyone
443   // RAUW's the GV uses of this constant will be invalid.
444   llvm::Constant *castedAddr =
445     llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(var, expectedType);
446   if (var != castedAddr)
447     LocalDeclMap.find(&D)->second = Address(castedAddr, alignment);
448   CGM.setStaticLocalDeclAddress(&D, castedAddr);
449 
450   CGM.getSanitizerMetadata()->reportGlobalToASan(var, D);
451 
452   // Emit global variable debug descriptor for static vars.
453   CGDebugInfo *DI = getDebugInfo();
454   if (DI && CGM.getCodeGenOpts().hasReducedDebugInfo()) {
455     DI->setLocation(D.getLocation());
456     DI->EmitGlobalVariable(var, &D);
457   }
458 }
459 
460 namespace {
461   struct DestroyObject final : EHScopeStack::Cleanup {
462     DestroyObject(Address addr, QualType type,
463                   CodeGenFunction::Destroyer *destroyer,
464                   bool useEHCleanupForArray)
465       : addr(addr), type(type), destroyer(destroyer),
466         useEHCleanupForArray(useEHCleanupForArray) {}
467 
468     Address addr;
469     QualType type;
470     CodeGenFunction::Destroyer *destroyer;
471     bool useEHCleanupForArray;
472 
473     void Emit(CodeGenFunction &CGF, Flags flags) override {
474       // Don't use an EH cleanup recursively from an EH cleanup.
475       bool useEHCleanupForArray =
476         flags.isForNormalCleanup() && this->useEHCleanupForArray;
477 
478       CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
479     }
480   };
481 
482   template <class Derived>
483   struct DestroyNRVOVariable : EHScopeStack::Cleanup {
484     DestroyNRVOVariable(Address addr, QualType type, llvm::Value *NRVOFlag)
485         : NRVOFlag(NRVOFlag), Loc(addr), Ty(type) {}
486 
487     llvm::Value *NRVOFlag;
488     Address Loc;
489     QualType Ty;
490 
491     void Emit(CodeGenFunction &CGF, Flags flags) override {
492       // Along the exceptions path we always execute the dtor.
493       bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
494 
495       llvm::BasicBlock *SkipDtorBB = nullptr;
496       if (NRVO) {
497         // If we exited via NRVO, we skip the destructor call.
498         llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
499         SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
500         llvm::Value *DidNRVO =
501           CGF.Builder.CreateFlagLoad(NRVOFlag, "nrvo.val");
502         CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
503         CGF.EmitBlock(RunDtorBB);
504       }
505 
506       static_cast<Derived *>(this)->emitDestructorCall(CGF);
507 
508       if (NRVO) CGF.EmitBlock(SkipDtorBB);
509     }
510 
511     virtual ~DestroyNRVOVariable() = default;
512   };
513 
514   struct DestroyNRVOVariableCXX final
515       : DestroyNRVOVariable<DestroyNRVOVariableCXX> {
516     DestroyNRVOVariableCXX(Address addr, QualType type,
517                            const CXXDestructorDecl *Dtor, llvm::Value *NRVOFlag)
518         : DestroyNRVOVariable<DestroyNRVOVariableCXX>(addr, type, NRVOFlag),
519           Dtor(Dtor) {}
520 
521     const CXXDestructorDecl *Dtor;
522 
523     void emitDestructorCall(CodeGenFunction &CGF) {
524       CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
525                                 /*ForVirtualBase=*/false,
526                                 /*Delegating=*/false, Loc, Ty);
527     }
528   };
529 
530   struct DestroyNRVOVariableC final
531       : DestroyNRVOVariable<DestroyNRVOVariableC> {
532     DestroyNRVOVariableC(Address addr, llvm::Value *NRVOFlag, QualType Ty)
533         : DestroyNRVOVariable<DestroyNRVOVariableC>(addr, Ty, NRVOFlag) {}
534 
535     void emitDestructorCall(CodeGenFunction &CGF) {
536       CGF.destroyNonTrivialCStruct(CGF, Loc, Ty);
537     }
538   };
539 
540   struct CallStackRestore final : EHScopeStack::Cleanup {
541     Address Stack;
542     CallStackRestore(Address Stack) : Stack(Stack) {}
543     void Emit(CodeGenFunction &CGF, Flags flags) override {
544       llvm::Value *V = CGF.Builder.CreateLoad(Stack);
545       llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
546       CGF.Builder.CreateCall(F, V);
547     }
548   };
549 
550   struct ExtendGCLifetime final : EHScopeStack::Cleanup {
551     const VarDecl &Var;
552     ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
553 
554     void Emit(CodeGenFunction &CGF, Flags flags) override {
555       // Compute the address of the local variable, in case it's a
556       // byref or something.
557       DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(&Var), false,
558                       Var.getType(), VK_LValue, SourceLocation());
559       llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE),
560                                                 SourceLocation());
561       CGF.EmitExtendGCLifetime(value);
562     }
563   };
564 
565   struct CallCleanupFunction final : EHScopeStack::Cleanup {
566     llvm::Constant *CleanupFn;
567     const CGFunctionInfo &FnInfo;
568     const VarDecl &Var;
569 
570     CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
571                         const VarDecl *Var)
572       : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
573 
574     void Emit(CodeGenFunction &CGF, Flags flags) override {
575       DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(&Var), false,
576                       Var.getType(), VK_LValue, SourceLocation());
577       // Compute the address of the local variable, in case it's a byref
578       // or something.
579       llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getPointer(CGF);
580 
581       // In some cases, the type of the function argument will be different from
582       // the type of the pointer. An example of this is
583       // void f(void* arg);
584       // __attribute__((cleanup(f))) void *g;
585       //
586       // To fix this we insert a bitcast here.
587       QualType ArgTy = FnInfo.arg_begin()->type;
588       llvm::Value *Arg =
589         CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
590 
591       CallArgList Args;
592       Args.add(RValue::get(Arg),
593                CGF.getContext().getPointerType(Var.getType()));
594       auto Callee = CGCallee::forDirect(CleanupFn);
595       CGF.EmitCall(FnInfo, Callee, ReturnValueSlot(), Args);
596     }
597   };
598 } // end anonymous namespace
599 
600 /// EmitAutoVarWithLifetime - Does the setup required for an automatic
601 /// variable with lifetime.
602 static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
603                                     Address addr,
604                                     Qualifiers::ObjCLifetime lifetime) {
605   switch (lifetime) {
606   case Qualifiers::OCL_None:
607     llvm_unreachable("present but none");
608 
609   case Qualifiers::OCL_ExplicitNone:
610     // nothing to do
611     break;
612 
613   case Qualifiers::OCL_Strong: {
614     CodeGenFunction::Destroyer *destroyer =
615       (var.hasAttr<ObjCPreciseLifetimeAttr>()
616        ? CodeGenFunction::destroyARCStrongPrecise
617        : CodeGenFunction::destroyARCStrongImprecise);
618 
619     CleanupKind cleanupKind = CGF.getARCCleanupKind();
620     CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
621                     cleanupKind & EHCleanup);
622     break;
623   }
624   case Qualifiers::OCL_Autoreleasing:
625     // nothing to do
626     break;
627 
628   case Qualifiers::OCL_Weak:
629     // __weak objects always get EH cleanups; otherwise, exceptions
630     // could cause really nasty crashes instead of mere leaks.
631     CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
632                     CodeGenFunction::destroyARCWeak,
633                     /*useEHCleanup*/ true);
634     break;
635   }
636 }
637 
638 static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
639   if (const Expr *e = dyn_cast<Expr>(s)) {
640     // Skip the most common kinds of expressions that make
641     // hierarchy-walking expensive.
642     s = e = e->IgnoreParenCasts();
643 
644     if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
645       return (ref->getDecl() == &var);
646     if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
647       const BlockDecl *block = be->getBlockDecl();
648       for (const auto &I : block->captures()) {
649         if (I.getVariable() == &var)
650           return true;
651       }
652     }
653   }
654 
655   for (const Stmt *SubStmt : s->children())
656     // SubStmt might be null; as in missing decl or conditional of an if-stmt.
657     if (SubStmt && isAccessedBy(var, SubStmt))
658       return true;
659 
660   return false;
661 }
662 
663 static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
664   if (!decl) return false;
665   if (!isa<VarDecl>(decl)) return false;
666   const VarDecl *var = cast<VarDecl>(decl);
667   return isAccessedBy(*var, e);
668 }
669 
670 static bool tryEmitARCCopyWeakInit(CodeGenFunction &CGF,
671                                    const LValue &destLV, const Expr *init) {
672   bool needsCast = false;
673 
674   while (auto castExpr = dyn_cast<CastExpr>(init->IgnoreParens())) {
675     switch (castExpr->getCastKind()) {
676     // Look through casts that don't require representation changes.
677     case CK_NoOp:
678     case CK_BitCast:
679     case CK_BlockPointerToObjCPointerCast:
680       needsCast = true;
681       break;
682 
683     // If we find an l-value to r-value cast from a __weak variable,
684     // emit this operation as a copy or move.
685     case CK_LValueToRValue: {
686       const Expr *srcExpr = castExpr->getSubExpr();
687       if (srcExpr->getType().getObjCLifetime() != Qualifiers::OCL_Weak)
688         return false;
689 
690       // Emit the source l-value.
691       LValue srcLV = CGF.EmitLValue(srcExpr);
692 
693       // Handle a formal type change to avoid asserting.
694       auto srcAddr = srcLV.getAddress(CGF);
695       if (needsCast) {
696         srcAddr = CGF.Builder.CreateElementBitCast(
697             srcAddr, destLV.getAddress(CGF).getElementType());
698       }
699 
700       // If it was an l-value, use objc_copyWeak.
701       if (srcExpr->getValueKind() == VK_LValue) {
702         CGF.EmitARCCopyWeak(destLV.getAddress(CGF), srcAddr);
703       } else {
704         assert(srcExpr->getValueKind() == VK_XValue);
705         CGF.EmitARCMoveWeak(destLV.getAddress(CGF), srcAddr);
706       }
707       return true;
708     }
709 
710     // Stop at anything else.
711     default:
712       return false;
713     }
714 
715     init = castExpr->getSubExpr();
716   }
717   return false;
718 }
719 
720 static void drillIntoBlockVariable(CodeGenFunction &CGF,
721                                    LValue &lvalue,
722                                    const VarDecl *var) {
723   lvalue.setAddress(CGF.emitBlockByrefAddress(lvalue.getAddress(CGF), var));
724 }
725 
726 void CodeGenFunction::EmitNullabilityCheck(LValue LHS, llvm::Value *RHS,
727                                            SourceLocation Loc) {
728   if (!SanOpts.has(SanitizerKind::NullabilityAssign))
729     return;
730 
731   auto Nullability = LHS.getType()->getNullability(getContext());
732   if (!Nullability || *Nullability != NullabilityKind::NonNull)
733     return;
734 
735   // Check if the right hand side of the assignment is nonnull, if the left
736   // hand side must be nonnull.
737   SanitizerScope SanScope(this);
738   llvm::Value *IsNotNull = Builder.CreateIsNotNull(RHS);
739   llvm::Constant *StaticData[] = {
740       EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(LHS.getType()),
741       llvm::ConstantInt::get(Int8Ty, 0), // The LogAlignment info is unused.
742       llvm::ConstantInt::get(Int8Ty, TCK_NonnullAssign)};
743   EmitCheck({{IsNotNull, SanitizerKind::NullabilityAssign}},
744             SanitizerHandler::TypeMismatch, StaticData, RHS);
745 }
746 
747 void CodeGenFunction::EmitScalarInit(const Expr *init, const ValueDecl *D,
748                                      LValue lvalue, bool capturedByInit) {
749   Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
750   if (!lifetime) {
751     llvm::Value *value = EmitScalarExpr(init);
752     if (capturedByInit)
753       drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
754     EmitNullabilityCheck(lvalue, value, init->getExprLoc());
755     EmitStoreThroughLValue(RValue::get(value), lvalue, true);
756     return;
757   }
758 
759   if (const CXXDefaultInitExpr *DIE = dyn_cast<CXXDefaultInitExpr>(init))
760     init = DIE->getExpr();
761 
762   // If we're emitting a value with lifetime, we have to do the
763   // initialization *before* we leave the cleanup scopes.
764   if (const FullExpr *fe = dyn_cast<FullExpr>(init)) {
765     enterFullExpression(fe);
766     init = fe->getSubExpr();
767   }
768   CodeGenFunction::RunCleanupsScope Scope(*this);
769 
770   // We have to maintain the illusion that the variable is
771   // zero-initialized.  If the variable might be accessed in its
772   // initializer, zero-initialize before running the initializer, then
773   // actually perform the initialization with an assign.
774   bool accessedByInit = false;
775   if (lifetime != Qualifiers::OCL_ExplicitNone)
776     accessedByInit = (capturedByInit || isAccessedBy(D, init));
777   if (accessedByInit) {
778     LValue tempLV = lvalue;
779     // Drill down to the __block object if necessary.
780     if (capturedByInit) {
781       // We can use a simple GEP for this because it can't have been
782       // moved yet.
783       tempLV.setAddress(emitBlockByrefAddress(tempLV.getAddress(*this),
784                                               cast<VarDecl>(D),
785                                               /*follow*/ false));
786     }
787 
788     auto ty =
789         cast<llvm::PointerType>(tempLV.getAddress(*this).getElementType());
790     llvm::Value *zero = CGM.getNullPointer(ty, tempLV.getType());
791 
792     // If __weak, we want to use a barrier under certain conditions.
793     if (lifetime == Qualifiers::OCL_Weak)
794       EmitARCInitWeak(tempLV.getAddress(*this), zero);
795 
796     // Otherwise just do a simple store.
797     else
798       EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
799   }
800 
801   // Emit the initializer.
802   llvm::Value *value = nullptr;
803 
804   switch (lifetime) {
805   case Qualifiers::OCL_None:
806     llvm_unreachable("present but none");
807 
808   case Qualifiers::OCL_Strong: {
809     if (!D || !isa<VarDecl>(D) || !cast<VarDecl>(D)->isARCPseudoStrong()) {
810       value = EmitARCRetainScalarExpr(init);
811       break;
812     }
813     // If D is pseudo-strong, treat it like __unsafe_unretained here. This means
814     // that we omit the retain, and causes non-autoreleased return values to be
815     // immediately released.
816     LLVM_FALLTHROUGH;
817   }
818 
819   case Qualifiers::OCL_ExplicitNone:
820     value = EmitARCUnsafeUnretainedScalarExpr(init);
821     break;
822 
823   case Qualifiers::OCL_Weak: {
824     // If it's not accessed by the initializer, try to emit the
825     // initialization with a copy or move.
826     if (!accessedByInit && tryEmitARCCopyWeakInit(*this, lvalue, init)) {
827       return;
828     }
829 
830     // No way to optimize a producing initializer into this.  It's not
831     // worth optimizing for, because the value will immediately
832     // disappear in the common case.
833     value = EmitScalarExpr(init);
834 
835     if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
836     if (accessedByInit)
837       EmitARCStoreWeak(lvalue.getAddress(*this), value, /*ignored*/ true);
838     else
839       EmitARCInitWeak(lvalue.getAddress(*this), value);
840     return;
841   }
842 
843   case Qualifiers::OCL_Autoreleasing:
844     value = EmitARCRetainAutoreleaseScalarExpr(init);
845     break;
846   }
847 
848   if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
849 
850   EmitNullabilityCheck(lvalue, value, init->getExprLoc());
851 
852   // If the variable might have been accessed by its initializer, we
853   // might have to initialize with a barrier.  We have to do this for
854   // both __weak and __strong, but __weak got filtered out above.
855   if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
856     llvm::Value *oldValue = EmitLoadOfScalar(lvalue, init->getExprLoc());
857     EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
858     EmitARCRelease(oldValue, ARCImpreciseLifetime);
859     return;
860   }
861 
862   EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
863 }
864 
865 /// Decide whether we can emit the non-zero parts of the specified initializer
866 /// with equal or fewer than NumStores scalar stores.
867 static bool canEmitInitWithFewStoresAfterBZero(llvm::Constant *Init,
868                                                unsigned &NumStores) {
869   // Zero and Undef never requires any extra stores.
870   if (isa<llvm::ConstantAggregateZero>(Init) ||
871       isa<llvm::ConstantPointerNull>(Init) ||
872       isa<llvm::UndefValue>(Init))
873     return true;
874   if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
875       isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
876       isa<llvm::ConstantExpr>(Init))
877     return Init->isNullValue() || NumStores--;
878 
879   // See if we can emit each element.
880   if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
881     for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
882       llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
883       if (!canEmitInitWithFewStoresAfterBZero(Elt, NumStores))
884         return false;
885     }
886     return true;
887   }
888 
889   if (llvm::ConstantDataSequential *CDS =
890         dyn_cast<llvm::ConstantDataSequential>(Init)) {
891     for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
892       llvm::Constant *Elt = CDS->getElementAsConstant(i);
893       if (!canEmitInitWithFewStoresAfterBZero(Elt, NumStores))
894         return false;
895     }
896     return true;
897   }
898 
899   // Anything else is hard and scary.
900   return false;
901 }
902 
903 /// For inits that canEmitInitWithFewStoresAfterBZero returned true for, emit
904 /// the scalar stores that would be required.
905 static void emitStoresForInitAfterBZero(CodeGenModule &CGM,
906                                         llvm::Constant *Init, Address Loc,
907                                         bool isVolatile, CGBuilderTy &Builder) {
908   assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) &&
909          "called emitStoresForInitAfterBZero for zero or undef value.");
910 
911   if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
912       isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
913       isa<llvm::ConstantExpr>(Init)) {
914     Builder.CreateStore(Init, Loc, isVolatile);
915     return;
916   }
917 
918   if (llvm::ConstantDataSequential *CDS =
919           dyn_cast<llvm::ConstantDataSequential>(Init)) {
920     for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
921       llvm::Constant *Elt = CDS->getElementAsConstant(i);
922 
923       // If necessary, get a pointer to the element and emit it.
924       if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
925         emitStoresForInitAfterBZero(
926             CGM, Elt, Builder.CreateConstInBoundsGEP2_32(Loc, 0, i), isVolatile,
927             Builder);
928     }
929     return;
930   }
931 
932   assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
933          "Unknown value type!");
934 
935   for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
936     llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
937 
938     // If necessary, get a pointer to the element and emit it.
939     if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
940       emitStoresForInitAfterBZero(CGM, Elt,
941                                   Builder.CreateConstInBoundsGEP2_32(Loc, 0, i),
942                                   isVolatile, Builder);
943   }
944 }
945 
946 /// Decide whether we should use bzero plus some stores to initialize a local
947 /// variable instead of using a memcpy from a constant global.  It is beneficial
948 /// to use bzero if the global is all zeros, or mostly zeros and large.
949 static bool shouldUseBZeroPlusStoresToInitialize(llvm::Constant *Init,
950                                                  uint64_t GlobalSize) {
951   // If a global is all zeros, always use a bzero.
952   if (isa<llvm::ConstantAggregateZero>(Init)) return true;
953 
954   // If a non-zero global is <= 32 bytes, always use a memcpy.  If it is large,
955   // do it if it will require 6 or fewer scalar stores.
956   // TODO: Should budget depends on the size?  Avoiding a large global warrants
957   // plopping in more stores.
958   unsigned StoreBudget = 6;
959   uint64_t SizeLimit = 32;
960 
961   return GlobalSize > SizeLimit &&
962          canEmitInitWithFewStoresAfterBZero(Init, StoreBudget);
963 }
964 
965 /// Decide whether we should use memset to initialize a local variable instead
966 /// of using a memcpy from a constant global. Assumes we've already decided to
967 /// not user bzero.
968 /// FIXME We could be more clever, as we are for bzero above, and generate
969 ///       memset followed by stores. It's unclear that's worth the effort.
970 static llvm::Value *shouldUseMemSetToInitialize(llvm::Constant *Init,
971                                                 uint64_t GlobalSize,
972                                                 const llvm::DataLayout &DL) {
973   uint64_t SizeLimit = 32;
974   if (GlobalSize <= SizeLimit)
975     return nullptr;
976   return llvm::isBytewiseValue(Init, DL);
977 }
978 
979 /// Decide whether we want to split a constant structure or array store into a
980 /// sequence of its fields' stores. This may cost us code size and compilation
981 /// speed, but plays better with store optimizations.
982 static bool shouldSplitConstantStore(CodeGenModule &CGM,
983                                      uint64_t GlobalByteSize) {
984   // Don't break things that occupy more than one cacheline.
985   uint64_t ByteSizeLimit = 64;
986   if (CGM.getCodeGenOpts().OptimizationLevel == 0)
987     return false;
988   if (GlobalByteSize <= ByteSizeLimit)
989     return true;
990   return false;
991 }
992 
993 enum class IsPattern { No, Yes };
994 
995 /// Generate a constant filled with either a pattern or zeroes.
996 static llvm::Constant *patternOrZeroFor(CodeGenModule &CGM, IsPattern isPattern,
997                                         llvm::Type *Ty) {
998   if (isPattern == IsPattern::Yes)
999     return initializationPatternFor(CGM, Ty);
1000   else
1001     return llvm::Constant::getNullValue(Ty);
1002 }
1003 
1004 static llvm::Constant *constWithPadding(CodeGenModule &CGM, IsPattern isPattern,
1005                                         llvm::Constant *constant);
1006 
1007 /// Helper function for constWithPadding() to deal with padding in structures.
1008 static llvm::Constant *constStructWithPadding(CodeGenModule &CGM,
1009                                               IsPattern isPattern,
1010                                               llvm::StructType *STy,
1011                                               llvm::Constant *constant) {
1012   const llvm::DataLayout &DL = CGM.getDataLayout();
1013   const llvm::StructLayout *Layout = DL.getStructLayout(STy);
1014   llvm::Type *Int8Ty = llvm::IntegerType::getInt8Ty(CGM.getLLVMContext());
1015   unsigned SizeSoFar = 0;
1016   SmallVector<llvm::Constant *, 8> Values;
1017   bool NestedIntact = true;
1018   for (unsigned i = 0, e = STy->getNumElements(); i != e; i++) {
1019     unsigned CurOff = Layout->getElementOffset(i);
1020     if (SizeSoFar < CurOff) {
1021       assert(!STy->isPacked());
1022       auto *PadTy = llvm::ArrayType::get(Int8Ty, CurOff - SizeSoFar);
1023       Values.push_back(patternOrZeroFor(CGM, isPattern, PadTy));
1024     }
1025     llvm::Constant *CurOp;
1026     if (constant->isZeroValue())
1027       CurOp = llvm::Constant::getNullValue(STy->getElementType(i));
1028     else
1029       CurOp = cast<llvm::Constant>(constant->getAggregateElement(i));
1030     auto *NewOp = constWithPadding(CGM, isPattern, CurOp);
1031     if (CurOp != NewOp)
1032       NestedIntact = false;
1033     Values.push_back(NewOp);
1034     SizeSoFar = CurOff + DL.getTypeAllocSize(CurOp->getType());
1035   }
1036   unsigned TotalSize = Layout->getSizeInBytes();
1037   if (SizeSoFar < TotalSize) {
1038     auto *PadTy = llvm::ArrayType::get(Int8Ty, TotalSize - SizeSoFar);
1039     Values.push_back(patternOrZeroFor(CGM, isPattern, PadTy));
1040   }
1041   if (NestedIntact && Values.size() == STy->getNumElements())
1042     return constant;
1043   return llvm::ConstantStruct::getAnon(Values, STy->isPacked());
1044 }
1045 
1046 /// Replace all padding bytes in a given constant with either a pattern byte or
1047 /// 0x00.
1048 static llvm::Constant *constWithPadding(CodeGenModule &CGM, IsPattern isPattern,
1049                                         llvm::Constant *constant) {
1050   llvm::Type *OrigTy = constant->getType();
1051   if (const auto STy = dyn_cast<llvm::StructType>(OrigTy))
1052     return constStructWithPadding(CGM, isPattern, STy, constant);
1053   if (auto *ArrayTy = dyn_cast<llvm::ArrayType>(OrigTy)) {
1054     llvm::SmallVector<llvm::Constant *, 8> Values;
1055     uint64_t Size = ArrayTy->getNumElements();
1056     if (!Size)
1057       return constant;
1058     llvm::Type *ElemTy = ArrayTy->getElementType();
1059     bool ZeroInitializer = constant->isNullValue();
1060     llvm::Constant *OpValue, *PaddedOp;
1061     if (ZeroInitializer) {
1062       OpValue = llvm::Constant::getNullValue(ElemTy);
1063       PaddedOp = constWithPadding(CGM, isPattern, OpValue);
1064     }
1065     for (unsigned Op = 0; Op != Size; ++Op) {
1066       if (!ZeroInitializer) {
1067         OpValue = constant->getAggregateElement(Op);
1068         PaddedOp = constWithPadding(CGM, isPattern, OpValue);
1069       }
1070       Values.push_back(PaddedOp);
1071     }
1072     auto *NewElemTy = Values[0]->getType();
1073     if (NewElemTy == ElemTy)
1074       return constant;
1075     auto *NewArrayTy = llvm::ArrayType::get(NewElemTy, Size);
1076     return llvm::ConstantArray::get(NewArrayTy, Values);
1077   }
1078   // FIXME: Add handling for tail padding in vectors. Vectors don't
1079   // have padding between or inside elements, but the total amount of
1080   // data can be less than the allocated size.
1081   return constant;
1082 }
1083 
1084 Address CodeGenModule::createUnnamedGlobalFrom(const VarDecl &D,
1085                                                llvm::Constant *Constant,
1086                                                CharUnits Align) {
1087   auto FunctionName = [&](const DeclContext *DC) -> std::string {
1088     if (const auto *FD = dyn_cast<FunctionDecl>(DC)) {
1089       if (const auto *CC = dyn_cast<CXXConstructorDecl>(FD))
1090         return CC->getNameAsString();
1091       if (const auto *CD = dyn_cast<CXXDestructorDecl>(FD))
1092         return CD->getNameAsString();
1093       return std::string(getMangledName(FD));
1094     } else if (const auto *OM = dyn_cast<ObjCMethodDecl>(DC)) {
1095       return OM->getNameAsString();
1096     } else if (isa<BlockDecl>(DC)) {
1097       return "<block>";
1098     } else if (isa<CapturedDecl>(DC)) {
1099       return "<captured>";
1100     } else {
1101       llvm_unreachable("expected a function or method");
1102     }
1103   };
1104 
1105   // Form a simple per-variable cache of these values in case we find we
1106   // want to reuse them.
1107   llvm::GlobalVariable *&CacheEntry = InitializerConstants[&D];
1108   if (!CacheEntry || CacheEntry->getInitializer() != Constant) {
1109     auto *Ty = Constant->getType();
1110     bool isConstant = true;
1111     llvm::GlobalVariable *InsertBefore = nullptr;
1112     unsigned AS =
1113         getContext().getTargetAddressSpace(getStringLiteralAddressSpace());
1114     std::string Name;
1115     if (D.hasGlobalStorage())
1116       Name = getMangledName(&D).str() + ".const";
1117     else if (const DeclContext *DC = D.getParentFunctionOrMethod())
1118       Name = ("__const." + FunctionName(DC) + "." + D.getName()).str();
1119     else
1120       llvm_unreachable("local variable has no parent function or method");
1121     llvm::GlobalVariable *GV = new llvm::GlobalVariable(
1122         getModule(), Ty, isConstant, llvm::GlobalValue::PrivateLinkage,
1123         Constant, Name, InsertBefore, llvm::GlobalValue::NotThreadLocal, AS);
1124     GV->setAlignment(Align.getAsAlign());
1125     GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1126     CacheEntry = GV;
1127   } else if (CacheEntry->getAlignment() < Align.getQuantity()) {
1128     CacheEntry->setAlignment(Align.getAsAlign());
1129   }
1130 
1131   return Address(CacheEntry, Align);
1132 }
1133 
1134 static Address createUnnamedGlobalForMemcpyFrom(CodeGenModule &CGM,
1135                                                 const VarDecl &D,
1136                                                 CGBuilderTy &Builder,
1137                                                 llvm::Constant *Constant,
1138                                                 CharUnits Align) {
1139   Address SrcPtr = CGM.createUnnamedGlobalFrom(D, Constant, Align);
1140   llvm::Type *BP = llvm::PointerType::getInt8PtrTy(CGM.getLLVMContext(),
1141                                                    SrcPtr.getAddressSpace());
1142   if (SrcPtr.getType() != BP)
1143     SrcPtr = Builder.CreateBitCast(SrcPtr, BP);
1144   return SrcPtr;
1145 }
1146 
1147 static void emitStoresForConstant(CodeGenModule &CGM, const VarDecl &D,
1148                                   Address Loc, bool isVolatile,
1149                                   CGBuilderTy &Builder,
1150                                   llvm::Constant *constant) {
1151   auto *Ty = constant->getType();
1152   uint64_t ConstantSize = CGM.getDataLayout().getTypeAllocSize(Ty);
1153   if (!ConstantSize)
1154     return;
1155 
1156   bool canDoSingleStore = Ty->isIntOrIntVectorTy() ||
1157                           Ty->isPtrOrPtrVectorTy() || Ty->isFPOrFPVectorTy();
1158   if (canDoSingleStore) {
1159     Builder.CreateStore(constant, Loc, isVolatile);
1160     return;
1161   }
1162 
1163   auto *SizeVal = llvm::ConstantInt::get(CGM.IntPtrTy, ConstantSize);
1164 
1165   // If the initializer is all or mostly the same, codegen with bzero / memset
1166   // then do a few stores afterward.
1167   if (shouldUseBZeroPlusStoresToInitialize(constant, ConstantSize)) {
1168     Builder.CreateMemSet(Loc, llvm::ConstantInt::get(CGM.Int8Ty, 0), SizeVal,
1169                          isVolatile);
1170 
1171     bool valueAlreadyCorrect =
1172         constant->isNullValue() || isa<llvm::UndefValue>(constant);
1173     if (!valueAlreadyCorrect) {
1174       Loc = Builder.CreateBitCast(Loc, Ty->getPointerTo(Loc.getAddressSpace()));
1175       emitStoresForInitAfterBZero(CGM, constant, Loc, isVolatile, Builder);
1176     }
1177     return;
1178   }
1179 
1180   // If the initializer is a repeated byte pattern, use memset.
1181   llvm::Value *Pattern =
1182       shouldUseMemSetToInitialize(constant, ConstantSize, CGM.getDataLayout());
1183   if (Pattern) {
1184     uint64_t Value = 0x00;
1185     if (!isa<llvm::UndefValue>(Pattern)) {
1186       const llvm::APInt &AP = cast<llvm::ConstantInt>(Pattern)->getValue();
1187       assert(AP.getBitWidth() <= 8);
1188       Value = AP.getLimitedValue();
1189     }
1190     Builder.CreateMemSet(Loc, llvm::ConstantInt::get(CGM.Int8Ty, Value), SizeVal,
1191                          isVolatile);
1192     return;
1193   }
1194 
1195   // If the initializer is small, use a handful of stores.
1196   if (shouldSplitConstantStore(CGM, ConstantSize)) {
1197     if (auto *STy = dyn_cast<llvm::StructType>(Ty)) {
1198       // FIXME: handle the case when STy != Loc.getElementType().
1199       if (STy == Loc.getElementType()) {
1200         for (unsigned i = 0; i != constant->getNumOperands(); i++) {
1201           Address EltPtr = Builder.CreateStructGEP(Loc, i);
1202           emitStoresForConstant(
1203               CGM, D, EltPtr, isVolatile, Builder,
1204               cast<llvm::Constant>(Builder.CreateExtractValue(constant, i)));
1205         }
1206         return;
1207       }
1208     } else if (auto *ATy = dyn_cast<llvm::ArrayType>(Ty)) {
1209       // FIXME: handle the case when ATy != Loc.getElementType().
1210       if (ATy == Loc.getElementType()) {
1211         for (unsigned i = 0; i != ATy->getNumElements(); i++) {
1212           Address EltPtr = Builder.CreateConstArrayGEP(Loc, i);
1213           emitStoresForConstant(
1214               CGM, D, EltPtr, isVolatile, Builder,
1215               cast<llvm::Constant>(Builder.CreateExtractValue(constant, i)));
1216         }
1217         return;
1218       }
1219     }
1220   }
1221 
1222   // Copy from a global.
1223   Builder.CreateMemCpy(Loc,
1224                        createUnnamedGlobalForMemcpyFrom(
1225                            CGM, D, Builder, constant, Loc.getAlignment()),
1226                        SizeVal, isVolatile);
1227 }
1228 
1229 static void emitStoresForZeroInit(CodeGenModule &CGM, const VarDecl &D,
1230                                   Address Loc, bool isVolatile,
1231                                   CGBuilderTy &Builder) {
1232   llvm::Type *ElTy = Loc.getElementType();
1233   llvm::Constant *constant =
1234       constWithPadding(CGM, IsPattern::No, llvm::Constant::getNullValue(ElTy));
1235   emitStoresForConstant(CGM, D, Loc, isVolatile, Builder, constant);
1236 }
1237 
1238 static void emitStoresForPatternInit(CodeGenModule &CGM, const VarDecl &D,
1239                                      Address Loc, bool isVolatile,
1240                                      CGBuilderTy &Builder) {
1241   llvm::Type *ElTy = Loc.getElementType();
1242   llvm::Constant *constant = constWithPadding(
1243       CGM, IsPattern::Yes, initializationPatternFor(CGM, ElTy));
1244   assert(!isa<llvm::UndefValue>(constant));
1245   emitStoresForConstant(CGM, D, Loc, isVolatile, Builder, constant);
1246 }
1247 
1248 static bool containsUndef(llvm::Constant *constant) {
1249   auto *Ty = constant->getType();
1250   if (isa<llvm::UndefValue>(constant))
1251     return true;
1252   if (Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy())
1253     for (llvm::Use &Op : constant->operands())
1254       if (containsUndef(cast<llvm::Constant>(Op)))
1255         return true;
1256   return false;
1257 }
1258 
1259 static llvm::Constant *replaceUndef(CodeGenModule &CGM, IsPattern isPattern,
1260                                     llvm::Constant *constant) {
1261   auto *Ty = constant->getType();
1262   if (isa<llvm::UndefValue>(constant))
1263     return patternOrZeroFor(CGM, isPattern, Ty);
1264   if (!(Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()))
1265     return constant;
1266   if (!containsUndef(constant))
1267     return constant;
1268   llvm::SmallVector<llvm::Constant *, 8> Values(constant->getNumOperands());
1269   for (unsigned Op = 0, NumOp = constant->getNumOperands(); Op != NumOp; ++Op) {
1270     auto *OpValue = cast<llvm::Constant>(constant->getOperand(Op));
1271     Values[Op] = replaceUndef(CGM, isPattern, OpValue);
1272   }
1273   if (Ty->isStructTy())
1274     return llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Values);
1275   if (Ty->isArrayTy())
1276     return llvm::ConstantArray::get(cast<llvm::ArrayType>(Ty), Values);
1277   assert(Ty->isVectorTy());
1278   return llvm::ConstantVector::get(Values);
1279 }
1280 
1281 /// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
1282 /// variable declaration with auto, register, or no storage class specifier.
1283 /// These turn into simple stack objects, or GlobalValues depending on target.
1284 void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
1285   AutoVarEmission emission = EmitAutoVarAlloca(D);
1286   EmitAutoVarInit(emission);
1287   EmitAutoVarCleanups(emission);
1288 }
1289 
1290 /// Emit a lifetime.begin marker if some criteria are satisfied.
1291 /// \return a pointer to the temporary size Value if a marker was emitted, null
1292 /// otherwise
1293 llvm::Value *CodeGenFunction::EmitLifetimeStart(uint64_t Size,
1294                                                 llvm::Value *Addr) {
1295   if (!ShouldEmitLifetimeMarkers)
1296     return nullptr;
1297 
1298   assert(Addr->getType()->getPointerAddressSpace() ==
1299              CGM.getDataLayout().getAllocaAddrSpace() &&
1300          "Pointer should be in alloca address space");
1301   llvm::Value *SizeV = llvm::ConstantInt::get(Int64Ty, Size);
1302   Addr = Builder.CreateBitCast(Addr, AllocaInt8PtrTy);
1303   llvm::CallInst *C =
1304       Builder.CreateCall(CGM.getLLVMLifetimeStartFn(), {SizeV, Addr});
1305   C->setDoesNotThrow();
1306   return SizeV;
1307 }
1308 
1309 void CodeGenFunction::EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr) {
1310   assert(Addr->getType()->getPointerAddressSpace() ==
1311              CGM.getDataLayout().getAllocaAddrSpace() &&
1312          "Pointer should be in alloca address space");
1313   Addr = Builder.CreateBitCast(Addr, AllocaInt8PtrTy);
1314   llvm::CallInst *C =
1315       Builder.CreateCall(CGM.getLLVMLifetimeEndFn(), {Size, Addr});
1316   C->setDoesNotThrow();
1317 }
1318 
1319 void CodeGenFunction::EmitAndRegisterVariableArrayDimensions(
1320     CGDebugInfo *DI, const VarDecl &D, bool EmitDebugInfo) {
1321   // For each dimension stores its QualType and corresponding
1322   // size-expression Value.
1323   SmallVector<CodeGenFunction::VlaSizePair, 4> Dimensions;
1324   SmallVector<IdentifierInfo *, 4> VLAExprNames;
1325 
1326   // Break down the array into individual dimensions.
1327   QualType Type1D = D.getType();
1328   while (getContext().getAsVariableArrayType(Type1D)) {
1329     auto VlaSize = getVLAElements1D(Type1D);
1330     if (auto *C = dyn_cast<llvm::ConstantInt>(VlaSize.NumElts))
1331       Dimensions.emplace_back(C, Type1D.getUnqualifiedType());
1332     else {
1333       // Generate a locally unique name for the size expression.
1334       Twine Name = Twine("__vla_expr") + Twine(VLAExprCounter++);
1335       SmallString<12> Buffer;
1336       StringRef NameRef = Name.toStringRef(Buffer);
1337       auto &Ident = getContext().Idents.getOwn(NameRef);
1338       VLAExprNames.push_back(&Ident);
1339       auto SizeExprAddr =
1340           CreateDefaultAlignTempAlloca(VlaSize.NumElts->getType(), NameRef);
1341       Builder.CreateStore(VlaSize.NumElts, SizeExprAddr);
1342       Dimensions.emplace_back(SizeExprAddr.getPointer(),
1343                               Type1D.getUnqualifiedType());
1344     }
1345     Type1D = VlaSize.Type;
1346   }
1347 
1348   if (!EmitDebugInfo)
1349     return;
1350 
1351   // Register each dimension's size-expression with a DILocalVariable,
1352   // so that it can be used by CGDebugInfo when instantiating a DISubrange
1353   // to describe this array.
1354   unsigned NameIdx = 0;
1355   for (auto &VlaSize : Dimensions) {
1356     llvm::Metadata *MD;
1357     if (auto *C = dyn_cast<llvm::ConstantInt>(VlaSize.NumElts))
1358       MD = llvm::ConstantAsMetadata::get(C);
1359     else {
1360       // Create an artificial VarDecl to generate debug info for.
1361       IdentifierInfo *NameIdent = VLAExprNames[NameIdx++];
1362       auto VlaExprTy = VlaSize.NumElts->getType()->getPointerElementType();
1363       auto QT = getContext().getIntTypeForBitwidth(
1364           VlaExprTy->getScalarSizeInBits(), false);
1365       auto *ArtificialDecl = VarDecl::Create(
1366           getContext(), const_cast<DeclContext *>(D.getDeclContext()),
1367           D.getLocation(), D.getLocation(), NameIdent, QT,
1368           getContext().CreateTypeSourceInfo(QT), SC_Auto);
1369       ArtificialDecl->setImplicit();
1370 
1371       MD = DI->EmitDeclareOfAutoVariable(ArtificialDecl, VlaSize.NumElts,
1372                                          Builder);
1373     }
1374     assert(MD && "No Size expression debug node created");
1375     DI->registerVLASizeExpression(VlaSize.Type, MD);
1376   }
1377 }
1378 
1379 /// EmitAutoVarAlloca - Emit the alloca and debug information for a
1380 /// local variable.  Does not emit initialization or destruction.
1381 CodeGenFunction::AutoVarEmission
1382 CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
1383   QualType Ty = D.getType();
1384   assert(
1385       Ty.getAddressSpace() == LangAS::Default ||
1386       (Ty.getAddressSpace() == LangAS::opencl_private && getLangOpts().OpenCL));
1387 
1388   AutoVarEmission emission(D);
1389 
1390   bool isEscapingByRef = D.isEscapingByref();
1391   emission.IsEscapingByRef = isEscapingByRef;
1392 
1393   CharUnits alignment = getContext().getDeclAlign(&D);
1394 
1395   // If the type is variably-modified, emit all the VLA sizes for it.
1396   if (Ty->isVariablyModifiedType())
1397     EmitVariablyModifiedType(Ty);
1398 
1399   auto *DI = getDebugInfo();
1400   bool EmitDebugInfo = DI && CGM.getCodeGenOpts().hasReducedDebugInfo();
1401 
1402   Address address = Address::invalid();
1403   Address AllocaAddr = Address::invalid();
1404   Address OpenMPLocalAddr =
1405       getLangOpts().OpenMP
1406           ? CGM.getOpenMPRuntime().getAddressOfLocalVariable(*this, &D)
1407           : Address::invalid();
1408   bool NRVO = getLangOpts().ElideConstructors && D.isNRVOVariable();
1409 
1410   if (getLangOpts().OpenMP && OpenMPLocalAddr.isValid()) {
1411     address = OpenMPLocalAddr;
1412   } else if (Ty->isConstantSizeType()) {
1413     // If this value is an array or struct with a statically determinable
1414     // constant initializer, there are optimizations we can do.
1415     //
1416     // TODO: We should constant-evaluate the initializer of any variable,
1417     // as long as it is initialized by a constant expression. Currently,
1418     // isConstantInitializer produces wrong answers for structs with
1419     // reference or bitfield members, and a few other cases, and checking
1420     // for POD-ness protects us from some of these.
1421     if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) &&
1422         (D.isConstexpr() ||
1423          ((Ty.isPODType(getContext()) ||
1424            getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
1425           D.getInit()->isConstantInitializer(getContext(), false)))) {
1426 
1427       // If the variable's a const type, and it's neither an NRVO
1428       // candidate nor a __block variable and has no mutable members,
1429       // emit it as a global instead.
1430       // Exception is if a variable is located in non-constant address space
1431       // in OpenCL.
1432       if ((!getLangOpts().OpenCL ||
1433            Ty.getAddressSpace() == LangAS::opencl_constant) &&
1434           (CGM.getCodeGenOpts().MergeAllConstants && !NRVO &&
1435            !isEscapingByRef && CGM.isTypeConstant(Ty, true))) {
1436         EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
1437 
1438         // Signal this condition to later callbacks.
1439         emission.Addr = Address::invalid();
1440         assert(emission.wasEmittedAsGlobal());
1441         return emission;
1442       }
1443 
1444       // Otherwise, tell the initialization code that we're in this case.
1445       emission.IsConstantAggregate = true;
1446     }
1447 
1448     // A normal fixed sized variable becomes an alloca in the entry block,
1449     // unless:
1450     // - it's an NRVO variable.
1451     // - we are compiling OpenMP and it's an OpenMP local variable.
1452     if (NRVO) {
1453       // The named return value optimization: allocate this variable in the
1454       // return slot, so that we can elide the copy when returning this
1455       // variable (C++0x [class.copy]p34).
1456       address = ReturnValue;
1457 
1458       if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
1459         const auto *RD = RecordTy->getDecl();
1460         const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
1461         if ((CXXRD && !CXXRD->hasTrivialDestructor()) ||
1462             RD->isNonTrivialToPrimitiveDestroy()) {
1463           // Create a flag that is used to indicate when the NRVO was applied
1464           // to this variable. Set it to zero to indicate that NRVO was not
1465           // applied.
1466           llvm::Value *Zero = Builder.getFalse();
1467           Address NRVOFlag =
1468             CreateTempAlloca(Zero->getType(), CharUnits::One(), "nrvo");
1469           EnsureInsertPoint();
1470           Builder.CreateStore(Zero, NRVOFlag);
1471 
1472           // Record the NRVO flag for this variable.
1473           NRVOFlags[&D] = NRVOFlag.getPointer();
1474           emission.NRVOFlag = NRVOFlag.getPointer();
1475         }
1476       }
1477     } else {
1478       CharUnits allocaAlignment;
1479       llvm::Type *allocaTy;
1480       if (isEscapingByRef) {
1481         auto &byrefInfo = getBlockByrefInfo(&D);
1482         allocaTy = byrefInfo.Type;
1483         allocaAlignment = byrefInfo.ByrefAlignment;
1484       } else {
1485         allocaTy = ConvertTypeForMem(Ty);
1486         allocaAlignment = alignment;
1487       }
1488 
1489       // Create the alloca.  Note that we set the name separately from
1490       // building the instruction so that it's there even in no-asserts
1491       // builds.
1492       address = CreateTempAlloca(allocaTy, allocaAlignment, D.getName(),
1493                                  /*ArraySize=*/nullptr, &AllocaAddr);
1494 
1495       // Don't emit lifetime markers for MSVC catch parameters. The lifetime of
1496       // the catch parameter starts in the catchpad instruction, and we can't
1497       // insert code in those basic blocks.
1498       bool IsMSCatchParam =
1499           D.isExceptionVariable() && getTarget().getCXXABI().isMicrosoft();
1500 
1501       // Emit a lifetime intrinsic if meaningful. There's no point in doing this
1502       // if we don't have a valid insertion point (?).
1503       if (HaveInsertPoint() && !IsMSCatchParam) {
1504         // If there's a jump into the lifetime of this variable, its lifetime
1505         // gets broken up into several regions in IR, which requires more work
1506         // to handle correctly. For now, just omit the intrinsics; this is a
1507         // rare case, and it's better to just be conservatively correct.
1508         // PR28267.
1509         //
1510         // We have to do this in all language modes if there's a jump past the
1511         // declaration. We also have to do it in C if there's a jump to an
1512         // earlier point in the current block because non-VLA lifetimes begin as
1513         // soon as the containing block is entered, not when its variables
1514         // actually come into scope; suppressing the lifetime annotations
1515         // completely in this case is unnecessarily pessimistic, but again, this
1516         // is rare.
1517         if (!Bypasses.IsBypassed(&D) &&
1518             !(!getLangOpts().CPlusPlus && hasLabelBeenSeenInCurrentScope())) {
1519           llvm::TypeSize size =
1520               CGM.getDataLayout().getTypeAllocSize(allocaTy);
1521           emission.SizeForLifetimeMarkers =
1522               size.isScalable() ? EmitLifetimeStart(-1, AllocaAddr.getPointer())
1523                                 : EmitLifetimeStart(size.getFixedSize(),
1524                                                     AllocaAddr.getPointer());
1525         }
1526       } else {
1527         assert(!emission.useLifetimeMarkers());
1528       }
1529     }
1530   } else {
1531     EnsureInsertPoint();
1532 
1533     if (!DidCallStackSave) {
1534       // Save the stack.
1535       Address Stack =
1536         CreateTempAlloca(Int8PtrTy, getPointerAlign(), "saved_stack");
1537 
1538       llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
1539       llvm::Value *V = Builder.CreateCall(F);
1540       Builder.CreateStore(V, Stack);
1541 
1542       DidCallStackSave = true;
1543 
1544       // Push a cleanup block and restore the stack there.
1545       // FIXME: in general circumstances, this should be an EH cleanup.
1546       pushStackRestore(NormalCleanup, Stack);
1547     }
1548 
1549     auto VlaSize = getVLASize(Ty);
1550     llvm::Type *llvmTy = ConvertTypeForMem(VlaSize.Type);
1551 
1552     // Allocate memory for the array.
1553     address = CreateTempAlloca(llvmTy, alignment, "vla", VlaSize.NumElts,
1554                                &AllocaAddr);
1555 
1556     // If we have debug info enabled, properly describe the VLA dimensions for
1557     // this type by registering the vla size expression for each of the
1558     // dimensions.
1559     EmitAndRegisterVariableArrayDimensions(DI, D, EmitDebugInfo);
1560   }
1561 
1562   setAddrOfLocalVar(&D, address);
1563   emission.Addr = address;
1564   emission.AllocaAddr = AllocaAddr;
1565 
1566   // Emit debug info for local var declaration.
1567   if (EmitDebugInfo && HaveInsertPoint()) {
1568     Address DebugAddr = address;
1569     bool UsePointerValue = NRVO && ReturnValuePointer.isValid();
1570     DI->setLocation(D.getLocation());
1571 
1572     // If NRVO, use a pointer to the return address.
1573     if (UsePointerValue)
1574       DebugAddr = ReturnValuePointer;
1575 
1576     (void)DI->EmitDeclareOfAutoVariable(&D, DebugAddr.getPointer(), Builder,
1577                                         UsePointerValue);
1578   }
1579 
1580   if (D.hasAttr<AnnotateAttr>() && HaveInsertPoint())
1581     EmitVarAnnotations(&D, address.getPointer());
1582 
1583   // Make sure we call @llvm.lifetime.end.
1584   if (emission.useLifetimeMarkers())
1585     EHStack.pushCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker,
1586                                          emission.getOriginalAllocatedAddress(),
1587                                          emission.getSizeForLifetimeMarkers());
1588 
1589   return emission;
1590 }
1591 
1592 static bool isCapturedBy(const VarDecl &, const Expr *);
1593 
1594 /// Determines whether the given __block variable is potentially
1595 /// captured by the given statement.
1596 static bool isCapturedBy(const VarDecl &Var, const Stmt *S) {
1597   if (const Expr *E = dyn_cast<Expr>(S))
1598     return isCapturedBy(Var, E);
1599   for (const Stmt *SubStmt : S->children())
1600     if (isCapturedBy(Var, SubStmt))
1601       return true;
1602   return false;
1603 }
1604 
1605 /// Determines whether the given __block variable is potentially
1606 /// captured by the given expression.
1607 static bool isCapturedBy(const VarDecl &Var, const Expr *E) {
1608   // Skip the most common kinds of expressions that make
1609   // hierarchy-walking expensive.
1610   E = E->IgnoreParenCasts();
1611 
1612   if (const BlockExpr *BE = dyn_cast<BlockExpr>(E)) {
1613     const BlockDecl *Block = BE->getBlockDecl();
1614     for (const auto &I : Block->captures()) {
1615       if (I.getVariable() == &Var)
1616         return true;
1617     }
1618 
1619     // No need to walk into the subexpressions.
1620     return false;
1621   }
1622 
1623   if (const StmtExpr *SE = dyn_cast<StmtExpr>(E)) {
1624     const CompoundStmt *CS = SE->getSubStmt();
1625     for (const auto *BI : CS->body())
1626       if (const auto *BIE = dyn_cast<Expr>(BI)) {
1627         if (isCapturedBy(Var, BIE))
1628           return true;
1629       }
1630       else if (const auto *DS = dyn_cast<DeclStmt>(BI)) {
1631           // special case declarations
1632           for (const auto *I : DS->decls()) {
1633               if (const auto *VD = dyn_cast<VarDecl>((I))) {
1634                 const Expr *Init = VD->getInit();
1635                 if (Init && isCapturedBy(Var, Init))
1636                   return true;
1637               }
1638           }
1639       }
1640       else
1641         // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
1642         // Later, provide code to poke into statements for capture analysis.
1643         return true;
1644     return false;
1645   }
1646 
1647   for (const Stmt *SubStmt : E->children())
1648     if (isCapturedBy(Var, SubStmt))
1649       return true;
1650 
1651   return false;
1652 }
1653 
1654 /// Determine whether the given initializer is trivial in the sense
1655 /// that it requires no code to be generated.
1656 bool CodeGenFunction::isTrivialInitializer(const Expr *Init) {
1657   if (!Init)
1658     return true;
1659 
1660   if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
1661     if (CXXConstructorDecl *Constructor = Construct->getConstructor())
1662       if (Constructor->isTrivial() &&
1663           Constructor->isDefaultConstructor() &&
1664           !Construct->requiresZeroInitialization())
1665         return true;
1666 
1667   return false;
1668 }
1669 
1670 void CodeGenFunction::emitZeroOrPatternForAutoVarInit(QualType type,
1671                                                       const VarDecl &D,
1672                                                       Address Loc) {
1673   auto trivialAutoVarInit = getContext().getLangOpts().getTrivialAutoVarInit();
1674   CharUnits Size = getContext().getTypeSizeInChars(type);
1675   bool isVolatile = type.isVolatileQualified();
1676   if (!Size.isZero()) {
1677     switch (trivialAutoVarInit) {
1678     case LangOptions::TrivialAutoVarInitKind::Uninitialized:
1679       llvm_unreachable("Uninitialized handled by caller");
1680     case LangOptions::TrivialAutoVarInitKind::Zero:
1681       emitStoresForZeroInit(CGM, D, Loc, isVolatile, Builder);
1682       break;
1683     case LangOptions::TrivialAutoVarInitKind::Pattern:
1684       emitStoresForPatternInit(CGM, D, Loc, isVolatile, Builder);
1685       break;
1686     }
1687     return;
1688   }
1689 
1690   // VLAs look zero-sized to getTypeInfo. We can't emit constant stores to
1691   // them, so emit a memcpy with the VLA size to initialize each element.
1692   // Technically zero-sized or negative-sized VLAs are undefined, and UBSan
1693   // will catch that code, but there exists code which generates zero-sized
1694   // VLAs. Be nice and initialize whatever they requested.
1695   const auto *VlaType = getContext().getAsVariableArrayType(type);
1696   if (!VlaType)
1697     return;
1698   auto VlaSize = getVLASize(VlaType);
1699   auto SizeVal = VlaSize.NumElts;
1700   CharUnits EltSize = getContext().getTypeSizeInChars(VlaSize.Type);
1701   switch (trivialAutoVarInit) {
1702   case LangOptions::TrivialAutoVarInitKind::Uninitialized:
1703     llvm_unreachable("Uninitialized handled by caller");
1704 
1705   case LangOptions::TrivialAutoVarInitKind::Zero:
1706     if (!EltSize.isOne())
1707       SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(EltSize));
1708     Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
1709                          isVolatile);
1710     break;
1711 
1712   case LangOptions::TrivialAutoVarInitKind::Pattern: {
1713     llvm::Type *ElTy = Loc.getElementType();
1714     llvm::Constant *Constant = constWithPadding(
1715         CGM, IsPattern::Yes, initializationPatternFor(CGM, ElTy));
1716     CharUnits ConstantAlign = getContext().getTypeAlignInChars(VlaSize.Type);
1717     llvm::BasicBlock *SetupBB = createBasicBlock("vla-setup.loop");
1718     llvm::BasicBlock *LoopBB = createBasicBlock("vla-init.loop");
1719     llvm::BasicBlock *ContBB = createBasicBlock("vla-init.cont");
1720     llvm::Value *IsZeroSizedVLA = Builder.CreateICmpEQ(
1721         SizeVal, llvm::ConstantInt::get(SizeVal->getType(), 0),
1722         "vla.iszerosized");
1723     Builder.CreateCondBr(IsZeroSizedVLA, ContBB, SetupBB);
1724     EmitBlock(SetupBB);
1725     if (!EltSize.isOne())
1726       SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(EltSize));
1727     llvm::Value *BaseSizeInChars =
1728         llvm::ConstantInt::get(IntPtrTy, EltSize.getQuantity());
1729     Address Begin = Builder.CreateElementBitCast(Loc, Int8Ty, "vla.begin");
1730     llvm::Value *End =
1731         Builder.CreateInBoundsGEP(Begin.getPointer(), SizeVal, "vla.end");
1732     llvm::BasicBlock *OriginBB = Builder.GetInsertBlock();
1733     EmitBlock(LoopBB);
1734     llvm::PHINode *Cur = Builder.CreatePHI(Begin.getType(), 2, "vla.cur");
1735     Cur->addIncoming(Begin.getPointer(), OriginBB);
1736     CharUnits CurAlign = Loc.getAlignment().alignmentOfArrayElement(EltSize);
1737     Builder.CreateMemCpy(Address(Cur, CurAlign),
1738                          createUnnamedGlobalForMemcpyFrom(
1739                              CGM, D, Builder, Constant, ConstantAlign),
1740                          BaseSizeInChars, isVolatile);
1741     llvm::Value *Next =
1742         Builder.CreateInBoundsGEP(Int8Ty, Cur, BaseSizeInChars, "vla.next");
1743     llvm::Value *Done = Builder.CreateICmpEQ(Next, End, "vla-init.isdone");
1744     Builder.CreateCondBr(Done, ContBB, LoopBB);
1745     Cur->addIncoming(Next, LoopBB);
1746     EmitBlock(ContBB);
1747   } break;
1748   }
1749 }
1750 
1751 void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
1752   assert(emission.Variable && "emission was not valid!");
1753 
1754   // If this was emitted as a global constant, we're done.
1755   if (emission.wasEmittedAsGlobal()) return;
1756 
1757   const VarDecl &D = *emission.Variable;
1758   auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, D.getLocation());
1759   QualType type = D.getType();
1760 
1761   // If this local has an initializer, emit it now.
1762   const Expr *Init = D.getInit();
1763 
1764   // If we are at an unreachable point, we don't need to emit the initializer
1765   // unless it contains a label.
1766   if (!HaveInsertPoint()) {
1767     if (!Init || !ContainsLabel(Init)) return;
1768     EnsureInsertPoint();
1769   }
1770 
1771   // Initialize the structure of a __block variable.
1772   if (emission.IsEscapingByRef)
1773     emitByrefStructureInit(emission);
1774 
1775   // Initialize the variable here if it doesn't have a initializer and it is a
1776   // C struct that is non-trivial to initialize or an array containing such a
1777   // struct.
1778   if (!Init &&
1779       type.isNonTrivialToPrimitiveDefaultInitialize() ==
1780           QualType::PDIK_Struct) {
1781     LValue Dst = MakeAddrLValue(emission.getAllocatedAddress(), type);
1782     if (emission.IsEscapingByRef)
1783       drillIntoBlockVariable(*this, Dst, &D);
1784     defaultInitNonTrivialCStructVar(Dst);
1785     return;
1786   }
1787 
1788   // Check whether this is a byref variable that's potentially
1789   // captured and moved by its own initializer.  If so, we'll need to
1790   // emit the initializer first, then copy into the variable.
1791   bool capturedByInit =
1792       Init && emission.IsEscapingByRef && isCapturedBy(D, Init);
1793 
1794   bool locIsByrefHeader = !capturedByInit;
1795   const Address Loc =
1796       locIsByrefHeader ? emission.getObjectAddress(*this) : emission.Addr;
1797 
1798   // Note: constexpr already initializes everything correctly.
1799   LangOptions::TrivialAutoVarInitKind trivialAutoVarInit =
1800       (D.isConstexpr()
1801            ? LangOptions::TrivialAutoVarInitKind::Uninitialized
1802            : (D.getAttr<UninitializedAttr>()
1803                   ? LangOptions::TrivialAutoVarInitKind::Uninitialized
1804                   : getContext().getLangOpts().getTrivialAutoVarInit()));
1805 
1806   auto initializeWhatIsTechnicallyUninitialized = [&](Address Loc) {
1807     if (trivialAutoVarInit ==
1808         LangOptions::TrivialAutoVarInitKind::Uninitialized)
1809       return;
1810 
1811     // Only initialize a __block's storage: we always initialize the header.
1812     if (emission.IsEscapingByRef && !locIsByrefHeader)
1813       Loc = emitBlockByrefAddress(Loc, &D, /*follow=*/false);
1814 
1815     return emitZeroOrPatternForAutoVarInit(type, D, Loc);
1816   };
1817 
1818   if (isTrivialInitializer(Init))
1819     return initializeWhatIsTechnicallyUninitialized(Loc);
1820 
1821   llvm::Constant *constant = nullptr;
1822   if (emission.IsConstantAggregate ||
1823       D.mightBeUsableInConstantExpressions(getContext())) {
1824     assert(!capturedByInit && "constant init contains a capturing block?");
1825     constant = ConstantEmitter(*this).tryEmitAbstractForInitializer(D);
1826     if (constant && !constant->isZeroValue() &&
1827         (trivialAutoVarInit !=
1828          LangOptions::TrivialAutoVarInitKind::Uninitialized)) {
1829       IsPattern isPattern =
1830           (trivialAutoVarInit == LangOptions::TrivialAutoVarInitKind::Pattern)
1831               ? IsPattern::Yes
1832               : IsPattern::No;
1833       // C guarantees that brace-init with fewer initializers than members in
1834       // the aggregate will initialize the rest of the aggregate as-if it were
1835       // static initialization. In turn static initialization guarantees that
1836       // padding is initialized to zero bits. We could instead pattern-init if D
1837       // has any ImplicitValueInitExpr, but that seems to be unintuitive
1838       // behavior.
1839       constant = constWithPadding(CGM, IsPattern::No,
1840                                   replaceUndef(CGM, isPattern, constant));
1841     }
1842   }
1843 
1844   if (!constant) {
1845     initializeWhatIsTechnicallyUninitialized(Loc);
1846     LValue lv = MakeAddrLValue(Loc, type);
1847     lv.setNonGC(true);
1848     return EmitExprAsInit(Init, &D, lv, capturedByInit);
1849   }
1850 
1851   if (!emission.IsConstantAggregate) {
1852     // For simple scalar/complex initialization, store the value directly.
1853     LValue lv = MakeAddrLValue(Loc, type);
1854     lv.setNonGC(true);
1855     return EmitStoreThroughLValue(RValue::get(constant), lv, true);
1856   }
1857 
1858   llvm::Type *BP = CGM.Int8Ty->getPointerTo(Loc.getAddressSpace());
1859   emitStoresForConstant(
1860       CGM, D, (Loc.getType() == BP) ? Loc : Builder.CreateBitCast(Loc, BP),
1861       type.isVolatileQualified(), Builder, constant);
1862 }
1863 
1864 /// Emit an expression as an initializer for an object (variable, field, etc.)
1865 /// at the given location.  The expression is not necessarily the normal
1866 /// initializer for the object, and the address is not necessarily
1867 /// its normal location.
1868 ///
1869 /// \param init the initializing expression
1870 /// \param D the object to act as if we're initializing
1871 /// \param loc the address to initialize; its type is a pointer
1872 ///   to the LLVM mapping of the object's type
1873 /// \param alignment the alignment of the address
1874 /// \param capturedByInit true if \p D is a __block variable
1875 ///   whose address is potentially changed by the initializer
1876 void CodeGenFunction::EmitExprAsInit(const Expr *init, const ValueDecl *D,
1877                                      LValue lvalue, bool capturedByInit) {
1878   QualType type = D->getType();
1879 
1880   if (type->isReferenceType()) {
1881     RValue rvalue = EmitReferenceBindingToExpr(init);
1882     if (capturedByInit)
1883       drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
1884     EmitStoreThroughLValue(rvalue, lvalue, true);
1885     return;
1886   }
1887   switch (getEvaluationKind(type)) {
1888   case TEK_Scalar:
1889     EmitScalarInit(init, D, lvalue, capturedByInit);
1890     return;
1891   case TEK_Complex: {
1892     ComplexPairTy complex = EmitComplexExpr(init);
1893     if (capturedByInit)
1894       drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
1895     EmitStoreOfComplex(complex, lvalue, /*init*/ true);
1896     return;
1897   }
1898   case TEK_Aggregate:
1899     if (type->isAtomicType()) {
1900       EmitAtomicInit(const_cast<Expr*>(init), lvalue);
1901     } else {
1902       AggValueSlot::Overlap_t Overlap = AggValueSlot::MayOverlap;
1903       if (isa<VarDecl>(D))
1904         Overlap = AggValueSlot::DoesNotOverlap;
1905       else if (auto *FD = dyn_cast<FieldDecl>(D))
1906         Overlap = getOverlapForFieldInit(FD);
1907       // TODO: how can we delay here if D is captured by its initializer?
1908       EmitAggExpr(init, AggValueSlot::forLValue(
1909                             lvalue, *this, AggValueSlot::IsDestructed,
1910                             AggValueSlot::DoesNotNeedGCBarriers,
1911                             AggValueSlot::IsNotAliased, Overlap));
1912     }
1913     return;
1914   }
1915   llvm_unreachable("bad evaluation kind");
1916 }
1917 
1918 /// Enter a destroy cleanup for the given local variable.
1919 void CodeGenFunction::emitAutoVarTypeCleanup(
1920                             const CodeGenFunction::AutoVarEmission &emission,
1921                             QualType::DestructionKind dtorKind) {
1922   assert(dtorKind != QualType::DK_none);
1923 
1924   // Note that for __block variables, we want to destroy the
1925   // original stack object, not the possibly forwarded object.
1926   Address addr = emission.getObjectAddress(*this);
1927 
1928   const VarDecl *var = emission.Variable;
1929   QualType type = var->getType();
1930 
1931   CleanupKind cleanupKind = NormalAndEHCleanup;
1932   CodeGenFunction::Destroyer *destroyer = nullptr;
1933 
1934   switch (dtorKind) {
1935   case QualType::DK_none:
1936     llvm_unreachable("no cleanup for trivially-destructible variable");
1937 
1938   case QualType::DK_cxx_destructor:
1939     // If there's an NRVO flag on the emission, we need a different
1940     // cleanup.
1941     if (emission.NRVOFlag) {
1942       assert(!type->isArrayType());
1943       CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
1944       EHStack.pushCleanup<DestroyNRVOVariableCXX>(cleanupKind, addr, type, dtor,
1945                                                   emission.NRVOFlag);
1946       return;
1947     }
1948     break;
1949 
1950   case QualType::DK_objc_strong_lifetime:
1951     // Suppress cleanups for pseudo-strong variables.
1952     if (var->isARCPseudoStrong()) return;
1953 
1954     // Otherwise, consider whether to use an EH cleanup or not.
1955     cleanupKind = getARCCleanupKind();
1956 
1957     // Use the imprecise destroyer by default.
1958     if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
1959       destroyer = CodeGenFunction::destroyARCStrongImprecise;
1960     break;
1961 
1962   case QualType::DK_objc_weak_lifetime:
1963     break;
1964 
1965   case QualType::DK_nontrivial_c_struct:
1966     destroyer = CodeGenFunction::destroyNonTrivialCStruct;
1967     if (emission.NRVOFlag) {
1968       assert(!type->isArrayType());
1969       EHStack.pushCleanup<DestroyNRVOVariableC>(cleanupKind, addr,
1970                                                 emission.NRVOFlag, type);
1971       return;
1972     }
1973     break;
1974   }
1975 
1976   // If we haven't chosen a more specific destroyer, use the default.
1977   if (!destroyer) destroyer = getDestroyer(dtorKind);
1978 
1979   // Use an EH cleanup in array destructors iff the destructor itself
1980   // is being pushed as an EH cleanup.
1981   bool useEHCleanup = (cleanupKind & EHCleanup);
1982   EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
1983                                      useEHCleanup);
1984 }
1985 
1986 void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
1987   assert(emission.Variable && "emission was not valid!");
1988 
1989   // If this was emitted as a global constant, we're done.
1990   if (emission.wasEmittedAsGlobal()) return;
1991 
1992   // If we don't have an insertion point, we're done.  Sema prevents
1993   // us from jumping into any of these scopes anyway.
1994   if (!HaveInsertPoint()) return;
1995 
1996   const VarDecl &D = *emission.Variable;
1997 
1998   // Check the type for a cleanup.
1999   if (QualType::DestructionKind dtorKind = D.needsDestruction(getContext()))
2000     emitAutoVarTypeCleanup(emission, dtorKind);
2001 
2002   // In GC mode, honor objc_precise_lifetime.
2003   if (getLangOpts().getGC() != LangOptions::NonGC &&
2004       D.hasAttr<ObjCPreciseLifetimeAttr>()) {
2005     EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
2006   }
2007 
2008   // Handle the cleanup attribute.
2009   if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
2010     const FunctionDecl *FD = CA->getFunctionDecl();
2011 
2012     llvm::Constant *F = CGM.GetAddrOfFunction(FD);
2013     assert(F && "Could not find function!");
2014 
2015     const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
2016     EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
2017   }
2018 
2019   // If this is a block variable, call _Block_object_destroy
2020   // (on the unforwarded address). Don't enter this cleanup if we're in pure-GC
2021   // mode.
2022   if (emission.IsEscapingByRef &&
2023       CGM.getLangOpts().getGC() != LangOptions::GCOnly) {
2024     BlockFieldFlags Flags = BLOCK_FIELD_IS_BYREF;
2025     if (emission.Variable->getType().isObjCGCWeak())
2026       Flags |= BLOCK_FIELD_IS_WEAK;
2027     enterByrefCleanup(NormalAndEHCleanup, emission.Addr, Flags,
2028                       /*LoadBlockVarAddr*/ false,
2029                       cxxDestructorCanThrow(emission.Variable->getType()));
2030   }
2031 }
2032 
2033 CodeGenFunction::Destroyer *
2034 CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
2035   switch (kind) {
2036   case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
2037   case QualType::DK_cxx_destructor:
2038     return destroyCXXObject;
2039   case QualType::DK_objc_strong_lifetime:
2040     return destroyARCStrongPrecise;
2041   case QualType::DK_objc_weak_lifetime:
2042     return destroyARCWeak;
2043   case QualType::DK_nontrivial_c_struct:
2044     return destroyNonTrivialCStruct;
2045   }
2046   llvm_unreachable("Unknown DestructionKind");
2047 }
2048 
2049 /// pushEHDestroy - Push the standard destructor for the given type as
2050 /// an EH-only cleanup.
2051 void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind,
2052                                     Address addr, QualType type) {
2053   assert(dtorKind && "cannot push destructor for trivial type");
2054   assert(needsEHCleanup(dtorKind));
2055 
2056   pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true);
2057 }
2058 
2059 /// pushDestroy - Push the standard destructor for the given type as
2060 /// at least a normal cleanup.
2061 void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
2062                                   Address addr, QualType type) {
2063   assert(dtorKind && "cannot push destructor for trivial type");
2064 
2065   CleanupKind cleanupKind = getCleanupKind(dtorKind);
2066   pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
2067               cleanupKind & EHCleanup);
2068 }
2069 
2070 void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, Address addr,
2071                                   QualType type, Destroyer *destroyer,
2072                                   bool useEHCleanupForArray) {
2073   pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
2074                                      destroyer, useEHCleanupForArray);
2075 }
2076 
2077 void CodeGenFunction::pushStackRestore(CleanupKind Kind, Address SPMem) {
2078   EHStack.pushCleanup<CallStackRestore>(Kind, SPMem);
2079 }
2080 
2081 void CodeGenFunction::pushLifetimeExtendedDestroy(
2082     CleanupKind cleanupKind, Address addr, QualType type,
2083     Destroyer *destroyer, bool useEHCleanupForArray) {
2084   // Push an EH-only cleanup for the object now.
2085   // FIXME: When popping normal cleanups, we need to keep this EH cleanup
2086   // around in case a temporary's destructor throws an exception.
2087   if (cleanupKind & EHCleanup)
2088     EHStack.pushCleanup<DestroyObject>(
2089         static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type,
2090         destroyer, useEHCleanupForArray);
2091 
2092   // Remember that we need to push a full cleanup for the object at the
2093   // end of the full-expression.
2094   pushCleanupAfterFullExpr<DestroyObject>(
2095       cleanupKind, addr, type, destroyer, useEHCleanupForArray);
2096 }
2097 
2098 /// emitDestroy - Immediately perform the destruction of the given
2099 /// object.
2100 ///
2101 /// \param addr - the address of the object; a type*
2102 /// \param type - the type of the object; if an array type, all
2103 ///   objects are destroyed in reverse order
2104 /// \param destroyer - the function to call to destroy individual
2105 ///   elements
2106 /// \param useEHCleanupForArray - whether an EH cleanup should be
2107 ///   used when destroying array elements, in case one of the
2108 ///   destructions throws an exception
2109 void CodeGenFunction::emitDestroy(Address addr, QualType type,
2110                                   Destroyer *destroyer,
2111                                   bool useEHCleanupForArray) {
2112   const ArrayType *arrayType = getContext().getAsArrayType(type);
2113   if (!arrayType)
2114     return destroyer(*this, addr, type);
2115 
2116   llvm::Value *length = emitArrayLength(arrayType, type, addr);
2117 
2118   CharUnits elementAlign =
2119     addr.getAlignment()
2120         .alignmentOfArrayElement(getContext().getTypeSizeInChars(type));
2121 
2122   // Normally we have to check whether the array is zero-length.
2123   bool checkZeroLength = true;
2124 
2125   // But if the array length is constant, we can suppress that.
2126   if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
2127     // ...and if it's constant zero, we can just skip the entire thing.
2128     if (constLength->isZero()) return;
2129     checkZeroLength = false;
2130   }
2131 
2132   llvm::Value *begin = addr.getPointer();
2133   llvm::Value *end = Builder.CreateInBoundsGEP(begin, length);
2134   emitArrayDestroy(begin, end, type, elementAlign, destroyer,
2135                    checkZeroLength, useEHCleanupForArray);
2136 }
2137 
2138 /// emitArrayDestroy - Destroys all the elements of the given array,
2139 /// beginning from last to first.  The array cannot be zero-length.
2140 ///
2141 /// \param begin - a type* denoting the first element of the array
2142 /// \param end - a type* denoting one past the end of the array
2143 /// \param elementType - the element type of the array
2144 /// \param destroyer - the function to call to destroy elements
2145 /// \param useEHCleanup - whether to push an EH cleanup to destroy
2146 ///   the remaining elements in case the destruction of a single
2147 ///   element throws
2148 void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
2149                                        llvm::Value *end,
2150                                        QualType elementType,
2151                                        CharUnits elementAlign,
2152                                        Destroyer *destroyer,
2153                                        bool checkZeroLength,
2154                                        bool useEHCleanup) {
2155   assert(!elementType->isArrayType());
2156 
2157   // The basic structure here is a do-while loop, because we don't
2158   // need to check for the zero-element case.
2159   llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
2160   llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
2161 
2162   if (checkZeroLength) {
2163     llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
2164                                                 "arraydestroy.isempty");
2165     Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
2166   }
2167 
2168   // Enter the loop body, making that address the current address.
2169   llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
2170   EmitBlock(bodyBB);
2171   llvm::PHINode *elementPast =
2172     Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
2173   elementPast->addIncoming(end, entryBB);
2174 
2175   // Shift the address back by one element.
2176   llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
2177   llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne,
2178                                                    "arraydestroy.element");
2179 
2180   if (useEHCleanup)
2181     pushRegularPartialArrayCleanup(begin, element, elementType, elementAlign,
2182                                    destroyer);
2183 
2184   // Perform the actual destruction there.
2185   destroyer(*this, Address(element, elementAlign), elementType);
2186 
2187   if (useEHCleanup)
2188     PopCleanupBlock();
2189 
2190   // Check whether we've reached the end.
2191   llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
2192   Builder.CreateCondBr(done, doneBB, bodyBB);
2193   elementPast->addIncoming(element, Builder.GetInsertBlock());
2194 
2195   // Done.
2196   EmitBlock(doneBB);
2197 }
2198 
2199 /// Perform partial array destruction as if in an EH cleanup.  Unlike
2200 /// emitArrayDestroy, the element type here may still be an array type.
2201 static void emitPartialArrayDestroy(CodeGenFunction &CGF,
2202                                     llvm::Value *begin, llvm::Value *end,
2203                                     QualType type, CharUnits elementAlign,
2204                                     CodeGenFunction::Destroyer *destroyer) {
2205   // If the element type is itself an array, drill down.
2206   unsigned arrayDepth = 0;
2207   while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
2208     // VLAs don't require a GEP index to walk into.
2209     if (!isa<VariableArrayType>(arrayType))
2210       arrayDepth++;
2211     type = arrayType->getElementType();
2212   }
2213 
2214   if (arrayDepth) {
2215     llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
2216 
2217     SmallVector<llvm::Value*,4> gepIndices(arrayDepth+1, zero);
2218     begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin");
2219     end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend");
2220   }
2221 
2222   // Destroy the array.  We don't ever need an EH cleanup because we
2223   // assume that we're in an EH cleanup ourselves, so a throwing
2224   // destructor causes an immediate terminate.
2225   CGF.emitArrayDestroy(begin, end, type, elementAlign, destroyer,
2226                        /*checkZeroLength*/ true, /*useEHCleanup*/ false);
2227 }
2228 
2229 namespace {
2230   /// RegularPartialArrayDestroy - a cleanup which performs a partial
2231   /// array destroy where the end pointer is regularly determined and
2232   /// does not need to be loaded from a local.
2233   class RegularPartialArrayDestroy final : public EHScopeStack::Cleanup {
2234     llvm::Value *ArrayBegin;
2235     llvm::Value *ArrayEnd;
2236     QualType ElementType;
2237     CodeGenFunction::Destroyer *Destroyer;
2238     CharUnits ElementAlign;
2239   public:
2240     RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
2241                                QualType elementType, CharUnits elementAlign,
2242                                CodeGenFunction::Destroyer *destroyer)
2243       : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
2244         ElementType(elementType), Destroyer(destroyer),
2245         ElementAlign(elementAlign) {}
2246 
2247     void Emit(CodeGenFunction &CGF, Flags flags) override {
2248       emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
2249                               ElementType, ElementAlign, Destroyer);
2250     }
2251   };
2252 
2253   /// IrregularPartialArrayDestroy - a cleanup which performs a
2254   /// partial array destroy where the end pointer is irregularly
2255   /// determined and must be loaded from a local.
2256   class IrregularPartialArrayDestroy final : public EHScopeStack::Cleanup {
2257     llvm::Value *ArrayBegin;
2258     Address ArrayEndPointer;
2259     QualType ElementType;
2260     CodeGenFunction::Destroyer *Destroyer;
2261     CharUnits ElementAlign;
2262   public:
2263     IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
2264                                  Address arrayEndPointer,
2265                                  QualType elementType,
2266                                  CharUnits elementAlign,
2267                                  CodeGenFunction::Destroyer *destroyer)
2268       : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
2269         ElementType(elementType), Destroyer(destroyer),
2270         ElementAlign(elementAlign) {}
2271 
2272     void Emit(CodeGenFunction &CGF, Flags flags) override {
2273       llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
2274       emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
2275                               ElementType, ElementAlign, Destroyer);
2276     }
2277   };
2278 } // end anonymous namespace
2279 
2280 /// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
2281 /// already-constructed elements of the given array.  The cleanup
2282 /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
2283 ///
2284 /// \param elementType - the immediate element type of the array;
2285 ///   possibly still an array type
2286 void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
2287                                                        Address arrayEndPointer,
2288                                                        QualType elementType,
2289                                                        CharUnits elementAlign,
2290                                                        Destroyer *destroyer) {
2291   pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
2292                                                     arrayBegin, arrayEndPointer,
2293                                                     elementType, elementAlign,
2294                                                     destroyer);
2295 }
2296 
2297 /// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
2298 /// already-constructed elements of the given array.  The cleanup
2299 /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
2300 ///
2301 /// \param elementType - the immediate element type of the array;
2302 ///   possibly still an array type
2303 void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
2304                                                      llvm::Value *arrayEnd,
2305                                                      QualType elementType,
2306                                                      CharUnits elementAlign,
2307                                                      Destroyer *destroyer) {
2308   pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
2309                                                   arrayBegin, arrayEnd,
2310                                                   elementType, elementAlign,
2311                                                   destroyer);
2312 }
2313 
2314 /// Lazily declare the @llvm.lifetime.start intrinsic.
2315 llvm::Function *CodeGenModule::getLLVMLifetimeStartFn() {
2316   if (LifetimeStartFn)
2317     return LifetimeStartFn;
2318   LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(),
2319     llvm::Intrinsic::lifetime_start, AllocaInt8PtrTy);
2320   return LifetimeStartFn;
2321 }
2322 
2323 /// Lazily declare the @llvm.lifetime.end intrinsic.
2324 llvm::Function *CodeGenModule::getLLVMLifetimeEndFn() {
2325   if (LifetimeEndFn)
2326     return LifetimeEndFn;
2327   LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(),
2328     llvm::Intrinsic::lifetime_end, AllocaInt8PtrTy);
2329   return LifetimeEndFn;
2330 }
2331 
2332 namespace {
2333   /// A cleanup to perform a release of an object at the end of a
2334   /// function.  This is used to balance out the incoming +1 of a
2335   /// ns_consumed argument when we can't reasonably do that just by
2336   /// not doing the initial retain for a __block argument.
2337   struct ConsumeARCParameter final : EHScopeStack::Cleanup {
2338     ConsumeARCParameter(llvm::Value *param,
2339                         ARCPreciseLifetime_t precise)
2340       : Param(param), Precise(precise) {}
2341 
2342     llvm::Value *Param;
2343     ARCPreciseLifetime_t Precise;
2344 
2345     void Emit(CodeGenFunction &CGF, Flags flags) override {
2346       CGF.EmitARCRelease(Param, Precise);
2347     }
2348   };
2349 } // end anonymous namespace
2350 
2351 /// Emit an alloca (or GlobalValue depending on target)
2352 /// for the specified parameter and set up LocalDeclMap.
2353 void CodeGenFunction::EmitParmDecl(const VarDecl &D, ParamValue Arg,
2354                                    unsigned ArgNo) {
2355   // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
2356   assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
2357          "Invalid argument to EmitParmDecl");
2358 
2359   Arg.getAnyValue()->setName(D.getName());
2360 
2361   QualType Ty = D.getType();
2362 
2363   // Use better IR generation for certain implicit parameters.
2364   if (auto IPD = dyn_cast<ImplicitParamDecl>(&D)) {
2365     // The only implicit argument a block has is its literal.
2366     // This may be passed as an inalloca'ed value on Windows x86.
2367     if (BlockInfo) {
2368       llvm::Value *V = Arg.isIndirect()
2369                            ? Builder.CreateLoad(Arg.getIndirectAddress())
2370                            : Arg.getDirectValue();
2371       setBlockContextParameter(IPD, ArgNo, V);
2372       return;
2373     }
2374   }
2375 
2376   Address DeclPtr = Address::invalid();
2377   bool DoStore = false;
2378   bool IsScalar = hasScalarEvaluationKind(Ty);
2379   // If we already have a pointer to the argument, reuse the input pointer.
2380   if (Arg.isIndirect()) {
2381     DeclPtr = Arg.getIndirectAddress();
2382     // If we have a prettier pointer type at this point, bitcast to that.
2383     unsigned AS = DeclPtr.getType()->getAddressSpace();
2384     llvm::Type *IRTy = ConvertTypeForMem(Ty)->getPointerTo(AS);
2385     if (DeclPtr.getType() != IRTy)
2386       DeclPtr = Builder.CreateBitCast(DeclPtr, IRTy, D.getName());
2387     // Indirect argument is in alloca address space, which may be different
2388     // from the default address space.
2389     auto AllocaAS = CGM.getASTAllocaAddressSpace();
2390     auto *V = DeclPtr.getPointer();
2391     auto SrcLangAS = getLangOpts().OpenCL ? LangAS::opencl_private : AllocaAS;
2392     auto DestLangAS =
2393         getLangOpts().OpenCL ? LangAS::opencl_private : LangAS::Default;
2394     if (SrcLangAS != DestLangAS) {
2395       assert(getContext().getTargetAddressSpace(SrcLangAS) ==
2396              CGM.getDataLayout().getAllocaAddrSpace());
2397       auto DestAS = getContext().getTargetAddressSpace(DestLangAS);
2398       auto *T = V->getType()->getPointerElementType()->getPointerTo(DestAS);
2399       DeclPtr = Address(getTargetHooks().performAddrSpaceCast(
2400                             *this, V, SrcLangAS, DestLangAS, T, true),
2401                         DeclPtr.getAlignment());
2402     }
2403 
2404     // Push a destructor cleanup for this parameter if the ABI requires it.
2405     // Don't push a cleanup in a thunk for a method that will also emit a
2406     // cleanup.
2407     if (hasAggregateEvaluationKind(Ty) && !CurFuncIsThunk &&
2408         Ty->castAs<RecordType>()->getDecl()->isParamDestroyedInCallee()) {
2409       if (QualType::DestructionKind DtorKind =
2410               D.needsDestruction(getContext())) {
2411         assert((DtorKind == QualType::DK_cxx_destructor ||
2412                 DtorKind == QualType::DK_nontrivial_c_struct) &&
2413                "unexpected destructor type");
2414         pushDestroy(DtorKind, DeclPtr, Ty);
2415         CalleeDestructedParamCleanups[cast<ParmVarDecl>(&D)] =
2416             EHStack.stable_begin();
2417       }
2418     }
2419   } else {
2420     // Check if the parameter address is controlled by OpenMP runtime.
2421     Address OpenMPLocalAddr =
2422         getLangOpts().OpenMP
2423             ? CGM.getOpenMPRuntime().getAddressOfLocalVariable(*this, &D)
2424             : Address::invalid();
2425     if (getLangOpts().OpenMP && OpenMPLocalAddr.isValid()) {
2426       DeclPtr = OpenMPLocalAddr;
2427     } else {
2428       // Otherwise, create a temporary to hold the value.
2429       DeclPtr = CreateMemTemp(Ty, getContext().getDeclAlign(&D),
2430                               D.getName() + ".addr");
2431     }
2432     DoStore = true;
2433   }
2434 
2435   llvm::Value *ArgVal = (DoStore ? Arg.getDirectValue() : nullptr);
2436 
2437   LValue lv = MakeAddrLValue(DeclPtr, Ty);
2438   if (IsScalar) {
2439     Qualifiers qs = Ty.getQualifiers();
2440     if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
2441       // We honor __attribute__((ns_consumed)) for types with lifetime.
2442       // For __strong, it's handled by just skipping the initial retain;
2443       // otherwise we have to balance out the initial +1 with an extra
2444       // cleanup to do the release at the end of the function.
2445       bool isConsumed = D.hasAttr<NSConsumedAttr>();
2446 
2447       // If a parameter is pseudo-strong then we can omit the implicit retain.
2448       if (D.isARCPseudoStrong()) {
2449         assert(lt == Qualifiers::OCL_Strong &&
2450                "pseudo-strong variable isn't strong?");
2451         assert(qs.hasConst() && "pseudo-strong variable should be const!");
2452         lt = Qualifiers::OCL_ExplicitNone;
2453       }
2454 
2455       // Load objects passed indirectly.
2456       if (Arg.isIndirect() && !ArgVal)
2457         ArgVal = Builder.CreateLoad(DeclPtr);
2458 
2459       if (lt == Qualifiers::OCL_Strong) {
2460         if (!isConsumed) {
2461           if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
2462             // use objc_storeStrong(&dest, value) for retaining the
2463             // object. But first, store a null into 'dest' because
2464             // objc_storeStrong attempts to release its old value.
2465             llvm::Value *Null = CGM.EmitNullConstant(D.getType());
2466             EmitStoreOfScalar(Null, lv, /* isInitialization */ true);
2467             EmitARCStoreStrongCall(lv.getAddress(*this), ArgVal, true);
2468             DoStore = false;
2469           }
2470           else
2471           // Don't use objc_retainBlock for block pointers, because we
2472           // don't want to Block_copy something just because we got it
2473           // as a parameter.
2474             ArgVal = EmitARCRetainNonBlock(ArgVal);
2475         }
2476       } else {
2477         // Push the cleanup for a consumed parameter.
2478         if (isConsumed) {
2479           ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
2480                                 ? ARCPreciseLifetime : ARCImpreciseLifetime);
2481           EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), ArgVal,
2482                                                    precise);
2483         }
2484 
2485         if (lt == Qualifiers::OCL_Weak) {
2486           EmitARCInitWeak(DeclPtr, ArgVal);
2487           DoStore = false; // The weak init is a store, no need to do two.
2488         }
2489       }
2490 
2491       // Enter the cleanup scope.
2492       EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
2493     }
2494   }
2495 
2496   // Store the initial value into the alloca.
2497   if (DoStore)
2498     EmitStoreOfScalar(ArgVal, lv, /* isInitialization */ true);
2499 
2500   setAddrOfLocalVar(&D, DeclPtr);
2501 
2502   // Emit debug info for param declarations in non-thunk functions.
2503   if (CGDebugInfo *DI = getDebugInfo()) {
2504     if (CGM.getCodeGenOpts().hasReducedDebugInfo() && !CurFuncIsThunk) {
2505       DI->EmitDeclareOfArgVariable(&D, DeclPtr.getPointer(), ArgNo, Builder);
2506     }
2507   }
2508 
2509   if (D.hasAttr<AnnotateAttr>())
2510     EmitVarAnnotations(&D, DeclPtr.getPointer());
2511 
2512   // We can only check return value nullability if all arguments to the
2513   // function satisfy their nullability preconditions. This makes it necessary
2514   // to emit null checks for args in the function body itself.
2515   if (requiresReturnValueNullabilityCheck()) {
2516     auto Nullability = Ty->getNullability(getContext());
2517     if (Nullability && *Nullability == NullabilityKind::NonNull) {
2518       SanitizerScope SanScope(this);
2519       RetValNullabilityPrecondition =
2520           Builder.CreateAnd(RetValNullabilityPrecondition,
2521                             Builder.CreateIsNotNull(Arg.getAnyValue()));
2522     }
2523   }
2524 }
2525 
2526 void CodeGenModule::EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D,
2527                                             CodeGenFunction *CGF) {
2528   if (!LangOpts.OpenMP || (!LangOpts.EmitAllDecls && !D->isUsed()))
2529     return;
2530   getOpenMPRuntime().emitUserDefinedReduction(CGF, D);
2531 }
2532 
2533 void CodeGenModule::EmitOMPDeclareMapper(const OMPDeclareMapperDecl *D,
2534                                          CodeGenFunction *CGF) {
2535   if (!LangOpts.OpenMP || LangOpts.OpenMPSimd ||
2536       (!LangOpts.EmitAllDecls && !D->isUsed()))
2537     return;
2538   getOpenMPRuntime().emitUserDefinedMapper(D, CGF);
2539 }
2540 
2541 void CodeGenModule::EmitOMPRequiresDecl(const OMPRequiresDecl *D) {
2542   getOpenMPRuntime().processRequiresDirective(D);
2543 }
2544