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