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