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         // If there's a jump into the lifetime of this variable, its lifetime
1026         // gets broken up into several regions in IR, which requires more work
1027         // to handle correctly. For now, just omit the intrinsics; this is a
1028         // rare case, and it's better to just be conservatively correct.
1029         // PR28267.
1030         //
1031         // We have to do this in all language modes if there's a jump past the
1032         // declaration. We also have to do it in C if there's a jump to an
1033         // earlier point in the current block because non-VLA lifetimes begin as
1034         // soon as the containing block is entered, not when its variables
1035         // actually come into scope; suppressing the lifetime annotations
1036         // completely in this case is unnecessarily pessimistic, but again, this
1037         // is rare.
1038         if (!Bypasses.IsBypassed(&D) &&
1039             !(!getLangOpts().CPlusPlus && hasLabelBeenSeenInCurrentScope())) {
1040           uint64_t size = CGM.getDataLayout().getTypeAllocSize(allocaTy);
1041           emission.SizeForLifetimeMarkers =
1042               EmitLifetimeStart(size, address.getPointer());
1043         }
1044       } else {
1045         assert(!emission.useLifetimeMarkers());
1046       }
1047     }
1048   } else {
1049     EnsureInsertPoint();
1050 
1051     if (!DidCallStackSave) {
1052       // Save the stack.
1053       Address Stack =
1054         CreateTempAlloca(Int8PtrTy, getPointerAlign(), "saved_stack");
1055 
1056       llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
1057       llvm::Value *V = Builder.CreateCall(F);
1058       Builder.CreateStore(V, Stack);
1059 
1060       DidCallStackSave = true;
1061 
1062       // Push a cleanup block and restore the stack there.
1063       // FIXME: in general circumstances, this should be an EH cleanup.
1064       pushStackRestore(NormalCleanup, Stack);
1065     }
1066 
1067     llvm::Value *elementCount;
1068     QualType elementType;
1069     std::tie(elementCount, elementType) = getVLASize(Ty);
1070 
1071     llvm::Type *llvmTy = ConvertTypeForMem(elementType);
1072 
1073     // Allocate memory for the array.
1074     llvm::AllocaInst *vla = Builder.CreateAlloca(llvmTy, elementCount, "vla");
1075     vla->setAlignment(alignment.getQuantity());
1076 
1077     address = Address(vla, alignment);
1078   }
1079 
1080   setAddrOfLocalVar(&D, address);
1081   emission.Addr = address;
1082 
1083   // Emit debug info for local var declaration.
1084   if (HaveInsertPoint())
1085     if (CGDebugInfo *DI = getDebugInfo()) {
1086       if (CGM.getCodeGenOpts().getDebugInfo() >=
1087           codegenoptions::LimitedDebugInfo) {
1088         DI->setLocation(D.getLocation());
1089         DI->EmitDeclareOfAutoVariable(&D, address.getPointer(), Builder);
1090       }
1091     }
1092 
1093   if (D.hasAttr<AnnotateAttr>())
1094     EmitVarAnnotations(&D, address.getPointer());
1095 
1096   return emission;
1097 }
1098 
1099 /// Determines whether the given __block variable is potentially
1100 /// captured by the given expression.
1101 static bool isCapturedBy(const VarDecl &var, const Expr *e) {
1102   // Skip the most common kinds of expressions that make
1103   // hierarchy-walking expensive.
1104   e = e->IgnoreParenCasts();
1105 
1106   if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
1107     const BlockDecl *block = be->getBlockDecl();
1108     for (const auto &I : block->captures()) {
1109       if (I.getVariable() == &var)
1110         return true;
1111     }
1112 
1113     // No need to walk into the subexpressions.
1114     return false;
1115   }
1116 
1117   if (const StmtExpr *SE = dyn_cast<StmtExpr>(e)) {
1118     const CompoundStmt *CS = SE->getSubStmt();
1119     for (const auto *BI : CS->body())
1120       if (const auto *E = dyn_cast<Expr>(BI)) {
1121         if (isCapturedBy(var, E))
1122             return true;
1123       }
1124       else if (const auto *DS = dyn_cast<DeclStmt>(BI)) {
1125           // special case declarations
1126           for (const auto *I : DS->decls()) {
1127               if (const auto *VD = dyn_cast<VarDecl>((I))) {
1128                 const Expr *Init = VD->getInit();
1129                 if (Init && isCapturedBy(var, Init))
1130                   return true;
1131               }
1132           }
1133       }
1134       else
1135         // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
1136         // Later, provide code to poke into statements for capture analysis.
1137         return true;
1138     return false;
1139   }
1140 
1141   for (const Stmt *SubStmt : e->children())
1142     if (isCapturedBy(var, cast<Expr>(SubStmt)))
1143       return true;
1144 
1145   return false;
1146 }
1147 
1148 /// \brief Determine whether the given initializer is trivial in the sense
1149 /// that it requires no code to be generated.
1150 bool CodeGenFunction::isTrivialInitializer(const Expr *Init) {
1151   if (!Init)
1152     return true;
1153 
1154   if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
1155     if (CXXConstructorDecl *Constructor = Construct->getConstructor())
1156       if (Constructor->isTrivial() &&
1157           Constructor->isDefaultConstructor() &&
1158           !Construct->requiresZeroInitialization())
1159         return true;
1160 
1161   return false;
1162 }
1163 
1164 void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
1165   assert(emission.Variable && "emission was not valid!");
1166 
1167   // If this was emitted as a global constant, we're done.
1168   if (emission.wasEmittedAsGlobal()) return;
1169 
1170   const VarDecl &D = *emission.Variable;
1171   auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, D.getLocation());
1172   QualType type = D.getType();
1173 
1174   // If this local has an initializer, emit it now.
1175   const Expr *Init = D.getInit();
1176 
1177   // If we are at an unreachable point, we don't need to emit the initializer
1178   // unless it contains a label.
1179   if (!HaveInsertPoint()) {
1180     if (!Init || !ContainsLabel(Init)) return;
1181     EnsureInsertPoint();
1182   }
1183 
1184   // Initialize the structure of a __block variable.
1185   if (emission.IsByRef)
1186     emitByrefStructureInit(emission);
1187 
1188   if (isTrivialInitializer(Init))
1189     return;
1190 
1191   // Check whether this is a byref variable that's potentially
1192   // captured and moved by its own initializer.  If so, we'll need to
1193   // emit the initializer first, then copy into the variable.
1194   bool capturedByInit = emission.IsByRef && isCapturedBy(D, Init);
1195 
1196   Address Loc =
1197     capturedByInit ? emission.Addr : emission.getObjectAddress(*this);
1198 
1199   llvm::Constant *constant = nullptr;
1200   if (emission.IsConstantAggregate || D.isConstexpr()) {
1201     assert(!capturedByInit && "constant init contains a capturing block?");
1202     constant = CGM.EmitConstantInit(D, this);
1203   }
1204 
1205   if (!constant) {
1206     LValue lv = MakeAddrLValue(Loc, type);
1207     lv.setNonGC(true);
1208     return EmitExprAsInit(Init, &D, lv, capturedByInit);
1209   }
1210 
1211   if (!emission.IsConstantAggregate) {
1212     // For simple scalar/complex initialization, store the value directly.
1213     LValue lv = MakeAddrLValue(Loc, type);
1214     lv.setNonGC(true);
1215     return EmitStoreThroughLValue(RValue::get(constant), lv, true);
1216   }
1217 
1218   // If this is a simple aggregate initialization, we can optimize it
1219   // in various ways.
1220   bool isVolatile = type.isVolatileQualified();
1221 
1222   llvm::Value *SizeVal =
1223     llvm::ConstantInt::get(IntPtrTy,
1224                            getContext().getTypeSizeInChars(type).getQuantity());
1225 
1226   llvm::Type *BP = Int8PtrTy;
1227   if (Loc.getType() != BP)
1228     Loc = Builder.CreateBitCast(Loc, BP);
1229 
1230   // If the initializer is all or mostly zeros, codegen with memset then do
1231   // a few stores afterward.
1232   if (shouldUseMemSetPlusStoresToInitialize(constant,
1233                 CGM.getDataLayout().getTypeAllocSize(constant->getType()))) {
1234     Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
1235                          isVolatile);
1236     // Zero and undef don't require a stores.
1237     if (!constant->isNullValue() && !isa<llvm::UndefValue>(constant)) {
1238       Loc = Builder.CreateBitCast(Loc, constant->getType()->getPointerTo());
1239       emitStoresForInitAfterMemset(constant, Loc.getPointer(),
1240                                    isVolatile, Builder);
1241     }
1242   } else {
1243     // Otherwise, create a temporary global with the initializer then
1244     // memcpy from the global to the alloca.
1245     std::string Name = getStaticDeclName(CGM, D);
1246     unsigned AS = 0;
1247     if (getLangOpts().OpenCL) {
1248       AS = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
1249       BP = llvm::PointerType::getInt8PtrTy(getLLVMContext(), AS);
1250     }
1251     llvm::GlobalVariable *GV =
1252       new llvm::GlobalVariable(CGM.getModule(), constant->getType(), true,
1253                                llvm::GlobalValue::PrivateLinkage,
1254                                constant, Name, nullptr,
1255                                llvm::GlobalValue::NotThreadLocal, AS);
1256     GV->setAlignment(Loc.getAlignment().getQuantity());
1257     GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1258 
1259     Address SrcPtr = Address(GV, Loc.getAlignment());
1260     if (SrcPtr.getType() != BP)
1261       SrcPtr = Builder.CreateBitCast(SrcPtr, BP);
1262 
1263     Builder.CreateMemCpy(Loc, SrcPtr, SizeVal, isVolatile);
1264   }
1265 }
1266 
1267 /// Emit an expression as an initializer for a variable at the given
1268 /// location.  The expression is not necessarily the normal
1269 /// initializer for the variable, and the address is not necessarily
1270 /// its normal location.
1271 ///
1272 /// \param init the initializing expression
1273 /// \param var the variable to act as if we're initializing
1274 /// \param loc the address to initialize; its type is a pointer
1275 ///   to the LLVM mapping of the variable's type
1276 /// \param alignment the alignment of the address
1277 /// \param capturedByInit true if the variable is a __block variable
1278 ///   whose address is potentially changed by the initializer
1279 void CodeGenFunction::EmitExprAsInit(const Expr *init, const ValueDecl *D,
1280                                      LValue lvalue, bool capturedByInit) {
1281   QualType type = D->getType();
1282 
1283   if (type->isReferenceType()) {
1284     RValue rvalue = EmitReferenceBindingToExpr(init);
1285     if (capturedByInit)
1286       drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
1287     EmitStoreThroughLValue(rvalue, lvalue, true);
1288     return;
1289   }
1290   switch (getEvaluationKind(type)) {
1291   case TEK_Scalar:
1292     EmitScalarInit(init, D, lvalue, capturedByInit);
1293     return;
1294   case TEK_Complex: {
1295     ComplexPairTy complex = EmitComplexExpr(init);
1296     if (capturedByInit)
1297       drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
1298     EmitStoreOfComplex(complex, lvalue, /*init*/ true);
1299     return;
1300   }
1301   case TEK_Aggregate:
1302     if (type->isAtomicType()) {
1303       EmitAtomicInit(const_cast<Expr*>(init), lvalue);
1304     } else {
1305       // TODO: how can we delay here if D is captured by its initializer?
1306       EmitAggExpr(init, AggValueSlot::forLValue(lvalue,
1307                                               AggValueSlot::IsDestructed,
1308                                          AggValueSlot::DoesNotNeedGCBarriers,
1309                                               AggValueSlot::IsNotAliased));
1310     }
1311     return;
1312   }
1313   llvm_unreachable("bad evaluation kind");
1314 }
1315 
1316 /// Enter a destroy cleanup for the given local variable.
1317 void CodeGenFunction::emitAutoVarTypeCleanup(
1318                             const CodeGenFunction::AutoVarEmission &emission,
1319                             QualType::DestructionKind dtorKind) {
1320   assert(dtorKind != QualType::DK_none);
1321 
1322   // Note that for __block variables, we want to destroy the
1323   // original stack object, not the possibly forwarded object.
1324   Address addr = emission.getObjectAddress(*this);
1325 
1326   const VarDecl *var = emission.Variable;
1327   QualType type = var->getType();
1328 
1329   CleanupKind cleanupKind = NormalAndEHCleanup;
1330   CodeGenFunction::Destroyer *destroyer = nullptr;
1331 
1332   switch (dtorKind) {
1333   case QualType::DK_none:
1334     llvm_unreachable("no cleanup for trivially-destructible variable");
1335 
1336   case QualType::DK_cxx_destructor:
1337     // If there's an NRVO flag on the emission, we need a different
1338     // cleanup.
1339     if (emission.NRVOFlag) {
1340       assert(!type->isArrayType());
1341       CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
1342       EHStack.pushCleanup<DestroyNRVOVariable>(cleanupKind, addr,
1343                                                dtor, emission.NRVOFlag);
1344       return;
1345     }
1346     break;
1347 
1348   case QualType::DK_objc_strong_lifetime:
1349     // Suppress cleanups for pseudo-strong variables.
1350     if (var->isARCPseudoStrong()) return;
1351 
1352     // Otherwise, consider whether to use an EH cleanup or not.
1353     cleanupKind = getARCCleanupKind();
1354 
1355     // Use the imprecise destroyer by default.
1356     if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
1357       destroyer = CodeGenFunction::destroyARCStrongImprecise;
1358     break;
1359 
1360   case QualType::DK_objc_weak_lifetime:
1361     break;
1362   }
1363 
1364   // If we haven't chosen a more specific destroyer, use the default.
1365   if (!destroyer) destroyer = getDestroyer(dtorKind);
1366 
1367   // Use an EH cleanup in array destructors iff the destructor itself
1368   // is being pushed as an EH cleanup.
1369   bool useEHCleanup = (cleanupKind & EHCleanup);
1370   EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
1371                                      useEHCleanup);
1372 }
1373 
1374 void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
1375   assert(emission.Variable && "emission was not valid!");
1376 
1377   // If this was emitted as a global constant, we're done.
1378   if (emission.wasEmittedAsGlobal()) return;
1379 
1380   // If we don't have an insertion point, we're done.  Sema prevents
1381   // us from jumping into any of these scopes anyway.
1382   if (!HaveInsertPoint()) return;
1383 
1384   const VarDecl &D = *emission.Variable;
1385 
1386   // Make sure we call @llvm.lifetime.end.  This needs to happen
1387   // *last*, so the cleanup needs to be pushed *first*.
1388   if (emission.useLifetimeMarkers())
1389     EHStack.pushCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker,
1390                                          emission.getAllocatedAddress(),
1391                                          emission.getSizeForLifetimeMarkers());
1392 
1393   // Check the type for a cleanup.
1394   if (QualType::DestructionKind dtorKind = D.getType().isDestructedType())
1395     emitAutoVarTypeCleanup(emission, dtorKind);
1396 
1397   // In GC mode, honor objc_precise_lifetime.
1398   if (getLangOpts().getGC() != LangOptions::NonGC &&
1399       D.hasAttr<ObjCPreciseLifetimeAttr>()) {
1400     EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
1401   }
1402 
1403   // Handle the cleanup attribute.
1404   if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
1405     const FunctionDecl *FD = CA->getFunctionDecl();
1406 
1407     llvm::Constant *F = CGM.GetAddrOfFunction(FD);
1408     assert(F && "Could not find function!");
1409 
1410     const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
1411     EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
1412   }
1413 
1414   // If this is a block variable, call _Block_object_destroy
1415   // (on the unforwarded address).
1416   if (emission.IsByRef)
1417     enterByrefCleanup(emission);
1418 }
1419 
1420 CodeGenFunction::Destroyer *
1421 CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
1422   switch (kind) {
1423   case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
1424   case QualType::DK_cxx_destructor:
1425     return destroyCXXObject;
1426   case QualType::DK_objc_strong_lifetime:
1427     return destroyARCStrongPrecise;
1428   case QualType::DK_objc_weak_lifetime:
1429     return destroyARCWeak;
1430   }
1431   llvm_unreachable("Unknown DestructionKind");
1432 }
1433 
1434 /// pushEHDestroy - Push the standard destructor for the given type as
1435 /// an EH-only cleanup.
1436 void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind,
1437                                     Address addr, QualType type) {
1438   assert(dtorKind && "cannot push destructor for trivial type");
1439   assert(needsEHCleanup(dtorKind));
1440 
1441   pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true);
1442 }
1443 
1444 /// pushDestroy - Push the standard destructor for the given type as
1445 /// at least a normal cleanup.
1446 void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
1447                                   Address addr, QualType type) {
1448   assert(dtorKind && "cannot push destructor for trivial type");
1449 
1450   CleanupKind cleanupKind = getCleanupKind(dtorKind);
1451   pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
1452               cleanupKind & EHCleanup);
1453 }
1454 
1455 void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, Address addr,
1456                                   QualType type, Destroyer *destroyer,
1457                                   bool useEHCleanupForArray) {
1458   pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
1459                                      destroyer, useEHCleanupForArray);
1460 }
1461 
1462 void CodeGenFunction::pushStackRestore(CleanupKind Kind, Address SPMem) {
1463   EHStack.pushCleanup<CallStackRestore>(Kind, SPMem);
1464 }
1465 
1466 void CodeGenFunction::pushLifetimeExtendedDestroy(
1467     CleanupKind cleanupKind, Address addr, QualType type,
1468     Destroyer *destroyer, bool useEHCleanupForArray) {
1469   assert(!isInConditionalBranch() &&
1470          "performing lifetime extension from within conditional");
1471 
1472   // Push an EH-only cleanup for the object now.
1473   // FIXME: When popping normal cleanups, we need to keep this EH cleanup
1474   // around in case a temporary's destructor throws an exception.
1475   if (cleanupKind & EHCleanup)
1476     EHStack.pushCleanup<DestroyObject>(
1477         static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type,
1478         destroyer, useEHCleanupForArray);
1479 
1480   // Remember that we need to push a full cleanup for the object at the
1481   // end of the full-expression.
1482   pushCleanupAfterFullExpr<DestroyObject>(
1483       cleanupKind, addr, type, destroyer, useEHCleanupForArray);
1484 }
1485 
1486 /// emitDestroy - Immediately perform the destruction of the given
1487 /// object.
1488 ///
1489 /// \param addr - the address of the object; a type*
1490 /// \param type - the type of the object; if an array type, all
1491 ///   objects are destroyed in reverse order
1492 /// \param destroyer - the function to call to destroy individual
1493 ///   elements
1494 /// \param useEHCleanupForArray - whether an EH cleanup should be
1495 ///   used when destroying array elements, in case one of the
1496 ///   destructions throws an exception
1497 void CodeGenFunction::emitDestroy(Address addr, QualType type,
1498                                   Destroyer *destroyer,
1499                                   bool useEHCleanupForArray) {
1500   const ArrayType *arrayType = getContext().getAsArrayType(type);
1501   if (!arrayType)
1502     return destroyer(*this, addr, type);
1503 
1504   llvm::Value *length = emitArrayLength(arrayType, type, addr);
1505 
1506   CharUnits elementAlign =
1507     addr.getAlignment()
1508         .alignmentOfArrayElement(getContext().getTypeSizeInChars(type));
1509 
1510   // Normally we have to check whether the array is zero-length.
1511   bool checkZeroLength = true;
1512 
1513   // But if the array length is constant, we can suppress that.
1514   if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
1515     // ...and if it's constant zero, we can just skip the entire thing.
1516     if (constLength->isZero()) return;
1517     checkZeroLength = false;
1518   }
1519 
1520   llvm::Value *begin = addr.getPointer();
1521   llvm::Value *end = Builder.CreateInBoundsGEP(begin, length);
1522   emitArrayDestroy(begin, end, type, elementAlign, destroyer,
1523                    checkZeroLength, useEHCleanupForArray);
1524 }
1525 
1526 /// emitArrayDestroy - Destroys all the elements of the given array,
1527 /// beginning from last to first.  The array cannot be zero-length.
1528 ///
1529 /// \param begin - a type* denoting the first element of the array
1530 /// \param end - a type* denoting one past the end of the array
1531 /// \param elementType - the element type of the array
1532 /// \param destroyer - the function to call to destroy elements
1533 /// \param useEHCleanup - whether to push an EH cleanup to destroy
1534 ///   the remaining elements in case the destruction of a single
1535 ///   element throws
1536 void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
1537                                        llvm::Value *end,
1538                                        QualType elementType,
1539                                        CharUnits elementAlign,
1540                                        Destroyer *destroyer,
1541                                        bool checkZeroLength,
1542                                        bool useEHCleanup) {
1543   assert(!elementType->isArrayType());
1544 
1545   // The basic structure here is a do-while loop, because we don't
1546   // need to check for the zero-element case.
1547   llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
1548   llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
1549 
1550   if (checkZeroLength) {
1551     llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
1552                                                 "arraydestroy.isempty");
1553     Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
1554   }
1555 
1556   // Enter the loop body, making that address the current address.
1557   llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1558   EmitBlock(bodyBB);
1559   llvm::PHINode *elementPast =
1560     Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
1561   elementPast->addIncoming(end, entryBB);
1562 
1563   // Shift the address back by one element.
1564   llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
1565   llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne,
1566                                                    "arraydestroy.element");
1567 
1568   if (useEHCleanup)
1569     pushRegularPartialArrayCleanup(begin, element, elementType, elementAlign,
1570                                    destroyer);
1571 
1572   // Perform the actual destruction there.
1573   destroyer(*this, Address(element, elementAlign), elementType);
1574 
1575   if (useEHCleanup)
1576     PopCleanupBlock();
1577 
1578   // Check whether we've reached the end.
1579   llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
1580   Builder.CreateCondBr(done, doneBB, bodyBB);
1581   elementPast->addIncoming(element, Builder.GetInsertBlock());
1582 
1583   // Done.
1584   EmitBlock(doneBB);
1585 }
1586 
1587 /// Perform partial array destruction as if in an EH cleanup.  Unlike
1588 /// emitArrayDestroy, the element type here may still be an array type.
1589 static void emitPartialArrayDestroy(CodeGenFunction &CGF,
1590                                     llvm::Value *begin, llvm::Value *end,
1591                                     QualType type, CharUnits elementAlign,
1592                                     CodeGenFunction::Destroyer *destroyer) {
1593   // If the element type is itself an array, drill down.
1594   unsigned arrayDepth = 0;
1595   while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
1596     // VLAs don't require a GEP index to walk into.
1597     if (!isa<VariableArrayType>(arrayType))
1598       arrayDepth++;
1599     type = arrayType->getElementType();
1600   }
1601 
1602   if (arrayDepth) {
1603     llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
1604 
1605     SmallVector<llvm::Value*,4> gepIndices(arrayDepth+1, zero);
1606     begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin");
1607     end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend");
1608   }
1609 
1610   // Destroy the array.  We don't ever need an EH cleanup because we
1611   // assume that we're in an EH cleanup ourselves, so a throwing
1612   // destructor causes an immediate terminate.
1613   CGF.emitArrayDestroy(begin, end, type, elementAlign, destroyer,
1614                        /*checkZeroLength*/ true, /*useEHCleanup*/ false);
1615 }
1616 
1617 namespace {
1618   /// RegularPartialArrayDestroy - a cleanup which performs a partial
1619   /// array destroy where the end pointer is regularly determined and
1620   /// does not need to be loaded from a local.
1621   class RegularPartialArrayDestroy final : public EHScopeStack::Cleanup {
1622     llvm::Value *ArrayBegin;
1623     llvm::Value *ArrayEnd;
1624     QualType ElementType;
1625     CodeGenFunction::Destroyer *Destroyer;
1626     CharUnits ElementAlign;
1627   public:
1628     RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
1629                                QualType elementType, CharUnits elementAlign,
1630                                CodeGenFunction::Destroyer *destroyer)
1631       : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
1632         ElementType(elementType), Destroyer(destroyer),
1633         ElementAlign(elementAlign) {}
1634 
1635     void Emit(CodeGenFunction &CGF, Flags flags) override {
1636       emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
1637                               ElementType, ElementAlign, Destroyer);
1638     }
1639   };
1640 
1641   /// IrregularPartialArrayDestroy - a cleanup which performs a
1642   /// partial array destroy where the end pointer is irregularly
1643   /// determined and must be loaded from a local.
1644   class IrregularPartialArrayDestroy final : public EHScopeStack::Cleanup {
1645     llvm::Value *ArrayBegin;
1646     Address ArrayEndPointer;
1647     QualType ElementType;
1648     CodeGenFunction::Destroyer *Destroyer;
1649     CharUnits ElementAlign;
1650   public:
1651     IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
1652                                  Address arrayEndPointer,
1653                                  QualType elementType,
1654                                  CharUnits elementAlign,
1655                                  CodeGenFunction::Destroyer *destroyer)
1656       : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
1657         ElementType(elementType), Destroyer(destroyer),
1658         ElementAlign(elementAlign) {}
1659 
1660     void Emit(CodeGenFunction &CGF, Flags flags) override {
1661       llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
1662       emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
1663                               ElementType, ElementAlign, Destroyer);
1664     }
1665   };
1666 } // end anonymous namespace
1667 
1668 /// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
1669 /// already-constructed elements of the given array.  The cleanup
1670 /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
1671 ///
1672 /// \param elementType - the immediate element type of the array;
1673 ///   possibly still an array type
1674 void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
1675                                                        Address arrayEndPointer,
1676                                                        QualType elementType,
1677                                                        CharUnits elementAlign,
1678                                                        Destroyer *destroyer) {
1679   pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
1680                                                     arrayBegin, arrayEndPointer,
1681                                                     elementType, elementAlign,
1682                                                     destroyer);
1683 }
1684 
1685 /// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
1686 /// already-constructed elements of the given array.  The cleanup
1687 /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
1688 ///
1689 /// \param elementType - the immediate element type of the array;
1690 ///   possibly still an array type
1691 void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
1692                                                      llvm::Value *arrayEnd,
1693                                                      QualType elementType,
1694                                                      CharUnits elementAlign,
1695                                                      Destroyer *destroyer) {
1696   pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
1697                                                   arrayBegin, arrayEnd,
1698                                                   elementType, elementAlign,
1699                                                   destroyer);
1700 }
1701 
1702 /// Lazily declare the @llvm.lifetime.start intrinsic.
1703 llvm::Constant *CodeGenModule::getLLVMLifetimeStartFn() {
1704   if (LifetimeStartFn) return LifetimeStartFn;
1705   LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(),
1706                                             llvm::Intrinsic::lifetime_start);
1707   return LifetimeStartFn;
1708 }
1709 
1710 /// Lazily declare the @llvm.lifetime.end intrinsic.
1711 llvm::Constant *CodeGenModule::getLLVMLifetimeEndFn() {
1712   if (LifetimeEndFn) return LifetimeEndFn;
1713   LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(),
1714                                               llvm::Intrinsic::lifetime_end);
1715   return LifetimeEndFn;
1716 }
1717 
1718 namespace {
1719   /// A cleanup to perform a release of an object at the end of a
1720   /// function.  This is used to balance out the incoming +1 of a
1721   /// ns_consumed argument when we can't reasonably do that just by
1722   /// not doing the initial retain for a __block argument.
1723   struct ConsumeARCParameter final : EHScopeStack::Cleanup {
1724     ConsumeARCParameter(llvm::Value *param,
1725                         ARCPreciseLifetime_t precise)
1726       : Param(param), Precise(precise) {}
1727 
1728     llvm::Value *Param;
1729     ARCPreciseLifetime_t Precise;
1730 
1731     void Emit(CodeGenFunction &CGF, Flags flags) override {
1732       CGF.EmitARCRelease(Param, Precise);
1733     }
1734   };
1735 } // end anonymous namespace
1736 
1737 /// Emit an alloca (or GlobalValue depending on target)
1738 /// for the specified parameter and set up LocalDeclMap.
1739 void CodeGenFunction::EmitParmDecl(const VarDecl &D, ParamValue Arg,
1740                                    unsigned ArgNo) {
1741   // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
1742   assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
1743          "Invalid argument to EmitParmDecl");
1744 
1745   Arg.getAnyValue()->setName(D.getName());
1746 
1747   QualType Ty = D.getType();
1748 
1749   // Use better IR generation for certain implicit parameters.
1750   if (auto IPD = dyn_cast<ImplicitParamDecl>(&D)) {
1751     // The only implicit argument a block has is its literal.
1752     // We assume this is always passed directly.
1753     if (BlockInfo) {
1754       setBlockContextParameter(IPD, ArgNo, Arg.getDirectValue());
1755       return;
1756     }
1757 
1758     // Apply any prologue 'this' adjustments required by the ABI. Be careful to
1759     // handle the case where 'this' is passed indirectly as part of an inalloca
1760     // struct.
1761     if (const CXXMethodDecl *MD =
1762             dyn_cast_or_null<CXXMethodDecl>(CurCodeDecl)) {
1763       if (MD->isVirtual() && IPD == CXXABIThisDecl) {
1764         llvm::Value *This = Arg.isIndirect()
1765                                 ? Builder.CreateLoad(Arg.getIndirectAddress())
1766                                 : Arg.getDirectValue();
1767         This = CGM.getCXXABI().adjustThisParameterInVirtualFunctionPrologue(
1768             *this, CurGD, This);
1769         if (Arg.isIndirect())
1770           Builder.CreateStore(This, Arg.getIndirectAddress());
1771         else
1772           Arg = ParamValue::forDirect(This);
1773       }
1774     }
1775   }
1776 
1777   Address DeclPtr = Address::invalid();
1778   bool DoStore = false;
1779   bool IsScalar = hasScalarEvaluationKind(Ty);
1780   // If we already have a pointer to the argument, reuse the input pointer.
1781   if (Arg.isIndirect()) {
1782     DeclPtr = Arg.getIndirectAddress();
1783     // If we have a prettier pointer type at this point, bitcast to that.
1784     unsigned AS = DeclPtr.getType()->getAddressSpace();
1785     llvm::Type *IRTy = ConvertTypeForMem(Ty)->getPointerTo(AS);
1786     if (DeclPtr.getType() != IRTy)
1787       DeclPtr = Builder.CreateBitCast(DeclPtr, IRTy, D.getName());
1788 
1789     // Push a destructor cleanup for this parameter if the ABI requires it.
1790     // Don't push a cleanup in a thunk for a method that will also emit a
1791     // cleanup.
1792     if (!IsScalar && !CurFuncIsThunk &&
1793         getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
1794       const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
1795       if (RD && RD->hasNonTrivialDestructor())
1796         pushDestroy(QualType::DK_cxx_destructor, DeclPtr, Ty);
1797     }
1798   } else {
1799     // Otherwise, create a temporary to hold the value.
1800     DeclPtr = CreateMemTemp(Ty, getContext().getDeclAlign(&D),
1801                             D.getName() + ".addr");
1802     DoStore = true;
1803   }
1804 
1805   llvm::Value *ArgVal = (DoStore ? Arg.getDirectValue() : nullptr);
1806 
1807   LValue lv = MakeAddrLValue(DeclPtr, Ty);
1808   if (IsScalar) {
1809     Qualifiers qs = Ty.getQualifiers();
1810     if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
1811       // We honor __attribute__((ns_consumed)) for types with lifetime.
1812       // For __strong, it's handled by just skipping the initial retain;
1813       // otherwise we have to balance out the initial +1 with an extra
1814       // cleanup to do the release at the end of the function.
1815       bool isConsumed = D.hasAttr<NSConsumedAttr>();
1816 
1817       // 'self' is always formally __strong, but if this is not an
1818       // init method then we don't want to retain it.
1819       if (D.isARCPseudoStrong()) {
1820         const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CurCodeDecl);
1821         assert(&D == method->getSelfDecl());
1822         assert(lt == Qualifiers::OCL_Strong);
1823         assert(qs.hasConst());
1824         assert(method->getMethodFamily() != OMF_init);
1825         (void) method;
1826         lt = Qualifiers::OCL_ExplicitNone;
1827       }
1828 
1829       if (lt == Qualifiers::OCL_Strong) {
1830         if (!isConsumed) {
1831           if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1832             // use objc_storeStrong(&dest, value) for retaining the
1833             // object. But first, store a null into 'dest' because
1834             // objc_storeStrong attempts to release its old value.
1835             llvm::Value *Null = CGM.EmitNullConstant(D.getType());
1836             EmitStoreOfScalar(Null, lv, /* isInitialization */ true);
1837             EmitARCStoreStrongCall(lv.getAddress(), ArgVal, true);
1838             DoStore = false;
1839           }
1840           else
1841           // Don't use objc_retainBlock for block pointers, because we
1842           // don't want to Block_copy something just because we got it
1843           // as a parameter.
1844             ArgVal = EmitARCRetainNonBlock(ArgVal);
1845         }
1846       } else {
1847         // Push the cleanup for a consumed parameter.
1848         if (isConsumed) {
1849           ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
1850                                 ? ARCPreciseLifetime : ARCImpreciseLifetime);
1851           EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), ArgVal,
1852                                                    precise);
1853         }
1854 
1855         if (lt == Qualifiers::OCL_Weak) {
1856           EmitARCInitWeak(DeclPtr, ArgVal);
1857           DoStore = false; // The weak init is a store, no need to do two.
1858         }
1859       }
1860 
1861       // Enter the cleanup scope.
1862       EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
1863     }
1864   }
1865 
1866   // Store the initial value into the alloca.
1867   if (DoStore)
1868     EmitStoreOfScalar(ArgVal, lv, /* isInitialization */ true);
1869 
1870   setAddrOfLocalVar(&D, DeclPtr);
1871 
1872   // Emit debug info for param declaration.
1873   if (CGDebugInfo *DI = getDebugInfo()) {
1874     if (CGM.getCodeGenOpts().getDebugInfo() >=
1875         codegenoptions::LimitedDebugInfo) {
1876       DI->EmitDeclareOfArgVariable(&D, DeclPtr.getPointer(), ArgNo, Builder);
1877     }
1878   }
1879 
1880   if (D.hasAttr<AnnotateAttr>())
1881     EmitVarAnnotations(&D, DeclPtr.getPointer());
1882 }
1883 
1884 void CodeGenModule::EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D,
1885                                             CodeGenFunction *CGF) {
1886   if (!LangOpts.OpenMP || (!LangOpts.EmitAllDecls && !D->isUsed()))
1887     return;
1888   getOpenMPRuntime().emitUserDefinedReduction(CGF, D);
1889 }
1890