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