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