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