10b57cec5SDimitry Andric //===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===// 20b57cec5SDimitry Andric // 30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information. 50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 60b57cec5SDimitry Andric // 70b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 80b57cec5SDimitry Andric // 90b57cec5SDimitry Andric // This coordinates the per-function state used while generating code. 100b57cec5SDimitry Andric // 110b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 120b57cec5SDimitry Andric 130b57cec5SDimitry Andric #include "CodeGenFunction.h" 140b57cec5SDimitry Andric #include "CGBlocks.h" 150b57cec5SDimitry Andric #include "CGCUDARuntime.h" 160b57cec5SDimitry Andric #include "CGCXXABI.h" 17480093f4SDimitry Andric #include "CGCleanup.h" 180b57cec5SDimitry Andric #include "CGDebugInfo.h" 19bdd1243dSDimitry Andric #include "CGHLSLRuntime.h" 200b57cec5SDimitry Andric #include "CGOpenMPRuntime.h" 210b57cec5SDimitry Andric #include "CodeGenModule.h" 220b57cec5SDimitry Andric #include "CodeGenPGO.h" 230b57cec5SDimitry Andric #include "TargetInfo.h" 240b57cec5SDimitry Andric #include "clang/AST/ASTContext.h" 250b57cec5SDimitry Andric #include "clang/AST/ASTLambda.h" 26480093f4SDimitry Andric #include "clang/AST/Attr.h" 270b57cec5SDimitry Andric #include "clang/AST/Decl.h" 280b57cec5SDimitry Andric #include "clang/AST/DeclCXX.h" 29e8d8bef9SDimitry Andric #include "clang/AST/Expr.h" 300b57cec5SDimitry Andric #include "clang/AST/StmtCXX.h" 310b57cec5SDimitry Andric #include "clang/AST/StmtObjC.h" 320b57cec5SDimitry Andric #include "clang/Basic/Builtins.h" 330b57cec5SDimitry Andric #include "clang/Basic/CodeGenOptions.h" 340b57cec5SDimitry Andric #include "clang/Basic/TargetInfo.h" 350b57cec5SDimitry Andric #include "clang/CodeGen/CGFunctionInfo.h" 360b57cec5SDimitry Andric #include "clang/Frontend/FrontendDiagnostic.h" 37e8d8bef9SDimitry Andric #include "llvm/ADT/ArrayRef.h" 385ffd83dbSDimitry Andric #include "llvm/Frontend/OpenMP/OMPIRBuilder.h" 390b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h" 400b57cec5SDimitry Andric #include "llvm/IR/Dominators.h" 41480093f4SDimitry Andric #include "llvm/IR/FPEnv.h" 42480093f4SDimitry Andric #include "llvm/IR/IntrinsicInst.h" 430b57cec5SDimitry Andric #include "llvm/IR/Intrinsics.h" 440b57cec5SDimitry Andric #include "llvm/IR/MDBuilder.h" 450b57cec5SDimitry Andric #include "llvm/IR/Operator.h" 46e8d8bef9SDimitry Andric #include "llvm/Support/CRC.h" 47*fe013be4SDimitry Andric #include "llvm/Support/xxhash.h" 48e8d8bef9SDimitry Andric #include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h" 490b57cec5SDimitry Andric #include "llvm/Transforms/Utils/PromoteMemToReg.h" 50bdd1243dSDimitry Andric #include <optional> 51349cc55cSDimitry Andric 520b57cec5SDimitry Andric using namespace clang; 530b57cec5SDimitry Andric using namespace CodeGen; 540b57cec5SDimitry Andric 550b57cec5SDimitry Andric /// shouldEmitLifetimeMarkers - Decide whether we need emit the life-time 560b57cec5SDimitry Andric /// markers. 570b57cec5SDimitry Andric static bool shouldEmitLifetimeMarkers(const CodeGenOptions &CGOpts, 580b57cec5SDimitry Andric const LangOptions &LangOpts) { 590b57cec5SDimitry Andric if (CGOpts.DisableLifetimeMarkers) 600b57cec5SDimitry Andric return false; 610b57cec5SDimitry Andric 62a7dea167SDimitry Andric // Sanitizers may use markers. 63a7dea167SDimitry Andric if (CGOpts.SanitizeAddressUseAfterScope || 64a7dea167SDimitry Andric LangOpts.Sanitize.has(SanitizerKind::HWAddress) || 65a7dea167SDimitry Andric LangOpts.Sanitize.has(SanitizerKind::Memory)) 660b57cec5SDimitry Andric return true; 670b57cec5SDimitry Andric 680b57cec5SDimitry Andric // For now, only in optimized builds. 690b57cec5SDimitry Andric return CGOpts.OptimizationLevel != 0; 700b57cec5SDimitry Andric } 710b57cec5SDimitry Andric 720b57cec5SDimitry Andric CodeGenFunction::CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext) 730b57cec5SDimitry Andric : CodeGenTypeCache(cgm), CGM(cgm), Target(cgm.getTarget()), 740b57cec5SDimitry Andric Builder(cgm, cgm.getModule().getContext(), llvm::ConstantFolder(), 750b57cec5SDimitry Andric CGBuilderInserterTy(this)), 765ffd83dbSDimitry Andric SanOpts(CGM.getLangOpts().Sanitize), CurFPFeatures(CGM.getLangOpts()), 775ffd83dbSDimitry Andric DebugInfo(CGM.getModuleDebugInfo()), PGO(cgm), 785ffd83dbSDimitry Andric ShouldEmitLifetimeMarkers( 795ffd83dbSDimitry Andric shouldEmitLifetimeMarkers(CGM.getCodeGenOpts(), CGM.getLangOpts())) { 800b57cec5SDimitry Andric if (!suppressNewContext) 810b57cec5SDimitry Andric CGM.getCXXABI().getMangleContext().startNewFunction(); 82fe6060f1SDimitry Andric EHStack.setCGF(this); 830b57cec5SDimitry Andric 845ffd83dbSDimitry Andric SetFastMathFlags(CurFPFeatures); 850b57cec5SDimitry Andric } 860b57cec5SDimitry Andric 870b57cec5SDimitry Andric CodeGenFunction::~CodeGenFunction() { 880b57cec5SDimitry Andric assert(LifetimeExtendedCleanupStack.empty() && "failed to emit a cleanup"); 890b57cec5SDimitry Andric 900b57cec5SDimitry Andric if (getLangOpts().OpenMP && CurFn) 910b57cec5SDimitry Andric CGM.getOpenMPRuntime().functionFinished(*this); 920b57cec5SDimitry Andric 935ffd83dbSDimitry Andric // If we have an OpenMPIRBuilder we want to finalize functions (incl. 945ffd83dbSDimitry Andric // outlining etc) at some point. Doing it once the function codegen is done 955ffd83dbSDimitry Andric // seems to be a reasonable spot. We do it here, as opposed to the deletion 965ffd83dbSDimitry Andric // time of the CodeGenModule, because we have to ensure the IR has not yet 975ffd83dbSDimitry Andric // been "emitted" to the outside, thus, modifications are still sensible. 98fe6060f1SDimitry Andric if (CGM.getLangOpts().OpenMPIRBuilder && CurFn) 99fe6060f1SDimitry Andric CGM.getOpenMPRuntime().getOMPBuilder().finalize(CurFn); 100480093f4SDimitry Andric } 101480093f4SDimitry Andric 102480093f4SDimitry Andric // Map the LangOption for exception behavior into 103480093f4SDimitry Andric // the corresponding enum in the IR. 1045ffd83dbSDimitry Andric llvm::fp::ExceptionBehavior 1055ffd83dbSDimitry Andric clang::ToConstrainedExceptMD(LangOptions::FPExceptionModeKind Kind) { 106480093f4SDimitry Andric 107480093f4SDimitry Andric switch (Kind) { 108480093f4SDimitry Andric case LangOptions::FPE_Ignore: return llvm::fp::ebIgnore; 109480093f4SDimitry Andric case LangOptions::FPE_MayTrap: return llvm::fp::ebMayTrap; 110480093f4SDimitry Andric case LangOptions::FPE_Strict: return llvm::fp::ebStrict; 11181ad6265SDimitry Andric default: 112480093f4SDimitry Andric llvm_unreachable("Unsupported FP Exception Behavior"); 113480093f4SDimitry Andric } 11481ad6265SDimitry Andric } 115480093f4SDimitry Andric 1165ffd83dbSDimitry Andric void CodeGenFunction::SetFastMathFlags(FPOptions FPFeatures) { 1175ffd83dbSDimitry Andric llvm::FastMathFlags FMF; 1185ffd83dbSDimitry Andric FMF.setAllowReassoc(FPFeatures.getAllowFPReassociate()); 1195ffd83dbSDimitry Andric FMF.setNoNaNs(FPFeatures.getNoHonorNaNs()); 1205ffd83dbSDimitry Andric FMF.setNoInfs(FPFeatures.getNoHonorInfs()); 1215ffd83dbSDimitry Andric FMF.setNoSignedZeros(FPFeatures.getNoSignedZero()); 1225ffd83dbSDimitry Andric FMF.setAllowReciprocal(FPFeatures.getAllowReciprocal()); 1235ffd83dbSDimitry Andric FMF.setApproxFunc(FPFeatures.getAllowApproxFunc()); 1245ffd83dbSDimitry Andric FMF.setAllowContract(FPFeatures.allowFPContractAcrossStatement()); 1255ffd83dbSDimitry Andric Builder.setFastMathFlags(FMF); 1260b57cec5SDimitry Andric } 1270b57cec5SDimitry Andric 1285ffd83dbSDimitry Andric CodeGenFunction::CGFPOptionsRAII::CGFPOptionsRAII(CodeGenFunction &CGF, 129e8d8bef9SDimitry Andric const Expr *E) 130e8d8bef9SDimitry Andric : CGF(CGF) { 131e8d8bef9SDimitry Andric ConstructorHelper(E->getFPFeaturesInEffect(CGF.getLangOpts())); 132e8d8bef9SDimitry Andric } 133e8d8bef9SDimitry Andric 134e8d8bef9SDimitry Andric CodeGenFunction::CGFPOptionsRAII::CGFPOptionsRAII(CodeGenFunction &CGF, 1355ffd83dbSDimitry Andric FPOptions FPFeatures) 136e8d8bef9SDimitry Andric : CGF(CGF) { 137e8d8bef9SDimitry Andric ConstructorHelper(FPFeatures); 138e8d8bef9SDimitry Andric } 139e8d8bef9SDimitry Andric 140e8d8bef9SDimitry Andric void CodeGenFunction::CGFPOptionsRAII::ConstructorHelper(FPOptions FPFeatures) { 141e8d8bef9SDimitry Andric OldFPFeatures = CGF.CurFPFeatures; 1425ffd83dbSDimitry Andric CGF.CurFPFeatures = FPFeatures; 1430b57cec5SDimitry Andric 144e8d8bef9SDimitry Andric OldExcept = CGF.Builder.getDefaultConstrainedExcept(); 145e8d8bef9SDimitry Andric OldRounding = CGF.Builder.getDefaultConstrainedRounding(); 146e8d8bef9SDimitry Andric 1475ffd83dbSDimitry Andric if (OldFPFeatures == FPFeatures) 1485ffd83dbSDimitry Andric return; 1495ffd83dbSDimitry Andric 1505ffd83dbSDimitry Andric FMFGuard.emplace(CGF.Builder); 1515ffd83dbSDimitry Andric 15281ad6265SDimitry Andric llvm::RoundingMode NewRoundingBehavior = FPFeatures.getRoundingMode(); 1535ffd83dbSDimitry Andric CGF.Builder.setDefaultConstrainedRounding(NewRoundingBehavior); 1545ffd83dbSDimitry Andric auto NewExceptionBehavior = 1555ffd83dbSDimitry Andric ToConstrainedExceptMD(static_cast<LangOptions::FPExceptionModeKind>( 15681ad6265SDimitry Andric FPFeatures.getExceptionMode())); 1575ffd83dbSDimitry Andric CGF.Builder.setDefaultConstrainedExcept(NewExceptionBehavior); 1585ffd83dbSDimitry Andric 1595ffd83dbSDimitry Andric CGF.SetFastMathFlags(FPFeatures); 1605ffd83dbSDimitry Andric 1615ffd83dbSDimitry Andric assert((CGF.CurFuncDecl == nullptr || CGF.Builder.getIsFPConstrained() || 1625ffd83dbSDimitry Andric isa<CXXConstructorDecl>(CGF.CurFuncDecl) || 1635ffd83dbSDimitry Andric isa<CXXDestructorDecl>(CGF.CurFuncDecl) || 1645ffd83dbSDimitry Andric (NewExceptionBehavior == llvm::fp::ebIgnore && 1655ffd83dbSDimitry Andric NewRoundingBehavior == llvm::RoundingMode::NearestTiesToEven)) && 1665ffd83dbSDimitry Andric "FPConstrained should be enabled on entire function"); 1675ffd83dbSDimitry Andric 1685ffd83dbSDimitry Andric auto mergeFnAttrValue = [&](StringRef Name, bool Value) { 1695ffd83dbSDimitry Andric auto OldValue = 170fe6060f1SDimitry Andric CGF.CurFn->getFnAttribute(Name).getValueAsBool(); 1715ffd83dbSDimitry Andric auto NewValue = OldValue & Value; 1725ffd83dbSDimitry Andric if (OldValue != NewValue) 1735ffd83dbSDimitry Andric CGF.CurFn->addFnAttr(Name, llvm::toStringRef(NewValue)); 1745ffd83dbSDimitry Andric }; 1755ffd83dbSDimitry Andric mergeFnAttrValue("no-infs-fp-math", FPFeatures.getNoHonorInfs()); 1765ffd83dbSDimitry Andric mergeFnAttrValue("no-nans-fp-math", FPFeatures.getNoHonorNaNs()); 1775ffd83dbSDimitry Andric mergeFnAttrValue("no-signed-zeros-fp-math", FPFeatures.getNoSignedZero()); 178bdd1243dSDimitry Andric mergeFnAttrValue( 179bdd1243dSDimitry Andric "unsafe-fp-math", 180bdd1243dSDimitry Andric FPFeatures.getAllowFPReassociate() && FPFeatures.getAllowReciprocal() && 181bdd1243dSDimitry Andric FPFeatures.getAllowApproxFunc() && FPFeatures.getNoSignedZero() && 182bdd1243dSDimitry Andric FPFeatures.allowFPContractAcrossStatement()); 1830b57cec5SDimitry Andric } 1840b57cec5SDimitry Andric 1855ffd83dbSDimitry Andric CodeGenFunction::CGFPOptionsRAII::~CGFPOptionsRAII() { 1865ffd83dbSDimitry Andric CGF.CurFPFeatures = OldFPFeatures; 187e8d8bef9SDimitry Andric CGF.Builder.setDefaultConstrainedExcept(OldExcept); 188e8d8bef9SDimitry Andric CGF.Builder.setDefaultConstrainedRounding(OldRounding); 1890b57cec5SDimitry Andric } 1900b57cec5SDimitry Andric 1910b57cec5SDimitry Andric LValue CodeGenFunction::MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T) { 1920b57cec5SDimitry Andric LValueBaseInfo BaseInfo; 1930b57cec5SDimitry Andric TBAAAccessInfo TBAAInfo; 1945ffd83dbSDimitry Andric CharUnits Alignment = CGM.getNaturalTypeAlignment(T, &BaseInfo, &TBAAInfo); 1950eae32dcSDimitry Andric Address Addr(V, ConvertTypeForMem(T), Alignment); 1960eae32dcSDimitry Andric return LValue::MakeAddr(Addr, T, getContext(), BaseInfo, TBAAInfo); 1970b57cec5SDimitry Andric } 1980b57cec5SDimitry Andric 1990b57cec5SDimitry Andric /// Given a value of type T* that may not be to a complete object, 2000b57cec5SDimitry Andric /// construct an l-value with the natural pointee alignment of T. 2010b57cec5SDimitry Andric LValue 2020b57cec5SDimitry Andric CodeGenFunction::MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T) { 2030b57cec5SDimitry Andric LValueBaseInfo BaseInfo; 2040b57cec5SDimitry Andric TBAAAccessInfo TBAAInfo; 2055ffd83dbSDimitry Andric CharUnits Align = CGM.getNaturalTypeAlignment(T, &BaseInfo, &TBAAInfo, 2060b57cec5SDimitry Andric /* forPointeeType= */ true); 2070eae32dcSDimitry Andric Address Addr(V, ConvertTypeForMem(T), Align); 2080eae32dcSDimitry Andric return MakeAddrLValue(Addr, T, BaseInfo, TBAAInfo); 2090b57cec5SDimitry Andric } 2100b57cec5SDimitry Andric 2110b57cec5SDimitry Andric 2120b57cec5SDimitry Andric llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) { 2130b57cec5SDimitry Andric return CGM.getTypes().ConvertTypeForMem(T); 2140b57cec5SDimitry Andric } 2150b57cec5SDimitry Andric 2160b57cec5SDimitry Andric llvm::Type *CodeGenFunction::ConvertType(QualType T) { 2170b57cec5SDimitry Andric return CGM.getTypes().ConvertType(T); 2180b57cec5SDimitry Andric } 2190b57cec5SDimitry Andric 2200b57cec5SDimitry Andric TypeEvaluationKind CodeGenFunction::getEvaluationKind(QualType type) { 2210b57cec5SDimitry Andric type = type.getCanonicalType(); 2220b57cec5SDimitry Andric while (true) { 2230b57cec5SDimitry Andric switch (type->getTypeClass()) { 2240b57cec5SDimitry Andric #define TYPE(name, parent) 2250b57cec5SDimitry Andric #define ABSTRACT_TYPE(name, parent) 2260b57cec5SDimitry Andric #define NON_CANONICAL_TYPE(name, parent) case Type::name: 2270b57cec5SDimitry Andric #define DEPENDENT_TYPE(name, parent) case Type::name: 2280b57cec5SDimitry Andric #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(name, parent) case Type::name: 229a7dea167SDimitry Andric #include "clang/AST/TypeNodes.inc" 2300b57cec5SDimitry Andric llvm_unreachable("non-canonical or dependent type in IR-generation"); 2310b57cec5SDimitry Andric 2320b57cec5SDimitry Andric case Type::Auto: 2330b57cec5SDimitry Andric case Type::DeducedTemplateSpecialization: 2340b57cec5SDimitry Andric llvm_unreachable("undeduced type in IR-generation"); 2350b57cec5SDimitry Andric 2360b57cec5SDimitry Andric // Various scalar types. 2370b57cec5SDimitry Andric case Type::Builtin: 2380b57cec5SDimitry Andric case Type::Pointer: 2390b57cec5SDimitry Andric case Type::BlockPointer: 2400b57cec5SDimitry Andric case Type::LValueReference: 2410b57cec5SDimitry Andric case Type::RValueReference: 2420b57cec5SDimitry Andric case Type::MemberPointer: 2430b57cec5SDimitry Andric case Type::Vector: 2440b57cec5SDimitry Andric case Type::ExtVector: 2455ffd83dbSDimitry Andric case Type::ConstantMatrix: 2460b57cec5SDimitry Andric case Type::FunctionProto: 2470b57cec5SDimitry Andric case Type::FunctionNoProto: 2480b57cec5SDimitry Andric case Type::Enum: 2490b57cec5SDimitry Andric case Type::ObjCObjectPointer: 2500b57cec5SDimitry Andric case Type::Pipe: 2510eae32dcSDimitry Andric case Type::BitInt: 2520b57cec5SDimitry Andric return TEK_Scalar; 2530b57cec5SDimitry Andric 2540b57cec5SDimitry Andric // Complexes. 2550b57cec5SDimitry Andric case Type::Complex: 2560b57cec5SDimitry Andric return TEK_Complex; 2570b57cec5SDimitry Andric 2580b57cec5SDimitry Andric // Arrays, records, and Objective-C objects. 2590b57cec5SDimitry Andric case Type::ConstantArray: 2600b57cec5SDimitry Andric case Type::IncompleteArray: 2610b57cec5SDimitry Andric case Type::VariableArray: 2620b57cec5SDimitry Andric case Type::Record: 2630b57cec5SDimitry Andric case Type::ObjCObject: 2640b57cec5SDimitry Andric case Type::ObjCInterface: 2650b57cec5SDimitry Andric return TEK_Aggregate; 2660b57cec5SDimitry Andric 2670b57cec5SDimitry Andric // We operate on atomic values according to their underlying type. 2680b57cec5SDimitry Andric case Type::Atomic: 2690b57cec5SDimitry Andric type = cast<AtomicType>(type)->getValueType(); 2700b57cec5SDimitry Andric continue; 2710b57cec5SDimitry Andric } 2720b57cec5SDimitry Andric llvm_unreachable("unknown type kind!"); 2730b57cec5SDimitry Andric } 2740b57cec5SDimitry Andric } 2750b57cec5SDimitry Andric 2760b57cec5SDimitry Andric llvm::DebugLoc CodeGenFunction::EmitReturnBlock() { 2770b57cec5SDimitry Andric // For cleanliness, we try to avoid emitting the return block for 2780b57cec5SDimitry Andric // simple cases. 2790b57cec5SDimitry Andric llvm::BasicBlock *CurBB = Builder.GetInsertBlock(); 2800b57cec5SDimitry Andric 2810b57cec5SDimitry Andric if (CurBB) { 2820b57cec5SDimitry Andric assert(!CurBB->getTerminator() && "Unexpected terminated block."); 2830b57cec5SDimitry Andric 2840b57cec5SDimitry Andric // We have a valid insert point, reuse it if it is empty or there are no 2850b57cec5SDimitry Andric // explicit jumps to the return block. 2860b57cec5SDimitry Andric if (CurBB->empty() || ReturnBlock.getBlock()->use_empty()) { 2870b57cec5SDimitry Andric ReturnBlock.getBlock()->replaceAllUsesWith(CurBB); 2880b57cec5SDimitry Andric delete ReturnBlock.getBlock(); 2890b57cec5SDimitry Andric ReturnBlock = JumpDest(); 2900b57cec5SDimitry Andric } else 2910b57cec5SDimitry Andric EmitBlock(ReturnBlock.getBlock()); 2920b57cec5SDimitry Andric return llvm::DebugLoc(); 2930b57cec5SDimitry Andric } 2940b57cec5SDimitry Andric 2950b57cec5SDimitry Andric // Otherwise, if the return block is the target of a single direct 2960b57cec5SDimitry Andric // branch then we can just put the code in that block instead. This 2970b57cec5SDimitry Andric // cleans up functions which started with a unified return block. 2980b57cec5SDimitry Andric if (ReturnBlock.getBlock()->hasOneUse()) { 2990b57cec5SDimitry Andric llvm::BranchInst *BI = 3000b57cec5SDimitry Andric dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->user_begin()); 3010b57cec5SDimitry Andric if (BI && BI->isUnconditional() && 3020b57cec5SDimitry Andric BI->getSuccessor(0) == ReturnBlock.getBlock()) { 3030b57cec5SDimitry Andric // Record/return the DebugLoc of the simple 'return' expression to be used 3040b57cec5SDimitry Andric // later by the actual 'ret' instruction. 3050b57cec5SDimitry Andric llvm::DebugLoc Loc = BI->getDebugLoc(); 3060b57cec5SDimitry Andric Builder.SetInsertPoint(BI->getParent()); 3070b57cec5SDimitry Andric BI->eraseFromParent(); 3080b57cec5SDimitry Andric delete ReturnBlock.getBlock(); 3090b57cec5SDimitry Andric ReturnBlock = JumpDest(); 3100b57cec5SDimitry Andric return Loc; 3110b57cec5SDimitry Andric } 3120b57cec5SDimitry Andric } 3130b57cec5SDimitry Andric 3140b57cec5SDimitry Andric // FIXME: We are at an unreachable point, there is no reason to emit the block 3150b57cec5SDimitry Andric // unless it has uses. However, we still need a place to put the debug 3160b57cec5SDimitry Andric // region.end for now. 3170b57cec5SDimitry Andric 3180b57cec5SDimitry Andric EmitBlock(ReturnBlock.getBlock()); 3190b57cec5SDimitry Andric return llvm::DebugLoc(); 3200b57cec5SDimitry Andric } 3210b57cec5SDimitry Andric 3220b57cec5SDimitry Andric static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) { 3230b57cec5SDimitry Andric if (!BB) return; 324bdd1243dSDimitry Andric if (!BB->use_empty()) { 325bdd1243dSDimitry Andric CGF.CurFn->insert(CGF.CurFn->end(), BB); 326bdd1243dSDimitry Andric return; 327bdd1243dSDimitry Andric } 3280b57cec5SDimitry Andric delete BB; 3290b57cec5SDimitry Andric } 3300b57cec5SDimitry Andric 3310b57cec5SDimitry Andric void CodeGenFunction::FinishFunction(SourceLocation EndLoc) { 3320b57cec5SDimitry Andric assert(BreakContinueStack.empty() && 3330b57cec5SDimitry Andric "mismatched push/pop in break/continue stack!"); 3340b57cec5SDimitry Andric 3350b57cec5SDimitry Andric bool OnlySimpleReturnStmts = NumSimpleReturnExprs > 0 3360b57cec5SDimitry Andric && NumSimpleReturnExprs == NumReturnExprs 3370b57cec5SDimitry Andric && ReturnBlock.getBlock()->use_empty(); 3380b57cec5SDimitry Andric // Usually the return expression is evaluated before the cleanup 3390b57cec5SDimitry Andric // code. If the function contains only a simple return statement, 3400b57cec5SDimitry Andric // such as a constant, the location before the cleanup code becomes 3410b57cec5SDimitry Andric // the last useful breakpoint in the function, because the simple 3420b57cec5SDimitry Andric // return expression will be evaluated after the cleanup code. To be 3430b57cec5SDimitry Andric // safe, set the debug location for cleanup code to the location of 3440b57cec5SDimitry Andric // the return statement. Otherwise the cleanup code should be at the 3450b57cec5SDimitry Andric // end of the function's lexical scope. 3460b57cec5SDimitry Andric // 3470b57cec5SDimitry Andric // If there are multiple branches to the return block, the branch 3480b57cec5SDimitry Andric // instructions will get the location of the return statements and 3490b57cec5SDimitry Andric // all will be fine. 3500b57cec5SDimitry Andric if (CGDebugInfo *DI = getDebugInfo()) { 3510b57cec5SDimitry Andric if (OnlySimpleReturnStmts) 3520b57cec5SDimitry Andric DI->EmitLocation(Builder, LastStopPoint); 3530b57cec5SDimitry Andric else 3540b57cec5SDimitry Andric DI->EmitLocation(Builder, EndLoc); 3550b57cec5SDimitry Andric } 3560b57cec5SDimitry Andric 3570b57cec5SDimitry Andric // Pop any cleanups that might have been associated with the 3580b57cec5SDimitry Andric // parameters. Do this in whatever block we're currently in; it's 3590b57cec5SDimitry Andric // important to do this before we enter the return block or return 3600b57cec5SDimitry Andric // edges will be *really* confused. 3610b57cec5SDimitry Andric bool HasCleanups = EHStack.stable_begin() != PrologueCleanupDepth; 3620b57cec5SDimitry Andric bool HasOnlyLifetimeMarkers = 3630b57cec5SDimitry Andric HasCleanups && EHStack.containsOnlyLifetimeMarkers(PrologueCleanupDepth); 3640b57cec5SDimitry Andric bool EmitRetDbgLoc = !HasCleanups || HasOnlyLifetimeMarkers; 365bdd1243dSDimitry Andric 366bdd1243dSDimitry Andric std::optional<ApplyDebugLocation> OAL; 3670b57cec5SDimitry Andric if (HasCleanups) { 3680b57cec5SDimitry Andric // Make sure the line table doesn't jump back into the body for 3690b57cec5SDimitry Andric // the ret after it's been at EndLoc. 370480093f4SDimitry Andric if (CGDebugInfo *DI = getDebugInfo()) { 3710b57cec5SDimitry Andric if (OnlySimpleReturnStmts) 3720b57cec5SDimitry Andric DI->EmitLocation(Builder, EndLoc); 373480093f4SDimitry Andric else 374480093f4SDimitry Andric // We may not have a valid end location. Try to apply it anyway, and 375480093f4SDimitry Andric // fall back to an artificial location if needed. 376bdd1243dSDimitry Andric OAL = ApplyDebugLocation::CreateDefaultArtificial(*this, EndLoc); 377480093f4SDimitry Andric } 3780b57cec5SDimitry Andric 3790b57cec5SDimitry Andric PopCleanupBlocks(PrologueCleanupDepth); 3800b57cec5SDimitry Andric } 3810b57cec5SDimitry Andric 3820b57cec5SDimitry Andric // Emit function epilog (to return). 3830b57cec5SDimitry Andric llvm::DebugLoc Loc = EmitReturnBlock(); 3840b57cec5SDimitry Andric 3850b57cec5SDimitry Andric if (ShouldInstrumentFunction()) { 3860b57cec5SDimitry Andric if (CGM.getCodeGenOpts().InstrumentFunctions) 3870b57cec5SDimitry Andric CurFn->addFnAttr("instrument-function-exit", "__cyg_profile_func_exit"); 3880b57cec5SDimitry Andric if (CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining) 3890b57cec5SDimitry Andric CurFn->addFnAttr("instrument-function-exit-inlined", 3900b57cec5SDimitry Andric "__cyg_profile_func_exit"); 3910b57cec5SDimitry Andric } 3920b57cec5SDimitry Andric 3930b57cec5SDimitry Andric // Emit debug descriptor for function end. 3940b57cec5SDimitry Andric if (CGDebugInfo *DI = getDebugInfo()) 3950b57cec5SDimitry Andric DI->EmitFunctionEnd(Builder, CurFn); 3960b57cec5SDimitry Andric 3970b57cec5SDimitry Andric // Reset the debug location to that of the simple 'return' expression, if any 3980b57cec5SDimitry Andric // rather than that of the end of the function's scope '}'. 3990b57cec5SDimitry Andric ApplyDebugLocation AL(*this, Loc); 4000b57cec5SDimitry Andric EmitFunctionEpilog(*CurFnInfo, EmitRetDbgLoc, EndLoc); 4010b57cec5SDimitry Andric EmitEndEHSpec(CurCodeDecl); 4020b57cec5SDimitry Andric 4030b57cec5SDimitry Andric assert(EHStack.empty() && 4040b57cec5SDimitry Andric "did not remove all scopes from cleanup stack!"); 4050b57cec5SDimitry Andric 4060b57cec5SDimitry Andric // If someone did an indirect goto, emit the indirect goto block at the end of 4070b57cec5SDimitry Andric // the function. 4080b57cec5SDimitry Andric if (IndirectBranch) { 4090b57cec5SDimitry Andric EmitBlock(IndirectBranch->getParent()); 4100b57cec5SDimitry Andric Builder.ClearInsertionPoint(); 4110b57cec5SDimitry Andric } 4120b57cec5SDimitry Andric 4130b57cec5SDimitry Andric // If some of our locals escaped, insert a call to llvm.localescape in the 4140b57cec5SDimitry Andric // entry block. 4150b57cec5SDimitry Andric if (!EscapedLocals.empty()) { 4160b57cec5SDimitry Andric // Invert the map from local to index into a simple vector. There should be 4170b57cec5SDimitry Andric // no holes. 4180b57cec5SDimitry Andric SmallVector<llvm::Value *, 4> EscapeArgs; 4190b57cec5SDimitry Andric EscapeArgs.resize(EscapedLocals.size()); 4200b57cec5SDimitry Andric for (auto &Pair : EscapedLocals) 4210b57cec5SDimitry Andric EscapeArgs[Pair.second] = Pair.first; 4220b57cec5SDimitry Andric llvm::Function *FrameEscapeFn = llvm::Intrinsic::getDeclaration( 4230b57cec5SDimitry Andric &CGM.getModule(), llvm::Intrinsic::localescape); 4240b57cec5SDimitry Andric CGBuilderTy(*this, AllocaInsertPt).CreateCall(FrameEscapeFn, EscapeArgs); 4250b57cec5SDimitry Andric } 4260b57cec5SDimitry Andric 4270b57cec5SDimitry Andric // Remove the AllocaInsertPt instruction, which is just a convenience for us. 4280b57cec5SDimitry Andric llvm::Instruction *Ptr = AllocaInsertPt; 4290b57cec5SDimitry Andric AllocaInsertPt = nullptr; 4300b57cec5SDimitry Andric Ptr->eraseFromParent(); 4310b57cec5SDimitry Andric 432349cc55cSDimitry Andric // PostAllocaInsertPt, if created, was lazily created when it was required, 433349cc55cSDimitry Andric // remove it now since it was just created for our own convenience. 434349cc55cSDimitry Andric if (PostAllocaInsertPt) { 435349cc55cSDimitry Andric llvm::Instruction *PostPtr = PostAllocaInsertPt; 436349cc55cSDimitry Andric PostAllocaInsertPt = nullptr; 437349cc55cSDimitry Andric PostPtr->eraseFromParent(); 438349cc55cSDimitry Andric } 439349cc55cSDimitry Andric 4400b57cec5SDimitry Andric // If someone took the address of a label but never did an indirect goto, we 4410b57cec5SDimitry Andric // made a zero entry PHI node, which is illegal, zap it now. 4420b57cec5SDimitry Andric if (IndirectBranch) { 4430b57cec5SDimitry Andric llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress()); 4440b57cec5SDimitry Andric if (PN->getNumIncomingValues() == 0) { 4450b57cec5SDimitry Andric PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType())); 4460b57cec5SDimitry Andric PN->eraseFromParent(); 4470b57cec5SDimitry Andric } 4480b57cec5SDimitry Andric } 4490b57cec5SDimitry Andric 4500b57cec5SDimitry Andric EmitIfUsed(*this, EHResumeBlock); 4510b57cec5SDimitry Andric EmitIfUsed(*this, TerminateLandingPad); 4520b57cec5SDimitry Andric EmitIfUsed(*this, TerminateHandler); 4530b57cec5SDimitry Andric EmitIfUsed(*this, UnreachableBlock); 4540b57cec5SDimitry Andric 4550b57cec5SDimitry Andric for (const auto &FuncletAndParent : TerminateFunclets) 4560b57cec5SDimitry Andric EmitIfUsed(*this, FuncletAndParent.second); 4570b57cec5SDimitry Andric 4580b57cec5SDimitry Andric if (CGM.getCodeGenOpts().EmitDeclMetadata) 4590b57cec5SDimitry Andric EmitDeclMetadata(); 4600b57cec5SDimitry Andric 461fe6060f1SDimitry Andric for (const auto &R : DeferredReplacements) { 462fe6060f1SDimitry Andric if (llvm::Value *Old = R.first) { 463fe6060f1SDimitry Andric Old->replaceAllUsesWith(R.second); 464fe6060f1SDimitry Andric cast<llvm::Instruction>(Old)->eraseFromParent(); 4650b57cec5SDimitry Andric } 466fe6060f1SDimitry Andric } 467fe6060f1SDimitry Andric DeferredReplacements.clear(); 4680b57cec5SDimitry Andric 4690b57cec5SDimitry Andric // Eliminate CleanupDestSlot alloca by replacing it with SSA values and 4700b57cec5SDimitry Andric // PHIs if the current function is a coroutine. We don't do it for all 4710b57cec5SDimitry Andric // functions as it may result in slight increase in numbers of instructions 4720b57cec5SDimitry Andric // if compiled with no optimizations. We do it for coroutine as the lifetime 4730b57cec5SDimitry Andric // of CleanupDestSlot alloca make correct coroutine frame building very 4740b57cec5SDimitry Andric // difficult. 4750b57cec5SDimitry Andric if (NormalCleanupDest.isValid() && isCoroutine()) { 4760b57cec5SDimitry Andric llvm::DominatorTree DT(*CurFn); 4770b57cec5SDimitry Andric llvm::PromoteMemToReg( 4780b57cec5SDimitry Andric cast<llvm::AllocaInst>(NormalCleanupDest.getPointer()), DT); 4790b57cec5SDimitry Andric NormalCleanupDest = Address::invalid(); 4800b57cec5SDimitry Andric } 4810b57cec5SDimitry Andric 4820b57cec5SDimitry Andric // Scan function arguments for vector width. 4830b57cec5SDimitry Andric for (llvm::Argument &A : CurFn->args()) 4840b57cec5SDimitry Andric if (auto *VT = dyn_cast<llvm::VectorType>(A.getType())) 4855ffd83dbSDimitry Andric LargestVectorWidth = 4865ffd83dbSDimitry Andric std::max((uint64_t)LargestVectorWidth, 487bdd1243dSDimitry Andric VT->getPrimitiveSizeInBits().getKnownMinValue()); 4880b57cec5SDimitry Andric 4890b57cec5SDimitry Andric // Update vector width based on return type. 4900b57cec5SDimitry Andric if (auto *VT = dyn_cast<llvm::VectorType>(CurFn->getReturnType())) 4915ffd83dbSDimitry Andric LargestVectorWidth = 4925ffd83dbSDimitry Andric std::max((uint64_t)LargestVectorWidth, 493bdd1243dSDimitry Andric VT->getPrimitiveSizeInBits().getKnownMinValue()); 4940b57cec5SDimitry Andric 49581ad6265SDimitry Andric if (CurFnInfo->getMaxVectorWidth() > LargestVectorWidth) 49681ad6265SDimitry Andric LargestVectorWidth = CurFnInfo->getMaxVectorWidth(); 49781ad6265SDimitry Andric 4980b57cec5SDimitry Andric // Add the required-vector-width attribute. This contains the max width from: 4990b57cec5SDimitry Andric // 1. min-vector-width attribute used in the source program. 5000b57cec5SDimitry Andric // 2. Any builtins used that have a vector width specified. 5010b57cec5SDimitry Andric // 3. Values passed in and out of inline assembly. 5020b57cec5SDimitry Andric // 4. Width of vector arguments and return types for this function. 5030b57cec5SDimitry Andric // 5. Width of vector aguments and return types for functions called by this 5040b57cec5SDimitry Andric // function. 505bdd1243dSDimitry Andric if (getContext().getTargetInfo().getTriple().isX86()) 506bdd1243dSDimitry Andric CurFn->addFnAttr("min-legal-vector-width", 507bdd1243dSDimitry Andric llvm::utostr(LargestVectorWidth)); 5080b57cec5SDimitry Andric 509349cc55cSDimitry Andric // Add vscale_range attribute if appropriate. 510bdd1243dSDimitry Andric std::optional<std::pair<unsigned, unsigned>> VScaleRange = 511349cc55cSDimitry Andric getContext().getTargetInfo().getVScaleRange(getLangOpts()); 512349cc55cSDimitry Andric if (VScaleRange) { 513349cc55cSDimitry Andric CurFn->addFnAttr(llvm::Attribute::getWithVScaleRangeArgs( 51481ad6265SDimitry Andric getLLVMContext(), VScaleRange->first, VScaleRange->second)); 515fe6060f1SDimitry Andric } 516fe6060f1SDimitry Andric 5170b57cec5SDimitry Andric // If we generated an unreachable return block, delete it now. 5180b57cec5SDimitry Andric if (ReturnBlock.isValid() && ReturnBlock.getBlock()->use_empty()) { 5190b57cec5SDimitry Andric Builder.ClearInsertionPoint(); 5200b57cec5SDimitry Andric ReturnBlock.getBlock()->eraseFromParent(); 5210b57cec5SDimitry Andric } 5220b57cec5SDimitry Andric if (ReturnValue.isValid()) { 5230b57cec5SDimitry Andric auto *RetAlloca = dyn_cast<llvm::AllocaInst>(ReturnValue.getPointer()); 5240b57cec5SDimitry Andric if (RetAlloca && RetAlloca->use_empty()) { 5250b57cec5SDimitry Andric RetAlloca->eraseFromParent(); 5260b57cec5SDimitry Andric ReturnValue = Address::invalid(); 5270b57cec5SDimitry Andric } 5280b57cec5SDimitry Andric } 5290b57cec5SDimitry Andric } 5300b57cec5SDimitry Andric 5310b57cec5SDimitry Andric /// ShouldInstrumentFunction - Return true if the current function should be 5320b57cec5SDimitry Andric /// instrumented with __cyg_profile_func_* calls 5330b57cec5SDimitry Andric bool CodeGenFunction::ShouldInstrumentFunction() { 5340b57cec5SDimitry Andric if (!CGM.getCodeGenOpts().InstrumentFunctions && 5350b57cec5SDimitry Andric !CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining && 5360b57cec5SDimitry Andric !CGM.getCodeGenOpts().InstrumentFunctionEntryBare) 5370b57cec5SDimitry Andric return false; 5380b57cec5SDimitry Andric if (!CurFuncDecl || CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>()) 5390b57cec5SDimitry Andric return false; 5400b57cec5SDimitry Andric return true; 5410b57cec5SDimitry Andric } 5420b57cec5SDimitry Andric 543349cc55cSDimitry Andric bool CodeGenFunction::ShouldSkipSanitizerInstrumentation() { 544349cc55cSDimitry Andric if (!CurFuncDecl) 545349cc55cSDimitry Andric return false; 546349cc55cSDimitry Andric return CurFuncDecl->hasAttr<DisableSanitizerInstrumentationAttr>(); 547349cc55cSDimitry Andric } 548349cc55cSDimitry Andric 5490b57cec5SDimitry Andric /// ShouldXRayInstrument - Return true if the current function should be 5500b57cec5SDimitry Andric /// instrumented with XRay nop sleds. 5510b57cec5SDimitry Andric bool CodeGenFunction::ShouldXRayInstrumentFunction() const { 5520b57cec5SDimitry Andric return CGM.getCodeGenOpts().XRayInstrumentFunctions; 5530b57cec5SDimitry Andric } 5540b57cec5SDimitry Andric 5550b57cec5SDimitry Andric /// AlwaysEmitXRayCustomEvents - Return true if we should emit IR for calls to 5560b57cec5SDimitry Andric /// the __xray_customevent(...) builtin calls, when doing XRay instrumentation. 5570b57cec5SDimitry Andric bool CodeGenFunction::AlwaysEmitXRayCustomEvents() const { 5580b57cec5SDimitry Andric return CGM.getCodeGenOpts().XRayInstrumentFunctions && 5590b57cec5SDimitry Andric (CGM.getCodeGenOpts().XRayAlwaysEmitCustomEvents || 5600b57cec5SDimitry Andric CGM.getCodeGenOpts().XRayInstrumentationBundle.Mask == 5610b57cec5SDimitry Andric XRayInstrKind::Custom); 5620b57cec5SDimitry Andric } 5630b57cec5SDimitry Andric 5640b57cec5SDimitry Andric bool CodeGenFunction::AlwaysEmitXRayTypedEvents() const { 5650b57cec5SDimitry Andric return CGM.getCodeGenOpts().XRayInstrumentFunctions && 5660b57cec5SDimitry Andric (CGM.getCodeGenOpts().XRayAlwaysEmitTypedEvents || 5670b57cec5SDimitry Andric CGM.getCodeGenOpts().XRayInstrumentationBundle.Mask == 5680b57cec5SDimitry Andric XRayInstrKind::Typed); 5690b57cec5SDimitry Andric } 5700b57cec5SDimitry Andric 571*fe013be4SDimitry Andric llvm::ConstantInt * 572*fe013be4SDimitry Andric CodeGenFunction::getUBSanFunctionTypeHash(QualType Ty) const { 573*fe013be4SDimitry Andric // Remove any (C++17) exception specifications, to allow calling e.g. a 574*fe013be4SDimitry Andric // noexcept function through a non-noexcept pointer. 575*fe013be4SDimitry Andric if (!isa<FunctionNoProtoType>(Ty)) 576*fe013be4SDimitry Andric Ty = getContext().getFunctionTypeWithExceptionSpec(Ty, EST_None); 577*fe013be4SDimitry Andric std::string Mangled; 578*fe013be4SDimitry Andric llvm::raw_string_ostream Out(Mangled); 579*fe013be4SDimitry Andric CGM.getCXXABI().getMangleContext().mangleTypeName(Ty, Out, false); 580*fe013be4SDimitry Andric return llvm::ConstantInt::get( 581*fe013be4SDimitry Andric CGM.Int32Ty, static_cast<uint32_t>(llvm::xxh3_64bits(Mangled))); 5820b57cec5SDimitry Andric } 5830b57cec5SDimitry Andric 58481ad6265SDimitry Andric void CodeGenFunction::EmitKernelMetadata(const FunctionDecl *FD, 58581ad6265SDimitry Andric llvm::Function *Fn) { 58681ad6265SDimitry Andric if (!FD->hasAttr<OpenCLKernelAttr>() && !FD->hasAttr<CUDAGlobalAttr>()) 5870b57cec5SDimitry Andric return; 5880b57cec5SDimitry Andric 5890b57cec5SDimitry Andric llvm::LLVMContext &Context = getLLVMContext(); 5900b57cec5SDimitry Andric 59181ad6265SDimitry Andric CGM.GenKernelArgMetadata(Fn, FD, this); 59281ad6265SDimitry Andric 59381ad6265SDimitry Andric if (!getLangOpts().OpenCL) 59481ad6265SDimitry Andric return; 5950b57cec5SDimitry Andric 5960b57cec5SDimitry Andric if (const VecTypeHintAttr *A = FD->getAttr<VecTypeHintAttr>()) { 5970b57cec5SDimitry Andric QualType HintQTy = A->getTypeHint(); 5980b57cec5SDimitry Andric const ExtVectorType *HintEltQTy = HintQTy->getAs<ExtVectorType>(); 5990b57cec5SDimitry Andric bool IsSignedInteger = 6000b57cec5SDimitry Andric HintQTy->isSignedIntegerType() || 6010b57cec5SDimitry Andric (HintEltQTy && HintEltQTy->getElementType()->isSignedIntegerType()); 6020b57cec5SDimitry Andric llvm::Metadata *AttrMDArgs[] = { 6030b57cec5SDimitry Andric llvm::ConstantAsMetadata::get(llvm::UndefValue::get( 6040b57cec5SDimitry Andric CGM.getTypes().ConvertType(A->getTypeHint()))), 6050b57cec5SDimitry Andric llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 6060b57cec5SDimitry Andric llvm::IntegerType::get(Context, 32), 6070b57cec5SDimitry Andric llvm::APInt(32, (uint64_t)(IsSignedInteger ? 1 : 0))))}; 6080b57cec5SDimitry Andric Fn->setMetadata("vec_type_hint", llvm::MDNode::get(Context, AttrMDArgs)); 6090b57cec5SDimitry Andric } 6100b57cec5SDimitry Andric 6110b57cec5SDimitry Andric if (const WorkGroupSizeHintAttr *A = FD->getAttr<WorkGroupSizeHintAttr>()) { 6120b57cec5SDimitry Andric llvm::Metadata *AttrMDArgs[] = { 6130b57cec5SDimitry Andric llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())), 6140b57cec5SDimitry Andric llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())), 6150b57cec5SDimitry Andric llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))}; 6160b57cec5SDimitry Andric Fn->setMetadata("work_group_size_hint", llvm::MDNode::get(Context, AttrMDArgs)); 6170b57cec5SDimitry Andric } 6180b57cec5SDimitry Andric 6190b57cec5SDimitry Andric if (const ReqdWorkGroupSizeAttr *A = FD->getAttr<ReqdWorkGroupSizeAttr>()) { 6200b57cec5SDimitry Andric llvm::Metadata *AttrMDArgs[] = { 6210b57cec5SDimitry Andric llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())), 6220b57cec5SDimitry Andric llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())), 6230b57cec5SDimitry Andric llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))}; 6240b57cec5SDimitry Andric Fn->setMetadata("reqd_work_group_size", llvm::MDNode::get(Context, AttrMDArgs)); 6250b57cec5SDimitry Andric } 6260b57cec5SDimitry Andric 6270b57cec5SDimitry Andric if (const OpenCLIntelReqdSubGroupSizeAttr *A = 6280b57cec5SDimitry Andric FD->getAttr<OpenCLIntelReqdSubGroupSizeAttr>()) { 6290b57cec5SDimitry Andric llvm::Metadata *AttrMDArgs[] = { 6300b57cec5SDimitry Andric llvm::ConstantAsMetadata::get(Builder.getInt32(A->getSubGroupSize()))}; 6310b57cec5SDimitry Andric Fn->setMetadata("intel_reqd_sub_group_size", 6320b57cec5SDimitry Andric llvm::MDNode::get(Context, AttrMDArgs)); 6330b57cec5SDimitry Andric } 6340b57cec5SDimitry Andric } 6350b57cec5SDimitry Andric 6360b57cec5SDimitry Andric /// Determine whether the function F ends with a return stmt. 6370b57cec5SDimitry Andric static bool endsWithReturn(const Decl* F) { 6380b57cec5SDimitry Andric const Stmt *Body = nullptr; 6390b57cec5SDimitry Andric if (auto *FD = dyn_cast_or_null<FunctionDecl>(F)) 6400b57cec5SDimitry Andric Body = FD->getBody(); 6410b57cec5SDimitry Andric else if (auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(F)) 6420b57cec5SDimitry Andric Body = OMD->getBody(); 6430b57cec5SDimitry Andric 6440b57cec5SDimitry Andric if (auto *CS = dyn_cast_or_null<CompoundStmt>(Body)) { 6450b57cec5SDimitry Andric auto LastStmt = CS->body_rbegin(); 6460b57cec5SDimitry Andric if (LastStmt != CS->body_rend()) 6470b57cec5SDimitry Andric return isa<ReturnStmt>(*LastStmt); 6480b57cec5SDimitry Andric } 6490b57cec5SDimitry Andric return false; 6500b57cec5SDimitry Andric } 6510b57cec5SDimitry Andric 6520b57cec5SDimitry Andric void CodeGenFunction::markAsIgnoreThreadCheckingAtRuntime(llvm::Function *Fn) { 6530b57cec5SDimitry Andric if (SanOpts.has(SanitizerKind::Thread)) { 6540b57cec5SDimitry Andric Fn->addFnAttr("sanitize_thread_no_checking_at_run_time"); 6550b57cec5SDimitry Andric Fn->removeFnAttr(llvm::Attribute::SanitizeThread); 6560b57cec5SDimitry Andric } 6570b57cec5SDimitry Andric } 6580b57cec5SDimitry Andric 659480093f4SDimitry Andric /// Check if the return value of this function requires sanitization. 660480093f4SDimitry Andric bool CodeGenFunction::requiresReturnValueCheck() const { 661480093f4SDimitry Andric return requiresReturnValueNullabilityCheck() || 662480093f4SDimitry Andric (SanOpts.has(SanitizerKind::ReturnsNonnullAttribute) && CurCodeDecl && 663480093f4SDimitry Andric CurCodeDecl->getAttr<ReturnsNonNullAttr>()); 664480093f4SDimitry Andric } 665480093f4SDimitry Andric 6660b57cec5SDimitry Andric static bool matchesStlAllocatorFn(const Decl *D, const ASTContext &Ctx) { 6670b57cec5SDimitry Andric auto *MD = dyn_cast_or_null<CXXMethodDecl>(D); 6680b57cec5SDimitry Andric if (!MD || !MD->getDeclName().getAsIdentifierInfo() || 6690b57cec5SDimitry Andric !MD->getDeclName().getAsIdentifierInfo()->isStr("allocate") || 6700b57cec5SDimitry Andric (MD->getNumParams() != 1 && MD->getNumParams() != 2)) 6710b57cec5SDimitry Andric return false; 6720b57cec5SDimitry Andric 6730b57cec5SDimitry Andric if (MD->parameters()[0]->getType().getCanonicalType() != Ctx.getSizeType()) 6740b57cec5SDimitry Andric return false; 6750b57cec5SDimitry Andric 6760b57cec5SDimitry Andric if (MD->getNumParams() == 2) { 6770b57cec5SDimitry Andric auto *PT = MD->parameters()[1]->getType()->getAs<PointerType>(); 6780b57cec5SDimitry Andric if (!PT || !PT->isVoidPointerType() || 6790b57cec5SDimitry Andric !PT->getPointeeType().isConstQualified()) 6800b57cec5SDimitry Andric return false; 6810b57cec5SDimitry Andric } 6820b57cec5SDimitry Andric 6830b57cec5SDimitry Andric return true; 6840b57cec5SDimitry Andric } 6850b57cec5SDimitry Andric 6860b57cec5SDimitry Andric /// Return the UBSan prologue signature for \p FD if one is available. 6870b57cec5SDimitry Andric static llvm::Constant *getPrologueSignature(CodeGenModule &CGM, 6880b57cec5SDimitry Andric const FunctionDecl *FD) { 6890b57cec5SDimitry Andric if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) 6900b57cec5SDimitry Andric if (!MD->isStatic()) 6910b57cec5SDimitry Andric return nullptr; 6920b57cec5SDimitry Andric return CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM); 6930b57cec5SDimitry Andric } 6940b57cec5SDimitry Andric 695480093f4SDimitry Andric void CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy, 6960b57cec5SDimitry Andric llvm::Function *Fn, 6970b57cec5SDimitry Andric const CGFunctionInfo &FnInfo, 6980b57cec5SDimitry Andric const FunctionArgList &Args, 6990b57cec5SDimitry Andric SourceLocation Loc, 7000b57cec5SDimitry Andric SourceLocation StartLoc) { 7010b57cec5SDimitry Andric assert(!CurFn && 7020b57cec5SDimitry Andric "Do not use a CodeGenFunction object for more than one function"); 7030b57cec5SDimitry Andric 7040b57cec5SDimitry Andric const Decl *D = GD.getDecl(); 7050b57cec5SDimitry Andric 7060b57cec5SDimitry Andric DidCallStackSave = false; 7070b57cec5SDimitry Andric CurCodeDecl = D; 708fe6060f1SDimitry Andric const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 709fe6060f1SDimitry Andric if (FD && FD->usesSEHTry()) 710bdd1243dSDimitry Andric CurSEHParent = GD; 7110b57cec5SDimitry Andric CurFuncDecl = (D ? D->getNonClosureContext() : nullptr); 7120b57cec5SDimitry Andric FnRetTy = RetTy; 7130b57cec5SDimitry Andric CurFn = Fn; 7140b57cec5SDimitry Andric CurFnInfo = &FnInfo; 7150b57cec5SDimitry Andric assert(CurFn->isDeclaration() && "Function already has body?"); 7160b57cec5SDimitry Andric 717fe6060f1SDimitry Andric // If this function is ignored for any of the enabled sanitizers, 7180b57cec5SDimitry Andric // disable the sanitizer for the function. 7190b57cec5SDimitry Andric do { 7200b57cec5SDimitry Andric #define SANITIZER(NAME, ID) \ 7210b57cec5SDimitry Andric if (SanOpts.empty()) \ 7220b57cec5SDimitry Andric break; \ 7230b57cec5SDimitry Andric if (SanOpts.has(SanitizerKind::ID)) \ 724fe6060f1SDimitry Andric if (CGM.isInNoSanitizeList(SanitizerKind::ID, Fn, Loc)) \ 7250b57cec5SDimitry Andric SanOpts.set(SanitizerKind::ID, false); 7260b57cec5SDimitry Andric 7270b57cec5SDimitry Andric #include "clang/Basic/Sanitizers.def" 7280b57cec5SDimitry Andric #undef SANITIZER 72904eeddc0SDimitry Andric } while (false); 7300b57cec5SDimitry Andric 7310b57cec5SDimitry Andric if (D) { 73281ad6265SDimitry Andric const bool SanitizeBounds = SanOpts.hasOneOf(SanitizerKind::Bounds); 733*fe013be4SDimitry Andric SanitizerMask no_sanitize_mask; 734fe6060f1SDimitry Andric bool NoSanitizeCoverage = false; 735fe6060f1SDimitry Andric 736bdd1243dSDimitry Andric for (auto *Attr : D->specific_attrs<NoSanitizeAttr>()) { 737*fe013be4SDimitry Andric no_sanitize_mask |= Attr->getMask(); 738fe6060f1SDimitry Andric // SanitizeCoverage is not handled by SanOpts. 739fe6060f1SDimitry Andric if (Attr->hasCoverage()) 740fe6060f1SDimitry Andric NoSanitizeCoverage = true; 7410b57cec5SDimitry Andric } 742fe6060f1SDimitry Andric 743*fe013be4SDimitry Andric // Apply the no_sanitize* attributes to SanOpts. 744*fe013be4SDimitry Andric SanOpts.Mask &= ~no_sanitize_mask; 745*fe013be4SDimitry Andric if (no_sanitize_mask & SanitizerKind::Address) 746*fe013be4SDimitry Andric SanOpts.set(SanitizerKind::KernelAddress, false); 747*fe013be4SDimitry Andric if (no_sanitize_mask & SanitizerKind::KernelAddress) 748*fe013be4SDimitry Andric SanOpts.set(SanitizerKind::Address, false); 749*fe013be4SDimitry Andric if (no_sanitize_mask & SanitizerKind::HWAddress) 750*fe013be4SDimitry Andric SanOpts.set(SanitizerKind::KernelHWAddress, false); 751*fe013be4SDimitry Andric if (no_sanitize_mask & SanitizerKind::KernelHWAddress) 752*fe013be4SDimitry Andric SanOpts.set(SanitizerKind::HWAddress, false); 753*fe013be4SDimitry Andric 75481ad6265SDimitry Andric if (SanitizeBounds && !SanOpts.hasOneOf(SanitizerKind::Bounds)) 75581ad6265SDimitry Andric Fn->addFnAttr(llvm::Attribute::NoSanitizeBounds); 75681ad6265SDimitry Andric 757fe6060f1SDimitry Andric if (NoSanitizeCoverage && CGM.getCodeGenOpts().hasSanitizeCoverage()) 758fe6060f1SDimitry Andric Fn->addFnAttr(llvm::Attribute::NoSanitizeCoverage); 759*fe013be4SDimitry Andric 760*fe013be4SDimitry Andric // Some passes need the non-negated no_sanitize attribute. Pass them on. 761*fe013be4SDimitry Andric if (CGM.getCodeGenOpts().hasSanitizeBinaryMetadata()) { 762*fe013be4SDimitry Andric if (no_sanitize_mask & SanitizerKind::Thread) 763*fe013be4SDimitry Andric Fn->addFnAttr("no_sanitize_thread"); 764*fe013be4SDimitry Andric } 7650b57cec5SDimitry Andric } 7660b57cec5SDimitry Andric 76781ad6265SDimitry Andric if (ShouldSkipSanitizerInstrumentation()) { 76881ad6265SDimitry Andric CurFn->addFnAttr(llvm::Attribute::DisableSanitizerInstrumentation); 76981ad6265SDimitry Andric } else { 7700b57cec5SDimitry Andric // Apply sanitizer attributes to the function. 7710b57cec5SDimitry Andric if (SanOpts.hasOneOf(SanitizerKind::Address | SanitizerKind::KernelAddress)) 7720b57cec5SDimitry Andric Fn->addFnAttr(llvm::Attribute::SanitizeAddress); 77381ad6265SDimitry Andric if (SanOpts.hasOneOf(SanitizerKind::HWAddress | 77481ad6265SDimitry Andric SanitizerKind::KernelHWAddress)) 7750b57cec5SDimitry Andric Fn->addFnAttr(llvm::Attribute::SanitizeHWAddress); 77681ad6265SDimitry Andric if (SanOpts.has(SanitizerKind::MemtagStack)) 7770b57cec5SDimitry Andric Fn->addFnAttr(llvm::Attribute::SanitizeMemTag); 7780b57cec5SDimitry Andric if (SanOpts.has(SanitizerKind::Thread)) 7790b57cec5SDimitry Andric Fn->addFnAttr(llvm::Attribute::SanitizeThread); 7800b57cec5SDimitry Andric if (SanOpts.hasOneOf(SanitizerKind::Memory | SanitizerKind::KernelMemory)) 7810b57cec5SDimitry Andric Fn->addFnAttr(llvm::Attribute::SanitizeMemory); 78281ad6265SDimitry Andric } 7830b57cec5SDimitry Andric if (SanOpts.has(SanitizerKind::SafeStack)) 7840b57cec5SDimitry Andric Fn->addFnAttr(llvm::Attribute::SafeStack); 7850b57cec5SDimitry Andric if (SanOpts.has(SanitizerKind::ShadowCallStack)) 7860b57cec5SDimitry Andric Fn->addFnAttr(llvm::Attribute::ShadowCallStack); 7870b57cec5SDimitry Andric 7880b57cec5SDimitry Andric // Apply fuzzing attribute to the function. 7890b57cec5SDimitry Andric if (SanOpts.hasOneOf(SanitizerKind::Fuzzer | SanitizerKind::FuzzerNoLink)) 7900b57cec5SDimitry Andric Fn->addFnAttr(llvm::Attribute::OptForFuzzing); 7910b57cec5SDimitry Andric 7920b57cec5SDimitry Andric // Ignore TSan memory acesses from within ObjC/ObjC++ dealloc, initialize, 7930b57cec5SDimitry Andric // .cxx_destruct, __destroy_helper_block_ and all of their calees at run time. 7940b57cec5SDimitry Andric if (SanOpts.has(SanitizerKind::Thread)) { 7950b57cec5SDimitry Andric if (const auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(D)) { 7960b57cec5SDimitry Andric IdentifierInfo *II = OMD->getSelector().getIdentifierInfoForSlot(0); 7970b57cec5SDimitry Andric if (OMD->getMethodFamily() == OMF_dealloc || 7980b57cec5SDimitry Andric OMD->getMethodFamily() == OMF_initialize || 7990b57cec5SDimitry Andric (OMD->getSelector().isUnarySelector() && II->isStr(".cxx_destruct"))) { 8000b57cec5SDimitry Andric markAsIgnoreThreadCheckingAtRuntime(Fn); 8010b57cec5SDimitry Andric } 8020b57cec5SDimitry Andric } 8030b57cec5SDimitry Andric } 8040b57cec5SDimitry Andric 8050b57cec5SDimitry Andric // Ignore unrelated casts in STL allocate() since the allocator must cast 8060b57cec5SDimitry Andric // from void* to T* before object initialization completes. Don't match on the 8070b57cec5SDimitry Andric // namespace because not all allocators are in std:: 8080b57cec5SDimitry Andric if (D && SanOpts.has(SanitizerKind::CFIUnrelatedCast)) { 8090b57cec5SDimitry Andric if (matchesStlAllocatorFn(D, getContext())) 8100b57cec5SDimitry Andric SanOpts.Mask &= ~SanitizerKind::CFIUnrelatedCast; 8110b57cec5SDimitry Andric } 8120b57cec5SDimitry Andric 813a7dea167SDimitry Andric // Ignore null checks in coroutine functions since the coroutines passes 814a7dea167SDimitry Andric // are not aware of how to move the extra UBSan instructions across the split 815a7dea167SDimitry Andric // coroutine boundaries. 816a7dea167SDimitry Andric if (D && SanOpts.has(SanitizerKind::Null)) 817fe6060f1SDimitry Andric if (FD && FD->getBody() && 818a7dea167SDimitry Andric FD->getBody()->getStmtClass() == Stmt::CoroutineBodyStmtClass) 819a7dea167SDimitry Andric SanOpts.Mask &= ~SanitizerKind::Null; 820a7dea167SDimitry Andric 821480093f4SDimitry Andric // Apply xray attributes to the function (as a string, for now) 822e8d8bef9SDimitry Andric bool AlwaysXRayAttr = false; 8235ffd83dbSDimitry Andric if (const auto *XRayAttr = D ? D->getAttr<XRayInstrumentAttr>() : nullptr) { 8240b57cec5SDimitry Andric if (CGM.getCodeGenOpts().XRayInstrumentationBundle.has( 8255ffd83dbSDimitry Andric XRayInstrKind::FunctionEntry) || 8265ffd83dbSDimitry Andric CGM.getCodeGenOpts().XRayInstrumentationBundle.has( 8275ffd83dbSDimitry Andric XRayInstrKind::FunctionExit)) { 828e8d8bef9SDimitry Andric if (XRayAttr->alwaysXRayInstrument() && ShouldXRayInstrumentFunction()) { 8290b57cec5SDimitry Andric Fn->addFnAttr("function-instrument", "xray-always"); 830e8d8bef9SDimitry Andric AlwaysXRayAttr = true; 831e8d8bef9SDimitry Andric } 8320b57cec5SDimitry Andric if (XRayAttr->neverXRayInstrument()) 8330b57cec5SDimitry Andric Fn->addFnAttr("function-instrument", "xray-never"); 8340b57cec5SDimitry Andric if (const auto *LogArgs = D->getAttr<XRayLogArgsAttr>()) 8350b57cec5SDimitry Andric if (ShouldXRayInstrumentFunction()) 8360b57cec5SDimitry Andric Fn->addFnAttr("xray-log-args", 8370b57cec5SDimitry Andric llvm::utostr(LogArgs->getArgumentCount())); 8380b57cec5SDimitry Andric } 8390b57cec5SDimitry Andric } else { 8400b57cec5SDimitry Andric if (ShouldXRayInstrumentFunction() && !CGM.imbueXRayAttrs(Fn, Loc)) 8410b57cec5SDimitry Andric Fn->addFnAttr( 8420b57cec5SDimitry Andric "xray-instruction-threshold", 8430b57cec5SDimitry Andric llvm::itostr(CGM.getCodeGenOpts().XRayInstructionThreshold)); 8440b57cec5SDimitry Andric } 845480093f4SDimitry Andric 8465ffd83dbSDimitry Andric if (ShouldXRayInstrumentFunction()) { 8475ffd83dbSDimitry Andric if (CGM.getCodeGenOpts().XRayIgnoreLoops) 8485ffd83dbSDimitry Andric Fn->addFnAttr("xray-ignore-loops"); 8495ffd83dbSDimitry Andric 8505ffd83dbSDimitry Andric if (!CGM.getCodeGenOpts().XRayInstrumentationBundle.has( 8515ffd83dbSDimitry Andric XRayInstrKind::FunctionExit)) 8525ffd83dbSDimitry Andric Fn->addFnAttr("xray-skip-exit"); 8535ffd83dbSDimitry Andric 8545ffd83dbSDimitry Andric if (!CGM.getCodeGenOpts().XRayInstrumentationBundle.has( 8555ffd83dbSDimitry Andric XRayInstrKind::FunctionEntry)) 8565ffd83dbSDimitry Andric Fn->addFnAttr("xray-skip-entry"); 857e8d8bef9SDimitry Andric 858e8d8bef9SDimitry Andric auto FuncGroups = CGM.getCodeGenOpts().XRayTotalFunctionGroups; 859e8d8bef9SDimitry Andric if (FuncGroups > 1) { 860bdd1243dSDimitry Andric auto FuncName = llvm::ArrayRef<uint8_t>(CurFn->getName().bytes_begin(), 861bdd1243dSDimitry Andric CurFn->getName().bytes_end()); 862e8d8bef9SDimitry Andric auto Group = crc32(FuncName) % FuncGroups; 863e8d8bef9SDimitry Andric if (Group != CGM.getCodeGenOpts().XRaySelectedFunctionGroup && 864e8d8bef9SDimitry Andric !AlwaysXRayAttr) 865e8d8bef9SDimitry Andric Fn->addFnAttr("function-instrument", "xray-never"); 8665ffd83dbSDimitry Andric } 867e8d8bef9SDimitry Andric } 868e8d8bef9SDimitry Andric 869bdd1243dSDimitry Andric if (CGM.getCodeGenOpts().getProfileInstr() != CodeGenOptions::ProfileNone) { 870bdd1243dSDimitry Andric switch (CGM.isFunctionBlockedFromProfileInstr(Fn, Loc)) { 871bdd1243dSDimitry Andric case ProfileList::Skip: 872bdd1243dSDimitry Andric Fn->addFnAttr(llvm::Attribute::SkipProfile); 873bdd1243dSDimitry Andric break; 874bdd1243dSDimitry Andric case ProfileList::Forbid: 875e8d8bef9SDimitry Andric Fn->addFnAttr(llvm::Attribute::NoProfile); 876bdd1243dSDimitry Andric break; 877bdd1243dSDimitry Andric case ProfileList::Allow: 878bdd1243dSDimitry Andric break; 879bdd1243dSDimitry Andric } 880bdd1243dSDimitry Andric } 8815ffd83dbSDimitry Andric 88255e4f9d5SDimitry Andric unsigned Count, Offset; 8835ffd83dbSDimitry Andric if (const auto *Attr = 8845ffd83dbSDimitry Andric D ? D->getAttr<PatchableFunctionEntryAttr>() : nullptr) { 88555e4f9d5SDimitry Andric Count = Attr->getCount(); 88655e4f9d5SDimitry Andric Offset = Attr->getOffset(); 88755e4f9d5SDimitry Andric } else { 88855e4f9d5SDimitry Andric Count = CGM.getCodeGenOpts().PatchableFunctionEntryCount; 88955e4f9d5SDimitry Andric Offset = CGM.getCodeGenOpts().PatchableFunctionEntryOffset; 89055e4f9d5SDimitry Andric } 89155e4f9d5SDimitry Andric if (Count && Offset <= Count) { 89255e4f9d5SDimitry Andric Fn->addFnAttr("patchable-function-entry", std::to_string(Count - Offset)); 89355e4f9d5SDimitry Andric if (Offset) 89455e4f9d5SDimitry Andric Fn->addFnAttr("patchable-function-prefix", std::to_string(Offset)); 895480093f4SDimitry Andric } 89604eeddc0SDimitry Andric // Instruct that functions for COFF/CodeView targets should start with a 89704eeddc0SDimitry Andric // patchable instruction, but only on x86/x64. Don't forward this to ARM/ARM64 89804eeddc0SDimitry Andric // backends as they don't need it -- instructions on these architectures are 89904eeddc0SDimitry Andric // always atomically patchable at runtime. 90004eeddc0SDimitry Andric if (CGM.getCodeGenOpts().HotPatch && 901bdd1243dSDimitry Andric getContext().getTargetInfo().getTriple().isX86() && 902bdd1243dSDimitry Andric getContext().getTargetInfo().getTriple().getEnvironment() != 903bdd1243dSDimitry Andric llvm::Triple::CODE16) 90404eeddc0SDimitry Andric Fn->addFnAttr("patchable-function", "prologue-short-redirect"); 9050b57cec5SDimitry Andric 9060b57cec5SDimitry Andric // Add no-jump-tables value. 907fe6060f1SDimitry Andric if (CGM.getCodeGenOpts().NoUseJumpTables) 908fe6060f1SDimitry Andric Fn->addFnAttr("no-jump-tables", "true"); 9090b57cec5SDimitry Andric 910480093f4SDimitry Andric // Add no-inline-line-tables value. 911480093f4SDimitry Andric if (CGM.getCodeGenOpts().NoInlineLineTables) 912480093f4SDimitry Andric Fn->addFnAttr("no-inline-line-tables"); 913480093f4SDimitry Andric 9140b57cec5SDimitry Andric // Add profile-sample-accurate value. 9150b57cec5SDimitry Andric if (CGM.getCodeGenOpts().ProfileSampleAccurate) 9160b57cec5SDimitry Andric Fn->addFnAttr("profile-sample-accurate"); 9170b57cec5SDimitry Andric 9185ffd83dbSDimitry Andric if (!CGM.getCodeGenOpts().SampleProfileFile.empty()) 9195ffd83dbSDimitry Andric Fn->addFnAttr("use-sample-profile"); 9205ffd83dbSDimitry Andric 921a7dea167SDimitry Andric if (D && D->hasAttr<CFICanonicalJumpTableAttr>()) 922a7dea167SDimitry Andric Fn->addFnAttr("cfi-canonical-jump-table"); 923a7dea167SDimitry Andric 924fe6060f1SDimitry Andric if (D && D->hasAttr<NoProfileFunctionAttr>()) 925fe6060f1SDimitry Andric Fn->addFnAttr(llvm::Attribute::NoProfile); 926fe6060f1SDimitry Andric 927753f127fSDimitry Andric if (D) { 928753f127fSDimitry Andric // Function attributes take precedence over command line flags. 929753f127fSDimitry Andric if (auto *A = D->getAttr<FunctionReturnThunksAttr>()) { 930753f127fSDimitry Andric switch (A->getThunkType()) { 931753f127fSDimitry Andric case FunctionReturnThunksAttr::Kind::Keep: 932753f127fSDimitry Andric break; 933753f127fSDimitry Andric case FunctionReturnThunksAttr::Kind::Extern: 934753f127fSDimitry Andric Fn->addFnAttr(llvm::Attribute::FnRetThunkExtern); 935753f127fSDimitry Andric break; 936753f127fSDimitry Andric } 937753f127fSDimitry Andric } else if (CGM.getCodeGenOpts().FunctionReturnThunks) 938753f127fSDimitry Andric Fn->addFnAttr(llvm::Attribute::FnRetThunkExtern); 939753f127fSDimitry Andric } 940753f127fSDimitry Andric 94181ad6265SDimitry Andric if (FD && (getLangOpts().OpenCL || 94281ad6265SDimitry Andric (getLangOpts().HIP && getLangOpts().CUDAIsDevice))) { 9430b57cec5SDimitry Andric // Add metadata for a kernel function. 94481ad6265SDimitry Andric EmitKernelMetadata(FD, Fn); 9450b57cec5SDimitry Andric } 9460b57cec5SDimitry Andric 9470b57cec5SDimitry Andric // If we are checking function types, emit a function type signature as 9480b57cec5SDimitry Andric // prologue data. 949*fe013be4SDimitry Andric if (FD && SanOpts.has(SanitizerKind::Function)) { 9500b57cec5SDimitry Andric if (llvm::Constant *PrologueSig = getPrologueSignature(CGM, FD)) { 95181ad6265SDimitry Andric llvm::LLVMContext &Ctx = Fn->getContext(); 95281ad6265SDimitry Andric llvm::MDBuilder MDB(Ctx); 953*fe013be4SDimitry Andric Fn->setMetadata( 954*fe013be4SDimitry Andric llvm::LLVMContext::MD_func_sanitize, 955*fe013be4SDimitry Andric MDB.createRTTIPointerPrologue( 956*fe013be4SDimitry Andric PrologueSig, getUBSanFunctionTypeHash(FD->getType()))); 9570b57cec5SDimitry Andric } 9580b57cec5SDimitry Andric } 9590b57cec5SDimitry Andric 9600b57cec5SDimitry Andric // If we're checking nullability, we need to know whether we can check the 9610b57cec5SDimitry Andric // return value. Initialize the flag to 'true' and refine it in EmitParmDecl. 9620b57cec5SDimitry Andric if (SanOpts.has(SanitizerKind::NullabilityReturn)) { 963bdd1243dSDimitry Andric auto Nullability = FnRetTy->getNullability(); 9640b57cec5SDimitry Andric if (Nullability && *Nullability == NullabilityKind::NonNull) { 9650b57cec5SDimitry Andric if (!(SanOpts.has(SanitizerKind::ReturnsNonnullAttribute) && 9660b57cec5SDimitry Andric CurCodeDecl && CurCodeDecl->getAttr<ReturnsNonNullAttr>())) 9670b57cec5SDimitry Andric RetValNullabilityPrecondition = 9680b57cec5SDimitry Andric llvm::ConstantInt::getTrue(getLLVMContext()); 9690b57cec5SDimitry Andric } 9700b57cec5SDimitry Andric } 9710b57cec5SDimitry Andric 9720b57cec5SDimitry Andric // If we're in C++ mode and the function name is "main", it is guaranteed 9730b57cec5SDimitry Andric // to be norecurse by the standard (3.6.1.3 "The function main shall not be 9740b57cec5SDimitry Andric // used within a program"). 9755ffd83dbSDimitry Andric // 9765ffd83dbSDimitry Andric // OpenCL C 2.0 v2.2-11 s6.9.i: 9775ffd83dbSDimitry Andric // Recursion is not supported. 9785ffd83dbSDimitry Andric // 9795ffd83dbSDimitry Andric // SYCL v1.2.1 s3.10: 9805ffd83dbSDimitry Andric // kernels cannot include RTTI information, exception classes, 9815ffd83dbSDimitry Andric // recursive code, virtual functions or make use of C++ libraries that 9825ffd83dbSDimitry Andric // are not compiled for the device. 983fe6060f1SDimitry Andric if (FD && ((getLangOpts().CPlusPlus && FD->isMain()) || 984fe6060f1SDimitry Andric getLangOpts().OpenCL || getLangOpts().SYCLIsDevice || 985fe6060f1SDimitry Andric (getLangOpts().CUDA && FD->hasAttr<CUDAGlobalAttr>()))) 9860b57cec5SDimitry Andric Fn->addFnAttr(llvm::Attribute::NoRecurse); 9870b57cec5SDimitry Andric 98881ad6265SDimitry Andric llvm::RoundingMode RM = getLangOpts().getDefaultRoundingMode(); 989349cc55cSDimitry Andric llvm::fp::ExceptionBehavior FPExceptionBehavior = 99081ad6265SDimitry Andric ToConstrainedExceptMD(getLangOpts().getDefaultExceptionMode()); 991349cc55cSDimitry Andric Builder.setDefaultConstrainedRounding(RM); 992349cc55cSDimitry Andric Builder.setDefaultConstrainedExcept(FPExceptionBehavior); 993349cc55cSDimitry Andric if ((FD && (FD->UsesFPIntrin() || FD->hasAttr<StrictFPAttr>())) || 994349cc55cSDimitry Andric (!FD && (FPExceptionBehavior != llvm::fp::ebIgnore || 995349cc55cSDimitry Andric RM != llvm::RoundingMode::NearestTiesToEven))) { 996349cc55cSDimitry Andric Builder.setIsFPConstrained(true); 997480093f4SDimitry Andric Fn->addFnAttr(llvm::Attribute::StrictFP); 9985ffd83dbSDimitry Andric } 999480093f4SDimitry Andric 10000b57cec5SDimitry Andric // If a custom alignment is used, force realigning to this alignment on 10010b57cec5SDimitry Andric // any main function which certainly will need it. 1002fe6060f1SDimitry Andric if (FD && ((FD->isMain() || FD->isMSVCRTEntryPoint()) && 1003fe6060f1SDimitry Andric CGM.getCodeGenOpts().StackAlignment)) 10040b57cec5SDimitry Andric Fn->addFnAttr("stackrealign"); 10050b57cec5SDimitry Andric 100681ad6265SDimitry Andric // "main" doesn't need to zero out call-used registers. 100781ad6265SDimitry Andric if (FD && FD->isMain()) 100881ad6265SDimitry Andric Fn->removeFnAttr("zero-call-used-regs"); 100981ad6265SDimitry Andric 10100b57cec5SDimitry Andric llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn); 10110b57cec5SDimitry Andric 10120b57cec5SDimitry Andric // Create a marker to make it easy to insert allocas into the entryblock 10130b57cec5SDimitry Andric // later. Don't create this with the builder, because we don't want it 10140b57cec5SDimitry Andric // folded. 10150b57cec5SDimitry Andric llvm::Value *Undef = llvm::UndefValue::get(Int32Ty); 10160b57cec5SDimitry Andric AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "allocapt", EntryBB); 10170b57cec5SDimitry Andric 10180b57cec5SDimitry Andric ReturnBlock = getJumpDestInCurrentScope("return"); 10190b57cec5SDimitry Andric 10200b57cec5SDimitry Andric Builder.SetInsertPoint(EntryBB); 10210b57cec5SDimitry Andric 10220b57cec5SDimitry Andric // If we're checking the return value, allocate space for a pointer to a 10230b57cec5SDimitry Andric // precise source location of the checked return statement. 10240b57cec5SDimitry Andric if (requiresReturnValueCheck()) { 10250b57cec5SDimitry Andric ReturnLocation = CreateDefaultAlignTempAlloca(Int8PtrTy, "return.sloc.ptr"); 1026349cc55cSDimitry Andric Builder.CreateStore(llvm::ConstantPointerNull::get(Int8PtrTy), 1027349cc55cSDimitry Andric ReturnLocation); 10280b57cec5SDimitry Andric } 10290b57cec5SDimitry Andric 10300b57cec5SDimitry Andric // Emit subprogram debug descriptor. 10310b57cec5SDimitry Andric if (CGDebugInfo *DI = getDebugInfo()) { 10320b57cec5SDimitry Andric // Reconstruct the type from the argument list so that implicit parameters, 10330b57cec5SDimitry Andric // such as 'this' and 'vtt', show up in the debug info. Preserve the calling 10340b57cec5SDimitry Andric // convention. 1035349cc55cSDimitry Andric DI->emitFunctionStart(GD, Loc, StartLoc, 1036349cc55cSDimitry Andric DI->getFunctionType(FD, RetTy, Args), CurFn, 1037349cc55cSDimitry Andric CurFuncIsThunk); 10380b57cec5SDimitry Andric } 10390b57cec5SDimitry Andric 10400b57cec5SDimitry Andric if (ShouldInstrumentFunction()) { 10410b57cec5SDimitry Andric if (CGM.getCodeGenOpts().InstrumentFunctions) 10420b57cec5SDimitry Andric CurFn->addFnAttr("instrument-function-entry", "__cyg_profile_func_enter"); 10430b57cec5SDimitry Andric if (CGM.getCodeGenOpts().InstrumentFunctionsAfterInlining) 10440b57cec5SDimitry Andric CurFn->addFnAttr("instrument-function-entry-inlined", 10450b57cec5SDimitry Andric "__cyg_profile_func_enter"); 10460b57cec5SDimitry Andric if (CGM.getCodeGenOpts().InstrumentFunctionEntryBare) 10470b57cec5SDimitry Andric CurFn->addFnAttr("instrument-function-entry-inlined", 10480b57cec5SDimitry Andric "__cyg_profile_func_enter_bare"); 10490b57cec5SDimitry Andric } 10500b57cec5SDimitry Andric 10510b57cec5SDimitry Andric // Since emitting the mcount call here impacts optimizations such as function 10520b57cec5SDimitry Andric // inlining, we just add an attribute to insert a mcount call in backend. 10530b57cec5SDimitry Andric // The attribute "counting-function" is set to mcount function name which is 10540b57cec5SDimitry Andric // architecture dependent. 10550b57cec5SDimitry Andric if (CGM.getCodeGenOpts().InstrumentForProfiling) { 10560b57cec5SDimitry Andric // Calls to fentry/mcount should not be generated if function has 10570b57cec5SDimitry Andric // the no_instrument_function attribute. 10580b57cec5SDimitry Andric if (!CurFuncDecl || !CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>()) { 10590b57cec5SDimitry Andric if (CGM.getCodeGenOpts().CallFEntry) 10600b57cec5SDimitry Andric Fn->addFnAttr("fentry-call", "true"); 10610b57cec5SDimitry Andric else { 10620b57cec5SDimitry Andric Fn->addFnAttr("instrument-function-entry-inlined", 10630b57cec5SDimitry Andric getTarget().getMCountName()); 10640b57cec5SDimitry Andric } 1065480093f4SDimitry Andric if (CGM.getCodeGenOpts().MNopMCount) { 1066480093f4SDimitry Andric if (!CGM.getCodeGenOpts().CallFEntry) 1067480093f4SDimitry Andric CGM.getDiags().Report(diag::err_opt_not_valid_without_opt) 1068480093f4SDimitry Andric << "-mnop-mcount" << "-mfentry"; 1069480093f4SDimitry Andric Fn->addFnAttr("mnop-mcount"); 10700b57cec5SDimitry Andric } 1071480093f4SDimitry Andric 1072480093f4SDimitry Andric if (CGM.getCodeGenOpts().RecordMCount) { 1073480093f4SDimitry Andric if (!CGM.getCodeGenOpts().CallFEntry) 1074480093f4SDimitry Andric CGM.getDiags().Report(diag::err_opt_not_valid_without_opt) 1075480093f4SDimitry Andric << "-mrecord-mcount" << "-mfentry"; 1076480093f4SDimitry Andric Fn->addFnAttr("mrecord-mcount"); 1077480093f4SDimitry Andric } 1078480093f4SDimitry Andric } 1079480093f4SDimitry Andric } 1080480093f4SDimitry Andric 1081480093f4SDimitry Andric if (CGM.getCodeGenOpts().PackedStack) { 1082480093f4SDimitry Andric if (getContext().getTargetInfo().getTriple().getArch() != 1083480093f4SDimitry Andric llvm::Triple::systemz) 1084480093f4SDimitry Andric CGM.getDiags().Report(diag::err_opt_not_valid_on_target) 1085480093f4SDimitry Andric << "-mpacked-stack"; 1086480093f4SDimitry Andric Fn->addFnAttr("packed-stack"); 10870b57cec5SDimitry Andric } 10880b57cec5SDimitry Andric 1089349cc55cSDimitry Andric if (CGM.getCodeGenOpts().WarnStackSize != UINT_MAX && 1090349cc55cSDimitry Andric !CGM.getDiags().isIgnored(diag::warn_fe_backend_frame_larger_than, Loc)) 1091fe6060f1SDimitry Andric Fn->addFnAttr("warn-stack-size", 1092fe6060f1SDimitry Andric std::to_string(CGM.getCodeGenOpts().WarnStackSize)); 1093fe6060f1SDimitry Andric 10940b57cec5SDimitry Andric if (RetTy->isVoidType()) { 10950b57cec5SDimitry Andric // Void type; nothing to return. 10960b57cec5SDimitry Andric ReturnValue = Address::invalid(); 10970b57cec5SDimitry Andric 10980b57cec5SDimitry Andric // Count the implicit return. 10990b57cec5SDimitry Andric if (!endsWithReturn(D)) 11000b57cec5SDimitry Andric ++NumReturnExprs; 11010b57cec5SDimitry Andric } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect) { 11020b57cec5SDimitry Andric // Indirect return; emit returned value directly into sret slot. 11030b57cec5SDimitry Andric // This reduces code size, and affects correctness in C++. 11040b57cec5SDimitry Andric auto AI = CurFn->arg_begin(); 11050b57cec5SDimitry Andric if (CurFnInfo->getReturnInfo().isSRetAfterThis()) 11060b57cec5SDimitry Andric ++AI; 1107*fe013be4SDimitry Andric ReturnValue = 1108*fe013be4SDimitry Andric Address(&*AI, ConvertType(RetTy), 1109*fe013be4SDimitry Andric CurFnInfo->getReturnInfo().getIndirectAlign(), KnownNonNull); 11100b57cec5SDimitry Andric if (!CurFnInfo->getReturnInfo().getIndirectByVal()) { 11110b57cec5SDimitry Andric ReturnValuePointer = 11120b57cec5SDimitry Andric CreateDefaultAlignTempAlloca(Int8PtrTy, "result.ptr"); 11130b57cec5SDimitry Andric Builder.CreateStore(Builder.CreatePointerBitCastOrAddrSpaceCast( 11140b57cec5SDimitry Andric ReturnValue.getPointer(), Int8PtrTy), 11150b57cec5SDimitry Andric ReturnValuePointer); 11160b57cec5SDimitry Andric } 11170b57cec5SDimitry Andric } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::InAlloca && 11180b57cec5SDimitry Andric !hasScalarEvaluationKind(CurFnInfo->getReturnType())) { 11190b57cec5SDimitry Andric // Load the sret pointer from the argument struct and return into that. 11200b57cec5SDimitry Andric unsigned Idx = CurFnInfo->getReturnInfo().getInAllocaFieldIndex(); 11210b57cec5SDimitry Andric llvm::Function::arg_iterator EI = CurFn->arg_end(); 11220b57cec5SDimitry Andric --EI; 1123fe6060f1SDimitry Andric llvm::Value *Addr = Builder.CreateStructGEP( 112481ad6265SDimitry Andric CurFnInfo->getArgStruct(), &*EI, Idx); 1125fe6060f1SDimitry Andric llvm::Type *Ty = 1126fe6060f1SDimitry Andric cast<llvm::GetElementPtrInst>(Addr)->getResultElementType(); 112781ad6265SDimitry Andric ReturnValuePointer = Address(Addr, Ty, getPointerAlign()); 1128fe6060f1SDimitry Andric Addr = Builder.CreateAlignedLoad(Ty, Addr, getPointerAlign(), "agg.result"); 1129*fe013be4SDimitry Andric ReturnValue = Address(Addr, ConvertType(RetTy), 1130*fe013be4SDimitry Andric CGM.getNaturalTypeAlignment(RetTy), KnownNonNull); 11310b57cec5SDimitry Andric } else { 11320b57cec5SDimitry Andric ReturnValue = CreateIRTemp(RetTy, "retval"); 11330b57cec5SDimitry Andric 11340b57cec5SDimitry Andric // Tell the epilog emitter to autorelease the result. We do this 11350b57cec5SDimitry Andric // now so that various specialized functions can suppress it 11360b57cec5SDimitry Andric // during their IR-generation. 11370b57cec5SDimitry Andric if (getLangOpts().ObjCAutoRefCount && 11380b57cec5SDimitry Andric !CurFnInfo->isReturnsRetained() && 11390b57cec5SDimitry Andric RetTy->isObjCRetainableType()) 11400b57cec5SDimitry Andric AutoreleaseResult = true; 11410b57cec5SDimitry Andric } 11420b57cec5SDimitry Andric 11430b57cec5SDimitry Andric EmitStartEHSpec(CurCodeDecl); 11440b57cec5SDimitry Andric 11450b57cec5SDimitry Andric PrologueCleanupDepth = EHStack.stable_begin(); 11460b57cec5SDimitry Andric 11470b57cec5SDimitry Andric // Emit OpenMP specific initialization of the device functions. 11480b57cec5SDimitry Andric if (getLangOpts().OpenMP && CurCodeDecl) 11490b57cec5SDimitry Andric CGM.getOpenMPRuntime().emitFunctionProlog(*this, CurCodeDecl); 11500b57cec5SDimitry Andric 1151bdd1243dSDimitry Andric // Handle emitting HLSL entry functions. 1152bdd1243dSDimitry Andric if (D && D->hasAttr<HLSLShaderAttr>()) 1153bdd1243dSDimitry Andric CGM.getHLSLRuntime().emitEntryFunction(FD, Fn); 1154bdd1243dSDimitry Andric 11550b57cec5SDimitry Andric EmitFunctionProlog(*CurFnInfo, CurFn, Args); 11560b57cec5SDimitry Andric 115781ad6265SDimitry Andric if (isa_and_nonnull<CXXMethodDecl>(D) && 115881ad6265SDimitry Andric cast<CXXMethodDecl>(D)->isInstance()) { 11590b57cec5SDimitry Andric CGM.getCXXABI().EmitInstanceFunctionProlog(*this); 11600b57cec5SDimitry Andric const CXXMethodDecl *MD = cast<CXXMethodDecl>(D); 11610b57cec5SDimitry Andric if (MD->getParent()->isLambda() && 11620b57cec5SDimitry Andric MD->getOverloadedOperator() == OO_Call) { 11630b57cec5SDimitry Andric // We're in a lambda; figure out the captures. 11640b57cec5SDimitry Andric MD->getParent()->getCaptureFields(LambdaCaptureFields, 11650b57cec5SDimitry Andric LambdaThisCaptureField); 11660b57cec5SDimitry Andric if (LambdaThisCaptureField) { 11670b57cec5SDimitry Andric // If the lambda captures the object referred to by '*this' - either by 11680b57cec5SDimitry Andric // value or by reference, make sure CXXThisValue points to the correct 11690b57cec5SDimitry Andric // object. 11700b57cec5SDimitry Andric 11710b57cec5SDimitry Andric // Get the lvalue for the field (which is a copy of the enclosing object 11720b57cec5SDimitry Andric // or contains the address of the enclosing object). 11730b57cec5SDimitry Andric LValue ThisFieldLValue = EmitLValueForLambdaField(LambdaThisCaptureField); 11740b57cec5SDimitry Andric if (!LambdaThisCaptureField->getType()->isPointerType()) { 11750b57cec5SDimitry Andric // If the enclosing object was captured by value, just use its address. 1176480093f4SDimitry Andric CXXThisValue = ThisFieldLValue.getAddress(*this).getPointer(); 11770b57cec5SDimitry Andric } else { 11780b57cec5SDimitry Andric // Load the lvalue pointed to by the field, since '*this' was captured 11790b57cec5SDimitry Andric // by reference. 11800b57cec5SDimitry Andric CXXThisValue = 11810b57cec5SDimitry Andric EmitLoadOfLValue(ThisFieldLValue, SourceLocation()).getScalarVal(); 11820b57cec5SDimitry Andric } 11830b57cec5SDimitry Andric } 11840b57cec5SDimitry Andric for (auto *FD : MD->getParent()->fields()) { 11850b57cec5SDimitry Andric if (FD->hasCapturedVLAType()) { 11860b57cec5SDimitry Andric auto *ExprArg = EmitLoadOfLValue(EmitLValueForLambdaField(FD), 11870b57cec5SDimitry Andric SourceLocation()).getScalarVal(); 11880b57cec5SDimitry Andric auto VAT = FD->getCapturedVLAType(); 11890b57cec5SDimitry Andric VLASizeMap[VAT->getSizeExpr()] = ExprArg; 11900b57cec5SDimitry Andric } 11910b57cec5SDimitry Andric } 11920b57cec5SDimitry Andric } else { 11930b57cec5SDimitry Andric // Not in a lambda; just use 'this' from the method. 11940b57cec5SDimitry Andric // FIXME: Should we generate a new load for each use of 'this'? The 11950b57cec5SDimitry Andric // fast register allocator would be happier... 11960b57cec5SDimitry Andric CXXThisValue = CXXABIThisValue; 11970b57cec5SDimitry Andric } 11980b57cec5SDimitry Andric 11990b57cec5SDimitry Andric // Check the 'this' pointer once per function, if it's available. 12000b57cec5SDimitry Andric if (CXXABIThisValue) { 12010b57cec5SDimitry Andric SanitizerSet SkippedChecks; 12020b57cec5SDimitry Andric SkippedChecks.set(SanitizerKind::ObjectSize, true); 12030b57cec5SDimitry Andric QualType ThisTy = MD->getThisType(); 12040b57cec5SDimitry Andric 12050b57cec5SDimitry Andric // If this is the call operator of a lambda with no capture-default, it 12060b57cec5SDimitry Andric // may have a static invoker function, which may call this operator with 12070b57cec5SDimitry Andric // a null 'this' pointer. 12080b57cec5SDimitry Andric if (isLambdaCallOperator(MD) && 12090b57cec5SDimitry Andric MD->getParent()->getLambdaCaptureDefault() == LCD_None) 12100b57cec5SDimitry Andric SkippedChecks.set(SanitizerKind::Null, true); 12110b57cec5SDimitry Andric 1212e8d8bef9SDimitry Andric EmitTypeCheck( 1213e8d8bef9SDimitry Andric isa<CXXConstructorDecl>(MD) ? TCK_ConstructorCall : TCK_MemberCall, 1214e8d8bef9SDimitry Andric Loc, CXXABIThisValue, ThisTy, CXXABIThisAlignment, SkippedChecks); 12150b57cec5SDimitry Andric } 12160b57cec5SDimitry Andric } 12170b57cec5SDimitry Andric 12180b57cec5SDimitry Andric // If any of the arguments have a variably modified type, make sure to 121981ad6265SDimitry Andric // emit the type size, but only if the function is not naked. Naked functions 122081ad6265SDimitry Andric // have no prolog to run this evaluation. 122181ad6265SDimitry Andric if (!FD || !FD->hasAttr<NakedAttr>()) { 122281ad6265SDimitry Andric for (const VarDecl *VD : Args) { 12230b57cec5SDimitry Andric // Dig out the type as written from ParmVarDecls; it's unclear whether 12240b57cec5SDimitry Andric // the standard (C99 6.9.1p10) requires this, but we're following the 12250b57cec5SDimitry Andric // precedent set by gcc. 12260b57cec5SDimitry Andric QualType Ty; 12270b57cec5SDimitry Andric if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) 12280b57cec5SDimitry Andric Ty = PVD->getOriginalType(); 12290b57cec5SDimitry Andric else 12300b57cec5SDimitry Andric Ty = VD->getType(); 12310b57cec5SDimitry Andric 12320b57cec5SDimitry Andric if (Ty->isVariablyModifiedType()) 12330b57cec5SDimitry Andric EmitVariablyModifiedType(Ty); 12340b57cec5SDimitry Andric } 123581ad6265SDimitry Andric } 12360b57cec5SDimitry Andric // Emit a location at the end of the prologue. 12370b57cec5SDimitry Andric if (CGDebugInfo *DI = getDebugInfo()) 12380b57cec5SDimitry Andric DI->EmitLocation(Builder, StartLoc); 12390b57cec5SDimitry Andric // TODO: Do we need to handle this in two places like we do with 12400b57cec5SDimitry Andric // target-features/target-cpu? 12410b57cec5SDimitry Andric if (CurFuncDecl) 12420b57cec5SDimitry Andric if (const auto *VecWidth = CurFuncDecl->getAttr<MinVectorWidthAttr>()) 12430b57cec5SDimitry Andric LargestVectorWidth = VecWidth->getVectorWidth(); 12440b57cec5SDimitry Andric } 12450b57cec5SDimitry Andric 12460b57cec5SDimitry Andric void CodeGenFunction::EmitFunctionBody(const Stmt *Body) { 12470b57cec5SDimitry Andric incrementProfileCounter(Body); 12480b57cec5SDimitry Andric if (const CompoundStmt *S = dyn_cast<CompoundStmt>(Body)) 12490b57cec5SDimitry Andric EmitCompoundStmtWithoutScope(*S); 12500b57cec5SDimitry Andric else 12510b57cec5SDimitry Andric EmitStmt(Body); 1252e8d8bef9SDimitry Andric 1253e8d8bef9SDimitry Andric // This is checked after emitting the function body so we know if there 1254e8d8bef9SDimitry Andric // are any permitted infinite loops. 1255fe6060f1SDimitry Andric if (checkIfFunctionMustProgress()) 1256e8d8bef9SDimitry Andric CurFn->addFnAttr(llvm::Attribute::MustProgress); 12570b57cec5SDimitry Andric } 12580b57cec5SDimitry Andric 12590b57cec5SDimitry Andric /// When instrumenting to collect profile data, the counts for some blocks 12600b57cec5SDimitry Andric /// such as switch cases need to not include the fall-through counts, so 12610b57cec5SDimitry Andric /// emit a branch around the instrumentation code. When not instrumenting, 12620b57cec5SDimitry Andric /// this just calls EmitBlock(). 12630b57cec5SDimitry Andric void CodeGenFunction::EmitBlockWithFallThrough(llvm::BasicBlock *BB, 12640b57cec5SDimitry Andric const Stmt *S) { 12650b57cec5SDimitry Andric llvm::BasicBlock *SkipCountBB = nullptr; 12660b57cec5SDimitry Andric if (HaveInsertPoint() && CGM.getCodeGenOpts().hasProfileClangInstr()) { 12670b57cec5SDimitry Andric // When instrumenting for profiling, the fallthrough to certain 12680b57cec5SDimitry Andric // statements needs to skip over the instrumentation code so that we 12690b57cec5SDimitry Andric // get an accurate count. 12700b57cec5SDimitry Andric SkipCountBB = createBasicBlock("skipcount"); 12710b57cec5SDimitry Andric EmitBranch(SkipCountBB); 12720b57cec5SDimitry Andric } 12730b57cec5SDimitry Andric EmitBlock(BB); 12740b57cec5SDimitry Andric uint64_t CurrentCount = getCurrentProfileCount(); 12750b57cec5SDimitry Andric incrementProfileCounter(S); 12760b57cec5SDimitry Andric setCurrentProfileCount(getCurrentProfileCount() + CurrentCount); 12770b57cec5SDimitry Andric if (SkipCountBB) 12780b57cec5SDimitry Andric EmitBlock(SkipCountBB); 12790b57cec5SDimitry Andric } 12800b57cec5SDimitry Andric 12810b57cec5SDimitry Andric /// Tries to mark the given function nounwind based on the 12820b57cec5SDimitry Andric /// non-existence of any throwing calls within it. We believe this is 12830b57cec5SDimitry Andric /// lightweight enough to do at -O0. 12840b57cec5SDimitry Andric static void TryMarkNoThrow(llvm::Function *F) { 12850b57cec5SDimitry Andric // LLVM treats 'nounwind' on a function as part of the type, so we 12860b57cec5SDimitry Andric // can't do this on functions that can be overwritten. 12870b57cec5SDimitry Andric if (F->isInterposable()) return; 12880b57cec5SDimitry Andric 12890b57cec5SDimitry Andric for (llvm::BasicBlock &BB : *F) 12900b57cec5SDimitry Andric for (llvm::Instruction &I : BB) 12910b57cec5SDimitry Andric if (I.mayThrow()) 12920b57cec5SDimitry Andric return; 12930b57cec5SDimitry Andric 12940b57cec5SDimitry Andric F->setDoesNotThrow(); 12950b57cec5SDimitry Andric } 12960b57cec5SDimitry Andric 12970b57cec5SDimitry Andric QualType CodeGenFunction::BuildFunctionArgList(GlobalDecl GD, 12980b57cec5SDimitry Andric FunctionArgList &Args) { 12990b57cec5SDimitry Andric const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 13000b57cec5SDimitry Andric QualType ResTy = FD->getReturnType(); 13010b57cec5SDimitry Andric 13020b57cec5SDimitry Andric const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 13030b57cec5SDimitry Andric if (MD && MD->isInstance()) { 13040b57cec5SDimitry Andric if (CGM.getCXXABI().HasThisReturn(GD)) 13050b57cec5SDimitry Andric ResTy = MD->getThisType(); 13060b57cec5SDimitry Andric else if (CGM.getCXXABI().hasMostDerivedReturn(GD)) 13070b57cec5SDimitry Andric ResTy = CGM.getContext().VoidPtrTy; 13080b57cec5SDimitry Andric CGM.getCXXABI().buildThisParam(*this, Args); 13090b57cec5SDimitry Andric } 13100b57cec5SDimitry Andric 13110b57cec5SDimitry Andric // The base version of an inheriting constructor whose constructed base is a 13120b57cec5SDimitry Andric // virtual base is not passed any arguments (because it doesn't actually call 13130b57cec5SDimitry Andric // the inherited constructor). 13140b57cec5SDimitry Andric bool PassedParams = true; 13150b57cec5SDimitry Andric if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) 13160b57cec5SDimitry Andric if (auto Inherited = CD->getInheritedConstructor()) 13170b57cec5SDimitry Andric PassedParams = 13180b57cec5SDimitry Andric getTypes().inheritingCtorHasParams(Inherited, GD.getCtorType()); 13190b57cec5SDimitry Andric 13200b57cec5SDimitry Andric if (PassedParams) { 13210b57cec5SDimitry Andric for (auto *Param : FD->parameters()) { 13220b57cec5SDimitry Andric Args.push_back(Param); 13230b57cec5SDimitry Andric if (!Param->hasAttr<PassObjectSizeAttr>()) 13240b57cec5SDimitry Andric continue; 13250b57cec5SDimitry Andric 13260b57cec5SDimitry Andric auto *Implicit = ImplicitParamDecl::Create( 13270b57cec5SDimitry Andric getContext(), Param->getDeclContext(), Param->getLocation(), 13280b57cec5SDimitry Andric /*Id=*/nullptr, getContext().getSizeType(), ImplicitParamDecl::Other); 13290b57cec5SDimitry Andric SizeArguments[Param] = Implicit; 13300b57cec5SDimitry Andric Args.push_back(Implicit); 13310b57cec5SDimitry Andric } 13320b57cec5SDimitry Andric } 13330b57cec5SDimitry Andric 13340b57cec5SDimitry Andric if (MD && (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD))) 13350b57cec5SDimitry Andric CGM.getCXXABI().addImplicitStructorParams(*this, ResTy, Args); 13360b57cec5SDimitry Andric 13370b57cec5SDimitry Andric return ResTy; 13380b57cec5SDimitry Andric } 13390b57cec5SDimitry Andric 13400b57cec5SDimitry Andric void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn, 13410b57cec5SDimitry Andric const CGFunctionInfo &FnInfo) { 13420eae32dcSDimitry Andric assert(Fn && "generating code for null Function"); 13430b57cec5SDimitry Andric const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 13440b57cec5SDimitry Andric CurGD = GD; 13450b57cec5SDimitry Andric 13460b57cec5SDimitry Andric FunctionArgList Args; 13470b57cec5SDimitry Andric QualType ResTy = BuildFunctionArgList(GD, Args); 13480b57cec5SDimitry Andric 1349349cc55cSDimitry Andric if (FD->isInlineBuiltinDeclaration()) { 13500eae32dcSDimitry Andric // When generating code for a builtin with an inline declaration, use a 13510eae32dcSDimitry Andric // mangled name to hold the actual body, while keeping an external 13520eae32dcSDimitry Andric // definition in case the function pointer is referenced somewhere. 1353349cc55cSDimitry Andric std::string FDInlineName = (Fn->getName() + ".inline").str(); 1354349cc55cSDimitry Andric llvm::Module *M = Fn->getParent(); 1355349cc55cSDimitry Andric llvm::Function *Clone = M->getFunction(FDInlineName); 1356349cc55cSDimitry Andric if (!Clone) { 1357349cc55cSDimitry Andric Clone = llvm::Function::Create(Fn->getFunctionType(), 1358349cc55cSDimitry Andric llvm::GlobalValue::InternalLinkage, 1359349cc55cSDimitry Andric Fn->getAddressSpace(), FDInlineName, M); 1360349cc55cSDimitry Andric Clone->addFnAttr(llvm::Attribute::AlwaysInline); 1361349cc55cSDimitry Andric } 1362349cc55cSDimitry Andric Fn->setLinkage(llvm::GlobalValue::ExternalLinkage); 1363349cc55cSDimitry Andric Fn = Clone; 13640eae32dcSDimitry Andric } else { 1365349cc55cSDimitry Andric // Detect the unusual situation where an inline version is shadowed by a 1366349cc55cSDimitry Andric // non-inline version. In that case we should pick the external one 1367349cc55cSDimitry Andric // everywhere. That's GCC behavior too. Unfortunately, I cannot find a way 1368349cc55cSDimitry Andric // to detect that situation before we reach codegen, so do some late 1369349cc55cSDimitry Andric // replacement. 1370349cc55cSDimitry Andric for (const FunctionDecl *PD = FD->getPreviousDecl(); PD; 1371349cc55cSDimitry Andric PD = PD->getPreviousDecl()) { 1372349cc55cSDimitry Andric if (LLVM_UNLIKELY(PD->isInlineBuiltinDeclaration())) { 1373349cc55cSDimitry Andric std::string FDInlineName = (Fn->getName() + ".inline").str(); 1374349cc55cSDimitry Andric llvm::Module *M = Fn->getParent(); 1375349cc55cSDimitry Andric if (llvm::Function *Clone = M->getFunction(FDInlineName)) { 1376349cc55cSDimitry Andric Clone->replaceAllUsesWith(Fn); 1377349cc55cSDimitry Andric Clone->eraseFromParent(); 1378349cc55cSDimitry Andric } 1379349cc55cSDimitry Andric break; 1380349cc55cSDimitry Andric } 1381349cc55cSDimitry Andric } 1382349cc55cSDimitry Andric } 1383349cc55cSDimitry Andric 13840b57cec5SDimitry Andric // Check if we should generate debug info for this function. 1385fe6060f1SDimitry Andric if (FD->hasAttr<NoDebugAttr>()) { 1386fe6060f1SDimitry Andric // Clear non-distinct debug info that was possibly attached to the function 1387fe6060f1SDimitry Andric // due to an earlier declaration without the nodebug attribute 1388fe6060f1SDimitry Andric Fn->setSubprogram(nullptr); 1389fe6060f1SDimitry Andric // Disable debug info indefinitely for this function 1390fe6060f1SDimitry Andric DebugInfo = nullptr; 1391fe6060f1SDimitry Andric } 13920b57cec5SDimitry Andric 13930b57cec5SDimitry Andric // The function might not have a body if we're generating thunks for a 13940b57cec5SDimitry Andric // function declaration. 13950b57cec5SDimitry Andric SourceRange BodyRange; 13960b57cec5SDimitry Andric if (Stmt *Body = FD->getBody()) 13970b57cec5SDimitry Andric BodyRange = Body->getSourceRange(); 13980b57cec5SDimitry Andric else 13990b57cec5SDimitry Andric BodyRange = FD->getLocation(); 14000b57cec5SDimitry Andric CurEHLocation = BodyRange.getEnd(); 14010b57cec5SDimitry Andric 14020b57cec5SDimitry Andric // Use the location of the start of the function to determine where 14030b57cec5SDimitry Andric // the function definition is located. By default use the location 14040b57cec5SDimitry Andric // of the declaration as the location for the subprogram. A function 14050b57cec5SDimitry Andric // may lack a declaration in the source code if it is created by code 14060b57cec5SDimitry Andric // gen. (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk). 14070b57cec5SDimitry Andric SourceLocation Loc = FD->getLocation(); 14080b57cec5SDimitry Andric 14090b57cec5SDimitry Andric // If this is a function specialization then use the pattern body 14100b57cec5SDimitry Andric // as the location for the function. 14110b57cec5SDimitry Andric if (const FunctionDecl *SpecDecl = FD->getTemplateInstantiationPattern()) 14120b57cec5SDimitry Andric if (SpecDecl->hasBody(SpecDecl)) 14130b57cec5SDimitry Andric Loc = SpecDecl->getLocation(); 14140b57cec5SDimitry Andric 14150b57cec5SDimitry Andric Stmt *Body = FD->getBody(); 14160b57cec5SDimitry Andric 1417fe6060f1SDimitry Andric if (Body) { 1418fe6060f1SDimitry Andric // Coroutines always emit lifetime markers. 1419fe6060f1SDimitry Andric if (isa<CoroutineBodyStmt>(Body)) 1420fe6060f1SDimitry Andric ShouldEmitLifetimeMarkers = true; 1421fe6060f1SDimitry Andric 1422fe6060f1SDimitry Andric // Initialize helper which will detect jumps which can cause invalid 1423fe6060f1SDimitry Andric // lifetime markers. 1424fe6060f1SDimitry Andric if (ShouldEmitLifetimeMarkers) 14250b57cec5SDimitry Andric Bypasses.Init(Body); 1426fe6060f1SDimitry Andric } 14270b57cec5SDimitry Andric 14280b57cec5SDimitry Andric // Emit the standard function prologue. 14290b57cec5SDimitry Andric StartFunction(GD, ResTy, Fn, FnInfo, Args, Loc, BodyRange.getBegin()); 14300b57cec5SDimitry Andric 1431fe6060f1SDimitry Andric // Save parameters for coroutine function. 1432fe6060f1SDimitry Andric if (Body && isa_and_nonnull<CoroutineBodyStmt>(Body)) 143381ad6265SDimitry Andric llvm::append_range(FnArgs, FD->parameters()); 1434fe6060f1SDimitry Andric 14350b57cec5SDimitry Andric // Generate the body of the function. 14360b57cec5SDimitry Andric PGO.assignRegionCounters(GD, CurFn); 14370b57cec5SDimitry Andric if (isa<CXXDestructorDecl>(FD)) 14380b57cec5SDimitry Andric EmitDestructorBody(Args); 14390b57cec5SDimitry Andric else if (isa<CXXConstructorDecl>(FD)) 14400b57cec5SDimitry Andric EmitConstructorBody(Args); 14410b57cec5SDimitry Andric else if (getLangOpts().CUDA && 14420b57cec5SDimitry Andric !getLangOpts().CUDAIsDevice && 14430b57cec5SDimitry Andric FD->hasAttr<CUDAGlobalAttr>()) 14440b57cec5SDimitry Andric CGM.getCUDARuntime().emitDeviceStub(*this, Args); 14450b57cec5SDimitry Andric else if (isa<CXXMethodDecl>(FD) && 14460b57cec5SDimitry Andric cast<CXXMethodDecl>(FD)->isLambdaStaticInvoker()) { 14470b57cec5SDimitry Andric // The lambda static invoker function is special, because it forwards or 14480b57cec5SDimitry Andric // clones the body of the function call operator (but is actually static). 14490b57cec5SDimitry Andric EmitLambdaStaticInvokeBody(cast<CXXMethodDecl>(FD)); 14500b57cec5SDimitry Andric } else if (FD->isDefaulted() && isa<CXXMethodDecl>(FD) && 14510b57cec5SDimitry Andric (cast<CXXMethodDecl>(FD)->isCopyAssignmentOperator() || 14520b57cec5SDimitry Andric cast<CXXMethodDecl>(FD)->isMoveAssignmentOperator())) { 14530b57cec5SDimitry Andric // Implicit copy-assignment gets the same special treatment as implicit 14540b57cec5SDimitry Andric // copy-constructors. 14550b57cec5SDimitry Andric emitImplicitAssignmentOperatorBody(Args); 14560b57cec5SDimitry Andric } else if (Body) { 14570b57cec5SDimitry Andric EmitFunctionBody(Body); 14580b57cec5SDimitry Andric } else 14590b57cec5SDimitry Andric llvm_unreachable("no definition for emitted function"); 14600b57cec5SDimitry Andric 14610b57cec5SDimitry Andric // C++11 [stmt.return]p2: 14620b57cec5SDimitry Andric // Flowing off the end of a function [...] results in undefined behavior in 14630b57cec5SDimitry Andric // a value-returning function. 14640b57cec5SDimitry Andric // C11 6.9.1p12: 14650b57cec5SDimitry Andric // If the '}' that terminates a function is reached, and the value of the 14660b57cec5SDimitry Andric // function call is used by the caller, the behavior is undefined. 14670b57cec5SDimitry Andric if (getLangOpts().CPlusPlus && !FD->hasImplicitReturnZero() && !SawAsmBlock && 14680b57cec5SDimitry Andric !FD->getReturnType()->isVoidType() && Builder.GetInsertBlock()) { 14690b57cec5SDimitry Andric bool ShouldEmitUnreachable = 14700b57cec5SDimitry Andric CGM.getCodeGenOpts().StrictReturn || 1471fe6060f1SDimitry Andric !CGM.MayDropFunctionReturn(FD->getASTContext(), FD->getReturnType()); 14720b57cec5SDimitry Andric if (SanOpts.has(SanitizerKind::Return)) { 14730b57cec5SDimitry Andric SanitizerScope SanScope(this); 14740b57cec5SDimitry Andric llvm::Value *IsFalse = Builder.getFalse(); 14750b57cec5SDimitry Andric EmitCheck(std::make_pair(IsFalse, SanitizerKind::Return), 14760b57cec5SDimitry Andric SanitizerHandler::MissingReturn, 1477bdd1243dSDimitry Andric EmitCheckSourceLocation(FD->getLocation()), std::nullopt); 14780b57cec5SDimitry Andric } else if (ShouldEmitUnreachable) { 14790b57cec5SDimitry Andric if (CGM.getCodeGenOpts().OptimizationLevel == 0) 14800b57cec5SDimitry Andric EmitTrapCall(llvm::Intrinsic::trap); 14810b57cec5SDimitry Andric } 14820b57cec5SDimitry Andric if (SanOpts.has(SanitizerKind::Return) || ShouldEmitUnreachable) { 14830b57cec5SDimitry Andric Builder.CreateUnreachable(); 14840b57cec5SDimitry Andric Builder.ClearInsertionPoint(); 14850b57cec5SDimitry Andric } 14860b57cec5SDimitry Andric } 14870b57cec5SDimitry Andric 14880b57cec5SDimitry Andric // Emit the standard function epilogue. 14890b57cec5SDimitry Andric FinishFunction(BodyRange.getEnd()); 14900b57cec5SDimitry Andric 14910b57cec5SDimitry Andric // If we haven't marked the function nothrow through other means, do 14920b57cec5SDimitry Andric // a quick pass now to see if we can. 14930b57cec5SDimitry Andric if (!CurFn->doesNotThrow()) 14940b57cec5SDimitry Andric TryMarkNoThrow(CurFn); 14950b57cec5SDimitry Andric } 14960b57cec5SDimitry Andric 14970b57cec5SDimitry Andric /// ContainsLabel - Return true if the statement contains a label in it. If 14980b57cec5SDimitry Andric /// this statement is not executed normally, it not containing a label means 14990b57cec5SDimitry Andric /// that we can just remove the code. 15000b57cec5SDimitry Andric bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) { 15010b57cec5SDimitry Andric // Null statement, not a label! 15020b57cec5SDimitry Andric if (!S) return false; 15030b57cec5SDimitry Andric 15040b57cec5SDimitry Andric // If this is a label, we have to emit the code, consider something like: 15050b57cec5SDimitry Andric // if (0) { ... foo: bar(); } goto foo; 15060b57cec5SDimitry Andric // 15070b57cec5SDimitry Andric // TODO: If anyone cared, we could track __label__'s, since we know that you 15080b57cec5SDimitry Andric // can't jump to one from outside their declared region. 15090b57cec5SDimitry Andric if (isa<LabelStmt>(S)) 15100b57cec5SDimitry Andric return true; 15110b57cec5SDimitry Andric 15120b57cec5SDimitry Andric // If this is a case/default statement, and we haven't seen a switch, we have 15130b57cec5SDimitry Andric // to emit the code. 15140b57cec5SDimitry Andric if (isa<SwitchCase>(S) && !IgnoreCaseStmts) 15150b57cec5SDimitry Andric return true; 15160b57cec5SDimitry Andric 15170b57cec5SDimitry Andric // If this is a switch statement, we want to ignore cases below it. 15180b57cec5SDimitry Andric if (isa<SwitchStmt>(S)) 15190b57cec5SDimitry Andric IgnoreCaseStmts = true; 15200b57cec5SDimitry Andric 15210b57cec5SDimitry Andric // Scan subexpressions for verboten labels. 15220b57cec5SDimitry Andric for (const Stmt *SubStmt : S->children()) 15230b57cec5SDimitry Andric if (ContainsLabel(SubStmt, IgnoreCaseStmts)) 15240b57cec5SDimitry Andric return true; 15250b57cec5SDimitry Andric 15260b57cec5SDimitry Andric return false; 15270b57cec5SDimitry Andric } 15280b57cec5SDimitry Andric 15290b57cec5SDimitry Andric /// containsBreak - Return true if the statement contains a break out of it. 15300b57cec5SDimitry Andric /// If the statement (recursively) contains a switch or loop with a break 15310b57cec5SDimitry Andric /// inside of it, this is fine. 15320b57cec5SDimitry Andric bool CodeGenFunction::containsBreak(const Stmt *S) { 15330b57cec5SDimitry Andric // Null statement, not a label! 15340b57cec5SDimitry Andric if (!S) return false; 15350b57cec5SDimitry Andric 15360b57cec5SDimitry Andric // If this is a switch or loop that defines its own break scope, then we can 15370b57cec5SDimitry Andric // include it and anything inside of it. 15380b57cec5SDimitry Andric if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) || 15390b57cec5SDimitry Andric isa<ForStmt>(S)) 15400b57cec5SDimitry Andric return false; 15410b57cec5SDimitry Andric 15420b57cec5SDimitry Andric if (isa<BreakStmt>(S)) 15430b57cec5SDimitry Andric return true; 15440b57cec5SDimitry Andric 15450b57cec5SDimitry Andric // Scan subexpressions for verboten breaks. 15460b57cec5SDimitry Andric for (const Stmt *SubStmt : S->children()) 15470b57cec5SDimitry Andric if (containsBreak(SubStmt)) 15480b57cec5SDimitry Andric return true; 15490b57cec5SDimitry Andric 15500b57cec5SDimitry Andric return false; 15510b57cec5SDimitry Andric } 15520b57cec5SDimitry Andric 15530b57cec5SDimitry Andric bool CodeGenFunction::mightAddDeclToScope(const Stmt *S) { 15540b57cec5SDimitry Andric if (!S) return false; 15550b57cec5SDimitry Andric 15560b57cec5SDimitry Andric // Some statement kinds add a scope and thus never add a decl to the current 15570b57cec5SDimitry Andric // scope. Note, this list is longer than the list of statements that might 15580b57cec5SDimitry Andric // have an unscoped decl nested within them, but this way is conservatively 15590b57cec5SDimitry Andric // correct even if more statement kinds are added. 15600b57cec5SDimitry Andric if (isa<IfStmt>(S) || isa<SwitchStmt>(S) || isa<WhileStmt>(S) || 15610b57cec5SDimitry Andric isa<DoStmt>(S) || isa<ForStmt>(S) || isa<CompoundStmt>(S) || 15620b57cec5SDimitry Andric isa<CXXForRangeStmt>(S) || isa<CXXTryStmt>(S) || 15630b57cec5SDimitry Andric isa<ObjCForCollectionStmt>(S) || isa<ObjCAtTryStmt>(S)) 15640b57cec5SDimitry Andric return false; 15650b57cec5SDimitry Andric 15660b57cec5SDimitry Andric if (isa<DeclStmt>(S)) 15670b57cec5SDimitry Andric return true; 15680b57cec5SDimitry Andric 15690b57cec5SDimitry Andric for (const Stmt *SubStmt : S->children()) 15700b57cec5SDimitry Andric if (mightAddDeclToScope(SubStmt)) 15710b57cec5SDimitry Andric return true; 15720b57cec5SDimitry Andric 15730b57cec5SDimitry Andric return false; 15740b57cec5SDimitry Andric } 15750b57cec5SDimitry Andric 15760b57cec5SDimitry Andric /// ConstantFoldsToSimpleInteger - If the specified expression does not fold 15770b57cec5SDimitry Andric /// to a constant, or if it does but contains a label, return false. If it 15780b57cec5SDimitry Andric /// constant folds return true and set the boolean result in Result. 15790b57cec5SDimitry Andric bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond, 15800b57cec5SDimitry Andric bool &ResultBool, 15810b57cec5SDimitry Andric bool AllowLabels) { 15820b57cec5SDimitry Andric llvm::APSInt ResultInt; 15830b57cec5SDimitry Andric if (!ConstantFoldsToSimpleInteger(Cond, ResultInt, AllowLabels)) 15840b57cec5SDimitry Andric return false; 15850b57cec5SDimitry Andric 15860b57cec5SDimitry Andric ResultBool = ResultInt.getBoolValue(); 15870b57cec5SDimitry Andric return true; 15880b57cec5SDimitry Andric } 15890b57cec5SDimitry Andric 15900b57cec5SDimitry Andric /// ConstantFoldsToSimpleInteger - If the specified expression does not fold 15910b57cec5SDimitry Andric /// to a constant, or if it does but contains a label, return false. If it 15920b57cec5SDimitry Andric /// constant folds return true and set the folded value. 15930b57cec5SDimitry Andric bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond, 15940b57cec5SDimitry Andric llvm::APSInt &ResultInt, 15950b57cec5SDimitry Andric bool AllowLabels) { 15960b57cec5SDimitry Andric // FIXME: Rename and handle conversion of other evaluatable things 15970b57cec5SDimitry Andric // to bool. 15980b57cec5SDimitry Andric Expr::EvalResult Result; 15990b57cec5SDimitry Andric if (!Cond->EvaluateAsInt(Result, getContext())) 16000b57cec5SDimitry Andric return false; // Not foldable, not integer or not fully evaluatable. 16010b57cec5SDimitry Andric 16020b57cec5SDimitry Andric llvm::APSInt Int = Result.Val.getInt(); 16030b57cec5SDimitry Andric if (!AllowLabels && CodeGenFunction::ContainsLabel(Cond)) 16040b57cec5SDimitry Andric return false; // Contains a label. 16050b57cec5SDimitry Andric 16060b57cec5SDimitry Andric ResultInt = Int; 16070b57cec5SDimitry Andric return true; 16080b57cec5SDimitry Andric } 16090b57cec5SDimitry Andric 1610e8d8bef9SDimitry Andric /// Determine whether the given condition is an instrumentable condition 1611e8d8bef9SDimitry Andric /// (i.e. no "&&" or "||"). 1612e8d8bef9SDimitry Andric bool CodeGenFunction::isInstrumentedCondition(const Expr *C) { 1613e8d8bef9SDimitry Andric // Bypass simplistic logical-NOT operator before determining whether the 1614e8d8bef9SDimitry Andric // condition contains any other logical operator. 1615e8d8bef9SDimitry Andric if (const UnaryOperator *UnOp = dyn_cast<UnaryOperator>(C->IgnoreParens())) 1616e8d8bef9SDimitry Andric if (UnOp->getOpcode() == UO_LNot) 1617e8d8bef9SDimitry Andric C = UnOp->getSubExpr(); 16180b57cec5SDimitry Andric 1619e8d8bef9SDimitry Andric const BinaryOperator *BOp = dyn_cast<BinaryOperator>(C->IgnoreParens()); 1620e8d8bef9SDimitry Andric return (!BOp || !BOp->isLogicalOp()); 1621e8d8bef9SDimitry Andric } 1622e8d8bef9SDimitry Andric 1623e8d8bef9SDimitry Andric /// EmitBranchToCounterBlock - Emit a conditional branch to a new block that 1624e8d8bef9SDimitry Andric /// increments a profile counter based on the semantics of the given logical 1625e8d8bef9SDimitry Andric /// operator opcode. This is used to instrument branch condition coverage for 1626e8d8bef9SDimitry Andric /// logical operators. 1627e8d8bef9SDimitry Andric void CodeGenFunction::EmitBranchToCounterBlock( 1628e8d8bef9SDimitry Andric const Expr *Cond, BinaryOperator::Opcode LOp, llvm::BasicBlock *TrueBlock, 1629e8d8bef9SDimitry Andric llvm::BasicBlock *FalseBlock, uint64_t TrueCount /* = 0 */, 1630e8d8bef9SDimitry Andric Stmt::Likelihood LH /* =None */, const Expr *CntrIdx /* = nullptr */) { 1631e8d8bef9SDimitry Andric // If not instrumenting, just emit a branch. 1632e8d8bef9SDimitry Andric bool InstrumentRegions = CGM.getCodeGenOpts().hasProfileClangInstr(); 1633e8d8bef9SDimitry Andric if (!InstrumentRegions || !isInstrumentedCondition(Cond)) 1634e8d8bef9SDimitry Andric return EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount, LH); 1635e8d8bef9SDimitry Andric 163604eeddc0SDimitry Andric llvm::BasicBlock *ThenBlock = nullptr; 163704eeddc0SDimitry Andric llvm::BasicBlock *ElseBlock = nullptr; 163804eeddc0SDimitry Andric llvm::BasicBlock *NextBlock = nullptr; 1639e8d8bef9SDimitry Andric 1640e8d8bef9SDimitry Andric // Create the block we'll use to increment the appropriate counter. 1641e8d8bef9SDimitry Andric llvm::BasicBlock *CounterIncrBlock = createBasicBlock("lop.rhscnt"); 1642e8d8bef9SDimitry Andric 1643e8d8bef9SDimitry Andric // Set block pointers according to Logical-AND (BO_LAnd) semantics. This 1644e8d8bef9SDimitry Andric // means we need to evaluate the condition and increment the counter on TRUE: 1645e8d8bef9SDimitry Andric // 1646e8d8bef9SDimitry Andric // if (Cond) 1647e8d8bef9SDimitry Andric // goto CounterIncrBlock; 1648e8d8bef9SDimitry Andric // else 1649e8d8bef9SDimitry Andric // goto FalseBlock; 1650e8d8bef9SDimitry Andric // 1651e8d8bef9SDimitry Andric // CounterIncrBlock: 1652e8d8bef9SDimitry Andric // Counter++; 1653e8d8bef9SDimitry Andric // goto TrueBlock; 1654e8d8bef9SDimitry Andric 1655e8d8bef9SDimitry Andric if (LOp == BO_LAnd) { 1656e8d8bef9SDimitry Andric ThenBlock = CounterIncrBlock; 1657e8d8bef9SDimitry Andric ElseBlock = FalseBlock; 1658e8d8bef9SDimitry Andric NextBlock = TrueBlock; 1659e8d8bef9SDimitry Andric } 1660e8d8bef9SDimitry Andric 1661e8d8bef9SDimitry Andric // Set block pointers according to Logical-OR (BO_LOr) semantics. This means 1662e8d8bef9SDimitry Andric // we need to evaluate the condition and increment the counter on FALSE: 1663e8d8bef9SDimitry Andric // 1664e8d8bef9SDimitry Andric // if (Cond) 1665e8d8bef9SDimitry Andric // goto TrueBlock; 1666e8d8bef9SDimitry Andric // else 1667e8d8bef9SDimitry Andric // goto CounterIncrBlock; 1668e8d8bef9SDimitry Andric // 1669e8d8bef9SDimitry Andric // CounterIncrBlock: 1670e8d8bef9SDimitry Andric // Counter++; 1671e8d8bef9SDimitry Andric // goto FalseBlock; 1672e8d8bef9SDimitry Andric 1673e8d8bef9SDimitry Andric else if (LOp == BO_LOr) { 1674e8d8bef9SDimitry Andric ThenBlock = TrueBlock; 1675e8d8bef9SDimitry Andric ElseBlock = CounterIncrBlock; 1676e8d8bef9SDimitry Andric NextBlock = FalseBlock; 1677e8d8bef9SDimitry Andric } else { 1678e8d8bef9SDimitry Andric llvm_unreachable("Expected Opcode must be that of a Logical Operator"); 1679e8d8bef9SDimitry Andric } 1680e8d8bef9SDimitry Andric 1681e8d8bef9SDimitry Andric // Emit Branch based on condition. 1682e8d8bef9SDimitry Andric EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, TrueCount, LH); 1683e8d8bef9SDimitry Andric 1684e8d8bef9SDimitry Andric // Emit the block containing the counter increment(s). 1685e8d8bef9SDimitry Andric EmitBlock(CounterIncrBlock); 1686e8d8bef9SDimitry Andric 1687e8d8bef9SDimitry Andric // Increment corresponding counter; if index not provided, use Cond as index. 1688e8d8bef9SDimitry Andric incrementProfileCounter(CntrIdx ? CntrIdx : Cond); 1689e8d8bef9SDimitry Andric 1690e8d8bef9SDimitry Andric // Go to the next block. 1691e8d8bef9SDimitry Andric EmitBranch(NextBlock); 1692e8d8bef9SDimitry Andric } 16930b57cec5SDimitry Andric 16940b57cec5SDimitry Andric /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if 16950b57cec5SDimitry Andric /// statement) to the specified blocks. Based on the condition, this might try 16960b57cec5SDimitry Andric /// to simplify the codegen of the conditional based on the branch. 1697e8d8bef9SDimitry Andric /// \param LH The value of the likelihood attribute on the True branch. 16980b57cec5SDimitry Andric void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond, 16990b57cec5SDimitry Andric llvm::BasicBlock *TrueBlock, 17000b57cec5SDimitry Andric llvm::BasicBlock *FalseBlock, 1701e8d8bef9SDimitry Andric uint64_t TrueCount, 1702e8d8bef9SDimitry Andric Stmt::Likelihood LH) { 17030b57cec5SDimitry Andric Cond = Cond->IgnoreParens(); 17040b57cec5SDimitry Andric 17050b57cec5SDimitry Andric if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) { 17060b57cec5SDimitry Andric 17070b57cec5SDimitry Andric // Handle X && Y in a condition. 17080b57cec5SDimitry Andric if (CondBOp->getOpcode() == BO_LAnd) { 17090b57cec5SDimitry Andric // If we have "1 && X", simplify the code. "0 && X" would have constant 17100b57cec5SDimitry Andric // folded if the case was simple enough. 17110b57cec5SDimitry Andric bool ConstantBool = false; 17120b57cec5SDimitry Andric if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) && 17130b57cec5SDimitry Andric ConstantBool) { 17140b57cec5SDimitry Andric // br(1 && X) -> br(X). 17150b57cec5SDimitry Andric incrementProfileCounter(CondBOp); 1716e8d8bef9SDimitry Andric return EmitBranchToCounterBlock(CondBOp->getRHS(), BO_LAnd, TrueBlock, 1717e8d8bef9SDimitry Andric FalseBlock, TrueCount, LH); 17180b57cec5SDimitry Andric } 17190b57cec5SDimitry Andric 17200b57cec5SDimitry Andric // If we have "X && 1", simplify the code to use an uncond branch. 17210b57cec5SDimitry Andric // "X && 0" would have been constant folded to 0. 17220b57cec5SDimitry Andric if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) && 17230b57cec5SDimitry Andric ConstantBool) { 17240b57cec5SDimitry Andric // br(X && 1) -> br(X). 1725e8d8bef9SDimitry Andric return EmitBranchToCounterBlock(CondBOp->getLHS(), BO_LAnd, TrueBlock, 1726e8d8bef9SDimitry Andric FalseBlock, TrueCount, LH, CondBOp); 17270b57cec5SDimitry Andric } 17280b57cec5SDimitry Andric 17290b57cec5SDimitry Andric // Emit the LHS as a conditional. If the LHS conditional is false, we 17300b57cec5SDimitry Andric // want to jump to the FalseBlock. 17310b57cec5SDimitry Andric llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true"); 17320b57cec5SDimitry Andric // The counter tells us how often we evaluate RHS, and all of TrueCount 17330b57cec5SDimitry Andric // can be propagated to that branch. 17340b57cec5SDimitry Andric uint64_t RHSCount = getProfileCount(CondBOp->getRHS()); 17350b57cec5SDimitry Andric 17360b57cec5SDimitry Andric ConditionalEvaluation eval(*this); 17370b57cec5SDimitry Andric { 17380b57cec5SDimitry Andric ApplyDebugLocation DL(*this, Cond); 1739e8d8bef9SDimitry Andric // Propagate the likelihood attribute like __builtin_expect 1740e8d8bef9SDimitry Andric // __builtin_expect(X && Y, 1) -> X and Y are likely 1741e8d8bef9SDimitry Andric // __builtin_expect(X && Y, 0) -> only Y is unlikely 1742e8d8bef9SDimitry Andric EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock, RHSCount, 1743e8d8bef9SDimitry Andric LH == Stmt::LH_Unlikely ? Stmt::LH_None : LH); 17440b57cec5SDimitry Andric EmitBlock(LHSTrue); 17450b57cec5SDimitry Andric } 17460b57cec5SDimitry Andric 17470b57cec5SDimitry Andric incrementProfileCounter(CondBOp); 17480b57cec5SDimitry Andric setCurrentProfileCount(getProfileCount(CondBOp->getRHS())); 17490b57cec5SDimitry Andric 17500b57cec5SDimitry Andric // Any temporaries created here are conditional. 17510b57cec5SDimitry Andric eval.begin(*this); 1752e8d8bef9SDimitry Andric EmitBranchToCounterBlock(CondBOp->getRHS(), BO_LAnd, TrueBlock, 1753e8d8bef9SDimitry Andric FalseBlock, TrueCount, LH); 17540b57cec5SDimitry Andric eval.end(*this); 17550b57cec5SDimitry Andric 17560b57cec5SDimitry Andric return; 17570b57cec5SDimitry Andric } 17580b57cec5SDimitry Andric 17590b57cec5SDimitry Andric if (CondBOp->getOpcode() == BO_LOr) { 17600b57cec5SDimitry Andric // If we have "0 || X", simplify the code. "1 || X" would have constant 17610b57cec5SDimitry Andric // folded if the case was simple enough. 17620b57cec5SDimitry Andric bool ConstantBool = false; 17630b57cec5SDimitry Andric if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) && 17640b57cec5SDimitry Andric !ConstantBool) { 17650b57cec5SDimitry Andric // br(0 || X) -> br(X). 17660b57cec5SDimitry Andric incrementProfileCounter(CondBOp); 1767e8d8bef9SDimitry Andric return EmitBranchToCounterBlock(CondBOp->getRHS(), BO_LOr, TrueBlock, 1768e8d8bef9SDimitry Andric FalseBlock, TrueCount, LH); 17690b57cec5SDimitry Andric } 17700b57cec5SDimitry Andric 17710b57cec5SDimitry Andric // If we have "X || 0", simplify the code to use an uncond branch. 17720b57cec5SDimitry Andric // "X || 1" would have been constant folded to 1. 17730b57cec5SDimitry Andric if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) && 17740b57cec5SDimitry Andric !ConstantBool) { 17750b57cec5SDimitry Andric // br(X || 0) -> br(X). 1776e8d8bef9SDimitry Andric return EmitBranchToCounterBlock(CondBOp->getLHS(), BO_LOr, TrueBlock, 1777e8d8bef9SDimitry Andric FalseBlock, TrueCount, LH, CondBOp); 17780b57cec5SDimitry Andric } 17790b57cec5SDimitry Andric 17800b57cec5SDimitry Andric // Emit the LHS as a conditional. If the LHS conditional is true, we 17810b57cec5SDimitry Andric // want to jump to the TrueBlock. 17820b57cec5SDimitry Andric llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false"); 17830b57cec5SDimitry Andric // We have the count for entry to the RHS and for the whole expression 17840b57cec5SDimitry Andric // being true, so we can divy up True count between the short circuit and 17850b57cec5SDimitry Andric // the RHS. 17860b57cec5SDimitry Andric uint64_t LHSCount = 17870b57cec5SDimitry Andric getCurrentProfileCount() - getProfileCount(CondBOp->getRHS()); 17880b57cec5SDimitry Andric uint64_t RHSCount = TrueCount - LHSCount; 17890b57cec5SDimitry Andric 17900b57cec5SDimitry Andric ConditionalEvaluation eval(*this); 17910b57cec5SDimitry Andric { 1792e8d8bef9SDimitry Andric // Propagate the likelihood attribute like __builtin_expect 1793e8d8bef9SDimitry Andric // __builtin_expect(X || Y, 1) -> only Y is likely 1794e8d8bef9SDimitry Andric // __builtin_expect(X || Y, 0) -> both X and Y are unlikely 17950b57cec5SDimitry Andric ApplyDebugLocation DL(*this, Cond); 1796e8d8bef9SDimitry Andric EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse, LHSCount, 1797e8d8bef9SDimitry Andric LH == Stmt::LH_Likely ? Stmt::LH_None : LH); 17980b57cec5SDimitry Andric EmitBlock(LHSFalse); 17990b57cec5SDimitry Andric } 18000b57cec5SDimitry Andric 18010b57cec5SDimitry Andric incrementProfileCounter(CondBOp); 18020b57cec5SDimitry Andric setCurrentProfileCount(getProfileCount(CondBOp->getRHS())); 18030b57cec5SDimitry Andric 18040b57cec5SDimitry Andric // Any temporaries created here are conditional. 18050b57cec5SDimitry Andric eval.begin(*this); 1806e8d8bef9SDimitry Andric EmitBranchToCounterBlock(CondBOp->getRHS(), BO_LOr, TrueBlock, FalseBlock, 1807e8d8bef9SDimitry Andric RHSCount, LH); 18080b57cec5SDimitry Andric 18090b57cec5SDimitry Andric eval.end(*this); 18100b57cec5SDimitry Andric 18110b57cec5SDimitry Andric return; 18120b57cec5SDimitry Andric } 18130b57cec5SDimitry Andric } 18140b57cec5SDimitry Andric 18150b57cec5SDimitry Andric if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) { 18160b57cec5SDimitry Andric // br(!x, t, f) -> br(x, f, t) 18170b57cec5SDimitry Andric if (CondUOp->getOpcode() == UO_LNot) { 18180b57cec5SDimitry Andric // Negate the count. 18190b57cec5SDimitry Andric uint64_t FalseCount = getCurrentProfileCount() - TrueCount; 1820e8d8bef9SDimitry Andric // The values of the enum are chosen to make this negation possible. 1821e8d8bef9SDimitry Andric LH = static_cast<Stmt::Likelihood>(-LH); 18220b57cec5SDimitry Andric // Negate the condition and swap the destination blocks. 18230b57cec5SDimitry Andric return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock, 1824e8d8bef9SDimitry Andric FalseCount, LH); 18250b57cec5SDimitry Andric } 18260b57cec5SDimitry Andric } 18270b57cec5SDimitry Andric 18280b57cec5SDimitry Andric if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) { 18290b57cec5SDimitry Andric // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f)) 18300b57cec5SDimitry Andric llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true"); 18310b57cec5SDimitry Andric llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false"); 18320b57cec5SDimitry Andric 1833e8d8bef9SDimitry Andric // The ConditionalOperator itself has no likelihood information for its 1834e8d8bef9SDimitry Andric // true and false branches. This matches the behavior of __builtin_expect. 18350b57cec5SDimitry Andric ConditionalEvaluation cond(*this); 18360b57cec5SDimitry Andric EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock, 1837e8d8bef9SDimitry Andric getProfileCount(CondOp), Stmt::LH_None); 18380b57cec5SDimitry Andric 18390b57cec5SDimitry Andric // When computing PGO branch weights, we only know the overall count for 18400b57cec5SDimitry Andric // the true block. This code is essentially doing tail duplication of the 18410b57cec5SDimitry Andric // naive code-gen, introducing new edges for which counts are not 18420b57cec5SDimitry Andric // available. Divide the counts proportionally between the LHS and RHS of 18430b57cec5SDimitry Andric // the conditional operator. 18440b57cec5SDimitry Andric uint64_t LHSScaledTrueCount = 0; 18450b57cec5SDimitry Andric if (TrueCount) { 18460b57cec5SDimitry Andric double LHSRatio = 18470b57cec5SDimitry Andric getProfileCount(CondOp) / (double)getCurrentProfileCount(); 18480b57cec5SDimitry Andric LHSScaledTrueCount = TrueCount * LHSRatio; 18490b57cec5SDimitry Andric } 18500b57cec5SDimitry Andric 18510b57cec5SDimitry Andric cond.begin(*this); 18520b57cec5SDimitry Andric EmitBlock(LHSBlock); 18530b57cec5SDimitry Andric incrementProfileCounter(CondOp); 18540b57cec5SDimitry Andric { 18550b57cec5SDimitry Andric ApplyDebugLocation DL(*this, Cond); 18560b57cec5SDimitry Andric EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock, 1857e8d8bef9SDimitry Andric LHSScaledTrueCount, LH); 18580b57cec5SDimitry Andric } 18590b57cec5SDimitry Andric cond.end(*this); 18600b57cec5SDimitry Andric 18610b57cec5SDimitry Andric cond.begin(*this); 18620b57cec5SDimitry Andric EmitBlock(RHSBlock); 18630b57cec5SDimitry Andric EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock, 1864e8d8bef9SDimitry Andric TrueCount - LHSScaledTrueCount, LH); 18650b57cec5SDimitry Andric cond.end(*this); 18660b57cec5SDimitry Andric 18670b57cec5SDimitry Andric return; 18680b57cec5SDimitry Andric } 18690b57cec5SDimitry Andric 18700b57cec5SDimitry Andric if (const CXXThrowExpr *Throw = dyn_cast<CXXThrowExpr>(Cond)) { 18710b57cec5SDimitry Andric // Conditional operator handling can give us a throw expression as a 18720b57cec5SDimitry Andric // condition for a case like: 18730b57cec5SDimitry Andric // br(c ? throw x : y, t, f) -> br(c, br(throw x, t, f), br(y, t, f) 18740b57cec5SDimitry Andric // Fold this to: 18750b57cec5SDimitry Andric // br(c, throw x, br(y, t, f)) 18760b57cec5SDimitry Andric EmitCXXThrowExpr(Throw, /*KeepInsertionPoint*/false); 18770b57cec5SDimitry Andric return; 18780b57cec5SDimitry Andric } 18790b57cec5SDimitry Andric 1880fe6060f1SDimitry Andric // Emit the code with the fully general case. 1881fe6060f1SDimitry Andric llvm::Value *CondV; 1882fe6060f1SDimitry Andric { 1883fe6060f1SDimitry Andric ApplyDebugLocation DL(*this, Cond); 1884fe6060f1SDimitry Andric CondV = EvaluateExprAsBool(Cond); 1885fe6060f1SDimitry Andric } 1886fe6060f1SDimitry Andric 1887fe6060f1SDimitry Andric llvm::MDNode *Weights = nullptr; 1888fe6060f1SDimitry Andric llvm::MDNode *Unpredictable = nullptr; 1889fe6060f1SDimitry Andric 18900b57cec5SDimitry Andric // If the branch has a condition wrapped by __builtin_unpredictable, 18910b57cec5SDimitry Andric // create metadata that specifies that the branch is unpredictable. 18920b57cec5SDimitry Andric // Don't bother if not optimizing because that metadata would not be used. 18930b57cec5SDimitry Andric auto *Call = dyn_cast<CallExpr>(Cond->IgnoreImpCasts()); 18940b57cec5SDimitry Andric if (Call && CGM.getCodeGenOpts().OptimizationLevel != 0) { 18950b57cec5SDimitry Andric auto *FD = dyn_cast_or_null<FunctionDecl>(Call->getCalleeDecl()); 18960b57cec5SDimitry Andric if (FD && FD->getBuiltinID() == Builtin::BI__builtin_unpredictable) { 18970b57cec5SDimitry Andric llvm::MDBuilder MDHelper(getLLVMContext()); 18980b57cec5SDimitry Andric Unpredictable = MDHelper.createUnpredictable(); 18990b57cec5SDimitry Andric } 19000b57cec5SDimitry Andric } 19010b57cec5SDimitry Andric 1902fe6060f1SDimitry Andric // If there is a Likelihood knowledge for the cond, lower it. 1903fe6060f1SDimitry Andric // Note that if not optimizing this won't emit anything. 1904fe6060f1SDimitry Andric llvm::Value *NewCondV = emitCondLikelihoodViaExpectIntrinsic(CondV, LH); 1905fe6060f1SDimitry Andric if (CondV != NewCondV) 1906fe6060f1SDimitry Andric CondV = NewCondV; 1907fe6060f1SDimitry Andric else { 1908fe6060f1SDimitry Andric // Otherwise, lower profile counts. Note that we do this even at -O0. 19090b57cec5SDimitry Andric uint64_t CurrentCount = std::max(getCurrentProfileCount(), TrueCount); 1910e8d8bef9SDimitry Andric Weights = createProfileWeights(TrueCount, CurrentCount - TrueCount); 1911e8d8bef9SDimitry Andric } 19120b57cec5SDimitry Andric 19130b57cec5SDimitry Andric Builder.CreateCondBr(CondV, TrueBlock, FalseBlock, Weights, Unpredictable); 19140b57cec5SDimitry Andric } 19150b57cec5SDimitry Andric 19160b57cec5SDimitry Andric /// ErrorUnsupported - Print out an error that codegen doesn't support the 19170b57cec5SDimitry Andric /// specified stmt yet. 19180b57cec5SDimitry Andric void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type) { 19190b57cec5SDimitry Andric CGM.ErrorUnsupported(S, Type); 19200b57cec5SDimitry Andric } 19210b57cec5SDimitry Andric 19220b57cec5SDimitry Andric /// emitNonZeroVLAInit - Emit the "zero" initialization of a 19230b57cec5SDimitry Andric /// variable-length array whose elements have a non-zero bit-pattern. 19240b57cec5SDimitry Andric /// 19250b57cec5SDimitry Andric /// \param baseType the inner-most element type of the array 19260b57cec5SDimitry Andric /// \param src - a char* pointing to the bit-pattern for a single 19270b57cec5SDimitry Andric /// base element of the array 19280b57cec5SDimitry Andric /// \param sizeInChars - the total size of the VLA, in chars 19290b57cec5SDimitry Andric static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType, 19300b57cec5SDimitry Andric Address dest, Address src, 19310b57cec5SDimitry Andric llvm::Value *sizeInChars) { 19320b57cec5SDimitry Andric CGBuilderTy &Builder = CGF.Builder; 19330b57cec5SDimitry Andric 19340b57cec5SDimitry Andric CharUnits baseSize = CGF.getContext().getTypeSizeInChars(baseType); 19350b57cec5SDimitry Andric llvm::Value *baseSizeInChars 19360b57cec5SDimitry Andric = llvm::ConstantInt::get(CGF.IntPtrTy, baseSize.getQuantity()); 19370b57cec5SDimitry Andric 1938*fe013be4SDimitry Andric Address begin = dest.withElementType(CGF.Int8Ty); 1939fe6060f1SDimitry Andric llvm::Value *end = Builder.CreateInBoundsGEP( 1940fe6060f1SDimitry Andric begin.getElementType(), begin.getPointer(), sizeInChars, "vla.end"); 19410b57cec5SDimitry Andric 19420b57cec5SDimitry Andric llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock(); 19430b57cec5SDimitry Andric llvm::BasicBlock *loopBB = CGF.createBasicBlock("vla-init.loop"); 19440b57cec5SDimitry Andric llvm::BasicBlock *contBB = CGF.createBasicBlock("vla-init.cont"); 19450b57cec5SDimitry Andric 19460b57cec5SDimitry Andric // Make a loop over the VLA. C99 guarantees that the VLA element 19470b57cec5SDimitry Andric // count must be nonzero. 19480b57cec5SDimitry Andric CGF.EmitBlock(loopBB); 19490b57cec5SDimitry Andric 19500b57cec5SDimitry Andric llvm::PHINode *cur = Builder.CreatePHI(begin.getType(), 2, "vla.cur"); 19510b57cec5SDimitry Andric cur->addIncoming(begin.getPointer(), originBB); 19520b57cec5SDimitry Andric 19530b57cec5SDimitry Andric CharUnits curAlign = 19540b57cec5SDimitry Andric dest.getAlignment().alignmentOfArrayElement(baseSize); 19550b57cec5SDimitry Andric 19560b57cec5SDimitry Andric // memcpy the individual element bit-pattern. 195781ad6265SDimitry Andric Builder.CreateMemCpy(Address(cur, CGF.Int8Ty, curAlign), src, baseSizeInChars, 19580b57cec5SDimitry Andric /*volatile*/ false); 19590b57cec5SDimitry Andric 19600b57cec5SDimitry Andric // Go to the next element. 19610b57cec5SDimitry Andric llvm::Value *next = 19620b57cec5SDimitry Andric Builder.CreateInBoundsGEP(CGF.Int8Ty, cur, baseSizeInChars, "vla.next"); 19630b57cec5SDimitry Andric 19640b57cec5SDimitry Andric // Leave if that's the end of the VLA. 19650b57cec5SDimitry Andric llvm::Value *done = Builder.CreateICmpEQ(next, end, "vla-init.isdone"); 19660b57cec5SDimitry Andric Builder.CreateCondBr(done, contBB, loopBB); 19670b57cec5SDimitry Andric cur->addIncoming(next, loopBB); 19680b57cec5SDimitry Andric 19690b57cec5SDimitry Andric CGF.EmitBlock(contBB); 19700b57cec5SDimitry Andric } 19710b57cec5SDimitry Andric 19720b57cec5SDimitry Andric void 19730b57cec5SDimitry Andric CodeGenFunction::EmitNullInitialization(Address DestPtr, QualType Ty) { 19740b57cec5SDimitry Andric // Ignore empty classes in C++. 19750b57cec5SDimitry Andric if (getLangOpts().CPlusPlus) { 19760b57cec5SDimitry Andric if (const RecordType *RT = Ty->getAs<RecordType>()) { 19770b57cec5SDimitry Andric if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty()) 19780b57cec5SDimitry Andric return; 19790b57cec5SDimitry Andric } 19800b57cec5SDimitry Andric } 19810b57cec5SDimitry Andric 19820b57cec5SDimitry Andric if (DestPtr.getElementType() != Int8Ty) 1983*fe013be4SDimitry Andric DestPtr = DestPtr.withElementType(Int8Ty); 19840b57cec5SDimitry Andric 19850b57cec5SDimitry Andric // Get size and alignment info for this aggregate. 19860b57cec5SDimitry Andric CharUnits size = getContext().getTypeSizeInChars(Ty); 19870b57cec5SDimitry Andric 19880b57cec5SDimitry Andric llvm::Value *SizeVal; 19890b57cec5SDimitry Andric const VariableArrayType *vla; 19900b57cec5SDimitry Andric 19910b57cec5SDimitry Andric // Don't bother emitting a zero-byte memset. 19920b57cec5SDimitry Andric if (size.isZero()) { 19930b57cec5SDimitry Andric // But note that getTypeInfo returns 0 for a VLA. 19940b57cec5SDimitry Andric if (const VariableArrayType *vlaType = 19950b57cec5SDimitry Andric dyn_cast_or_null<VariableArrayType>( 19960b57cec5SDimitry Andric getContext().getAsArrayType(Ty))) { 19970b57cec5SDimitry Andric auto VlaSize = getVLASize(vlaType); 19980b57cec5SDimitry Andric SizeVal = VlaSize.NumElts; 19990b57cec5SDimitry Andric CharUnits eltSize = getContext().getTypeSizeInChars(VlaSize.Type); 20000b57cec5SDimitry Andric if (!eltSize.isOne()) 20010b57cec5SDimitry Andric SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(eltSize)); 20020b57cec5SDimitry Andric vla = vlaType; 20030b57cec5SDimitry Andric } else { 20040b57cec5SDimitry Andric return; 20050b57cec5SDimitry Andric } 20060b57cec5SDimitry Andric } else { 20070b57cec5SDimitry Andric SizeVal = CGM.getSize(size); 20080b57cec5SDimitry Andric vla = nullptr; 20090b57cec5SDimitry Andric } 20100b57cec5SDimitry Andric 20110b57cec5SDimitry Andric // If the type contains a pointer to data member we can't memset it to zero. 20120b57cec5SDimitry Andric // Instead, create a null constant and copy it to the destination. 20130b57cec5SDimitry Andric // TODO: there are other patterns besides zero that we can usefully memset, 20140b57cec5SDimitry Andric // like -1, which happens to be the pattern used by member-pointers. 20150b57cec5SDimitry Andric if (!CGM.getTypes().isZeroInitializable(Ty)) { 20160b57cec5SDimitry Andric // For a VLA, emit a single element, then splat that over the VLA. 20170b57cec5SDimitry Andric if (vla) Ty = getContext().getBaseElementType(vla); 20180b57cec5SDimitry Andric 20190b57cec5SDimitry Andric llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty); 20200b57cec5SDimitry Andric 20210b57cec5SDimitry Andric llvm::GlobalVariable *NullVariable = 20220b57cec5SDimitry Andric new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(), 20230b57cec5SDimitry Andric /*isConstant=*/true, 20240b57cec5SDimitry Andric llvm::GlobalVariable::PrivateLinkage, 20250b57cec5SDimitry Andric NullConstant, Twine()); 20260b57cec5SDimitry Andric CharUnits NullAlign = DestPtr.getAlignment(); 2027a7dea167SDimitry Andric NullVariable->setAlignment(NullAlign.getAsAlign()); 20280b57cec5SDimitry Andric Address SrcPtr(Builder.CreateBitCast(NullVariable, Builder.getInt8PtrTy()), 202981ad6265SDimitry Andric Builder.getInt8Ty(), NullAlign); 20300b57cec5SDimitry Andric 20310b57cec5SDimitry Andric if (vla) return emitNonZeroVLAInit(*this, Ty, DestPtr, SrcPtr, SizeVal); 20320b57cec5SDimitry Andric 20330b57cec5SDimitry Andric // Get and call the appropriate llvm.memcpy overload. 20340b57cec5SDimitry Andric Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, false); 20350b57cec5SDimitry Andric return; 20360b57cec5SDimitry Andric } 20370b57cec5SDimitry Andric 20380b57cec5SDimitry Andric // Otherwise, just memset the whole thing to zero. This is legal 20390b57cec5SDimitry Andric // because in LLVM, all default initializers (other than the ones we just 20400b57cec5SDimitry Andric // handled above) are guaranteed to have a bit pattern of all zeros. 20410b57cec5SDimitry Andric Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal, false); 20420b57cec5SDimitry Andric } 20430b57cec5SDimitry Andric 20440b57cec5SDimitry Andric llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelDecl *L) { 20450b57cec5SDimitry Andric // Make sure that there is a block for the indirect goto. 20460b57cec5SDimitry Andric if (!IndirectBranch) 20470b57cec5SDimitry Andric GetIndirectGotoBlock(); 20480b57cec5SDimitry Andric 20490b57cec5SDimitry Andric llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock(); 20500b57cec5SDimitry Andric 20510b57cec5SDimitry Andric // Make sure the indirect branch includes all of the address-taken blocks. 20520b57cec5SDimitry Andric IndirectBranch->addDestination(BB); 20530b57cec5SDimitry Andric return llvm::BlockAddress::get(CurFn, BB); 20540b57cec5SDimitry Andric } 20550b57cec5SDimitry Andric 20560b57cec5SDimitry Andric llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() { 20570b57cec5SDimitry Andric // If we already made the indirect branch for indirect goto, return its block. 20580b57cec5SDimitry Andric if (IndirectBranch) return IndirectBranch->getParent(); 20590b57cec5SDimitry Andric 20600b57cec5SDimitry Andric CGBuilderTy TmpBuilder(*this, createBasicBlock("indirectgoto")); 20610b57cec5SDimitry Andric 20620b57cec5SDimitry Andric // Create the PHI node that indirect gotos will add entries to. 20630b57cec5SDimitry Andric llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, 0, 20640b57cec5SDimitry Andric "indirect.goto.dest"); 20650b57cec5SDimitry Andric 20660b57cec5SDimitry Andric // Create the indirect branch instruction. 20670b57cec5SDimitry Andric IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal); 20680b57cec5SDimitry Andric return IndirectBranch->getParent(); 20690b57cec5SDimitry Andric } 20700b57cec5SDimitry Andric 20710b57cec5SDimitry Andric /// Computes the length of an array in elements, as well as the base 20720b57cec5SDimitry Andric /// element type and a properly-typed first element pointer. 20730b57cec5SDimitry Andric llvm::Value *CodeGenFunction::emitArrayLength(const ArrayType *origArrayType, 20740b57cec5SDimitry Andric QualType &baseType, 20750b57cec5SDimitry Andric Address &addr) { 20760b57cec5SDimitry Andric const ArrayType *arrayType = origArrayType; 20770b57cec5SDimitry Andric 20780b57cec5SDimitry Andric // If it's a VLA, we have to load the stored size. Note that 20790b57cec5SDimitry Andric // this is the size of the VLA in bytes, not its size in elements. 20800b57cec5SDimitry Andric llvm::Value *numVLAElements = nullptr; 20810b57cec5SDimitry Andric if (isa<VariableArrayType>(arrayType)) { 20820b57cec5SDimitry Andric numVLAElements = getVLASize(cast<VariableArrayType>(arrayType)).NumElts; 20830b57cec5SDimitry Andric 20840b57cec5SDimitry Andric // Walk into all VLAs. This doesn't require changes to addr, 20850b57cec5SDimitry Andric // which has type T* where T is the first non-VLA element type. 20860b57cec5SDimitry Andric do { 20870b57cec5SDimitry Andric QualType elementType = arrayType->getElementType(); 20880b57cec5SDimitry Andric arrayType = getContext().getAsArrayType(elementType); 20890b57cec5SDimitry Andric 20900b57cec5SDimitry Andric // If we only have VLA components, 'addr' requires no adjustment. 20910b57cec5SDimitry Andric if (!arrayType) { 20920b57cec5SDimitry Andric baseType = elementType; 20930b57cec5SDimitry Andric return numVLAElements; 20940b57cec5SDimitry Andric } 20950b57cec5SDimitry Andric } while (isa<VariableArrayType>(arrayType)); 20960b57cec5SDimitry Andric 20970b57cec5SDimitry Andric // We get out here only if we find a constant array type 20980b57cec5SDimitry Andric // inside the VLA. 20990b57cec5SDimitry Andric } 21000b57cec5SDimitry Andric 21010b57cec5SDimitry Andric // We have some number of constant-length arrays, so addr should 21020b57cec5SDimitry Andric // have LLVM type [M x [N x [...]]]*. Build a GEP that walks 21030b57cec5SDimitry Andric // down to the first element of addr. 21040b57cec5SDimitry Andric SmallVector<llvm::Value*, 8> gepIndices; 21050b57cec5SDimitry Andric 21060b57cec5SDimitry Andric // GEP down to the array type. 21070b57cec5SDimitry Andric llvm::ConstantInt *zero = Builder.getInt32(0); 21080b57cec5SDimitry Andric gepIndices.push_back(zero); 21090b57cec5SDimitry Andric 21100b57cec5SDimitry Andric uint64_t countFromCLAs = 1; 21110b57cec5SDimitry Andric QualType eltType; 21120b57cec5SDimitry Andric 21130b57cec5SDimitry Andric llvm::ArrayType *llvmArrayType = 21140b57cec5SDimitry Andric dyn_cast<llvm::ArrayType>(addr.getElementType()); 21150b57cec5SDimitry Andric while (llvmArrayType) { 21160b57cec5SDimitry Andric assert(isa<ConstantArrayType>(arrayType)); 21170b57cec5SDimitry Andric assert(cast<ConstantArrayType>(arrayType)->getSize().getZExtValue() 21180b57cec5SDimitry Andric == llvmArrayType->getNumElements()); 21190b57cec5SDimitry Andric 21200b57cec5SDimitry Andric gepIndices.push_back(zero); 21210b57cec5SDimitry Andric countFromCLAs *= llvmArrayType->getNumElements(); 21220b57cec5SDimitry Andric eltType = arrayType->getElementType(); 21230b57cec5SDimitry Andric 21240b57cec5SDimitry Andric llvmArrayType = 21250b57cec5SDimitry Andric dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType()); 21260b57cec5SDimitry Andric arrayType = getContext().getAsArrayType(arrayType->getElementType()); 21270b57cec5SDimitry Andric assert((!llvmArrayType || arrayType) && 21280b57cec5SDimitry Andric "LLVM and Clang types are out-of-synch"); 21290b57cec5SDimitry Andric } 21300b57cec5SDimitry Andric 21310b57cec5SDimitry Andric if (arrayType) { 21320b57cec5SDimitry Andric // From this point onwards, the Clang array type has been emitted 21330b57cec5SDimitry Andric // as some other type (probably a packed struct). Compute the array 21340b57cec5SDimitry Andric // size, and just emit the 'begin' expression as a bitcast. 21350b57cec5SDimitry Andric while (arrayType) { 21360b57cec5SDimitry Andric countFromCLAs *= 21370b57cec5SDimitry Andric cast<ConstantArrayType>(arrayType)->getSize().getZExtValue(); 21380b57cec5SDimitry Andric eltType = arrayType->getElementType(); 21390b57cec5SDimitry Andric arrayType = getContext().getAsArrayType(eltType); 21400b57cec5SDimitry Andric } 21410b57cec5SDimitry Andric 21420b57cec5SDimitry Andric llvm::Type *baseType = ConvertType(eltType); 2143*fe013be4SDimitry Andric addr = addr.withElementType(baseType); 21440b57cec5SDimitry Andric } else { 21450b57cec5SDimitry Andric // Create the actual GEP. 2146fe6060f1SDimitry Andric addr = Address(Builder.CreateInBoundsGEP( 2147fe6060f1SDimitry Andric addr.getElementType(), addr.getPointer(), gepIndices, "array.begin"), 214804eeddc0SDimitry Andric ConvertTypeForMem(eltType), 21490b57cec5SDimitry Andric addr.getAlignment()); 21500b57cec5SDimitry Andric } 21510b57cec5SDimitry Andric 21520b57cec5SDimitry Andric baseType = eltType; 21530b57cec5SDimitry Andric 21540b57cec5SDimitry Andric llvm::Value *numElements 21550b57cec5SDimitry Andric = llvm::ConstantInt::get(SizeTy, countFromCLAs); 21560b57cec5SDimitry Andric 21570b57cec5SDimitry Andric // If we had any VLA dimensions, factor them in. 21580b57cec5SDimitry Andric if (numVLAElements) 21590b57cec5SDimitry Andric numElements = Builder.CreateNUWMul(numVLAElements, numElements); 21600b57cec5SDimitry Andric 21610b57cec5SDimitry Andric return numElements; 21620b57cec5SDimitry Andric } 21630b57cec5SDimitry Andric 21640b57cec5SDimitry Andric CodeGenFunction::VlaSizePair CodeGenFunction::getVLASize(QualType type) { 21650b57cec5SDimitry Andric const VariableArrayType *vla = getContext().getAsVariableArrayType(type); 21660b57cec5SDimitry Andric assert(vla && "type was not a variable array type!"); 21670b57cec5SDimitry Andric return getVLASize(vla); 21680b57cec5SDimitry Andric } 21690b57cec5SDimitry Andric 21700b57cec5SDimitry Andric CodeGenFunction::VlaSizePair 21710b57cec5SDimitry Andric CodeGenFunction::getVLASize(const VariableArrayType *type) { 21720b57cec5SDimitry Andric // The number of elements so far; always size_t. 21730b57cec5SDimitry Andric llvm::Value *numElements = nullptr; 21740b57cec5SDimitry Andric 21750b57cec5SDimitry Andric QualType elementType; 21760b57cec5SDimitry Andric do { 21770b57cec5SDimitry Andric elementType = type->getElementType(); 21780b57cec5SDimitry Andric llvm::Value *vlaSize = VLASizeMap[type->getSizeExpr()]; 21790b57cec5SDimitry Andric assert(vlaSize && "no size for VLA!"); 21800b57cec5SDimitry Andric assert(vlaSize->getType() == SizeTy); 21810b57cec5SDimitry Andric 21820b57cec5SDimitry Andric if (!numElements) { 21830b57cec5SDimitry Andric numElements = vlaSize; 21840b57cec5SDimitry Andric } else { 21850b57cec5SDimitry Andric // It's undefined behavior if this wraps around, so mark it that way. 21860b57cec5SDimitry Andric // FIXME: Teach -fsanitize=undefined to trap this. 21870b57cec5SDimitry Andric numElements = Builder.CreateNUWMul(numElements, vlaSize); 21880b57cec5SDimitry Andric } 21890b57cec5SDimitry Andric } while ((type = getContext().getAsVariableArrayType(elementType))); 21900b57cec5SDimitry Andric 21910b57cec5SDimitry Andric return { numElements, elementType }; 21920b57cec5SDimitry Andric } 21930b57cec5SDimitry Andric 21940b57cec5SDimitry Andric CodeGenFunction::VlaSizePair 21950b57cec5SDimitry Andric CodeGenFunction::getVLAElements1D(QualType type) { 21960b57cec5SDimitry Andric const VariableArrayType *vla = getContext().getAsVariableArrayType(type); 21970b57cec5SDimitry Andric assert(vla && "type was not a variable array type!"); 21980b57cec5SDimitry Andric return getVLAElements1D(vla); 21990b57cec5SDimitry Andric } 22000b57cec5SDimitry Andric 22010b57cec5SDimitry Andric CodeGenFunction::VlaSizePair 22020b57cec5SDimitry Andric CodeGenFunction::getVLAElements1D(const VariableArrayType *Vla) { 22030b57cec5SDimitry Andric llvm::Value *VlaSize = VLASizeMap[Vla->getSizeExpr()]; 22040b57cec5SDimitry Andric assert(VlaSize && "no size for VLA!"); 22050b57cec5SDimitry Andric assert(VlaSize->getType() == SizeTy); 22060b57cec5SDimitry Andric return { VlaSize, Vla->getElementType() }; 22070b57cec5SDimitry Andric } 22080b57cec5SDimitry Andric 22090b57cec5SDimitry Andric void CodeGenFunction::EmitVariablyModifiedType(QualType type) { 22100b57cec5SDimitry Andric assert(type->isVariablyModifiedType() && 22110b57cec5SDimitry Andric "Must pass variably modified type to EmitVLASizes!"); 22120b57cec5SDimitry Andric 22130b57cec5SDimitry Andric EnsureInsertPoint(); 22140b57cec5SDimitry Andric 22150b57cec5SDimitry Andric // We're going to walk down into the type and look for VLA 22160b57cec5SDimitry Andric // expressions. 22170b57cec5SDimitry Andric do { 22180b57cec5SDimitry Andric assert(type->isVariablyModifiedType()); 22190b57cec5SDimitry Andric 22200b57cec5SDimitry Andric const Type *ty = type.getTypePtr(); 22210b57cec5SDimitry Andric switch (ty->getTypeClass()) { 22220b57cec5SDimitry Andric 22230b57cec5SDimitry Andric #define TYPE(Class, Base) 22240b57cec5SDimitry Andric #define ABSTRACT_TYPE(Class, Base) 22250b57cec5SDimitry Andric #define NON_CANONICAL_TYPE(Class, Base) 22260b57cec5SDimitry Andric #define DEPENDENT_TYPE(Class, Base) case Type::Class: 22270b57cec5SDimitry Andric #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 2228a7dea167SDimitry Andric #include "clang/AST/TypeNodes.inc" 22290b57cec5SDimitry Andric llvm_unreachable("unexpected dependent type!"); 22300b57cec5SDimitry Andric 22310b57cec5SDimitry Andric // These types are never variably-modified. 22320b57cec5SDimitry Andric case Type::Builtin: 22330b57cec5SDimitry Andric case Type::Complex: 22340b57cec5SDimitry Andric case Type::Vector: 22350b57cec5SDimitry Andric case Type::ExtVector: 22365ffd83dbSDimitry Andric case Type::ConstantMatrix: 22370b57cec5SDimitry Andric case Type::Record: 22380b57cec5SDimitry Andric case Type::Enum: 22390eae32dcSDimitry Andric case Type::Using: 22400b57cec5SDimitry Andric case Type::TemplateSpecialization: 22410b57cec5SDimitry Andric case Type::ObjCTypeParam: 22420b57cec5SDimitry Andric case Type::ObjCObject: 22430b57cec5SDimitry Andric case Type::ObjCInterface: 22440b57cec5SDimitry Andric case Type::ObjCObjectPointer: 22450eae32dcSDimitry Andric case Type::BitInt: 22460b57cec5SDimitry Andric llvm_unreachable("type class is never variably-modified!"); 22470b57cec5SDimitry Andric 2248bdd1243dSDimitry Andric case Type::Elaborated: 2249bdd1243dSDimitry Andric type = cast<ElaboratedType>(ty)->getNamedType(); 2250bdd1243dSDimitry Andric break; 2251bdd1243dSDimitry Andric 22520b57cec5SDimitry Andric case Type::Adjusted: 22530b57cec5SDimitry Andric type = cast<AdjustedType>(ty)->getAdjustedType(); 22540b57cec5SDimitry Andric break; 22550b57cec5SDimitry Andric 22560b57cec5SDimitry Andric case Type::Decayed: 22570b57cec5SDimitry Andric type = cast<DecayedType>(ty)->getPointeeType(); 22580b57cec5SDimitry Andric break; 22590b57cec5SDimitry Andric 22600b57cec5SDimitry Andric case Type::Pointer: 22610b57cec5SDimitry Andric type = cast<PointerType>(ty)->getPointeeType(); 22620b57cec5SDimitry Andric break; 22630b57cec5SDimitry Andric 22640b57cec5SDimitry Andric case Type::BlockPointer: 22650b57cec5SDimitry Andric type = cast<BlockPointerType>(ty)->getPointeeType(); 22660b57cec5SDimitry Andric break; 22670b57cec5SDimitry Andric 22680b57cec5SDimitry Andric case Type::LValueReference: 22690b57cec5SDimitry Andric case Type::RValueReference: 22700b57cec5SDimitry Andric type = cast<ReferenceType>(ty)->getPointeeType(); 22710b57cec5SDimitry Andric break; 22720b57cec5SDimitry Andric 22730b57cec5SDimitry Andric case Type::MemberPointer: 22740b57cec5SDimitry Andric type = cast<MemberPointerType>(ty)->getPointeeType(); 22750b57cec5SDimitry Andric break; 22760b57cec5SDimitry Andric 22770b57cec5SDimitry Andric case Type::ConstantArray: 22780b57cec5SDimitry Andric case Type::IncompleteArray: 22790b57cec5SDimitry Andric // Losing element qualification here is fine. 22800b57cec5SDimitry Andric type = cast<ArrayType>(ty)->getElementType(); 22810b57cec5SDimitry Andric break; 22820b57cec5SDimitry Andric 22830b57cec5SDimitry Andric case Type::VariableArray: { 22840b57cec5SDimitry Andric // Losing element qualification here is fine. 22850b57cec5SDimitry Andric const VariableArrayType *vat = cast<VariableArrayType>(ty); 22860b57cec5SDimitry Andric 22870b57cec5SDimitry Andric // Unknown size indication requires no size computation. 22880b57cec5SDimitry Andric // Otherwise, evaluate and record it. 228904eeddc0SDimitry Andric if (const Expr *sizeExpr = vat->getSizeExpr()) { 22900b57cec5SDimitry Andric // It's possible that we might have emitted this already, 22910b57cec5SDimitry Andric // e.g. with a typedef and a pointer to it. 229204eeddc0SDimitry Andric llvm::Value *&entry = VLASizeMap[sizeExpr]; 22930b57cec5SDimitry Andric if (!entry) { 229404eeddc0SDimitry Andric llvm::Value *size = EmitScalarExpr(sizeExpr); 22950b57cec5SDimitry Andric 22960b57cec5SDimitry Andric // C11 6.7.6.2p5: 22970b57cec5SDimitry Andric // If the size is an expression that is not an integer constant 22980b57cec5SDimitry Andric // expression [...] each time it is evaluated it shall have a value 22990b57cec5SDimitry Andric // greater than zero. 230004eeddc0SDimitry Andric if (SanOpts.has(SanitizerKind::VLABound)) { 23010b57cec5SDimitry Andric SanitizerScope SanScope(this); 230204eeddc0SDimitry Andric llvm::Value *Zero = llvm::Constant::getNullValue(size->getType()); 230304eeddc0SDimitry Andric clang::QualType SEType = sizeExpr->getType(); 230404eeddc0SDimitry Andric llvm::Value *CheckCondition = 230504eeddc0SDimitry Andric SEType->isSignedIntegerType() 230604eeddc0SDimitry Andric ? Builder.CreateICmpSGT(size, Zero) 230704eeddc0SDimitry Andric : Builder.CreateICmpUGT(size, Zero); 23080b57cec5SDimitry Andric llvm::Constant *StaticArgs[] = { 230904eeddc0SDimitry Andric EmitCheckSourceLocation(sizeExpr->getBeginLoc()), 231004eeddc0SDimitry Andric EmitCheckTypeDescriptor(SEType)}; 231104eeddc0SDimitry Andric EmitCheck(std::make_pair(CheckCondition, SanitizerKind::VLABound), 231204eeddc0SDimitry Andric SanitizerHandler::VLABoundNotPositive, StaticArgs, size); 23130b57cec5SDimitry Andric } 23140b57cec5SDimitry Andric 23150b57cec5SDimitry Andric // Always zexting here would be wrong if it weren't 23160b57cec5SDimitry Andric // undefined behavior to have a negative bound. 231704eeddc0SDimitry Andric // FIXME: What about when size's type is larger than size_t? 231804eeddc0SDimitry Andric entry = Builder.CreateIntCast(size, SizeTy, /*signed*/ false); 23190b57cec5SDimitry Andric } 23200b57cec5SDimitry Andric } 23210b57cec5SDimitry Andric type = vat->getElementType(); 23220b57cec5SDimitry Andric break; 23230b57cec5SDimitry Andric } 23240b57cec5SDimitry Andric 23250b57cec5SDimitry Andric case Type::FunctionProto: 23260b57cec5SDimitry Andric case Type::FunctionNoProto: 23270b57cec5SDimitry Andric type = cast<FunctionType>(ty)->getReturnType(); 23280b57cec5SDimitry Andric break; 23290b57cec5SDimitry Andric 23300b57cec5SDimitry Andric case Type::Paren: 23310b57cec5SDimitry Andric case Type::TypeOf: 23320b57cec5SDimitry Andric case Type::UnaryTransform: 23330b57cec5SDimitry Andric case Type::Attributed: 233481ad6265SDimitry Andric case Type::BTFTagAttributed: 23350b57cec5SDimitry Andric case Type::SubstTemplateTypeParm: 23360b57cec5SDimitry Andric case Type::MacroQualified: 23370b57cec5SDimitry Andric // Keep walking after single level desugaring. 23380b57cec5SDimitry Andric type = type.getSingleStepDesugaredType(getContext()); 23390b57cec5SDimitry Andric break; 23400b57cec5SDimitry Andric 23410b57cec5SDimitry Andric case Type::Typedef: 23420b57cec5SDimitry Andric case Type::Decltype: 23430b57cec5SDimitry Andric case Type::Auto: 23440b57cec5SDimitry Andric case Type::DeducedTemplateSpecialization: 23450b57cec5SDimitry Andric // Stop walking: nothing to do. 23460b57cec5SDimitry Andric return; 23470b57cec5SDimitry Andric 23480b57cec5SDimitry Andric case Type::TypeOfExpr: 23490b57cec5SDimitry Andric // Stop walking: emit typeof expression. 23500b57cec5SDimitry Andric EmitIgnoredExpr(cast<TypeOfExprType>(ty)->getUnderlyingExpr()); 23510b57cec5SDimitry Andric return; 23520b57cec5SDimitry Andric 23530b57cec5SDimitry Andric case Type::Atomic: 23540b57cec5SDimitry Andric type = cast<AtomicType>(ty)->getValueType(); 23550b57cec5SDimitry Andric break; 23560b57cec5SDimitry Andric 23570b57cec5SDimitry Andric case Type::Pipe: 23580b57cec5SDimitry Andric type = cast<PipeType>(ty)->getElementType(); 23590b57cec5SDimitry Andric break; 23600b57cec5SDimitry Andric } 23610b57cec5SDimitry Andric } while (type->isVariablyModifiedType()); 23620b57cec5SDimitry Andric } 23630b57cec5SDimitry Andric 23640b57cec5SDimitry Andric Address CodeGenFunction::EmitVAListRef(const Expr* E) { 23650b57cec5SDimitry Andric if (getContext().getBuiltinVaListType()->isArrayType()) 23660b57cec5SDimitry Andric return EmitPointerWithAlignment(E); 2367480093f4SDimitry Andric return EmitLValue(E).getAddress(*this); 23680b57cec5SDimitry Andric } 23690b57cec5SDimitry Andric 23700b57cec5SDimitry Andric Address CodeGenFunction::EmitMSVAListRef(const Expr *E) { 2371480093f4SDimitry Andric return EmitLValue(E).getAddress(*this); 23720b57cec5SDimitry Andric } 23730b57cec5SDimitry Andric 23740b57cec5SDimitry Andric void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E, 23750b57cec5SDimitry Andric const APValue &Init) { 23760b57cec5SDimitry Andric assert(Init.hasValue() && "Invalid DeclRefExpr initializer!"); 23770b57cec5SDimitry Andric if (CGDebugInfo *Dbg = getDebugInfo()) 2378480093f4SDimitry Andric if (CGM.getCodeGenOpts().hasReducedDebugInfo()) 23790b57cec5SDimitry Andric Dbg->EmitGlobalVariable(E->getDecl(), Init); 23800b57cec5SDimitry Andric } 23810b57cec5SDimitry Andric 23820b57cec5SDimitry Andric CodeGenFunction::PeepholeProtection 23830b57cec5SDimitry Andric CodeGenFunction::protectFromPeepholes(RValue rvalue) { 23840b57cec5SDimitry Andric // At the moment, the only aggressive peephole we do in IR gen 23850b57cec5SDimitry Andric // is trunc(zext) folding, but if we add more, we can easily 23860b57cec5SDimitry Andric // extend this protection. 23870b57cec5SDimitry Andric 23880b57cec5SDimitry Andric if (!rvalue.isScalar()) return PeepholeProtection(); 23890b57cec5SDimitry Andric llvm::Value *value = rvalue.getScalarVal(); 23900b57cec5SDimitry Andric if (!isa<llvm::ZExtInst>(value)) return PeepholeProtection(); 23910b57cec5SDimitry Andric 23920b57cec5SDimitry Andric // Just make an extra bitcast. 23930b57cec5SDimitry Andric assert(HaveInsertPoint()); 23940b57cec5SDimitry Andric llvm::Instruction *inst = new llvm::BitCastInst(value, value->getType(), "", 23950b57cec5SDimitry Andric Builder.GetInsertBlock()); 23960b57cec5SDimitry Andric 23970b57cec5SDimitry Andric PeepholeProtection protection; 23980b57cec5SDimitry Andric protection.Inst = inst; 23990b57cec5SDimitry Andric return protection; 24000b57cec5SDimitry Andric } 24010b57cec5SDimitry Andric 24020b57cec5SDimitry Andric void CodeGenFunction::unprotectFromPeepholes(PeepholeProtection protection) { 24030b57cec5SDimitry Andric if (!protection.Inst) return; 24040b57cec5SDimitry Andric 24050b57cec5SDimitry Andric // In theory, we could try to duplicate the peepholes now, but whatever. 24060b57cec5SDimitry Andric protection.Inst->eraseFromParent(); 24070b57cec5SDimitry Andric } 24080b57cec5SDimitry Andric 24095ffd83dbSDimitry Andric void CodeGenFunction::emitAlignmentAssumption(llvm::Value *PtrValue, 24100b57cec5SDimitry Andric QualType Ty, SourceLocation Loc, 24110b57cec5SDimitry Andric SourceLocation AssumptionLoc, 24120b57cec5SDimitry Andric llvm::Value *Alignment, 24130b57cec5SDimitry Andric llvm::Value *OffsetValue) { 2414e8d8bef9SDimitry Andric if (Alignment->getType() != IntPtrTy) 2415e8d8bef9SDimitry Andric Alignment = 2416e8d8bef9SDimitry Andric Builder.CreateIntCast(Alignment, IntPtrTy, false, "casted.align"); 2417e8d8bef9SDimitry Andric if (OffsetValue && OffsetValue->getType() != IntPtrTy) 2418e8d8bef9SDimitry Andric OffsetValue = 2419e8d8bef9SDimitry Andric Builder.CreateIntCast(OffsetValue, IntPtrTy, true, "casted.offset"); 2420e8d8bef9SDimitry Andric llvm::Value *TheCheck = nullptr; 2421590d96feSDimitry Andric if (SanOpts.has(SanitizerKind::Alignment)) { 2422e8d8bef9SDimitry Andric llvm::Value *PtrIntValue = 2423e8d8bef9SDimitry Andric Builder.CreatePtrToInt(PtrValue, IntPtrTy, "ptrint"); 2424e8d8bef9SDimitry Andric 2425e8d8bef9SDimitry Andric if (OffsetValue) { 2426e8d8bef9SDimitry Andric bool IsOffsetZero = false; 2427e8d8bef9SDimitry Andric if (const auto *CI = dyn_cast<llvm::ConstantInt>(OffsetValue)) 2428e8d8bef9SDimitry Andric IsOffsetZero = CI->isZero(); 2429e8d8bef9SDimitry Andric 2430e8d8bef9SDimitry Andric if (!IsOffsetZero) 2431e8d8bef9SDimitry Andric PtrIntValue = Builder.CreateSub(PtrIntValue, OffsetValue, "offsetptr"); 2432e8d8bef9SDimitry Andric } 2433e8d8bef9SDimitry Andric 2434e8d8bef9SDimitry Andric llvm::Value *Zero = llvm::ConstantInt::get(IntPtrTy, 0); 2435e8d8bef9SDimitry Andric llvm::Value *Mask = 2436e8d8bef9SDimitry Andric Builder.CreateSub(Alignment, llvm::ConstantInt::get(IntPtrTy, 1)); 2437e8d8bef9SDimitry Andric llvm::Value *MaskedPtr = Builder.CreateAnd(PtrIntValue, Mask, "maskedptr"); 2438e8d8bef9SDimitry Andric TheCheck = Builder.CreateICmpEQ(MaskedPtr, Zero, "maskcond"); 2439e8d8bef9SDimitry Andric } 2440e8d8bef9SDimitry Andric llvm::Instruction *Assumption = Builder.CreateAlignmentAssumption( 2441e8d8bef9SDimitry Andric CGM.getDataLayout(), PtrValue, Alignment, OffsetValue); 2442e8d8bef9SDimitry Andric 2443e8d8bef9SDimitry Andric if (!SanOpts.has(SanitizerKind::Alignment)) 2444e8d8bef9SDimitry Andric return; 24455ffd83dbSDimitry Andric emitAlignmentAssumptionCheck(PtrValue, Ty, Loc, AssumptionLoc, Alignment, 24465ffd83dbSDimitry Andric OffsetValue, TheCheck, Assumption); 24475ffd83dbSDimitry Andric } 24485ffd83dbSDimitry Andric 24495ffd83dbSDimitry Andric void CodeGenFunction::emitAlignmentAssumption(llvm::Value *PtrValue, 24500b57cec5SDimitry Andric const Expr *E, 24510b57cec5SDimitry Andric SourceLocation AssumptionLoc, 2452a7dea167SDimitry Andric llvm::Value *Alignment, 24530b57cec5SDimitry Andric llvm::Value *OffsetValue) { 24540b57cec5SDimitry Andric QualType Ty = E->getType(); 24550b57cec5SDimitry Andric SourceLocation Loc = E->getExprLoc(); 24560b57cec5SDimitry Andric 24575ffd83dbSDimitry Andric emitAlignmentAssumption(PtrValue, Ty, Loc, AssumptionLoc, Alignment, 24580b57cec5SDimitry Andric OffsetValue); 24590b57cec5SDimitry Andric } 24600b57cec5SDimitry Andric 24610b57cec5SDimitry Andric llvm::Value *CodeGenFunction::EmitAnnotationCall(llvm::Function *AnnotationFn, 24620b57cec5SDimitry Andric llvm::Value *AnnotatedVal, 24630b57cec5SDimitry Andric StringRef AnnotationStr, 2464e8d8bef9SDimitry Andric SourceLocation Location, 2465e8d8bef9SDimitry Andric const AnnotateAttr *Attr) { 2466e8d8bef9SDimitry Andric SmallVector<llvm::Value *, 5> Args = { 24670b57cec5SDimitry Andric AnnotatedVal, 2468bdd1243dSDimitry Andric Builder.CreateBitCast(CGM.EmitAnnotationString(AnnotationStr), 2469bdd1243dSDimitry Andric ConstGlobalsPtrTy), 2470bdd1243dSDimitry Andric Builder.CreateBitCast(CGM.EmitAnnotationUnit(Location), 2471bdd1243dSDimitry Andric ConstGlobalsPtrTy), 2472e8d8bef9SDimitry Andric CGM.EmitAnnotationLineNo(Location), 24730b57cec5SDimitry Andric }; 2474e8d8bef9SDimitry Andric if (Attr) 2475e8d8bef9SDimitry Andric Args.push_back(CGM.EmitAnnotationArgs(Attr)); 24760b57cec5SDimitry Andric return Builder.CreateCall(AnnotationFn, Args); 24770b57cec5SDimitry Andric } 24780b57cec5SDimitry Andric 24790b57cec5SDimitry Andric void CodeGenFunction::EmitVarAnnotations(const VarDecl *D, llvm::Value *V) { 24800b57cec5SDimitry Andric assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute"); 24810b57cec5SDimitry Andric // FIXME We create a new bitcast for every annotation because that's what 24820b57cec5SDimitry Andric // llvm-gcc was doing. 2483bdd1243dSDimitry Andric unsigned AS = V->getType()->getPointerAddressSpace(); 2484bdd1243dSDimitry Andric llvm::Type *I8PtrTy = Builder.getInt8PtrTy(AS); 24850b57cec5SDimitry Andric for (const auto *I : D->specific_attrs<AnnotateAttr>()) 2486bdd1243dSDimitry Andric EmitAnnotationCall(CGM.getIntrinsic(llvm::Intrinsic::var_annotation, 2487bdd1243dSDimitry Andric {I8PtrTy, CGM.ConstGlobalsPtrTy}), 2488bdd1243dSDimitry Andric Builder.CreateBitCast(V, I8PtrTy, V->getName()), 2489e8d8bef9SDimitry Andric I->getAnnotation(), D->getLocation(), I); 24900b57cec5SDimitry Andric } 24910b57cec5SDimitry Andric 24920b57cec5SDimitry Andric Address CodeGenFunction::EmitFieldAnnotations(const FieldDecl *D, 24930b57cec5SDimitry Andric Address Addr) { 24940b57cec5SDimitry Andric assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute"); 24950b57cec5SDimitry Andric llvm::Value *V = Addr.getPointer(); 24960b57cec5SDimitry Andric llvm::Type *VTy = V->getType(); 2497349cc55cSDimitry Andric auto *PTy = dyn_cast<llvm::PointerType>(VTy); 2498349cc55cSDimitry Andric unsigned AS = PTy ? PTy->getAddressSpace() : 0; 2499349cc55cSDimitry Andric llvm::PointerType *IntrinTy = 2500*fe013be4SDimitry Andric llvm::PointerType::get(CGM.getLLVMContext(), AS); 2501bdd1243dSDimitry Andric llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::ptr_annotation, 2502bdd1243dSDimitry Andric {IntrinTy, CGM.ConstGlobalsPtrTy}); 25030b57cec5SDimitry Andric 25040b57cec5SDimitry Andric for (const auto *I : D->specific_attrs<AnnotateAttr>()) { 25050b57cec5SDimitry Andric // FIXME Always emit the cast inst so we can differentiate between 25060b57cec5SDimitry Andric // annotation on the first field of a struct and annotation on the struct 25070b57cec5SDimitry Andric // itself. 2508349cc55cSDimitry Andric if (VTy != IntrinTy) 2509349cc55cSDimitry Andric V = Builder.CreateBitCast(V, IntrinTy); 2510e8d8bef9SDimitry Andric V = EmitAnnotationCall(F, V, I->getAnnotation(), D->getLocation(), I); 25110b57cec5SDimitry Andric V = Builder.CreateBitCast(V, VTy); 25120b57cec5SDimitry Andric } 25130b57cec5SDimitry Andric 251481ad6265SDimitry Andric return Address(V, Addr.getElementType(), Addr.getAlignment()); 25150b57cec5SDimitry Andric } 25160b57cec5SDimitry Andric 25170b57cec5SDimitry Andric CodeGenFunction::CGCapturedStmtInfo::~CGCapturedStmtInfo() { } 25180b57cec5SDimitry Andric 25190b57cec5SDimitry Andric CodeGenFunction::SanitizerScope::SanitizerScope(CodeGenFunction *CGF) 25200b57cec5SDimitry Andric : CGF(CGF) { 25210b57cec5SDimitry Andric assert(!CGF->IsSanitizerScope); 25220b57cec5SDimitry Andric CGF->IsSanitizerScope = true; 25230b57cec5SDimitry Andric } 25240b57cec5SDimitry Andric 25250b57cec5SDimitry Andric CodeGenFunction::SanitizerScope::~SanitizerScope() { 25260b57cec5SDimitry Andric CGF->IsSanitizerScope = false; 25270b57cec5SDimitry Andric } 25280b57cec5SDimitry Andric 25290b57cec5SDimitry Andric void CodeGenFunction::InsertHelper(llvm::Instruction *I, 25300b57cec5SDimitry Andric const llvm::Twine &Name, 25310b57cec5SDimitry Andric llvm::BasicBlock *BB, 25320b57cec5SDimitry Andric llvm::BasicBlock::iterator InsertPt) const { 25330b57cec5SDimitry Andric LoopStack.InsertHelper(I); 25340b57cec5SDimitry Andric if (IsSanitizerScope) 2535*fe013be4SDimitry Andric I->setNoSanitizeMetadata(); 25360b57cec5SDimitry Andric } 25370b57cec5SDimitry Andric 25380b57cec5SDimitry Andric void CGBuilderInserter::InsertHelper( 25390b57cec5SDimitry Andric llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock *BB, 25400b57cec5SDimitry Andric llvm::BasicBlock::iterator InsertPt) const { 25410b57cec5SDimitry Andric llvm::IRBuilderDefaultInserter::InsertHelper(I, Name, BB, InsertPt); 25420b57cec5SDimitry Andric if (CGF) 25430b57cec5SDimitry Andric CGF->InsertHelper(I, Name, BB, InsertPt); 25440b57cec5SDimitry Andric } 25450b57cec5SDimitry Andric 25460b57cec5SDimitry Andric // Emits an error if we don't have a valid set of target features for the 25470b57cec5SDimitry Andric // called function. 25480b57cec5SDimitry Andric void CodeGenFunction::checkTargetFeatures(const CallExpr *E, 25490b57cec5SDimitry Andric const FunctionDecl *TargetDecl) { 25500b57cec5SDimitry Andric return checkTargetFeatures(E->getBeginLoc(), TargetDecl); 25510b57cec5SDimitry Andric } 25520b57cec5SDimitry Andric 25530b57cec5SDimitry Andric // Emits an error if we don't have a valid set of target features for the 25540b57cec5SDimitry Andric // called function. 25550b57cec5SDimitry Andric void CodeGenFunction::checkTargetFeatures(SourceLocation Loc, 25560b57cec5SDimitry Andric const FunctionDecl *TargetDecl) { 25570b57cec5SDimitry Andric // Early exit if this is an indirect call. 25580b57cec5SDimitry Andric if (!TargetDecl) 25590b57cec5SDimitry Andric return; 25600b57cec5SDimitry Andric 25610b57cec5SDimitry Andric // Get the current enclosing function if it exists. If it doesn't 25620b57cec5SDimitry Andric // we can't check the target features anyhow. 2563a7dea167SDimitry Andric const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl); 25640b57cec5SDimitry Andric if (!FD) 25650b57cec5SDimitry Andric return; 25660b57cec5SDimitry Andric 25670b57cec5SDimitry Andric // Grab the required features for the call. For a builtin this is listed in 25680b57cec5SDimitry Andric // the td file with the default cpu, for an always_inline function this is any 25690b57cec5SDimitry Andric // listed cpu and any listed features. 25700b57cec5SDimitry Andric unsigned BuiltinID = TargetDecl->getBuiltinID(); 25710b57cec5SDimitry Andric std::string MissingFeature; 2572e8d8bef9SDimitry Andric llvm::StringMap<bool> CallerFeatureMap; 2573e8d8bef9SDimitry Andric CGM.getContext().getFunctionFeatureMap(CallerFeatureMap, FD); 25740b57cec5SDimitry Andric if (BuiltinID) { 257581ad6265SDimitry Andric StringRef FeatureList(CGM.getContext().BuiltinInfo.getRequiredFeatures(BuiltinID)); 257681ad6265SDimitry Andric if (!Builtin::evaluateRequiredTargetFeatures( 257781ad6265SDimitry Andric FeatureList, CallerFeatureMap)) { 25780b57cec5SDimitry Andric CGM.getDiags().Report(Loc, diag::err_builtin_needs_feature) 257981ad6265SDimitry Andric << TargetDecl->getDeclName() 258081ad6265SDimitry Andric << FeatureList; 258181ad6265SDimitry Andric } 2582480093f4SDimitry Andric } else if (!TargetDecl->isMultiVersion() && 2583480093f4SDimitry Andric TargetDecl->hasAttr<TargetAttr>()) { 25840b57cec5SDimitry Andric // Get the required features for the callee. 25850b57cec5SDimitry Andric 25860b57cec5SDimitry Andric const TargetAttr *TD = TargetDecl->getAttr<TargetAttr>(); 2587480093f4SDimitry Andric ParsedTargetAttr ParsedAttr = 2588480093f4SDimitry Andric CGM.getContext().filterFunctionTargetAttrs(TD); 25890b57cec5SDimitry Andric 25900b57cec5SDimitry Andric SmallVector<StringRef, 1> ReqFeatures; 25910b57cec5SDimitry Andric llvm::StringMap<bool> CalleeFeatureMap; 2592c3ca3130SDimitry Andric CGM.getContext().getFunctionFeatureMap(CalleeFeatureMap, TargetDecl); 25930b57cec5SDimitry Andric 25940b57cec5SDimitry Andric for (const auto &F : ParsedAttr.Features) { 25950b57cec5SDimitry Andric if (F[0] == '+' && CalleeFeatureMap.lookup(F.substr(1))) 25960b57cec5SDimitry Andric ReqFeatures.push_back(StringRef(F).substr(1)); 25970b57cec5SDimitry Andric } 25980b57cec5SDimitry Andric 25990b57cec5SDimitry Andric for (const auto &F : CalleeFeatureMap) { 26000b57cec5SDimitry Andric // Only positive features are "required". 26010b57cec5SDimitry Andric if (F.getValue()) 26020b57cec5SDimitry Andric ReqFeatures.push_back(F.getKey()); 26030b57cec5SDimitry Andric } 2604e8d8bef9SDimitry Andric if (!llvm::all_of(ReqFeatures, [&](StringRef Feature) { 2605e8d8bef9SDimitry Andric if (!CallerFeatureMap.lookup(Feature)) { 2606e8d8bef9SDimitry Andric MissingFeature = Feature.str(); 2607e8d8bef9SDimitry Andric return false; 2608e8d8bef9SDimitry Andric } 2609e8d8bef9SDimitry Andric return true; 2610e8d8bef9SDimitry Andric })) 26110b57cec5SDimitry Andric CGM.getDiags().Report(Loc, diag::err_function_needs_feature) 26120b57cec5SDimitry Andric << FD->getDeclName() << TargetDecl->getDeclName() << MissingFeature; 2613*fe013be4SDimitry Andric } else if (!FD->isMultiVersion() && FD->hasAttr<TargetAttr>()) { 2614*fe013be4SDimitry Andric llvm::StringMap<bool> CalleeFeatureMap; 2615*fe013be4SDimitry Andric CGM.getContext().getFunctionFeatureMap(CalleeFeatureMap, TargetDecl); 2616*fe013be4SDimitry Andric 2617*fe013be4SDimitry Andric for (const auto &F : CalleeFeatureMap) { 2618*fe013be4SDimitry Andric if (F.getValue() && (!CallerFeatureMap.lookup(F.getKey()) || 2619*fe013be4SDimitry Andric !CallerFeatureMap.find(F.getKey())->getValue())) 2620*fe013be4SDimitry Andric CGM.getDiags().Report(Loc, diag::err_function_needs_feature) 2621*fe013be4SDimitry Andric << FD->getDeclName() << TargetDecl->getDeclName() << F.getKey(); 2622*fe013be4SDimitry Andric } 26230b57cec5SDimitry Andric } 26240b57cec5SDimitry Andric } 26250b57cec5SDimitry Andric 26260b57cec5SDimitry Andric void CodeGenFunction::EmitSanitizerStatReport(llvm::SanitizerStatKind SSK) { 26270b57cec5SDimitry Andric if (!CGM.getCodeGenOpts().SanitizeStats) 26280b57cec5SDimitry Andric return; 26290b57cec5SDimitry Andric 26300b57cec5SDimitry Andric llvm::IRBuilder<> IRB(Builder.GetInsertBlock(), Builder.GetInsertPoint()); 26310b57cec5SDimitry Andric IRB.SetCurrentDebugLocation(Builder.getCurrentDebugLocation()); 26320b57cec5SDimitry Andric CGM.getSanStats().create(IRB, SSK); 26330b57cec5SDimitry Andric } 26340b57cec5SDimitry Andric 2635bdd1243dSDimitry Andric void CodeGenFunction::EmitKCFIOperandBundle( 2636bdd1243dSDimitry Andric const CGCallee &Callee, SmallVectorImpl<llvm::OperandBundleDef> &Bundles) { 2637bdd1243dSDimitry Andric const FunctionProtoType *FP = 2638bdd1243dSDimitry Andric Callee.getAbstractInfo().getCalleeFunctionProtoType(); 2639bdd1243dSDimitry Andric if (FP) 2640bdd1243dSDimitry Andric Bundles.emplace_back("kcfi", CGM.CreateKCFITypeId(FP->desugar())); 2641bdd1243dSDimitry Andric } 2642bdd1243dSDimitry Andric 2643bdd1243dSDimitry Andric llvm::Value *CodeGenFunction::FormAArch64ResolverCondition( 2644bdd1243dSDimitry Andric const MultiVersionResolverOption &RO) { 2645bdd1243dSDimitry Andric llvm::SmallVector<StringRef, 8> CondFeatures; 2646bdd1243dSDimitry Andric for (const StringRef &Feature : RO.Conditions.Features) { 2647bdd1243dSDimitry Andric // Form condition for features which are not yet enabled in target 2648bdd1243dSDimitry Andric if (!getContext().getTargetInfo().hasFeature(Feature)) 2649bdd1243dSDimitry Andric CondFeatures.push_back(Feature); 2650bdd1243dSDimitry Andric } 2651bdd1243dSDimitry Andric if (!CondFeatures.empty()) { 2652bdd1243dSDimitry Andric return EmitAArch64CpuSupports(CondFeatures); 2653bdd1243dSDimitry Andric } 2654bdd1243dSDimitry Andric return nullptr; 2655bdd1243dSDimitry Andric } 2656bdd1243dSDimitry Andric 2657bdd1243dSDimitry Andric llvm::Value *CodeGenFunction::FormX86ResolverCondition( 2658bdd1243dSDimitry Andric const MultiVersionResolverOption &RO) { 26590b57cec5SDimitry Andric llvm::Value *Condition = nullptr; 26600b57cec5SDimitry Andric 26610b57cec5SDimitry Andric if (!RO.Conditions.Architecture.empty()) 26620b57cec5SDimitry Andric Condition = EmitX86CpuIs(RO.Conditions.Architecture); 26630b57cec5SDimitry Andric 26640b57cec5SDimitry Andric if (!RO.Conditions.Features.empty()) { 26650b57cec5SDimitry Andric llvm::Value *FeatureCond = EmitX86CpuSupports(RO.Conditions.Features); 26660b57cec5SDimitry Andric Condition = 26670b57cec5SDimitry Andric Condition ? Builder.CreateAnd(Condition, FeatureCond) : FeatureCond; 26680b57cec5SDimitry Andric } 26690b57cec5SDimitry Andric return Condition; 26700b57cec5SDimitry Andric } 26710b57cec5SDimitry Andric 26720b57cec5SDimitry Andric static void CreateMultiVersionResolverReturn(CodeGenModule &CGM, 26730b57cec5SDimitry Andric llvm::Function *Resolver, 26740b57cec5SDimitry Andric CGBuilderTy &Builder, 26750b57cec5SDimitry Andric llvm::Function *FuncToReturn, 26760b57cec5SDimitry Andric bool SupportsIFunc) { 26770b57cec5SDimitry Andric if (SupportsIFunc) { 26780b57cec5SDimitry Andric Builder.CreateRet(FuncToReturn); 26790b57cec5SDimitry Andric return; 26800b57cec5SDimitry Andric } 26810b57cec5SDimitry Andric 268281ad6265SDimitry Andric llvm::SmallVector<llvm::Value *, 10> Args( 268381ad6265SDimitry Andric llvm::make_pointer_range(Resolver->args())); 26840b57cec5SDimitry Andric 26850b57cec5SDimitry Andric llvm::CallInst *Result = Builder.CreateCall(FuncToReturn, Args); 26860b57cec5SDimitry Andric Result->setTailCallKind(llvm::CallInst::TCK_MustTail); 26870b57cec5SDimitry Andric 26880b57cec5SDimitry Andric if (Resolver->getReturnType()->isVoidTy()) 26890b57cec5SDimitry Andric Builder.CreateRetVoid(); 26900b57cec5SDimitry Andric else 26910b57cec5SDimitry Andric Builder.CreateRet(Result); 26920b57cec5SDimitry Andric } 26930b57cec5SDimitry Andric 26940b57cec5SDimitry Andric void CodeGenFunction::EmitMultiVersionResolver( 26950b57cec5SDimitry Andric llvm::Function *Resolver, ArrayRef<MultiVersionResolverOption> Options) { 2696bdd1243dSDimitry Andric 2697bdd1243dSDimitry Andric llvm::Triple::ArchType ArchType = 2698bdd1243dSDimitry Andric getContext().getTargetInfo().getTriple().getArch(); 2699bdd1243dSDimitry Andric 2700bdd1243dSDimitry Andric switch (ArchType) { 2701bdd1243dSDimitry Andric case llvm::Triple::x86: 2702bdd1243dSDimitry Andric case llvm::Triple::x86_64: 2703bdd1243dSDimitry Andric EmitX86MultiVersionResolver(Resolver, Options); 2704bdd1243dSDimitry Andric return; 2705bdd1243dSDimitry Andric case llvm::Triple::aarch64: 2706bdd1243dSDimitry Andric EmitAArch64MultiVersionResolver(Resolver, Options); 2707bdd1243dSDimitry Andric return; 2708bdd1243dSDimitry Andric 2709bdd1243dSDimitry Andric default: 2710bdd1243dSDimitry Andric assert(false && "Only implemented for x86 and AArch64 targets"); 2711bdd1243dSDimitry Andric } 2712bdd1243dSDimitry Andric } 2713bdd1243dSDimitry Andric 2714bdd1243dSDimitry Andric void CodeGenFunction::EmitAArch64MultiVersionResolver( 2715bdd1243dSDimitry Andric llvm::Function *Resolver, ArrayRef<MultiVersionResolverOption> Options) { 2716bdd1243dSDimitry Andric assert(!Options.empty() && "No multiversion resolver options found"); 2717bdd1243dSDimitry Andric assert(Options.back().Conditions.Features.size() == 0 && 2718bdd1243dSDimitry Andric "Default case must be last"); 2719bdd1243dSDimitry Andric bool SupportsIFunc = getContext().getTargetInfo().supportsIFunc(); 2720bdd1243dSDimitry Andric assert(SupportsIFunc && 2721bdd1243dSDimitry Andric "Multiversion resolver requires target IFUNC support"); 2722bdd1243dSDimitry Andric bool AArch64CpuInitialized = false; 2723bdd1243dSDimitry Andric llvm::BasicBlock *CurBlock = createBasicBlock("resolver_entry", Resolver); 2724bdd1243dSDimitry Andric 2725bdd1243dSDimitry Andric for (const MultiVersionResolverOption &RO : Options) { 2726bdd1243dSDimitry Andric Builder.SetInsertPoint(CurBlock); 2727bdd1243dSDimitry Andric llvm::Value *Condition = FormAArch64ResolverCondition(RO); 2728bdd1243dSDimitry Andric 2729bdd1243dSDimitry Andric // The 'default' or 'all features enabled' case. 2730bdd1243dSDimitry Andric if (!Condition) { 2731bdd1243dSDimitry Andric CreateMultiVersionResolverReturn(CGM, Resolver, Builder, RO.Function, 2732bdd1243dSDimitry Andric SupportsIFunc); 2733bdd1243dSDimitry Andric return; 2734bdd1243dSDimitry Andric } 2735bdd1243dSDimitry Andric 2736bdd1243dSDimitry Andric if (!AArch64CpuInitialized) { 2737bdd1243dSDimitry Andric Builder.SetInsertPoint(CurBlock, CurBlock->begin()); 2738bdd1243dSDimitry Andric EmitAArch64CpuInit(); 2739bdd1243dSDimitry Andric AArch64CpuInitialized = true; 2740bdd1243dSDimitry Andric Builder.SetInsertPoint(CurBlock); 2741bdd1243dSDimitry Andric } 2742bdd1243dSDimitry Andric 2743bdd1243dSDimitry Andric llvm::BasicBlock *RetBlock = createBasicBlock("resolver_return", Resolver); 2744bdd1243dSDimitry Andric CGBuilderTy RetBuilder(*this, RetBlock); 2745bdd1243dSDimitry Andric CreateMultiVersionResolverReturn(CGM, Resolver, RetBuilder, RO.Function, 2746bdd1243dSDimitry Andric SupportsIFunc); 2747bdd1243dSDimitry Andric CurBlock = createBasicBlock("resolver_else", Resolver); 2748bdd1243dSDimitry Andric Builder.CreateCondBr(Condition, RetBlock, CurBlock); 2749bdd1243dSDimitry Andric } 2750bdd1243dSDimitry Andric 2751bdd1243dSDimitry Andric // If no default, emit an unreachable. 2752bdd1243dSDimitry Andric Builder.SetInsertPoint(CurBlock); 2753bdd1243dSDimitry Andric llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap); 2754bdd1243dSDimitry Andric TrapCall->setDoesNotReturn(); 2755bdd1243dSDimitry Andric TrapCall->setDoesNotThrow(); 2756bdd1243dSDimitry Andric Builder.CreateUnreachable(); 2757bdd1243dSDimitry Andric Builder.ClearInsertionPoint(); 2758bdd1243dSDimitry Andric } 2759bdd1243dSDimitry Andric 2760bdd1243dSDimitry Andric void CodeGenFunction::EmitX86MultiVersionResolver( 2761bdd1243dSDimitry Andric llvm::Function *Resolver, ArrayRef<MultiVersionResolverOption> Options) { 27620b57cec5SDimitry Andric 27630b57cec5SDimitry Andric bool SupportsIFunc = getContext().getTargetInfo().supportsIFunc(); 27640b57cec5SDimitry Andric 27650b57cec5SDimitry Andric // Main function's basic block. 27660b57cec5SDimitry Andric llvm::BasicBlock *CurBlock = createBasicBlock("resolver_entry", Resolver); 27670b57cec5SDimitry Andric Builder.SetInsertPoint(CurBlock); 27680b57cec5SDimitry Andric EmitX86CpuInit(); 27690b57cec5SDimitry Andric 27700b57cec5SDimitry Andric for (const MultiVersionResolverOption &RO : Options) { 27710b57cec5SDimitry Andric Builder.SetInsertPoint(CurBlock); 2772bdd1243dSDimitry Andric llvm::Value *Condition = FormX86ResolverCondition(RO); 27730b57cec5SDimitry Andric 27740b57cec5SDimitry Andric // The 'default' or 'generic' case. 27750b57cec5SDimitry Andric if (!Condition) { 27760b57cec5SDimitry Andric assert(&RO == Options.end() - 1 && 27770b57cec5SDimitry Andric "Default or Generic case must be last"); 27780b57cec5SDimitry Andric CreateMultiVersionResolverReturn(CGM, Resolver, Builder, RO.Function, 27790b57cec5SDimitry Andric SupportsIFunc); 27800b57cec5SDimitry Andric return; 27810b57cec5SDimitry Andric } 27820b57cec5SDimitry Andric 27830b57cec5SDimitry Andric llvm::BasicBlock *RetBlock = createBasicBlock("resolver_return", Resolver); 27840b57cec5SDimitry Andric CGBuilderTy RetBuilder(*this, RetBlock); 27850b57cec5SDimitry Andric CreateMultiVersionResolverReturn(CGM, Resolver, RetBuilder, RO.Function, 27860b57cec5SDimitry Andric SupportsIFunc); 27870b57cec5SDimitry Andric CurBlock = createBasicBlock("resolver_else", Resolver); 27880b57cec5SDimitry Andric Builder.CreateCondBr(Condition, RetBlock, CurBlock); 27890b57cec5SDimitry Andric } 27900b57cec5SDimitry Andric 27910b57cec5SDimitry Andric // If no generic/default, emit an unreachable. 27920b57cec5SDimitry Andric Builder.SetInsertPoint(CurBlock); 27930b57cec5SDimitry Andric llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap); 27940b57cec5SDimitry Andric TrapCall->setDoesNotReturn(); 27950b57cec5SDimitry Andric TrapCall->setDoesNotThrow(); 27960b57cec5SDimitry Andric Builder.CreateUnreachable(); 27970b57cec5SDimitry Andric Builder.ClearInsertionPoint(); 27980b57cec5SDimitry Andric } 27990b57cec5SDimitry Andric 28000b57cec5SDimitry Andric // Loc - where the diagnostic will point, where in the source code this 28010b57cec5SDimitry Andric // alignment has failed. 28020b57cec5SDimitry Andric // SecondaryLoc - if present (will be present if sufficiently different from 28030b57cec5SDimitry Andric // Loc), the diagnostic will additionally point a "Note:" to this location. 28040b57cec5SDimitry Andric // It should be the location where the __attribute__((assume_aligned)) 28050b57cec5SDimitry Andric // was written e.g. 28065ffd83dbSDimitry Andric void CodeGenFunction::emitAlignmentAssumptionCheck( 28070b57cec5SDimitry Andric llvm::Value *Ptr, QualType Ty, SourceLocation Loc, 28080b57cec5SDimitry Andric SourceLocation SecondaryLoc, llvm::Value *Alignment, 28090b57cec5SDimitry Andric llvm::Value *OffsetValue, llvm::Value *TheCheck, 28100b57cec5SDimitry Andric llvm::Instruction *Assumption) { 28110b57cec5SDimitry Andric assert(Assumption && isa<llvm::CallInst>(Assumption) && 28125ffd83dbSDimitry Andric cast<llvm::CallInst>(Assumption)->getCalledOperand() == 28130b57cec5SDimitry Andric llvm::Intrinsic::getDeclaration( 28140b57cec5SDimitry Andric Builder.GetInsertBlock()->getParent()->getParent(), 28150b57cec5SDimitry Andric llvm::Intrinsic::assume) && 28160b57cec5SDimitry Andric "Assumption should be a call to llvm.assume()."); 28170b57cec5SDimitry Andric assert(&(Builder.GetInsertBlock()->back()) == Assumption && 28180b57cec5SDimitry Andric "Assumption should be the last instruction of the basic block, " 28190b57cec5SDimitry Andric "since the basic block is still being generated."); 28200b57cec5SDimitry Andric 28210b57cec5SDimitry Andric if (!SanOpts.has(SanitizerKind::Alignment)) 28220b57cec5SDimitry Andric return; 28230b57cec5SDimitry Andric 28240b57cec5SDimitry Andric // Don't check pointers to volatile data. The behavior here is implementation- 28250b57cec5SDimitry Andric // defined. 28260b57cec5SDimitry Andric if (Ty->getPointeeType().isVolatileQualified()) 28270b57cec5SDimitry Andric return; 28280b57cec5SDimitry Andric 28290b57cec5SDimitry Andric // We need to temorairly remove the assumption so we can insert the 28300b57cec5SDimitry Andric // sanitizer check before it, else the check will be dropped by optimizations. 28310b57cec5SDimitry Andric Assumption->removeFromParent(); 28320b57cec5SDimitry Andric 28330b57cec5SDimitry Andric { 28340b57cec5SDimitry Andric SanitizerScope SanScope(this); 28350b57cec5SDimitry Andric 28360b57cec5SDimitry Andric if (!OffsetValue) 283704eeddc0SDimitry Andric OffsetValue = Builder.getInt1(false); // no offset. 28380b57cec5SDimitry Andric 28390b57cec5SDimitry Andric llvm::Constant *StaticData[] = {EmitCheckSourceLocation(Loc), 28400b57cec5SDimitry Andric EmitCheckSourceLocation(SecondaryLoc), 28410b57cec5SDimitry Andric EmitCheckTypeDescriptor(Ty)}; 28420b57cec5SDimitry Andric llvm::Value *DynamicData[] = {EmitCheckValue(Ptr), 28430b57cec5SDimitry Andric EmitCheckValue(Alignment), 28440b57cec5SDimitry Andric EmitCheckValue(OffsetValue)}; 28450b57cec5SDimitry Andric EmitCheck({std::make_pair(TheCheck, SanitizerKind::Alignment)}, 28460b57cec5SDimitry Andric SanitizerHandler::AlignmentAssumption, StaticData, DynamicData); 28470b57cec5SDimitry Andric } 28480b57cec5SDimitry Andric 28490b57cec5SDimitry Andric // We are now in the (new, empty) "cont" basic block. 28500b57cec5SDimitry Andric // Reintroduce the assumption. 28510b57cec5SDimitry Andric Builder.Insert(Assumption); 28520b57cec5SDimitry Andric // FIXME: Assumption still has it's original basic block as it's Parent. 28530b57cec5SDimitry Andric } 28540b57cec5SDimitry Andric 28550b57cec5SDimitry Andric llvm::DebugLoc CodeGenFunction::SourceLocToDebugLoc(SourceLocation Location) { 28560b57cec5SDimitry Andric if (CGDebugInfo *DI = getDebugInfo()) 28570b57cec5SDimitry Andric return DI->SourceLocToDebugLoc(Location); 28580b57cec5SDimitry Andric 28590b57cec5SDimitry Andric return llvm::DebugLoc(); 28600b57cec5SDimitry Andric } 2861e8d8bef9SDimitry Andric 2862fe6060f1SDimitry Andric llvm::Value * 2863fe6060f1SDimitry Andric CodeGenFunction::emitCondLikelihoodViaExpectIntrinsic(llvm::Value *Cond, 2864fe6060f1SDimitry Andric Stmt::Likelihood LH) { 2865e8d8bef9SDimitry Andric switch (LH) { 2866e8d8bef9SDimitry Andric case Stmt::LH_None: 2867fe6060f1SDimitry Andric return Cond; 2868e8d8bef9SDimitry Andric case Stmt::LH_Likely: 2869fe6060f1SDimitry Andric case Stmt::LH_Unlikely: 2870fe6060f1SDimitry Andric // Don't generate llvm.expect on -O0 as the backend won't use it for 2871fe6060f1SDimitry Andric // anything. 2872fe6060f1SDimitry Andric if (CGM.getCodeGenOpts().OptimizationLevel == 0) 2873fe6060f1SDimitry Andric return Cond; 2874fe6060f1SDimitry Andric llvm::Type *CondTy = Cond->getType(); 2875fe6060f1SDimitry Andric assert(CondTy->isIntegerTy(1) && "expecting condition to be a boolean"); 2876fe6060f1SDimitry Andric llvm::Function *FnExpect = 2877fe6060f1SDimitry Andric CGM.getIntrinsic(llvm::Intrinsic::expect, CondTy); 2878fe6060f1SDimitry Andric llvm::Value *ExpectedValueOfCond = 2879fe6060f1SDimitry Andric llvm::ConstantInt::getBool(CondTy, LH == Stmt::LH_Likely); 2880fe6060f1SDimitry Andric return Builder.CreateCall(FnExpect, {Cond, ExpectedValueOfCond}, 2881fe6060f1SDimitry Andric Cond->getName() + ".expval"); 2882e8d8bef9SDimitry Andric } 2883e8d8bef9SDimitry Andric llvm_unreachable("Unknown Likelihood"); 2884e8d8bef9SDimitry Andric } 288581ad6265SDimitry Andric 288681ad6265SDimitry Andric llvm::Value *CodeGenFunction::emitBoolVecConversion(llvm::Value *SrcVec, 288781ad6265SDimitry Andric unsigned NumElementsDst, 288881ad6265SDimitry Andric const llvm::Twine &Name) { 288981ad6265SDimitry Andric auto *SrcTy = cast<llvm::FixedVectorType>(SrcVec->getType()); 289081ad6265SDimitry Andric unsigned NumElementsSrc = SrcTy->getNumElements(); 289181ad6265SDimitry Andric if (NumElementsSrc == NumElementsDst) 289281ad6265SDimitry Andric return SrcVec; 289381ad6265SDimitry Andric 289481ad6265SDimitry Andric std::vector<int> ShuffleMask(NumElementsDst, -1); 289581ad6265SDimitry Andric for (unsigned MaskIdx = 0; 289681ad6265SDimitry Andric MaskIdx < std::min<>(NumElementsDst, NumElementsSrc); ++MaskIdx) 289781ad6265SDimitry Andric ShuffleMask[MaskIdx] = MaskIdx; 289881ad6265SDimitry Andric 289981ad6265SDimitry Andric return Builder.CreateShuffleVector(SrcVec, ShuffleMask, Name); 290081ad6265SDimitry Andric } 2901