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 or array store into a
974 /// sequence of its fields' stores. This may cost us code size and compilation
975 /// speed, but plays better with store optimizations.
976 static bool shouldSplitConstantStore(CodeGenModule &CGM,
977                                      uint64_t GlobalByteSize) {
978   // Don't break things 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, STy->isPacked());
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 canDoSingleStore = Ty->isIntOrIntVectorTy() ||
1207                           Ty->isPtrOrPtrVectorTy() || Ty->isFPOrFPVectorTy();
1208   if (canDoSingleStore) {
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   uint64_t ConstantSize = CGM.getDataLayout().getTypeAllocSize(Ty);
1217   if (!ConstantSize)
1218     return;
1219   auto *SizeVal = llvm::ConstantInt::get(IntPtrTy, ConstantSize);
1220 
1221   // If the initializer is all or mostly the same, codegen with bzero / memset
1222   // then do a few stores afterward.
1223   if (shouldUseBZeroPlusStoresToInitialize(constant, ConstantSize)) {
1224     Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
1225                          isVolatile);
1226 
1227     bool valueAlreadyCorrect =
1228         constant->isNullValue() || isa<llvm::UndefValue>(constant);
1229     if (!valueAlreadyCorrect) {
1230       Loc = Builder.CreateBitCast(Loc, Ty->getPointerTo(Loc.getAddressSpace()));
1231       emitStoresForInitAfterBZero(CGM, constant, Loc, isVolatile, Builder);
1232     }
1233     return;
1234   }
1235 
1236   // If the initializer is a repeated byte pattern, use memset.
1237   llvm::Value *Pattern = shouldUseMemSetToInitialize(constant, ConstantSize);
1238   if (Pattern) {
1239     uint64_t Value = 0x00;
1240     if (!isa<llvm::UndefValue>(Pattern)) {
1241       const llvm::APInt &AP = cast<llvm::ConstantInt>(Pattern)->getValue();
1242       assert(AP.getBitWidth() <= 8);
1243       Value = AP.getLimitedValue();
1244     }
1245     Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, Value), SizeVal,
1246                          isVolatile);
1247     return;
1248   }
1249 
1250   // If the initializer is small, use a handful of stores.
1251   if (shouldSplitConstantStore(CGM, ConstantSize)) {
1252     if (auto *STy = dyn_cast<llvm::StructType>(Ty)) {
1253       // FIXME: handle the case when STy != Loc.getElementType().
1254       if (STy == Loc.getElementType()) {
1255         for (unsigned i = 0; i != constant->getNumOperands(); i++) {
1256           Address EltPtr = Builder.CreateStructGEP(Loc, i);
1257           emitStoresForConstant(
1258               CGM, D, EltPtr, isVolatile, Builder,
1259               cast<llvm::Constant>(Builder.CreateExtractValue(constant, i)));
1260         }
1261         return;
1262       }
1263     } else if (auto *ATy = dyn_cast<llvm::ArrayType>(Ty)) {
1264       // FIXME: handle the case when ATy != Loc.getElementType().
1265       if (ATy == Loc.getElementType()) {
1266         for (unsigned i = 0; i != ATy->getNumElements(); i++) {
1267           Address EltPtr = Builder.CreateConstArrayGEP(Loc, i);
1268           emitStoresForConstant(
1269               CGM, D, EltPtr, isVolatile, Builder,
1270               cast<llvm::Constant>(Builder.CreateExtractValue(constant, i)));
1271         }
1272         return;
1273       }
1274     }
1275   }
1276 
1277   // Copy from a global.
1278   Builder.CreateMemCpy(
1279       Loc,
1280       createUnnamedGlobalFrom(CGM, D, Builder, constant, Loc.getAlignment()),
1281       SizeVal, isVolatile);
1282 }
1283 
1284 static void emitStoresForZeroInit(CodeGenModule &CGM, const VarDecl &D,
1285                                   Address Loc, bool isVolatile,
1286                                   CGBuilderTy &Builder) {
1287   llvm::Type *ElTy = Loc.getElementType();
1288   llvm::Constant *constant =
1289       constWithPadding(CGM, IsPattern::No, llvm::Constant::getNullValue(ElTy));
1290   emitStoresForConstant(CGM, D, Loc, isVolatile, Builder, constant);
1291 }
1292 
1293 static void emitStoresForPatternInit(CodeGenModule &CGM, const VarDecl &D,
1294                                      Address Loc, bool isVolatile,
1295                                      CGBuilderTy &Builder) {
1296   llvm::Type *ElTy = Loc.getElementType();
1297   llvm::Constant *constant =
1298       constWithPadding(CGM, IsPattern::Yes, patternFor(CGM, ElTy));
1299   assert(!isa<llvm::UndefValue>(constant));
1300   emitStoresForConstant(CGM, D, Loc, isVolatile, Builder, constant);
1301 }
1302 
1303 static bool containsUndef(llvm::Constant *constant) {
1304   auto *Ty = constant->getType();
1305   if (isa<llvm::UndefValue>(constant))
1306     return true;
1307   if (Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy())
1308     for (llvm::Use &Op : constant->operands())
1309       if (containsUndef(cast<llvm::Constant>(Op)))
1310         return true;
1311   return false;
1312 }
1313 
1314 static llvm::Constant *replaceUndef(CodeGenModule &CGM, IsPattern isPattern,
1315                                     llvm::Constant *constant) {
1316   auto *Ty = constant->getType();
1317   if (isa<llvm::UndefValue>(constant))
1318     return patternOrZeroFor(CGM, isPattern, Ty);
1319   if (!(Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()))
1320     return constant;
1321   if (!containsUndef(constant))
1322     return constant;
1323   llvm::SmallVector<llvm::Constant *, 8> Values(constant->getNumOperands());
1324   for (unsigned Op = 0, NumOp = constant->getNumOperands(); Op != NumOp; ++Op) {
1325     auto *OpValue = cast<llvm::Constant>(constant->getOperand(Op));
1326     Values[Op] = replaceUndef(CGM, isPattern, OpValue);
1327   }
1328   if (Ty->isStructTy())
1329     return llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Values);
1330   if (Ty->isArrayTy())
1331     return llvm::ConstantArray::get(cast<llvm::ArrayType>(Ty), Values);
1332   assert(Ty->isVectorTy());
1333   return llvm::ConstantVector::get(Values);
1334 }
1335 
1336 /// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
1337 /// variable declaration with auto, register, or no storage class specifier.
1338 /// These turn into simple stack objects, or GlobalValues depending on target.
1339 void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
1340   AutoVarEmission emission = EmitAutoVarAlloca(D);
1341   EmitAutoVarInit(emission);
1342   EmitAutoVarCleanups(emission);
1343 }
1344 
1345 /// Emit a lifetime.begin marker if some criteria are satisfied.
1346 /// \return a pointer to the temporary size Value if a marker was emitted, null
1347 /// otherwise
1348 llvm::Value *CodeGenFunction::EmitLifetimeStart(uint64_t Size,
1349                                                 llvm::Value *Addr) {
1350   if (!ShouldEmitLifetimeMarkers)
1351     return nullptr;
1352 
1353   assert(Addr->getType()->getPointerAddressSpace() ==
1354              CGM.getDataLayout().getAllocaAddrSpace() &&
1355          "Pointer should be in alloca address space");
1356   llvm::Value *SizeV = llvm::ConstantInt::get(Int64Ty, Size);
1357   Addr = Builder.CreateBitCast(Addr, AllocaInt8PtrTy);
1358   llvm::CallInst *C =
1359       Builder.CreateCall(CGM.getLLVMLifetimeStartFn(), {SizeV, Addr});
1360   C->setDoesNotThrow();
1361   return SizeV;
1362 }
1363 
1364 void CodeGenFunction::EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr) {
1365   assert(Addr->getType()->getPointerAddressSpace() ==
1366              CGM.getDataLayout().getAllocaAddrSpace() &&
1367          "Pointer should be in alloca address space");
1368   Addr = Builder.CreateBitCast(Addr, AllocaInt8PtrTy);
1369   llvm::CallInst *C =
1370       Builder.CreateCall(CGM.getLLVMLifetimeEndFn(), {Size, Addr});
1371   C->setDoesNotThrow();
1372 }
1373 
1374 void CodeGenFunction::EmitAndRegisterVariableArrayDimensions(
1375     CGDebugInfo *DI, const VarDecl &D, bool EmitDebugInfo) {
1376   // For each dimension stores its QualType and corresponding
1377   // size-expression Value.
1378   SmallVector<CodeGenFunction::VlaSizePair, 4> Dimensions;
1379   SmallVector<IdentifierInfo *, 4> VLAExprNames;
1380 
1381   // Break down the array into individual dimensions.
1382   QualType Type1D = D.getType();
1383   while (getContext().getAsVariableArrayType(Type1D)) {
1384     auto VlaSize = getVLAElements1D(Type1D);
1385     if (auto *C = dyn_cast<llvm::ConstantInt>(VlaSize.NumElts))
1386       Dimensions.emplace_back(C, Type1D.getUnqualifiedType());
1387     else {
1388       // Generate a locally unique name for the size expression.
1389       Twine Name = Twine("__vla_expr") + Twine(VLAExprCounter++);
1390       SmallString<12> Buffer;
1391       StringRef NameRef = Name.toStringRef(Buffer);
1392       auto &Ident = getContext().Idents.getOwn(NameRef);
1393       VLAExprNames.push_back(&Ident);
1394       auto SizeExprAddr =
1395           CreateDefaultAlignTempAlloca(VlaSize.NumElts->getType(), NameRef);
1396       Builder.CreateStore(VlaSize.NumElts, SizeExprAddr);
1397       Dimensions.emplace_back(SizeExprAddr.getPointer(),
1398                               Type1D.getUnqualifiedType());
1399     }
1400     Type1D = VlaSize.Type;
1401   }
1402 
1403   if (!EmitDebugInfo)
1404     return;
1405 
1406   // Register each dimension's size-expression with a DILocalVariable,
1407   // so that it can be used by CGDebugInfo when instantiating a DISubrange
1408   // to describe this array.
1409   unsigned NameIdx = 0;
1410   for (auto &VlaSize : Dimensions) {
1411     llvm::Metadata *MD;
1412     if (auto *C = dyn_cast<llvm::ConstantInt>(VlaSize.NumElts))
1413       MD = llvm::ConstantAsMetadata::get(C);
1414     else {
1415       // Create an artificial VarDecl to generate debug info for.
1416       IdentifierInfo *NameIdent = VLAExprNames[NameIdx++];
1417       auto VlaExprTy = VlaSize.NumElts->getType()->getPointerElementType();
1418       auto QT = getContext().getIntTypeForBitwidth(
1419           VlaExprTy->getScalarSizeInBits(), false);
1420       auto *ArtificialDecl = VarDecl::Create(
1421           getContext(), const_cast<DeclContext *>(D.getDeclContext()),
1422           D.getLocation(), D.getLocation(), NameIdent, QT,
1423           getContext().CreateTypeSourceInfo(QT), SC_Auto);
1424       ArtificialDecl->setImplicit();
1425 
1426       MD = DI->EmitDeclareOfAutoVariable(ArtificialDecl, VlaSize.NumElts,
1427                                          Builder);
1428     }
1429     assert(MD && "No Size expression debug node created");
1430     DI->registerVLASizeExpression(VlaSize.Type, MD);
1431   }
1432 }
1433 
1434 /// EmitAutoVarAlloca - Emit the alloca and debug information for a
1435 /// local variable.  Does not emit initialization or destruction.
1436 CodeGenFunction::AutoVarEmission
1437 CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
1438   QualType Ty = D.getType();
1439   assert(
1440       Ty.getAddressSpace() == LangAS::Default ||
1441       (Ty.getAddressSpace() == LangAS::opencl_private && getLangOpts().OpenCL));
1442 
1443   AutoVarEmission emission(D);
1444 
1445   bool isEscapingByRef = D.isEscapingByref();
1446   emission.IsEscapingByRef = isEscapingByRef;
1447 
1448   CharUnits alignment = getContext().getDeclAlign(&D);
1449 
1450   // If the type is variably-modified, emit all the VLA sizes for it.
1451   if (Ty->isVariablyModifiedType())
1452     EmitVariablyModifiedType(Ty);
1453 
1454   auto *DI = getDebugInfo();
1455   bool EmitDebugInfo = DI && CGM.getCodeGenOpts().getDebugInfo() >=
1456                                  codegenoptions::LimitedDebugInfo;
1457 
1458   Address address = Address::invalid();
1459   Address AllocaAddr = Address::invalid();
1460   Address OpenMPLocalAddr =
1461       getLangOpts().OpenMP
1462           ? CGM.getOpenMPRuntime().getAddressOfLocalVariable(*this, &D)
1463           : Address::invalid();
1464   if (getLangOpts().OpenMP && OpenMPLocalAddr.isValid()) {
1465     address = OpenMPLocalAddr;
1466   } else if (Ty->isConstantSizeType()) {
1467     bool NRVO = getLangOpts().ElideConstructors &&
1468       D.isNRVOVariable();
1469 
1470     // If this value is an array or struct with a statically determinable
1471     // constant initializer, there are optimizations we can do.
1472     //
1473     // TODO: We should constant-evaluate the initializer of any variable,
1474     // as long as it is initialized by a constant expression. Currently,
1475     // isConstantInitializer produces wrong answers for structs with
1476     // reference or bitfield members, and a few other cases, and checking
1477     // for POD-ness protects us from some of these.
1478     if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) &&
1479         (D.isConstexpr() ||
1480          ((Ty.isPODType(getContext()) ||
1481            getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
1482           D.getInit()->isConstantInitializer(getContext(), false)))) {
1483 
1484       // If the variable's a const type, and it's neither an NRVO
1485       // candidate nor a __block variable and has no mutable members,
1486       // emit it as a global instead.
1487       // Exception is if a variable is located in non-constant address space
1488       // in OpenCL.
1489       if ((!getLangOpts().OpenCL ||
1490            Ty.getAddressSpace() == LangAS::opencl_constant) &&
1491           (CGM.getCodeGenOpts().MergeAllConstants && !NRVO &&
1492            !isEscapingByRef && CGM.isTypeConstant(Ty, true))) {
1493         EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
1494 
1495         // Signal this condition to later callbacks.
1496         emission.Addr = Address::invalid();
1497         assert(emission.wasEmittedAsGlobal());
1498         return emission;
1499       }
1500 
1501       // Otherwise, tell the initialization code that we're in this case.
1502       emission.IsConstantAggregate = true;
1503     }
1504 
1505     // A normal fixed sized variable becomes an alloca in the entry block,
1506     // unless:
1507     // - it's an NRVO variable.
1508     // - we are compiling OpenMP and it's an OpenMP local variable.
1509     if (NRVO) {
1510       // The named return value optimization: allocate this variable in the
1511       // return slot, so that we can elide the copy when returning this
1512       // variable (C++0x [class.copy]p34).
1513       address = ReturnValue;
1514 
1515       if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
1516         const auto *RD = RecordTy->getDecl();
1517         const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
1518         if ((CXXRD && !CXXRD->hasTrivialDestructor()) ||
1519             RD->isNonTrivialToPrimitiveDestroy()) {
1520           // Create a flag that is used to indicate when the NRVO was applied
1521           // to this variable. Set it to zero to indicate that NRVO was not
1522           // applied.
1523           llvm::Value *Zero = Builder.getFalse();
1524           Address NRVOFlag =
1525             CreateTempAlloca(Zero->getType(), CharUnits::One(), "nrvo");
1526           EnsureInsertPoint();
1527           Builder.CreateStore(Zero, NRVOFlag);
1528 
1529           // Record the NRVO flag for this variable.
1530           NRVOFlags[&D] = NRVOFlag.getPointer();
1531           emission.NRVOFlag = NRVOFlag.getPointer();
1532         }
1533       }
1534     } else {
1535       CharUnits allocaAlignment;
1536       llvm::Type *allocaTy;
1537       if (isEscapingByRef) {
1538         auto &byrefInfo = getBlockByrefInfo(&D);
1539         allocaTy = byrefInfo.Type;
1540         allocaAlignment = byrefInfo.ByrefAlignment;
1541       } else {
1542         allocaTy = ConvertTypeForMem(Ty);
1543         allocaAlignment = alignment;
1544       }
1545 
1546       // Create the alloca.  Note that we set the name separately from
1547       // building the instruction so that it's there even in no-asserts
1548       // builds.
1549       address = CreateTempAlloca(allocaTy, allocaAlignment, D.getName(),
1550                                  /*ArraySize=*/nullptr, &AllocaAddr);
1551 
1552       // Don't emit lifetime markers for MSVC catch parameters. The lifetime of
1553       // the catch parameter starts in the catchpad instruction, and we can't
1554       // insert code in those basic blocks.
1555       bool IsMSCatchParam =
1556           D.isExceptionVariable() && getTarget().getCXXABI().isMicrosoft();
1557 
1558       // Emit a lifetime intrinsic if meaningful. There's no point in doing this
1559       // if we don't have a valid insertion point (?).
1560       if (HaveInsertPoint() && !IsMSCatchParam) {
1561         // If there's a jump into the lifetime of this variable, its lifetime
1562         // gets broken up into several regions in IR, which requires more work
1563         // to handle correctly. For now, just omit the intrinsics; this is a
1564         // rare case, and it's better to just be conservatively correct.
1565         // PR28267.
1566         //
1567         // We have to do this in all language modes if there's a jump past the
1568         // declaration. We also have to do it in C if there's a jump to an
1569         // earlier point in the current block because non-VLA lifetimes begin as
1570         // soon as the containing block is entered, not when its variables
1571         // actually come into scope; suppressing the lifetime annotations
1572         // completely in this case is unnecessarily pessimistic, but again, this
1573         // is rare.
1574         if (!Bypasses.IsBypassed(&D) &&
1575             !(!getLangOpts().CPlusPlus && hasLabelBeenSeenInCurrentScope())) {
1576           uint64_t size = CGM.getDataLayout().getTypeAllocSize(allocaTy);
1577           emission.SizeForLifetimeMarkers =
1578               EmitLifetimeStart(size, AllocaAddr.getPointer());
1579         }
1580       } else {
1581         assert(!emission.useLifetimeMarkers());
1582       }
1583     }
1584   } else {
1585     EnsureInsertPoint();
1586 
1587     if (!DidCallStackSave) {
1588       // Save the stack.
1589       Address Stack =
1590         CreateTempAlloca(Int8PtrTy, getPointerAlign(), "saved_stack");
1591 
1592       llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
1593       llvm::Value *V = Builder.CreateCall(F);
1594       Builder.CreateStore(V, Stack);
1595 
1596       DidCallStackSave = true;
1597 
1598       // Push a cleanup block and restore the stack there.
1599       // FIXME: in general circumstances, this should be an EH cleanup.
1600       pushStackRestore(NormalCleanup, Stack);
1601     }
1602 
1603     auto VlaSize = getVLASize(Ty);
1604     llvm::Type *llvmTy = ConvertTypeForMem(VlaSize.Type);
1605 
1606     // Allocate memory for the array.
1607     address = CreateTempAlloca(llvmTy, alignment, "vla", VlaSize.NumElts,
1608                                &AllocaAddr);
1609 
1610     // If we have debug info enabled, properly describe the VLA dimensions for
1611     // this type by registering the vla size expression for each of the
1612     // dimensions.
1613     EmitAndRegisterVariableArrayDimensions(DI, D, EmitDebugInfo);
1614   }
1615 
1616   setAddrOfLocalVar(&D, address);
1617   emission.Addr = address;
1618   emission.AllocaAddr = AllocaAddr;
1619 
1620   // Emit debug info for local var declaration.
1621   if (EmitDebugInfo && HaveInsertPoint()) {
1622     DI->setLocation(D.getLocation());
1623     (void)DI->EmitDeclareOfAutoVariable(&D, address.getPointer(), Builder);
1624   }
1625 
1626   if (D.hasAttr<AnnotateAttr>() && HaveInsertPoint())
1627     EmitVarAnnotations(&D, address.getPointer());
1628 
1629   // Make sure we call @llvm.lifetime.end.
1630   if (emission.useLifetimeMarkers())
1631     EHStack.pushCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker,
1632                                          emission.getOriginalAllocatedAddress(),
1633                                          emission.getSizeForLifetimeMarkers());
1634 
1635   return emission;
1636 }
1637 
1638 static bool isCapturedBy(const VarDecl &, const Expr *);
1639 
1640 /// Determines whether the given __block variable is potentially
1641 /// captured by the given statement.
1642 static bool isCapturedBy(const VarDecl &Var, const Stmt *S) {
1643   if (const Expr *E = dyn_cast<Expr>(S))
1644     return isCapturedBy(Var, E);
1645   for (const Stmt *SubStmt : S->children())
1646     if (isCapturedBy(Var, SubStmt))
1647       return true;
1648   return false;
1649 }
1650 
1651 /// Determines whether the given __block variable is potentially
1652 /// captured by the given expression.
1653 static bool isCapturedBy(const VarDecl &Var, const Expr *E) {
1654   // Skip the most common kinds of expressions that make
1655   // hierarchy-walking expensive.
1656   E = E->IgnoreParenCasts();
1657 
1658   if (const BlockExpr *BE = dyn_cast<BlockExpr>(E)) {
1659     const BlockDecl *Block = BE->getBlockDecl();
1660     for (const auto &I : Block->captures()) {
1661       if (I.getVariable() == &Var)
1662         return true;
1663     }
1664 
1665     // No need to walk into the subexpressions.
1666     return false;
1667   }
1668 
1669   if (const StmtExpr *SE = dyn_cast<StmtExpr>(E)) {
1670     const CompoundStmt *CS = SE->getSubStmt();
1671     for (const auto *BI : CS->body())
1672       if (const auto *BIE = dyn_cast<Expr>(BI)) {
1673         if (isCapturedBy(Var, BIE))
1674           return true;
1675       }
1676       else if (const auto *DS = dyn_cast<DeclStmt>(BI)) {
1677           // special case declarations
1678           for (const auto *I : DS->decls()) {
1679               if (const auto *VD = dyn_cast<VarDecl>((I))) {
1680                 const Expr *Init = VD->getInit();
1681                 if (Init && isCapturedBy(Var, Init))
1682                   return true;
1683               }
1684           }
1685       }
1686       else
1687         // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
1688         // Later, provide code to poke into statements for capture analysis.
1689         return true;
1690     return false;
1691   }
1692 
1693   for (const Stmt *SubStmt : E->children())
1694     if (isCapturedBy(Var, SubStmt))
1695       return true;
1696 
1697   return false;
1698 }
1699 
1700 /// Determine whether the given initializer is trivial in the sense
1701 /// that it requires no code to be generated.
1702 bool CodeGenFunction::isTrivialInitializer(const Expr *Init) {
1703   if (!Init)
1704     return true;
1705 
1706   if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
1707     if (CXXConstructorDecl *Constructor = Construct->getConstructor())
1708       if (Constructor->isTrivial() &&
1709           Constructor->isDefaultConstructor() &&
1710           !Construct->requiresZeroInitialization())
1711         return true;
1712 
1713   return false;
1714 }
1715 
1716 void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
1717   assert(emission.Variable && "emission was not valid!");
1718 
1719   // If this was emitted as a global constant, we're done.
1720   if (emission.wasEmittedAsGlobal()) return;
1721 
1722   const VarDecl &D = *emission.Variable;
1723   auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, D.getLocation());
1724   QualType type = D.getType();
1725 
1726   bool isVolatile = type.isVolatileQualified();
1727 
1728   // If this local has an initializer, emit it now.
1729   const Expr *Init = D.getInit();
1730 
1731   // If we are at an unreachable point, we don't need to emit the initializer
1732   // unless it contains a label.
1733   if (!HaveInsertPoint()) {
1734     if (!Init || !ContainsLabel(Init)) return;
1735     EnsureInsertPoint();
1736   }
1737 
1738   // Initialize the structure of a __block variable.
1739   if (emission.IsEscapingByRef)
1740     emitByrefStructureInit(emission);
1741 
1742   // Initialize the variable here if it doesn't have a initializer and it is a
1743   // C struct that is non-trivial to initialize or an array containing such a
1744   // struct.
1745   if (!Init &&
1746       type.isNonTrivialToPrimitiveDefaultInitialize() ==
1747           QualType::PDIK_Struct) {
1748     LValue Dst = MakeAddrLValue(emission.getAllocatedAddress(), type);
1749     if (emission.IsEscapingByRef)
1750       drillIntoBlockVariable(*this, Dst, &D);
1751     defaultInitNonTrivialCStructVar(Dst);
1752     return;
1753   }
1754 
1755   // Check whether this is a byref variable that's potentially
1756   // captured and moved by its own initializer.  If so, we'll need to
1757   // emit the initializer first, then copy into the variable.
1758   bool capturedByInit =
1759       Init && emission.IsEscapingByRef && isCapturedBy(D, Init);
1760 
1761   bool locIsByrefHeader = !capturedByInit;
1762   const Address Loc =
1763       locIsByrefHeader ? emission.getObjectAddress(*this) : emission.Addr;
1764 
1765   // Note: constexpr already initializes everything correctly.
1766   LangOptions::TrivialAutoVarInitKind trivialAutoVarInit =
1767       (D.isConstexpr()
1768            ? LangOptions::TrivialAutoVarInitKind::Uninitialized
1769            : (D.getAttr<UninitializedAttr>()
1770                   ? LangOptions::TrivialAutoVarInitKind::Uninitialized
1771                   : getContext().getLangOpts().getTrivialAutoVarInit()));
1772 
1773   auto initializeWhatIsTechnicallyUninitialized = [&](Address Loc) {
1774     if (trivialAutoVarInit ==
1775         LangOptions::TrivialAutoVarInitKind::Uninitialized)
1776       return;
1777 
1778     // Only initialize a __block's storage: we always initialize the header.
1779     if (emission.IsEscapingByRef && !locIsByrefHeader)
1780       Loc = emitBlockByrefAddress(Loc, &D, /*follow=*/false);
1781 
1782     CharUnits Size = getContext().getTypeSizeInChars(type);
1783     if (!Size.isZero()) {
1784       switch (trivialAutoVarInit) {
1785       case LangOptions::TrivialAutoVarInitKind::Uninitialized:
1786         llvm_unreachable("Uninitialized handled above");
1787       case LangOptions::TrivialAutoVarInitKind::Zero:
1788         emitStoresForZeroInit(CGM, D, Loc, isVolatile, Builder);
1789         break;
1790       case LangOptions::TrivialAutoVarInitKind::Pattern:
1791         emitStoresForPatternInit(CGM, D, Loc, isVolatile, Builder);
1792         break;
1793       }
1794       return;
1795     }
1796 
1797     // VLAs look zero-sized to getTypeInfo. We can't emit constant stores to
1798     // them, so emit a memcpy with the VLA size to initialize each element.
1799     // Technically zero-sized or negative-sized VLAs are undefined, and UBSan
1800     // will catch that code, but there exists code which generates zero-sized
1801     // VLAs. Be nice and initialize whatever they requested.
1802     const auto *VlaType = getContext().getAsVariableArrayType(type);
1803     if (!VlaType)
1804       return;
1805     auto VlaSize = getVLASize(VlaType);
1806     auto SizeVal = VlaSize.NumElts;
1807     CharUnits EltSize = getContext().getTypeSizeInChars(VlaSize.Type);
1808     switch (trivialAutoVarInit) {
1809     case LangOptions::TrivialAutoVarInitKind::Uninitialized:
1810       llvm_unreachable("Uninitialized handled above");
1811 
1812     case LangOptions::TrivialAutoVarInitKind::Zero:
1813       if (!EltSize.isOne())
1814         SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(EltSize));
1815       Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
1816                            isVolatile);
1817       break;
1818 
1819     case LangOptions::TrivialAutoVarInitKind::Pattern: {
1820       llvm::Type *ElTy = Loc.getElementType();
1821       llvm::Constant *Constant =
1822           constWithPadding(CGM, IsPattern::Yes, patternFor(CGM, ElTy));
1823       CharUnits ConstantAlign = getContext().getTypeAlignInChars(VlaSize.Type);
1824       llvm::BasicBlock *SetupBB = createBasicBlock("vla-setup.loop");
1825       llvm::BasicBlock *LoopBB = createBasicBlock("vla-init.loop");
1826       llvm::BasicBlock *ContBB = createBasicBlock("vla-init.cont");
1827       llvm::Value *IsZeroSizedVLA = Builder.CreateICmpEQ(
1828           SizeVal, llvm::ConstantInt::get(SizeVal->getType(), 0),
1829           "vla.iszerosized");
1830       Builder.CreateCondBr(IsZeroSizedVLA, ContBB, SetupBB);
1831       EmitBlock(SetupBB);
1832       if (!EltSize.isOne())
1833         SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(EltSize));
1834       llvm::Value *BaseSizeInChars =
1835           llvm::ConstantInt::get(IntPtrTy, EltSize.getQuantity());
1836       Address Begin = Builder.CreateElementBitCast(Loc, Int8Ty, "vla.begin");
1837       llvm::Value *End =
1838           Builder.CreateInBoundsGEP(Begin.getPointer(), SizeVal, "vla.end");
1839       llvm::BasicBlock *OriginBB = Builder.GetInsertBlock();
1840       EmitBlock(LoopBB);
1841       llvm::PHINode *Cur = Builder.CreatePHI(Begin.getType(), 2, "vla.cur");
1842       Cur->addIncoming(Begin.getPointer(), OriginBB);
1843       CharUnits CurAlign = Loc.getAlignment().alignmentOfArrayElement(EltSize);
1844       Builder.CreateMemCpy(
1845           Address(Cur, CurAlign),
1846           createUnnamedGlobalFrom(CGM, D, Builder, Constant, ConstantAlign),
1847           BaseSizeInChars, isVolatile);
1848       llvm::Value *Next =
1849           Builder.CreateInBoundsGEP(Int8Ty, Cur, BaseSizeInChars, "vla.next");
1850       llvm::Value *Done = Builder.CreateICmpEQ(Next, End, "vla-init.isdone");
1851       Builder.CreateCondBr(Done, ContBB, LoopBB);
1852       Cur->addIncoming(Next, LoopBB);
1853       EmitBlock(ContBB);
1854     } break;
1855     }
1856   };
1857 
1858   if (isTrivialInitializer(Init)) {
1859     initializeWhatIsTechnicallyUninitialized(Loc);
1860     return;
1861   }
1862 
1863   llvm::Constant *constant = nullptr;
1864   if (emission.IsConstantAggregate || D.isConstexpr()) {
1865     assert(!capturedByInit && "constant init contains a capturing block?");
1866     constant = ConstantEmitter(*this).tryEmitAbstractForInitializer(D);
1867     if (constant && trivialAutoVarInit !=
1868                         LangOptions::TrivialAutoVarInitKind::Uninitialized) {
1869       IsPattern isPattern =
1870           (trivialAutoVarInit == LangOptions::TrivialAutoVarInitKind::Pattern)
1871               ? IsPattern::Yes
1872               : IsPattern::No;
1873       constant = constWithPadding(CGM, isPattern,
1874                                   replaceUndef(CGM, isPattern, constant));
1875     }
1876   }
1877 
1878   if (!constant) {
1879     initializeWhatIsTechnicallyUninitialized(Loc);
1880     LValue lv = MakeAddrLValue(Loc, type);
1881     lv.setNonGC(true);
1882     return EmitExprAsInit(Init, &D, lv, capturedByInit);
1883   }
1884 
1885   if (!emission.IsConstantAggregate) {
1886     // For simple scalar/complex initialization, store the value directly.
1887     LValue lv = MakeAddrLValue(Loc, type);
1888     lv.setNonGC(true);
1889     return EmitStoreThroughLValue(RValue::get(constant), lv, true);
1890   }
1891 
1892   llvm::Type *BP = CGM.Int8Ty->getPointerTo(Loc.getAddressSpace());
1893   emitStoresForConstant(
1894       CGM, D, (Loc.getType() == BP) ? Loc : Builder.CreateBitCast(Loc, BP),
1895       isVolatile, Builder, constant);
1896 }
1897 
1898 /// Emit an expression as an initializer for an object (variable, field, etc.)
1899 /// at the given location.  The expression is not necessarily the normal
1900 /// initializer for the object, and the address is not necessarily
1901 /// its normal location.
1902 ///
1903 /// \param init the initializing expression
1904 /// \param D the object to act as if we're initializing
1905 /// \param loc the address to initialize; its type is a pointer
1906 ///   to the LLVM mapping of the object's type
1907 /// \param alignment the alignment of the address
1908 /// \param capturedByInit true if \p D is a __block variable
1909 ///   whose address is potentially changed by the initializer
1910 void CodeGenFunction::EmitExprAsInit(const Expr *init, const ValueDecl *D,
1911                                      LValue lvalue, bool capturedByInit) {
1912   QualType type = D->getType();
1913 
1914   if (type->isReferenceType()) {
1915     RValue rvalue = EmitReferenceBindingToExpr(init);
1916     if (capturedByInit)
1917       drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
1918     EmitStoreThroughLValue(rvalue, lvalue, true);
1919     return;
1920   }
1921   switch (getEvaluationKind(type)) {
1922   case TEK_Scalar:
1923     EmitScalarInit(init, D, lvalue, capturedByInit);
1924     return;
1925   case TEK_Complex: {
1926     ComplexPairTy complex = EmitComplexExpr(init);
1927     if (capturedByInit)
1928       drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
1929     EmitStoreOfComplex(complex, lvalue, /*init*/ true);
1930     return;
1931   }
1932   case TEK_Aggregate:
1933     if (type->isAtomicType()) {
1934       EmitAtomicInit(const_cast<Expr*>(init), lvalue);
1935     } else {
1936       AggValueSlot::Overlap_t Overlap = AggValueSlot::MayOverlap;
1937       if (isa<VarDecl>(D))
1938         Overlap = AggValueSlot::DoesNotOverlap;
1939       else if (auto *FD = dyn_cast<FieldDecl>(D))
1940         Overlap = overlapForFieldInit(FD);
1941       // TODO: how can we delay here if D is captured by its initializer?
1942       EmitAggExpr(init, AggValueSlot::forLValue(lvalue,
1943                                               AggValueSlot::IsDestructed,
1944                                          AggValueSlot::DoesNotNeedGCBarriers,
1945                                               AggValueSlot::IsNotAliased,
1946                                               Overlap));
1947     }
1948     return;
1949   }
1950   llvm_unreachable("bad evaluation kind");
1951 }
1952 
1953 /// Enter a destroy cleanup for the given local variable.
1954 void CodeGenFunction::emitAutoVarTypeCleanup(
1955                             const CodeGenFunction::AutoVarEmission &emission,
1956                             QualType::DestructionKind dtorKind) {
1957   assert(dtorKind != QualType::DK_none);
1958 
1959   // Note that for __block variables, we want to destroy the
1960   // original stack object, not the possibly forwarded object.
1961   Address addr = emission.getObjectAddress(*this);
1962 
1963   const VarDecl *var = emission.Variable;
1964   QualType type = var->getType();
1965 
1966   CleanupKind cleanupKind = NormalAndEHCleanup;
1967   CodeGenFunction::Destroyer *destroyer = nullptr;
1968 
1969   switch (dtorKind) {
1970   case QualType::DK_none:
1971     llvm_unreachable("no cleanup for trivially-destructible variable");
1972 
1973   case QualType::DK_cxx_destructor:
1974     // If there's an NRVO flag on the emission, we need a different
1975     // cleanup.
1976     if (emission.NRVOFlag) {
1977       assert(!type->isArrayType());
1978       CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
1979       EHStack.pushCleanup<DestroyNRVOVariableCXX>(cleanupKind, addr, dtor,
1980                                                   emission.NRVOFlag);
1981       return;
1982     }
1983     break;
1984 
1985   case QualType::DK_objc_strong_lifetime:
1986     // Suppress cleanups for pseudo-strong variables.
1987     if (var->isARCPseudoStrong()) return;
1988 
1989     // Otherwise, consider whether to use an EH cleanup or not.
1990     cleanupKind = getARCCleanupKind();
1991 
1992     // Use the imprecise destroyer by default.
1993     if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
1994       destroyer = CodeGenFunction::destroyARCStrongImprecise;
1995     break;
1996 
1997   case QualType::DK_objc_weak_lifetime:
1998     break;
1999 
2000   case QualType::DK_nontrivial_c_struct:
2001     destroyer = CodeGenFunction::destroyNonTrivialCStruct;
2002     if (emission.NRVOFlag) {
2003       assert(!type->isArrayType());
2004       EHStack.pushCleanup<DestroyNRVOVariableC>(cleanupKind, addr,
2005                                                 emission.NRVOFlag, type);
2006       return;
2007     }
2008     break;
2009   }
2010 
2011   // If we haven't chosen a more specific destroyer, use the default.
2012   if (!destroyer) destroyer = getDestroyer(dtorKind);
2013 
2014   // Use an EH cleanup in array destructors iff the destructor itself
2015   // is being pushed as an EH cleanup.
2016   bool useEHCleanup = (cleanupKind & EHCleanup);
2017   EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
2018                                      useEHCleanup);
2019 }
2020 
2021 void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
2022   assert(emission.Variable && "emission was not valid!");
2023 
2024   // If this was emitted as a global constant, we're done.
2025   if (emission.wasEmittedAsGlobal()) return;
2026 
2027   // If we don't have an insertion point, we're done.  Sema prevents
2028   // us from jumping into any of these scopes anyway.
2029   if (!HaveInsertPoint()) return;
2030 
2031   const VarDecl &D = *emission.Variable;
2032 
2033   // Check the type for a cleanup.
2034   if (QualType::DestructionKind dtorKind = D.getType().isDestructedType())
2035     emitAutoVarTypeCleanup(emission, dtorKind);
2036 
2037   // In GC mode, honor objc_precise_lifetime.
2038   if (getLangOpts().getGC() != LangOptions::NonGC &&
2039       D.hasAttr<ObjCPreciseLifetimeAttr>()) {
2040     EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
2041   }
2042 
2043   // Handle the cleanup attribute.
2044   if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
2045     const FunctionDecl *FD = CA->getFunctionDecl();
2046 
2047     llvm::Constant *F = CGM.GetAddrOfFunction(FD);
2048     assert(F && "Could not find function!");
2049 
2050     const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
2051     EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
2052   }
2053 
2054   // If this is a block variable, call _Block_object_destroy
2055   // (on the unforwarded address). Don't enter this cleanup if we're in pure-GC
2056   // mode.
2057   if (emission.IsEscapingByRef &&
2058       CGM.getLangOpts().getGC() != LangOptions::GCOnly) {
2059     BlockFieldFlags Flags = BLOCK_FIELD_IS_BYREF;
2060     if (emission.Variable->getType().isObjCGCWeak())
2061       Flags |= BLOCK_FIELD_IS_WEAK;
2062     enterByrefCleanup(NormalAndEHCleanup, emission.Addr, Flags,
2063                       /*LoadBlockVarAddr*/ false,
2064                       cxxDestructorCanThrow(emission.Variable->getType()));
2065   }
2066 }
2067 
2068 CodeGenFunction::Destroyer *
2069 CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
2070   switch (kind) {
2071   case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
2072   case QualType::DK_cxx_destructor:
2073     return destroyCXXObject;
2074   case QualType::DK_objc_strong_lifetime:
2075     return destroyARCStrongPrecise;
2076   case QualType::DK_objc_weak_lifetime:
2077     return destroyARCWeak;
2078   case QualType::DK_nontrivial_c_struct:
2079     return destroyNonTrivialCStruct;
2080   }
2081   llvm_unreachable("Unknown DestructionKind");
2082 }
2083 
2084 /// pushEHDestroy - Push the standard destructor for the given type as
2085 /// an EH-only cleanup.
2086 void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind,
2087                                     Address addr, QualType type) {
2088   assert(dtorKind && "cannot push destructor for trivial type");
2089   assert(needsEHCleanup(dtorKind));
2090 
2091   pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true);
2092 }
2093 
2094 /// pushDestroy - Push the standard destructor for the given type as
2095 /// at least a normal cleanup.
2096 void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
2097                                   Address addr, QualType type) {
2098   assert(dtorKind && "cannot push destructor for trivial type");
2099 
2100   CleanupKind cleanupKind = getCleanupKind(dtorKind);
2101   pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
2102               cleanupKind & EHCleanup);
2103 }
2104 
2105 void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, Address addr,
2106                                   QualType type, Destroyer *destroyer,
2107                                   bool useEHCleanupForArray) {
2108   pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
2109                                      destroyer, useEHCleanupForArray);
2110 }
2111 
2112 void CodeGenFunction::pushStackRestore(CleanupKind Kind, Address SPMem) {
2113   EHStack.pushCleanup<CallStackRestore>(Kind, SPMem);
2114 }
2115 
2116 void CodeGenFunction::pushLifetimeExtendedDestroy(
2117     CleanupKind cleanupKind, Address addr, QualType type,
2118     Destroyer *destroyer, bool useEHCleanupForArray) {
2119   // Push an EH-only cleanup for the object now.
2120   // FIXME: When popping normal cleanups, we need to keep this EH cleanup
2121   // around in case a temporary's destructor throws an exception.
2122   if (cleanupKind & EHCleanup)
2123     EHStack.pushCleanup<DestroyObject>(
2124         static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type,
2125         destroyer, useEHCleanupForArray);
2126 
2127   // Remember that we need to push a full cleanup for the object at the
2128   // end of the full-expression.
2129   pushCleanupAfterFullExpr<DestroyObject>(
2130       cleanupKind, addr, type, destroyer, useEHCleanupForArray);
2131 }
2132 
2133 /// emitDestroy - Immediately perform the destruction of the given
2134 /// object.
2135 ///
2136 /// \param addr - the address of the object; a type*
2137 /// \param type - the type of the object; if an array type, all
2138 ///   objects are destroyed in reverse order
2139 /// \param destroyer - the function to call to destroy individual
2140 ///   elements
2141 /// \param useEHCleanupForArray - whether an EH cleanup should be
2142 ///   used when destroying array elements, in case one of the
2143 ///   destructions throws an exception
2144 void CodeGenFunction::emitDestroy(Address addr, QualType type,
2145                                   Destroyer *destroyer,
2146                                   bool useEHCleanupForArray) {
2147   const ArrayType *arrayType = getContext().getAsArrayType(type);
2148   if (!arrayType)
2149     return destroyer(*this, addr, type);
2150 
2151   llvm::Value *length = emitArrayLength(arrayType, type, addr);
2152 
2153   CharUnits elementAlign =
2154     addr.getAlignment()
2155         .alignmentOfArrayElement(getContext().getTypeSizeInChars(type));
2156 
2157   // Normally we have to check whether the array is zero-length.
2158   bool checkZeroLength = true;
2159 
2160   // But if the array length is constant, we can suppress that.
2161   if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
2162     // ...and if it's constant zero, we can just skip the entire thing.
2163     if (constLength->isZero()) return;
2164     checkZeroLength = false;
2165   }
2166 
2167   llvm::Value *begin = addr.getPointer();
2168   llvm::Value *end = Builder.CreateInBoundsGEP(begin, length);
2169   emitArrayDestroy(begin, end, type, elementAlign, destroyer,
2170                    checkZeroLength, useEHCleanupForArray);
2171 }
2172 
2173 /// emitArrayDestroy - Destroys all the elements of the given array,
2174 /// beginning from last to first.  The array cannot be zero-length.
2175 ///
2176 /// \param begin - a type* denoting the first element of the array
2177 /// \param end - a type* denoting one past the end of the array
2178 /// \param elementType - the element type of the array
2179 /// \param destroyer - the function to call to destroy elements
2180 /// \param useEHCleanup - whether to push an EH cleanup to destroy
2181 ///   the remaining elements in case the destruction of a single
2182 ///   element throws
2183 void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
2184                                        llvm::Value *end,
2185                                        QualType elementType,
2186                                        CharUnits elementAlign,
2187                                        Destroyer *destroyer,
2188                                        bool checkZeroLength,
2189                                        bool useEHCleanup) {
2190   assert(!elementType->isArrayType());
2191 
2192   // The basic structure here is a do-while loop, because we don't
2193   // need to check for the zero-element case.
2194   llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
2195   llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
2196 
2197   if (checkZeroLength) {
2198     llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
2199                                                 "arraydestroy.isempty");
2200     Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
2201   }
2202 
2203   // Enter the loop body, making that address the current address.
2204   llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
2205   EmitBlock(bodyBB);
2206   llvm::PHINode *elementPast =
2207     Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
2208   elementPast->addIncoming(end, entryBB);
2209 
2210   // Shift the address back by one element.
2211   llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
2212   llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne,
2213                                                    "arraydestroy.element");
2214 
2215   if (useEHCleanup)
2216     pushRegularPartialArrayCleanup(begin, element, elementType, elementAlign,
2217                                    destroyer);
2218 
2219   // Perform the actual destruction there.
2220   destroyer(*this, Address(element, elementAlign), elementType);
2221 
2222   if (useEHCleanup)
2223     PopCleanupBlock();
2224 
2225   // Check whether we've reached the end.
2226   llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
2227   Builder.CreateCondBr(done, doneBB, bodyBB);
2228   elementPast->addIncoming(element, Builder.GetInsertBlock());
2229 
2230   // Done.
2231   EmitBlock(doneBB);
2232 }
2233 
2234 /// Perform partial array destruction as if in an EH cleanup.  Unlike
2235 /// emitArrayDestroy, the element type here may still be an array type.
2236 static void emitPartialArrayDestroy(CodeGenFunction &CGF,
2237                                     llvm::Value *begin, llvm::Value *end,
2238                                     QualType type, CharUnits elementAlign,
2239                                     CodeGenFunction::Destroyer *destroyer) {
2240   // If the element type is itself an array, drill down.
2241   unsigned arrayDepth = 0;
2242   while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
2243     // VLAs don't require a GEP index to walk into.
2244     if (!isa<VariableArrayType>(arrayType))
2245       arrayDepth++;
2246     type = arrayType->getElementType();
2247   }
2248 
2249   if (arrayDepth) {
2250     llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
2251 
2252     SmallVector<llvm::Value*,4> gepIndices(arrayDepth+1, zero);
2253     begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin");
2254     end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend");
2255   }
2256 
2257   // Destroy the array.  We don't ever need an EH cleanup because we
2258   // assume that we're in an EH cleanup ourselves, so a throwing
2259   // destructor causes an immediate terminate.
2260   CGF.emitArrayDestroy(begin, end, type, elementAlign, destroyer,
2261                        /*checkZeroLength*/ true, /*useEHCleanup*/ false);
2262 }
2263 
2264 namespace {
2265   /// RegularPartialArrayDestroy - a cleanup which performs a partial
2266   /// array destroy where the end pointer is regularly determined and
2267   /// does not need to be loaded from a local.
2268   class RegularPartialArrayDestroy final : public EHScopeStack::Cleanup {
2269     llvm::Value *ArrayBegin;
2270     llvm::Value *ArrayEnd;
2271     QualType ElementType;
2272     CodeGenFunction::Destroyer *Destroyer;
2273     CharUnits ElementAlign;
2274   public:
2275     RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
2276                                QualType elementType, CharUnits elementAlign,
2277                                CodeGenFunction::Destroyer *destroyer)
2278       : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
2279         ElementType(elementType), Destroyer(destroyer),
2280         ElementAlign(elementAlign) {}
2281 
2282     void Emit(CodeGenFunction &CGF, Flags flags) override {
2283       emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
2284                               ElementType, ElementAlign, Destroyer);
2285     }
2286   };
2287 
2288   /// IrregularPartialArrayDestroy - a cleanup which performs a
2289   /// partial array destroy where the end pointer is irregularly
2290   /// determined and must be loaded from a local.
2291   class IrregularPartialArrayDestroy final : public EHScopeStack::Cleanup {
2292     llvm::Value *ArrayBegin;
2293     Address ArrayEndPointer;
2294     QualType ElementType;
2295     CodeGenFunction::Destroyer *Destroyer;
2296     CharUnits ElementAlign;
2297   public:
2298     IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
2299                                  Address arrayEndPointer,
2300                                  QualType elementType,
2301                                  CharUnits elementAlign,
2302                                  CodeGenFunction::Destroyer *destroyer)
2303       : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
2304         ElementType(elementType), Destroyer(destroyer),
2305         ElementAlign(elementAlign) {}
2306 
2307     void Emit(CodeGenFunction &CGF, Flags flags) override {
2308       llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
2309       emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
2310                               ElementType, ElementAlign, Destroyer);
2311     }
2312   };
2313 } // end anonymous namespace
2314 
2315 /// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
2316 /// already-constructed elements of the given array.  The cleanup
2317 /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
2318 ///
2319 /// \param elementType - the immediate element type of the array;
2320 ///   possibly still an array type
2321 void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
2322                                                        Address arrayEndPointer,
2323                                                        QualType elementType,
2324                                                        CharUnits elementAlign,
2325                                                        Destroyer *destroyer) {
2326   pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
2327                                                     arrayBegin, arrayEndPointer,
2328                                                     elementType, elementAlign,
2329                                                     destroyer);
2330 }
2331 
2332 /// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
2333 /// already-constructed elements of the given array.  The cleanup
2334 /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
2335 ///
2336 /// \param elementType - the immediate element type of the array;
2337 ///   possibly still an array type
2338 void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
2339                                                      llvm::Value *arrayEnd,
2340                                                      QualType elementType,
2341                                                      CharUnits elementAlign,
2342                                                      Destroyer *destroyer) {
2343   pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
2344                                                   arrayBegin, arrayEnd,
2345                                                   elementType, elementAlign,
2346                                                   destroyer);
2347 }
2348 
2349 /// Lazily declare the @llvm.lifetime.start intrinsic.
2350 llvm::Function *CodeGenModule::getLLVMLifetimeStartFn() {
2351   if (LifetimeStartFn)
2352     return LifetimeStartFn;
2353   LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(),
2354     llvm::Intrinsic::lifetime_start, AllocaInt8PtrTy);
2355   return LifetimeStartFn;
2356 }
2357 
2358 /// Lazily declare the @llvm.lifetime.end intrinsic.
2359 llvm::Function *CodeGenModule::getLLVMLifetimeEndFn() {
2360   if (LifetimeEndFn)
2361     return LifetimeEndFn;
2362   LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(),
2363     llvm::Intrinsic::lifetime_end, AllocaInt8PtrTy);
2364   return LifetimeEndFn;
2365 }
2366 
2367 namespace {
2368   /// A cleanup to perform a release of an object at the end of a
2369   /// function.  This is used to balance out the incoming +1 of a
2370   /// ns_consumed argument when we can't reasonably do that just by
2371   /// not doing the initial retain for a __block argument.
2372   struct ConsumeARCParameter final : EHScopeStack::Cleanup {
2373     ConsumeARCParameter(llvm::Value *param,
2374                         ARCPreciseLifetime_t precise)
2375       : Param(param), Precise(precise) {}
2376 
2377     llvm::Value *Param;
2378     ARCPreciseLifetime_t Precise;
2379 
2380     void Emit(CodeGenFunction &CGF, Flags flags) override {
2381       CGF.EmitARCRelease(Param, Precise);
2382     }
2383   };
2384 } // end anonymous namespace
2385 
2386 /// Emit an alloca (or GlobalValue depending on target)
2387 /// for the specified parameter and set up LocalDeclMap.
2388 void CodeGenFunction::EmitParmDecl(const VarDecl &D, ParamValue Arg,
2389                                    unsigned ArgNo) {
2390   // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
2391   assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
2392          "Invalid argument to EmitParmDecl");
2393 
2394   Arg.getAnyValue()->setName(D.getName());
2395 
2396   QualType Ty = D.getType();
2397 
2398   // Use better IR generation for certain implicit parameters.
2399   if (auto IPD = dyn_cast<ImplicitParamDecl>(&D)) {
2400     // The only implicit argument a block has is its literal.
2401     // This may be passed as an inalloca'ed value on Windows x86.
2402     if (BlockInfo) {
2403       llvm::Value *V = Arg.isIndirect()
2404                            ? Builder.CreateLoad(Arg.getIndirectAddress())
2405                            : Arg.getDirectValue();
2406       setBlockContextParameter(IPD, ArgNo, V);
2407       return;
2408     }
2409   }
2410 
2411   Address DeclPtr = Address::invalid();
2412   bool DoStore = false;
2413   bool IsScalar = hasScalarEvaluationKind(Ty);
2414   // If we already have a pointer to the argument, reuse the input pointer.
2415   if (Arg.isIndirect()) {
2416     DeclPtr = Arg.getIndirectAddress();
2417     // If we have a prettier pointer type at this point, bitcast to that.
2418     unsigned AS = DeclPtr.getType()->getAddressSpace();
2419     llvm::Type *IRTy = ConvertTypeForMem(Ty)->getPointerTo(AS);
2420     if (DeclPtr.getType() != IRTy)
2421       DeclPtr = Builder.CreateBitCast(DeclPtr, IRTy, D.getName());
2422     // Indirect argument is in alloca address space, which may be different
2423     // from the default address space.
2424     auto AllocaAS = CGM.getASTAllocaAddressSpace();
2425     auto *V = DeclPtr.getPointer();
2426     auto SrcLangAS = getLangOpts().OpenCL ? LangAS::opencl_private : AllocaAS;
2427     auto DestLangAS =
2428         getLangOpts().OpenCL ? LangAS::opencl_private : LangAS::Default;
2429     if (SrcLangAS != DestLangAS) {
2430       assert(getContext().getTargetAddressSpace(SrcLangAS) ==
2431              CGM.getDataLayout().getAllocaAddrSpace());
2432       auto DestAS = getContext().getTargetAddressSpace(DestLangAS);
2433       auto *T = V->getType()->getPointerElementType()->getPointerTo(DestAS);
2434       DeclPtr = Address(getTargetHooks().performAddrSpaceCast(
2435                             *this, V, SrcLangAS, DestLangAS, T, true),
2436                         DeclPtr.getAlignment());
2437     }
2438 
2439     // Push a destructor cleanup for this parameter if the ABI requires it.
2440     // Don't push a cleanup in a thunk for a method that will also emit a
2441     // cleanup.
2442     if (hasAggregateEvaluationKind(Ty) && !CurFuncIsThunk &&
2443         Ty->getAs<RecordType>()->getDecl()->isParamDestroyedInCallee()) {
2444       if (QualType::DestructionKind DtorKind = Ty.isDestructedType()) {
2445         assert((DtorKind == QualType::DK_cxx_destructor ||
2446                 DtorKind == QualType::DK_nontrivial_c_struct) &&
2447                "unexpected destructor type");
2448         pushDestroy(DtorKind, DeclPtr, Ty);
2449         CalleeDestructedParamCleanups[cast<ParmVarDecl>(&D)] =
2450             EHStack.stable_begin();
2451       }
2452     }
2453   } else {
2454     // Check if the parameter address is controlled by OpenMP runtime.
2455     Address OpenMPLocalAddr =
2456         getLangOpts().OpenMP
2457             ? CGM.getOpenMPRuntime().getAddressOfLocalVariable(*this, &D)
2458             : Address::invalid();
2459     if (getLangOpts().OpenMP && OpenMPLocalAddr.isValid()) {
2460       DeclPtr = OpenMPLocalAddr;
2461     } else {
2462       // Otherwise, create a temporary to hold the value.
2463       DeclPtr = CreateMemTemp(Ty, getContext().getDeclAlign(&D),
2464                               D.getName() + ".addr");
2465     }
2466     DoStore = true;
2467   }
2468 
2469   llvm::Value *ArgVal = (DoStore ? Arg.getDirectValue() : nullptr);
2470 
2471   LValue lv = MakeAddrLValue(DeclPtr, Ty);
2472   if (IsScalar) {
2473     Qualifiers qs = Ty.getQualifiers();
2474     if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
2475       // We honor __attribute__((ns_consumed)) for types with lifetime.
2476       // For __strong, it's handled by just skipping the initial retain;
2477       // otherwise we have to balance out the initial +1 with an extra
2478       // cleanup to do the release at the end of the function.
2479       bool isConsumed = D.hasAttr<NSConsumedAttr>();
2480 
2481       // If a parameter is pseudo-strong then we can omit the implicit retain.
2482       if (D.isARCPseudoStrong()) {
2483         assert(lt == Qualifiers::OCL_Strong &&
2484                "pseudo-strong variable isn't strong?");
2485         assert(qs.hasConst() && "pseudo-strong variable should be const!");
2486         lt = Qualifiers::OCL_ExplicitNone;
2487       }
2488 
2489       // Load objects passed indirectly.
2490       if (Arg.isIndirect() && !ArgVal)
2491         ArgVal = Builder.CreateLoad(DeclPtr);
2492 
2493       if (lt == Qualifiers::OCL_Strong) {
2494         if (!isConsumed) {
2495           if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
2496             // use objc_storeStrong(&dest, value) for retaining the
2497             // object. But first, store a null into 'dest' because
2498             // objc_storeStrong attempts to release its old value.
2499             llvm::Value *Null = CGM.EmitNullConstant(D.getType());
2500             EmitStoreOfScalar(Null, lv, /* isInitialization */ true);
2501             EmitARCStoreStrongCall(lv.getAddress(), ArgVal, true);
2502             DoStore = false;
2503           }
2504           else
2505           // Don't use objc_retainBlock for block pointers, because we
2506           // don't want to Block_copy something just because we got it
2507           // as a parameter.
2508             ArgVal = EmitARCRetainNonBlock(ArgVal);
2509         }
2510       } else {
2511         // Push the cleanup for a consumed parameter.
2512         if (isConsumed) {
2513           ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
2514                                 ? ARCPreciseLifetime : ARCImpreciseLifetime);
2515           EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), ArgVal,
2516                                                    precise);
2517         }
2518 
2519         if (lt == Qualifiers::OCL_Weak) {
2520           EmitARCInitWeak(DeclPtr, ArgVal);
2521           DoStore = false; // The weak init is a store, no need to do two.
2522         }
2523       }
2524 
2525       // Enter the cleanup scope.
2526       EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
2527     }
2528   }
2529 
2530   // Store the initial value into the alloca.
2531   if (DoStore)
2532     EmitStoreOfScalar(ArgVal, lv, /* isInitialization */ true);
2533 
2534   setAddrOfLocalVar(&D, DeclPtr);
2535 
2536   // Emit debug info for param declaration.
2537   if (CGDebugInfo *DI = getDebugInfo()) {
2538     if (CGM.getCodeGenOpts().getDebugInfo() >=
2539         codegenoptions::LimitedDebugInfo) {
2540       DI->EmitDeclareOfArgVariable(&D, DeclPtr.getPointer(), ArgNo, Builder);
2541     }
2542   }
2543 
2544   if (D.hasAttr<AnnotateAttr>())
2545     EmitVarAnnotations(&D, DeclPtr.getPointer());
2546 
2547   // We can only check return value nullability if all arguments to the
2548   // function satisfy their nullability preconditions. This makes it necessary
2549   // to emit null checks for args in the function body itself.
2550   if (requiresReturnValueNullabilityCheck()) {
2551     auto Nullability = Ty->getNullability(getContext());
2552     if (Nullability && *Nullability == NullabilityKind::NonNull) {
2553       SanitizerScope SanScope(this);
2554       RetValNullabilityPrecondition =
2555           Builder.CreateAnd(RetValNullabilityPrecondition,
2556                             Builder.CreateIsNotNull(Arg.getAnyValue()));
2557     }
2558   }
2559 }
2560 
2561 void CodeGenModule::EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D,
2562                                             CodeGenFunction *CGF) {
2563   if (!LangOpts.OpenMP || (!LangOpts.EmitAllDecls && !D->isUsed()))
2564     return;
2565   getOpenMPRuntime().emitUserDefinedReduction(CGF, D);
2566 }
2567 
2568 void CodeGenModule::EmitOMPDeclareMapper(const OMPDeclareMapperDecl *D,
2569                                             CodeGenFunction *CGF) {
2570   if (!LangOpts.OpenMP || (!LangOpts.EmitAllDecls && !D->isUsed()))
2571     return;
2572   // FIXME: need to implement mapper code generation
2573 }
2574 
2575 void CodeGenModule::EmitOMPRequiresDecl(const OMPRequiresDecl *D) {
2576   getOpenMPRuntime().checkArchForUnifiedAddressing(D);
2577 }
2578