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