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::TemplateParamObject:
122   case Decl::OMPThreadPrivate:
123   case Decl::OMPAllocate:
124   case Decl::OMPCapturedExpr:
125   case Decl::OMPRequires:
126   case Decl::Empty:
127   case Decl::Concept:
128   case Decl::LifetimeExtendedTemporary:
129   case Decl::RequiresExprBody:
130     // None of these decls require codegen support.
131     return;
132 
133   case Decl::NamespaceAlias:
134     if (CGDebugInfo *DI = getDebugInfo())
135         DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(D));
136     return;
137   case Decl::Using:          // using X; [C++]
138     if (CGDebugInfo *DI = getDebugInfo())
139         DI->EmitUsingDecl(cast<UsingDecl>(D));
140     return;
141   case Decl::UsingEnum: // using enum X; [C++]
142     if (CGDebugInfo *DI = getDebugInfo())
143       DI->EmitUsingEnumDecl(cast<UsingEnumDecl>(D));
144     return;
145   case Decl::UsingPack:
146     for (auto *Using : cast<UsingPackDecl>(D).expansions())
147       EmitDecl(*Using);
148     return;
149   case Decl::UsingDirective: // using namespace X; [C++]
150     if (CGDebugInfo *DI = getDebugInfo())
151       DI->EmitUsingDirective(cast<UsingDirectiveDecl>(D));
152     return;
153   case Decl::Var:
154   case Decl::Decomposition: {
155     const VarDecl &VD = cast<VarDecl>(D);
156     assert(VD.isLocalVarDecl() &&
157            "Should not see file-scope variables inside a function!");
158     EmitVarDecl(VD);
159     if (auto *DD = dyn_cast<DecompositionDecl>(&VD))
160       for (auto *B : DD->bindings())
161         if (auto *HD = B->getHoldingVar())
162           EmitVarDecl(*HD);
163     return;
164   }
165 
166   case Decl::OMPDeclareReduction:
167     return CGM.EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(&D), this);
168 
169   case Decl::OMPDeclareMapper:
170     return CGM.EmitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(&D), this);
171 
172   case Decl::Typedef:      // typedef int X;
173   case Decl::TypeAlias: {  // using X = int; [C++0x]
174     QualType Ty = cast<TypedefNameDecl>(D).getUnderlyingType();
175     if (CGDebugInfo *DI = getDebugInfo())
176       DI->EmitAndRetainType(Ty);
177     if (Ty->isVariablyModifiedType())
178       EmitVariablyModifiedType(Ty);
179     return;
180   }
181   }
182 }
183 
184 /// EmitVarDecl - This method handles emission of any variable declaration
185 /// inside a function, including static vars etc.
186 void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
187   if (D.hasExternalStorage())
188     // Don't emit it now, allow it to be emitted lazily on its first use.
189     return;
190 
191   // Some function-scope variable does not have static storage but still
192   // needs to be emitted like a static variable, e.g. a function-scope
193   // variable in constant address space in OpenCL.
194   if (D.getStorageDuration() != SD_Automatic) {
195     // Static sampler variables translated to function calls.
196     if (D.getType()->isSamplerT())
197       return;
198 
199     llvm::GlobalValue::LinkageTypes Linkage =
200         CGM.getLLVMLinkageVarDefinition(&D, /*IsConstant=*/false);
201 
202     // FIXME: We need to force the emission/use of a guard variable for
203     // some variables even if we can constant-evaluate them because
204     // we can't guarantee every translation unit will constant-evaluate them.
205 
206     return EmitStaticVarDecl(D, Linkage);
207   }
208 
209   if (D.getType().getAddressSpace() == LangAS::opencl_local)
210     return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D);
211 
212   assert(D.hasLocalStorage());
213   return EmitAutoVarDecl(D);
214 }
215 
216 static std::string getStaticDeclName(CodeGenModule &CGM, const VarDecl &D) {
217   if (CGM.getLangOpts().CPlusPlus)
218     return CGM.getMangledName(&D).str();
219 
220   // If this isn't C++, we don't need a mangled name, just a pretty one.
221   assert(!D.isExternallyVisible() && "name shouldn't matter");
222   std::string ContextName;
223   const DeclContext *DC = D.getDeclContext();
224   if (auto *CD = dyn_cast<CapturedDecl>(DC))
225     DC = cast<DeclContext>(CD->getNonClosureContext());
226   if (const auto *FD = dyn_cast<FunctionDecl>(DC))
227     ContextName = std::string(CGM.getMangledName(FD));
228   else if (const auto *BD = dyn_cast<BlockDecl>(DC))
229     ContextName = std::string(CGM.getBlockMangledName(GlobalDecl(), BD));
230   else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(DC))
231     ContextName = OMD->getSelector().getAsString();
232   else
233     llvm_unreachable("Unknown context for static var decl");
234 
235   ContextName += "." + D.getNameAsString();
236   return ContextName;
237 }
238 
239 llvm::Constant *CodeGenModule::getOrCreateStaticVarDecl(
240     const VarDecl &D, llvm::GlobalValue::LinkageTypes Linkage) {
241   // In general, we don't always emit static var decls once before we reference
242   // them. It is possible to reference them before emitting the function that
243   // contains them, and it is possible to emit the containing function multiple
244   // times.
245   if (llvm::Constant *ExistingGV = StaticLocalDeclMap[&D])
246     return ExistingGV;
247 
248   QualType Ty = D.getType();
249   assert(Ty->isConstantSizeType() && "VLAs can't be static");
250 
251   // Use the label if the variable is renamed with the asm-label extension.
252   std::string Name;
253   if (D.hasAttr<AsmLabelAttr>())
254     Name = std::string(getMangledName(&D));
255   else
256     Name = getStaticDeclName(*this, D);
257 
258   llvm::Type *LTy = getTypes().ConvertTypeForMem(Ty);
259   LangAS AS = GetGlobalVarAddressSpace(&D);
260   unsigned TargetAS = getContext().getTargetAddressSpace(AS);
261 
262   // OpenCL variables in local address space and CUDA shared
263   // variables cannot have an initializer.
264   llvm::Constant *Init = nullptr;
265   if (Ty.getAddressSpace() == LangAS::opencl_local ||
266       D.hasAttr<CUDASharedAttr>() || D.hasAttr<LoaderUninitializedAttr>())
267     Init = llvm::UndefValue::get(LTy);
268   else
269     Init = EmitNullConstant(Ty);
270 
271   llvm::GlobalVariable *GV = new llvm::GlobalVariable(
272       getModule(), LTy, Ty.isConstant(getContext()), Linkage, Init, Name,
273       nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
274   GV->setAlignment(getContext().getDeclAlign(&D).getAsAlign());
275 
276   if (supportsCOMDAT() && GV->isWeakForLinker())
277     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
278 
279   if (D.getTLSKind())
280     setTLSMode(GV, D);
281 
282   setGVProperties(GV, &D);
283 
284   // Make sure the result is of the correct type.
285   LangAS ExpectedAS = Ty.getAddressSpace();
286   llvm::Constant *Addr = GV;
287   if (AS != ExpectedAS) {
288     Addr = getTargetCodeGenInfo().performAddrSpaceCast(
289         *this, GV, AS, ExpectedAS,
290         LTy->getPointerTo(getContext().getTargetAddressSpace(ExpectedAS)));
291   }
292 
293   setStaticLocalDeclAddress(&D, Addr);
294 
295   // Ensure that the static local gets initialized by making sure the parent
296   // function gets emitted eventually.
297   const Decl *DC = cast<Decl>(D.getDeclContext());
298 
299   // We can't name blocks or captured statements directly, so try to emit their
300   // parents.
301   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC)) {
302     DC = DC->getNonClosureContext();
303     // FIXME: Ensure that global blocks get emitted.
304     if (!DC)
305       return Addr;
306   }
307 
308   GlobalDecl GD;
309   if (const auto *CD = dyn_cast<CXXConstructorDecl>(DC))
310     GD = GlobalDecl(CD, Ctor_Base);
311   else if (const auto *DD = dyn_cast<CXXDestructorDecl>(DC))
312     GD = GlobalDecl(DD, Dtor_Base);
313   else if (const auto *FD = dyn_cast<FunctionDecl>(DC))
314     GD = GlobalDecl(FD);
315   else {
316     // Don't do anything for Obj-C method decls or global closures. We should
317     // never defer them.
318     assert(isa<ObjCMethodDecl>(DC) && "unexpected parent code decl");
319   }
320   if (GD.getDecl()) {
321     // Disable emission of the parent function for the OpenMP device codegen.
322     CGOpenMPRuntime::DisableAutoDeclareTargetRAII NoDeclTarget(*this);
323     (void)GetAddrOfGlobal(GD);
324   }
325 
326   return Addr;
327 }
328 
329 /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
330 /// global variable that has already been created for it.  If the initializer
331 /// has a different type than GV does, this may free GV and return a different
332 /// one.  Otherwise it just returns GV.
333 llvm::GlobalVariable *
334 CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
335                                                llvm::GlobalVariable *GV) {
336   ConstantEmitter emitter(*this);
337   llvm::Constant *Init = emitter.tryEmitForInitializer(D);
338 
339   // If constant emission failed, then this should be a C++ static
340   // initializer.
341   if (!Init) {
342     if (!getLangOpts().CPlusPlus)
343       CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
344     else if (HaveInsertPoint()) {
345       // Since we have a static initializer, this global variable can't
346       // be constant.
347       GV->setConstant(false);
348 
349       EmitCXXGuardedInit(D, GV, /*PerformInit*/true);
350     }
351     return GV;
352   }
353 
354   // The initializer may differ in type from the global. Rewrite
355   // the global to match the initializer.  (We have to do this
356   // because some types, like unions, can't be completely represented
357   // in the LLVM type system.)
358   if (GV->getValueType() != Init->getType()) {
359     llvm::GlobalVariable *OldGV = GV;
360 
361     GV = new llvm::GlobalVariable(
362         CGM.getModule(), Init->getType(), OldGV->isConstant(),
363         OldGV->getLinkage(), Init, "",
364         /*InsertBefore*/ OldGV, OldGV->getThreadLocalMode(),
365         OldGV->getType()->getPointerAddressSpace());
366     GV->setVisibility(OldGV->getVisibility());
367     GV->setDSOLocal(OldGV->isDSOLocal());
368     GV->setComdat(OldGV->getComdat());
369 
370     // Steal the name of the old global
371     GV->takeName(OldGV);
372 
373     // Replace all uses of the old global with the new global
374     llvm::Constant *NewPtrForOldDecl =
375     llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
376     OldGV->replaceAllUsesWith(NewPtrForOldDecl);
377 
378     // Erase the old global, since it is no longer used.
379     OldGV->eraseFromParent();
380   }
381 
382   GV->setConstant(CGM.isTypeConstant(D.getType(), true));
383   GV->setInitializer(Init);
384 
385   emitter.finalize(GV);
386 
387   if (D.needsDestruction(getContext()) == QualType::DK_cxx_destructor &&
388       HaveInsertPoint()) {
389     // We have a constant initializer, but a nontrivial destructor. We still
390     // need to perform a guarded "initialization" in order to register the
391     // destructor.
392     EmitCXXGuardedInit(D, GV, /*PerformInit*/false);
393   }
394 
395   return GV;
396 }
397 
398 void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
399                                       llvm::GlobalValue::LinkageTypes Linkage) {
400   // Check to see if we already have a global variable for this
401   // declaration.  This can happen when double-emitting function
402   // bodies, e.g. with complete and base constructors.
403   llvm::Constant *addr = CGM.getOrCreateStaticVarDecl(D, Linkage);
404   CharUnits alignment = getContext().getDeclAlign(&D);
405 
406   // Store into LocalDeclMap before generating initializer to handle
407   // circular references.
408   setAddrOfLocalVar(
409       &D, Address(addr, ConvertTypeForMem(D.getType()), alignment));
410 
411   // We can't have a VLA here, but we can have a pointer to a VLA,
412   // even though that doesn't really make any sense.
413   // Make sure to evaluate VLA bounds now so that we have them for later.
414   if (D.getType()->isVariablyModifiedType())
415     EmitVariablyModifiedType(D.getType());
416 
417   // Save the type in case adding the initializer forces a type change.
418   llvm::Type *expectedType = addr->getType();
419 
420   llvm::GlobalVariable *var =
421     cast<llvm::GlobalVariable>(addr->stripPointerCasts());
422 
423   // CUDA's local and local static __shared__ variables should not
424   // have any non-empty initializers. This is ensured by Sema.
425   // Whatever initializer such variable may have when it gets here is
426   // a no-op and should not be emitted.
427   bool isCudaSharedVar = getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
428                          D.hasAttr<CUDASharedAttr>();
429   // If this value has an initializer, emit it.
430   if (D.getInit() && !isCudaSharedVar)
431     var = AddInitializerToStaticVarDecl(D, var);
432 
433   var->setAlignment(alignment.getAsAlign());
434 
435   if (D.hasAttr<AnnotateAttr>())
436     CGM.AddGlobalAnnotations(&D, var);
437 
438   if (auto *SA = D.getAttr<PragmaClangBSSSectionAttr>())
439     var->addAttribute("bss-section", SA->getName());
440   if (auto *SA = D.getAttr<PragmaClangDataSectionAttr>())
441     var->addAttribute("data-section", SA->getName());
442   if (auto *SA = D.getAttr<PragmaClangRodataSectionAttr>())
443     var->addAttribute("rodata-section", SA->getName());
444   if (auto *SA = D.getAttr<PragmaClangRelroSectionAttr>())
445     var->addAttribute("relro-section", SA->getName());
446 
447   if (const SectionAttr *SA = D.getAttr<SectionAttr>())
448     var->setSection(SA->getName());
449 
450   if (D.hasAttr<RetainAttr>())
451     CGM.addUsedGlobal(var);
452   else if (D.hasAttr<UsedAttr>())
453     CGM.addUsedOrCompilerUsedGlobal(var);
454 
455   // We may have to cast the constant because of the initializer
456   // mismatch above.
457   //
458   // FIXME: It is really dangerous to store this in the map; if anyone
459   // RAUW's the GV uses of this constant will be invalid.
460   llvm::Constant *castedAddr =
461     llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(var, expectedType);
462   if (var != castedAddr)
463     LocalDeclMap.find(&D)->second = Address(castedAddr, 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   llvm::Type *BP = llvm::PointerType::getInt8PtrTy(CGM.getLLVMContext(),
1160                                                    SrcPtr.getAddressSpace());
1161   if (SrcPtr.getType() != BP)
1162     SrcPtr = Builder.CreateBitCast(SrcPtr, BP);
1163   return SrcPtr;
1164 }
1165 
1166 static void emitStoresForConstant(CodeGenModule &CGM, const VarDecl &D,
1167                                   Address Loc, bool isVolatile,
1168                                   CGBuilderTy &Builder,
1169                                   llvm::Constant *constant, bool IsAutoInit) {
1170   auto *Ty = constant->getType();
1171   uint64_t ConstantSize = CGM.getDataLayout().getTypeAllocSize(Ty);
1172   if (!ConstantSize)
1173     return;
1174 
1175   bool canDoSingleStore = Ty->isIntOrIntVectorTy() ||
1176                           Ty->isPtrOrPtrVectorTy() || Ty->isFPOrFPVectorTy();
1177   if (canDoSingleStore) {
1178     auto *I = Builder.CreateStore(constant, Loc, isVolatile);
1179     if (IsAutoInit)
1180       I->addAnnotationMetadata("auto-init");
1181     return;
1182   }
1183 
1184   auto *SizeVal = llvm::ConstantInt::get(CGM.IntPtrTy, ConstantSize);
1185 
1186   // If the initializer is all or mostly the same, codegen with bzero / memset
1187   // then do a few stores afterward.
1188   if (shouldUseBZeroPlusStoresToInitialize(constant, ConstantSize)) {
1189     auto *I = Builder.CreateMemSet(Loc, llvm::ConstantInt::get(CGM.Int8Ty, 0),
1190                                    SizeVal, isVolatile);
1191     if (IsAutoInit)
1192       I->addAnnotationMetadata("auto-init");
1193 
1194     bool valueAlreadyCorrect =
1195         constant->isNullValue() || isa<llvm::UndefValue>(constant);
1196     if (!valueAlreadyCorrect) {
1197       Loc = Builder.CreateBitCast(Loc, Ty->getPointerTo(Loc.getAddressSpace()));
1198       emitStoresForInitAfterBZero(CGM, constant, Loc, isVolatile, Builder,
1199                                   IsAutoInit);
1200     }
1201     return;
1202   }
1203 
1204   // If the initializer is a repeated byte pattern, use memset.
1205   llvm::Value *Pattern =
1206       shouldUseMemSetToInitialize(constant, ConstantSize, CGM.getDataLayout());
1207   if (Pattern) {
1208     uint64_t Value = 0x00;
1209     if (!isa<llvm::UndefValue>(Pattern)) {
1210       const llvm::APInt &AP = cast<llvm::ConstantInt>(Pattern)->getValue();
1211       assert(AP.getBitWidth() <= 8);
1212       Value = AP.getLimitedValue();
1213     }
1214     auto *I = Builder.CreateMemSet(
1215         Loc, llvm::ConstantInt::get(CGM.Int8Ty, Value), SizeVal, isVolatile);
1216     if (IsAutoInit)
1217       I->addAnnotationMetadata("auto-init");
1218     return;
1219   }
1220 
1221   // If the initializer is small, use a handful of stores.
1222   if (shouldSplitConstantStore(CGM, ConstantSize)) {
1223     if (auto *STy = dyn_cast<llvm::StructType>(Ty)) {
1224       // FIXME: handle the case when STy != Loc.getElementType().
1225       if (STy == Loc.getElementType()) {
1226         for (unsigned i = 0; i != constant->getNumOperands(); i++) {
1227           Address EltPtr = Builder.CreateStructGEP(Loc, i);
1228           emitStoresForConstant(
1229               CGM, D, EltPtr, isVolatile, Builder,
1230               cast<llvm::Constant>(Builder.CreateExtractValue(constant, i)),
1231               IsAutoInit);
1232         }
1233         return;
1234       }
1235     } else if (auto *ATy = dyn_cast<llvm::ArrayType>(Ty)) {
1236       // FIXME: handle the case when ATy != Loc.getElementType().
1237       if (ATy == Loc.getElementType()) {
1238         for (unsigned i = 0; i != ATy->getNumElements(); i++) {
1239           Address EltPtr = Builder.CreateConstArrayGEP(Loc, i);
1240           emitStoresForConstant(
1241               CGM, D, EltPtr, isVolatile, Builder,
1242               cast<llvm::Constant>(Builder.CreateExtractValue(constant, i)),
1243               IsAutoInit);
1244         }
1245         return;
1246       }
1247     }
1248   }
1249 
1250   // Copy from a global.
1251   auto *I =
1252       Builder.CreateMemCpy(Loc,
1253                            createUnnamedGlobalForMemcpyFrom(
1254                                CGM, D, Builder, constant, Loc.getAlignment()),
1255                            SizeVal, isVolatile);
1256   if (IsAutoInit)
1257     I->addAnnotationMetadata("auto-init");
1258 }
1259 
1260 static void emitStoresForZeroInit(CodeGenModule &CGM, const VarDecl &D,
1261                                   Address Loc, bool isVolatile,
1262                                   CGBuilderTy &Builder) {
1263   llvm::Type *ElTy = Loc.getElementType();
1264   llvm::Constant *constant =
1265       constWithPadding(CGM, IsPattern::No, llvm::Constant::getNullValue(ElTy));
1266   emitStoresForConstant(CGM, D, Loc, isVolatile, Builder, constant,
1267                         /*IsAutoInit=*/true);
1268 }
1269 
1270 static void emitStoresForPatternInit(CodeGenModule &CGM, const VarDecl &D,
1271                                      Address Loc, bool isVolatile,
1272                                      CGBuilderTy &Builder) {
1273   llvm::Type *ElTy = Loc.getElementType();
1274   llvm::Constant *constant = constWithPadding(
1275       CGM, IsPattern::Yes, initializationPatternFor(CGM, ElTy));
1276   assert(!isa<llvm::UndefValue>(constant));
1277   emitStoresForConstant(CGM, D, Loc, isVolatile, Builder, constant,
1278                         /*IsAutoInit=*/true);
1279 }
1280 
1281 static bool containsUndef(llvm::Constant *constant) {
1282   auto *Ty = constant->getType();
1283   if (isa<llvm::UndefValue>(constant))
1284     return true;
1285   if (Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy())
1286     for (llvm::Use &Op : constant->operands())
1287       if (containsUndef(cast<llvm::Constant>(Op)))
1288         return true;
1289   return false;
1290 }
1291 
1292 static llvm::Constant *replaceUndef(CodeGenModule &CGM, IsPattern isPattern,
1293                                     llvm::Constant *constant) {
1294   auto *Ty = constant->getType();
1295   if (isa<llvm::UndefValue>(constant))
1296     return patternOrZeroFor(CGM, isPattern, Ty);
1297   if (!(Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()))
1298     return constant;
1299   if (!containsUndef(constant))
1300     return constant;
1301   llvm::SmallVector<llvm::Constant *, 8> Values(constant->getNumOperands());
1302   for (unsigned Op = 0, NumOp = constant->getNumOperands(); Op != NumOp; ++Op) {
1303     auto *OpValue = cast<llvm::Constant>(constant->getOperand(Op));
1304     Values[Op] = replaceUndef(CGM, isPattern, OpValue);
1305   }
1306   if (Ty->isStructTy())
1307     return llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Values);
1308   if (Ty->isArrayTy())
1309     return llvm::ConstantArray::get(cast<llvm::ArrayType>(Ty), Values);
1310   assert(Ty->isVectorTy());
1311   return llvm::ConstantVector::get(Values);
1312 }
1313 
1314 /// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
1315 /// variable declaration with auto, register, or no storage class specifier.
1316 /// These turn into simple stack objects, or GlobalValues depending on target.
1317 void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
1318   AutoVarEmission emission = EmitAutoVarAlloca(D);
1319   EmitAutoVarInit(emission);
1320   EmitAutoVarCleanups(emission);
1321 }
1322 
1323 /// Emit a lifetime.begin marker if some criteria are satisfied.
1324 /// \return a pointer to the temporary size Value if a marker was emitted, null
1325 /// otherwise
1326 llvm::Value *CodeGenFunction::EmitLifetimeStart(llvm::TypeSize Size,
1327                                                 llvm::Value *Addr) {
1328   if (!ShouldEmitLifetimeMarkers)
1329     return nullptr;
1330 
1331   assert(Addr->getType()->getPointerAddressSpace() ==
1332              CGM.getDataLayout().getAllocaAddrSpace() &&
1333          "Pointer should be in alloca address space");
1334   llvm::Value *SizeV = llvm::ConstantInt::get(
1335       Int64Ty, Size.isScalable() ? -1 : Size.getFixedValue());
1336   Addr = Builder.CreateBitCast(Addr, AllocaInt8PtrTy);
1337   llvm::CallInst *C =
1338       Builder.CreateCall(CGM.getLLVMLifetimeStartFn(), {SizeV, Addr});
1339   C->setDoesNotThrow();
1340   return SizeV;
1341 }
1342 
1343 void CodeGenFunction::EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr) {
1344   assert(Addr->getType()->getPointerAddressSpace() ==
1345              CGM.getDataLayout().getAllocaAddrSpace() &&
1346          "Pointer should be in alloca address space");
1347   Addr = Builder.CreateBitCast(Addr, AllocaInt8PtrTy);
1348   llvm::CallInst *C =
1349       Builder.CreateCall(CGM.getLLVMLifetimeEndFn(), {Size, Addr});
1350   C->setDoesNotThrow();
1351 }
1352 
1353 void CodeGenFunction::EmitAndRegisterVariableArrayDimensions(
1354     CGDebugInfo *DI, const VarDecl &D, bool EmitDebugInfo) {
1355   // For each dimension stores its QualType and corresponding
1356   // size-expression Value.
1357   SmallVector<CodeGenFunction::VlaSizePair, 4> Dimensions;
1358   SmallVector<IdentifierInfo *, 4> VLAExprNames;
1359 
1360   // Break down the array into individual dimensions.
1361   QualType Type1D = D.getType();
1362   while (getContext().getAsVariableArrayType(Type1D)) {
1363     auto VlaSize = getVLAElements1D(Type1D);
1364     if (auto *C = dyn_cast<llvm::ConstantInt>(VlaSize.NumElts))
1365       Dimensions.emplace_back(C, Type1D.getUnqualifiedType());
1366     else {
1367       // Generate a locally unique name for the size expression.
1368       Twine Name = Twine("__vla_expr") + Twine(VLAExprCounter++);
1369       SmallString<12> Buffer;
1370       StringRef NameRef = Name.toStringRef(Buffer);
1371       auto &Ident = getContext().Idents.getOwn(NameRef);
1372       VLAExprNames.push_back(&Ident);
1373       auto SizeExprAddr =
1374           CreateDefaultAlignTempAlloca(VlaSize.NumElts->getType(), NameRef);
1375       Builder.CreateStore(VlaSize.NumElts, SizeExprAddr);
1376       Dimensions.emplace_back(SizeExprAddr.getPointer(),
1377                               Type1D.getUnqualifiedType());
1378     }
1379     Type1D = VlaSize.Type;
1380   }
1381 
1382   if (!EmitDebugInfo)
1383     return;
1384 
1385   // Register each dimension's size-expression with a DILocalVariable,
1386   // so that it can be used by CGDebugInfo when instantiating a DISubrange
1387   // to describe this array.
1388   unsigned NameIdx = 0;
1389   for (auto &VlaSize : Dimensions) {
1390     llvm::Metadata *MD;
1391     if (auto *C = dyn_cast<llvm::ConstantInt>(VlaSize.NumElts))
1392       MD = llvm::ConstantAsMetadata::get(C);
1393     else {
1394       // Create an artificial VarDecl to generate debug info for.
1395       IdentifierInfo *NameIdent = VLAExprNames[NameIdx++];
1396       auto VlaExprTy = VlaSize.NumElts->getType()->getPointerElementType();
1397       auto QT = getContext().getIntTypeForBitwidth(
1398           VlaExprTy->getScalarSizeInBits(), false);
1399       auto *ArtificialDecl = VarDecl::Create(
1400           getContext(), const_cast<DeclContext *>(D.getDeclContext()),
1401           D.getLocation(), D.getLocation(), NameIdent, QT,
1402           getContext().CreateTypeSourceInfo(QT), SC_Auto);
1403       ArtificialDecl->setImplicit();
1404 
1405       MD = DI->EmitDeclareOfAutoVariable(ArtificialDecl, VlaSize.NumElts,
1406                                          Builder);
1407     }
1408     assert(MD && "No Size expression debug node created");
1409     DI->registerVLASizeExpression(VlaSize.Type, MD);
1410   }
1411 }
1412 
1413 /// EmitAutoVarAlloca - Emit the alloca and debug information for a
1414 /// local variable.  Does not emit initialization or destruction.
1415 CodeGenFunction::AutoVarEmission
1416 CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
1417   QualType Ty = D.getType();
1418   assert(
1419       Ty.getAddressSpace() == LangAS::Default ||
1420       (Ty.getAddressSpace() == LangAS::opencl_private && getLangOpts().OpenCL));
1421 
1422   AutoVarEmission emission(D);
1423 
1424   bool isEscapingByRef = D.isEscapingByref();
1425   emission.IsEscapingByRef = isEscapingByRef;
1426 
1427   CharUnits alignment = getContext().getDeclAlign(&D);
1428 
1429   // If the type is variably-modified, emit all the VLA sizes for it.
1430   if (Ty->isVariablyModifiedType())
1431     EmitVariablyModifiedType(Ty);
1432 
1433   auto *DI = getDebugInfo();
1434   bool EmitDebugInfo = DI && CGM.getCodeGenOpts().hasReducedDebugInfo();
1435 
1436   Address address = Address::invalid();
1437   Address AllocaAddr = Address::invalid();
1438   Address OpenMPLocalAddr = Address::invalid();
1439   if (CGM.getLangOpts().OpenMPIRBuilder)
1440     OpenMPLocalAddr = OMPBuilderCBHelpers::getAddressOfLocalVariable(*this, &D);
1441   else
1442     OpenMPLocalAddr =
1443         getLangOpts().OpenMP
1444             ? CGM.getOpenMPRuntime().getAddressOfLocalVariable(*this, &D)
1445             : Address::invalid();
1446 
1447   bool NRVO = getLangOpts().ElideConstructors && D.isNRVOVariable();
1448 
1449   if (getLangOpts().OpenMP && OpenMPLocalAddr.isValid()) {
1450     address = OpenMPLocalAddr;
1451     AllocaAddr = OpenMPLocalAddr;
1452   } else if (Ty->isConstantSizeType()) {
1453     // If this value is an array or struct with a statically determinable
1454     // constant initializer, there are optimizations we can do.
1455     //
1456     // TODO: We should constant-evaluate the initializer of any variable,
1457     // as long as it is initialized by a constant expression. Currently,
1458     // isConstantInitializer produces wrong answers for structs with
1459     // reference or bitfield members, and a few other cases, and checking
1460     // for POD-ness protects us from some of these.
1461     if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) &&
1462         (D.isConstexpr() ||
1463          ((Ty.isPODType(getContext()) ||
1464            getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
1465           D.getInit()->isConstantInitializer(getContext(), false)))) {
1466 
1467       // If the variable's a const type, and it's neither an NRVO
1468       // candidate nor a __block variable and has no mutable members,
1469       // emit it as a global instead.
1470       // Exception is if a variable is located in non-constant address space
1471       // in OpenCL.
1472       if ((!getLangOpts().OpenCL ||
1473            Ty.getAddressSpace() == LangAS::opencl_constant) &&
1474           (CGM.getCodeGenOpts().MergeAllConstants && !NRVO &&
1475            !isEscapingByRef && CGM.isTypeConstant(Ty, true))) {
1476         EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
1477 
1478         // Signal this condition to later callbacks.
1479         emission.Addr = Address::invalid();
1480         assert(emission.wasEmittedAsGlobal());
1481         return emission;
1482       }
1483 
1484       // Otherwise, tell the initialization code that we're in this case.
1485       emission.IsConstantAggregate = true;
1486     }
1487 
1488     // A normal fixed sized variable becomes an alloca in the entry block,
1489     // unless:
1490     // - it's an NRVO variable.
1491     // - we are compiling OpenMP and it's an OpenMP local variable.
1492     if (NRVO) {
1493       // The named return value optimization: allocate this variable in the
1494       // return slot, so that we can elide the copy when returning this
1495       // variable (C++0x [class.copy]p34).
1496       address = ReturnValue;
1497       AllocaAddr = ReturnValue;
1498 
1499       if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
1500         const auto *RD = RecordTy->getDecl();
1501         const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
1502         if ((CXXRD && !CXXRD->hasTrivialDestructor()) ||
1503             RD->isNonTrivialToPrimitiveDestroy()) {
1504           // Create a flag that is used to indicate when the NRVO was applied
1505           // to this variable. Set it to zero to indicate that NRVO was not
1506           // applied.
1507           llvm::Value *Zero = Builder.getFalse();
1508           Address NRVOFlag =
1509               CreateTempAlloca(Zero->getType(), CharUnits::One(), "nrvo",
1510                                /*ArraySize=*/nullptr, &AllocaAddr);
1511           EnsureInsertPoint();
1512           Builder.CreateStore(Zero, NRVOFlag);
1513 
1514           // Record the NRVO flag for this variable.
1515           NRVOFlags[&D] = NRVOFlag.getPointer();
1516           emission.NRVOFlag = NRVOFlag.getPointer();
1517         }
1518       }
1519     } else {
1520       CharUnits allocaAlignment;
1521       llvm::Type *allocaTy;
1522       if (isEscapingByRef) {
1523         auto &byrefInfo = getBlockByrefInfo(&D);
1524         allocaTy = byrefInfo.Type;
1525         allocaAlignment = byrefInfo.ByrefAlignment;
1526       } else {
1527         allocaTy = ConvertTypeForMem(Ty);
1528         allocaAlignment = alignment;
1529       }
1530 
1531       // Create the alloca.  Note that we set the name separately from
1532       // building the instruction so that it's there even in no-asserts
1533       // builds.
1534       address = CreateTempAlloca(allocaTy, allocaAlignment, D.getName(),
1535                                  /*ArraySize=*/nullptr, &AllocaAddr);
1536 
1537       // Don't emit lifetime markers for MSVC catch parameters. The lifetime of
1538       // the catch parameter starts in the catchpad instruction, and we can't
1539       // insert code in those basic blocks.
1540       bool IsMSCatchParam =
1541           D.isExceptionVariable() && getTarget().getCXXABI().isMicrosoft();
1542 
1543       // Emit a lifetime intrinsic if meaningful. There's no point in doing this
1544       // if we don't have a valid insertion point (?).
1545       if (HaveInsertPoint() && !IsMSCatchParam) {
1546         // If there's a jump into the lifetime of this variable, its lifetime
1547         // gets broken up into several regions in IR, which requires more work
1548         // to handle correctly. For now, just omit the intrinsics; this is a
1549         // rare case, and it's better to just be conservatively correct.
1550         // PR28267.
1551         //
1552         // We have to do this in all language modes if there's a jump past the
1553         // declaration. We also have to do it in C if there's a jump to an
1554         // earlier point in the current block because non-VLA lifetimes begin as
1555         // soon as the containing block is entered, not when its variables
1556         // actually come into scope; suppressing the lifetime annotations
1557         // completely in this case is unnecessarily pessimistic, but again, this
1558         // is rare.
1559         if (!Bypasses.IsBypassed(&D) &&
1560             !(!getLangOpts().CPlusPlus && hasLabelBeenSeenInCurrentScope())) {
1561           llvm::TypeSize Size = CGM.getDataLayout().getTypeAllocSize(allocaTy);
1562           emission.SizeForLifetimeMarkers =
1563               EmitLifetimeStart(Size, AllocaAddr.getPointer());
1564         }
1565       } else {
1566         assert(!emission.useLifetimeMarkers());
1567       }
1568     }
1569   } else {
1570     EnsureInsertPoint();
1571 
1572     if (!DidCallStackSave) {
1573       // Save the stack.
1574       Address Stack =
1575         CreateTempAlloca(Int8PtrTy, getPointerAlign(), "saved_stack");
1576 
1577       llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
1578       llvm::Value *V = Builder.CreateCall(F);
1579       Builder.CreateStore(V, Stack);
1580 
1581       DidCallStackSave = true;
1582 
1583       // Push a cleanup block and restore the stack there.
1584       // FIXME: in general circumstances, this should be an EH cleanup.
1585       pushStackRestore(NormalCleanup, Stack);
1586     }
1587 
1588     auto VlaSize = getVLASize(Ty);
1589     llvm::Type *llvmTy = ConvertTypeForMem(VlaSize.Type);
1590 
1591     // Allocate memory for the array.
1592     address = CreateTempAlloca(llvmTy, alignment, "vla", VlaSize.NumElts,
1593                                &AllocaAddr);
1594 
1595     // If we have debug info enabled, properly describe the VLA dimensions for
1596     // this type by registering the vla size expression for each of the
1597     // dimensions.
1598     EmitAndRegisterVariableArrayDimensions(DI, D, EmitDebugInfo);
1599   }
1600 
1601   setAddrOfLocalVar(&D, address);
1602   emission.Addr = address;
1603   emission.AllocaAddr = AllocaAddr;
1604 
1605   // Emit debug info for local var declaration.
1606   if (EmitDebugInfo && HaveInsertPoint()) {
1607     Address DebugAddr = address;
1608     bool UsePointerValue = NRVO && ReturnValuePointer.isValid();
1609     DI->setLocation(D.getLocation());
1610 
1611     // If NRVO, use a pointer to the return address.
1612     if (UsePointerValue) {
1613       DebugAddr = ReturnValuePointer;
1614       AllocaAddr = ReturnValuePointer;
1615     }
1616     (void)DI->EmitDeclareOfAutoVariable(&D, AllocaAddr.getPointer(), Builder,
1617                                         UsePointerValue);
1618   }
1619 
1620   if (D.hasAttr<AnnotateAttr>() && HaveInsertPoint())
1621     EmitVarAnnotations(&D, address.getPointer());
1622 
1623   // Make sure we call @llvm.lifetime.end.
1624   if (emission.useLifetimeMarkers())
1625     EHStack.pushCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker,
1626                                          emission.getOriginalAllocatedAddress(),
1627                                          emission.getSizeForLifetimeMarkers());
1628 
1629   return emission;
1630 }
1631 
1632 static bool isCapturedBy(const VarDecl &, const Expr *);
1633 
1634 /// Determines whether the given __block variable is potentially
1635 /// captured by the given statement.
1636 static bool isCapturedBy(const VarDecl &Var, const Stmt *S) {
1637   if (const Expr *E = dyn_cast<Expr>(S))
1638     return isCapturedBy(Var, E);
1639   for (const Stmt *SubStmt : S->children())
1640     if (isCapturedBy(Var, SubStmt))
1641       return true;
1642   return false;
1643 }
1644 
1645 /// Determines whether the given __block variable is potentially
1646 /// captured by the given expression.
1647 static bool isCapturedBy(const VarDecl &Var, const Expr *E) {
1648   // Skip the most common kinds of expressions that make
1649   // hierarchy-walking expensive.
1650   E = E->IgnoreParenCasts();
1651 
1652   if (const BlockExpr *BE = dyn_cast<BlockExpr>(E)) {
1653     const BlockDecl *Block = BE->getBlockDecl();
1654     for (const auto &I : Block->captures()) {
1655       if (I.getVariable() == &Var)
1656         return true;
1657     }
1658 
1659     // No need to walk into the subexpressions.
1660     return false;
1661   }
1662 
1663   if (const StmtExpr *SE = dyn_cast<StmtExpr>(E)) {
1664     const CompoundStmt *CS = SE->getSubStmt();
1665     for (const auto *BI : CS->body())
1666       if (const auto *BIE = dyn_cast<Expr>(BI)) {
1667         if (isCapturedBy(Var, BIE))
1668           return true;
1669       }
1670       else if (const auto *DS = dyn_cast<DeclStmt>(BI)) {
1671           // special case declarations
1672           for (const auto *I : DS->decls()) {
1673               if (const auto *VD = dyn_cast<VarDecl>((I))) {
1674                 const Expr *Init = VD->getInit();
1675                 if (Init && isCapturedBy(Var, Init))
1676                   return true;
1677               }
1678           }
1679       }
1680       else
1681         // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
1682         // Later, provide code to poke into statements for capture analysis.
1683         return true;
1684     return false;
1685   }
1686 
1687   for (const Stmt *SubStmt : E->children())
1688     if (isCapturedBy(Var, SubStmt))
1689       return true;
1690 
1691   return false;
1692 }
1693 
1694 /// Determine whether the given initializer is trivial in the sense
1695 /// that it requires no code to be generated.
1696 bool CodeGenFunction::isTrivialInitializer(const Expr *Init) {
1697   if (!Init)
1698     return true;
1699 
1700   if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
1701     if (CXXConstructorDecl *Constructor = Construct->getConstructor())
1702       if (Constructor->isTrivial() &&
1703           Constructor->isDefaultConstructor() &&
1704           !Construct->requiresZeroInitialization())
1705         return true;
1706 
1707   return false;
1708 }
1709 
1710 void CodeGenFunction::emitZeroOrPatternForAutoVarInit(QualType type,
1711                                                       const VarDecl &D,
1712                                                       Address Loc) {
1713   auto trivialAutoVarInit = getContext().getLangOpts().getTrivialAutoVarInit();
1714   CharUnits Size = getContext().getTypeSizeInChars(type);
1715   bool isVolatile = type.isVolatileQualified();
1716   if (!Size.isZero()) {
1717     switch (trivialAutoVarInit) {
1718     case LangOptions::TrivialAutoVarInitKind::Uninitialized:
1719       llvm_unreachable("Uninitialized handled by caller");
1720     case LangOptions::TrivialAutoVarInitKind::Zero:
1721       if (CGM.stopAutoInit())
1722         return;
1723       emitStoresForZeroInit(CGM, D, Loc, isVolatile, Builder);
1724       break;
1725     case LangOptions::TrivialAutoVarInitKind::Pattern:
1726       if (CGM.stopAutoInit())
1727         return;
1728       emitStoresForPatternInit(CGM, D, Loc, isVolatile, Builder);
1729       break;
1730     }
1731     return;
1732   }
1733 
1734   // VLAs look zero-sized to getTypeInfo. We can't emit constant stores to
1735   // them, so emit a memcpy with the VLA size to initialize each element.
1736   // Technically zero-sized or negative-sized VLAs are undefined, and UBSan
1737   // will catch that code, but there exists code which generates zero-sized
1738   // VLAs. Be nice and initialize whatever they requested.
1739   const auto *VlaType = getContext().getAsVariableArrayType(type);
1740   if (!VlaType)
1741     return;
1742   auto VlaSize = getVLASize(VlaType);
1743   auto SizeVal = VlaSize.NumElts;
1744   CharUnits EltSize = getContext().getTypeSizeInChars(VlaSize.Type);
1745   switch (trivialAutoVarInit) {
1746   case LangOptions::TrivialAutoVarInitKind::Uninitialized:
1747     llvm_unreachable("Uninitialized handled by caller");
1748 
1749   case LangOptions::TrivialAutoVarInitKind::Zero: {
1750     if (CGM.stopAutoInit())
1751       return;
1752     if (!EltSize.isOne())
1753       SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(EltSize));
1754     auto *I = Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0),
1755                                    SizeVal, isVolatile);
1756     I->addAnnotationMetadata("auto-init");
1757     break;
1758   }
1759 
1760   case LangOptions::TrivialAutoVarInitKind::Pattern: {
1761     if (CGM.stopAutoInit())
1762       return;
1763     llvm::Type *ElTy = Loc.getElementType();
1764     llvm::Constant *Constant = constWithPadding(
1765         CGM, IsPattern::Yes, initializationPatternFor(CGM, ElTy));
1766     CharUnits ConstantAlign = getContext().getTypeAlignInChars(VlaSize.Type);
1767     llvm::BasicBlock *SetupBB = createBasicBlock("vla-setup.loop");
1768     llvm::BasicBlock *LoopBB = createBasicBlock("vla-init.loop");
1769     llvm::BasicBlock *ContBB = createBasicBlock("vla-init.cont");
1770     llvm::Value *IsZeroSizedVLA = Builder.CreateICmpEQ(
1771         SizeVal, llvm::ConstantInt::get(SizeVal->getType(), 0),
1772         "vla.iszerosized");
1773     Builder.CreateCondBr(IsZeroSizedVLA, ContBB, SetupBB);
1774     EmitBlock(SetupBB);
1775     if (!EltSize.isOne())
1776       SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(EltSize));
1777     llvm::Value *BaseSizeInChars =
1778         llvm::ConstantInt::get(IntPtrTy, EltSize.getQuantity());
1779     Address Begin = Builder.CreateElementBitCast(Loc, Int8Ty, "vla.begin");
1780     llvm::Value *End = Builder.CreateInBoundsGEP(
1781         Begin.getElementType(), Begin.getPointer(), SizeVal, "vla.end");
1782     llvm::BasicBlock *OriginBB = Builder.GetInsertBlock();
1783     EmitBlock(LoopBB);
1784     llvm::PHINode *Cur = Builder.CreatePHI(Begin.getType(), 2, "vla.cur");
1785     Cur->addIncoming(Begin.getPointer(), OriginBB);
1786     CharUnits CurAlign = Loc.getAlignment().alignmentOfArrayElement(EltSize);
1787     auto *I =
1788         Builder.CreateMemCpy(Address(Cur, CurAlign),
1789                              createUnnamedGlobalForMemcpyFrom(
1790                                  CGM, D, Builder, Constant, ConstantAlign),
1791                              BaseSizeInChars, isVolatile);
1792     I->addAnnotationMetadata("auto-init");
1793     llvm::Value *Next =
1794         Builder.CreateInBoundsGEP(Int8Ty, Cur, BaseSizeInChars, "vla.next");
1795     llvm::Value *Done = Builder.CreateICmpEQ(Next, End, "vla-init.isdone");
1796     Builder.CreateCondBr(Done, ContBB, LoopBB);
1797     Cur->addIncoming(Next, LoopBB);
1798     EmitBlock(ContBB);
1799   } break;
1800   }
1801 }
1802 
1803 void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
1804   assert(emission.Variable && "emission was not valid!");
1805 
1806   // If this was emitted as a global constant, we're done.
1807   if (emission.wasEmittedAsGlobal()) return;
1808 
1809   const VarDecl &D = *emission.Variable;
1810   auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, D.getLocation());
1811   QualType type = D.getType();
1812 
1813   // If this local has an initializer, emit it now.
1814   const Expr *Init = D.getInit();
1815 
1816   // If we are at an unreachable point, we don't need to emit the initializer
1817   // unless it contains a label.
1818   if (!HaveInsertPoint()) {
1819     if (!Init || !ContainsLabel(Init)) return;
1820     EnsureInsertPoint();
1821   }
1822 
1823   // Initialize the structure of a __block variable.
1824   if (emission.IsEscapingByRef)
1825     emitByrefStructureInit(emission);
1826 
1827   // Initialize the variable here if it doesn't have a initializer and it is a
1828   // C struct that is non-trivial to initialize or an array containing such a
1829   // struct.
1830   if (!Init &&
1831       type.isNonTrivialToPrimitiveDefaultInitialize() ==
1832           QualType::PDIK_Struct) {
1833     LValue Dst = MakeAddrLValue(emission.getAllocatedAddress(), type);
1834     if (emission.IsEscapingByRef)
1835       drillIntoBlockVariable(*this, Dst, &D);
1836     defaultInitNonTrivialCStructVar(Dst);
1837     return;
1838   }
1839 
1840   // Check whether this is a byref variable that's potentially
1841   // captured and moved by its own initializer.  If so, we'll need to
1842   // emit the initializer first, then copy into the variable.
1843   bool capturedByInit =
1844       Init && emission.IsEscapingByRef && isCapturedBy(D, Init);
1845 
1846   bool locIsByrefHeader = !capturedByInit;
1847   const Address Loc =
1848       locIsByrefHeader ? emission.getObjectAddress(*this) : emission.Addr;
1849 
1850   // Note: constexpr already initializes everything correctly.
1851   LangOptions::TrivialAutoVarInitKind trivialAutoVarInit =
1852       (D.isConstexpr()
1853            ? LangOptions::TrivialAutoVarInitKind::Uninitialized
1854            : (D.getAttr<UninitializedAttr>()
1855                   ? LangOptions::TrivialAutoVarInitKind::Uninitialized
1856                   : getContext().getLangOpts().getTrivialAutoVarInit()));
1857 
1858   auto initializeWhatIsTechnicallyUninitialized = [&](Address Loc) {
1859     if (trivialAutoVarInit ==
1860         LangOptions::TrivialAutoVarInitKind::Uninitialized)
1861       return;
1862 
1863     // Only initialize a __block's storage: we always initialize the header.
1864     if (emission.IsEscapingByRef && !locIsByrefHeader)
1865       Loc = emitBlockByrefAddress(Loc, &D, /*follow=*/false);
1866 
1867     return emitZeroOrPatternForAutoVarInit(type, D, Loc);
1868   };
1869 
1870   if (isTrivialInitializer(Init))
1871     return initializeWhatIsTechnicallyUninitialized(Loc);
1872 
1873   llvm::Constant *constant = nullptr;
1874   if (emission.IsConstantAggregate ||
1875       D.mightBeUsableInConstantExpressions(getContext())) {
1876     assert(!capturedByInit && "constant init contains a capturing block?");
1877     constant = ConstantEmitter(*this).tryEmitAbstractForInitializer(D);
1878     if (constant && !constant->isZeroValue() &&
1879         (trivialAutoVarInit !=
1880          LangOptions::TrivialAutoVarInitKind::Uninitialized)) {
1881       IsPattern isPattern =
1882           (trivialAutoVarInit == LangOptions::TrivialAutoVarInitKind::Pattern)
1883               ? IsPattern::Yes
1884               : IsPattern::No;
1885       // C guarantees that brace-init with fewer initializers than members in
1886       // the aggregate will initialize the rest of the aggregate as-if it were
1887       // static initialization. In turn static initialization guarantees that
1888       // padding is initialized to zero bits. We could instead pattern-init if D
1889       // has any ImplicitValueInitExpr, but that seems to be unintuitive
1890       // behavior.
1891       constant = constWithPadding(CGM, IsPattern::No,
1892                                   replaceUndef(CGM, isPattern, constant));
1893     }
1894   }
1895 
1896   if (!constant) {
1897     initializeWhatIsTechnicallyUninitialized(Loc);
1898     LValue lv = MakeAddrLValue(Loc, type);
1899     lv.setNonGC(true);
1900     return EmitExprAsInit(Init, &D, lv, capturedByInit);
1901   }
1902 
1903   if (!emission.IsConstantAggregate) {
1904     // For simple scalar/complex initialization, store the value directly.
1905     LValue lv = MakeAddrLValue(Loc, type);
1906     lv.setNonGC(true);
1907     return EmitStoreThroughLValue(RValue::get(constant), lv, true);
1908   }
1909 
1910   llvm::Type *BP = CGM.Int8Ty->getPointerTo(Loc.getAddressSpace());
1911   emitStoresForConstant(
1912       CGM, D, (Loc.getType() == BP) ? Loc : Builder.CreateBitCast(Loc, BP),
1913       type.isVolatileQualified(), Builder, constant, /*IsAutoInit=*/false);
1914 }
1915 
1916 /// Emit an expression as an initializer for an object (variable, field, etc.)
1917 /// at the given location.  The expression is not necessarily the normal
1918 /// initializer for the object, and the address is not necessarily
1919 /// its normal location.
1920 ///
1921 /// \param init the initializing expression
1922 /// \param D the object to act as if we're initializing
1923 /// \param lvalue the lvalue to initialize
1924 /// \param capturedByInit true if \p D is a __block variable
1925 ///   whose address is potentially changed by the initializer
1926 void CodeGenFunction::EmitExprAsInit(const Expr *init, const ValueDecl *D,
1927                                      LValue lvalue, bool capturedByInit) {
1928   QualType type = D->getType();
1929 
1930   if (type->isReferenceType()) {
1931     RValue rvalue = EmitReferenceBindingToExpr(init);
1932     if (capturedByInit)
1933       drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
1934     EmitStoreThroughLValue(rvalue, lvalue, true);
1935     return;
1936   }
1937   switch (getEvaluationKind(type)) {
1938   case TEK_Scalar:
1939     EmitScalarInit(init, D, lvalue, capturedByInit);
1940     return;
1941   case TEK_Complex: {
1942     ComplexPairTy complex = EmitComplexExpr(init);
1943     if (capturedByInit)
1944       drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
1945     EmitStoreOfComplex(complex, lvalue, /*init*/ true);
1946     return;
1947   }
1948   case TEK_Aggregate:
1949     if (type->isAtomicType()) {
1950       EmitAtomicInit(const_cast<Expr*>(init), lvalue);
1951     } else {
1952       AggValueSlot::Overlap_t Overlap = AggValueSlot::MayOverlap;
1953       if (isa<VarDecl>(D))
1954         Overlap = AggValueSlot::DoesNotOverlap;
1955       else if (auto *FD = dyn_cast<FieldDecl>(D))
1956         Overlap = getOverlapForFieldInit(FD);
1957       // TODO: how can we delay here if D is captured by its initializer?
1958       EmitAggExpr(init, AggValueSlot::forLValue(
1959                             lvalue, *this, AggValueSlot::IsDestructed,
1960                             AggValueSlot::DoesNotNeedGCBarriers,
1961                             AggValueSlot::IsNotAliased, Overlap));
1962     }
1963     return;
1964   }
1965   llvm_unreachable("bad evaluation kind");
1966 }
1967 
1968 /// Enter a destroy cleanup for the given local variable.
1969 void CodeGenFunction::emitAutoVarTypeCleanup(
1970                             const CodeGenFunction::AutoVarEmission &emission,
1971                             QualType::DestructionKind dtorKind) {
1972   assert(dtorKind != QualType::DK_none);
1973 
1974   // Note that for __block variables, we want to destroy the
1975   // original stack object, not the possibly forwarded object.
1976   Address addr = emission.getObjectAddress(*this);
1977 
1978   const VarDecl *var = emission.Variable;
1979   QualType type = var->getType();
1980 
1981   CleanupKind cleanupKind = NormalAndEHCleanup;
1982   CodeGenFunction::Destroyer *destroyer = nullptr;
1983 
1984   switch (dtorKind) {
1985   case QualType::DK_none:
1986     llvm_unreachable("no cleanup for trivially-destructible variable");
1987 
1988   case QualType::DK_cxx_destructor:
1989     // If there's an NRVO flag on the emission, we need a different
1990     // cleanup.
1991     if (emission.NRVOFlag) {
1992       assert(!type->isArrayType());
1993       CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
1994       EHStack.pushCleanup<DestroyNRVOVariableCXX>(cleanupKind, addr, type, dtor,
1995                                                   emission.NRVOFlag);
1996       return;
1997     }
1998     break;
1999 
2000   case QualType::DK_objc_strong_lifetime:
2001     // Suppress cleanups for pseudo-strong variables.
2002     if (var->isARCPseudoStrong()) return;
2003 
2004     // Otherwise, consider whether to use an EH cleanup or not.
2005     cleanupKind = getARCCleanupKind();
2006 
2007     // Use the imprecise destroyer by default.
2008     if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
2009       destroyer = CodeGenFunction::destroyARCStrongImprecise;
2010     break;
2011 
2012   case QualType::DK_objc_weak_lifetime:
2013     break;
2014 
2015   case QualType::DK_nontrivial_c_struct:
2016     destroyer = CodeGenFunction::destroyNonTrivialCStruct;
2017     if (emission.NRVOFlag) {
2018       assert(!type->isArrayType());
2019       EHStack.pushCleanup<DestroyNRVOVariableC>(cleanupKind, addr,
2020                                                 emission.NRVOFlag, type);
2021       return;
2022     }
2023     break;
2024   }
2025 
2026   // If we haven't chosen a more specific destroyer, use the default.
2027   if (!destroyer) destroyer = getDestroyer(dtorKind);
2028 
2029   // Use an EH cleanup in array destructors iff the destructor itself
2030   // is being pushed as an EH cleanup.
2031   bool useEHCleanup = (cleanupKind & EHCleanup);
2032   EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
2033                                      useEHCleanup);
2034 }
2035 
2036 void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
2037   assert(emission.Variable && "emission was not valid!");
2038 
2039   // If this was emitted as a global constant, we're done.
2040   if (emission.wasEmittedAsGlobal()) return;
2041 
2042   // If we don't have an insertion point, we're done.  Sema prevents
2043   // us from jumping into any of these scopes anyway.
2044   if (!HaveInsertPoint()) return;
2045 
2046   const VarDecl &D = *emission.Variable;
2047 
2048   // Check the type for a cleanup.
2049   if (QualType::DestructionKind dtorKind = D.needsDestruction(getContext()))
2050     emitAutoVarTypeCleanup(emission, dtorKind);
2051 
2052   // In GC mode, honor objc_precise_lifetime.
2053   if (getLangOpts().getGC() != LangOptions::NonGC &&
2054       D.hasAttr<ObjCPreciseLifetimeAttr>()) {
2055     EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
2056   }
2057 
2058   // Handle the cleanup attribute.
2059   if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
2060     const FunctionDecl *FD = CA->getFunctionDecl();
2061 
2062     llvm::Constant *F = CGM.GetAddrOfFunction(FD);
2063     assert(F && "Could not find function!");
2064 
2065     const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
2066     EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
2067   }
2068 
2069   // If this is a block variable, call _Block_object_destroy
2070   // (on the unforwarded address). Don't enter this cleanup if we're in pure-GC
2071   // mode.
2072   if (emission.IsEscapingByRef &&
2073       CGM.getLangOpts().getGC() != LangOptions::GCOnly) {
2074     BlockFieldFlags Flags = BLOCK_FIELD_IS_BYREF;
2075     if (emission.Variable->getType().isObjCGCWeak())
2076       Flags |= BLOCK_FIELD_IS_WEAK;
2077     enterByrefCleanup(NormalAndEHCleanup, emission.Addr, Flags,
2078                       /*LoadBlockVarAddr*/ false,
2079                       cxxDestructorCanThrow(emission.Variable->getType()));
2080   }
2081 }
2082 
2083 CodeGenFunction::Destroyer *
2084 CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
2085   switch (kind) {
2086   case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
2087   case QualType::DK_cxx_destructor:
2088     return destroyCXXObject;
2089   case QualType::DK_objc_strong_lifetime:
2090     return destroyARCStrongPrecise;
2091   case QualType::DK_objc_weak_lifetime:
2092     return destroyARCWeak;
2093   case QualType::DK_nontrivial_c_struct:
2094     return destroyNonTrivialCStruct;
2095   }
2096   llvm_unreachable("Unknown DestructionKind");
2097 }
2098 
2099 /// pushEHDestroy - Push the standard destructor for the given type as
2100 /// an EH-only cleanup.
2101 void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind,
2102                                     Address addr, QualType type) {
2103   assert(dtorKind && "cannot push destructor for trivial type");
2104   assert(needsEHCleanup(dtorKind));
2105 
2106   pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true);
2107 }
2108 
2109 /// pushDestroy - Push the standard destructor for the given type as
2110 /// at least a normal cleanup.
2111 void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
2112                                   Address addr, QualType type) {
2113   assert(dtorKind && "cannot push destructor for trivial type");
2114 
2115   CleanupKind cleanupKind = getCleanupKind(dtorKind);
2116   pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
2117               cleanupKind & EHCleanup);
2118 }
2119 
2120 void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, Address addr,
2121                                   QualType type, Destroyer *destroyer,
2122                                   bool useEHCleanupForArray) {
2123   pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
2124                                      destroyer, useEHCleanupForArray);
2125 }
2126 
2127 void CodeGenFunction::pushStackRestore(CleanupKind Kind, Address SPMem) {
2128   EHStack.pushCleanup<CallStackRestore>(Kind, SPMem);
2129 }
2130 
2131 void CodeGenFunction::pushLifetimeExtendedDestroy(CleanupKind cleanupKind,
2132                                                   Address addr, QualType type,
2133                                                   Destroyer *destroyer,
2134                                                   bool useEHCleanupForArray) {
2135   // If we're not in a conditional branch, we don't need to bother generating a
2136   // conditional cleanup.
2137   if (!isInConditionalBranch()) {
2138     // Push an EH-only cleanup for the object now.
2139     // FIXME: When popping normal cleanups, we need to keep this EH cleanup
2140     // around in case a temporary's destructor throws an exception.
2141     if (cleanupKind & EHCleanup)
2142       EHStack.pushCleanup<DestroyObject>(
2143           static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type,
2144           destroyer, useEHCleanupForArray);
2145 
2146     return pushCleanupAfterFullExprWithActiveFlag<DestroyObject>(
2147         cleanupKind, Address::invalid(), addr, type, destroyer, useEHCleanupForArray);
2148   }
2149 
2150   // Otherwise, we should only destroy the object if it's been initialized.
2151   // Re-use the active flag and saved address across both the EH and end of
2152   // scope cleanups.
2153 
2154   using SavedType = typename DominatingValue<Address>::saved_type;
2155   using ConditionalCleanupType =
2156       EHScopeStack::ConditionalCleanup<DestroyObject, Address, QualType,
2157                                        Destroyer *, bool>;
2158 
2159   Address ActiveFlag = createCleanupActiveFlag();
2160   SavedType SavedAddr = saveValueInCond(addr);
2161 
2162   if (cleanupKind & EHCleanup) {
2163     EHStack.pushCleanup<ConditionalCleanupType>(
2164         static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), SavedAddr, type,
2165         destroyer, useEHCleanupForArray);
2166     initFullExprCleanupWithFlag(ActiveFlag);
2167   }
2168 
2169   pushCleanupAfterFullExprWithActiveFlag<ConditionalCleanupType>(
2170       cleanupKind, ActiveFlag, SavedAddr, type, destroyer,
2171       useEHCleanupForArray);
2172 }
2173 
2174 /// emitDestroy - Immediately perform the destruction of the given
2175 /// object.
2176 ///
2177 /// \param addr - the address of the object; a type*
2178 /// \param type - the type of the object; if an array type, all
2179 ///   objects are destroyed in reverse order
2180 /// \param destroyer - the function to call to destroy individual
2181 ///   elements
2182 /// \param useEHCleanupForArray - whether an EH cleanup should be
2183 ///   used when destroying array elements, in case one of the
2184 ///   destructions throws an exception
2185 void CodeGenFunction::emitDestroy(Address addr, QualType type,
2186                                   Destroyer *destroyer,
2187                                   bool useEHCleanupForArray) {
2188   const ArrayType *arrayType = getContext().getAsArrayType(type);
2189   if (!arrayType)
2190     return destroyer(*this, addr, type);
2191 
2192   llvm::Value *length = emitArrayLength(arrayType, type, addr);
2193 
2194   CharUnits elementAlign =
2195     addr.getAlignment()
2196         .alignmentOfArrayElement(getContext().getTypeSizeInChars(type));
2197 
2198   // Normally we have to check whether the array is zero-length.
2199   bool checkZeroLength = true;
2200 
2201   // But if the array length is constant, we can suppress that.
2202   if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
2203     // ...and if it's constant zero, we can just skip the entire thing.
2204     if (constLength->isZero()) return;
2205     checkZeroLength = false;
2206   }
2207 
2208   llvm::Value *begin = addr.getPointer();
2209   llvm::Value *end =
2210       Builder.CreateInBoundsGEP(addr.getElementType(), begin, length);
2211   emitArrayDestroy(begin, end, type, elementAlign, destroyer,
2212                    checkZeroLength, useEHCleanupForArray);
2213 }
2214 
2215 /// emitArrayDestroy - Destroys all the elements of the given array,
2216 /// beginning from last to first.  The array cannot be zero-length.
2217 ///
2218 /// \param begin - a type* denoting the first element of the array
2219 /// \param end - a type* denoting one past the end of the array
2220 /// \param elementType - the element type of the array
2221 /// \param destroyer - the function to call to destroy elements
2222 /// \param useEHCleanup - whether to push an EH cleanup to destroy
2223 ///   the remaining elements in case the destruction of a single
2224 ///   element throws
2225 void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
2226                                        llvm::Value *end,
2227                                        QualType elementType,
2228                                        CharUnits elementAlign,
2229                                        Destroyer *destroyer,
2230                                        bool checkZeroLength,
2231                                        bool useEHCleanup) {
2232   assert(!elementType->isArrayType());
2233 
2234   // The basic structure here is a do-while loop, because we don't
2235   // need to check for the zero-element case.
2236   llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
2237   llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
2238 
2239   if (checkZeroLength) {
2240     llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
2241                                                 "arraydestroy.isempty");
2242     Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
2243   }
2244 
2245   // Enter the loop body, making that address the current address.
2246   llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
2247   EmitBlock(bodyBB);
2248   llvm::PHINode *elementPast =
2249     Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
2250   elementPast->addIncoming(end, entryBB);
2251 
2252   // Shift the address back by one element.
2253   llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
2254   llvm::Value *element = Builder.CreateInBoundsGEP(
2255       elementPast->getType()->getPointerElementType(), elementPast, negativeOne,
2256       "arraydestroy.element");
2257 
2258   if (useEHCleanup)
2259     pushRegularPartialArrayCleanup(begin, element, elementType, elementAlign,
2260                                    destroyer);
2261 
2262   // Perform the actual destruction there.
2263   destroyer(*this, Address(element, elementAlign), elementType);
2264 
2265   if (useEHCleanup)
2266     PopCleanupBlock();
2267 
2268   // Check whether we've reached the end.
2269   llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
2270   Builder.CreateCondBr(done, doneBB, bodyBB);
2271   elementPast->addIncoming(element, Builder.GetInsertBlock());
2272 
2273   // Done.
2274   EmitBlock(doneBB);
2275 }
2276 
2277 /// Perform partial array destruction as if in an EH cleanup.  Unlike
2278 /// emitArrayDestroy, the element type here may still be an array type.
2279 static void emitPartialArrayDestroy(CodeGenFunction &CGF,
2280                                     llvm::Value *begin, llvm::Value *end,
2281                                     QualType type, CharUnits elementAlign,
2282                                     CodeGenFunction::Destroyer *destroyer) {
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     llvm::Type *elemTy = begin->getType()->getPointerElementType();
2297     begin = CGF.Builder.CreateInBoundsGEP(
2298         elemTy, begin, gepIndices, "pad.arraybegin");
2299     end = CGF.Builder.CreateInBoundsGEP(
2300         elemTy, end, gepIndices, "pad.arrayend");
2301   }
2302 
2303   // Destroy the array.  We don't ever need an EH cleanup because we
2304   // assume that we're in an EH cleanup ourselves, so a throwing
2305   // destructor causes an immediate terminate.
2306   CGF.emitArrayDestroy(begin, end, type, elementAlign, destroyer,
2307                        /*checkZeroLength*/ true, /*useEHCleanup*/ false);
2308 }
2309 
2310 namespace {
2311   /// RegularPartialArrayDestroy - a cleanup which performs a partial
2312   /// array destroy where the end pointer is regularly determined and
2313   /// does not need to be loaded from a local.
2314   class RegularPartialArrayDestroy final : public EHScopeStack::Cleanup {
2315     llvm::Value *ArrayBegin;
2316     llvm::Value *ArrayEnd;
2317     QualType ElementType;
2318     CodeGenFunction::Destroyer *Destroyer;
2319     CharUnits ElementAlign;
2320   public:
2321     RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
2322                                QualType elementType, CharUnits elementAlign,
2323                                CodeGenFunction::Destroyer *destroyer)
2324       : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
2325         ElementType(elementType), Destroyer(destroyer),
2326         ElementAlign(elementAlign) {}
2327 
2328     void Emit(CodeGenFunction &CGF, Flags flags) override {
2329       emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
2330                               ElementType, ElementAlign, Destroyer);
2331     }
2332   };
2333 
2334   /// IrregularPartialArrayDestroy - a cleanup which performs a
2335   /// partial array destroy where the end pointer is irregularly
2336   /// determined and must be loaded from a local.
2337   class IrregularPartialArrayDestroy final : public EHScopeStack::Cleanup {
2338     llvm::Value *ArrayBegin;
2339     Address ArrayEndPointer;
2340     QualType ElementType;
2341     CodeGenFunction::Destroyer *Destroyer;
2342     CharUnits ElementAlign;
2343   public:
2344     IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
2345                                  Address arrayEndPointer,
2346                                  QualType elementType,
2347                                  CharUnits elementAlign,
2348                                  CodeGenFunction::Destroyer *destroyer)
2349       : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
2350         ElementType(elementType), Destroyer(destroyer),
2351         ElementAlign(elementAlign) {}
2352 
2353     void Emit(CodeGenFunction &CGF, Flags flags) override {
2354       llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
2355       emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
2356                               ElementType, ElementAlign, Destroyer);
2357     }
2358   };
2359 } // end anonymous namespace
2360 
2361 /// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
2362 /// already-constructed elements of the given array.  The cleanup
2363 /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
2364 ///
2365 /// \param elementType - the immediate element type of the array;
2366 ///   possibly still an array type
2367 void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
2368                                                        Address arrayEndPointer,
2369                                                        QualType elementType,
2370                                                        CharUnits elementAlign,
2371                                                        Destroyer *destroyer) {
2372   pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
2373                                                     arrayBegin, arrayEndPointer,
2374                                                     elementType, elementAlign,
2375                                                     destroyer);
2376 }
2377 
2378 /// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
2379 /// already-constructed elements of the given array.  The cleanup
2380 /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
2381 ///
2382 /// \param elementType - the immediate element type of the array;
2383 ///   possibly still an array type
2384 void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
2385                                                      llvm::Value *arrayEnd,
2386                                                      QualType elementType,
2387                                                      CharUnits elementAlign,
2388                                                      Destroyer *destroyer) {
2389   pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
2390                                                   arrayBegin, arrayEnd,
2391                                                   elementType, elementAlign,
2392                                                   destroyer);
2393 }
2394 
2395 /// Lazily declare the @llvm.lifetime.start intrinsic.
2396 llvm::Function *CodeGenModule::getLLVMLifetimeStartFn() {
2397   if (LifetimeStartFn)
2398     return LifetimeStartFn;
2399   LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(),
2400     llvm::Intrinsic::lifetime_start, AllocaInt8PtrTy);
2401   return LifetimeStartFn;
2402 }
2403 
2404 /// Lazily declare the @llvm.lifetime.end intrinsic.
2405 llvm::Function *CodeGenModule::getLLVMLifetimeEndFn() {
2406   if (LifetimeEndFn)
2407     return LifetimeEndFn;
2408   LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(),
2409     llvm::Intrinsic::lifetime_end, AllocaInt8PtrTy);
2410   return LifetimeEndFn;
2411 }
2412 
2413 namespace {
2414   /// A cleanup to perform a release of an object at the end of a
2415   /// function.  This is used to balance out the incoming +1 of a
2416   /// ns_consumed argument when we can't reasonably do that just by
2417   /// not doing the initial retain for a __block argument.
2418   struct ConsumeARCParameter final : EHScopeStack::Cleanup {
2419     ConsumeARCParameter(llvm::Value *param,
2420                         ARCPreciseLifetime_t precise)
2421       : Param(param), Precise(precise) {}
2422 
2423     llvm::Value *Param;
2424     ARCPreciseLifetime_t Precise;
2425 
2426     void Emit(CodeGenFunction &CGF, Flags flags) override {
2427       CGF.EmitARCRelease(Param, Precise);
2428     }
2429   };
2430 } // end anonymous namespace
2431 
2432 /// Emit an alloca (or GlobalValue depending on target)
2433 /// for the specified parameter and set up LocalDeclMap.
2434 void CodeGenFunction::EmitParmDecl(const VarDecl &D, ParamValue Arg,
2435                                    unsigned ArgNo) {
2436   // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
2437   assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
2438          "Invalid argument to EmitParmDecl");
2439 
2440   Arg.getAnyValue()->setName(D.getName());
2441 
2442   QualType Ty = D.getType();
2443 
2444   // Use better IR generation for certain implicit parameters.
2445   if (auto IPD = dyn_cast<ImplicitParamDecl>(&D)) {
2446     // The only implicit argument a block has is its literal.
2447     // This may be passed as an inalloca'ed value on Windows x86.
2448     if (BlockInfo) {
2449       llvm::Value *V = Arg.isIndirect()
2450                            ? Builder.CreateLoad(Arg.getIndirectAddress())
2451                            : Arg.getDirectValue();
2452       setBlockContextParameter(IPD, ArgNo, V);
2453       return;
2454     }
2455   }
2456 
2457   Address DeclPtr = Address::invalid();
2458   Address AllocaPtr = Address::invalid();
2459   bool DoStore = false;
2460   bool IsScalar = hasScalarEvaluationKind(Ty);
2461   // If we already have a pointer to the argument, reuse the input pointer.
2462   if (Arg.isIndirect()) {
2463     DeclPtr = Arg.getIndirectAddress();
2464     // If we have a prettier pointer type at this point, bitcast to that.
2465     unsigned AS = DeclPtr.getType()->getAddressSpace();
2466     llvm::Type *IRTy = ConvertTypeForMem(Ty)->getPointerTo(AS);
2467     if (DeclPtr.getType() != IRTy)
2468       DeclPtr = Builder.CreateBitCast(DeclPtr, IRTy, D.getName());
2469     // Indirect argument is in alloca address space, which may be different
2470     // from the default address space.
2471     auto AllocaAS = CGM.getASTAllocaAddressSpace();
2472     auto *V = DeclPtr.getPointer();
2473     AllocaPtr = DeclPtr;
2474     auto SrcLangAS = getLangOpts().OpenCL ? LangAS::opencl_private : AllocaAS;
2475     auto DestLangAS =
2476         getLangOpts().OpenCL ? LangAS::opencl_private : LangAS::Default;
2477     if (SrcLangAS != DestLangAS) {
2478       assert(getContext().getTargetAddressSpace(SrcLangAS) ==
2479              CGM.getDataLayout().getAllocaAddrSpace());
2480       auto DestAS = getContext().getTargetAddressSpace(DestLangAS);
2481       auto *T = V->getType()->getPointerElementType()->getPointerTo(DestAS);
2482       DeclPtr = Address(getTargetHooks().performAddrSpaceCast(
2483                             *this, V, SrcLangAS, DestLangAS, T, true),
2484                         DeclPtr.getAlignment());
2485     }
2486 
2487     // Push a destructor cleanup for this parameter if the ABI requires it.
2488     // Don't push a cleanup in a thunk for a method that will also emit a
2489     // cleanup.
2490     if (Ty->isRecordType() && !CurFuncIsThunk &&
2491         Ty->castAs<RecordType>()->getDecl()->isParamDestroyedInCallee()) {
2492       if (QualType::DestructionKind DtorKind =
2493               D.needsDestruction(getContext())) {
2494         assert((DtorKind == QualType::DK_cxx_destructor ||
2495                 DtorKind == QualType::DK_nontrivial_c_struct) &&
2496                "unexpected destructor type");
2497         pushDestroy(DtorKind, DeclPtr, Ty);
2498         CalleeDestructedParamCleanups[cast<ParmVarDecl>(&D)] =
2499             EHStack.stable_begin();
2500       }
2501     }
2502   } else {
2503     // Check if the parameter address is controlled by OpenMP runtime.
2504     Address OpenMPLocalAddr =
2505         getLangOpts().OpenMP
2506             ? CGM.getOpenMPRuntime().getAddressOfLocalVariable(*this, &D)
2507             : Address::invalid();
2508     if (getLangOpts().OpenMP && OpenMPLocalAddr.isValid()) {
2509       DeclPtr = OpenMPLocalAddr;
2510       AllocaPtr = DeclPtr;
2511     } else {
2512       // Otherwise, create a temporary to hold the value.
2513       DeclPtr = CreateMemTemp(Ty, getContext().getDeclAlign(&D),
2514                               D.getName() + ".addr", &AllocaPtr);
2515     }
2516     DoStore = true;
2517   }
2518 
2519   llvm::Value *ArgVal = (DoStore ? Arg.getDirectValue() : nullptr);
2520 
2521   LValue lv = MakeAddrLValue(DeclPtr, Ty);
2522   if (IsScalar) {
2523     Qualifiers qs = Ty.getQualifiers();
2524     if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
2525       // We honor __attribute__((ns_consumed)) for types with lifetime.
2526       // For __strong, it's handled by just skipping the initial retain;
2527       // otherwise we have to balance out the initial +1 with an extra
2528       // cleanup to do the release at the end of the function.
2529       bool isConsumed = D.hasAttr<NSConsumedAttr>();
2530 
2531       // If a parameter is pseudo-strong then we can omit the implicit retain.
2532       if (D.isARCPseudoStrong()) {
2533         assert(lt == Qualifiers::OCL_Strong &&
2534                "pseudo-strong variable isn't strong?");
2535         assert(qs.hasConst() && "pseudo-strong variable should be const!");
2536         lt = Qualifiers::OCL_ExplicitNone;
2537       }
2538 
2539       // Load objects passed indirectly.
2540       if (Arg.isIndirect() && !ArgVal)
2541         ArgVal = Builder.CreateLoad(DeclPtr);
2542 
2543       if (lt == Qualifiers::OCL_Strong) {
2544         if (!isConsumed) {
2545           if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
2546             // use objc_storeStrong(&dest, value) for retaining the
2547             // object. But first, store a null into 'dest' because
2548             // objc_storeStrong attempts to release its old value.
2549             llvm::Value *Null = CGM.EmitNullConstant(D.getType());
2550             EmitStoreOfScalar(Null, lv, /* isInitialization */ true);
2551             EmitARCStoreStrongCall(lv.getAddress(*this), ArgVal, true);
2552             DoStore = false;
2553           }
2554           else
2555           // Don't use objc_retainBlock for block pointers, because we
2556           // don't want to Block_copy something just because we got it
2557           // as a parameter.
2558             ArgVal = EmitARCRetainNonBlock(ArgVal);
2559         }
2560       } else {
2561         // Push the cleanup for a consumed parameter.
2562         if (isConsumed) {
2563           ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
2564                                 ? ARCPreciseLifetime : ARCImpreciseLifetime);
2565           EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), ArgVal,
2566                                                    precise);
2567         }
2568 
2569         if (lt == Qualifiers::OCL_Weak) {
2570           EmitARCInitWeak(DeclPtr, ArgVal);
2571           DoStore = false; // The weak init is a store, no need to do two.
2572         }
2573       }
2574 
2575       // Enter the cleanup scope.
2576       EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
2577     }
2578   }
2579 
2580   // Store the initial value into the alloca.
2581   if (DoStore)
2582     EmitStoreOfScalar(ArgVal, lv, /* isInitialization */ true);
2583 
2584   setAddrOfLocalVar(&D, DeclPtr);
2585 
2586   // Emit debug info for param declarations in non-thunk functions.
2587   if (CGDebugInfo *DI = getDebugInfo()) {
2588     if (CGM.getCodeGenOpts().hasReducedDebugInfo() && !CurFuncIsThunk) {
2589       llvm::DILocalVariable *DILocalVar = DI->EmitDeclareOfArgVariable(
2590           &D, AllocaPtr.getPointer(), ArgNo, Builder);
2591       if (const auto *Var = dyn_cast_or_null<ParmVarDecl>(&D))
2592         DI->getParamDbgMappings().insert({Var, DILocalVar});
2593     }
2594   }
2595 
2596   if (D.hasAttr<AnnotateAttr>())
2597     EmitVarAnnotations(&D, DeclPtr.getPointer());
2598 
2599   // We can only check return value nullability if all arguments to the
2600   // function satisfy their nullability preconditions. This makes it necessary
2601   // to emit null checks for args in the function body itself.
2602   if (requiresReturnValueNullabilityCheck()) {
2603     auto Nullability = Ty->getNullability(getContext());
2604     if (Nullability && *Nullability == NullabilityKind::NonNull) {
2605       SanitizerScope SanScope(this);
2606       RetValNullabilityPrecondition =
2607           Builder.CreateAnd(RetValNullabilityPrecondition,
2608                             Builder.CreateIsNotNull(Arg.getAnyValue()));
2609     }
2610   }
2611 }
2612 
2613 void CodeGenModule::EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D,
2614                                             CodeGenFunction *CGF) {
2615   if (!LangOpts.OpenMP || (!LangOpts.EmitAllDecls && !D->isUsed()))
2616     return;
2617   getOpenMPRuntime().emitUserDefinedReduction(CGF, D);
2618 }
2619 
2620 void CodeGenModule::EmitOMPDeclareMapper(const OMPDeclareMapperDecl *D,
2621                                          CodeGenFunction *CGF) {
2622   if (!LangOpts.OpenMP || LangOpts.OpenMPSimd ||
2623       (!LangOpts.EmitAllDecls && !D->isUsed()))
2624     return;
2625   getOpenMPRuntime().emitUserDefinedMapper(D, CGF);
2626 }
2627 
2628 void CodeGenModule::EmitOMPRequiresDecl(const OMPRequiresDecl *D) {
2629   getOpenMPRuntime().processRequiresDirective(D);
2630 }
2631 
2632 void CodeGenModule::EmitOMPAllocateDecl(const OMPAllocateDecl *D) {
2633   for (const Expr *E : D->varlists()) {
2634     const auto *DE = cast<DeclRefExpr>(E);
2635     const auto *VD = cast<VarDecl>(DE->getDecl());
2636 
2637     // Skip all but globals.
2638     if (!VD->hasGlobalStorage())
2639       continue;
2640 
2641     // Check if the global has been materialized yet or not. If not, we are done
2642     // as any later generation will utilize the OMPAllocateDeclAttr. However, if
2643     // we already emitted the global we might have done so before the
2644     // OMPAllocateDeclAttr was attached, leading to the wrong address space
2645     // (potentially). While not pretty, common practise is to remove the old IR
2646     // global and generate a new one, so we do that here too. Uses are replaced
2647     // properly.
2648     StringRef MangledName = getMangledName(VD);
2649     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2650     if (!Entry)
2651       continue;
2652 
2653     // We can also keep the existing global if the address space is what we
2654     // expect it to be, if not, it is replaced.
2655     QualType ASTTy = VD->getType();
2656     clang::LangAS GVAS = GetGlobalVarAddressSpace(VD);
2657     auto TargetAS = getContext().getTargetAddressSpace(GVAS);
2658     if (Entry->getType()->getAddressSpace() == TargetAS)
2659       continue;
2660 
2661     // Make a new global with the correct type / address space.
2662     llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
2663     llvm::PointerType *PTy = llvm::PointerType::get(Ty, TargetAS);
2664 
2665     // Replace all uses of the old global with a cast. Since we mutate the type
2666     // in place we neeed an intermediate that takes the spot of the old entry
2667     // until we can create the cast.
2668     llvm::GlobalVariable *DummyGV = new llvm::GlobalVariable(
2669         getModule(), Entry->getValueType(), false,
2670         llvm::GlobalValue::CommonLinkage, nullptr, "dummy", nullptr,
2671         llvm::GlobalVariable::NotThreadLocal, Entry->getAddressSpace());
2672     Entry->replaceAllUsesWith(DummyGV);
2673 
2674     Entry->mutateType(PTy);
2675     llvm::Constant *NewPtrForOldDecl =
2676         llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
2677             Entry, DummyGV->getType());
2678 
2679     // Now we have a casted version of the changed global, the dummy can be
2680     // replaced and deleted.
2681     DummyGV->replaceAllUsesWith(NewPtrForOldDecl);
2682     DummyGV->eraseFromParent();
2683   }
2684 }
2685