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