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