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