xref: /netbsd-src/external/apache2/llvm/dist/clang/lib/CodeGen/CGDecl.cpp (revision e038c9c4676b0f19b1b7dd08a940c6ed64a6d5ae)
17330f729Sjoerg //===--- CGDecl.cpp - Emit LLVM Code for declarations ---------------------===//
27330f729Sjoerg //
37330f729Sjoerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
47330f729Sjoerg // See https://llvm.org/LICENSE.txt for license information.
57330f729Sjoerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
67330f729Sjoerg //
77330f729Sjoerg //===----------------------------------------------------------------------===//
87330f729Sjoerg //
97330f729Sjoerg // This contains code to emit Decl nodes as LLVM code.
107330f729Sjoerg //
117330f729Sjoerg //===----------------------------------------------------------------------===//
127330f729Sjoerg 
137330f729Sjoerg #include "CGBlocks.h"
147330f729Sjoerg #include "CGCXXABI.h"
157330f729Sjoerg #include "CGCleanup.h"
167330f729Sjoerg #include "CGDebugInfo.h"
177330f729Sjoerg #include "CGOpenCLRuntime.h"
187330f729Sjoerg #include "CGOpenMPRuntime.h"
197330f729Sjoerg #include "CodeGenFunction.h"
207330f729Sjoerg #include "CodeGenModule.h"
217330f729Sjoerg #include "ConstantEmitter.h"
227330f729Sjoerg #include "PatternInit.h"
237330f729Sjoerg #include "TargetInfo.h"
247330f729Sjoerg #include "clang/AST/ASTContext.h"
25*e038c9c4Sjoerg #include "clang/AST/Attr.h"
267330f729Sjoerg #include "clang/AST/CharUnits.h"
277330f729Sjoerg #include "clang/AST/Decl.h"
287330f729Sjoerg #include "clang/AST/DeclObjC.h"
297330f729Sjoerg #include "clang/AST/DeclOpenMP.h"
307330f729Sjoerg #include "clang/Basic/CodeGenOptions.h"
317330f729Sjoerg #include "clang/Basic/SourceManager.h"
327330f729Sjoerg #include "clang/Basic/TargetInfo.h"
337330f729Sjoerg #include "clang/CodeGen/CGFunctionInfo.h"
34*e038c9c4Sjoerg #include "clang/Sema/Sema.h"
357330f729Sjoerg #include "llvm/Analysis/ValueTracking.h"
367330f729Sjoerg #include "llvm/IR/DataLayout.h"
377330f729Sjoerg #include "llvm/IR/GlobalVariable.h"
387330f729Sjoerg #include "llvm/IR/Intrinsics.h"
397330f729Sjoerg #include "llvm/IR/Type.h"
407330f729Sjoerg 
417330f729Sjoerg using namespace clang;
427330f729Sjoerg using namespace CodeGen;
437330f729Sjoerg 
44*e038c9c4Sjoerg static_assert(clang::Sema::MaximumAlignment <= llvm::Value::MaximumAlignment,
45*e038c9c4Sjoerg               "Clang max alignment greater than what LLVM supports?");
46*e038c9c4Sjoerg 
EmitDecl(const Decl & D)477330f729Sjoerg void CodeGenFunction::EmitDecl(const Decl &D) {
487330f729Sjoerg   switch (D.getKind()) {
497330f729Sjoerg   case Decl::BuiltinTemplate:
507330f729Sjoerg   case Decl::TranslationUnit:
517330f729Sjoerg   case Decl::ExternCContext:
527330f729Sjoerg   case Decl::Namespace:
537330f729Sjoerg   case Decl::UnresolvedUsingTypename:
547330f729Sjoerg   case Decl::ClassTemplateSpecialization:
557330f729Sjoerg   case Decl::ClassTemplatePartialSpecialization:
567330f729Sjoerg   case Decl::VarTemplateSpecialization:
577330f729Sjoerg   case Decl::VarTemplatePartialSpecialization:
587330f729Sjoerg   case Decl::TemplateTypeParm:
597330f729Sjoerg   case Decl::UnresolvedUsingValue:
607330f729Sjoerg   case Decl::NonTypeTemplateParm:
617330f729Sjoerg   case Decl::CXXDeductionGuide:
627330f729Sjoerg   case Decl::CXXMethod:
637330f729Sjoerg   case Decl::CXXConstructor:
647330f729Sjoerg   case Decl::CXXDestructor:
657330f729Sjoerg   case Decl::CXXConversion:
667330f729Sjoerg   case Decl::Field:
677330f729Sjoerg   case Decl::MSProperty:
687330f729Sjoerg   case Decl::IndirectField:
697330f729Sjoerg   case Decl::ObjCIvar:
707330f729Sjoerg   case Decl::ObjCAtDefsField:
717330f729Sjoerg   case Decl::ParmVar:
727330f729Sjoerg   case Decl::ImplicitParam:
737330f729Sjoerg   case Decl::ClassTemplate:
747330f729Sjoerg   case Decl::VarTemplate:
757330f729Sjoerg   case Decl::FunctionTemplate:
767330f729Sjoerg   case Decl::TypeAliasTemplate:
777330f729Sjoerg   case Decl::TemplateTemplateParm:
787330f729Sjoerg   case Decl::ObjCMethod:
797330f729Sjoerg   case Decl::ObjCCategory:
807330f729Sjoerg   case Decl::ObjCProtocol:
817330f729Sjoerg   case Decl::ObjCInterface:
827330f729Sjoerg   case Decl::ObjCCategoryImpl:
837330f729Sjoerg   case Decl::ObjCImplementation:
847330f729Sjoerg   case Decl::ObjCProperty:
857330f729Sjoerg   case Decl::ObjCCompatibleAlias:
867330f729Sjoerg   case Decl::PragmaComment:
877330f729Sjoerg   case Decl::PragmaDetectMismatch:
887330f729Sjoerg   case Decl::AccessSpec:
897330f729Sjoerg   case Decl::LinkageSpec:
907330f729Sjoerg   case Decl::Export:
917330f729Sjoerg   case Decl::ObjCPropertyImpl:
927330f729Sjoerg   case Decl::FileScopeAsm:
937330f729Sjoerg   case Decl::Friend:
947330f729Sjoerg   case Decl::FriendTemplate:
957330f729Sjoerg   case Decl::Block:
967330f729Sjoerg   case Decl::Captured:
977330f729Sjoerg   case Decl::ClassScopeFunctionSpecialization:
987330f729Sjoerg   case Decl::UsingShadow:
997330f729Sjoerg   case Decl::ConstructorUsingShadow:
1007330f729Sjoerg   case Decl::ObjCTypeParam:
1017330f729Sjoerg   case Decl::Binding:
1027330f729Sjoerg     llvm_unreachable("Declaration should not be in declstmts!");
1037330f729Sjoerg   case Decl::Record:    // struct/union/class X;
1047330f729Sjoerg   case Decl::CXXRecord: // struct/union/class X; [C++]
105*e038c9c4Sjoerg     if (CGDebugInfo *DI = getDebugInfo())
106*e038c9c4Sjoerg       if (cast<RecordDecl>(D).getDefinition())
107*e038c9c4Sjoerg         DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(&D)));
108*e038c9c4Sjoerg     return;
109*e038c9c4Sjoerg   case Decl::Enum:      // enum X;
110*e038c9c4Sjoerg     if (CGDebugInfo *DI = getDebugInfo())
111*e038c9c4Sjoerg       if (cast<EnumDecl>(D).getDefinition())
112*e038c9c4Sjoerg         DI->EmitAndRetainType(getContext().getEnumType(cast<EnumDecl>(&D)));
113*e038c9c4Sjoerg     return;
114*e038c9c4Sjoerg   case Decl::Function:     // void X();
115*e038c9c4Sjoerg   case Decl::EnumConstant: // enum ? { X = ? }
1167330f729Sjoerg   case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
1177330f729Sjoerg   case Decl::Label:        // __label__ x;
1187330f729Sjoerg   case Decl::Import:
119*e038c9c4Sjoerg   case Decl::MSGuid:    // __declspec(uuid("..."))
120*e038c9c4Sjoerg   case Decl::TemplateParamObject:
1217330f729Sjoerg   case Decl::OMPThreadPrivate:
1227330f729Sjoerg   case Decl::OMPAllocate:
1237330f729Sjoerg   case Decl::OMPCapturedExpr:
1247330f729Sjoerg   case Decl::OMPRequires:
1257330f729Sjoerg   case Decl::Empty:
1267330f729Sjoerg   case Decl::Concept:
127*e038c9c4Sjoerg   case Decl::LifetimeExtendedTemporary:
128*e038c9c4Sjoerg   case Decl::RequiresExprBody:
1297330f729Sjoerg     // None of these decls require codegen support.
1307330f729Sjoerg     return;
1317330f729Sjoerg 
1327330f729Sjoerg   case Decl::NamespaceAlias:
1337330f729Sjoerg     if (CGDebugInfo *DI = getDebugInfo())
1347330f729Sjoerg         DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(D));
1357330f729Sjoerg     return;
1367330f729Sjoerg   case Decl::Using:          // using X; [C++]
1377330f729Sjoerg     if (CGDebugInfo *DI = getDebugInfo())
1387330f729Sjoerg         DI->EmitUsingDecl(cast<UsingDecl>(D));
1397330f729Sjoerg     return;
1407330f729Sjoerg   case Decl::UsingPack:
1417330f729Sjoerg     for (auto *Using : cast<UsingPackDecl>(D).expansions())
1427330f729Sjoerg       EmitDecl(*Using);
1437330f729Sjoerg     return;
1447330f729Sjoerg   case Decl::UsingDirective: // using namespace X; [C++]
1457330f729Sjoerg     if (CGDebugInfo *DI = getDebugInfo())
1467330f729Sjoerg       DI->EmitUsingDirective(cast<UsingDirectiveDecl>(D));
1477330f729Sjoerg     return;
1487330f729Sjoerg   case Decl::Var:
1497330f729Sjoerg   case Decl::Decomposition: {
1507330f729Sjoerg     const VarDecl &VD = cast<VarDecl>(D);
1517330f729Sjoerg     assert(VD.isLocalVarDecl() &&
1527330f729Sjoerg            "Should not see file-scope variables inside a function!");
1537330f729Sjoerg     EmitVarDecl(VD);
1547330f729Sjoerg     if (auto *DD = dyn_cast<DecompositionDecl>(&VD))
1557330f729Sjoerg       for (auto *B : DD->bindings())
1567330f729Sjoerg         if (auto *HD = B->getHoldingVar())
1577330f729Sjoerg           EmitVarDecl(*HD);
1587330f729Sjoerg     return;
1597330f729Sjoerg   }
1607330f729Sjoerg 
1617330f729Sjoerg   case Decl::OMPDeclareReduction:
1627330f729Sjoerg     return CGM.EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(&D), this);
1637330f729Sjoerg 
1647330f729Sjoerg   case Decl::OMPDeclareMapper:
1657330f729Sjoerg     return CGM.EmitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(&D), this);
1667330f729Sjoerg 
1677330f729Sjoerg   case Decl::Typedef:      // typedef int X;
1687330f729Sjoerg   case Decl::TypeAlias: {  // using X = int; [C++0x]
169*e038c9c4Sjoerg     QualType Ty = cast<TypedefNameDecl>(D).getUnderlyingType();
170*e038c9c4Sjoerg     if (CGDebugInfo *DI = getDebugInfo())
171*e038c9c4Sjoerg       DI->EmitAndRetainType(Ty);
1727330f729Sjoerg     if (Ty->isVariablyModifiedType())
1737330f729Sjoerg       EmitVariablyModifiedType(Ty);
1747330f729Sjoerg     return;
1757330f729Sjoerg   }
1767330f729Sjoerg   }
1777330f729Sjoerg }
1787330f729Sjoerg 
1797330f729Sjoerg /// EmitVarDecl - This method handles emission of any variable declaration
1807330f729Sjoerg /// inside a function, including static vars etc.
EmitVarDecl(const VarDecl & D)1817330f729Sjoerg void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
1827330f729Sjoerg   if (D.hasExternalStorage())
1837330f729Sjoerg     // Don't emit it now, allow it to be emitted lazily on its first use.
1847330f729Sjoerg     return;
1857330f729Sjoerg 
1867330f729Sjoerg   // Some function-scope variable does not have static storage but still
1877330f729Sjoerg   // needs to be emitted like a static variable, e.g. a function-scope
1887330f729Sjoerg   // variable in constant address space in OpenCL.
1897330f729Sjoerg   if (D.getStorageDuration() != SD_Automatic) {
1907330f729Sjoerg     // Static sampler variables translated to function calls.
1917330f729Sjoerg     if (D.getType()->isSamplerT())
1927330f729Sjoerg       return;
1937330f729Sjoerg 
1947330f729Sjoerg     llvm::GlobalValue::LinkageTypes Linkage =
1957330f729Sjoerg         CGM.getLLVMLinkageVarDefinition(&D, /*IsConstant=*/false);
1967330f729Sjoerg 
1977330f729Sjoerg     // FIXME: We need to force the emission/use of a guard variable for
1987330f729Sjoerg     // some variables even if we can constant-evaluate them because
1997330f729Sjoerg     // we can't guarantee every translation unit will constant-evaluate them.
2007330f729Sjoerg 
2017330f729Sjoerg     return EmitStaticVarDecl(D, Linkage);
2027330f729Sjoerg   }
2037330f729Sjoerg 
2047330f729Sjoerg   if (D.getType().getAddressSpace() == LangAS::opencl_local)
2057330f729Sjoerg     return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D);
2067330f729Sjoerg 
2077330f729Sjoerg   assert(D.hasLocalStorage());
2087330f729Sjoerg   return EmitAutoVarDecl(D);
2097330f729Sjoerg }
2107330f729Sjoerg 
getStaticDeclName(CodeGenModule & CGM,const VarDecl & D)2117330f729Sjoerg static std::string getStaticDeclName(CodeGenModule &CGM, const VarDecl &D) {
2127330f729Sjoerg   if (CGM.getLangOpts().CPlusPlus)
2137330f729Sjoerg     return CGM.getMangledName(&D).str();
2147330f729Sjoerg 
2157330f729Sjoerg   // If this isn't C++, we don't need a mangled name, just a pretty one.
2167330f729Sjoerg   assert(!D.isExternallyVisible() && "name shouldn't matter");
2177330f729Sjoerg   std::string ContextName;
2187330f729Sjoerg   const DeclContext *DC = D.getDeclContext();
2197330f729Sjoerg   if (auto *CD = dyn_cast<CapturedDecl>(DC))
2207330f729Sjoerg     DC = cast<DeclContext>(CD->getNonClosureContext());
2217330f729Sjoerg   if (const auto *FD = dyn_cast<FunctionDecl>(DC))
222*e038c9c4Sjoerg     ContextName = std::string(CGM.getMangledName(FD));
2237330f729Sjoerg   else if (const auto *BD = dyn_cast<BlockDecl>(DC))
224*e038c9c4Sjoerg     ContextName = std::string(CGM.getBlockMangledName(GlobalDecl(), BD));
2257330f729Sjoerg   else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(DC))
2267330f729Sjoerg     ContextName = OMD->getSelector().getAsString();
2277330f729Sjoerg   else
2287330f729Sjoerg     llvm_unreachable("Unknown context for static var decl");
2297330f729Sjoerg 
2307330f729Sjoerg   ContextName += "." + D.getNameAsString();
2317330f729Sjoerg   return ContextName;
2327330f729Sjoerg }
2337330f729Sjoerg 
getOrCreateStaticVarDecl(const VarDecl & D,llvm::GlobalValue::LinkageTypes Linkage)2347330f729Sjoerg llvm::Constant *CodeGenModule::getOrCreateStaticVarDecl(
2357330f729Sjoerg     const VarDecl &D, llvm::GlobalValue::LinkageTypes Linkage) {
2367330f729Sjoerg   // In general, we don't always emit static var decls once before we reference
2377330f729Sjoerg   // them. It is possible to reference them before emitting the function that
2387330f729Sjoerg   // contains them, and it is possible to emit the containing function multiple
2397330f729Sjoerg   // times.
2407330f729Sjoerg   if (llvm::Constant *ExistingGV = StaticLocalDeclMap[&D])
2417330f729Sjoerg     return ExistingGV;
2427330f729Sjoerg 
2437330f729Sjoerg   QualType Ty = D.getType();
2447330f729Sjoerg   assert(Ty->isConstantSizeType() && "VLAs can't be static");
2457330f729Sjoerg 
2467330f729Sjoerg   // Use the label if the variable is renamed with the asm-label extension.
2477330f729Sjoerg   std::string Name;
2487330f729Sjoerg   if (D.hasAttr<AsmLabelAttr>())
249*e038c9c4Sjoerg     Name = std::string(getMangledName(&D));
2507330f729Sjoerg   else
2517330f729Sjoerg     Name = getStaticDeclName(*this, D);
2527330f729Sjoerg 
2537330f729Sjoerg   llvm::Type *LTy = getTypes().ConvertTypeForMem(Ty);
2547330f729Sjoerg   LangAS AS = GetGlobalVarAddressSpace(&D);
2557330f729Sjoerg   unsigned TargetAS = getContext().getTargetAddressSpace(AS);
2567330f729Sjoerg 
2577330f729Sjoerg   // OpenCL variables in local address space and CUDA shared
2587330f729Sjoerg   // variables cannot have an initializer.
2597330f729Sjoerg   llvm::Constant *Init = nullptr;
2607330f729Sjoerg   if (Ty.getAddressSpace() == LangAS::opencl_local ||
261*e038c9c4Sjoerg       D.hasAttr<CUDASharedAttr>() || D.hasAttr<LoaderUninitializedAttr>())
2627330f729Sjoerg     Init = llvm::UndefValue::get(LTy);
2637330f729Sjoerg   else
2647330f729Sjoerg     Init = EmitNullConstant(Ty);
2657330f729Sjoerg 
2667330f729Sjoerg   llvm::GlobalVariable *GV = new llvm::GlobalVariable(
2677330f729Sjoerg       getModule(), LTy, Ty.isConstant(getContext()), Linkage, Init, Name,
2687330f729Sjoerg       nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
2697330f729Sjoerg   GV->setAlignment(getContext().getDeclAlign(&D).getAsAlign());
2707330f729Sjoerg 
2717330f729Sjoerg   if (supportsCOMDAT() && GV->isWeakForLinker())
2727330f729Sjoerg     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
2737330f729Sjoerg 
2747330f729Sjoerg   if (D.getTLSKind())
2757330f729Sjoerg     setTLSMode(GV, D);
2767330f729Sjoerg 
2777330f729Sjoerg   setGVProperties(GV, &D);
2787330f729Sjoerg 
2797330f729Sjoerg   // Make sure the result is of the correct type.
2807330f729Sjoerg   LangAS ExpectedAS = Ty.getAddressSpace();
2817330f729Sjoerg   llvm::Constant *Addr = GV;
2827330f729Sjoerg   if (AS != ExpectedAS) {
2837330f729Sjoerg     Addr = getTargetCodeGenInfo().performAddrSpaceCast(
2847330f729Sjoerg         *this, GV, AS, ExpectedAS,
2857330f729Sjoerg         LTy->getPointerTo(getContext().getTargetAddressSpace(ExpectedAS)));
2867330f729Sjoerg   }
2877330f729Sjoerg 
2887330f729Sjoerg   setStaticLocalDeclAddress(&D, Addr);
2897330f729Sjoerg 
2907330f729Sjoerg   // Ensure that the static local gets initialized by making sure the parent
2917330f729Sjoerg   // function gets emitted eventually.
2927330f729Sjoerg   const Decl *DC = cast<Decl>(D.getDeclContext());
2937330f729Sjoerg 
2947330f729Sjoerg   // We can't name blocks or captured statements directly, so try to emit their
2957330f729Sjoerg   // parents.
2967330f729Sjoerg   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC)) {
2977330f729Sjoerg     DC = DC->getNonClosureContext();
2987330f729Sjoerg     // FIXME: Ensure that global blocks get emitted.
2997330f729Sjoerg     if (!DC)
3007330f729Sjoerg       return Addr;
3017330f729Sjoerg   }
3027330f729Sjoerg 
3037330f729Sjoerg   GlobalDecl GD;
3047330f729Sjoerg   if (const auto *CD = dyn_cast<CXXConstructorDecl>(DC))
3057330f729Sjoerg     GD = GlobalDecl(CD, Ctor_Base);
3067330f729Sjoerg   else if (const auto *DD = dyn_cast<CXXDestructorDecl>(DC))
3077330f729Sjoerg     GD = GlobalDecl(DD, Dtor_Base);
3087330f729Sjoerg   else if (const auto *FD = dyn_cast<FunctionDecl>(DC))
3097330f729Sjoerg     GD = GlobalDecl(FD);
3107330f729Sjoerg   else {
3117330f729Sjoerg     // Don't do anything for Obj-C method decls or global closures. We should
3127330f729Sjoerg     // never defer them.
3137330f729Sjoerg     assert(isa<ObjCMethodDecl>(DC) && "unexpected parent code decl");
3147330f729Sjoerg   }
3157330f729Sjoerg   if (GD.getDecl()) {
3167330f729Sjoerg     // Disable emission of the parent function for the OpenMP device codegen.
3177330f729Sjoerg     CGOpenMPRuntime::DisableAutoDeclareTargetRAII NoDeclTarget(*this);
3187330f729Sjoerg     (void)GetAddrOfGlobal(GD);
3197330f729Sjoerg   }
3207330f729Sjoerg 
3217330f729Sjoerg   return Addr;
3227330f729Sjoerg }
3237330f729Sjoerg 
3247330f729Sjoerg /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
3257330f729Sjoerg /// global variable that has already been created for it.  If the initializer
3267330f729Sjoerg /// has a different type than GV does, this may free GV and return a different
3277330f729Sjoerg /// one.  Otherwise it just returns GV.
3287330f729Sjoerg llvm::GlobalVariable *
AddInitializerToStaticVarDecl(const VarDecl & D,llvm::GlobalVariable * GV)3297330f729Sjoerg CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
3307330f729Sjoerg                                                llvm::GlobalVariable *GV) {
3317330f729Sjoerg   ConstantEmitter emitter(*this);
3327330f729Sjoerg   llvm::Constant *Init = emitter.tryEmitForInitializer(D);
3337330f729Sjoerg 
3347330f729Sjoerg   // If constant emission failed, then this should be a C++ static
3357330f729Sjoerg   // initializer.
3367330f729Sjoerg   if (!Init) {
3377330f729Sjoerg     if (!getLangOpts().CPlusPlus)
3387330f729Sjoerg       CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
3397330f729Sjoerg     else if (HaveInsertPoint()) {
3407330f729Sjoerg       // Since we have a static initializer, this global variable can't
3417330f729Sjoerg       // be constant.
3427330f729Sjoerg       GV->setConstant(false);
3437330f729Sjoerg 
3447330f729Sjoerg       EmitCXXGuardedInit(D, GV, /*PerformInit*/true);
3457330f729Sjoerg     }
3467330f729Sjoerg     return GV;
3477330f729Sjoerg   }
3487330f729Sjoerg 
3497330f729Sjoerg   // The initializer may differ in type from the global. Rewrite
3507330f729Sjoerg   // the global to match the initializer.  (We have to do this
3517330f729Sjoerg   // because some types, like unions, can't be completely represented
3527330f729Sjoerg   // in the LLVM type system.)
353*e038c9c4Sjoerg   if (GV->getValueType() != Init->getType()) {
3547330f729Sjoerg     llvm::GlobalVariable *OldGV = GV;
3557330f729Sjoerg 
356*e038c9c4Sjoerg     GV = new llvm::GlobalVariable(
357*e038c9c4Sjoerg         CGM.getModule(), Init->getType(), OldGV->isConstant(),
3587330f729Sjoerg         OldGV->getLinkage(), Init, "",
359*e038c9c4Sjoerg         /*InsertBefore*/ OldGV, OldGV->getThreadLocalMode(),
360*e038c9c4Sjoerg         OldGV->getType()->getPointerAddressSpace());
3617330f729Sjoerg     GV->setVisibility(OldGV->getVisibility());
3627330f729Sjoerg     GV->setDSOLocal(OldGV->isDSOLocal());
3637330f729Sjoerg     GV->setComdat(OldGV->getComdat());
3647330f729Sjoerg 
3657330f729Sjoerg     // Steal the name of the old global
3667330f729Sjoerg     GV->takeName(OldGV);
3677330f729Sjoerg 
3687330f729Sjoerg     // Replace all uses of the old global with the new global
3697330f729Sjoerg     llvm::Constant *NewPtrForOldDecl =
3707330f729Sjoerg     llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
3717330f729Sjoerg     OldGV->replaceAllUsesWith(NewPtrForOldDecl);
3727330f729Sjoerg 
3737330f729Sjoerg     // Erase the old global, since it is no longer used.
3747330f729Sjoerg     OldGV->eraseFromParent();
3757330f729Sjoerg   }
3767330f729Sjoerg 
3777330f729Sjoerg   GV->setConstant(CGM.isTypeConstant(D.getType(), true));
3787330f729Sjoerg   GV->setInitializer(Init);
3797330f729Sjoerg 
3807330f729Sjoerg   emitter.finalize(GV);
3817330f729Sjoerg 
382*e038c9c4Sjoerg   if (D.needsDestruction(getContext()) == QualType::DK_cxx_destructor &&
383*e038c9c4Sjoerg       HaveInsertPoint()) {
3847330f729Sjoerg     // We have a constant initializer, but a nontrivial destructor. We still
3857330f729Sjoerg     // need to perform a guarded "initialization" in order to register the
3867330f729Sjoerg     // destructor.
3877330f729Sjoerg     EmitCXXGuardedInit(D, GV, /*PerformInit*/false);
3887330f729Sjoerg   }
3897330f729Sjoerg 
3907330f729Sjoerg   return GV;
3917330f729Sjoerg }
3927330f729Sjoerg 
EmitStaticVarDecl(const VarDecl & D,llvm::GlobalValue::LinkageTypes Linkage)3937330f729Sjoerg void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
3947330f729Sjoerg                                       llvm::GlobalValue::LinkageTypes Linkage) {
3957330f729Sjoerg   // Check to see if we already have a global variable for this
3967330f729Sjoerg   // declaration.  This can happen when double-emitting function
3977330f729Sjoerg   // bodies, e.g. with complete and base constructors.
3987330f729Sjoerg   llvm::Constant *addr = CGM.getOrCreateStaticVarDecl(D, Linkage);
3997330f729Sjoerg   CharUnits alignment = getContext().getDeclAlign(&D);
4007330f729Sjoerg 
4017330f729Sjoerg   // Store into LocalDeclMap before generating initializer to handle
4027330f729Sjoerg   // circular references.
4037330f729Sjoerg   setAddrOfLocalVar(&D, Address(addr, alignment));
4047330f729Sjoerg 
4057330f729Sjoerg   // We can't have a VLA here, but we can have a pointer to a VLA,
4067330f729Sjoerg   // even though that doesn't really make any sense.
4077330f729Sjoerg   // Make sure to evaluate VLA bounds now so that we have them for later.
4087330f729Sjoerg   if (D.getType()->isVariablyModifiedType())
4097330f729Sjoerg     EmitVariablyModifiedType(D.getType());
4107330f729Sjoerg 
4117330f729Sjoerg   // Save the type in case adding the initializer forces a type change.
4127330f729Sjoerg   llvm::Type *expectedType = addr->getType();
4137330f729Sjoerg 
4147330f729Sjoerg   llvm::GlobalVariable *var =
4157330f729Sjoerg     cast<llvm::GlobalVariable>(addr->stripPointerCasts());
4167330f729Sjoerg 
4177330f729Sjoerg   // CUDA's local and local static __shared__ variables should not
4187330f729Sjoerg   // have any non-empty initializers. This is ensured by Sema.
4197330f729Sjoerg   // Whatever initializer such variable may have when it gets here is
4207330f729Sjoerg   // a no-op and should not be emitted.
4217330f729Sjoerg   bool isCudaSharedVar = getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
4227330f729Sjoerg                          D.hasAttr<CUDASharedAttr>();
4237330f729Sjoerg   // If this value has an initializer, emit it.
4247330f729Sjoerg   if (D.getInit() && !isCudaSharedVar)
4257330f729Sjoerg     var = AddInitializerToStaticVarDecl(D, var);
4267330f729Sjoerg 
4277330f729Sjoerg   var->setAlignment(alignment.getAsAlign());
4287330f729Sjoerg 
4297330f729Sjoerg   if (D.hasAttr<AnnotateAttr>())
4307330f729Sjoerg     CGM.AddGlobalAnnotations(&D, var);
4317330f729Sjoerg 
4327330f729Sjoerg   if (auto *SA = D.getAttr<PragmaClangBSSSectionAttr>())
4337330f729Sjoerg     var->addAttribute("bss-section", SA->getName());
4347330f729Sjoerg   if (auto *SA = D.getAttr<PragmaClangDataSectionAttr>())
4357330f729Sjoerg     var->addAttribute("data-section", SA->getName());
4367330f729Sjoerg   if (auto *SA = D.getAttr<PragmaClangRodataSectionAttr>())
4377330f729Sjoerg     var->addAttribute("rodata-section", SA->getName());
4387330f729Sjoerg   if (auto *SA = D.getAttr<PragmaClangRelroSectionAttr>())
4397330f729Sjoerg     var->addAttribute("relro-section", SA->getName());
4407330f729Sjoerg 
4417330f729Sjoerg   if (const SectionAttr *SA = D.getAttr<SectionAttr>())
4427330f729Sjoerg     var->setSection(SA->getName());
4437330f729Sjoerg 
444*e038c9c4Sjoerg   if (D.hasAttr<RetainAttr>())
4457330f729Sjoerg     CGM.addUsedGlobal(var);
446*e038c9c4Sjoerg   else if (D.hasAttr<UsedAttr>())
447*e038c9c4Sjoerg     CGM.addUsedOrCompilerUsedGlobal(var);
4487330f729Sjoerg 
4497330f729Sjoerg   // We may have to cast the constant because of the initializer
4507330f729Sjoerg   // mismatch above.
4517330f729Sjoerg   //
4527330f729Sjoerg   // FIXME: It is really dangerous to store this in the map; if anyone
4537330f729Sjoerg   // RAUW's the GV uses of this constant will be invalid.
4547330f729Sjoerg   llvm::Constant *castedAddr =
4557330f729Sjoerg     llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(var, expectedType);
4567330f729Sjoerg   if (var != castedAddr)
4577330f729Sjoerg     LocalDeclMap.find(&D)->second = Address(castedAddr, alignment);
4587330f729Sjoerg   CGM.setStaticLocalDeclAddress(&D, castedAddr);
4597330f729Sjoerg 
4607330f729Sjoerg   CGM.getSanitizerMetadata()->reportGlobalToASan(var, D);
4617330f729Sjoerg 
4627330f729Sjoerg   // Emit global variable debug descriptor for static vars.
4637330f729Sjoerg   CGDebugInfo *DI = getDebugInfo();
464*e038c9c4Sjoerg   if (DI && CGM.getCodeGenOpts().hasReducedDebugInfo()) {
4657330f729Sjoerg     DI->setLocation(D.getLocation());
4667330f729Sjoerg     DI->EmitGlobalVariable(var, &D);
4677330f729Sjoerg   }
4687330f729Sjoerg }
4697330f729Sjoerg 
4707330f729Sjoerg namespace {
4717330f729Sjoerg   struct DestroyObject final : EHScopeStack::Cleanup {
DestroyObject__anon76247d8b0111::DestroyObject4727330f729Sjoerg     DestroyObject(Address addr, QualType type,
4737330f729Sjoerg                   CodeGenFunction::Destroyer *destroyer,
4747330f729Sjoerg                   bool useEHCleanupForArray)
4757330f729Sjoerg       : addr(addr), type(type), destroyer(destroyer),
4767330f729Sjoerg         useEHCleanupForArray(useEHCleanupForArray) {}
4777330f729Sjoerg 
4787330f729Sjoerg     Address addr;
4797330f729Sjoerg     QualType type;
4807330f729Sjoerg     CodeGenFunction::Destroyer *destroyer;
4817330f729Sjoerg     bool useEHCleanupForArray;
4827330f729Sjoerg 
Emit__anon76247d8b0111::DestroyObject4837330f729Sjoerg     void Emit(CodeGenFunction &CGF, Flags flags) override {
4847330f729Sjoerg       // Don't use an EH cleanup recursively from an EH cleanup.
4857330f729Sjoerg       bool useEHCleanupForArray =
4867330f729Sjoerg         flags.isForNormalCleanup() && this->useEHCleanupForArray;
4877330f729Sjoerg 
4887330f729Sjoerg       CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
4897330f729Sjoerg     }
4907330f729Sjoerg   };
4917330f729Sjoerg 
4927330f729Sjoerg   template <class Derived>
4937330f729Sjoerg   struct DestroyNRVOVariable : EHScopeStack::Cleanup {
DestroyNRVOVariable__anon76247d8b0111::DestroyNRVOVariable4947330f729Sjoerg     DestroyNRVOVariable(Address addr, QualType type, llvm::Value *NRVOFlag)
4957330f729Sjoerg         : NRVOFlag(NRVOFlag), Loc(addr), Ty(type) {}
4967330f729Sjoerg 
4977330f729Sjoerg     llvm::Value *NRVOFlag;
4987330f729Sjoerg     Address Loc;
4997330f729Sjoerg     QualType Ty;
5007330f729Sjoerg 
Emit__anon76247d8b0111::DestroyNRVOVariable5017330f729Sjoerg     void Emit(CodeGenFunction &CGF, Flags flags) override {
5027330f729Sjoerg       // Along the exceptions path we always execute the dtor.
5037330f729Sjoerg       bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
5047330f729Sjoerg 
5057330f729Sjoerg       llvm::BasicBlock *SkipDtorBB = nullptr;
5067330f729Sjoerg       if (NRVO) {
5077330f729Sjoerg         // If we exited via NRVO, we skip the destructor call.
5087330f729Sjoerg         llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
5097330f729Sjoerg         SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
5107330f729Sjoerg         llvm::Value *DidNRVO =
5117330f729Sjoerg           CGF.Builder.CreateFlagLoad(NRVOFlag, "nrvo.val");
5127330f729Sjoerg         CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
5137330f729Sjoerg         CGF.EmitBlock(RunDtorBB);
5147330f729Sjoerg       }
5157330f729Sjoerg 
5167330f729Sjoerg       static_cast<Derived *>(this)->emitDestructorCall(CGF);
5177330f729Sjoerg 
5187330f729Sjoerg       if (NRVO) CGF.EmitBlock(SkipDtorBB);
5197330f729Sjoerg     }
5207330f729Sjoerg 
5217330f729Sjoerg     virtual ~DestroyNRVOVariable() = default;
5227330f729Sjoerg   };
5237330f729Sjoerg 
5247330f729Sjoerg   struct DestroyNRVOVariableCXX final
5257330f729Sjoerg       : DestroyNRVOVariable<DestroyNRVOVariableCXX> {
DestroyNRVOVariableCXX__anon76247d8b0111::DestroyNRVOVariableCXX5267330f729Sjoerg     DestroyNRVOVariableCXX(Address addr, QualType type,
5277330f729Sjoerg                            const CXXDestructorDecl *Dtor, llvm::Value *NRVOFlag)
5287330f729Sjoerg         : DestroyNRVOVariable<DestroyNRVOVariableCXX>(addr, type, NRVOFlag),
5297330f729Sjoerg           Dtor(Dtor) {}
5307330f729Sjoerg 
5317330f729Sjoerg     const CXXDestructorDecl *Dtor;
5327330f729Sjoerg 
emitDestructorCall__anon76247d8b0111::DestroyNRVOVariableCXX5337330f729Sjoerg     void emitDestructorCall(CodeGenFunction &CGF) {
5347330f729Sjoerg       CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
5357330f729Sjoerg                                 /*ForVirtualBase=*/false,
5367330f729Sjoerg                                 /*Delegating=*/false, Loc, Ty);
5377330f729Sjoerg     }
5387330f729Sjoerg   };
5397330f729Sjoerg 
5407330f729Sjoerg   struct DestroyNRVOVariableC final
5417330f729Sjoerg       : DestroyNRVOVariable<DestroyNRVOVariableC> {
DestroyNRVOVariableC__anon76247d8b0111::DestroyNRVOVariableC5427330f729Sjoerg     DestroyNRVOVariableC(Address addr, llvm::Value *NRVOFlag, QualType Ty)
5437330f729Sjoerg         : DestroyNRVOVariable<DestroyNRVOVariableC>(addr, Ty, NRVOFlag) {}
5447330f729Sjoerg 
emitDestructorCall__anon76247d8b0111::DestroyNRVOVariableC5457330f729Sjoerg     void emitDestructorCall(CodeGenFunction &CGF) {
5467330f729Sjoerg       CGF.destroyNonTrivialCStruct(CGF, Loc, Ty);
5477330f729Sjoerg     }
5487330f729Sjoerg   };
5497330f729Sjoerg 
5507330f729Sjoerg   struct CallStackRestore final : EHScopeStack::Cleanup {
5517330f729Sjoerg     Address Stack;
CallStackRestore__anon76247d8b0111::CallStackRestore5527330f729Sjoerg     CallStackRestore(Address Stack) : Stack(Stack) {}
isRedundantBeforeReturn__anon76247d8b0111::CallStackRestore553*e038c9c4Sjoerg     bool isRedundantBeforeReturn() override { return true; }
Emit__anon76247d8b0111::CallStackRestore5547330f729Sjoerg     void Emit(CodeGenFunction &CGF, Flags flags) override {
5557330f729Sjoerg       llvm::Value *V = CGF.Builder.CreateLoad(Stack);
5567330f729Sjoerg       llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
5577330f729Sjoerg       CGF.Builder.CreateCall(F, V);
5587330f729Sjoerg     }
5597330f729Sjoerg   };
5607330f729Sjoerg 
5617330f729Sjoerg   struct ExtendGCLifetime final : EHScopeStack::Cleanup {
5627330f729Sjoerg     const VarDecl &Var;
ExtendGCLifetime__anon76247d8b0111::ExtendGCLifetime5637330f729Sjoerg     ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
5647330f729Sjoerg 
Emit__anon76247d8b0111::ExtendGCLifetime5657330f729Sjoerg     void Emit(CodeGenFunction &CGF, Flags flags) override {
5667330f729Sjoerg       // Compute the address of the local variable, in case it's a
5677330f729Sjoerg       // byref or something.
5687330f729Sjoerg       DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(&Var), false,
5697330f729Sjoerg                       Var.getType(), VK_LValue, SourceLocation());
5707330f729Sjoerg       llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE),
5717330f729Sjoerg                                                 SourceLocation());
5727330f729Sjoerg       CGF.EmitExtendGCLifetime(value);
5737330f729Sjoerg     }
5747330f729Sjoerg   };
5757330f729Sjoerg 
5767330f729Sjoerg   struct CallCleanupFunction final : EHScopeStack::Cleanup {
5777330f729Sjoerg     llvm::Constant *CleanupFn;
5787330f729Sjoerg     const CGFunctionInfo &FnInfo;
5797330f729Sjoerg     const VarDecl &Var;
5807330f729Sjoerg 
CallCleanupFunction__anon76247d8b0111::CallCleanupFunction5817330f729Sjoerg     CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
5827330f729Sjoerg                         const VarDecl *Var)
5837330f729Sjoerg       : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
5847330f729Sjoerg 
Emit__anon76247d8b0111::CallCleanupFunction5857330f729Sjoerg     void Emit(CodeGenFunction &CGF, Flags flags) override {
5867330f729Sjoerg       DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(&Var), false,
5877330f729Sjoerg                       Var.getType(), VK_LValue, SourceLocation());
5887330f729Sjoerg       // Compute the address of the local variable, in case it's a byref
5897330f729Sjoerg       // or something.
590*e038c9c4Sjoerg       llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getPointer(CGF);
5917330f729Sjoerg 
5927330f729Sjoerg       // In some cases, the type of the function argument will be different from
5937330f729Sjoerg       // the type of the pointer. An example of this is
5947330f729Sjoerg       // void f(void* arg);
5957330f729Sjoerg       // __attribute__((cleanup(f))) void *g;
5967330f729Sjoerg       //
5977330f729Sjoerg       // To fix this we insert a bitcast here.
5987330f729Sjoerg       QualType ArgTy = FnInfo.arg_begin()->type;
5997330f729Sjoerg       llvm::Value *Arg =
6007330f729Sjoerg         CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
6017330f729Sjoerg 
6027330f729Sjoerg       CallArgList Args;
6037330f729Sjoerg       Args.add(RValue::get(Arg),
6047330f729Sjoerg                CGF.getContext().getPointerType(Var.getType()));
6057330f729Sjoerg       auto Callee = CGCallee::forDirect(CleanupFn);
6067330f729Sjoerg       CGF.EmitCall(FnInfo, Callee, ReturnValueSlot(), Args);
6077330f729Sjoerg     }
6087330f729Sjoerg   };
6097330f729Sjoerg } // end anonymous namespace
6107330f729Sjoerg 
6117330f729Sjoerg /// EmitAutoVarWithLifetime - Does the setup required for an automatic
6127330f729Sjoerg /// variable with lifetime.
EmitAutoVarWithLifetime(CodeGenFunction & CGF,const VarDecl & var,Address addr,Qualifiers::ObjCLifetime lifetime)6137330f729Sjoerg static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
6147330f729Sjoerg                                     Address addr,
6157330f729Sjoerg                                     Qualifiers::ObjCLifetime lifetime) {
6167330f729Sjoerg   switch (lifetime) {
6177330f729Sjoerg   case Qualifiers::OCL_None:
6187330f729Sjoerg     llvm_unreachable("present but none");
6197330f729Sjoerg 
6207330f729Sjoerg   case Qualifiers::OCL_ExplicitNone:
6217330f729Sjoerg     // nothing to do
6227330f729Sjoerg     break;
6237330f729Sjoerg 
6247330f729Sjoerg   case Qualifiers::OCL_Strong: {
6257330f729Sjoerg     CodeGenFunction::Destroyer *destroyer =
6267330f729Sjoerg       (var.hasAttr<ObjCPreciseLifetimeAttr>()
6277330f729Sjoerg        ? CodeGenFunction::destroyARCStrongPrecise
6287330f729Sjoerg        : CodeGenFunction::destroyARCStrongImprecise);
6297330f729Sjoerg 
6307330f729Sjoerg     CleanupKind cleanupKind = CGF.getARCCleanupKind();
6317330f729Sjoerg     CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
6327330f729Sjoerg                     cleanupKind & EHCleanup);
6337330f729Sjoerg     break;
6347330f729Sjoerg   }
6357330f729Sjoerg   case Qualifiers::OCL_Autoreleasing:
6367330f729Sjoerg     // nothing to do
6377330f729Sjoerg     break;
6387330f729Sjoerg 
6397330f729Sjoerg   case Qualifiers::OCL_Weak:
6407330f729Sjoerg     // __weak objects always get EH cleanups; otherwise, exceptions
6417330f729Sjoerg     // could cause really nasty crashes instead of mere leaks.
6427330f729Sjoerg     CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
6437330f729Sjoerg                     CodeGenFunction::destroyARCWeak,
6447330f729Sjoerg                     /*useEHCleanup*/ true);
6457330f729Sjoerg     break;
6467330f729Sjoerg   }
6477330f729Sjoerg }
6487330f729Sjoerg 
isAccessedBy(const VarDecl & var,const Stmt * s)6497330f729Sjoerg static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
6507330f729Sjoerg   if (const Expr *e = dyn_cast<Expr>(s)) {
6517330f729Sjoerg     // Skip the most common kinds of expressions that make
6527330f729Sjoerg     // hierarchy-walking expensive.
6537330f729Sjoerg     s = e = e->IgnoreParenCasts();
6547330f729Sjoerg 
6557330f729Sjoerg     if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
6567330f729Sjoerg       return (ref->getDecl() == &var);
6577330f729Sjoerg     if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
6587330f729Sjoerg       const BlockDecl *block = be->getBlockDecl();
6597330f729Sjoerg       for (const auto &I : block->captures()) {
6607330f729Sjoerg         if (I.getVariable() == &var)
6617330f729Sjoerg           return true;
6627330f729Sjoerg       }
6637330f729Sjoerg     }
6647330f729Sjoerg   }
6657330f729Sjoerg 
6667330f729Sjoerg   for (const Stmt *SubStmt : s->children())
6677330f729Sjoerg     // SubStmt might be null; as in missing decl or conditional of an if-stmt.
6687330f729Sjoerg     if (SubStmt && isAccessedBy(var, SubStmt))
6697330f729Sjoerg       return true;
6707330f729Sjoerg 
6717330f729Sjoerg   return false;
6727330f729Sjoerg }
6737330f729Sjoerg 
isAccessedBy(const ValueDecl * decl,const Expr * e)6747330f729Sjoerg static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
6757330f729Sjoerg   if (!decl) return false;
6767330f729Sjoerg   if (!isa<VarDecl>(decl)) return false;
6777330f729Sjoerg   const VarDecl *var = cast<VarDecl>(decl);
6787330f729Sjoerg   return isAccessedBy(*var, e);
6797330f729Sjoerg }
6807330f729Sjoerg 
tryEmitARCCopyWeakInit(CodeGenFunction & CGF,const LValue & destLV,const Expr * init)6817330f729Sjoerg static bool tryEmitARCCopyWeakInit(CodeGenFunction &CGF,
6827330f729Sjoerg                                    const LValue &destLV, const Expr *init) {
6837330f729Sjoerg   bool needsCast = false;
6847330f729Sjoerg 
6857330f729Sjoerg   while (auto castExpr = dyn_cast<CastExpr>(init->IgnoreParens())) {
6867330f729Sjoerg     switch (castExpr->getCastKind()) {
6877330f729Sjoerg     // Look through casts that don't require representation changes.
6887330f729Sjoerg     case CK_NoOp:
6897330f729Sjoerg     case CK_BitCast:
6907330f729Sjoerg     case CK_BlockPointerToObjCPointerCast:
6917330f729Sjoerg       needsCast = true;
6927330f729Sjoerg       break;
6937330f729Sjoerg 
6947330f729Sjoerg     // If we find an l-value to r-value cast from a __weak variable,
6957330f729Sjoerg     // emit this operation as a copy or move.
6967330f729Sjoerg     case CK_LValueToRValue: {
6977330f729Sjoerg       const Expr *srcExpr = castExpr->getSubExpr();
6987330f729Sjoerg       if (srcExpr->getType().getObjCLifetime() != Qualifiers::OCL_Weak)
6997330f729Sjoerg         return false;
7007330f729Sjoerg 
7017330f729Sjoerg       // Emit the source l-value.
7027330f729Sjoerg       LValue srcLV = CGF.EmitLValue(srcExpr);
7037330f729Sjoerg 
7047330f729Sjoerg       // Handle a formal type change to avoid asserting.
705*e038c9c4Sjoerg       auto srcAddr = srcLV.getAddress(CGF);
7067330f729Sjoerg       if (needsCast) {
707*e038c9c4Sjoerg         srcAddr = CGF.Builder.CreateElementBitCast(
708*e038c9c4Sjoerg             srcAddr, destLV.getAddress(CGF).getElementType());
7097330f729Sjoerg       }
7107330f729Sjoerg 
7117330f729Sjoerg       // If it was an l-value, use objc_copyWeak.
7127330f729Sjoerg       if (srcExpr->getValueKind() == VK_LValue) {
713*e038c9c4Sjoerg         CGF.EmitARCCopyWeak(destLV.getAddress(CGF), srcAddr);
7147330f729Sjoerg       } else {
7157330f729Sjoerg         assert(srcExpr->getValueKind() == VK_XValue);
716*e038c9c4Sjoerg         CGF.EmitARCMoveWeak(destLV.getAddress(CGF), srcAddr);
7177330f729Sjoerg       }
7187330f729Sjoerg       return true;
7197330f729Sjoerg     }
7207330f729Sjoerg 
7217330f729Sjoerg     // Stop at anything else.
7227330f729Sjoerg     default:
7237330f729Sjoerg       return false;
7247330f729Sjoerg     }
7257330f729Sjoerg 
7267330f729Sjoerg     init = castExpr->getSubExpr();
7277330f729Sjoerg   }
7287330f729Sjoerg   return false;
7297330f729Sjoerg }
7307330f729Sjoerg 
drillIntoBlockVariable(CodeGenFunction & CGF,LValue & lvalue,const VarDecl * var)7317330f729Sjoerg static void drillIntoBlockVariable(CodeGenFunction &CGF,
7327330f729Sjoerg                                    LValue &lvalue,
7337330f729Sjoerg                                    const VarDecl *var) {
734*e038c9c4Sjoerg   lvalue.setAddress(CGF.emitBlockByrefAddress(lvalue.getAddress(CGF), var));
7357330f729Sjoerg }
7367330f729Sjoerg 
EmitNullabilityCheck(LValue LHS,llvm::Value * RHS,SourceLocation Loc)7377330f729Sjoerg void CodeGenFunction::EmitNullabilityCheck(LValue LHS, llvm::Value *RHS,
7387330f729Sjoerg                                            SourceLocation Loc) {
7397330f729Sjoerg   if (!SanOpts.has(SanitizerKind::NullabilityAssign))
7407330f729Sjoerg     return;
7417330f729Sjoerg 
7427330f729Sjoerg   auto Nullability = LHS.getType()->getNullability(getContext());
7437330f729Sjoerg   if (!Nullability || *Nullability != NullabilityKind::NonNull)
7447330f729Sjoerg     return;
7457330f729Sjoerg 
7467330f729Sjoerg   // Check if the right hand side of the assignment is nonnull, if the left
7477330f729Sjoerg   // hand side must be nonnull.
7487330f729Sjoerg   SanitizerScope SanScope(this);
7497330f729Sjoerg   llvm::Value *IsNotNull = Builder.CreateIsNotNull(RHS);
7507330f729Sjoerg   llvm::Constant *StaticData[] = {
7517330f729Sjoerg       EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(LHS.getType()),
7527330f729Sjoerg       llvm::ConstantInt::get(Int8Ty, 0), // The LogAlignment info is unused.
7537330f729Sjoerg       llvm::ConstantInt::get(Int8Ty, TCK_NonnullAssign)};
7547330f729Sjoerg   EmitCheck({{IsNotNull, SanitizerKind::NullabilityAssign}},
7557330f729Sjoerg             SanitizerHandler::TypeMismatch, StaticData, RHS);
7567330f729Sjoerg }
7577330f729Sjoerg 
EmitScalarInit(const Expr * init,const ValueDecl * D,LValue lvalue,bool capturedByInit)7587330f729Sjoerg void CodeGenFunction::EmitScalarInit(const Expr *init, const ValueDecl *D,
7597330f729Sjoerg                                      LValue lvalue, bool capturedByInit) {
7607330f729Sjoerg   Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
7617330f729Sjoerg   if (!lifetime) {
7627330f729Sjoerg     llvm::Value *value = EmitScalarExpr(init);
7637330f729Sjoerg     if (capturedByInit)
7647330f729Sjoerg       drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
7657330f729Sjoerg     EmitNullabilityCheck(lvalue, value, init->getExprLoc());
7667330f729Sjoerg     EmitStoreThroughLValue(RValue::get(value), lvalue, true);
7677330f729Sjoerg     return;
7687330f729Sjoerg   }
7697330f729Sjoerg 
7707330f729Sjoerg   if (const CXXDefaultInitExpr *DIE = dyn_cast<CXXDefaultInitExpr>(init))
7717330f729Sjoerg     init = DIE->getExpr();
7727330f729Sjoerg 
7737330f729Sjoerg   // If we're emitting a value with lifetime, we have to do the
7747330f729Sjoerg   // initialization *before* we leave the cleanup scopes.
775*e038c9c4Sjoerg   if (auto *EWC = dyn_cast<ExprWithCleanups>(init)) {
7767330f729Sjoerg     CodeGenFunction::RunCleanupsScope Scope(*this);
777*e038c9c4Sjoerg     return EmitScalarInit(EWC->getSubExpr(), D, lvalue, capturedByInit);
778*e038c9c4Sjoerg   }
7797330f729Sjoerg 
7807330f729Sjoerg   // We have to maintain the illusion that the variable is
7817330f729Sjoerg   // zero-initialized.  If the variable might be accessed in its
7827330f729Sjoerg   // initializer, zero-initialize before running the initializer, then
7837330f729Sjoerg   // actually perform the initialization with an assign.
7847330f729Sjoerg   bool accessedByInit = false;
7857330f729Sjoerg   if (lifetime != Qualifiers::OCL_ExplicitNone)
7867330f729Sjoerg     accessedByInit = (capturedByInit || isAccessedBy(D, init));
7877330f729Sjoerg   if (accessedByInit) {
7887330f729Sjoerg     LValue tempLV = lvalue;
7897330f729Sjoerg     // Drill down to the __block object if necessary.
7907330f729Sjoerg     if (capturedByInit) {
7917330f729Sjoerg       // We can use a simple GEP for this because it can't have been
7927330f729Sjoerg       // moved yet.
793*e038c9c4Sjoerg       tempLV.setAddress(emitBlockByrefAddress(tempLV.getAddress(*this),
7947330f729Sjoerg                                               cast<VarDecl>(D),
7957330f729Sjoerg                                               /*follow*/ false));
7967330f729Sjoerg     }
7977330f729Sjoerg 
798*e038c9c4Sjoerg     auto ty =
799*e038c9c4Sjoerg         cast<llvm::PointerType>(tempLV.getAddress(*this).getElementType());
8007330f729Sjoerg     llvm::Value *zero = CGM.getNullPointer(ty, tempLV.getType());
8017330f729Sjoerg 
8027330f729Sjoerg     // If __weak, we want to use a barrier under certain conditions.
8037330f729Sjoerg     if (lifetime == Qualifiers::OCL_Weak)
804*e038c9c4Sjoerg       EmitARCInitWeak(tempLV.getAddress(*this), zero);
8057330f729Sjoerg 
8067330f729Sjoerg     // Otherwise just do a simple store.
8077330f729Sjoerg     else
8087330f729Sjoerg       EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
8097330f729Sjoerg   }
8107330f729Sjoerg 
8117330f729Sjoerg   // Emit the initializer.
8127330f729Sjoerg   llvm::Value *value = nullptr;
8137330f729Sjoerg 
8147330f729Sjoerg   switch (lifetime) {
8157330f729Sjoerg   case Qualifiers::OCL_None:
8167330f729Sjoerg     llvm_unreachable("present but none");
8177330f729Sjoerg 
8187330f729Sjoerg   case Qualifiers::OCL_Strong: {
8197330f729Sjoerg     if (!D || !isa<VarDecl>(D) || !cast<VarDecl>(D)->isARCPseudoStrong()) {
8207330f729Sjoerg       value = EmitARCRetainScalarExpr(init);
8217330f729Sjoerg       break;
8227330f729Sjoerg     }
8237330f729Sjoerg     // If D is pseudo-strong, treat it like __unsafe_unretained here. This means
8247330f729Sjoerg     // that we omit the retain, and causes non-autoreleased return values to be
8257330f729Sjoerg     // immediately released.
8267330f729Sjoerg     LLVM_FALLTHROUGH;
8277330f729Sjoerg   }
8287330f729Sjoerg 
8297330f729Sjoerg   case Qualifiers::OCL_ExplicitNone:
8307330f729Sjoerg     value = EmitARCUnsafeUnretainedScalarExpr(init);
8317330f729Sjoerg     break;
8327330f729Sjoerg 
8337330f729Sjoerg   case Qualifiers::OCL_Weak: {
8347330f729Sjoerg     // If it's not accessed by the initializer, try to emit the
8357330f729Sjoerg     // initialization with a copy or move.
8367330f729Sjoerg     if (!accessedByInit && tryEmitARCCopyWeakInit(*this, lvalue, init)) {
8377330f729Sjoerg       return;
8387330f729Sjoerg     }
8397330f729Sjoerg 
8407330f729Sjoerg     // No way to optimize a producing initializer into this.  It's not
8417330f729Sjoerg     // worth optimizing for, because the value will immediately
8427330f729Sjoerg     // disappear in the common case.
8437330f729Sjoerg     value = EmitScalarExpr(init);
8447330f729Sjoerg 
8457330f729Sjoerg     if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
8467330f729Sjoerg     if (accessedByInit)
847*e038c9c4Sjoerg       EmitARCStoreWeak(lvalue.getAddress(*this), value, /*ignored*/ true);
8487330f729Sjoerg     else
849*e038c9c4Sjoerg       EmitARCInitWeak(lvalue.getAddress(*this), value);
8507330f729Sjoerg     return;
8517330f729Sjoerg   }
8527330f729Sjoerg 
8537330f729Sjoerg   case Qualifiers::OCL_Autoreleasing:
8547330f729Sjoerg     value = EmitARCRetainAutoreleaseScalarExpr(init);
8557330f729Sjoerg     break;
8567330f729Sjoerg   }
8577330f729Sjoerg 
8587330f729Sjoerg   if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
8597330f729Sjoerg 
8607330f729Sjoerg   EmitNullabilityCheck(lvalue, value, init->getExprLoc());
8617330f729Sjoerg 
8627330f729Sjoerg   // If the variable might have been accessed by its initializer, we
8637330f729Sjoerg   // might have to initialize with a barrier.  We have to do this for
8647330f729Sjoerg   // both __weak and __strong, but __weak got filtered out above.
8657330f729Sjoerg   if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
8667330f729Sjoerg     llvm::Value *oldValue = EmitLoadOfScalar(lvalue, init->getExprLoc());
8677330f729Sjoerg     EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
8687330f729Sjoerg     EmitARCRelease(oldValue, ARCImpreciseLifetime);
8697330f729Sjoerg     return;
8707330f729Sjoerg   }
8717330f729Sjoerg 
8727330f729Sjoerg   EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
8737330f729Sjoerg }
8747330f729Sjoerg 
8757330f729Sjoerg /// Decide whether we can emit the non-zero parts of the specified initializer
8767330f729Sjoerg /// with equal or fewer than NumStores scalar stores.
canEmitInitWithFewStoresAfterBZero(llvm::Constant * Init,unsigned & NumStores)8777330f729Sjoerg static bool canEmitInitWithFewStoresAfterBZero(llvm::Constant *Init,
8787330f729Sjoerg                                                unsigned &NumStores) {
8797330f729Sjoerg   // Zero and Undef never requires any extra stores.
8807330f729Sjoerg   if (isa<llvm::ConstantAggregateZero>(Init) ||
8817330f729Sjoerg       isa<llvm::ConstantPointerNull>(Init) ||
8827330f729Sjoerg       isa<llvm::UndefValue>(Init))
8837330f729Sjoerg     return true;
8847330f729Sjoerg   if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
8857330f729Sjoerg       isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
8867330f729Sjoerg       isa<llvm::ConstantExpr>(Init))
8877330f729Sjoerg     return Init->isNullValue() || NumStores--;
8887330f729Sjoerg 
8897330f729Sjoerg   // See if we can emit each element.
8907330f729Sjoerg   if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
8917330f729Sjoerg     for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
8927330f729Sjoerg       llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
8937330f729Sjoerg       if (!canEmitInitWithFewStoresAfterBZero(Elt, NumStores))
8947330f729Sjoerg         return false;
8957330f729Sjoerg     }
8967330f729Sjoerg     return true;
8977330f729Sjoerg   }
8987330f729Sjoerg 
8997330f729Sjoerg   if (llvm::ConstantDataSequential *CDS =
9007330f729Sjoerg         dyn_cast<llvm::ConstantDataSequential>(Init)) {
9017330f729Sjoerg     for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
9027330f729Sjoerg       llvm::Constant *Elt = CDS->getElementAsConstant(i);
9037330f729Sjoerg       if (!canEmitInitWithFewStoresAfterBZero(Elt, NumStores))
9047330f729Sjoerg         return false;
9057330f729Sjoerg     }
9067330f729Sjoerg     return true;
9077330f729Sjoerg   }
9087330f729Sjoerg 
9097330f729Sjoerg   // Anything else is hard and scary.
9107330f729Sjoerg   return false;
9117330f729Sjoerg }
9127330f729Sjoerg 
9137330f729Sjoerg /// For inits that canEmitInitWithFewStoresAfterBZero returned true for, emit
9147330f729Sjoerg /// the scalar stores that would be required.
emitStoresForInitAfterBZero(CodeGenModule & CGM,llvm::Constant * Init,Address Loc,bool isVolatile,CGBuilderTy & Builder,bool IsAutoInit)9157330f729Sjoerg static void emitStoresForInitAfterBZero(CodeGenModule &CGM,
9167330f729Sjoerg                                         llvm::Constant *Init, Address Loc,
917*e038c9c4Sjoerg                                         bool isVolatile, CGBuilderTy &Builder,
918*e038c9c4Sjoerg                                         bool IsAutoInit) {
9197330f729Sjoerg   assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) &&
9207330f729Sjoerg          "called emitStoresForInitAfterBZero for zero or undef value.");
9217330f729Sjoerg 
9227330f729Sjoerg   if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
9237330f729Sjoerg       isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
9247330f729Sjoerg       isa<llvm::ConstantExpr>(Init)) {
925*e038c9c4Sjoerg     auto *I = Builder.CreateStore(Init, Loc, isVolatile);
926*e038c9c4Sjoerg     if (IsAutoInit)
927*e038c9c4Sjoerg       I->addAnnotationMetadata("auto-init");
9287330f729Sjoerg     return;
9297330f729Sjoerg   }
9307330f729Sjoerg 
9317330f729Sjoerg   if (llvm::ConstantDataSequential *CDS =
9327330f729Sjoerg           dyn_cast<llvm::ConstantDataSequential>(Init)) {
9337330f729Sjoerg     for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
9347330f729Sjoerg       llvm::Constant *Elt = CDS->getElementAsConstant(i);
9357330f729Sjoerg 
9367330f729Sjoerg       // If necessary, get a pointer to the element and emit it.
9377330f729Sjoerg       if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
9387330f729Sjoerg         emitStoresForInitAfterBZero(
9397330f729Sjoerg             CGM, Elt, Builder.CreateConstInBoundsGEP2_32(Loc, 0, i), isVolatile,
940*e038c9c4Sjoerg             Builder, IsAutoInit);
9417330f729Sjoerg     }
9427330f729Sjoerg     return;
9437330f729Sjoerg   }
9447330f729Sjoerg 
9457330f729Sjoerg   assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
9467330f729Sjoerg          "Unknown value type!");
9477330f729Sjoerg 
9487330f729Sjoerg   for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
9497330f729Sjoerg     llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
9507330f729Sjoerg 
9517330f729Sjoerg     // If necessary, get a pointer to the element and emit it.
9527330f729Sjoerg     if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
9537330f729Sjoerg       emitStoresForInitAfterBZero(CGM, Elt,
9547330f729Sjoerg                                   Builder.CreateConstInBoundsGEP2_32(Loc, 0, i),
955*e038c9c4Sjoerg                                   isVolatile, Builder, IsAutoInit);
9567330f729Sjoerg   }
9577330f729Sjoerg }
9587330f729Sjoerg 
9597330f729Sjoerg /// Decide whether we should use bzero plus some stores to initialize a local
9607330f729Sjoerg /// variable instead of using a memcpy from a constant global.  It is beneficial
9617330f729Sjoerg /// to use bzero if the global is all zeros, or mostly zeros and large.
shouldUseBZeroPlusStoresToInitialize(llvm::Constant * Init,uint64_t GlobalSize)9627330f729Sjoerg static bool shouldUseBZeroPlusStoresToInitialize(llvm::Constant *Init,
9637330f729Sjoerg                                                  uint64_t GlobalSize) {
9647330f729Sjoerg   // If a global is all zeros, always use a bzero.
9657330f729Sjoerg   if (isa<llvm::ConstantAggregateZero>(Init)) return true;
9667330f729Sjoerg 
9677330f729Sjoerg   // If a non-zero global is <= 32 bytes, always use a memcpy.  If it is large,
9687330f729Sjoerg   // do it if it will require 6 or fewer scalar stores.
9697330f729Sjoerg   // TODO: Should budget depends on the size?  Avoiding a large global warrants
9707330f729Sjoerg   // plopping in more stores.
9717330f729Sjoerg   unsigned StoreBudget = 6;
9727330f729Sjoerg   uint64_t SizeLimit = 32;
9737330f729Sjoerg 
9747330f729Sjoerg   return GlobalSize > SizeLimit &&
9757330f729Sjoerg          canEmitInitWithFewStoresAfterBZero(Init, StoreBudget);
9767330f729Sjoerg }
9777330f729Sjoerg 
9787330f729Sjoerg /// Decide whether we should use memset to initialize a local variable instead
9797330f729Sjoerg /// of using a memcpy from a constant global. Assumes we've already decided to
9807330f729Sjoerg /// not user bzero.
9817330f729Sjoerg /// FIXME We could be more clever, as we are for bzero above, and generate
9827330f729Sjoerg ///       memset followed by stores. It's unclear that's worth the effort.
shouldUseMemSetToInitialize(llvm::Constant * Init,uint64_t GlobalSize,const llvm::DataLayout & DL)9837330f729Sjoerg static llvm::Value *shouldUseMemSetToInitialize(llvm::Constant *Init,
9847330f729Sjoerg                                                 uint64_t GlobalSize,
9857330f729Sjoerg                                                 const llvm::DataLayout &DL) {
9867330f729Sjoerg   uint64_t SizeLimit = 32;
9877330f729Sjoerg   if (GlobalSize <= SizeLimit)
9887330f729Sjoerg     return nullptr;
9897330f729Sjoerg   return llvm::isBytewiseValue(Init, DL);
9907330f729Sjoerg }
9917330f729Sjoerg 
9927330f729Sjoerg /// Decide whether we want to split a constant structure or array store into a
9937330f729Sjoerg /// sequence of its fields' stores. This may cost us code size and compilation
9947330f729Sjoerg /// speed, but plays better with store optimizations.
shouldSplitConstantStore(CodeGenModule & CGM,uint64_t GlobalByteSize)9957330f729Sjoerg static bool shouldSplitConstantStore(CodeGenModule &CGM,
9967330f729Sjoerg                                      uint64_t GlobalByteSize) {
9977330f729Sjoerg   // Don't break things that occupy more than one cacheline.
9987330f729Sjoerg   uint64_t ByteSizeLimit = 64;
9997330f729Sjoerg   if (CGM.getCodeGenOpts().OptimizationLevel == 0)
10007330f729Sjoerg     return false;
10017330f729Sjoerg   if (GlobalByteSize <= ByteSizeLimit)
10027330f729Sjoerg     return true;
10037330f729Sjoerg   return false;
10047330f729Sjoerg }
10057330f729Sjoerg 
10067330f729Sjoerg enum class IsPattern { No, Yes };
10077330f729Sjoerg 
10087330f729Sjoerg /// Generate a constant filled with either a pattern or zeroes.
patternOrZeroFor(CodeGenModule & CGM,IsPattern isPattern,llvm::Type * Ty)10097330f729Sjoerg static llvm::Constant *patternOrZeroFor(CodeGenModule &CGM, IsPattern isPattern,
10107330f729Sjoerg                                         llvm::Type *Ty) {
10117330f729Sjoerg   if (isPattern == IsPattern::Yes)
10127330f729Sjoerg     return initializationPatternFor(CGM, Ty);
10137330f729Sjoerg   else
10147330f729Sjoerg     return llvm::Constant::getNullValue(Ty);
10157330f729Sjoerg }
10167330f729Sjoerg 
10177330f729Sjoerg static llvm::Constant *constWithPadding(CodeGenModule &CGM, IsPattern isPattern,
10187330f729Sjoerg                                         llvm::Constant *constant);
10197330f729Sjoerg 
10207330f729Sjoerg /// Helper function for constWithPadding() to deal with padding in structures.
constStructWithPadding(CodeGenModule & CGM,IsPattern isPattern,llvm::StructType * STy,llvm::Constant * constant)10217330f729Sjoerg static llvm::Constant *constStructWithPadding(CodeGenModule &CGM,
10227330f729Sjoerg                                               IsPattern isPattern,
10237330f729Sjoerg                                               llvm::StructType *STy,
10247330f729Sjoerg                                               llvm::Constant *constant) {
10257330f729Sjoerg   const llvm::DataLayout &DL = CGM.getDataLayout();
10267330f729Sjoerg   const llvm::StructLayout *Layout = DL.getStructLayout(STy);
10277330f729Sjoerg   llvm::Type *Int8Ty = llvm::IntegerType::getInt8Ty(CGM.getLLVMContext());
10287330f729Sjoerg   unsigned SizeSoFar = 0;
10297330f729Sjoerg   SmallVector<llvm::Constant *, 8> Values;
10307330f729Sjoerg   bool NestedIntact = true;
10317330f729Sjoerg   for (unsigned i = 0, e = STy->getNumElements(); i != e; i++) {
10327330f729Sjoerg     unsigned CurOff = Layout->getElementOffset(i);
10337330f729Sjoerg     if (SizeSoFar < CurOff) {
10347330f729Sjoerg       assert(!STy->isPacked());
10357330f729Sjoerg       auto *PadTy = llvm::ArrayType::get(Int8Ty, CurOff - SizeSoFar);
10367330f729Sjoerg       Values.push_back(patternOrZeroFor(CGM, isPattern, PadTy));
10377330f729Sjoerg     }
10387330f729Sjoerg     llvm::Constant *CurOp;
10397330f729Sjoerg     if (constant->isZeroValue())
10407330f729Sjoerg       CurOp = llvm::Constant::getNullValue(STy->getElementType(i));
10417330f729Sjoerg     else
10427330f729Sjoerg       CurOp = cast<llvm::Constant>(constant->getAggregateElement(i));
10437330f729Sjoerg     auto *NewOp = constWithPadding(CGM, isPattern, CurOp);
10447330f729Sjoerg     if (CurOp != NewOp)
10457330f729Sjoerg       NestedIntact = false;
10467330f729Sjoerg     Values.push_back(NewOp);
10477330f729Sjoerg     SizeSoFar = CurOff + DL.getTypeAllocSize(CurOp->getType());
10487330f729Sjoerg   }
10497330f729Sjoerg   unsigned TotalSize = Layout->getSizeInBytes();
10507330f729Sjoerg   if (SizeSoFar < TotalSize) {
10517330f729Sjoerg     auto *PadTy = llvm::ArrayType::get(Int8Ty, TotalSize - SizeSoFar);
10527330f729Sjoerg     Values.push_back(patternOrZeroFor(CGM, isPattern, PadTy));
10537330f729Sjoerg   }
10547330f729Sjoerg   if (NestedIntact && Values.size() == STy->getNumElements())
10557330f729Sjoerg     return constant;
10567330f729Sjoerg   return llvm::ConstantStruct::getAnon(Values, STy->isPacked());
10577330f729Sjoerg }
10587330f729Sjoerg 
10597330f729Sjoerg /// Replace all padding bytes in a given constant with either a pattern byte or
10607330f729Sjoerg /// 0x00.
constWithPadding(CodeGenModule & CGM,IsPattern isPattern,llvm::Constant * constant)10617330f729Sjoerg static llvm::Constant *constWithPadding(CodeGenModule &CGM, IsPattern isPattern,
10627330f729Sjoerg                                         llvm::Constant *constant) {
10637330f729Sjoerg   llvm::Type *OrigTy = constant->getType();
10647330f729Sjoerg   if (const auto STy = dyn_cast<llvm::StructType>(OrigTy))
10657330f729Sjoerg     return constStructWithPadding(CGM, isPattern, STy, constant);
1066*e038c9c4Sjoerg   if (auto *ArrayTy = dyn_cast<llvm::ArrayType>(OrigTy)) {
10677330f729Sjoerg     llvm::SmallVector<llvm::Constant *, 8> Values;
1068*e038c9c4Sjoerg     uint64_t Size = ArrayTy->getNumElements();
10697330f729Sjoerg     if (!Size)
10707330f729Sjoerg       return constant;
1071*e038c9c4Sjoerg     llvm::Type *ElemTy = ArrayTy->getElementType();
1072*e038c9c4Sjoerg     bool ZeroInitializer = constant->isNullValue();
10737330f729Sjoerg     llvm::Constant *OpValue, *PaddedOp;
10747330f729Sjoerg     if (ZeroInitializer) {
10757330f729Sjoerg       OpValue = llvm::Constant::getNullValue(ElemTy);
10767330f729Sjoerg       PaddedOp = constWithPadding(CGM, isPattern, OpValue);
10777330f729Sjoerg     }
10787330f729Sjoerg     for (unsigned Op = 0; Op != Size; ++Op) {
10797330f729Sjoerg       if (!ZeroInitializer) {
10807330f729Sjoerg         OpValue = constant->getAggregateElement(Op);
10817330f729Sjoerg         PaddedOp = constWithPadding(CGM, isPattern, OpValue);
10827330f729Sjoerg       }
10837330f729Sjoerg       Values.push_back(PaddedOp);
10847330f729Sjoerg     }
10857330f729Sjoerg     auto *NewElemTy = Values[0]->getType();
10867330f729Sjoerg     if (NewElemTy == ElemTy)
10877330f729Sjoerg       return constant;
1088*e038c9c4Sjoerg     auto *NewArrayTy = llvm::ArrayType::get(NewElemTy, Size);
1089*e038c9c4Sjoerg     return llvm::ConstantArray::get(NewArrayTy, Values);
10907330f729Sjoerg   }
1091*e038c9c4Sjoerg   // FIXME: Add handling for tail padding in vectors. Vectors don't
1092*e038c9c4Sjoerg   // have padding between or inside elements, but the total amount of
1093*e038c9c4Sjoerg   // data can be less than the allocated size.
10947330f729Sjoerg   return constant;
10957330f729Sjoerg }
10967330f729Sjoerg 
createUnnamedGlobalFrom(const VarDecl & D,llvm::Constant * Constant,CharUnits Align)10977330f729Sjoerg Address CodeGenModule::createUnnamedGlobalFrom(const VarDecl &D,
10987330f729Sjoerg                                                llvm::Constant *Constant,
10997330f729Sjoerg                                                CharUnits Align) {
11007330f729Sjoerg   auto FunctionName = [&](const DeclContext *DC) -> std::string {
11017330f729Sjoerg     if (const auto *FD = dyn_cast<FunctionDecl>(DC)) {
11027330f729Sjoerg       if (const auto *CC = dyn_cast<CXXConstructorDecl>(FD))
11037330f729Sjoerg         return CC->getNameAsString();
11047330f729Sjoerg       if (const auto *CD = dyn_cast<CXXDestructorDecl>(FD))
11057330f729Sjoerg         return CD->getNameAsString();
1106*e038c9c4Sjoerg       return std::string(getMangledName(FD));
11077330f729Sjoerg     } else if (const auto *OM = dyn_cast<ObjCMethodDecl>(DC)) {
11087330f729Sjoerg       return OM->getNameAsString();
11097330f729Sjoerg     } else if (isa<BlockDecl>(DC)) {
11107330f729Sjoerg       return "<block>";
11117330f729Sjoerg     } else if (isa<CapturedDecl>(DC)) {
11127330f729Sjoerg       return "<captured>";
11137330f729Sjoerg     } else {
11147330f729Sjoerg       llvm_unreachable("expected a function or method");
11157330f729Sjoerg     }
11167330f729Sjoerg   };
11177330f729Sjoerg 
11187330f729Sjoerg   // Form a simple per-variable cache of these values in case we find we
11197330f729Sjoerg   // want to reuse them.
11207330f729Sjoerg   llvm::GlobalVariable *&CacheEntry = InitializerConstants[&D];
11217330f729Sjoerg   if (!CacheEntry || CacheEntry->getInitializer() != Constant) {
11227330f729Sjoerg     auto *Ty = Constant->getType();
11237330f729Sjoerg     bool isConstant = true;
11247330f729Sjoerg     llvm::GlobalVariable *InsertBefore = nullptr;
11257330f729Sjoerg     unsigned AS =
1126*e038c9c4Sjoerg         getContext().getTargetAddressSpace(GetGlobalConstantAddressSpace());
11277330f729Sjoerg     std::string Name;
11287330f729Sjoerg     if (D.hasGlobalStorage())
11297330f729Sjoerg       Name = getMangledName(&D).str() + ".const";
11307330f729Sjoerg     else if (const DeclContext *DC = D.getParentFunctionOrMethod())
11317330f729Sjoerg       Name = ("__const." + FunctionName(DC) + "." + D.getName()).str();
11327330f729Sjoerg     else
11337330f729Sjoerg       llvm_unreachable("local variable has no parent function or method");
11347330f729Sjoerg     llvm::GlobalVariable *GV = new llvm::GlobalVariable(
11357330f729Sjoerg         getModule(), Ty, isConstant, llvm::GlobalValue::PrivateLinkage,
11367330f729Sjoerg         Constant, Name, InsertBefore, llvm::GlobalValue::NotThreadLocal, AS);
11377330f729Sjoerg     GV->setAlignment(Align.getAsAlign());
11387330f729Sjoerg     GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
11397330f729Sjoerg     CacheEntry = GV;
11407330f729Sjoerg   } else if (CacheEntry->getAlignment() < Align.getQuantity()) {
11417330f729Sjoerg     CacheEntry->setAlignment(Align.getAsAlign());
11427330f729Sjoerg   }
11437330f729Sjoerg 
11447330f729Sjoerg   return Address(CacheEntry, Align);
11457330f729Sjoerg }
11467330f729Sjoerg 
createUnnamedGlobalForMemcpyFrom(CodeGenModule & CGM,const VarDecl & D,CGBuilderTy & Builder,llvm::Constant * Constant,CharUnits Align)11477330f729Sjoerg static Address createUnnamedGlobalForMemcpyFrom(CodeGenModule &CGM,
11487330f729Sjoerg                                                 const VarDecl &D,
11497330f729Sjoerg                                                 CGBuilderTy &Builder,
11507330f729Sjoerg                                                 llvm::Constant *Constant,
11517330f729Sjoerg                                                 CharUnits Align) {
11527330f729Sjoerg   Address SrcPtr = CGM.createUnnamedGlobalFrom(D, Constant, Align);
11537330f729Sjoerg   llvm::Type *BP = llvm::PointerType::getInt8PtrTy(CGM.getLLVMContext(),
11547330f729Sjoerg                                                    SrcPtr.getAddressSpace());
11557330f729Sjoerg   if (SrcPtr.getType() != BP)
11567330f729Sjoerg     SrcPtr = Builder.CreateBitCast(SrcPtr, BP);
11577330f729Sjoerg   return SrcPtr;
11587330f729Sjoerg }
11597330f729Sjoerg 
emitStoresForConstant(CodeGenModule & CGM,const VarDecl & D,Address Loc,bool isVolatile,CGBuilderTy & Builder,llvm::Constant * constant,bool IsAutoInit)11607330f729Sjoerg static void emitStoresForConstant(CodeGenModule &CGM, const VarDecl &D,
11617330f729Sjoerg                                   Address Loc, bool isVolatile,
11627330f729Sjoerg                                   CGBuilderTy &Builder,
1163*e038c9c4Sjoerg                                   llvm::Constant *constant, bool IsAutoInit) {
11647330f729Sjoerg   auto *Ty = constant->getType();
11657330f729Sjoerg   uint64_t ConstantSize = CGM.getDataLayout().getTypeAllocSize(Ty);
11667330f729Sjoerg   if (!ConstantSize)
11677330f729Sjoerg     return;
11687330f729Sjoerg 
11697330f729Sjoerg   bool canDoSingleStore = Ty->isIntOrIntVectorTy() ||
11707330f729Sjoerg                           Ty->isPtrOrPtrVectorTy() || Ty->isFPOrFPVectorTy();
11717330f729Sjoerg   if (canDoSingleStore) {
1172*e038c9c4Sjoerg     auto *I = Builder.CreateStore(constant, Loc, isVolatile);
1173*e038c9c4Sjoerg     if (IsAutoInit)
1174*e038c9c4Sjoerg       I->addAnnotationMetadata("auto-init");
11757330f729Sjoerg     return;
11767330f729Sjoerg   }
11777330f729Sjoerg 
11787330f729Sjoerg   auto *SizeVal = llvm::ConstantInt::get(CGM.IntPtrTy, ConstantSize);
11797330f729Sjoerg 
11807330f729Sjoerg   // If the initializer is all or mostly the same, codegen with bzero / memset
11817330f729Sjoerg   // then do a few stores afterward.
11827330f729Sjoerg   if (shouldUseBZeroPlusStoresToInitialize(constant, ConstantSize)) {
1183*e038c9c4Sjoerg     auto *I = Builder.CreateMemSet(Loc, llvm::ConstantInt::get(CGM.Int8Ty, 0),
1184*e038c9c4Sjoerg                                    SizeVal, isVolatile);
1185*e038c9c4Sjoerg     if (IsAutoInit)
1186*e038c9c4Sjoerg       I->addAnnotationMetadata("auto-init");
11877330f729Sjoerg 
11887330f729Sjoerg     bool valueAlreadyCorrect =
11897330f729Sjoerg         constant->isNullValue() || isa<llvm::UndefValue>(constant);
11907330f729Sjoerg     if (!valueAlreadyCorrect) {
11917330f729Sjoerg       Loc = Builder.CreateBitCast(Loc, Ty->getPointerTo(Loc.getAddressSpace()));
1192*e038c9c4Sjoerg       emitStoresForInitAfterBZero(CGM, constant, Loc, isVolatile, Builder,
1193*e038c9c4Sjoerg                                   IsAutoInit);
11947330f729Sjoerg     }
11957330f729Sjoerg     return;
11967330f729Sjoerg   }
11977330f729Sjoerg 
11987330f729Sjoerg   // If the initializer is a repeated byte pattern, use memset.
11997330f729Sjoerg   llvm::Value *Pattern =
12007330f729Sjoerg       shouldUseMemSetToInitialize(constant, ConstantSize, CGM.getDataLayout());
12017330f729Sjoerg   if (Pattern) {
12027330f729Sjoerg     uint64_t Value = 0x00;
12037330f729Sjoerg     if (!isa<llvm::UndefValue>(Pattern)) {
12047330f729Sjoerg       const llvm::APInt &AP = cast<llvm::ConstantInt>(Pattern)->getValue();
12057330f729Sjoerg       assert(AP.getBitWidth() <= 8);
12067330f729Sjoerg       Value = AP.getLimitedValue();
12077330f729Sjoerg     }
1208*e038c9c4Sjoerg     auto *I = Builder.CreateMemSet(
1209*e038c9c4Sjoerg         Loc, llvm::ConstantInt::get(CGM.Int8Ty, Value), SizeVal, isVolatile);
1210*e038c9c4Sjoerg     if (IsAutoInit)
1211*e038c9c4Sjoerg       I->addAnnotationMetadata("auto-init");
12127330f729Sjoerg     return;
12137330f729Sjoerg   }
12147330f729Sjoerg 
12157330f729Sjoerg   // If the initializer is small, use a handful of stores.
12167330f729Sjoerg   if (shouldSplitConstantStore(CGM, ConstantSize)) {
12177330f729Sjoerg     if (auto *STy = dyn_cast<llvm::StructType>(Ty)) {
12187330f729Sjoerg       // FIXME: handle the case when STy != Loc.getElementType().
12197330f729Sjoerg       if (STy == Loc.getElementType()) {
12207330f729Sjoerg         for (unsigned i = 0; i != constant->getNumOperands(); i++) {
12217330f729Sjoerg           Address EltPtr = Builder.CreateStructGEP(Loc, i);
12227330f729Sjoerg           emitStoresForConstant(
12237330f729Sjoerg               CGM, D, EltPtr, isVolatile, Builder,
1224*e038c9c4Sjoerg               cast<llvm::Constant>(Builder.CreateExtractValue(constant, i)),
1225*e038c9c4Sjoerg               IsAutoInit);
12267330f729Sjoerg         }
12277330f729Sjoerg         return;
12287330f729Sjoerg       }
12297330f729Sjoerg     } else if (auto *ATy = dyn_cast<llvm::ArrayType>(Ty)) {
12307330f729Sjoerg       // FIXME: handle the case when ATy != Loc.getElementType().
12317330f729Sjoerg       if (ATy == Loc.getElementType()) {
12327330f729Sjoerg         for (unsigned i = 0; i != ATy->getNumElements(); i++) {
12337330f729Sjoerg           Address EltPtr = Builder.CreateConstArrayGEP(Loc, i);
12347330f729Sjoerg           emitStoresForConstant(
12357330f729Sjoerg               CGM, D, EltPtr, isVolatile, Builder,
1236*e038c9c4Sjoerg               cast<llvm::Constant>(Builder.CreateExtractValue(constant, i)),
1237*e038c9c4Sjoerg               IsAutoInit);
12387330f729Sjoerg         }
12397330f729Sjoerg         return;
12407330f729Sjoerg       }
12417330f729Sjoerg     }
12427330f729Sjoerg   }
12437330f729Sjoerg 
12447330f729Sjoerg   // Copy from a global.
1245*e038c9c4Sjoerg   auto *I =
12467330f729Sjoerg       Builder.CreateMemCpy(Loc,
12477330f729Sjoerg                            createUnnamedGlobalForMemcpyFrom(
12487330f729Sjoerg                                CGM, D, Builder, constant, Loc.getAlignment()),
12497330f729Sjoerg                            SizeVal, isVolatile);
1250*e038c9c4Sjoerg   if (IsAutoInit)
1251*e038c9c4Sjoerg     I->addAnnotationMetadata("auto-init");
12527330f729Sjoerg }
12537330f729Sjoerg 
emitStoresForZeroInit(CodeGenModule & CGM,const VarDecl & D,Address Loc,bool isVolatile,CGBuilderTy & Builder)12547330f729Sjoerg static void emitStoresForZeroInit(CodeGenModule &CGM, const VarDecl &D,
12557330f729Sjoerg                                   Address Loc, bool isVolatile,
12567330f729Sjoerg                                   CGBuilderTy &Builder) {
12577330f729Sjoerg   llvm::Type *ElTy = Loc.getElementType();
12587330f729Sjoerg   llvm::Constant *constant =
12597330f729Sjoerg       constWithPadding(CGM, IsPattern::No, llvm::Constant::getNullValue(ElTy));
1260*e038c9c4Sjoerg   emitStoresForConstant(CGM, D, Loc, isVolatile, Builder, constant,
1261*e038c9c4Sjoerg                         /*IsAutoInit=*/true);
12627330f729Sjoerg }
12637330f729Sjoerg 
emitStoresForPatternInit(CodeGenModule & CGM,const VarDecl & D,Address Loc,bool isVolatile,CGBuilderTy & Builder)12647330f729Sjoerg static void emitStoresForPatternInit(CodeGenModule &CGM, const VarDecl &D,
12657330f729Sjoerg                                      Address Loc, bool isVolatile,
12667330f729Sjoerg                                      CGBuilderTy &Builder) {
12677330f729Sjoerg   llvm::Type *ElTy = Loc.getElementType();
12687330f729Sjoerg   llvm::Constant *constant = constWithPadding(
12697330f729Sjoerg       CGM, IsPattern::Yes, initializationPatternFor(CGM, ElTy));
12707330f729Sjoerg   assert(!isa<llvm::UndefValue>(constant));
1271*e038c9c4Sjoerg   emitStoresForConstant(CGM, D, Loc, isVolatile, Builder, constant,
1272*e038c9c4Sjoerg                         /*IsAutoInit=*/true);
12737330f729Sjoerg }
12747330f729Sjoerg 
containsUndef(llvm::Constant * constant)12757330f729Sjoerg static bool containsUndef(llvm::Constant *constant) {
12767330f729Sjoerg   auto *Ty = constant->getType();
12777330f729Sjoerg   if (isa<llvm::UndefValue>(constant))
12787330f729Sjoerg     return true;
12797330f729Sjoerg   if (Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy())
12807330f729Sjoerg     for (llvm::Use &Op : constant->operands())
12817330f729Sjoerg       if (containsUndef(cast<llvm::Constant>(Op)))
12827330f729Sjoerg         return true;
12837330f729Sjoerg   return false;
12847330f729Sjoerg }
12857330f729Sjoerg 
replaceUndef(CodeGenModule & CGM,IsPattern isPattern,llvm::Constant * constant)12867330f729Sjoerg static llvm::Constant *replaceUndef(CodeGenModule &CGM, IsPattern isPattern,
12877330f729Sjoerg                                     llvm::Constant *constant) {
12887330f729Sjoerg   auto *Ty = constant->getType();
12897330f729Sjoerg   if (isa<llvm::UndefValue>(constant))
12907330f729Sjoerg     return patternOrZeroFor(CGM, isPattern, Ty);
12917330f729Sjoerg   if (!(Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()))
12927330f729Sjoerg     return constant;
12937330f729Sjoerg   if (!containsUndef(constant))
12947330f729Sjoerg     return constant;
12957330f729Sjoerg   llvm::SmallVector<llvm::Constant *, 8> Values(constant->getNumOperands());
12967330f729Sjoerg   for (unsigned Op = 0, NumOp = constant->getNumOperands(); Op != NumOp; ++Op) {
12977330f729Sjoerg     auto *OpValue = cast<llvm::Constant>(constant->getOperand(Op));
12987330f729Sjoerg     Values[Op] = replaceUndef(CGM, isPattern, OpValue);
12997330f729Sjoerg   }
13007330f729Sjoerg   if (Ty->isStructTy())
13017330f729Sjoerg     return llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Values);
13027330f729Sjoerg   if (Ty->isArrayTy())
13037330f729Sjoerg     return llvm::ConstantArray::get(cast<llvm::ArrayType>(Ty), Values);
13047330f729Sjoerg   assert(Ty->isVectorTy());
13057330f729Sjoerg   return llvm::ConstantVector::get(Values);
13067330f729Sjoerg }
13077330f729Sjoerg 
13087330f729Sjoerg /// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
13097330f729Sjoerg /// variable declaration with auto, register, or no storage class specifier.
13107330f729Sjoerg /// These turn into simple stack objects, or GlobalValues depending on target.
EmitAutoVarDecl(const VarDecl & D)13117330f729Sjoerg void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
13127330f729Sjoerg   AutoVarEmission emission = EmitAutoVarAlloca(D);
13137330f729Sjoerg   EmitAutoVarInit(emission);
13147330f729Sjoerg   EmitAutoVarCleanups(emission);
13157330f729Sjoerg }
13167330f729Sjoerg 
13177330f729Sjoerg /// Emit a lifetime.begin marker if some criteria are satisfied.
13187330f729Sjoerg /// \return a pointer to the temporary size Value if a marker was emitted, null
13197330f729Sjoerg /// otherwise
EmitLifetimeStart(uint64_t Size,llvm::Value * Addr)13207330f729Sjoerg llvm::Value *CodeGenFunction::EmitLifetimeStart(uint64_t Size,
13217330f729Sjoerg                                                 llvm::Value *Addr) {
13227330f729Sjoerg   if (!ShouldEmitLifetimeMarkers)
13237330f729Sjoerg     return nullptr;
13247330f729Sjoerg 
13257330f729Sjoerg   assert(Addr->getType()->getPointerAddressSpace() ==
13267330f729Sjoerg              CGM.getDataLayout().getAllocaAddrSpace() &&
13277330f729Sjoerg          "Pointer should be in alloca address space");
13287330f729Sjoerg   llvm::Value *SizeV = llvm::ConstantInt::get(Int64Ty, Size);
13297330f729Sjoerg   Addr = Builder.CreateBitCast(Addr, AllocaInt8PtrTy);
13307330f729Sjoerg   llvm::CallInst *C =
13317330f729Sjoerg       Builder.CreateCall(CGM.getLLVMLifetimeStartFn(), {SizeV, Addr});
13327330f729Sjoerg   C->setDoesNotThrow();
13337330f729Sjoerg   return SizeV;
13347330f729Sjoerg }
13357330f729Sjoerg 
EmitLifetimeEnd(llvm::Value * Size,llvm::Value * Addr)13367330f729Sjoerg void CodeGenFunction::EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr) {
13377330f729Sjoerg   assert(Addr->getType()->getPointerAddressSpace() ==
13387330f729Sjoerg              CGM.getDataLayout().getAllocaAddrSpace() &&
13397330f729Sjoerg          "Pointer should be in alloca address space");
13407330f729Sjoerg   Addr = Builder.CreateBitCast(Addr, AllocaInt8PtrTy);
13417330f729Sjoerg   llvm::CallInst *C =
13427330f729Sjoerg       Builder.CreateCall(CGM.getLLVMLifetimeEndFn(), {Size, Addr});
13437330f729Sjoerg   C->setDoesNotThrow();
13447330f729Sjoerg }
13457330f729Sjoerg 
EmitAndRegisterVariableArrayDimensions(CGDebugInfo * DI,const VarDecl & D,bool EmitDebugInfo)13467330f729Sjoerg void CodeGenFunction::EmitAndRegisterVariableArrayDimensions(
13477330f729Sjoerg     CGDebugInfo *DI, const VarDecl &D, bool EmitDebugInfo) {
13487330f729Sjoerg   // For each dimension stores its QualType and corresponding
13497330f729Sjoerg   // size-expression Value.
13507330f729Sjoerg   SmallVector<CodeGenFunction::VlaSizePair, 4> Dimensions;
13517330f729Sjoerg   SmallVector<IdentifierInfo *, 4> VLAExprNames;
13527330f729Sjoerg 
13537330f729Sjoerg   // Break down the array into individual dimensions.
13547330f729Sjoerg   QualType Type1D = D.getType();
13557330f729Sjoerg   while (getContext().getAsVariableArrayType(Type1D)) {
13567330f729Sjoerg     auto VlaSize = getVLAElements1D(Type1D);
13577330f729Sjoerg     if (auto *C = dyn_cast<llvm::ConstantInt>(VlaSize.NumElts))
13587330f729Sjoerg       Dimensions.emplace_back(C, Type1D.getUnqualifiedType());
13597330f729Sjoerg     else {
13607330f729Sjoerg       // Generate a locally unique name for the size expression.
13617330f729Sjoerg       Twine Name = Twine("__vla_expr") + Twine(VLAExprCounter++);
13627330f729Sjoerg       SmallString<12> Buffer;
13637330f729Sjoerg       StringRef NameRef = Name.toStringRef(Buffer);
13647330f729Sjoerg       auto &Ident = getContext().Idents.getOwn(NameRef);
13657330f729Sjoerg       VLAExprNames.push_back(&Ident);
13667330f729Sjoerg       auto SizeExprAddr =
13677330f729Sjoerg           CreateDefaultAlignTempAlloca(VlaSize.NumElts->getType(), NameRef);
13687330f729Sjoerg       Builder.CreateStore(VlaSize.NumElts, SizeExprAddr);
13697330f729Sjoerg       Dimensions.emplace_back(SizeExprAddr.getPointer(),
13707330f729Sjoerg                               Type1D.getUnqualifiedType());
13717330f729Sjoerg     }
13727330f729Sjoerg     Type1D = VlaSize.Type;
13737330f729Sjoerg   }
13747330f729Sjoerg 
13757330f729Sjoerg   if (!EmitDebugInfo)
13767330f729Sjoerg     return;
13777330f729Sjoerg 
13787330f729Sjoerg   // Register each dimension's size-expression with a DILocalVariable,
13797330f729Sjoerg   // so that it can be used by CGDebugInfo when instantiating a DISubrange
13807330f729Sjoerg   // to describe this array.
13817330f729Sjoerg   unsigned NameIdx = 0;
13827330f729Sjoerg   for (auto &VlaSize : Dimensions) {
13837330f729Sjoerg     llvm::Metadata *MD;
13847330f729Sjoerg     if (auto *C = dyn_cast<llvm::ConstantInt>(VlaSize.NumElts))
13857330f729Sjoerg       MD = llvm::ConstantAsMetadata::get(C);
13867330f729Sjoerg     else {
13877330f729Sjoerg       // Create an artificial VarDecl to generate debug info for.
13887330f729Sjoerg       IdentifierInfo *NameIdent = VLAExprNames[NameIdx++];
13897330f729Sjoerg       auto VlaExprTy = VlaSize.NumElts->getType()->getPointerElementType();
13907330f729Sjoerg       auto QT = getContext().getIntTypeForBitwidth(
13917330f729Sjoerg           VlaExprTy->getScalarSizeInBits(), false);
13927330f729Sjoerg       auto *ArtificialDecl = VarDecl::Create(
13937330f729Sjoerg           getContext(), const_cast<DeclContext *>(D.getDeclContext()),
13947330f729Sjoerg           D.getLocation(), D.getLocation(), NameIdent, QT,
13957330f729Sjoerg           getContext().CreateTypeSourceInfo(QT), SC_Auto);
13967330f729Sjoerg       ArtificialDecl->setImplicit();
13977330f729Sjoerg 
13987330f729Sjoerg       MD = DI->EmitDeclareOfAutoVariable(ArtificialDecl, VlaSize.NumElts,
13997330f729Sjoerg                                          Builder);
14007330f729Sjoerg     }
14017330f729Sjoerg     assert(MD && "No Size expression debug node created");
14027330f729Sjoerg     DI->registerVLASizeExpression(VlaSize.Type, MD);
14037330f729Sjoerg   }
14047330f729Sjoerg }
14057330f729Sjoerg 
14067330f729Sjoerg /// EmitAutoVarAlloca - Emit the alloca and debug information for a
14077330f729Sjoerg /// local variable.  Does not emit initialization or destruction.
14087330f729Sjoerg CodeGenFunction::AutoVarEmission
EmitAutoVarAlloca(const VarDecl & D)14097330f729Sjoerg CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
14107330f729Sjoerg   QualType Ty = D.getType();
14117330f729Sjoerg   assert(
14127330f729Sjoerg       Ty.getAddressSpace() == LangAS::Default ||
14137330f729Sjoerg       (Ty.getAddressSpace() == LangAS::opencl_private && getLangOpts().OpenCL));
14147330f729Sjoerg 
14157330f729Sjoerg   AutoVarEmission emission(D);
14167330f729Sjoerg 
14177330f729Sjoerg   bool isEscapingByRef = D.isEscapingByref();
14187330f729Sjoerg   emission.IsEscapingByRef = isEscapingByRef;
14197330f729Sjoerg 
14207330f729Sjoerg   CharUnits alignment = getContext().getDeclAlign(&D);
14217330f729Sjoerg 
14227330f729Sjoerg   // If the type is variably-modified, emit all the VLA sizes for it.
14237330f729Sjoerg   if (Ty->isVariablyModifiedType())
14247330f729Sjoerg     EmitVariablyModifiedType(Ty);
14257330f729Sjoerg 
14267330f729Sjoerg   auto *DI = getDebugInfo();
1427*e038c9c4Sjoerg   bool EmitDebugInfo = DI && CGM.getCodeGenOpts().hasReducedDebugInfo();
14287330f729Sjoerg 
14297330f729Sjoerg   Address address = Address::invalid();
14307330f729Sjoerg   Address AllocaAddr = Address::invalid();
1431*e038c9c4Sjoerg   Address OpenMPLocalAddr = Address::invalid();
1432*e038c9c4Sjoerg   if (CGM.getLangOpts().OpenMPIRBuilder)
1433*e038c9c4Sjoerg     OpenMPLocalAddr = OMPBuilderCBHelpers::getAddressOfLocalVariable(*this, &D);
1434*e038c9c4Sjoerg   else
1435*e038c9c4Sjoerg     OpenMPLocalAddr =
14367330f729Sjoerg         getLangOpts().OpenMP
14377330f729Sjoerg             ? CGM.getOpenMPRuntime().getAddressOfLocalVariable(*this, &D)
14387330f729Sjoerg             : Address::invalid();
1439*e038c9c4Sjoerg 
14407330f729Sjoerg   bool NRVO = getLangOpts().ElideConstructors && D.isNRVOVariable();
14417330f729Sjoerg 
14427330f729Sjoerg   if (getLangOpts().OpenMP && OpenMPLocalAddr.isValid()) {
14437330f729Sjoerg     address = OpenMPLocalAddr;
14447330f729Sjoerg   } else if (Ty->isConstantSizeType()) {
14457330f729Sjoerg     // If this value is an array or struct with a statically determinable
14467330f729Sjoerg     // constant initializer, there are optimizations we can do.
14477330f729Sjoerg     //
14487330f729Sjoerg     // TODO: We should constant-evaluate the initializer of any variable,
14497330f729Sjoerg     // as long as it is initialized by a constant expression. Currently,
14507330f729Sjoerg     // isConstantInitializer produces wrong answers for structs with
14517330f729Sjoerg     // reference or bitfield members, and a few other cases, and checking
14527330f729Sjoerg     // for POD-ness protects us from some of these.
14537330f729Sjoerg     if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) &&
14547330f729Sjoerg         (D.isConstexpr() ||
14557330f729Sjoerg          ((Ty.isPODType(getContext()) ||
14567330f729Sjoerg            getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
14577330f729Sjoerg           D.getInit()->isConstantInitializer(getContext(), false)))) {
14587330f729Sjoerg 
14597330f729Sjoerg       // If the variable's a const type, and it's neither an NRVO
14607330f729Sjoerg       // candidate nor a __block variable and has no mutable members,
14617330f729Sjoerg       // emit it as a global instead.
14627330f729Sjoerg       // Exception is if a variable is located in non-constant address space
14637330f729Sjoerg       // in OpenCL.
14647330f729Sjoerg       if ((!getLangOpts().OpenCL ||
14657330f729Sjoerg            Ty.getAddressSpace() == LangAS::opencl_constant) &&
14667330f729Sjoerg           (CGM.getCodeGenOpts().MergeAllConstants && !NRVO &&
14677330f729Sjoerg            !isEscapingByRef && CGM.isTypeConstant(Ty, true))) {
14687330f729Sjoerg         EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
14697330f729Sjoerg 
14707330f729Sjoerg         // Signal this condition to later callbacks.
14717330f729Sjoerg         emission.Addr = Address::invalid();
14727330f729Sjoerg         assert(emission.wasEmittedAsGlobal());
14737330f729Sjoerg         return emission;
14747330f729Sjoerg       }
14757330f729Sjoerg 
14767330f729Sjoerg       // Otherwise, tell the initialization code that we're in this case.
14777330f729Sjoerg       emission.IsConstantAggregate = true;
14787330f729Sjoerg     }
14797330f729Sjoerg 
14807330f729Sjoerg     // A normal fixed sized variable becomes an alloca in the entry block,
14817330f729Sjoerg     // unless:
14827330f729Sjoerg     // - it's an NRVO variable.
14837330f729Sjoerg     // - we are compiling OpenMP and it's an OpenMP local variable.
14847330f729Sjoerg     if (NRVO) {
14857330f729Sjoerg       // The named return value optimization: allocate this variable in the
14867330f729Sjoerg       // return slot, so that we can elide the copy when returning this
14877330f729Sjoerg       // variable (C++0x [class.copy]p34).
14887330f729Sjoerg       address = ReturnValue;
14897330f729Sjoerg 
14907330f729Sjoerg       if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
14917330f729Sjoerg         const auto *RD = RecordTy->getDecl();
14927330f729Sjoerg         const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
14937330f729Sjoerg         if ((CXXRD && !CXXRD->hasTrivialDestructor()) ||
14947330f729Sjoerg             RD->isNonTrivialToPrimitiveDestroy()) {
14957330f729Sjoerg           // Create a flag that is used to indicate when the NRVO was applied
14967330f729Sjoerg           // to this variable. Set it to zero to indicate that NRVO was not
14977330f729Sjoerg           // applied.
14987330f729Sjoerg           llvm::Value *Zero = Builder.getFalse();
14997330f729Sjoerg           Address NRVOFlag =
15007330f729Sjoerg             CreateTempAlloca(Zero->getType(), CharUnits::One(), "nrvo");
15017330f729Sjoerg           EnsureInsertPoint();
15027330f729Sjoerg           Builder.CreateStore(Zero, NRVOFlag);
15037330f729Sjoerg 
15047330f729Sjoerg           // Record the NRVO flag for this variable.
15057330f729Sjoerg           NRVOFlags[&D] = NRVOFlag.getPointer();
15067330f729Sjoerg           emission.NRVOFlag = NRVOFlag.getPointer();
15077330f729Sjoerg         }
15087330f729Sjoerg       }
15097330f729Sjoerg     } else {
15107330f729Sjoerg       CharUnits allocaAlignment;
15117330f729Sjoerg       llvm::Type *allocaTy;
15127330f729Sjoerg       if (isEscapingByRef) {
15137330f729Sjoerg         auto &byrefInfo = getBlockByrefInfo(&D);
15147330f729Sjoerg         allocaTy = byrefInfo.Type;
15157330f729Sjoerg         allocaAlignment = byrefInfo.ByrefAlignment;
15167330f729Sjoerg       } else {
15177330f729Sjoerg         allocaTy = ConvertTypeForMem(Ty);
15187330f729Sjoerg         allocaAlignment = alignment;
15197330f729Sjoerg       }
15207330f729Sjoerg 
15217330f729Sjoerg       // Create the alloca.  Note that we set the name separately from
15227330f729Sjoerg       // building the instruction so that it's there even in no-asserts
15237330f729Sjoerg       // builds.
15247330f729Sjoerg       address = CreateTempAlloca(allocaTy, allocaAlignment, D.getName(),
15257330f729Sjoerg                                  /*ArraySize=*/nullptr, &AllocaAddr);
15267330f729Sjoerg 
15277330f729Sjoerg       // Don't emit lifetime markers for MSVC catch parameters. The lifetime of
15287330f729Sjoerg       // the catch parameter starts in the catchpad instruction, and we can't
15297330f729Sjoerg       // insert code in those basic blocks.
15307330f729Sjoerg       bool IsMSCatchParam =
15317330f729Sjoerg           D.isExceptionVariable() && getTarget().getCXXABI().isMicrosoft();
15327330f729Sjoerg 
15337330f729Sjoerg       // Emit a lifetime intrinsic if meaningful. There's no point in doing this
15347330f729Sjoerg       // if we don't have a valid insertion point (?).
15357330f729Sjoerg       if (HaveInsertPoint() && !IsMSCatchParam) {
15367330f729Sjoerg         // If there's a jump into the lifetime of this variable, its lifetime
15377330f729Sjoerg         // gets broken up into several regions in IR, which requires more work
15387330f729Sjoerg         // to handle correctly. For now, just omit the intrinsics; this is a
15397330f729Sjoerg         // rare case, and it's better to just be conservatively correct.
15407330f729Sjoerg         // PR28267.
15417330f729Sjoerg         //
15427330f729Sjoerg         // We have to do this in all language modes if there's a jump past the
15437330f729Sjoerg         // declaration. We also have to do it in C if there's a jump to an
15447330f729Sjoerg         // earlier point in the current block because non-VLA lifetimes begin as
15457330f729Sjoerg         // soon as the containing block is entered, not when its variables
15467330f729Sjoerg         // actually come into scope; suppressing the lifetime annotations
15477330f729Sjoerg         // completely in this case is unnecessarily pessimistic, but again, this
15487330f729Sjoerg         // is rare.
15497330f729Sjoerg         if (!Bypasses.IsBypassed(&D) &&
15507330f729Sjoerg             !(!getLangOpts().CPlusPlus && hasLabelBeenSeenInCurrentScope())) {
1551*e038c9c4Sjoerg           llvm::TypeSize size =
1552*e038c9c4Sjoerg               CGM.getDataLayout().getTypeAllocSize(allocaTy);
15537330f729Sjoerg           emission.SizeForLifetimeMarkers =
1554*e038c9c4Sjoerg               size.isScalable() ? EmitLifetimeStart(-1, AllocaAddr.getPointer())
1555*e038c9c4Sjoerg                                 : EmitLifetimeStart(size.getFixedSize(),
1556*e038c9c4Sjoerg                                                     AllocaAddr.getPointer());
15577330f729Sjoerg         }
15587330f729Sjoerg       } else {
15597330f729Sjoerg         assert(!emission.useLifetimeMarkers());
15607330f729Sjoerg       }
15617330f729Sjoerg     }
15627330f729Sjoerg   } else {
15637330f729Sjoerg     EnsureInsertPoint();
15647330f729Sjoerg 
15657330f729Sjoerg     if (!DidCallStackSave) {
15667330f729Sjoerg       // Save the stack.
15677330f729Sjoerg       Address Stack =
15687330f729Sjoerg         CreateTempAlloca(Int8PtrTy, getPointerAlign(), "saved_stack");
15697330f729Sjoerg 
15707330f729Sjoerg       llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
15717330f729Sjoerg       llvm::Value *V = Builder.CreateCall(F);
15727330f729Sjoerg       Builder.CreateStore(V, Stack);
15737330f729Sjoerg 
15747330f729Sjoerg       DidCallStackSave = true;
15757330f729Sjoerg 
15767330f729Sjoerg       // Push a cleanup block and restore the stack there.
15777330f729Sjoerg       // FIXME: in general circumstances, this should be an EH cleanup.
15787330f729Sjoerg       pushStackRestore(NormalCleanup, Stack);
15797330f729Sjoerg     }
15807330f729Sjoerg 
15817330f729Sjoerg     auto VlaSize = getVLASize(Ty);
15827330f729Sjoerg     llvm::Type *llvmTy = ConvertTypeForMem(VlaSize.Type);
15837330f729Sjoerg 
15847330f729Sjoerg     // Allocate memory for the array.
15857330f729Sjoerg     address = CreateTempAlloca(llvmTy, alignment, "vla", VlaSize.NumElts,
15867330f729Sjoerg                                &AllocaAddr);
15877330f729Sjoerg 
15887330f729Sjoerg     // If we have debug info enabled, properly describe the VLA dimensions for
15897330f729Sjoerg     // this type by registering the vla size expression for each of the
15907330f729Sjoerg     // dimensions.
15917330f729Sjoerg     EmitAndRegisterVariableArrayDimensions(DI, D, EmitDebugInfo);
15927330f729Sjoerg   }
15937330f729Sjoerg 
15947330f729Sjoerg   setAddrOfLocalVar(&D, address);
15957330f729Sjoerg   emission.Addr = address;
15967330f729Sjoerg   emission.AllocaAddr = AllocaAddr;
15977330f729Sjoerg 
15987330f729Sjoerg   // Emit debug info for local var declaration.
15997330f729Sjoerg   if (EmitDebugInfo && HaveInsertPoint()) {
16007330f729Sjoerg     Address DebugAddr = address;
16017330f729Sjoerg     bool UsePointerValue = NRVO && ReturnValuePointer.isValid();
16027330f729Sjoerg     DI->setLocation(D.getLocation());
16037330f729Sjoerg 
16047330f729Sjoerg     // If NRVO, use a pointer to the return address.
16057330f729Sjoerg     if (UsePointerValue)
16067330f729Sjoerg       DebugAddr = ReturnValuePointer;
16077330f729Sjoerg 
16087330f729Sjoerg     (void)DI->EmitDeclareOfAutoVariable(&D, DebugAddr.getPointer(), Builder,
16097330f729Sjoerg                                         UsePointerValue);
16107330f729Sjoerg   }
16117330f729Sjoerg 
16127330f729Sjoerg   if (D.hasAttr<AnnotateAttr>() && HaveInsertPoint())
16137330f729Sjoerg     EmitVarAnnotations(&D, address.getPointer());
16147330f729Sjoerg 
16157330f729Sjoerg   // Make sure we call @llvm.lifetime.end.
16167330f729Sjoerg   if (emission.useLifetimeMarkers())
16177330f729Sjoerg     EHStack.pushCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker,
16187330f729Sjoerg                                          emission.getOriginalAllocatedAddress(),
16197330f729Sjoerg                                          emission.getSizeForLifetimeMarkers());
16207330f729Sjoerg 
16217330f729Sjoerg   return emission;
16227330f729Sjoerg }
16237330f729Sjoerg 
16247330f729Sjoerg static bool isCapturedBy(const VarDecl &, const Expr *);
16257330f729Sjoerg 
16267330f729Sjoerg /// Determines whether the given __block variable is potentially
16277330f729Sjoerg /// captured by the given statement.
isCapturedBy(const VarDecl & Var,const Stmt * S)16287330f729Sjoerg static bool isCapturedBy(const VarDecl &Var, const Stmt *S) {
16297330f729Sjoerg   if (const Expr *E = dyn_cast<Expr>(S))
16307330f729Sjoerg     return isCapturedBy(Var, E);
16317330f729Sjoerg   for (const Stmt *SubStmt : S->children())
16327330f729Sjoerg     if (isCapturedBy(Var, SubStmt))
16337330f729Sjoerg       return true;
16347330f729Sjoerg   return false;
16357330f729Sjoerg }
16367330f729Sjoerg 
16377330f729Sjoerg /// Determines whether the given __block variable is potentially
16387330f729Sjoerg /// captured by the given expression.
isCapturedBy(const VarDecl & Var,const Expr * E)16397330f729Sjoerg static bool isCapturedBy(const VarDecl &Var, const Expr *E) {
16407330f729Sjoerg   // Skip the most common kinds of expressions that make
16417330f729Sjoerg   // hierarchy-walking expensive.
16427330f729Sjoerg   E = E->IgnoreParenCasts();
16437330f729Sjoerg 
16447330f729Sjoerg   if (const BlockExpr *BE = dyn_cast<BlockExpr>(E)) {
16457330f729Sjoerg     const BlockDecl *Block = BE->getBlockDecl();
16467330f729Sjoerg     for (const auto &I : Block->captures()) {
16477330f729Sjoerg       if (I.getVariable() == &Var)
16487330f729Sjoerg         return true;
16497330f729Sjoerg     }
16507330f729Sjoerg 
16517330f729Sjoerg     // No need to walk into the subexpressions.
16527330f729Sjoerg     return false;
16537330f729Sjoerg   }
16547330f729Sjoerg 
16557330f729Sjoerg   if (const StmtExpr *SE = dyn_cast<StmtExpr>(E)) {
16567330f729Sjoerg     const CompoundStmt *CS = SE->getSubStmt();
16577330f729Sjoerg     for (const auto *BI : CS->body())
16587330f729Sjoerg       if (const auto *BIE = dyn_cast<Expr>(BI)) {
16597330f729Sjoerg         if (isCapturedBy(Var, BIE))
16607330f729Sjoerg           return true;
16617330f729Sjoerg       }
16627330f729Sjoerg       else if (const auto *DS = dyn_cast<DeclStmt>(BI)) {
16637330f729Sjoerg           // special case declarations
16647330f729Sjoerg           for (const auto *I : DS->decls()) {
16657330f729Sjoerg               if (const auto *VD = dyn_cast<VarDecl>((I))) {
16667330f729Sjoerg                 const Expr *Init = VD->getInit();
16677330f729Sjoerg                 if (Init && isCapturedBy(Var, Init))
16687330f729Sjoerg                   return true;
16697330f729Sjoerg               }
16707330f729Sjoerg           }
16717330f729Sjoerg       }
16727330f729Sjoerg       else
16737330f729Sjoerg         // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
16747330f729Sjoerg         // Later, provide code to poke into statements for capture analysis.
16757330f729Sjoerg         return true;
16767330f729Sjoerg     return false;
16777330f729Sjoerg   }
16787330f729Sjoerg 
16797330f729Sjoerg   for (const Stmt *SubStmt : E->children())
16807330f729Sjoerg     if (isCapturedBy(Var, SubStmt))
16817330f729Sjoerg       return true;
16827330f729Sjoerg 
16837330f729Sjoerg   return false;
16847330f729Sjoerg }
16857330f729Sjoerg 
16867330f729Sjoerg /// Determine whether the given initializer is trivial in the sense
16877330f729Sjoerg /// that it requires no code to be generated.
isTrivialInitializer(const Expr * Init)16887330f729Sjoerg bool CodeGenFunction::isTrivialInitializer(const Expr *Init) {
16897330f729Sjoerg   if (!Init)
16907330f729Sjoerg     return true;
16917330f729Sjoerg 
16927330f729Sjoerg   if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
16937330f729Sjoerg     if (CXXConstructorDecl *Constructor = Construct->getConstructor())
16947330f729Sjoerg       if (Constructor->isTrivial() &&
16957330f729Sjoerg           Constructor->isDefaultConstructor() &&
16967330f729Sjoerg           !Construct->requiresZeroInitialization())
16977330f729Sjoerg         return true;
16987330f729Sjoerg 
16997330f729Sjoerg   return false;
17007330f729Sjoerg }
17017330f729Sjoerg 
emitZeroOrPatternForAutoVarInit(QualType type,const VarDecl & D,Address Loc)17027330f729Sjoerg void CodeGenFunction::emitZeroOrPatternForAutoVarInit(QualType type,
17037330f729Sjoerg                                                       const VarDecl &D,
17047330f729Sjoerg                                                       Address Loc) {
17057330f729Sjoerg   auto trivialAutoVarInit = getContext().getLangOpts().getTrivialAutoVarInit();
17067330f729Sjoerg   CharUnits Size = getContext().getTypeSizeInChars(type);
17077330f729Sjoerg   bool isVolatile = type.isVolatileQualified();
17087330f729Sjoerg   if (!Size.isZero()) {
17097330f729Sjoerg     switch (trivialAutoVarInit) {
17107330f729Sjoerg     case LangOptions::TrivialAutoVarInitKind::Uninitialized:
17117330f729Sjoerg       llvm_unreachable("Uninitialized handled by caller");
17127330f729Sjoerg     case LangOptions::TrivialAutoVarInitKind::Zero:
1713*e038c9c4Sjoerg       if (CGM.stopAutoInit())
1714*e038c9c4Sjoerg         return;
17157330f729Sjoerg       emitStoresForZeroInit(CGM, D, Loc, isVolatile, Builder);
17167330f729Sjoerg       break;
17177330f729Sjoerg     case LangOptions::TrivialAutoVarInitKind::Pattern:
1718*e038c9c4Sjoerg       if (CGM.stopAutoInit())
1719*e038c9c4Sjoerg         return;
17207330f729Sjoerg       emitStoresForPatternInit(CGM, D, Loc, isVolatile, Builder);
17217330f729Sjoerg       break;
17227330f729Sjoerg     }
17237330f729Sjoerg     return;
17247330f729Sjoerg   }
17257330f729Sjoerg 
17267330f729Sjoerg   // VLAs look zero-sized to getTypeInfo. We can't emit constant stores to
17277330f729Sjoerg   // them, so emit a memcpy with the VLA size to initialize each element.
17287330f729Sjoerg   // Technically zero-sized or negative-sized VLAs are undefined, and UBSan
17297330f729Sjoerg   // will catch that code, but there exists code which generates zero-sized
17307330f729Sjoerg   // VLAs. Be nice and initialize whatever they requested.
17317330f729Sjoerg   const auto *VlaType = getContext().getAsVariableArrayType(type);
17327330f729Sjoerg   if (!VlaType)
17337330f729Sjoerg     return;
17347330f729Sjoerg   auto VlaSize = getVLASize(VlaType);
17357330f729Sjoerg   auto SizeVal = VlaSize.NumElts;
17367330f729Sjoerg   CharUnits EltSize = getContext().getTypeSizeInChars(VlaSize.Type);
17377330f729Sjoerg   switch (trivialAutoVarInit) {
17387330f729Sjoerg   case LangOptions::TrivialAutoVarInitKind::Uninitialized:
17397330f729Sjoerg     llvm_unreachable("Uninitialized handled by caller");
17407330f729Sjoerg 
1741*e038c9c4Sjoerg   case LangOptions::TrivialAutoVarInitKind::Zero: {
1742*e038c9c4Sjoerg     if (CGM.stopAutoInit())
1743*e038c9c4Sjoerg       return;
17447330f729Sjoerg     if (!EltSize.isOne())
17457330f729Sjoerg       SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(EltSize));
1746*e038c9c4Sjoerg     auto *I = Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0),
1747*e038c9c4Sjoerg                                    SizeVal, isVolatile);
1748*e038c9c4Sjoerg     I->addAnnotationMetadata("auto-init");
17497330f729Sjoerg     break;
1750*e038c9c4Sjoerg   }
17517330f729Sjoerg 
17527330f729Sjoerg   case LangOptions::TrivialAutoVarInitKind::Pattern: {
1753*e038c9c4Sjoerg     if (CGM.stopAutoInit())
1754*e038c9c4Sjoerg       return;
17557330f729Sjoerg     llvm::Type *ElTy = Loc.getElementType();
17567330f729Sjoerg     llvm::Constant *Constant = constWithPadding(
17577330f729Sjoerg         CGM, IsPattern::Yes, initializationPatternFor(CGM, ElTy));
17587330f729Sjoerg     CharUnits ConstantAlign = getContext().getTypeAlignInChars(VlaSize.Type);
17597330f729Sjoerg     llvm::BasicBlock *SetupBB = createBasicBlock("vla-setup.loop");
17607330f729Sjoerg     llvm::BasicBlock *LoopBB = createBasicBlock("vla-init.loop");
17617330f729Sjoerg     llvm::BasicBlock *ContBB = createBasicBlock("vla-init.cont");
17627330f729Sjoerg     llvm::Value *IsZeroSizedVLA = Builder.CreateICmpEQ(
17637330f729Sjoerg         SizeVal, llvm::ConstantInt::get(SizeVal->getType(), 0),
17647330f729Sjoerg         "vla.iszerosized");
17657330f729Sjoerg     Builder.CreateCondBr(IsZeroSizedVLA, ContBB, SetupBB);
17667330f729Sjoerg     EmitBlock(SetupBB);
17677330f729Sjoerg     if (!EltSize.isOne())
17687330f729Sjoerg       SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(EltSize));
17697330f729Sjoerg     llvm::Value *BaseSizeInChars =
17707330f729Sjoerg         llvm::ConstantInt::get(IntPtrTy, EltSize.getQuantity());
17717330f729Sjoerg     Address Begin = Builder.CreateElementBitCast(Loc, Int8Ty, "vla.begin");
1772*e038c9c4Sjoerg     llvm::Value *End = Builder.CreateInBoundsGEP(
1773*e038c9c4Sjoerg         Begin.getElementType(), Begin.getPointer(), SizeVal, "vla.end");
17747330f729Sjoerg     llvm::BasicBlock *OriginBB = Builder.GetInsertBlock();
17757330f729Sjoerg     EmitBlock(LoopBB);
17767330f729Sjoerg     llvm::PHINode *Cur = Builder.CreatePHI(Begin.getType(), 2, "vla.cur");
17777330f729Sjoerg     Cur->addIncoming(Begin.getPointer(), OriginBB);
17787330f729Sjoerg     CharUnits CurAlign = Loc.getAlignment().alignmentOfArrayElement(EltSize);
1779*e038c9c4Sjoerg     auto *I =
17807330f729Sjoerg         Builder.CreateMemCpy(Address(Cur, CurAlign),
17817330f729Sjoerg                              createUnnamedGlobalForMemcpyFrom(
17827330f729Sjoerg                                  CGM, D, Builder, Constant, ConstantAlign),
17837330f729Sjoerg                              BaseSizeInChars, isVolatile);
1784*e038c9c4Sjoerg     I->addAnnotationMetadata("auto-init");
17857330f729Sjoerg     llvm::Value *Next =
17867330f729Sjoerg         Builder.CreateInBoundsGEP(Int8Ty, Cur, BaseSizeInChars, "vla.next");
17877330f729Sjoerg     llvm::Value *Done = Builder.CreateICmpEQ(Next, End, "vla-init.isdone");
17887330f729Sjoerg     Builder.CreateCondBr(Done, ContBB, LoopBB);
17897330f729Sjoerg     Cur->addIncoming(Next, LoopBB);
17907330f729Sjoerg     EmitBlock(ContBB);
17917330f729Sjoerg   } break;
17927330f729Sjoerg   }
17937330f729Sjoerg }
17947330f729Sjoerg 
EmitAutoVarInit(const AutoVarEmission & emission)17957330f729Sjoerg void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
17967330f729Sjoerg   assert(emission.Variable && "emission was not valid!");
17977330f729Sjoerg 
17987330f729Sjoerg   // If this was emitted as a global constant, we're done.
17997330f729Sjoerg   if (emission.wasEmittedAsGlobal()) return;
18007330f729Sjoerg 
18017330f729Sjoerg   const VarDecl &D = *emission.Variable;
18027330f729Sjoerg   auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, D.getLocation());
18037330f729Sjoerg   QualType type = D.getType();
18047330f729Sjoerg 
18057330f729Sjoerg   // If this local has an initializer, emit it now.
18067330f729Sjoerg   const Expr *Init = D.getInit();
18077330f729Sjoerg 
18087330f729Sjoerg   // If we are at an unreachable point, we don't need to emit the initializer
18097330f729Sjoerg   // unless it contains a label.
18107330f729Sjoerg   if (!HaveInsertPoint()) {
18117330f729Sjoerg     if (!Init || !ContainsLabel(Init)) return;
18127330f729Sjoerg     EnsureInsertPoint();
18137330f729Sjoerg   }
18147330f729Sjoerg 
18157330f729Sjoerg   // Initialize the structure of a __block variable.
18167330f729Sjoerg   if (emission.IsEscapingByRef)
18177330f729Sjoerg     emitByrefStructureInit(emission);
18187330f729Sjoerg 
18197330f729Sjoerg   // Initialize the variable here if it doesn't have a initializer and it is a
18207330f729Sjoerg   // C struct that is non-trivial to initialize or an array containing such a
18217330f729Sjoerg   // struct.
18227330f729Sjoerg   if (!Init &&
18237330f729Sjoerg       type.isNonTrivialToPrimitiveDefaultInitialize() ==
18247330f729Sjoerg           QualType::PDIK_Struct) {
18257330f729Sjoerg     LValue Dst = MakeAddrLValue(emission.getAllocatedAddress(), type);
18267330f729Sjoerg     if (emission.IsEscapingByRef)
18277330f729Sjoerg       drillIntoBlockVariable(*this, Dst, &D);
18287330f729Sjoerg     defaultInitNonTrivialCStructVar(Dst);
18297330f729Sjoerg     return;
18307330f729Sjoerg   }
18317330f729Sjoerg 
18327330f729Sjoerg   // Check whether this is a byref variable that's potentially
18337330f729Sjoerg   // captured and moved by its own initializer.  If so, we'll need to
18347330f729Sjoerg   // emit the initializer first, then copy into the variable.
18357330f729Sjoerg   bool capturedByInit =
18367330f729Sjoerg       Init && emission.IsEscapingByRef && isCapturedBy(D, Init);
18377330f729Sjoerg 
18387330f729Sjoerg   bool locIsByrefHeader = !capturedByInit;
18397330f729Sjoerg   const Address Loc =
18407330f729Sjoerg       locIsByrefHeader ? emission.getObjectAddress(*this) : emission.Addr;
18417330f729Sjoerg 
18427330f729Sjoerg   // Note: constexpr already initializes everything correctly.
18437330f729Sjoerg   LangOptions::TrivialAutoVarInitKind trivialAutoVarInit =
18447330f729Sjoerg       (D.isConstexpr()
18457330f729Sjoerg            ? LangOptions::TrivialAutoVarInitKind::Uninitialized
18467330f729Sjoerg            : (D.getAttr<UninitializedAttr>()
18477330f729Sjoerg                   ? LangOptions::TrivialAutoVarInitKind::Uninitialized
18487330f729Sjoerg                   : getContext().getLangOpts().getTrivialAutoVarInit()));
18497330f729Sjoerg 
18507330f729Sjoerg   auto initializeWhatIsTechnicallyUninitialized = [&](Address Loc) {
18517330f729Sjoerg     if (trivialAutoVarInit ==
18527330f729Sjoerg         LangOptions::TrivialAutoVarInitKind::Uninitialized)
18537330f729Sjoerg       return;
18547330f729Sjoerg 
18557330f729Sjoerg     // Only initialize a __block's storage: we always initialize the header.
18567330f729Sjoerg     if (emission.IsEscapingByRef && !locIsByrefHeader)
18577330f729Sjoerg       Loc = emitBlockByrefAddress(Loc, &D, /*follow=*/false);
18587330f729Sjoerg 
18597330f729Sjoerg     return emitZeroOrPatternForAutoVarInit(type, D, Loc);
18607330f729Sjoerg   };
18617330f729Sjoerg 
18627330f729Sjoerg   if (isTrivialInitializer(Init))
18637330f729Sjoerg     return initializeWhatIsTechnicallyUninitialized(Loc);
18647330f729Sjoerg 
18657330f729Sjoerg   llvm::Constant *constant = nullptr;
18667330f729Sjoerg   if (emission.IsConstantAggregate ||
18677330f729Sjoerg       D.mightBeUsableInConstantExpressions(getContext())) {
18687330f729Sjoerg     assert(!capturedByInit && "constant init contains a capturing block?");
18697330f729Sjoerg     constant = ConstantEmitter(*this).tryEmitAbstractForInitializer(D);
18707330f729Sjoerg     if (constant && !constant->isZeroValue() &&
18717330f729Sjoerg         (trivialAutoVarInit !=
18727330f729Sjoerg          LangOptions::TrivialAutoVarInitKind::Uninitialized)) {
18737330f729Sjoerg       IsPattern isPattern =
18747330f729Sjoerg           (trivialAutoVarInit == LangOptions::TrivialAutoVarInitKind::Pattern)
18757330f729Sjoerg               ? IsPattern::Yes
18767330f729Sjoerg               : IsPattern::No;
18777330f729Sjoerg       // C guarantees that brace-init with fewer initializers than members in
18787330f729Sjoerg       // the aggregate will initialize the rest of the aggregate as-if it were
18797330f729Sjoerg       // static initialization. In turn static initialization guarantees that
18807330f729Sjoerg       // padding is initialized to zero bits. We could instead pattern-init if D
18817330f729Sjoerg       // has any ImplicitValueInitExpr, but that seems to be unintuitive
18827330f729Sjoerg       // behavior.
18837330f729Sjoerg       constant = constWithPadding(CGM, IsPattern::No,
18847330f729Sjoerg                                   replaceUndef(CGM, isPattern, constant));
18857330f729Sjoerg     }
18867330f729Sjoerg   }
18877330f729Sjoerg 
18887330f729Sjoerg   if (!constant) {
18897330f729Sjoerg     initializeWhatIsTechnicallyUninitialized(Loc);
18907330f729Sjoerg     LValue lv = MakeAddrLValue(Loc, type);
18917330f729Sjoerg     lv.setNonGC(true);
18927330f729Sjoerg     return EmitExprAsInit(Init, &D, lv, capturedByInit);
18937330f729Sjoerg   }
18947330f729Sjoerg 
18957330f729Sjoerg   if (!emission.IsConstantAggregate) {
18967330f729Sjoerg     // For simple scalar/complex initialization, store the value directly.
18977330f729Sjoerg     LValue lv = MakeAddrLValue(Loc, type);
18987330f729Sjoerg     lv.setNonGC(true);
18997330f729Sjoerg     return EmitStoreThroughLValue(RValue::get(constant), lv, true);
19007330f729Sjoerg   }
19017330f729Sjoerg 
19027330f729Sjoerg   llvm::Type *BP = CGM.Int8Ty->getPointerTo(Loc.getAddressSpace());
19037330f729Sjoerg   emitStoresForConstant(
19047330f729Sjoerg       CGM, D, (Loc.getType() == BP) ? Loc : Builder.CreateBitCast(Loc, BP),
1905*e038c9c4Sjoerg       type.isVolatileQualified(), Builder, constant, /*IsAutoInit=*/false);
19067330f729Sjoerg }
19077330f729Sjoerg 
19087330f729Sjoerg /// Emit an expression as an initializer for an object (variable, field, etc.)
19097330f729Sjoerg /// at the given location.  The expression is not necessarily the normal
19107330f729Sjoerg /// initializer for the object, and the address is not necessarily
19117330f729Sjoerg /// its normal location.
19127330f729Sjoerg ///
19137330f729Sjoerg /// \param init the initializing expression
19147330f729Sjoerg /// \param D the object to act as if we're initializing
1915*e038c9c4Sjoerg /// \param lvalue the lvalue to initialize
19167330f729Sjoerg /// \param capturedByInit true if \p D is a __block variable
19177330f729Sjoerg ///   whose address is potentially changed by the initializer
EmitExprAsInit(const Expr * init,const ValueDecl * D,LValue lvalue,bool capturedByInit)19187330f729Sjoerg void CodeGenFunction::EmitExprAsInit(const Expr *init, const ValueDecl *D,
19197330f729Sjoerg                                      LValue lvalue, bool capturedByInit) {
19207330f729Sjoerg   QualType type = D->getType();
19217330f729Sjoerg 
19227330f729Sjoerg   if (type->isReferenceType()) {
19237330f729Sjoerg     RValue rvalue = EmitReferenceBindingToExpr(init);
19247330f729Sjoerg     if (capturedByInit)
19257330f729Sjoerg       drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
19267330f729Sjoerg     EmitStoreThroughLValue(rvalue, lvalue, true);
19277330f729Sjoerg     return;
19287330f729Sjoerg   }
19297330f729Sjoerg   switch (getEvaluationKind(type)) {
19307330f729Sjoerg   case TEK_Scalar:
19317330f729Sjoerg     EmitScalarInit(init, D, lvalue, capturedByInit);
19327330f729Sjoerg     return;
19337330f729Sjoerg   case TEK_Complex: {
19347330f729Sjoerg     ComplexPairTy complex = EmitComplexExpr(init);
19357330f729Sjoerg     if (capturedByInit)
19367330f729Sjoerg       drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
19377330f729Sjoerg     EmitStoreOfComplex(complex, lvalue, /*init*/ true);
19387330f729Sjoerg     return;
19397330f729Sjoerg   }
19407330f729Sjoerg   case TEK_Aggregate:
19417330f729Sjoerg     if (type->isAtomicType()) {
19427330f729Sjoerg       EmitAtomicInit(const_cast<Expr*>(init), lvalue);
19437330f729Sjoerg     } else {
19447330f729Sjoerg       AggValueSlot::Overlap_t Overlap = AggValueSlot::MayOverlap;
19457330f729Sjoerg       if (isa<VarDecl>(D))
19467330f729Sjoerg         Overlap = AggValueSlot::DoesNotOverlap;
19477330f729Sjoerg       else if (auto *FD = dyn_cast<FieldDecl>(D))
19487330f729Sjoerg         Overlap = getOverlapForFieldInit(FD);
19497330f729Sjoerg       // TODO: how can we delay here if D is captured by its initializer?
1950*e038c9c4Sjoerg       EmitAggExpr(init, AggValueSlot::forLValue(
1951*e038c9c4Sjoerg                             lvalue, *this, AggValueSlot::IsDestructed,
19527330f729Sjoerg                             AggValueSlot::DoesNotNeedGCBarriers,
1953*e038c9c4Sjoerg                             AggValueSlot::IsNotAliased, Overlap));
19547330f729Sjoerg     }
19557330f729Sjoerg     return;
19567330f729Sjoerg   }
19577330f729Sjoerg   llvm_unreachable("bad evaluation kind");
19587330f729Sjoerg }
19597330f729Sjoerg 
19607330f729Sjoerg /// Enter a destroy cleanup for the given local variable.
emitAutoVarTypeCleanup(const CodeGenFunction::AutoVarEmission & emission,QualType::DestructionKind dtorKind)19617330f729Sjoerg void CodeGenFunction::emitAutoVarTypeCleanup(
19627330f729Sjoerg                             const CodeGenFunction::AutoVarEmission &emission,
19637330f729Sjoerg                             QualType::DestructionKind dtorKind) {
19647330f729Sjoerg   assert(dtorKind != QualType::DK_none);
19657330f729Sjoerg 
19667330f729Sjoerg   // Note that for __block variables, we want to destroy the
19677330f729Sjoerg   // original stack object, not the possibly forwarded object.
19687330f729Sjoerg   Address addr = emission.getObjectAddress(*this);
19697330f729Sjoerg 
19707330f729Sjoerg   const VarDecl *var = emission.Variable;
19717330f729Sjoerg   QualType type = var->getType();
19727330f729Sjoerg 
19737330f729Sjoerg   CleanupKind cleanupKind = NormalAndEHCleanup;
19747330f729Sjoerg   CodeGenFunction::Destroyer *destroyer = nullptr;
19757330f729Sjoerg 
19767330f729Sjoerg   switch (dtorKind) {
19777330f729Sjoerg   case QualType::DK_none:
19787330f729Sjoerg     llvm_unreachable("no cleanup for trivially-destructible variable");
19797330f729Sjoerg 
19807330f729Sjoerg   case QualType::DK_cxx_destructor:
19817330f729Sjoerg     // If there's an NRVO flag on the emission, we need a different
19827330f729Sjoerg     // cleanup.
19837330f729Sjoerg     if (emission.NRVOFlag) {
19847330f729Sjoerg       assert(!type->isArrayType());
19857330f729Sjoerg       CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
19867330f729Sjoerg       EHStack.pushCleanup<DestroyNRVOVariableCXX>(cleanupKind, addr, type, dtor,
19877330f729Sjoerg                                                   emission.NRVOFlag);
19887330f729Sjoerg       return;
19897330f729Sjoerg     }
19907330f729Sjoerg     break;
19917330f729Sjoerg 
19927330f729Sjoerg   case QualType::DK_objc_strong_lifetime:
19937330f729Sjoerg     // Suppress cleanups for pseudo-strong variables.
19947330f729Sjoerg     if (var->isARCPseudoStrong()) return;
19957330f729Sjoerg 
19967330f729Sjoerg     // Otherwise, consider whether to use an EH cleanup or not.
19977330f729Sjoerg     cleanupKind = getARCCleanupKind();
19987330f729Sjoerg 
19997330f729Sjoerg     // Use the imprecise destroyer by default.
20007330f729Sjoerg     if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
20017330f729Sjoerg       destroyer = CodeGenFunction::destroyARCStrongImprecise;
20027330f729Sjoerg     break;
20037330f729Sjoerg 
20047330f729Sjoerg   case QualType::DK_objc_weak_lifetime:
20057330f729Sjoerg     break;
20067330f729Sjoerg 
20077330f729Sjoerg   case QualType::DK_nontrivial_c_struct:
20087330f729Sjoerg     destroyer = CodeGenFunction::destroyNonTrivialCStruct;
20097330f729Sjoerg     if (emission.NRVOFlag) {
20107330f729Sjoerg       assert(!type->isArrayType());
20117330f729Sjoerg       EHStack.pushCleanup<DestroyNRVOVariableC>(cleanupKind, addr,
20127330f729Sjoerg                                                 emission.NRVOFlag, type);
20137330f729Sjoerg       return;
20147330f729Sjoerg     }
20157330f729Sjoerg     break;
20167330f729Sjoerg   }
20177330f729Sjoerg 
20187330f729Sjoerg   // If we haven't chosen a more specific destroyer, use the default.
20197330f729Sjoerg   if (!destroyer) destroyer = getDestroyer(dtorKind);
20207330f729Sjoerg 
20217330f729Sjoerg   // Use an EH cleanup in array destructors iff the destructor itself
20227330f729Sjoerg   // is being pushed as an EH cleanup.
20237330f729Sjoerg   bool useEHCleanup = (cleanupKind & EHCleanup);
20247330f729Sjoerg   EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
20257330f729Sjoerg                                      useEHCleanup);
20267330f729Sjoerg }
20277330f729Sjoerg 
EmitAutoVarCleanups(const AutoVarEmission & emission)20287330f729Sjoerg void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
20297330f729Sjoerg   assert(emission.Variable && "emission was not valid!");
20307330f729Sjoerg 
20317330f729Sjoerg   // If this was emitted as a global constant, we're done.
20327330f729Sjoerg   if (emission.wasEmittedAsGlobal()) return;
20337330f729Sjoerg 
20347330f729Sjoerg   // If we don't have an insertion point, we're done.  Sema prevents
20357330f729Sjoerg   // us from jumping into any of these scopes anyway.
20367330f729Sjoerg   if (!HaveInsertPoint()) return;
20377330f729Sjoerg 
20387330f729Sjoerg   const VarDecl &D = *emission.Variable;
20397330f729Sjoerg 
20407330f729Sjoerg   // Check the type for a cleanup.
20417330f729Sjoerg   if (QualType::DestructionKind dtorKind = D.needsDestruction(getContext()))
20427330f729Sjoerg     emitAutoVarTypeCleanup(emission, dtorKind);
20437330f729Sjoerg 
20447330f729Sjoerg   // In GC mode, honor objc_precise_lifetime.
20457330f729Sjoerg   if (getLangOpts().getGC() != LangOptions::NonGC &&
20467330f729Sjoerg       D.hasAttr<ObjCPreciseLifetimeAttr>()) {
20477330f729Sjoerg     EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
20487330f729Sjoerg   }
20497330f729Sjoerg 
20507330f729Sjoerg   // Handle the cleanup attribute.
20517330f729Sjoerg   if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
20527330f729Sjoerg     const FunctionDecl *FD = CA->getFunctionDecl();
20537330f729Sjoerg 
20547330f729Sjoerg     llvm::Constant *F = CGM.GetAddrOfFunction(FD);
20557330f729Sjoerg     assert(F && "Could not find function!");
20567330f729Sjoerg 
20577330f729Sjoerg     const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
20587330f729Sjoerg     EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
20597330f729Sjoerg   }
20607330f729Sjoerg 
20617330f729Sjoerg   // If this is a block variable, call _Block_object_destroy
20627330f729Sjoerg   // (on the unforwarded address). Don't enter this cleanup if we're in pure-GC
20637330f729Sjoerg   // mode.
20647330f729Sjoerg   if (emission.IsEscapingByRef &&
20657330f729Sjoerg       CGM.getLangOpts().getGC() != LangOptions::GCOnly) {
20667330f729Sjoerg     BlockFieldFlags Flags = BLOCK_FIELD_IS_BYREF;
20677330f729Sjoerg     if (emission.Variable->getType().isObjCGCWeak())
20687330f729Sjoerg       Flags |= BLOCK_FIELD_IS_WEAK;
20697330f729Sjoerg     enterByrefCleanup(NormalAndEHCleanup, emission.Addr, Flags,
20707330f729Sjoerg                       /*LoadBlockVarAddr*/ false,
20717330f729Sjoerg                       cxxDestructorCanThrow(emission.Variable->getType()));
20727330f729Sjoerg   }
20737330f729Sjoerg }
20747330f729Sjoerg 
20757330f729Sjoerg CodeGenFunction::Destroyer *
getDestroyer(QualType::DestructionKind kind)20767330f729Sjoerg CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
20777330f729Sjoerg   switch (kind) {
20787330f729Sjoerg   case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
20797330f729Sjoerg   case QualType::DK_cxx_destructor:
20807330f729Sjoerg     return destroyCXXObject;
20817330f729Sjoerg   case QualType::DK_objc_strong_lifetime:
20827330f729Sjoerg     return destroyARCStrongPrecise;
20837330f729Sjoerg   case QualType::DK_objc_weak_lifetime:
20847330f729Sjoerg     return destroyARCWeak;
20857330f729Sjoerg   case QualType::DK_nontrivial_c_struct:
20867330f729Sjoerg     return destroyNonTrivialCStruct;
20877330f729Sjoerg   }
20887330f729Sjoerg   llvm_unreachable("Unknown DestructionKind");
20897330f729Sjoerg }
20907330f729Sjoerg 
20917330f729Sjoerg /// pushEHDestroy - Push the standard destructor for the given type as
20927330f729Sjoerg /// an EH-only cleanup.
pushEHDestroy(QualType::DestructionKind dtorKind,Address addr,QualType type)20937330f729Sjoerg void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind,
20947330f729Sjoerg                                     Address addr, QualType type) {
20957330f729Sjoerg   assert(dtorKind && "cannot push destructor for trivial type");
20967330f729Sjoerg   assert(needsEHCleanup(dtorKind));
20977330f729Sjoerg 
20987330f729Sjoerg   pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true);
20997330f729Sjoerg }
21007330f729Sjoerg 
21017330f729Sjoerg /// pushDestroy - Push the standard destructor for the given type as
21027330f729Sjoerg /// at least a normal cleanup.
pushDestroy(QualType::DestructionKind dtorKind,Address addr,QualType type)21037330f729Sjoerg void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
21047330f729Sjoerg                                   Address addr, QualType type) {
21057330f729Sjoerg   assert(dtorKind && "cannot push destructor for trivial type");
21067330f729Sjoerg 
21077330f729Sjoerg   CleanupKind cleanupKind = getCleanupKind(dtorKind);
21087330f729Sjoerg   pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
21097330f729Sjoerg               cleanupKind & EHCleanup);
21107330f729Sjoerg }
21117330f729Sjoerg 
pushDestroy(CleanupKind cleanupKind,Address addr,QualType type,Destroyer * destroyer,bool useEHCleanupForArray)21127330f729Sjoerg void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, Address addr,
21137330f729Sjoerg                                   QualType type, Destroyer *destroyer,
21147330f729Sjoerg                                   bool useEHCleanupForArray) {
21157330f729Sjoerg   pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
21167330f729Sjoerg                                      destroyer, useEHCleanupForArray);
21177330f729Sjoerg }
21187330f729Sjoerg 
pushStackRestore(CleanupKind Kind,Address SPMem)21197330f729Sjoerg void CodeGenFunction::pushStackRestore(CleanupKind Kind, Address SPMem) {
21207330f729Sjoerg   EHStack.pushCleanup<CallStackRestore>(Kind, SPMem);
21217330f729Sjoerg }
21227330f729Sjoerg 
pushLifetimeExtendedDestroy(CleanupKind cleanupKind,Address addr,QualType type,Destroyer * destroyer,bool useEHCleanupForArray)2123*e038c9c4Sjoerg void CodeGenFunction::pushLifetimeExtendedDestroy(CleanupKind cleanupKind,
2124*e038c9c4Sjoerg                                                   Address addr, QualType type,
2125*e038c9c4Sjoerg                                                   Destroyer *destroyer,
2126*e038c9c4Sjoerg                                                   bool useEHCleanupForArray) {
2127*e038c9c4Sjoerg   // If we're not in a conditional branch, we don't need to bother generating a
2128*e038c9c4Sjoerg   // conditional cleanup.
2129*e038c9c4Sjoerg   if (!isInConditionalBranch()) {
21307330f729Sjoerg     // Push an EH-only cleanup for the object now.
21317330f729Sjoerg     // FIXME: When popping normal cleanups, we need to keep this EH cleanup
21327330f729Sjoerg     // around in case a temporary's destructor throws an exception.
21337330f729Sjoerg     if (cleanupKind & EHCleanup)
21347330f729Sjoerg       EHStack.pushCleanup<DestroyObject>(
21357330f729Sjoerg           static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type,
21367330f729Sjoerg           destroyer, useEHCleanupForArray);
21377330f729Sjoerg 
2138*e038c9c4Sjoerg     return pushCleanupAfterFullExprWithActiveFlag<DestroyObject>(
2139*e038c9c4Sjoerg         cleanupKind, Address::invalid(), addr, type, destroyer, useEHCleanupForArray);
2140*e038c9c4Sjoerg   }
2141*e038c9c4Sjoerg 
2142*e038c9c4Sjoerg   // Otherwise, we should only destroy the object if it's been initialized.
2143*e038c9c4Sjoerg   // Re-use the active flag and saved address across both the EH and end of
2144*e038c9c4Sjoerg   // scope cleanups.
2145*e038c9c4Sjoerg 
2146*e038c9c4Sjoerg   using SavedType = typename DominatingValue<Address>::saved_type;
2147*e038c9c4Sjoerg   using ConditionalCleanupType =
2148*e038c9c4Sjoerg       EHScopeStack::ConditionalCleanup<DestroyObject, Address, QualType,
2149*e038c9c4Sjoerg                                        Destroyer *, bool>;
2150*e038c9c4Sjoerg 
2151*e038c9c4Sjoerg   Address ActiveFlag = createCleanupActiveFlag();
2152*e038c9c4Sjoerg   SavedType SavedAddr = saveValueInCond(addr);
2153*e038c9c4Sjoerg 
2154*e038c9c4Sjoerg   if (cleanupKind & EHCleanup) {
2155*e038c9c4Sjoerg     EHStack.pushCleanup<ConditionalCleanupType>(
2156*e038c9c4Sjoerg         static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), SavedAddr, type,
2157*e038c9c4Sjoerg         destroyer, useEHCleanupForArray);
2158*e038c9c4Sjoerg     initFullExprCleanupWithFlag(ActiveFlag);
2159*e038c9c4Sjoerg   }
2160*e038c9c4Sjoerg 
2161*e038c9c4Sjoerg   pushCleanupAfterFullExprWithActiveFlag<ConditionalCleanupType>(
2162*e038c9c4Sjoerg       cleanupKind, ActiveFlag, SavedAddr, type, destroyer,
2163*e038c9c4Sjoerg       useEHCleanupForArray);
21647330f729Sjoerg }
21657330f729Sjoerg 
21667330f729Sjoerg /// emitDestroy - Immediately perform the destruction of the given
21677330f729Sjoerg /// object.
21687330f729Sjoerg ///
21697330f729Sjoerg /// \param addr - the address of the object; a type*
21707330f729Sjoerg /// \param type - the type of the object; if an array type, all
21717330f729Sjoerg ///   objects are destroyed in reverse order
21727330f729Sjoerg /// \param destroyer - the function to call to destroy individual
21737330f729Sjoerg ///   elements
21747330f729Sjoerg /// \param useEHCleanupForArray - whether an EH cleanup should be
21757330f729Sjoerg ///   used when destroying array elements, in case one of the
21767330f729Sjoerg ///   destructions throws an exception
emitDestroy(Address addr,QualType type,Destroyer * destroyer,bool useEHCleanupForArray)21777330f729Sjoerg void CodeGenFunction::emitDestroy(Address addr, QualType type,
21787330f729Sjoerg                                   Destroyer *destroyer,
21797330f729Sjoerg                                   bool useEHCleanupForArray) {
21807330f729Sjoerg   const ArrayType *arrayType = getContext().getAsArrayType(type);
21817330f729Sjoerg   if (!arrayType)
21827330f729Sjoerg     return destroyer(*this, addr, type);
21837330f729Sjoerg 
21847330f729Sjoerg   llvm::Value *length = emitArrayLength(arrayType, type, addr);
21857330f729Sjoerg 
21867330f729Sjoerg   CharUnits elementAlign =
21877330f729Sjoerg     addr.getAlignment()
21887330f729Sjoerg         .alignmentOfArrayElement(getContext().getTypeSizeInChars(type));
21897330f729Sjoerg 
21907330f729Sjoerg   // Normally we have to check whether the array is zero-length.
21917330f729Sjoerg   bool checkZeroLength = true;
21927330f729Sjoerg 
21937330f729Sjoerg   // But if the array length is constant, we can suppress that.
21947330f729Sjoerg   if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
21957330f729Sjoerg     // ...and if it's constant zero, we can just skip the entire thing.
21967330f729Sjoerg     if (constLength->isZero()) return;
21977330f729Sjoerg     checkZeroLength = false;
21987330f729Sjoerg   }
21997330f729Sjoerg 
22007330f729Sjoerg   llvm::Value *begin = addr.getPointer();
2201*e038c9c4Sjoerg   llvm::Value *end =
2202*e038c9c4Sjoerg       Builder.CreateInBoundsGEP(addr.getElementType(), begin, length);
22037330f729Sjoerg   emitArrayDestroy(begin, end, type, elementAlign, destroyer,
22047330f729Sjoerg                    checkZeroLength, useEHCleanupForArray);
22057330f729Sjoerg }
22067330f729Sjoerg 
22077330f729Sjoerg /// emitArrayDestroy - Destroys all the elements of the given array,
22087330f729Sjoerg /// beginning from last to first.  The array cannot be zero-length.
22097330f729Sjoerg ///
22107330f729Sjoerg /// \param begin - a type* denoting the first element of the array
22117330f729Sjoerg /// \param end - a type* denoting one past the end of the array
22127330f729Sjoerg /// \param elementType - the element type of the array
22137330f729Sjoerg /// \param destroyer - the function to call to destroy elements
22147330f729Sjoerg /// \param useEHCleanup - whether to push an EH cleanup to destroy
22157330f729Sjoerg ///   the remaining elements in case the destruction of a single
22167330f729Sjoerg ///   element throws
emitArrayDestroy(llvm::Value * begin,llvm::Value * end,QualType elementType,CharUnits elementAlign,Destroyer * destroyer,bool checkZeroLength,bool useEHCleanup)22177330f729Sjoerg void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
22187330f729Sjoerg                                        llvm::Value *end,
22197330f729Sjoerg                                        QualType elementType,
22207330f729Sjoerg                                        CharUnits elementAlign,
22217330f729Sjoerg                                        Destroyer *destroyer,
22227330f729Sjoerg                                        bool checkZeroLength,
22237330f729Sjoerg                                        bool useEHCleanup) {
22247330f729Sjoerg   assert(!elementType->isArrayType());
22257330f729Sjoerg 
22267330f729Sjoerg   // The basic structure here is a do-while loop, because we don't
22277330f729Sjoerg   // need to check for the zero-element case.
22287330f729Sjoerg   llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
22297330f729Sjoerg   llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
22307330f729Sjoerg 
22317330f729Sjoerg   if (checkZeroLength) {
22327330f729Sjoerg     llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
22337330f729Sjoerg                                                 "arraydestroy.isempty");
22347330f729Sjoerg     Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
22357330f729Sjoerg   }
22367330f729Sjoerg 
22377330f729Sjoerg   // Enter the loop body, making that address the current address.
22387330f729Sjoerg   llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
22397330f729Sjoerg   EmitBlock(bodyBB);
22407330f729Sjoerg   llvm::PHINode *elementPast =
22417330f729Sjoerg     Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
22427330f729Sjoerg   elementPast->addIncoming(end, entryBB);
22437330f729Sjoerg 
22447330f729Sjoerg   // Shift the address back by one element.
22457330f729Sjoerg   llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
22467330f729Sjoerg   llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne,
22477330f729Sjoerg                                                    "arraydestroy.element");
22487330f729Sjoerg 
22497330f729Sjoerg   if (useEHCleanup)
22507330f729Sjoerg     pushRegularPartialArrayCleanup(begin, element, elementType, elementAlign,
22517330f729Sjoerg                                    destroyer);
22527330f729Sjoerg 
22537330f729Sjoerg   // Perform the actual destruction there.
22547330f729Sjoerg   destroyer(*this, Address(element, elementAlign), elementType);
22557330f729Sjoerg 
22567330f729Sjoerg   if (useEHCleanup)
22577330f729Sjoerg     PopCleanupBlock();
22587330f729Sjoerg 
22597330f729Sjoerg   // Check whether we've reached the end.
22607330f729Sjoerg   llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
22617330f729Sjoerg   Builder.CreateCondBr(done, doneBB, bodyBB);
22627330f729Sjoerg   elementPast->addIncoming(element, Builder.GetInsertBlock());
22637330f729Sjoerg 
22647330f729Sjoerg   // Done.
22657330f729Sjoerg   EmitBlock(doneBB);
22667330f729Sjoerg }
22677330f729Sjoerg 
22687330f729Sjoerg /// Perform partial array destruction as if in an EH cleanup.  Unlike
22697330f729Sjoerg /// emitArrayDestroy, the element type here may still be an array type.
emitPartialArrayDestroy(CodeGenFunction & CGF,llvm::Value * begin,llvm::Value * end,QualType type,CharUnits elementAlign,CodeGenFunction::Destroyer * destroyer)22707330f729Sjoerg static void emitPartialArrayDestroy(CodeGenFunction &CGF,
22717330f729Sjoerg                                     llvm::Value *begin, llvm::Value *end,
22727330f729Sjoerg                                     QualType type, CharUnits elementAlign,
22737330f729Sjoerg                                     CodeGenFunction::Destroyer *destroyer) {
22747330f729Sjoerg   // If the element type is itself an array, drill down.
22757330f729Sjoerg   unsigned arrayDepth = 0;
22767330f729Sjoerg   while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
22777330f729Sjoerg     // VLAs don't require a GEP index to walk into.
22787330f729Sjoerg     if (!isa<VariableArrayType>(arrayType))
22797330f729Sjoerg       arrayDepth++;
22807330f729Sjoerg     type = arrayType->getElementType();
22817330f729Sjoerg   }
22827330f729Sjoerg 
22837330f729Sjoerg   if (arrayDepth) {
22847330f729Sjoerg     llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
22857330f729Sjoerg 
22867330f729Sjoerg     SmallVector<llvm::Value*,4> gepIndices(arrayDepth+1, zero);
22877330f729Sjoerg     begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin");
22887330f729Sjoerg     end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend");
22897330f729Sjoerg   }
22907330f729Sjoerg 
22917330f729Sjoerg   // Destroy the array.  We don't ever need an EH cleanup because we
22927330f729Sjoerg   // assume that we're in an EH cleanup ourselves, so a throwing
22937330f729Sjoerg   // destructor causes an immediate terminate.
22947330f729Sjoerg   CGF.emitArrayDestroy(begin, end, type, elementAlign, destroyer,
22957330f729Sjoerg                        /*checkZeroLength*/ true, /*useEHCleanup*/ false);
22967330f729Sjoerg }
22977330f729Sjoerg 
22987330f729Sjoerg namespace {
22997330f729Sjoerg   /// RegularPartialArrayDestroy - a cleanup which performs a partial
23007330f729Sjoerg   /// array destroy where the end pointer is regularly determined and
23017330f729Sjoerg   /// does not need to be loaded from a local.
23027330f729Sjoerg   class RegularPartialArrayDestroy final : public EHScopeStack::Cleanup {
23037330f729Sjoerg     llvm::Value *ArrayBegin;
23047330f729Sjoerg     llvm::Value *ArrayEnd;
23057330f729Sjoerg     QualType ElementType;
23067330f729Sjoerg     CodeGenFunction::Destroyer *Destroyer;
23077330f729Sjoerg     CharUnits ElementAlign;
23087330f729Sjoerg   public:
RegularPartialArrayDestroy(llvm::Value * arrayBegin,llvm::Value * arrayEnd,QualType elementType,CharUnits elementAlign,CodeGenFunction::Destroyer * destroyer)23097330f729Sjoerg     RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
23107330f729Sjoerg                                QualType elementType, CharUnits elementAlign,
23117330f729Sjoerg                                CodeGenFunction::Destroyer *destroyer)
23127330f729Sjoerg       : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
23137330f729Sjoerg         ElementType(elementType), Destroyer(destroyer),
23147330f729Sjoerg         ElementAlign(elementAlign) {}
23157330f729Sjoerg 
Emit(CodeGenFunction & CGF,Flags flags)23167330f729Sjoerg     void Emit(CodeGenFunction &CGF, Flags flags) override {
23177330f729Sjoerg       emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
23187330f729Sjoerg                               ElementType, ElementAlign, Destroyer);
23197330f729Sjoerg     }
23207330f729Sjoerg   };
23217330f729Sjoerg 
23227330f729Sjoerg   /// IrregularPartialArrayDestroy - a cleanup which performs a
23237330f729Sjoerg   /// partial array destroy where the end pointer is irregularly
23247330f729Sjoerg   /// determined and must be loaded from a local.
23257330f729Sjoerg   class IrregularPartialArrayDestroy final : public EHScopeStack::Cleanup {
23267330f729Sjoerg     llvm::Value *ArrayBegin;
23277330f729Sjoerg     Address ArrayEndPointer;
23287330f729Sjoerg     QualType ElementType;
23297330f729Sjoerg     CodeGenFunction::Destroyer *Destroyer;
23307330f729Sjoerg     CharUnits ElementAlign;
23317330f729Sjoerg   public:
IrregularPartialArrayDestroy(llvm::Value * arrayBegin,Address arrayEndPointer,QualType elementType,CharUnits elementAlign,CodeGenFunction::Destroyer * destroyer)23327330f729Sjoerg     IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
23337330f729Sjoerg                                  Address arrayEndPointer,
23347330f729Sjoerg                                  QualType elementType,
23357330f729Sjoerg                                  CharUnits elementAlign,
23367330f729Sjoerg                                  CodeGenFunction::Destroyer *destroyer)
23377330f729Sjoerg       : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
23387330f729Sjoerg         ElementType(elementType), Destroyer(destroyer),
23397330f729Sjoerg         ElementAlign(elementAlign) {}
23407330f729Sjoerg 
Emit(CodeGenFunction & CGF,Flags flags)23417330f729Sjoerg     void Emit(CodeGenFunction &CGF, Flags flags) override {
23427330f729Sjoerg       llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
23437330f729Sjoerg       emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
23447330f729Sjoerg                               ElementType, ElementAlign, Destroyer);
23457330f729Sjoerg     }
23467330f729Sjoerg   };
23477330f729Sjoerg } // end anonymous namespace
23487330f729Sjoerg 
23497330f729Sjoerg /// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
23507330f729Sjoerg /// already-constructed elements of the given array.  The cleanup
23517330f729Sjoerg /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
23527330f729Sjoerg ///
23537330f729Sjoerg /// \param elementType - the immediate element type of the array;
23547330f729Sjoerg ///   possibly still an array type
pushIrregularPartialArrayCleanup(llvm::Value * arrayBegin,Address arrayEndPointer,QualType elementType,CharUnits elementAlign,Destroyer * destroyer)23557330f729Sjoerg void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
23567330f729Sjoerg                                                        Address arrayEndPointer,
23577330f729Sjoerg                                                        QualType elementType,
23587330f729Sjoerg                                                        CharUnits elementAlign,
23597330f729Sjoerg                                                        Destroyer *destroyer) {
23607330f729Sjoerg   pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
23617330f729Sjoerg                                                     arrayBegin, arrayEndPointer,
23627330f729Sjoerg                                                     elementType, elementAlign,
23637330f729Sjoerg                                                     destroyer);
23647330f729Sjoerg }
23657330f729Sjoerg 
23667330f729Sjoerg /// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
23677330f729Sjoerg /// already-constructed elements of the given array.  The cleanup
23687330f729Sjoerg /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
23697330f729Sjoerg ///
23707330f729Sjoerg /// \param elementType - the immediate element type of the array;
23717330f729Sjoerg ///   possibly still an array type
pushRegularPartialArrayCleanup(llvm::Value * arrayBegin,llvm::Value * arrayEnd,QualType elementType,CharUnits elementAlign,Destroyer * destroyer)23727330f729Sjoerg void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
23737330f729Sjoerg                                                      llvm::Value *arrayEnd,
23747330f729Sjoerg                                                      QualType elementType,
23757330f729Sjoerg                                                      CharUnits elementAlign,
23767330f729Sjoerg                                                      Destroyer *destroyer) {
23777330f729Sjoerg   pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
23787330f729Sjoerg                                                   arrayBegin, arrayEnd,
23797330f729Sjoerg                                                   elementType, elementAlign,
23807330f729Sjoerg                                                   destroyer);
23817330f729Sjoerg }
23827330f729Sjoerg 
23837330f729Sjoerg /// Lazily declare the @llvm.lifetime.start intrinsic.
getLLVMLifetimeStartFn()23847330f729Sjoerg llvm::Function *CodeGenModule::getLLVMLifetimeStartFn() {
23857330f729Sjoerg   if (LifetimeStartFn)
23867330f729Sjoerg     return LifetimeStartFn;
23877330f729Sjoerg   LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(),
23887330f729Sjoerg     llvm::Intrinsic::lifetime_start, AllocaInt8PtrTy);
23897330f729Sjoerg   return LifetimeStartFn;
23907330f729Sjoerg }
23917330f729Sjoerg 
23927330f729Sjoerg /// Lazily declare the @llvm.lifetime.end intrinsic.
getLLVMLifetimeEndFn()23937330f729Sjoerg llvm::Function *CodeGenModule::getLLVMLifetimeEndFn() {
23947330f729Sjoerg   if (LifetimeEndFn)
23957330f729Sjoerg     return LifetimeEndFn;
23967330f729Sjoerg   LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(),
23977330f729Sjoerg     llvm::Intrinsic::lifetime_end, AllocaInt8PtrTy);
23987330f729Sjoerg   return LifetimeEndFn;
23997330f729Sjoerg }
24007330f729Sjoerg 
24017330f729Sjoerg namespace {
24027330f729Sjoerg   /// A cleanup to perform a release of an object at the end of a
24037330f729Sjoerg   /// function.  This is used to balance out the incoming +1 of a
24047330f729Sjoerg   /// ns_consumed argument when we can't reasonably do that just by
24057330f729Sjoerg   /// not doing the initial retain for a __block argument.
24067330f729Sjoerg   struct ConsumeARCParameter final : EHScopeStack::Cleanup {
ConsumeARCParameter__anon76247d8b0511::ConsumeARCParameter24077330f729Sjoerg     ConsumeARCParameter(llvm::Value *param,
24087330f729Sjoerg                         ARCPreciseLifetime_t precise)
24097330f729Sjoerg       : Param(param), Precise(precise) {}
24107330f729Sjoerg 
24117330f729Sjoerg     llvm::Value *Param;
24127330f729Sjoerg     ARCPreciseLifetime_t Precise;
24137330f729Sjoerg 
Emit__anon76247d8b0511::ConsumeARCParameter24147330f729Sjoerg     void Emit(CodeGenFunction &CGF, Flags flags) override {
24157330f729Sjoerg       CGF.EmitARCRelease(Param, Precise);
24167330f729Sjoerg     }
24177330f729Sjoerg   };
24187330f729Sjoerg } // end anonymous namespace
24197330f729Sjoerg 
24207330f729Sjoerg /// Emit an alloca (or GlobalValue depending on target)
24217330f729Sjoerg /// for the specified parameter and set up LocalDeclMap.
EmitParmDecl(const VarDecl & D,ParamValue Arg,unsigned ArgNo)24227330f729Sjoerg void CodeGenFunction::EmitParmDecl(const VarDecl &D, ParamValue Arg,
24237330f729Sjoerg                                    unsigned ArgNo) {
24247330f729Sjoerg   // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
24257330f729Sjoerg   assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
24267330f729Sjoerg          "Invalid argument to EmitParmDecl");
24277330f729Sjoerg 
24287330f729Sjoerg   Arg.getAnyValue()->setName(D.getName());
24297330f729Sjoerg 
24307330f729Sjoerg   QualType Ty = D.getType();
24317330f729Sjoerg 
24327330f729Sjoerg   // Use better IR generation for certain implicit parameters.
24337330f729Sjoerg   if (auto IPD = dyn_cast<ImplicitParamDecl>(&D)) {
24347330f729Sjoerg     // The only implicit argument a block has is its literal.
24357330f729Sjoerg     // This may be passed as an inalloca'ed value on Windows x86.
24367330f729Sjoerg     if (BlockInfo) {
24377330f729Sjoerg       llvm::Value *V = Arg.isIndirect()
24387330f729Sjoerg                            ? Builder.CreateLoad(Arg.getIndirectAddress())
24397330f729Sjoerg                            : Arg.getDirectValue();
24407330f729Sjoerg       setBlockContextParameter(IPD, ArgNo, V);
24417330f729Sjoerg       return;
24427330f729Sjoerg     }
24437330f729Sjoerg   }
24447330f729Sjoerg 
24457330f729Sjoerg   Address DeclPtr = Address::invalid();
24467330f729Sjoerg   bool DoStore = false;
24477330f729Sjoerg   bool IsScalar = hasScalarEvaluationKind(Ty);
24487330f729Sjoerg   // If we already have a pointer to the argument, reuse the input pointer.
24497330f729Sjoerg   if (Arg.isIndirect()) {
24507330f729Sjoerg     DeclPtr = Arg.getIndirectAddress();
24517330f729Sjoerg     // If we have a prettier pointer type at this point, bitcast to that.
24527330f729Sjoerg     unsigned AS = DeclPtr.getType()->getAddressSpace();
24537330f729Sjoerg     llvm::Type *IRTy = ConvertTypeForMem(Ty)->getPointerTo(AS);
24547330f729Sjoerg     if (DeclPtr.getType() != IRTy)
24557330f729Sjoerg       DeclPtr = Builder.CreateBitCast(DeclPtr, IRTy, D.getName());
24567330f729Sjoerg     // Indirect argument is in alloca address space, which may be different
24577330f729Sjoerg     // from the default address space.
24587330f729Sjoerg     auto AllocaAS = CGM.getASTAllocaAddressSpace();
24597330f729Sjoerg     auto *V = DeclPtr.getPointer();
24607330f729Sjoerg     auto SrcLangAS = getLangOpts().OpenCL ? LangAS::opencl_private : AllocaAS;
24617330f729Sjoerg     auto DestLangAS =
24627330f729Sjoerg         getLangOpts().OpenCL ? LangAS::opencl_private : LangAS::Default;
24637330f729Sjoerg     if (SrcLangAS != DestLangAS) {
24647330f729Sjoerg       assert(getContext().getTargetAddressSpace(SrcLangAS) ==
24657330f729Sjoerg              CGM.getDataLayout().getAllocaAddrSpace());
24667330f729Sjoerg       auto DestAS = getContext().getTargetAddressSpace(DestLangAS);
24677330f729Sjoerg       auto *T = V->getType()->getPointerElementType()->getPointerTo(DestAS);
24687330f729Sjoerg       DeclPtr = Address(getTargetHooks().performAddrSpaceCast(
24697330f729Sjoerg                             *this, V, SrcLangAS, DestLangAS, T, true),
24707330f729Sjoerg                         DeclPtr.getAlignment());
24717330f729Sjoerg     }
24727330f729Sjoerg 
24737330f729Sjoerg     // Push a destructor cleanup for this parameter if the ABI requires it.
24747330f729Sjoerg     // Don't push a cleanup in a thunk for a method that will also emit a
24757330f729Sjoerg     // cleanup.
2476*e038c9c4Sjoerg     if (Ty->isRecordType() && !CurFuncIsThunk &&
24777330f729Sjoerg         Ty->castAs<RecordType>()->getDecl()->isParamDestroyedInCallee()) {
24787330f729Sjoerg       if (QualType::DestructionKind DtorKind =
24797330f729Sjoerg               D.needsDestruction(getContext())) {
24807330f729Sjoerg         assert((DtorKind == QualType::DK_cxx_destructor ||
24817330f729Sjoerg                 DtorKind == QualType::DK_nontrivial_c_struct) &&
24827330f729Sjoerg                "unexpected destructor type");
24837330f729Sjoerg         pushDestroy(DtorKind, DeclPtr, Ty);
24847330f729Sjoerg         CalleeDestructedParamCleanups[cast<ParmVarDecl>(&D)] =
24857330f729Sjoerg             EHStack.stable_begin();
24867330f729Sjoerg       }
24877330f729Sjoerg     }
24887330f729Sjoerg   } else {
24897330f729Sjoerg     // Check if the parameter address is controlled by OpenMP runtime.
24907330f729Sjoerg     Address OpenMPLocalAddr =
24917330f729Sjoerg         getLangOpts().OpenMP
24927330f729Sjoerg             ? CGM.getOpenMPRuntime().getAddressOfLocalVariable(*this, &D)
24937330f729Sjoerg             : Address::invalid();
24947330f729Sjoerg     if (getLangOpts().OpenMP && OpenMPLocalAddr.isValid()) {
24957330f729Sjoerg       DeclPtr = OpenMPLocalAddr;
24967330f729Sjoerg     } else {
24977330f729Sjoerg       // Otherwise, create a temporary to hold the value.
24987330f729Sjoerg       DeclPtr = CreateMemTemp(Ty, getContext().getDeclAlign(&D),
24997330f729Sjoerg                               D.getName() + ".addr");
25007330f729Sjoerg     }
25017330f729Sjoerg     DoStore = true;
25027330f729Sjoerg   }
25037330f729Sjoerg 
25047330f729Sjoerg   llvm::Value *ArgVal = (DoStore ? Arg.getDirectValue() : nullptr);
25057330f729Sjoerg 
25067330f729Sjoerg   LValue lv = MakeAddrLValue(DeclPtr, Ty);
25077330f729Sjoerg   if (IsScalar) {
25087330f729Sjoerg     Qualifiers qs = Ty.getQualifiers();
25097330f729Sjoerg     if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
25107330f729Sjoerg       // We honor __attribute__((ns_consumed)) for types with lifetime.
25117330f729Sjoerg       // For __strong, it's handled by just skipping the initial retain;
25127330f729Sjoerg       // otherwise we have to balance out the initial +1 with an extra
25137330f729Sjoerg       // cleanup to do the release at the end of the function.
25147330f729Sjoerg       bool isConsumed = D.hasAttr<NSConsumedAttr>();
25157330f729Sjoerg 
25167330f729Sjoerg       // If a parameter is pseudo-strong then we can omit the implicit retain.
25177330f729Sjoerg       if (D.isARCPseudoStrong()) {
25187330f729Sjoerg         assert(lt == Qualifiers::OCL_Strong &&
25197330f729Sjoerg                "pseudo-strong variable isn't strong?");
25207330f729Sjoerg         assert(qs.hasConst() && "pseudo-strong variable should be const!");
25217330f729Sjoerg         lt = Qualifiers::OCL_ExplicitNone;
25227330f729Sjoerg       }
25237330f729Sjoerg 
25247330f729Sjoerg       // Load objects passed indirectly.
25257330f729Sjoerg       if (Arg.isIndirect() && !ArgVal)
25267330f729Sjoerg         ArgVal = Builder.CreateLoad(DeclPtr);
25277330f729Sjoerg 
25287330f729Sjoerg       if (lt == Qualifiers::OCL_Strong) {
25297330f729Sjoerg         if (!isConsumed) {
25307330f729Sjoerg           if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
25317330f729Sjoerg             // use objc_storeStrong(&dest, value) for retaining the
25327330f729Sjoerg             // object. But first, store a null into 'dest' because
25337330f729Sjoerg             // objc_storeStrong attempts to release its old value.
25347330f729Sjoerg             llvm::Value *Null = CGM.EmitNullConstant(D.getType());
25357330f729Sjoerg             EmitStoreOfScalar(Null, lv, /* isInitialization */ true);
2536*e038c9c4Sjoerg             EmitARCStoreStrongCall(lv.getAddress(*this), ArgVal, true);
25377330f729Sjoerg             DoStore = false;
25387330f729Sjoerg           }
25397330f729Sjoerg           else
25407330f729Sjoerg           // Don't use objc_retainBlock for block pointers, because we
25417330f729Sjoerg           // don't want to Block_copy something just because we got it
25427330f729Sjoerg           // as a parameter.
25437330f729Sjoerg             ArgVal = EmitARCRetainNonBlock(ArgVal);
25447330f729Sjoerg         }
25457330f729Sjoerg       } else {
25467330f729Sjoerg         // Push the cleanup for a consumed parameter.
25477330f729Sjoerg         if (isConsumed) {
25487330f729Sjoerg           ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
25497330f729Sjoerg                                 ? ARCPreciseLifetime : ARCImpreciseLifetime);
25507330f729Sjoerg           EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), ArgVal,
25517330f729Sjoerg                                                    precise);
25527330f729Sjoerg         }
25537330f729Sjoerg 
25547330f729Sjoerg         if (lt == Qualifiers::OCL_Weak) {
25557330f729Sjoerg           EmitARCInitWeak(DeclPtr, ArgVal);
25567330f729Sjoerg           DoStore = false; // The weak init is a store, no need to do two.
25577330f729Sjoerg         }
25587330f729Sjoerg       }
25597330f729Sjoerg 
25607330f729Sjoerg       // Enter the cleanup scope.
25617330f729Sjoerg       EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
25627330f729Sjoerg     }
25637330f729Sjoerg   }
25647330f729Sjoerg 
25657330f729Sjoerg   // Store the initial value into the alloca.
25667330f729Sjoerg   if (DoStore)
25677330f729Sjoerg     EmitStoreOfScalar(ArgVal, lv, /* isInitialization */ true);
25687330f729Sjoerg 
25697330f729Sjoerg   setAddrOfLocalVar(&D, DeclPtr);
25707330f729Sjoerg 
25717330f729Sjoerg   // Emit debug info for param declarations in non-thunk functions.
25727330f729Sjoerg   if (CGDebugInfo *DI = getDebugInfo()) {
2573*e038c9c4Sjoerg     if (CGM.getCodeGenOpts().hasReducedDebugInfo() && !CurFuncIsThunk) {
2574*e038c9c4Sjoerg       llvm::DILocalVariable *DILocalVar = DI->EmitDeclareOfArgVariable(
2575*e038c9c4Sjoerg           &D, DeclPtr.getPointer(), ArgNo, Builder);
2576*e038c9c4Sjoerg       if (const auto *Var = dyn_cast_or_null<ParmVarDecl>(&D))
2577*e038c9c4Sjoerg         DI->getParamDbgMappings().insert({Var, DILocalVar});
25787330f729Sjoerg     }
25797330f729Sjoerg   }
25807330f729Sjoerg 
25817330f729Sjoerg   if (D.hasAttr<AnnotateAttr>())
25827330f729Sjoerg     EmitVarAnnotations(&D, DeclPtr.getPointer());
25837330f729Sjoerg 
25847330f729Sjoerg   // We can only check return value nullability if all arguments to the
25857330f729Sjoerg   // function satisfy their nullability preconditions. This makes it necessary
25867330f729Sjoerg   // to emit null checks for args in the function body itself.
25877330f729Sjoerg   if (requiresReturnValueNullabilityCheck()) {
25887330f729Sjoerg     auto Nullability = Ty->getNullability(getContext());
25897330f729Sjoerg     if (Nullability && *Nullability == NullabilityKind::NonNull) {
25907330f729Sjoerg       SanitizerScope SanScope(this);
25917330f729Sjoerg       RetValNullabilityPrecondition =
25927330f729Sjoerg           Builder.CreateAnd(RetValNullabilityPrecondition,
25937330f729Sjoerg                             Builder.CreateIsNotNull(Arg.getAnyValue()));
25947330f729Sjoerg     }
25957330f729Sjoerg   }
25967330f729Sjoerg }
25977330f729Sjoerg 
EmitOMPDeclareReduction(const OMPDeclareReductionDecl * D,CodeGenFunction * CGF)25987330f729Sjoerg void CodeGenModule::EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D,
25997330f729Sjoerg                                             CodeGenFunction *CGF) {
26007330f729Sjoerg   if (!LangOpts.OpenMP || (!LangOpts.EmitAllDecls && !D->isUsed()))
26017330f729Sjoerg     return;
26027330f729Sjoerg   getOpenMPRuntime().emitUserDefinedReduction(CGF, D);
26037330f729Sjoerg }
26047330f729Sjoerg 
EmitOMPDeclareMapper(const OMPDeclareMapperDecl * D,CodeGenFunction * CGF)26057330f729Sjoerg void CodeGenModule::EmitOMPDeclareMapper(const OMPDeclareMapperDecl *D,
26067330f729Sjoerg                                          CodeGenFunction *CGF) {
26077330f729Sjoerg   if (!LangOpts.OpenMP || LangOpts.OpenMPSimd ||
26087330f729Sjoerg       (!LangOpts.EmitAllDecls && !D->isUsed()))
26097330f729Sjoerg     return;
26107330f729Sjoerg   getOpenMPRuntime().emitUserDefinedMapper(D, CGF);
26117330f729Sjoerg }
26127330f729Sjoerg 
EmitOMPRequiresDecl(const OMPRequiresDecl * D)26137330f729Sjoerg void CodeGenModule::EmitOMPRequiresDecl(const OMPRequiresDecl *D) {
2614*e038c9c4Sjoerg   getOpenMPRuntime().processRequiresDirective(D);
2615*e038c9c4Sjoerg }
2616*e038c9c4Sjoerg 
EmitOMPAllocateDecl(const OMPAllocateDecl * D)2617*e038c9c4Sjoerg void CodeGenModule::EmitOMPAllocateDecl(const OMPAllocateDecl *D) {
2618*e038c9c4Sjoerg   for (const Expr *E : D->varlists()) {
2619*e038c9c4Sjoerg     const auto *DE = cast<DeclRefExpr>(E);
2620*e038c9c4Sjoerg     const auto *VD = cast<VarDecl>(DE->getDecl());
2621*e038c9c4Sjoerg 
2622*e038c9c4Sjoerg     // Skip all but globals.
2623*e038c9c4Sjoerg     if (!VD->hasGlobalStorage())
2624*e038c9c4Sjoerg       continue;
2625*e038c9c4Sjoerg 
2626*e038c9c4Sjoerg     // Check if the global has been materialized yet or not. If not, we are done
2627*e038c9c4Sjoerg     // as any later generation will utilize the OMPAllocateDeclAttr. However, if
2628*e038c9c4Sjoerg     // we already emitted the global we might have done so before the
2629*e038c9c4Sjoerg     // OMPAllocateDeclAttr was attached, leading to the wrong address space
2630*e038c9c4Sjoerg     // (potentially). While not pretty, common practise is to remove the old IR
2631*e038c9c4Sjoerg     // global and generate a new one, so we do that here too. Uses are replaced
2632*e038c9c4Sjoerg     // properly.
2633*e038c9c4Sjoerg     StringRef MangledName = getMangledName(VD);
2634*e038c9c4Sjoerg     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2635*e038c9c4Sjoerg     if (!Entry)
2636*e038c9c4Sjoerg       continue;
2637*e038c9c4Sjoerg 
2638*e038c9c4Sjoerg     // We can also keep the existing global if the address space is what we
2639*e038c9c4Sjoerg     // expect it to be, if not, it is replaced.
2640*e038c9c4Sjoerg     QualType ASTTy = VD->getType();
2641*e038c9c4Sjoerg     clang::LangAS GVAS = GetGlobalVarAddressSpace(VD);
2642*e038c9c4Sjoerg     auto TargetAS = getContext().getTargetAddressSpace(GVAS);
2643*e038c9c4Sjoerg     if (Entry->getType()->getAddressSpace() == TargetAS)
2644*e038c9c4Sjoerg       continue;
2645*e038c9c4Sjoerg 
2646*e038c9c4Sjoerg     // Make a new global with the correct type / address space.
2647*e038c9c4Sjoerg     llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
2648*e038c9c4Sjoerg     llvm::PointerType *PTy = llvm::PointerType::get(Ty, TargetAS);
2649*e038c9c4Sjoerg 
2650*e038c9c4Sjoerg     // Replace all uses of the old global with a cast. Since we mutate the type
2651*e038c9c4Sjoerg     // in place we neeed an intermediate that takes the spot of the old entry
2652*e038c9c4Sjoerg     // until we can create the cast.
2653*e038c9c4Sjoerg     llvm::GlobalVariable *DummyGV = new llvm::GlobalVariable(
2654*e038c9c4Sjoerg         getModule(), Entry->getValueType(), false,
2655*e038c9c4Sjoerg         llvm::GlobalValue::CommonLinkage, nullptr, "dummy", nullptr,
2656*e038c9c4Sjoerg         llvm::GlobalVariable::NotThreadLocal, Entry->getAddressSpace());
2657*e038c9c4Sjoerg     Entry->replaceAllUsesWith(DummyGV);
2658*e038c9c4Sjoerg 
2659*e038c9c4Sjoerg     Entry->mutateType(PTy);
2660*e038c9c4Sjoerg     llvm::Constant *NewPtrForOldDecl =
2661*e038c9c4Sjoerg         llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
2662*e038c9c4Sjoerg             Entry, DummyGV->getType());
2663*e038c9c4Sjoerg 
2664*e038c9c4Sjoerg     // Now we have a casted version of the changed global, the dummy can be
2665*e038c9c4Sjoerg     // replaced and deleted.
2666*e038c9c4Sjoerg     DummyGV->replaceAllUsesWith(NewPtrForOldDecl);
2667*e038c9c4Sjoerg     DummyGV->eraseFromParent();
2668*e038c9c4Sjoerg   }
26697330f729Sjoerg }
2670