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