38#include "llvm/ADT/ArrayRef.h"
39#include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
40#include "llvm/IR/DataLayout.h"
41#include "llvm/IR/Dominators.h"
42#include "llvm/IR/FPEnv.h"
43#include "llvm/IR/IntrinsicInst.h"
44#include "llvm/IR/Intrinsics.h"
45#include "llvm/IR/MDBuilder.h"
46#include "llvm/Support/CRC.h"
47#include "llvm/Support/xxhash.h"
48#include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
49#include "llvm/Transforms/Utils/PromoteMemToReg.h"
53using namespace CodeGen;
63 if (CGOpts.DisableLifetimeMarkers)
67 if (CGOpts.SanitizeAddressUseAfterScope ||
73 return CGOpts.OptimizationLevel != 0;
76CodeGenFunction::CodeGenFunction(
CodeGenModule &cgm,
bool suppressNewContext)
78 Builder(cgm, cgm.getModule().getContext(),
llvm::ConstantFolder(),
80 SanOpts(CGM.getLangOpts().Sanitize), CurFPFeatures(CGM.getLangOpts()),
81 DebugInfo(CGM.getModuleDebugInfo()), PGO(cgm),
82 ShouldEmitLifetimeMarkers(
84 if (!suppressNewContext)
85 CGM.getCXXABI().getMangleContext().startNewFunction();
88 SetFastMathFlags(CurFPFeatures);
91CodeGenFunction::~CodeGenFunction() {
94 "missed to deactivate a cleanup");
110llvm::fp::ExceptionBehavior
118 llvm_unreachable(
"Unsupported FP Exception Behavior");
123 llvm::FastMathFlags FMF;
124 FMF.setAllowReassoc(FPFeatures.getAllowFPReassociate());
125 FMF.setNoNaNs(FPFeatures.getNoHonorNaNs());
126 FMF.setNoInfs(FPFeatures.getNoHonorInfs());
127 FMF.setNoSignedZeros(FPFeatures.getNoSignedZero());
128 FMF.setAllowReciprocal(FPFeatures.getAllowReciprocal());
129 FMF.setApproxFunc(FPFeatures.getAllowApproxFunc());
143 ConstructorHelper(FPFeatures);
146void CodeGenFunction::CGFPOptionsRAII::ConstructorHelper(
FPOptions FPFeatures) {
147 OldFPFeatures = CGF.CurFPFeatures;
148 CGF.CurFPFeatures = FPFeatures;
150 OldExcept = CGF.Builder.getDefaultConstrainedExcept();
151 OldRounding = CGF.Builder.getDefaultConstrainedRounding();
153 if (OldFPFeatures == FPFeatures)
156 FMFGuard.emplace(CGF.Builder);
159 CGF.Builder.setDefaultConstrainedRounding(NewRoundingBehavior);
160 auto NewExceptionBehavior =
163 CGF.Builder.setDefaultConstrainedExcept(NewExceptionBehavior);
165 CGF.SetFastMathFlags(FPFeatures);
167 assert((CGF.CurFuncDecl ==
nullptr || CGF.Builder.getIsFPConstrained() ||
168 isa<CXXConstructorDecl>(CGF.CurFuncDecl) ||
169 isa<CXXDestructorDecl>(CGF.CurFuncDecl) ||
170 (NewExceptionBehavior == llvm::fp::ebIgnore &&
171 NewRoundingBehavior == llvm::RoundingMode::NearestTiesToEven)) &&
172 "FPConstrained should be enabled on entire function");
174 auto mergeFnAttrValue = [&](StringRef Name,
bool Value) {
176 CGF.CurFn->getFnAttribute(Name).getValueAsBool();
177 auto NewValue = OldValue &
Value;
178 if (OldValue != NewValue)
179 CGF.CurFn->addFnAttr(Name, llvm::toStringRef(NewValue));
181 mergeFnAttrValue(
"no-infs-fp-math", FPFeatures.getNoHonorInfs());
182 mergeFnAttrValue(
"no-nans-fp-math", FPFeatures.getNoHonorNaNs());
183 mergeFnAttrValue(
"no-signed-zeros-fp-math", FPFeatures.getNoSignedZero());
186 FPFeatures.getAllowFPReassociate() && FPFeatures.getAllowReciprocal() &&
187 FPFeatures.getAllowApproxFunc() && FPFeatures.getNoSignedZero() &&
192 CGF.CurFPFeatures = OldFPFeatures;
193 CGF.Builder.setDefaultConstrainedExcept(OldExcept);
194 CGF.Builder.setDefaultConstrainedRounding(OldRounding);
208 nullptr, IsKnownNonNull)
216 return ::makeNaturalAlignAddrLValue(
V,
T,
false,
223 return ::makeNaturalAlignAddrLValue(
V,
T,
true,
229 return ::makeNaturalAlignAddrLValue(
V,
T,
false,
235 return ::makeNaturalAlignAddrLValue(
V,
T,
true,
248 llvm::Type *LLVMTy) {
255 switch (
type->getTypeClass()) {
256#define TYPE(name, parent)
257#define ABSTRACT_TYPE(name, parent)
258#define NON_CANONICAL_TYPE(name, parent) case Type::name:
259#define DEPENDENT_TYPE(name, parent) case Type::name:
260#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(name, parent) case Type::name:
261#include "clang/AST/TypeNodes.inc"
262 llvm_unreachable(
"non-canonical or dependent type in IR-generation");
265 case Type::DeducedTemplateSpecialization:
266 llvm_unreachable(
"undeduced type in IR-generation");
271 case Type::BlockPointer:
272 case Type::LValueReference:
273 case Type::RValueReference:
274 case Type::MemberPointer:
276 case Type::ExtVector:
277 case Type::ConstantMatrix:
278 case Type::FunctionProto:
279 case Type::FunctionNoProto:
281 case Type::ObjCObjectPointer:
284 case Type::HLSLAttributedResource:
292 case Type::ConstantArray:
293 case Type::IncompleteArray:
294 case Type::VariableArray:
296 case Type::ObjCObject:
297 case Type::ObjCInterface:
298 case Type::ArrayParameter:
303 type = cast<AtomicType>(
type)->getValueType();
306 llvm_unreachable(
"unknown type kind!");
313 llvm::BasicBlock *CurBB =
Builder.GetInsertBlock();
316 assert(!CurBB->getTerminator() &&
"Unexpected terminated block.");
326 return llvm::DebugLoc();
333 llvm::BranchInst *BI =
335 if (BI && BI->isUnconditional() &&
339 llvm::DebugLoc
Loc = BI->getDebugLoc();
340 Builder.SetInsertPoint(BI->getParent());
341 BI->eraseFromParent();
353 return llvm::DebugLoc();
358 if (!BB->use_empty()) {
366 assert(BreakContinueStack.empty() &&
367 "mismatched push/pop in break/continue stack!");
369 "mismatched push/pop of cleanups in EHStack!");
371 "mismatched activate/deactivate of cleanups!");
376 "mismatched push/pop in convergence stack!");
379 bool OnlySimpleReturnStmts = NumSimpleReturnExprs > 0
380 && NumSimpleReturnExprs == NumReturnExprs
395 if (OnlySimpleReturnStmts)
396 DI->EmitLocation(
Builder, LastStopPoint);
398 DI->EmitLocation(
Builder, EndLoc);
406 bool HasOnlyLifetimeMarkers =
408 bool EmitRetDbgLoc = !HasCleanups || HasOnlyLifetimeMarkers;
410 std::optional<ApplyDebugLocation> OAL;
415 if (OnlySimpleReturnStmts)
416 DI->EmitLocation(
Builder, EndLoc);
431 CurFn->addFnAttr(
"instrument-function-exit",
"__cyg_profile_func_exit");
433 CurFn->addFnAttr(
"instrument-function-exit-inlined",
434 "__cyg_profile_func_exit");
448 "did not remove all scopes from cleanup stack!");
452 if (IndirectBranch) {
459 if (!EscapedLocals.empty()) {
463 EscapeArgs.resize(EscapedLocals.size());
464 for (
auto &Pair : EscapedLocals)
465 EscapeArgs[Pair.second] = Pair.first;
466 llvm::Function *FrameEscapeFn = llvm::Intrinsic::getOrInsertDeclaration(
474 Ptr->eraseFromParent();
478 if (PostAllocaInsertPt) {
479 llvm::Instruction *PostPtr = PostAllocaInsertPt;
480 PostAllocaInsertPt =
nullptr;
481 PostPtr->eraseFromParent();
486 if (IndirectBranch) {
487 llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
488 if (PN->getNumIncomingValues() == 0) {
489 PN->replaceAllUsesWith(llvm::PoisonValue::get(PN->getType()));
490 PN->eraseFromParent();
499 for (
const auto &FuncletAndParent : TerminateFunclets)
505 for (
const auto &R : DeferredReplacements) {
506 if (llvm::Value *Old = R.first) {
507 Old->replaceAllUsesWith(R.second);
508 cast<llvm::Instruction>(Old)->eraseFromParent();
511 DeferredReplacements.clear();
520 llvm::DominatorTree DT(*
CurFn);
521 llvm::PromoteMemToReg(
527 for (llvm::Argument &A :
CurFn->args())
528 if (
auto *VT = dyn_cast<llvm::VectorType>(A.getType()))
530 std::max((uint64_t)LargestVectorWidth,
531 VT->getPrimitiveSizeInBits().getKnownMinValue());
534 if (
auto *VT = dyn_cast<llvm::VectorType>(
CurFn->getReturnType()))
536 std::max((uint64_t)LargestVectorWidth,
537 VT->getPrimitiveSizeInBits().getKnownMinValue());
549 if (
getContext().getTargetInfo().getTriple().isX86())
550 CurFn->addFnAttr(
"min-legal-vector-width",
551 llvm::utostr(LargestVectorWidth));
554 std::optional<std::pair<unsigned, unsigned>> VScaleRange =
557 CurFn->addFnAttr(llvm::Attribute::getWithVScaleRangeArgs(
569 if (RetAlloca && RetAlloca->use_empty()) {
570 RetAlloca->eraseFromParent();
623 llvm::raw_string_ostream Out(Mangled);
625 return llvm::ConstantInt::get(
629void CodeGenFunction::EmitKernelMetadata(
const FunctionDecl *FD,
630 llvm::Function *Fn) {
631 if (!FD->
hasAttr<OpenCLKernelAttr>() && !FD->
hasAttr<CUDAGlobalAttr>())
640 getContext().getTargetInfo().getTriple().isSPIRV())))
643 if (
const VecTypeHintAttr *A = FD->
getAttr<VecTypeHintAttr>()) {
644 QualType HintQTy = A->getTypeHint();
646 bool IsSignedInteger =
649 llvm::Metadata *AttrMDArgs[] = {
650 llvm::ConstantAsMetadata::get(llvm::UndefValue::get(
652 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
653 llvm::IntegerType::get(Context, 32),
654 llvm::APInt(32, (uint64_t)(IsSignedInteger ? 1 : 0))))};
655 Fn->setMetadata(
"vec_type_hint", llvm::MDNode::get(Context, AttrMDArgs));
658 if (
const WorkGroupSizeHintAttr *A = FD->
getAttr<WorkGroupSizeHintAttr>()) {
659 llvm::Metadata *AttrMDArgs[] = {
660 llvm::ConstantAsMetadata::get(
Builder.getInt32(A->getXDim())),
661 llvm::ConstantAsMetadata::get(
Builder.getInt32(A->getYDim())),
662 llvm::ConstantAsMetadata::get(
Builder.getInt32(A->getZDim()))};
663 Fn->setMetadata(
"work_group_size_hint", llvm::MDNode::get(Context, AttrMDArgs));
666 if (
const ReqdWorkGroupSizeAttr *A = FD->
getAttr<ReqdWorkGroupSizeAttr>()) {
667 llvm::Metadata *AttrMDArgs[] = {
668 llvm::ConstantAsMetadata::get(
Builder.getInt32(A->getXDim())),
669 llvm::ConstantAsMetadata::get(
Builder.getInt32(A->getYDim())),
670 llvm::ConstantAsMetadata::get(
Builder.getInt32(A->getZDim()))};
671 Fn->setMetadata(
"reqd_work_group_size", llvm::MDNode::get(Context, AttrMDArgs));
674 if (
const OpenCLIntelReqdSubGroupSizeAttr *A =
675 FD->
getAttr<OpenCLIntelReqdSubGroupSizeAttr>()) {
676 llvm::Metadata *AttrMDArgs[] = {
677 llvm::ConstantAsMetadata::get(
Builder.getInt32(A->getSubGroupSize()))};
678 Fn->setMetadata(
"intel_reqd_sub_group_size",
679 llvm::MDNode::get(Context, AttrMDArgs));
685 const Stmt *Body =
nullptr;
686 if (
auto *FD = dyn_cast_or_null<FunctionDecl>(F))
688 else if (
auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(F))
689 Body = OMD->getBody();
691 if (
auto *CS = dyn_cast_or_null<CompoundStmt>(Body)) {
692 auto LastStmt = CS->body_rbegin();
693 if (LastStmt != CS->body_rend())
694 return isa<ReturnStmt>(*LastStmt);
701 Fn->addFnAttr(
"sanitize_thread_no_checking_at_run_time");
702 Fn->removeFnAttr(llvm::Attribute::SanitizeThread);
707bool CodeGenFunction::requiresReturnValueCheck()
const {
708 return requiresReturnValueNullabilityCheck() ||
714 auto *MD = dyn_cast_or_null<CXXMethodDecl>(
D);
715 if (!MD || !MD->getDeclName().getAsIdentifierInfo() ||
716 !MD->getDeclName().getAsIdentifierInfo()->isStr(
"allocate") ||
717 (MD->getNumParams() != 1 && MD->getNumParams() != 2))
720 if (MD->parameters()[0]->getType().getCanonicalType() != Ctx.
getSizeType())
723 if (MD->getNumParams() == 2) {
724 auto *PT = MD->parameters()[1]->getType()->getAs<
PointerType>();
725 if (!PT || !PT->isVoidPointerType() ||
726 !PT->getPointeeType().isConstQualified())
738bool CodeGenFunction::hasInAllocaArg(
const CXXMethodDecl *MD) {
742 return isInAllocaArgument(CGM.getCXXABI(), P->getType());
749 if (
const auto *MD = dyn_cast<CXXMethodDecl>(FD))
762 "Do not use a CodeGenFunction object for more than one function");
766 DidCallStackSave =
false;
775 assert(
CurFn->isDeclaration() &&
"Function already has body?");
780#define SANITIZER(NAME, ID) \
781 if (SanOpts.empty()) \
783 if (SanOpts.has(SanitizerKind::ID)) \
784 if (CGM.isInNoSanitizeList(SanitizerKind::ID, Fn, Loc)) \
785 SanOpts.set(SanitizerKind::ID, false);
787#include "clang/Basic/Sanitizers.def"
794 bool NoSanitizeCoverage =
false;
797 no_sanitize_mask |=
Attr->getMask();
799 if (
Attr->hasCoverage())
800 NoSanitizeCoverage =
true;
805 if (no_sanitize_mask & SanitizerKind::Address)
806 SanOpts.
set(SanitizerKind::KernelAddress,
false);
807 if (no_sanitize_mask & SanitizerKind::KernelAddress)
809 if (no_sanitize_mask & SanitizerKind::HWAddress)
810 SanOpts.
set(SanitizerKind::KernelHWAddress,
false);
811 if (no_sanitize_mask & SanitizerKind::KernelHWAddress)
815 Fn->addFnAttr(llvm::Attribute::NoSanitizeBounds);
818 Fn->addFnAttr(llvm::Attribute::NoSanitizeCoverage);
822 if (no_sanitize_mask & SanitizerKind::Thread)
823 Fn->addFnAttr(
"no_sanitize_thread");
828 CurFn->addFnAttr(llvm::Attribute::DisableSanitizerInstrumentation);
831 if (
SanOpts.
hasOneOf(SanitizerKind::Address | SanitizerKind::KernelAddress))
832 Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
834 SanitizerKind::KernelHWAddress))
835 Fn->addFnAttr(llvm::Attribute::SanitizeHWAddress);
837 Fn->addFnAttr(llvm::Attribute::SanitizeMemTag);
839 Fn->addFnAttr(llvm::Attribute::SanitizeThread);
841 Fn->addFnAttr(llvm::Attribute::SanitizeType);
842 if (
SanOpts.
has(SanitizerKind::NumericalStability))
843 Fn->addFnAttr(llvm::Attribute::SanitizeNumericalStability);
844 if (
SanOpts.
hasOneOf(SanitizerKind::Memory | SanitizerKind::KernelMemory))
845 Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
848 Fn->addFnAttr(llvm::Attribute::SafeStack);
849 if (
SanOpts.
has(SanitizerKind::ShadowCallStack))
850 Fn->addFnAttr(llvm::Attribute::ShadowCallStack);
856 Fn->addFnAttr(llvm::Attribute::SanitizeRealtime);
858 Fn->addFnAttr(llvm::Attribute::SanitizeRealtimeBlocking);
862 if (
SanOpts.
hasOneOf(SanitizerKind::Fuzzer | SanitizerKind::FuzzerNoLink))
863 Fn->addFnAttr(llvm::Attribute::OptForFuzzing);
868 if (
const auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(
D)) {
869 const IdentifierInfo *II = OMD->getSelector().getIdentifierInfoForSlot(0);
872 (OMD->getSelector().isUnarySelector() && II->
isStr(
".cxx_destruct"))) {
881 if (
D &&
SanOpts.
has(SanitizerKind::CFIUnrelatedCast)) {
897 Fn->addFnAttr(
"ptrauth-returns");
899 Fn->addFnAttr(
"ptrauth-calls");
901 Fn->addFnAttr(
"ptrauth-auth-traps");
903 Fn->addFnAttr(
"ptrauth-indirect-gotos");
905 Fn->addFnAttr(
"aarch64-jump-table-hardening");
908 bool AlwaysXRayAttr =
false;
909 if (
const auto *XRayAttr =
D ?
D->
getAttr<XRayInstrumentAttr>() :
nullptr) {
915 Fn->addFnAttr(
"function-instrument",
"xray-always");
916 AlwaysXRayAttr =
true;
918 if (XRayAttr->neverXRayInstrument())
919 Fn->addFnAttr(
"function-instrument",
"xray-never");
920 if (
const auto *LogArgs =
D->
getAttr<XRayLogArgsAttr>())
922 Fn->addFnAttr(
"xray-log-args",
923 llvm::utostr(LogArgs->getArgumentCount()));
928 "xray-instruction-threshold",
934 Fn->addFnAttr(
"xray-ignore-loops");
938 Fn->addFnAttr(
"xray-skip-exit");
942 Fn->addFnAttr(
"xray-skip-entry");
945 if (FuncGroups > 1) {
947 CurFn->getName().bytes_end());
948 auto Group = crc32(FuncName) % FuncGroups;
951 Fn->addFnAttr(
"function-instrument",
"xray-never");
958 Fn->addFnAttr(llvm::Attribute::SkipProfile);
961 Fn->addFnAttr(llvm::Attribute::NoProfile);
968 unsigned Count, Offset;
969 if (
const auto *
Attr =
970 D ?
D->
getAttr<PatchableFunctionEntryAttr>() :
nullptr) {
971 Count =
Attr->getCount();
972 Offset =
Attr->getOffset();
977 if (Count && Offset <= Count) {
978 Fn->addFnAttr(
"patchable-function-entry", std::to_string(Count - Offset));
980 Fn->addFnAttr(
"patchable-function-prefix", std::to_string(Offset));
987 getContext().getTargetInfo().getTriple().isX86() &&
988 getContext().getTargetInfo().getTriple().getEnvironment() !=
989 llvm::Triple::CODE16)
990 Fn->addFnAttr(
"patchable-function",
"prologue-short-redirect");
994 Fn->addFnAttr(
"no-jump-tables",
"true");
998 Fn->addFnAttr(
"no-inline-line-tables");
1002 Fn->addFnAttr(
"profile-sample-accurate");
1005 Fn->addFnAttr(
"use-sample-profile");
1007 if (
D &&
D->
hasAttr<CFICanonicalJumpTableAttr>())
1008 Fn->addFnAttr(
"cfi-canonical-jump-table");
1010 if (
D &&
D->
hasAttr<NoProfileFunctionAttr>())
1011 Fn->addFnAttr(llvm::Attribute::NoProfile);
1013 if (
D &&
D->
hasAttr<HybridPatchableAttr>())
1014 Fn->addFnAttr(llvm::Attribute::HybridPatchable);
1018 if (
auto *A =
D->
getAttr<FunctionReturnThunksAttr>()) {
1019 switch (A->getThunkType()) {
1020 case FunctionReturnThunksAttr::Kind::Keep:
1022 case FunctionReturnThunksAttr::Kind::Extern:
1023 Fn->addFnAttr(llvm::Attribute::FnRetThunkExtern);
1027 Fn->addFnAttr(llvm::Attribute::FnRetThunkExtern);
1032 getContext().getTargetInfo().getTriple().isSPIRV()) ||
1036 EmitKernelMetadata(FD, Fn);
1039 if (FD && FD->
hasAttr<ClspvLibclcBuiltinAttr>()) {
1040 Fn->setMetadata(
"clspv_libclc_builtin",
1046 if (FD &&
SanOpts.
has(SanitizerKind::Function)) {
1048 llvm::LLVMContext &Ctx =
Fn->getContext();
1049 llvm::MDBuilder MDB(Ctx);
1051 llvm::LLVMContext::MD_func_sanitize,
1052 MDB.createRTTIPointerPrologue(
1059 if (
SanOpts.
has(SanitizerKind::NullabilityReturn)) {
1063 if (!(
SanOpts.
has(SanitizerKind::ReturnsNonnullAttribute) &&
1065 RetValNullabilityPrecondition =
1088 Fn->addFnAttr(llvm::Attribute::NoRecurse);
1091 llvm::fp::ExceptionBehavior FPExceptionBehavior =
1093 Builder.setDefaultConstrainedRounding(RM);
1094 Builder.setDefaultConstrainedExcept(FPExceptionBehavior);
1096 (!FD && (FPExceptionBehavior != llvm::fp::ebIgnore ||
1097 RM != llvm::RoundingMode::NearestTiesToEven))) {
1098 Builder.setIsFPConstrained(
true);
1099 Fn->addFnAttr(llvm::Attribute::StrictFP);
1106 Fn->addFnAttr(
"stackrealign");
1110 Fn->removeFnAttr(
"zero-call-used-regs");
1117 llvm::Value *Poison = llvm::PoisonValue::get(
Int32Ty);
1122 Builder.SetInsertPoint(EntryBB);
1126 if (requiresReturnValueCheck()) {
1137 DI->emitFunctionStart(GD,
Loc, StartLoc,
1138 DI->getFunctionType(FD, RetTy, Args),
CurFn,
1144 CurFn->addFnAttr(
"instrument-function-entry",
"__cyg_profile_func_enter");
1146 CurFn->addFnAttr(
"instrument-function-entry-inlined",
1147 "__cyg_profile_func_enter");
1149 CurFn->addFnAttr(
"instrument-function-entry-inlined",
1150 "__cyg_profile_func_enter_bare");
1162 Fn->addFnAttr(
"fentry-call",
"true");
1164 Fn->addFnAttr(
"instrument-function-entry-inlined",
1170 <<
"-mnop-mcount" <<
"-mfentry";
1171 Fn->addFnAttr(
"mnop-mcount");
1177 <<
"-mrecord-mcount" <<
"-mfentry";
1178 Fn->addFnAttr(
"mrecord-mcount");
1184 if (
getContext().getTargetInfo().getTriple().getArch() !=
1185 llvm::Triple::systemz)
1187 <<
"-mpacked-stack";
1188 Fn->addFnAttr(
"packed-stack");
1193 Fn->addFnAttr(
"warn-stack-size",
1206 auto AI =
CurFn->arg_begin();
1222 llvm::Function::arg_iterator EI =
CurFn->arg_end();
1227 cast<llvm::GetElementPtrInst>(Addr)->getResultElementType();
1254 if (FD->
hasAttr<HLSLShaderAttr>()) {
1262 if (
const CXXMethodDecl *MD = dyn_cast_if_present<CXXMethodDecl>(
D);
1283 CXXThisValue = ThisFieldLValue.
getPointer(*
this);
1292 if (FD->hasCapturedVLAType()) {
1295 auto VAT = FD->getCapturedVLAType();
1296 VLASizeMap[VAT->getSizeExpr()] = ExprArg;
1303 CXXThisValue = CXXABIThisValue;
1307 if (CXXABIThisValue) {
1309 SkippedChecks.
set(SanitizerKind::ObjectSize,
true);
1316 SkippedChecks.
set(SanitizerKind::Null,
true);
1320 Loc, CXXABIThisValue, ThisTy, CXXABIThisAlignment, SkippedChecks);
1327 if (!FD || !FD->
hasAttr<NakedAttr>()) {
1328 for (
const VarDecl *VD : Args) {
1333 if (
const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD))
1334 Ty = PVD->getOriginalType();
1344 DI->EmitLocation(
Builder, StartLoc);
1349 LargestVectorWidth = VecWidth->getVectorWidth();
1358 if (
const CompoundStmt *S = dyn_cast<CompoundStmt>(Body))
1370 llvm::BasicBlock *SkipCountBB =
nullptr;
1395 if (F->isInterposable())
return;
1397 for (llvm::BasicBlock &BB : *F)
1398 for (llvm::Instruction &I : BB)
1402 F->setDoesNotThrow();
1422 bool PassedParams =
true;
1424 if (
auto Inherited = CD->getInheritedConstructor())
1430 Args.push_back(Param);
1431 if (!Param->hasAttr<PassObjectSizeAttr>())
1435 getContext(), Param->getDeclContext(), Param->getLocation(),
1442 if (MD && (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)))
1450 assert(Fn &&
"generating code for null Function");
1463 std::string FDInlineName = (
Fn->getName() +
".inline").str();
1464 llvm::Module *M =
Fn->getParent();
1465 llvm::Function *Clone = M->getFunction(FDInlineName);
1467 Clone = llvm::Function::Create(
Fn->getFunctionType(),
1468 llvm::GlobalValue::InternalLinkage,
1469 Fn->getAddressSpace(), FDInlineName, M);
1470 Clone->addFnAttr(llvm::Attribute::AlwaysInline);
1472 Fn->setLinkage(llvm::GlobalValue::ExternalLinkage);
1482 if (LLVM_UNLIKELY(PD->isInlineBuiltinDeclaration())) {
1483 std::string FDInlineName = (
Fn->getName() +
".inline").str();
1484 llvm::Module *M =
Fn->getParent();
1485 if (llvm::Function *Clone = M->getFunction(FDInlineName)) {
1486 Clone->replaceAllUsesWith(Fn);
1487 Clone->eraseFromParent();
1495 if (FD->
hasAttr<NoDebugAttr>()) {
1498 Fn->setSubprogram(
nullptr);
1500 DebugInfo =
nullptr;
1510 CurEHLocation = BodyRange.
getEnd();
1522 if (SpecDecl->hasBody(SpecDecl))
1523 Loc = SpecDecl->getLocation();
1529 if (isa<CoroutineBodyStmt>(Body))
1530 ShouldEmitLifetimeMarkers =
true;
1534 if (ShouldEmitLifetimeMarkers)
1542 if (Body && isa_and_nonnull<CoroutineBodyStmt>(Body))
1550 CurFn->addFnAttr(llvm::Attribute::MustProgress);
1554 if (isa<CXXDestructorDecl>(FD))
1556 else if (isa<CXXConstructorDecl>(FD))
1560 FD->
hasAttr<CUDAGlobalAttr>())
1562 else if (isa<CXXMethodDecl>(FD) &&
1563 cast<CXXMethodDecl>(FD)->isLambdaStaticInvoker()) {
1567 }
else if (isa<CXXMethodDecl>(FD) &&
1570 cast<CXXMethodDecl>(FD)->getParent()->getLambdaStaticInvoker() &&
1571 hasInAllocaArg(cast<CXXMethodDecl>(FD))) {
1578 }
else if (FD->
isDefaulted() && isa<CXXMethodDecl>(FD) &&
1579 (cast<CXXMethodDecl>(FD)->isCopyAssignmentOperator() ||
1580 cast<CXXMethodDecl>(FD)->isMoveAssignmentOperator())) {
1587 llvm_unreachable(
"no definition for emitted function");
1597 bool ShouldEmitUnreachable =
1601 SanitizerScope SanScope(
this);
1602 llvm::Value *IsFalse =
Builder.getFalse();
1603 EmitCheck(std::make_pair(IsFalse, SanitizerKind::Return),
1604 SanitizerHandler::MissingReturn,
1606 }
else if (ShouldEmitUnreachable) {
1610 if (
SanOpts.
has(SanitizerKind::Return) || ShouldEmitUnreachable) {
1612 Builder.ClearInsertionPoint();
1621 if (!
CurFn->doesNotThrow())
1630 if (!S)
return false;
1637 if (isa<LabelStmt>(S))
1642 if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
1646 if (isa<SwitchStmt>(S))
1647 IgnoreCaseStmts =
true;
1650 for (
const Stmt *SubStmt : S->children())
1662 if (!S)
return false;
1666 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) ||
1670 if (isa<BreakStmt>(S))
1674 for (
const Stmt *SubStmt : S->children())
1682 if (!S)
return false;
1688 if (isa<IfStmt>(S) || isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
1689 isa<DoStmt>(S) || isa<ForStmt>(S) || isa<CompoundStmt>(S) ||
1690 isa<CXXForRangeStmt>(S) || isa<CXXTryStmt>(S) ||
1691 isa<ObjCForCollectionStmt>(S) || isa<ObjCAtTryStmt>(S))
1694 if (isa<DeclStmt>(S))
1697 for (
const Stmt *SubStmt : S->children())
1717 llvm::APSInt ResultInt;
1721 ResultBool = ResultInt.getBoolValue();
1729 llvm::APSInt &ResultInt,
1747 while (
const UnaryOperator *Op = dyn_cast<UnaryOperator>(
C->IgnoreParens())) {
1748 if (Op->getOpcode() != UO_LNot)
1750 C = Op->getSubExpr();
1752 return C->IgnoreParens();
1768 llvm::BasicBlock *FalseBlock, uint64_t TrueCount ,
1775 const Stmt *CntrStmt = (CntrIdx ? CntrIdx : Cond);
1777 llvm::BasicBlock *ThenBlock =
nullptr;
1778 llvm::BasicBlock *ElseBlock =
nullptr;
1779 llvm::BasicBlock *NextBlock =
nullptr;
1796 if (LOp == BO_LAnd) {
1797 ThenBlock = CounterIncrBlock;
1798 ElseBlock = FalseBlock;
1799 NextBlock = TrueBlock;
1814 else if (LOp == BO_LOr) {
1815 ThenBlock = TrueBlock;
1816 ElseBlock = CounterIncrBlock;
1817 NextBlock = FalseBlock;
1819 llvm_unreachable(
"Expected Opcode must be that of a Logical Operator");
1843 const Expr *Cond, llvm::BasicBlock *TrueBlock, llvm::BasicBlock *FalseBlock,
1847 if (
const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
1849 if (CondBOp->getOpcode() == BO_LAnd) {
1854 bool ConstantBool =
false;
1860 FalseBlock, TrueCount, LH);
1871 FalseBlock, TrueCount, LH, CondBOp);
1883 ConditionalEvaluation eval(*
this);
1900 FalseBlock, TrueCount, LH);
1906 if (CondBOp->getOpcode() == BO_LOr) {
1911 bool ConstantBool =
false;
1917 FalseBlock, TrueCount, LH);
1928 FalseBlock, TrueCount, LH, CondBOp);
1940 uint64_t RHSCount = TrueCount - LHSCount;
1942 ConditionalEvaluation eval(*
this);
1967 if (
const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
1975 if (CondUOp->getOpcode() == UO_LNot && !MCDCCondition) {
1993 ConditionalEvaluation cond(*
this);
2006 LHSScaledTrueCount = TrueCount * LHSRatio;
2015 LHSScaledTrueCount, LH, CondOp);
2022 TrueCount - LHSScaledTrueCount, LH, CondOp);
2028 if (
const CXXThrowExpr *Throw = dyn_cast<CXXThrowExpr>(Cond)) {
2048 const Expr *MCDCBaseExpr = Cond;
2055 MCDCBaseExpr = ConditionalOp;
2060 llvm::MDNode *Weights =
nullptr;
2061 llvm::MDNode *Unpredictable =
nullptr;
2068 auto *FD = dyn_cast_or_null<FunctionDecl>(
Call->getCalleeDecl());
2069 if (FD && FD->
getBuiltinID() == Builtin::BI__builtin_unpredictable) {
2071 Unpredictable = MDHelper.createUnpredictable();
2077 llvm::Value *NewCondV = emitCondLikelihoodViaExpectIntrinsic(CondV, LH);
2078 if (CondV != NewCondV)
2083 Weights = createProfileWeights(TrueCount, CurrentCount - TrueCount);
2086 Builder.CreateCondBr(CondV, TrueBlock, FalseBlock, Weights, Unpredictable);
2104 llvm::Value *sizeInChars) {
2108 llvm::Value *baseSizeInChars
2114 sizeInChars,
"vla.end");
2116 llvm::BasicBlock *originBB = CGF.
Builder.GetInsertBlock();
2124 llvm::PHINode *cur =
Builder.CreatePHI(begin.
getType(), 2,
"vla.cur");
2139 llvm::Value *done =
Builder.CreateICmpEQ(next, end,
"vla-init.isdone");
2140 Builder.CreateCondBr(done, contBB, loopBB);
2141 cur->addIncoming(next, loopBB);
2151 if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
2162 llvm::Value *SizeVal;
2169 dyn_cast_or_null<VariableArrayType>(
2172 SizeVal = VlaSize.NumElts;
2174 if (!eltSize.
isOne())
2195 llvm::GlobalVariable *NullVariable =
2196 new llvm::GlobalVariable(
CGM.
getModule(), NullConstant->getType(),
2198 llvm::GlobalVariable::PrivateLinkage,
2199 NullConstant, Twine());
2201 NullVariable->setAlignment(NullAlign.
getAsAlign());
2219 if (!IndirectBranch)
2225 IndirectBranch->addDestination(BB);
2226 return llvm::BlockAddress::get(
CurFn, BB);
2231 if (IndirectBranch)
return IndirectBranch->getParent();
2236 llvm::Value *DestVal = TmpBuilder.CreatePHI(
Int8PtrTy, 0,
2237 "indirect.goto.dest");
2240 IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
2241 return IndirectBranch->getParent();
2253 llvm::Value *numVLAElements =
nullptr;
2254 if (isa<VariableArrayType>(
arrayType)) {
2265 baseType = elementType;
2266 return numVLAElements;
2268 }
while (isa<VariableArrayType>(
arrayType));
2280 llvm::ConstantInt *zero =
Builder.getInt32(0);
2281 gepIndices.push_back(zero);
2286 llvm::ArrayType *llvmArrayType =
2288 while (llvmArrayType) {
2289 assert(isa<ConstantArrayType>(
arrayType));
2290 assert(cast<ConstantArrayType>(
arrayType)->getZExtSize() ==
2291 llvmArrayType->getNumElements());
2293 gepIndices.push_back(zero);
2294 countFromCLAs *= llvmArrayType->getNumElements();
2298 dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType());
2301 "LLVM and Clang types are out-of-synch");
2309 countFromCLAs *= cast<ConstantArrayType>(
arrayType)->getZExtSize();
2320 gepIndices,
"array.begin"),
2326 llvm::Value *numElements
2327 = llvm::ConstantInt::get(
SizeTy, countFromCLAs);
2331 numElements =
Builder.CreateNUWMul(numVLAElements, numElements);
2338 assert(vla &&
"type was not a variable array type!");
2342CodeGenFunction::VlaSizePair
2345 llvm::Value *numElements =
nullptr;
2349 elementType =
type->getElementType();
2350 llvm::Value *vlaSize = VLASizeMap[
type->getSizeExpr()];
2351 assert(vlaSize &&
"no size for VLA!");
2352 assert(vlaSize->getType() ==
SizeTy);
2355 numElements = vlaSize;
2359 numElements =
Builder.CreateNUWMul(numElements, vlaSize);
2361 }
while ((
type =
getContext().getAsVariableArrayType(elementType)));
2363 return { numElements, elementType };
2366CodeGenFunction::VlaSizePair
2369 assert(vla &&
"type was not a variable array type!");
2373CodeGenFunction::VlaSizePair
2375 llvm::Value *VlaSize = VLASizeMap[Vla->
getSizeExpr()];
2376 assert(VlaSize &&
"no size for VLA!");
2377 assert(VlaSize->getType() ==
SizeTy);
2382 assert(
type->isVariablyModifiedType() &&
2383 "Must pass variably modified type to EmitVLASizes!");
2390 assert(
type->isVariablyModifiedType());
2392 const Type *ty =
type.getTypePtr();
2395#define TYPE(Class, Base)
2396#define ABSTRACT_TYPE(Class, Base)
2397#define NON_CANONICAL_TYPE(Class, Base)
2398#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2399#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
2400#include "clang/AST/TypeNodes.inc"
2401 llvm_unreachable(
"unexpected dependent type!");
2407 case Type::ExtVector:
2408 case Type::ConstantMatrix:
2412 case Type::TemplateSpecialization:
2413 case Type::ObjCTypeParam:
2414 case Type::ObjCObject:
2415 case Type::ObjCInterface:
2416 case Type::ObjCObjectPointer:
2418 llvm_unreachable(
"type class is never variably-modified!");
2420 case Type::Elaborated:
2421 type = cast<ElaboratedType>(ty)->getNamedType();
2424 case Type::Adjusted:
2425 type = cast<AdjustedType>(ty)->getAdjustedType();
2429 type = cast<DecayedType>(ty)->getPointeeType();
2433 type = cast<PointerType>(ty)->getPointeeType();
2436 case Type::BlockPointer:
2437 type = cast<BlockPointerType>(ty)->getPointeeType();
2440 case Type::LValueReference:
2441 case Type::RValueReference:
2442 type = cast<ReferenceType>(ty)->getPointeeType();
2445 case Type::MemberPointer:
2446 type = cast<MemberPointerType>(ty)->getPointeeType();
2449 case Type::ArrayParameter:
2450 case Type::ConstantArray:
2451 case Type::IncompleteArray:
2453 type = cast<ArrayType>(ty)->getElementType();
2456 case Type::VariableArray: {
2465 llvm::Value *&entry = VLASizeMap[sizeExpr];
2474 SanitizerScope SanScope(
this);
2475 llvm::Value *
Zero = llvm::Constant::getNullValue(size->getType());
2477 llvm::Value *CheckCondition =
2479 ?
Builder.CreateICmpSGT(size, Zero)
2480 :
Builder.CreateICmpUGT(size, Zero);
2481 llvm::Constant *StaticArgs[] = {
2484 EmitCheck(std::make_pair(CheckCondition, SanitizerKind::VLABound),
2485 SanitizerHandler::VLABoundNotPositive, StaticArgs, size);
2498 case Type::FunctionProto:
2499 case Type::FunctionNoProto:
2500 type = cast<FunctionType>(ty)->getReturnType();
2505 case Type::UnaryTransform:
2506 case Type::Attributed:
2507 case Type::BTFTagAttributed:
2508 case Type::HLSLAttributedResource:
2509 case Type::SubstTemplateTypeParm:
2510 case Type::MacroQualified:
2511 case Type::CountAttributed:
2517 case Type::Decltype:
2519 case Type::DeducedTemplateSpecialization:
2520 case Type::PackIndexing:
2524 case Type::TypeOfExpr:
2530 type = cast<AtomicType>(ty)->getValueType();
2534 type = cast<PipeType>(ty)->getElementType();
2537 }
while (
type->isVariablyModifiedType());
2541 if (
getContext().getBuiltinVaListType()->isArrayType())
2552 assert(
Init.hasValue() &&
"Invalid DeclRefExpr initializer!");
2555 Dbg->EmitGlobalVariable(
E->getDecl(),
Init);
2558CodeGenFunction::PeepholeProtection
2564 if (!rvalue.
isScalar())
return PeepholeProtection();
2566 if (!isa<llvm::ZExtInst>(value))
return PeepholeProtection();
2570 llvm::Instruction *inst =
new llvm::BitCastInst(value, value->getType(),
"",
2573 PeepholeProtection protection;
2574 protection.Inst = inst;
2579 if (!protection.Inst)
return;
2582 protection.Inst->eraseFromParent();
2588 llvm::Value *Alignment,
2589 llvm::Value *OffsetValue) {
2590 if (Alignment->getType() !=
IntPtrTy)
2593 if (OffsetValue && OffsetValue->getType() !=
IntPtrTy)
2596 llvm::Value *TheCheck =
nullptr;
2598 llvm::Value *PtrIntValue =
2602 bool IsOffsetZero =
false;
2603 if (
const auto *CI = dyn_cast<llvm::ConstantInt>(OffsetValue))
2604 IsOffsetZero = CI->isZero();
2607 PtrIntValue =
Builder.CreateSub(PtrIntValue, OffsetValue,
"offsetptr");
2610 llvm::Value *
Zero = llvm::ConstantInt::get(
IntPtrTy, 0);
2613 llvm::Value *MaskedPtr =
Builder.CreateAnd(PtrIntValue, Mask,
"maskedptr");
2614 TheCheck =
Builder.CreateICmpEQ(MaskedPtr, Zero,
"maskcond");
2616 llvm::Instruction *Assumption =
Builder.CreateAlignmentAssumption(
2622 OffsetValue, TheCheck, Assumption);
2628 llvm::Value *Alignment,
2629 llvm::Value *OffsetValue) {
2638 llvm::Value *AnnotatedVal,
2639 StringRef AnnotationStr,
2641 const AnnotateAttr *
Attr) {
2650 return Builder.CreateCall(AnnotationFn, Args);
2654 assert(
D->
hasAttr<AnnotateAttr>() &&
"no annotate attribute");
2657 {V->getType(), CGM.ConstGlobalsPtrTy}),
2663 assert(
D->
hasAttr<AnnotateAttr>() &&
"no annotate attribute");
2665 llvm::Type *VTy =
V->getType();
2666 auto *PTy = dyn_cast<llvm::PointerType>(VTy);
2667 unsigned AS = PTy ? PTy->getAddressSpace() : 0;
2668 llvm::PointerType *IntrinTy =
2677 if (VTy != IntrinTy)
2695 CGF->IsSanitizerScope =
false;
2699 const llvm::Twine &Name,
2700 llvm::BasicBlock::iterator InsertPt)
const {
2703 I->setNoSanitizeMetadata();
2707 llvm::Instruction *I,
const llvm::Twine &Name,
2708 llvm::BasicBlock::iterator InsertPt)
const {
2709 llvm::IRBuilderDefaultInserter::InsertHelper(I, Name, InsertPt);
2711 CGF->InsertHelper(I, Name, InsertPt);
2722 if (BuiltinID == X86::BI__builtin_ia32_cmpps ||
2723 BuiltinID == X86::BI__builtin_ia32_cmpss ||
2724 BuiltinID == X86::BI__builtin_ia32_cmppd ||
2725 BuiltinID == X86::BI__builtin_ia32_cmpsd) {
2727 llvm::StringMap<bool> TargetFetureMap;
2731 if (
Result.getSExtValue() > 7 && !TargetFetureMap.lookup(
"avx"))
2757 std::string MissingFeature;
2758 llvm::StringMap<bool> CallerFeatureMap;
2768 FeatureList, CallerFeatureMap) && !IsHipStdPar) {
2774 TargetDecl->
hasAttr<TargetAttr>()) {
2777 const TargetAttr *TD = TargetDecl->
getAttr<TargetAttr>();
2782 llvm::StringMap<bool> CalleeFeatureMap;
2786 if (F[0] ==
'+' && CalleeFeatureMap.lookup(F.substr(1)))
2787 ReqFeatures.push_back(StringRef(F).substr(1));
2790 for (
const auto &F : CalleeFeatureMap) {
2793 ReqFeatures.push_back(F.getKey());
2795 if (!llvm::all_of(ReqFeatures, [&](StringRef Feature) {
2796 if (!CallerFeatureMap.lookup(Feature)) {
2797 MissingFeature = Feature.str();
2805 llvm::StringMap<bool> CalleeFeatureMap;
2808 for (
const auto &F : CalleeFeatureMap) {
2809 if (F.getValue() && (!CallerFeatureMap.lookup(F.getKey()) ||
2810 !CallerFeatureMap.find(F.getKey())->getValue()) &&
2822 llvm::IRBuilder<> IRB(
Builder.GetInsertBlock(),
Builder.GetInsertPoint());
2823 IRB.SetCurrentDebugLocation(
Builder.getCurrentDebugLocation());
2830 Callee.getAbstractInfo().getCalleeFunctionProtoType();
2836CodeGenFunction::FormAArch64ResolverCondition(
const FMVResolverOption &RO) {
2837 return RO.Features.empty() ? nullptr : EmitAArch64CpuSupports(RO.Features);
2841CodeGenFunction::FormX86ResolverCondition(
const FMVResolverOption &RO) {
2844 if (RO.Architecture) {
2845 StringRef Arch = *RO.Architecture;
2848 if (Arch.starts_with(
"x86-64"))
2854 if (!RO.Features.empty()) {
2855 llvm::Value *FeatureCond = EmitX86CpuSupports(RO.Features);
2863 llvm::Function *Resolver,
2865 llvm::Function *FuncToReturn,
2866 bool SupportsIFunc) {
2867 if (SupportsIFunc) {
2868 Builder.CreateRet(FuncToReturn);
2873 llvm::make_pointer_range(Resolver->args()));
2875 llvm::CallInst *
Result =
Builder.CreateCall(FuncToReturn, Args);
2876 Result->setTailCallKind(llvm::CallInst::TCK_MustTail);
2878 if (Resolver->getReturnType()->isVoidTy())
2887 llvm::Triple::ArchType ArchType =
2891 case llvm::Triple::x86:
2892 case llvm::Triple::x86_64:
2895 case llvm::Triple::aarch64:
2898 case llvm::Triple::riscv32:
2899 case llvm::Triple::riscv64:
2904 assert(
false &&
"Only implemented for x86, AArch64 and RISC-V targets");
2911 if (
getContext().getTargetInfo().getTriple().getOS() !=
2912 llvm::Triple::OSType::Linux) {
2918 Builder.SetInsertPoint(CurBlock);
2922 bool HasDefault =
false;
2923 unsigned DefaultIndex = 0;
2926 for (
unsigned Index = 0; Index < Options.size(); Index++) {
2928 if (Options[Index].Features.empty()) {
2930 DefaultIndex = Index;
2934 Builder.SetInsertPoint(CurBlock);
2960 for (StringRef Feat : Options[Index].Features) {
2961 std::vector<std::string> FeatStr =
2964 assert(FeatStr.size() == 1 &&
"Feature string not delimited");
2966 std::string &CurrFeat = FeatStr.front();
2967 if (CurrFeat[0] ==
'+')
2968 TargetAttrFeats.push_back(CurrFeat.substr(1));
2971 if (TargetAttrFeats.empty())
2974 for (std::string &Feat : TargetAttrFeats)
2975 CurrTargetAttrFeats.push_back(Feat);
2977 Builder.SetInsertPoint(CurBlock);
2980 llvm::BasicBlock *RetBlock =
createBasicBlock(
"resolver_return", Resolver);
2983 Options[Index].
Function, SupportsIFunc);
2986 Builder.SetInsertPoint(CurBlock);
2987 Builder.CreateCondBr(FeatsCondition, RetBlock, ElseBlock);
2989 CurBlock = ElseBlock;
2994 Builder.SetInsertPoint(CurBlock);
3001 Builder.SetInsertPoint(CurBlock);
3002 llvm::CallInst *TrapCall =
EmitTrapCall(llvm::Intrinsic::trap);
3003 TrapCall->setDoesNotReturn();
3004 TrapCall->setDoesNotThrow();
3006 Builder.ClearInsertionPoint();
3011 assert(!Options.empty() &&
"No multiversion resolver options found");
3012 assert(Options.back().Features.size() == 0 &&
"Default case must be last");
3014 assert(SupportsIFunc &&
3015 "Multiversion resolver requires target IFUNC support");
3016 bool AArch64CpuInitialized =
false;
3019 for (
const FMVResolverOption &RO : Options) {
3020 Builder.SetInsertPoint(CurBlock);
3021 llvm::Value *
Condition = FormAArch64ResolverCondition(RO);
3030 if (!AArch64CpuInitialized) {
3031 Builder.SetInsertPoint(CurBlock, CurBlock->begin());
3032 EmitAArch64CpuInit();
3033 AArch64CpuInitialized =
true;
3034 Builder.SetInsertPoint(CurBlock);
3037 llvm::BasicBlock *RetBlock =
createBasicBlock(
"resolver_return", Resolver);
3046 Builder.SetInsertPoint(CurBlock);
3047 llvm::CallInst *TrapCall =
EmitTrapCall(llvm::Intrinsic::trap);
3048 TrapCall->setDoesNotReturn();
3049 TrapCall->setDoesNotThrow();
3051 Builder.ClearInsertionPoint();
3061 Builder.SetInsertPoint(CurBlock);
3064 for (
const FMVResolverOption &RO : Options) {
3065 Builder.SetInsertPoint(CurBlock);
3066 llvm::Value *
Condition = FormX86ResolverCondition(RO);
3070 assert(&RO == Options.end() - 1 &&
3071 "Default or Generic case must be last");
3077 llvm::BasicBlock *RetBlock =
createBasicBlock(
"resolver_return", Resolver);
3086 Builder.SetInsertPoint(CurBlock);
3087 llvm::CallInst *TrapCall =
EmitTrapCall(llvm::Intrinsic::trap);
3088 TrapCall->setDoesNotReturn();
3089 TrapCall->setDoesNotThrow();
3091 Builder.ClearInsertionPoint();
3103 llvm::Value *OffsetValue, llvm::Value *TheCheck,
3104 llvm::Instruction *Assumption) {
3105 assert(isa_and_nonnull<llvm::CallInst>(Assumption) &&
3106 cast<llvm::CallInst>(Assumption)->getCalledOperand() ==
3107 llvm::Intrinsic::getOrInsertDeclaration(
3108 Builder.GetInsertBlock()->getParent()->getParent(),
3109 llvm::Intrinsic::assume) &&
3110 "Assumption should be a call to llvm.assume().");
3111 assert(&(
Builder.GetInsertBlock()->back()) == Assumption &&
3112 "Assumption should be the last instruction of the basic block, "
3113 "since the basic block is still being generated.");
3125 Assumption->removeFromParent();
3128 SanitizerScope SanScope(
this);
3131 OffsetValue =
Builder.getInt1(
false);
3139 EmitCheck({std::make_pair(TheCheck, SanitizerKind::Alignment)},
3140 SanitizerHandler::AlignmentAssumption, StaticData, DynamicData);
3151 return DI->SourceLocToDebugLoc(Location);
3153 return llvm::DebugLoc();
3157CodeGenFunction::emitCondLikelihoodViaExpectIntrinsic(llvm::Value *Cond,
3168 llvm::Type *CondTy = Cond->getType();
3169 assert(CondTy->isIntegerTy(1) &&
"expecting condition to be a boolean");
3170 llvm::Function *FnExpect =
3172 llvm::Value *ExpectedValueOfCond =
3174 return Builder.CreateCall(FnExpect, {Cond, ExpectedValueOfCond},
3175 Cond->getName() +
".expval");
3177 llvm_unreachable(
"Unknown Likelihood");
3181 unsigned NumElementsDst,
3182 const llvm::Twine &Name) {
3183 auto *SrcTy = cast<llvm::FixedVectorType>(SrcVec->getType());
3184 unsigned NumElementsSrc = SrcTy->getNumElements();
3185 if (NumElementsSrc == NumElementsDst)
3188 std::vector<int> ShuffleMask(NumElementsDst, -1);
3189 for (
unsigned MaskIdx = 0;
3190 MaskIdx < std::min<>(NumElementsDst, NumElementsSrc); ++MaskIdx)
3191 ShuffleMask[MaskIdx] = MaskIdx;
3193 return Builder.CreateShuffleVector(SrcVec, ShuffleMask, Name);
3208 llvm::Value *Args[] = {Key, Discriminator};
3209 Bundles.emplace_back(
"ptrauth", Args);
3215 unsigned IntrinsicID) {
3222 if (!Discriminator) {
3227 auto OrigType =
Pointer->getType();
3245 llvm::Intrinsic::ptrauth_sign);
3251 auto StripIntrinsic = CGF.
CGM.
getIntrinsic(llvm::Intrinsic::ptrauth_strip);
3255 auto OrigType =
Pointer->getType();
3272 llvm::Intrinsic::ptrauth_auth);
Defines the clang::ASTContext interface.
This file provides some common utility functions for processing Lambda related AST Constructs.
Defines enum values for all the target-independent builtin functions.
static llvm::Value * EmitPointerAuthCommon(CodeGenFunction &CGF, const CGPointerAuthInfo &PointerAuth, llvm::Value *Pointer, unsigned IntrinsicID)
static void CreateMultiVersionResolverReturn(CodeGenModule &CGM, llvm::Function *Resolver, CGBuilderTy &Builder, llvm::Function *FuncToReturn, bool SupportsIFunc)
static llvm::Value * EmitStrip(CodeGenFunction &CGF, const CGPointerAuthInfo &PointerAuth, llvm::Value *Pointer)
static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType, Address dest, Address src, llvm::Value *sizeInChars)
emitNonZeroVLAInit - Emit the "zero" initialization of a variable-length array whose elements have a ...
static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB)
static LValue makeNaturalAlignAddrLValue(llvm::Value *V, QualType T, bool ForPointeeType, bool MightBeSigned, CodeGenFunction &CGF, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
static void TryMarkNoThrow(llvm::Function *F)
Tries to mark the given function nounwind based on the non-existence of any throwing calls within it.
static llvm::Constant * getPrologueSignature(CodeGenModule &CGM, const FunctionDecl *FD)
Return the UBSan prologue signature for FD if one is available.
static bool endsWithReturn(const Decl *F)
Determine whether the function F ends with a return stmt.
static bool shouldEmitLifetimeMarkers(const CodeGenOptions &CGOpts, const LangOptions &LangOpts)
shouldEmitLifetimeMarkers - Decide whether we need emit the life-time markers.
static bool matchesStlAllocatorFn(const Decl *D, const ASTContext &Ctx)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
llvm::MachO::Target Target
Defines the Objective-C statement AST node classes.
Enumerates target-specific builtins in their own namespaces within namespace clang.
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
ParsedTargetAttr filterFunctionTargetAttrs(const TargetAttr *TD) const
Parses the target attributes passed in, and returns only the ones that are valid feature names.
Builtin::Context & BuiltinInfo
QualType getFunctionTypeWithExceptionSpec(QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const
Get a function type and produce the equivalent function type with the specified exception specificati...
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
bool hasAnyFunctionEffects() const
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
const VariableArrayType * getAsVariableArrayType(QualType T) const
const TargetInfo & getTargetInfo() const
void getFunctionFeatureMap(llvm::StringMap< bool > &FeatureMap, const FunctionDecl *) const
Represents an array type, per C99 6.7.5.2 - Array Declarators.
QualType getElementType() const
Attr - This represents one attribute.
A builtin binary operation expression such as "x + y" or "x <= y".
static bool isLogicalOp(Opcode Opc)
const char * getRequiredFeatures(unsigned ID) const
Represents a C++ constructor within a class.
Represents a static or instance method of a struct/union/class.
bool isImplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An implicit object member function is a non-static member function without an exp...
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
QualType getThisType() const
Return the type of the this pointer.
Represents a C++ struct/union/class.
bool isLambda() const
Determine whether this class describes a lambda function object.
void getCaptureFields(llvm::DenseMap< const ValueDecl *, FieldDecl * > &Captures, FieldDecl *&ThisCapture) const
For a closure type, retrieve the mapping from captured variables and this to the non-static data memb...
bool isCapturelessLambda() const
A C++ throw-expression (C++ [except.throw]).
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
CharUnits - This is an opaque type for sizes expressed in character units.
bool isZero() const
isZero - Test whether the quantity equals zero.
llvm::Align getAsAlign() const
getAsAlign - Returns Quantity as a valid llvm::Align, Beware llvm::Align assumes power of two 8-bit b...
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
CharUnits alignmentOfArrayElement(CharUnits elementSize) const
Given that this is the alignment of the first element of an array, return the minimum alignment of an...
bool isOne() const
isOne - Test whether the quantity equals one.
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
std::string SampleProfileFile
Name of the profile file to use with -fprofile-sample-use.
bool hasProfileClangInstr() const
Check if Clang profile instrumenation is on.
XRayInstrSet XRayInstrumentationBundle
Set of XRay instrumentation kinds to emit.
bool hasSanitizeCoverage() const
PointerAuthOptions PointerAuth
Configuration for pointer-signing.
bool hasReducedDebugInfo() const
Check if type and variable info should be emitted.
bool hasSanitizeBinaryMetadata() const
unsigned getInAllocaFieldIndex() const
bool getIndirectByVal() const
@ InAlloca
InAlloca - Pass the argument directly using the LLVM inalloca attribute.
@ Indirect
Indirect - Pass the argument indirectly via a hidden pointer with the specified alignment (0 indicate...
bool isSRetAfterThis() const
CharUnits getIndirectAlign() const
Like RawAddress, an abstract representation of an aligned address, but the pointer contained in this ...
llvm::Value * emitRawPointer(CodeGenFunction &CGF) const
Return the pointer contained in this class after authenticating it and adding offset to it if necessa...
CharUnits getAlignment() const
llvm::Type * getElementType() const
Return the type of the values stored in this address.
Address withElementType(llvm::Type *ElemTy) const
Return address with different element type, but same pointer and alignment.
llvm::PointerType * getType() const
Return the type of the pointer value.
A scoped helper to set the current debug location to the specified location or preferred location of ...
static ApplyDebugLocation CreateDefaultArtificial(CodeGenFunction &CGF, SourceLocation TemporaryLocation)
Apply TemporaryLocation if it is valid.
This is an IRBuilder insertion helper that forwards to CodeGenFunction::InsertHelper,...
void InsertHelper(llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock::iterator InsertPt) const override
This forwards to CodeGenFunction::InsertHelper.
llvm::StoreInst * CreateStore(llvm::Value *Val, Address Addr, bool IsVolatile=false)
llvm::CallInst * CreateMemSet(Address Dest, llvm::Value *Value, llvm::Value *Size, bool IsVolatile=false)
Address CreateStructGEP(Address Addr, unsigned Index, const llvm::Twine &Name="")
llvm::CallInst * CreateMemCpy(Address Dest, Address Src, llvm::Value *Size, bool IsVolatile=false)
llvm::LoadInst * CreateAlignedLoad(llvm::Type *Ty, llvm::Value *Addr, CharUnits Align, const llvm::Twine &Name="")
llvm::ConstantInt * getSize(CharUnits N)
Address CreateInBoundsGEP(Address Addr, ArrayRef< llvm::Value * > IdxList, llvm::Type *ElementType, CharUnits Align, const Twine &Name="")
virtual void emitDeviceStub(CodeGenFunction &CGF, FunctionArgList &Args)=0
Emits a kernel launch stub.
Implements C++ ABI-specific code generation functions.
virtual bool hasMostDerivedReturn(GlobalDecl GD) const
virtual bool HasThisReturn(GlobalDecl GD) const
Returns true if the given constructor or destructor is one of the kinds that the ABI says returns 'th...
virtual void EmitInstanceFunctionProlog(CodeGenFunction &CGF)=0
Emit the ABI-specific prolog for the function.
@ RAA_DirectInMemory
Pass it on the stack using its defined layout.
void buildThisParam(CodeGenFunction &CGF, FunctionArgList &Params)
Build a parameter variable suitable for 'this'.
virtual void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy, FunctionArgList &Params)=0
Insert any ABI-specific implicit parameters into the parameter list for a function.
virtual RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const =0
Returns how an argument of the given record type should be passed.
MangleContext & getMangleContext()
Gets the mangle context.
All available information about a concrete callee.
This class gathers all debug information during compilation and is responsible for emitting to llvm g...
CGFunctionInfo - Class to encapsulate the information about a function definition.
ABIArgInfo & getReturnInfo()
bool isReturnsRetained() const
In ARC, whether this function retains its return value.
CanQualType getReturnType() const
bool isDelegateCall() const
unsigned getMaxVectorWidth() const
Return the maximum vector width in the arguments.
llvm::StructType * getArgStruct() const
Get the struct type used to represent all the arguments in memory.
void setHLSLFunctionAttributes(const FunctionDecl *FD, llvm::Function *Fn)
void emitEntryFunction(const FunctionDecl *FD, llvm::Function *Fn)
virtual void functionFinished(CodeGenFunction &CGF)
Cleans up references to the objects in finished function.
llvm::OpenMPIRBuilder & getOMPBuilder()
virtual void emitFunctionProlog(CodeGenFunction &CGF, const Decl *D)
Emits OpenMP-specific function prolog.
llvm::Value * getDiscriminator() const
virtual ~CGCapturedStmtInfo()
CGFPOptionsRAII(CodeGenFunction &CGF, FPOptions FPFeatures)
SanitizerScope(CodeGenFunction *CGF)
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
llvm::Value * EmitPointerAuthAuth(const CGPointerAuthInfo &Info, llvm::Value *Pointer)
void EmitDestructorBody(FunctionArgList &Args)
void EmitBranchToCounterBlock(const Expr *Cond, BinaryOperator::Opcode LOp, llvm::BasicBlock *TrueBlock, llvm::BasicBlock *FalseBlock, uint64_t TrueCount=0, Stmt::Likelihood LH=Stmt::LH_None, const Expr *CntrIdx=nullptr)
EmitBranchToCounterBlock - Emit a conditional branch to a new block that increments a profile counter...
void FinishFunction(SourceLocation EndLoc=SourceLocation())
FinishFunction - Complete IR generation of the current function.
void EmitNullInitialization(Address DestPtr, QualType Ty)
EmitNullInitialization - Generate code to set a value of the given type to null, If the type contains...
void EmitPointerAuthOperandBundle(const CGPointerAuthInfo &Info, SmallVectorImpl< llvm::OperandBundleDef > &Bundles)
GlobalDecl CurGD
CurGD - The GlobalDecl for the current function being compiled.
static TypeEvaluationKind getEvaluationKind(QualType T)
getEvaluationKind - Return the TypeEvaluationKind of QualType T.
static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts=false)
ContainsLabel - Return true if the statement contains a label in it.
void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock, llvm::BasicBlock *FalseBlock, uint64_t TrueCount, Stmt::Likelihood LH=Stmt::LH_None, const Expr *ConditionalOp=nullptr)
EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g.
llvm::CallInst * EmitTrapCall(llvm::Intrinsic::ID IntrID)
Emit a call to trap or debugtrap and attach function attribute "trap-func-name" if specified.
JumpDest getJumpDestInCurrentScope(llvm::BasicBlock *Target)
The given basic block lies in the current EH scope, but may be a target of a potentially scope-crossi...
void EmitSanitizerStatReport(llvm::SanitizerStatKind SSK)
SanitizerSet SanOpts
Sanitizers enabled for this function.
void EmitAArch64MultiVersionResolver(llvm::Function *Resolver, ArrayRef< FMVResolverOption > Options)
void unprotectFromPeepholes(PeepholeProtection protection)
void EmitLambdaStaticInvokeBody(const CXXMethodDecl *MD)
bool ShouldInstrumentFunction()
ShouldInstrumentFunction - Return true if the current function should be instrumented with __cyg_prof...
Address EmitCompoundStmtWithoutScope(const CompoundStmt &S, bool GetLast=false, AggValueSlot AVS=AggValueSlot::ignored())
static bool hasScalarEvaluationKind(QualType T)
void EmitMultiVersionResolver(llvm::Function *Resolver, ArrayRef< FMVResolverOption > Options)
FieldDecl * LambdaThisCaptureField
LValue MakeNaturalAlignPointeeRawAddrLValue(llvm::Value *V, QualType T)
Same as MakeNaturalAlignPointeeAddrLValue except that the pointer is known to be unsigned.
void EmitKCFIOperandBundle(const CGCallee &Callee, SmallVectorImpl< llvm::OperandBundleDef > &Bundles)
void emitAlignmentAssumptionCheck(llvm::Value *Ptr, QualType Ty, SourceLocation Loc, SourceLocation AssumptionLoc, llvm::Value *Alignment, llvm::Value *OffsetValue, llvm::Value *TheCheck, llvm::Instruction *Assumption)
llvm::BlockAddress * GetAddrOfLabel(const LabelDecl *L)
RawAddress CreateDefaultAlignTempAlloca(llvm::Type *Ty, const Twine &Name="tmp")
CreateDefaultAlignedTempAlloca - This creates an alloca with the default ABI alignment of the given L...
llvm::Value * emitArrayLength(const ArrayType *arrayType, QualType &baseType, Address &addr)
emitArrayLength - Compute the length of an array, even if it's a VLA, and drill down to the base elem...
VlaSizePair getVLASize(const VariableArrayType *vla)
Returns an LLVM value that corresponds to the size, in non-variably-sized elements,...
void EmitEndEHSpec(const Decl *D)
EmitEndEHSpec - Emit the end of the exception spec.
llvm::Value * EmitRISCVCpuSupports(const CallExpr *E)
bool CurFuncIsThunk
In C++, whether we are code generating a thunk.
LValue EmitLValue(const Expr *E, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
EmitLValue - Emit code to compute a designator that specifies the location of the expression.
llvm::SmallVector< DeferredDeactivateCleanup > DeferredDeactivationCleanupStack
void EmitVariablyModifiedType(QualType Ty)
EmitVLASize - Capture all the sizes for the VLA expressions in the given variably-modified type and s...
llvm::BasicBlock * createBasicBlock(const Twine &name="", llvm::Function *parent=nullptr, llvm::BasicBlock *before=nullptr)
createBasicBlock - Create an LLVM basic block.
const LangOptions & getLangOpts() const
void EmitFunctionEpilog(const CGFunctionInfo &FI, bool EmitRetDbgLoc, SourceLocation EndLoc)
EmitFunctionEpilog - Emit the target specific LLVM code to return the given temporary.
llvm::Constant * EmitCheckTypeDescriptor(QualType T)
Emit a description of a type in a format suitable for passing to a runtime sanitizer handler.
llvm::BasicBlock * EHResumeBlock
EHResumeBlock - Unified block containing a call to llvm.eh.resume.
void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false)
EmitBlock - Emit the given block.
static bool isInstrumentedCondition(const Expr *C)
isInstrumentedCondition - Determine whether the given condition is an instrumentable condition (i....
void EmitFunctionBody(const Stmt *Body)
void EmitRISCVMultiVersionResolver(llvm::Function *Resolver, ArrayRef< FMVResolverOption > Options)
Address makeNaturalAddressForPointer(llvm::Value *Ptr, QualType T, CharUnits Alignment=CharUnits::Zero(), bool ForPointeeType=false, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
Construct an address with the natural alignment of T.
RValue EmitLoadOfLValue(LValue V, SourceLocation Loc)
EmitLoadOfLValue - Given an expression that represents a value lvalue, this method emits the address ...
@ TCK_ConstructorCall
Checking the 'this' pointer for a constructor call.
@ TCK_MemberCall
Checking the 'this' pointer for a call to a non-static member function.
void setCurrentProfileCount(uint64_t Count)
Set the profiler's current count.
void EmitIgnoredExpr(const Expr *E)
EmitIgnoredExpr - Emit an expression in a context which ignores the result.
void PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize, std::initializer_list< llvm::Value ** > ValuesToReload={})
Takes the old cleanup stack size and emits the cleanup blocks that have been added.
llvm::Type * ConvertTypeForMem(QualType T)
const Decl * CurCodeDecl
CurCodeDecl - This is the inner-most code context, which includes blocks.
llvm::AssertingVH< llvm::Instruction > AllocaInsertPt
AllocaInsertPoint - This is an instruction in the entry block before which we prefer to insert alloca...
bool AlwaysEmitXRayCustomEvents() const
AlwaysEmitXRayCustomEvents - Return true if we must unconditionally emit XRay custom event handling c...
JumpDest ReturnBlock
ReturnBlock - Unified return block.
void EmitVarAnnotations(const VarDecl *D, llvm::Value *V)
Emit local annotations for the local variable V, declared by D.
llvm::Value * EmitPointerAuthSign(const CGPointerAuthInfo &Info, llvm::Value *Pointer)
static const Expr * stripCond(const Expr *C)
Ignore parentheses and logical-NOT to track conditions consistently.
PeepholeProtection protectFromPeepholes(RValue rvalue)
protectFromPeepholes - Protect a value that we're intending to store to the side, but which will prob...
const TargetInfo & getTarget() const
llvm::DebugLoc SourceLocToDebugLoc(SourceLocation Location)
Converts Location to a DebugLoc, if debug information is enabled.
void EmitFunctionProlog(const CGFunctionInfo &FI, llvm::Function *Fn, const FunctionArgList &Args)
EmitFunctionProlog - Emit the target specific LLVM code to load the arguments for the given function.
Address EmitPointerWithAlignment(const Expr *Addr, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
EmitPointerWithAlignment - Given an expression with a pointer type, emit the value and compute our be...
void EmitX86MultiVersionResolver(llvm::Function *Resolver, ArrayRef< FMVResolverOption > Options)
void EmitCheck(ArrayRef< std::pair< llvm::Value *, SanitizerMask > > Checked, SanitizerHandler Check, ArrayRef< llvm::Constant * > StaticArgs, ArrayRef< llvm::Value * > DynamicArgs)
Create a basic block that will either trap or call a handler function in the UBSan runtime with the p...
llvm::Value * EmitRISCVCpuInit()
void EmitBlockWithFallThrough(llvm::BasicBlock *BB, const Stmt *S)
bool ShouldSkipSanitizerInstrumentation()
ShouldSkipSanitizerInstrumentation - Return true if the current function should not be instrumented w...
uint64_t getCurrentProfileCount()
Get the profiler's current count.
SmallVector< const BinaryOperator *, 16 > MCDCLogOpStack
Stack to track the Logical Operator recursion nest for MC/DC.
void StartFunction(GlobalDecl GD, QualType RetTy, llvm::Function *Fn, const CGFunctionInfo &FnInfo, const FunctionArgList &Args, SourceLocation Loc=SourceLocation(), SourceLocation StartLoc=SourceLocation())
Emit code for the start of a function.
bool HaveInsertPoint() const
HaveInsertPoint - True if an insertion point is defined.
llvm::Constant * EmitCheckSourceLocation(SourceLocation Loc)
Emit a description of a source location in a format suitable for passing to a runtime sanitizer handl...
void markAsIgnoreThreadCheckingAtRuntime(llvm::Function *Fn)
Annotate the function with an attribute that disables TSan checking at runtime.
void ErrorUnsupported(const Stmt *S, const char *Type)
ErrorUnsupported - Print out an error that codegen doesn't support the specified stmt yet.
CGDebugInfo * getDebugInfo()
Address EmitVAListRef(const Expr *E)
void EmitBranch(llvm::BasicBlock *Block)
EmitBranch - Emit a branch to the specified basic block from the current insert block,...
void maybeCreateMCDCCondBitmap()
Allocate a temp value on the stack that MCDC can use to track condition results.
SmallVector< llvm::IntrinsicInst *, 4 > ConvergenceTokenStack
Stack to track the controlled convergence tokens.
void emitAlignmentAssumption(llvm::Value *PtrValue, QualType Ty, SourceLocation Loc, SourceLocation AssumptionLoc, llvm::Value *Alignment, llvm::Value *OffsetValue=nullptr)
llvm::Value * emitBoolVecConversion(llvm::Value *SrcVec, unsigned NumElementsDst, const llvm::Twine &Name="")
LValue MakeNaturalAlignRawAddrLValue(llvm::Value *V, QualType T)
bool ShouldXRayInstrumentFunction() const
ShouldXRayInstrument - Return true if the current function should be instrumented with XRay nop sleds...
void EmitStartEHSpec(const Decl *D)
EmitStartEHSpec - Emit the start of the exception spec.
llvm::Value * EmitCheckValue(llvm::Value *V)
Convert a value into a format suitable for passing to a runtime sanitizer handler.
VlaSizePair getVLAElements1D(const VariableArrayType *vla)
Return the number of elements for a single dimension for the given array type.
bool AlwaysEmitXRayTypedEvents() const
AlwaysEmitXRayTypedEvents - Return true if clang must unconditionally emit XRay typed event handling ...
void EmitConstructorBody(FunctionArgList &Args)
void SetFastMathFlags(FPOptions FPFeatures)
Set the codegen fast-math flags.
ASTContext & getContext() const
const Decl * CurFuncDecl
CurFuncDecl - Holds the Decl for the current outermost non-closure context.
void maybeUpdateMCDCCondBitmap(const Expr *E, llvm::Value *Val)
Update the MCDC temp value with the condition's evaluated result.
void checkTargetFeatures(const CallExpr *E, const FunctionDecl *TargetDecl)
void EmitLambdaInAllocaCallOpBody(const CXXMethodDecl *MD)
llvm::SmallVector< char, 256 > LifetimeExtendedCleanupStack
void EmitDeclRefExprDbgValue(const DeclRefExpr *E, const APValue &Init)
void EmitCXXThrowExpr(const CXXThrowExpr *E, bool KeepInsertionPoint=true)
bool ConstantFoldsToSimpleInteger(const Expr *Cond, bool &Result, bool AllowLabels=false)
ConstantFoldsToSimpleInteger - If the specified expression does not fold to a constant,...
Address ReturnValuePointer
ReturnValuePointer - The temporary alloca to hold a pointer to sret.
llvm::ConstantInt * getUBSanFunctionTypeHash(QualType T) const
Return a type hash constant for a function instrumented by -fsanitize=function.
void EmitStmt(const Stmt *S, ArrayRef< const Attr * > Attrs={})
EmitStmt - Emit the code for the statement.
JumpDest getJumpDestForLabel(const LabelDecl *S)
getBasicBlockForLabel - Return the LLVM basicblock that the specified label maps to.
llvm::DenseMap< const ValueDecl *, FieldDecl * > LambdaCaptureFields
bool AutoreleaseResult
In ARC, whether we should autorelease the return value.
llvm::CallInst * EmitRuntimeCall(llvm::FunctionCallee callee, const Twine &name="")
llvm::Type * ConvertType(QualType T)
CodeGenTypes & getTypes() const
bool IsSanitizerScope
True if CodeGen currently emits code implementing sanitizer checks.
void EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc, LValue LV, QualType Type, SanitizerSet SkippedChecks=SanitizerSet(), llvm::Value *ArraySize=nullptr)
llvm::SmallVector< const ParmVarDecl *, 4 > FnArgs
Save Parameter Decl for coroutine.
QualType BuildFunctionArgList(GlobalDecl GD, FunctionArgList &Args)
RawAddress NormalCleanupDest
i32s containing the indexes of the cleanup destinations.
llvm::Value * EvaluateExprAsBool(const Expr *E)
EvaluateExprAsBool - Perform the usual unary conversions on the specified expression and compare the ...
Address EmitMSVAListRef(const Expr *E)
Emit a "reference" to a __builtin_ms_va_list; this is always the value of the expression,...
VarBypassDetector Bypasses
EHScopeStack::stable_iterator PrologueCleanupDepth
PrologueCleanupDepth - The cleanup depth enclosing all the cleanups associated with the parameters.
static bool mightAddDeclToScope(const Stmt *S)
Determine if the given statement might introduce a declaration into the current scope,...
uint64_t getProfileCount(const Stmt *S)
Get the profiler's count for the given statement.
RawAddress CreateIRTemp(QualType T, const Twine &Name="tmp")
CreateIRTemp - Create a temporary IR object of the given type, with appropriate alignment.
void emitImplicitAssignmentOperatorBody(FunctionArgList &Args)
LValue MakeAddrLValue(Address Addr, QualType T, AlignmentSource Source=AlignmentSource::Type)
const CGFunctionInfo * CurFnInfo
LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
void InsertHelper(llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock::iterator InsertPt) const
CGBuilder insert helper.
Address EmitFieldAnnotations(const FieldDecl *D, Address V)
Emit field annotations for the given field & value.
Address ReturnValue
ReturnValue - The temporary alloca to hold the return value.
void EnsureInsertPoint()
EnsureInsertPoint - Ensure that an insertion point is defined so that emitted IR has a place to go.
LValue MakeNaturalAlignPointeeAddrLValue(llvm::Value *V, QualType T)
Given a value of type T* that may not be to a complete object, construct an l-value with the natural ...
llvm::LLVMContext & getLLVMContext()
bool SawAsmBlock
Whether we processed a Microsoft-style asm block during CodeGen.
llvm::Value * EmitScalarExpr(const Expr *E, bool IgnoreResultAssign=false)
EmitScalarExpr - Emit the computation of the specified expression of LLVM scalar type,...
bool checkIfFunctionMustProgress()
Returns true if a function must make progress, which means the mustprogress attribute can be added.
void incrementProfileCounter(const Stmt *S, llvm::Value *StepV=nullptr)
Increment the profiler's counter for the given statement by StepV.
llvm::Value * EmitAnnotationCall(llvm::Function *AnnotationFn, llvm::Value *AnnotatedVal, StringRef AnnotationStr, SourceLocation Location, const AnnotateAttr *Attr)
Emit an annotation call (intrinsic).
llvm::BasicBlock * GetIndirectGotoBlock()
llvm::Type * convertTypeForLoadStore(QualType ASTTy, llvm::Type *LLVMTy=nullptr)
llvm::DebugLoc EmitReturnBlock()
Emit the unified return block, trying to avoid its emission when possible.
void GenerateCode(GlobalDecl GD, llvm::Function *Fn, const CGFunctionInfo &FnInfo)
LValue EmitLValueForLambdaField(const FieldDecl *Field)
static bool containsBreak(const Stmt *S)
containsBreak - Return true if the statement contains a break out of it.
This class organizes the cross-function state that is used while generating LLVM code.
CGHLSLRuntime & getHLSLRuntime()
Return a reference to the configured HLSL runtime.
llvm::Constant * EmitAnnotationArgs(const AnnotateAttr *Attr)
Emit additional args of the annotation.
llvm::Module & getModule() const
DiagnosticsEngine & getDiags() const
void ErrorUnsupported(const Stmt *S, const char *Type)
Print out an error that codegen doesn't support the specified stmt yet.
const LangOptions & getLangOpts() const
CGCUDARuntime & getCUDARuntime()
Return a reference to the configured CUDA runtime.
llvm::Constant * EmitAnnotationLineNo(SourceLocation L)
Emit the annotation line number.
CharUnits getNaturalTypeAlignment(QualType T, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr, bool forPointeeType=false)
CodeGenTypes & getTypes()
const llvm::DataLayout & getDataLayout() const
bool shouldEmitConvergenceTokens() const
CGCXXABI & getCXXABI() const
CGOpenMPRuntime & getOpenMPRuntime()
Return a reference to the configured OpenMP runtime.
bool imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc, StringRef Category=StringRef()) const
Imbue XRay attributes to a function, applying the always/never attribute lists in the process.
ProfileList::ExclusionType isFunctionBlockedFromProfileInstr(llvm::Function *Fn, SourceLocation Loc) const
ASTContext & getContext() const
llvm::SanitizerStatReport & getSanStats()
llvm::Constant * EmitAnnotationString(StringRef Str)
Emit an annotation string.
const TargetCodeGenInfo & getTargetCodeGenInfo()
const CodeGenOptions & getCodeGenOpts() const
llvm::LLVMContext & getLLVMContext()
void GenKernelArgMetadata(llvm::Function *FN, const FunctionDecl *FD=nullptr, CodeGenFunction *CGF=nullptr)
OpenCL v1.2 s5.6.4.6 allows the compiler to store kernel argument information in the program executab...
llvm::Function * getIntrinsic(unsigned IID, ArrayRef< llvm::Type * > Tys={})
llvm::Constant * EmitNullConstant(QualType T)
Return the result of value-initializing the given type, i.e.
llvm::ConstantInt * CreateKCFITypeId(QualType T)
Generate a KCFI type identifier for T.
bool MayDropFunctionReturn(const ASTContext &Context, QualType ReturnType) const
Whether this function's return type has no side effects, and thus may be trivially discarded if it is...
llvm::Constant * EmitAnnotationUnit(SourceLocation Loc)
Emit the annotation's translation unit.
llvm::ConstantInt * getSize(CharUnits numChars)
Emit the given number of characters as a value of type size_t.
void assignRegionCounters(GlobalDecl GD, llvm::Function *Fn)
Assign counters to regions and configure them for PGO of a given function.
llvm::Type * ConvertType(QualType T)
ConvertType - Convert type T into a llvm::Type.
bool inheritingCtorHasParams(const InheritedConstructor &Inherited, CXXCtorType Type)
Determine if a C++ inheriting constructor should have parameters matching those of its inherited cons...
llvm::Type * convertTypeForLoadStore(QualType T, llvm::Type *LLVMTy=nullptr)
Given that T is a scalar type, return the IR type that should be used for load and store operations.
llvm::Type * ConvertTypeForMem(QualType T)
ConvertTypeForMem - Convert type T into a llvm::Type.
bool isZeroInitializable(QualType T)
IsZeroInitializable - Return whether a type can be zero-initialized (in the C++ sense) with an LLVM z...
stable_iterator stable_begin() const
Create a stable reference to the top of the EH stack.
bool containsOnlyLifetimeMarkers(stable_iterator Old) const
bool empty() const
Determines whether the exception-scopes stack is empty.
FunctionArgList - Type for representing both the decl and type of parameters to a function.
LValue - This represents an lvalue references.
llvm::Value * getPointer(CodeGenFunction &CGF) const
Address getAddress() const
void InsertHelper(llvm::Instruction *I) const
Function called by the CodeGenFunction when an instruction is created.
RValue - This trivial value class is used to represent the result of an expression that is evaluated.
llvm::Value * getScalarVal() const
getScalarVal() - Return the Value* of this scalar value.
llvm::Value * getPointer() const
virtual void checkFunctionABI(CodeGenModule &CGM, const FunctionDecl *Decl) const
Any further codegen related checks that need to be done on a function signature in a target specific ...
virtual llvm::Constant * getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const
Return a constant used by UBSan as a signature to identify functions possessing type information,...
void Init(const Stmt *Body)
Clear the object and pre-process for the given statement, usually function body statement.
CompoundStmt - This represents a group of statements like { stmt stmt }.
ConditionalOperator - The ?: ternary operator.
A reference to a declared variable, function, enum, etc.
Decl - This represents one declaration (or definition), e.g.
ASTContext & getASTContext() const LLVM_READONLY
Decl * getNonClosureContext()
Find the innermost non-closure ancestor of this declaration, walking up through blocks,...
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
SourceLocation getLocation() const
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
This represents one expression.
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer,...
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Returns the set of floating point options that apply to this expression.
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc=nullptr) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
ExtVectorType - Extended vector type.
LangOptions::FPExceptionModeKind getExceptionMode() const
bool allowFPContractAcrossStatement() const
RoundingMode getRoundingMode() const
Represents a member of a struct/union/class.
Represents a function declaration or definition.
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
bool UsesFPIntrin() const
Determine whether the function was declared in source context that requires constrained FP intrinsics...
bool usesSEHTry() const
Indicates the function uses __try.
QualType getReturnType() const
ArrayRef< ParmVarDecl * > parameters() const
FunctionDecl * getTemplateInstantiationPattern(bool ForDefinition=true) const
Retrieve the function declaration from which this function could be instantiated, if it is an instant...
FunctionEffectsRef getFunctionEffects() const
bool isMSVCRTEntryPoint() const
Determines whether this function is a MSVCRT user defined entry point.
bool isInlineBuiltinDeclaration() const
Determine if this function provides an inline implementation of a builtin.
bool hasImplicitReturnZero() const
Whether falling off this function implicitly returns null/zero.
bool isMain() const
Determines whether this function is "main", which is the entry point into an executable program.
bool isDefaulted() const
Whether this function is defaulted.
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Represents a prototype with parameter type info, e.g.
GlobalDecl - represents a global declaration.
CXXCtorType getCtorType() const
const Decl * getDecl() const
One of these records is kept for each identifier that is lexed.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
static ImplicitParamDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, ImplicitParamKind ParamKind)
Create implicit parameter.
Represents the declaration of a label.
FPExceptionModeKind
Possible floating point exception behavior.
@ FPE_Strict
Strictly preserve the floating-point exception semantics.
@ FPE_MayTrap
Transformations do not cause new exceptions but may hide some.
@ FPE_Ignore
Assume that floating-point exceptions are masked.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
SanitizerSet Sanitize
Set of enabled sanitizers.
RoundingMode getDefaultRoundingMode() const
virtual void mangleCanonicalTypeName(QualType T, raw_ostream &, bool NormalizeIntegers=false)=0
Generates a unique string for an externally visible type for use with TBAA or type uniquing.
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Represents a parameter to a function.
ParsedAttr - Represents a syntactic attribute.
PointerType - C99 6.7.5.1 - Pointer Declarators.
@ Forbid
Profiling is forbidden using the noprofile attribute.
@ Skip
Profiling is skipped using the skipprofile attribute.
@ Allow
Profiling is allowed.
A (possibly-)qualified type.
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
field_range fields() const
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
decl_type * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
Encodes a location in the source.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
Stmt - This represents one statement.
StmtClass getStmtClass() const
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Likelihood
The likelihood of a branch being taken.
@ LH_Unlikely
Branch has the [[unlikely]] attribute.
@ LH_None
No attribute set or branches of the IfStmt have the same attribute.
@ LH_Likely
Branch has the [[likely]] attribute.
SourceLocation getBeginLoc() const LLVM_READONLY
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
bool supportsIFunc() const
Identify whether this target supports IFuncs.
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
virtual ParsedTargetAttr parseTargetAttr(StringRef Str) const
virtual std::optional< std::pair< unsigned, unsigned > > getVScaleRange(const LangOptions &LangOpts) const
Returns target-specific min and max values VScale_Range.
The base class of the type hierarchy.
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
bool isPointerType() const
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
TypeClass getTypeClass() const
const T * getAs() const
Member-template getAs<specific type>'.
bool isRecordType() const
bool isObjCRetainableType() const
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
bool isFunctionNoProtoType() const
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Represents a variable declaration or definition.
Represents a C array with a specified size that is not an integer-constant-expression.
Expr * getSizeExpr() const
QualType getElementType() const
Defines the clang::TargetInfo interface.
bool evaluateRequiredTargetFeatures(llvm::StringRef RequiredFatures, const llvm::StringMap< bool > &TargetFetureMap)
Returns true if the required target features of a builtin function are enabled.
TypeEvaluationKind
The kind of evaluation to perform on values of a particular type.
constexpr XRayInstrMask Typed
constexpr XRayInstrMask FunctionExit
constexpr XRayInstrMask FunctionEntry
constexpr XRayInstrMask Custom
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const AstTypeMatcher< ArrayType > arrayType
Matches all kinds of arrays.
bool Zero(InterpState &S, CodePtr OpPC)
The JSON file list parser is used to communicate input to InstallAPI.
@ NonNull
Values of this type can never be null.
bool isLambdaCallOperator(const CXXMethodDecl *MD)
@ Result
The result type of a method or function.
const FunctionProtoType * T
llvm::fp::ExceptionBehavior ToConstrainedExceptMD(LangOptions::FPExceptionModeKind Kind)
@ Other
Other implicit parameter.
@ EST_None
no exception specification
@ Implicit
An implicit conversion.
Diagnostic wrappers for TextAPI types for error reporting.
cl::opt< bool > EnableSingleByteCoverage
llvm::BasicBlock * getBlock() const
This structure provides a set of types that are commonly used during IR emission.
llvm::PointerType * ConstGlobalsPtrTy
void* in the address space for constant globals
llvm::IntegerType * Int8Ty
i8, i16, i32, and i64
llvm::IntegerType * SizeTy
llvm::IntegerType * Int32Ty
llvm::IntegerType * IntPtrTy
llvm::PointerType * Int8PtrTy
CharUnits getPointerAlign() const
EvalResult is a struct with detailed info about an evaluated expression.
A FunctionEffect plus a potential boolean expression determining whether the effect is declared (e....
Contains information gathered from parsing the contents of TargetAttr.
std::vector< std::string > Features
bool ReturnAddresses
Should return addresses be authenticated?
bool AArch64JumpTableHardening
Use hardened lowering for jump-table dispatch?
PointerAuthSchema FunctionPointers
The ABI for C function pointers.
bool AuthTraps
Do authentication failures cause a trap?
bool IndirectGotos
Do indirect goto label addresses need to be authenticated?
void set(SanitizerMask K, bool Value)
Enable or disable a certain (single) sanitizer.
bool has(SanitizerMask K) const
Check if a certain (single) sanitizer is enabled.
SanitizerMask Mask
Bitmask of enabled sanitizers.
bool hasOneOf(SanitizerMask K) const
Check if one or more sanitizers are enabled.
bool has(XRayInstrMask K) const