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