46#include "llvm/ADT/STLExtras.h"
47#include "llvm/ADT/ScopeExit.h"
48#include "llvm/ADT/StringExtras.h"
49#include "llvm/IR/Constants.h"
50#include "llvm/IR/DataLayout.h"
51#include "llvm/IR/Intrinsics.h"
52#include "llvm/IR/IntrinsicsWebAssembly.h"
53#include "llvm/IR/LLVMContext.h"
54#include "llvm/IR/MDBuilder.h"
55#include "llvm/IR/MatrixBuilder.h"
56#include "llvm/Support/ConvertUTF.h"
57#include "llvm/Support/Endian.h"
58#include "llvm/Support/MathExtras.h"
59#include "llvm/Support/Path.h"
60#include "llvm/Support/SaveAndRestore.h"
61#include "llvm/Support/xxhash.h"
62#include "llvm/Transforms/Utils/SanitizerStats.h"
93#define SANITIZER_CHECK(Enum, Name, Version, Msg) \
94 case SanitizerHandler::Enum: \
99 llvm_unreachable(
"unhandled switch case");
107 llvm::Value *ArraySize) {
109 auto Alloca =
Builder.CreateStructuredAlloca(Ty, Name);
120 llvm::Value *ArraySize) {
130 llvm::IRBuilderBase::InsertPointGuard IPG(Builder);
145 llvm::Value *ArraySize,
149 *AllocaAddr = Alloca;
150 return MaybeCastStackAddressSpace(Alloca, DestLangAS, ArraySize);
158 llvm::Value *ArraySize) {
159 llvm::AllocaInst *Alloca;
161 Alloca =
Builder.CreateAlloca(Ty, ArraySize, Name);
164 new llvm::AllocaInst(Ty,
CGM.getDataLayout().getAllocaAddrSpace(),
166 if (
SanOpts.Mask & SanitizerKind::Address) {
167 Alloca->addAnnotationMetadata({
"alloca_name_altered", Name.str()});
170 Allocas->Add(Alloca);
207 auto *ArrayElementTy = ArrayTy->getElementType();
208 auto ArrayElements = ArrayTy->getNumElements();
211 ArrayElementTy = VectorTy->getElementType();
212 ArrayElements *= VectorTy->getNumElements();
214 auto *VectorTy = llvm::FixedVectorType::get(ArrayElementTy, ArrayElements);
237 PGO->setCurrentStmt(E);
240 return CGM.getCXXABI().EmitMemberPointerIsNotNull(*
this, MemPtr, MPT);
263 if (
const auto *CondOp = dyn_cast<AbstractConditionalOperator>(
286 if (!ignoreResult && aggSlot.
isIgnored())
291 llvm_unreachable(
"bad evaluation kind");
333 llvm_unreachable(
"bad evaluation kind");
356 llvm_unreachable(
"bad evaluation kind");
396 bool Precise = isa_and_nonnull<VarDecl>(VD) &&
397 VD->
hasAttr<ObjCPreciseLifetimeAttr>();
418 llvm_unreachable(
"temporary cannot have dynamic storage duration");
420 llvm_unreachable(
"unknown storage duration");
430 if (
const auto *ClassDecl =
434 ReferenceTemporaryDtor = ClassDecl->getDestructor();
436 if (!ReferenceTemporaryDtor)
441 bool CanRegisterDestructor =
446 llvm::FunctionCallee CleanupFn;
447 llvm::Constant *CleanupArg;
453 CleanupArg = llvm::Constant::getNullValue(CGF.
Int8PtrTy);
470 llvm_unreachable(
"temporary cannot have dynamic storage duration");
492 auto *GV =
new llvm::GlobalVariable(
494 llvm::GlobalValue::PrivateLinkage,
Init,
".ref.tmp",
nullptr,
495 llvm::GlobalValue::NotThreadLocal,
499 llvm::Constant *
C = GV;
506 return RawAddress(
C, GV->getValueType(), alignment);
515 llvm_unreachable(
"temporary can't have dynamic storage duration");
517 llvm_unreachable(
"unknown storage duration");
526 "Reference should never be pseudo-strong!");
534 if (
auto *Var = dyn_cast<llvm::GlobalVariable>(
Object.getPointer())) {
544 if (Var->hasInitializer())
547 Var->setInitializer(
CGM.EmitNullConstant(E->
getType()));
553 default: llvm_unreachable(
"expected scalar or aggregate expression");
576 for (
const auto &Ignored : CommaLHSs)
579 if (
const auto *opaque = dyn_cast<OpaqueValueExpr>(E)) {
580 if (opaque->getType()->isRecordType()) {
581 assert(Adjustments.empty());
589 if (
auto *Var = dyn_cast<llvm::GlobalVariable>(
590 Object.getPointer()->stripPointerCasts())) {
596 if (!Var->hasInitializer()) {
597 Var->setInitializer(
CGM.EmitNullConstant(E->
getType()));
618 if (!ShouldEmitLifetimeMarkers)
629 CGBuilderTy::InsertPoint OldIP;
631 ((!
SanOpts.has(SanitizerKind::HWAddress) &&
632 !
SanOpts.has(SanitizerKind::Memory) &&
633 !
SanOpts.has(SanitizerKind::MemtagStack) &&
634 !
CGM.getCodeGenOpts().SanitizeAddressUseAfterScope) ||
636 OldConditional = OutermostConditional;
637 OutermostConditional =
nullptr;
648 if (OldConditional) {
649 OutermostConditional = OldConditional;
666 switch (Adjustment.Kind) {
670 Adjustment.DerivedToBase.BasePath->path_begin(),
671 Adjustment.DerivedToBase.BasePath->path_end(),
679 "materialized temporary field is not a simple lvalue");
687 E,
Object, Ptr, Adjustment.Ptr.MPT,
true);
720 const llvm::Constant *Elts) {
728 Builder.CreateMul(Ptr, Builder.getInt64(0xbf58476d1ce4e5b9u));
730 Builder.CreateXor(A0, Builder.CreateLShr(A0, Builder.getInt64(31)));
731 return Builder.CreateXor(Acc, A1);
748 return SanOpts.has(SanitizerKind::Null) ||
749 SanOpts.has(SanitizerKind::Alignment) ||
750 SanOpts.has(SanitizerKind::ObjectSize) ||
751 SanOpts.has(SanitizerKind::Vptr);
758 llvm::Value *ArraySize) {
765 if (Ptr->getType()->getPointerAddressSpace())
776 auto PtrToAlloca = dyn_cast<llvm::AllocaInst>(Ptr->stripPointerCasts());
778 llvm::Value *IsNonNull =
nullptr;
779 bool IsGuaranteedNonNull =
780 SkippedChecks.
has(SanitizerKind::Null) || PtrToAlloca;
782 llvm::BasicBlock *Done =
nullptr;
783 bool DoneViaNullSanitize =
false;
786 auto CheckHandler = SanitizerHandler::TypeMismatch;
788 {SanitizerKind::SO_Null,
789 SanitizerKind::SO_ObjectSize,
790 SanitizerKind::SO_Alignment},
798 if ((
SanOpts.has(SanitizerKind::Null) || AllowNullPointers) &&
799 !IsGuaranteedNonNull) {
801 IsNonNull =
Builder.CreateIsNotNull(Ptr);
805 IsGuaranteedNonNull = IsNonNull ==
True;
808 if (!IsGuaranteedNonNull) {
809 if (AllowNullPointers) {
813 DoneViaNullSanitize =
true;
815 Builder.CreateCondBr(IsNonNull, Rest, Done);
818 Checks.push_back(std::make_pair(IsNonNull, SanitizerKind::SO_Null));
823 if (
SanOpts.has(SanitizerKind::ObjectSize) &&
824 !SkippedChecks.
has(SanitizerKind::ObjectSize) &&
826 uint64_t TySize =
CGM.getMinimumObjectSize(Ty).getQuantity();
827 llvm::Value *Size = llvm::ConstantInt::get(
IntPtrTy, TySize);
829 Size =
Builder.CreateMul(Size, ArraySize);
832 llvm::Constant *ConstantSize = dyn_cast<llvm::Constant>(Size);
833 if (!ConstantSize || !ConstantSize->isNullValue()) {
840 llvm::Function *F =
CGM.getIntrinsic(llvm::Intrinsic::objectsize, Tys);
842 llvm::Value *NullIsUnknown =
Builder.getFalse();
843 llvm::Value *Dynamic =
Builder.getFalse();
844 llvm::Value *LargeEnough =
Builder.CreateICmpUGE(
845 Builder.CreateCall(F, {Ptr, Min, NullIsUnknown, Dynamic}), Size);
847 std::make_pair(LargeEnough, SanitizerKind::SO_ObjectSize));
851 llvm::MaybeAlign AlignVal;
852 llvm::Value *PtrAsInt =
nullptr;
854 if (
SanOpts.has(SanitizerKind::Alignment) &&
855 !SkippedChecks.
has(SanitizerKind::Alignment)) {
858 AlignVal =
CGM.getNaturalTypeAlignment(Ty,
nullptr,
nullptr,
863 if (AlignVal && *AlignVal > llvm::Align(1) &&
864 (!PtrToAlloca || PtrToAlloca->getAlign() < *AlignVal)) {
866 llvm::Value *Align =
Builder.CreateAnd(
867 PtrAsInt, llvm::ConstantInt::get(
IntPtrTy, AlignVal->value() - 1));
868 llvm::Value *Aligned =
872 std::make_pair(Aligned, SanitizerKind::SO_Alignment));
876 if (Checks.size() > 0) {
877 llvm::Constant *StaticData[] = {
879 llvm::ConstantInt::get(
Int8Ty, AlignVal ? llvm::Log2(*AlignVal) : 1),
880 llvm::ConstantInt::get(
Int8Ty, TCK)};
881 EmitCheck(Checks, CheckHandler, StaticData, PtrAsInt ? PtrAsInt : Ptr);
893 if (
SanOpts.has(SanitizerKind::Vptr) &&
896 SanitizerHandler::DynamicTypeCacheMiss);
900 if (!IsGuaranteedNonNull) {
902 IsNonNull =
Builder.CreateIsNotNull(Ptr);
906 Builder.CreateCondBr(IsNonNull, VptrNotNull, Done);
912 llvm::raw_svector_ostream Out(MangledName);
917 if (!
CGM.getContext().getNoSanitizeList().containsType(SanitizerKind::Vptr,
920 llvm::Value *TypeHash =
921 llvm::ConstantInt::get(
Int64Ty, xxh3_64bits(Out.str()));
935 const int CacheSize = 128;
936 llvm::Type *HashTable = llvm::ArrayType::get(
IntPtrTy, CacheSize);
937 llvm::Value *
Cache =
CGM.CreateRuntimeVariable(HashTable,
938 "__ubsan_vptr_type_cache");
939 llvm::Value *Slot =
Builder.CreateAnd(Hash,
942 llvm::Value *Indices[] = {
Builder.getInt32(0), Slot };
943 llvm::Value *CacheVal =
Builder.CreateAlignedLoad(
951 llvm::Value *EqualHash =
Builder.CreateICmpEQ(CacheVal, Hash);
952 llvm::Constant *StaticData[] = {
956 llvm::ConstantInt::get(
Int8Ty, TCK)
958 llvm::Value *DynamicData[] = { Ptr, Hash };
959 EmitCheck(std::make_pair(EqualHash, SanitizerKind::SO_Vptr),
960 SanitizerHandler::DynamicTypeCacheMiss, StaticData,
968 {DoneViaNullSanitize ? SanitizerKind::SO_Null : SanitizerKind::SO_Vptr},
969 DoneViaNullSanitize ? SanitizerHandler::TypeMismatch
970 : SanitizerHandler::DynamicTypeCacheMiss);
979 uint64_t EltSize =
C.getTypeSizeInChars(EltTy).getQuantity();
987 auto *ParamDecl = dyn_cast<ParmVarDecl>(ArrayDeclRef->getDecl());
991 auto *POSAttr = ParamDecl->getAttr<PassObjectSizeAttr>();
996 int POSType = POSAttr->getType();
997 if (POSType != 0 && POSType != 1)
1001 auto PassedSizeIt = SizeArguments.find(ParamDecl);
1002 if (PassedSizeIt == SizeArguments.end())
1006 assert(LocalDeclMap.count(PassedSizeDecl) &&
"Passed size not loadable");
1007 Address AddrOfSize = LocalDeclMap.find(PassedSizeDecl)->second;
1010 llvm::Value *SizeOfElement =
1011 llvm::ConstantInt::get(SizeInBytes->getType(), EltSize);
1012 return Builder.CreateUDiv(SizeInBytes, SizeOfElement);
1021 StrictFlexArraysLevel) {
1024 IndexedType =
Base->getType();
1025 return CGF.
Builder.getInt32(VT->getNumElements());
1030 if (
const auto *CE = dyn_cast<CastExpr>(
Base)) {
1031 if (CE->getCastKind() == CK_ArrayToPointerDecay &&
1032 !CE->getSubExpr()->isFlexibleArrayMemberLike(CGF.
getContext(),
1033 StrictFlexArraysLevel)) {
1036 IndexedType = CE->getSubExpr()->getType();
1038 if (
const auto *CAT = dyn_cast<ConstantArrayType>(AT))
1039 return CGF.
Builder.getInt(CAT->getSize());
1041 if (
const auto *VAT = dyn_cast<VariableArrayType>(AT))
1049 QualType EltTy{
Base->getType()->getPointeeOrArrayElementType(), 0};
1051 IndexedType =
Base->getType();
1092class StructAccessBase
1093 :
public ConstStmtVisitor<StructAccessBase, const Expr *> {
1097 const FieldDecl *CountDecl;
1102 bool IsExpectedRecordDecl(
const Expr *E)
const {
1111 StructAccessBase(
const FieldDecl *CountDecl) : CountDecl(CountDecl) {}
1130 const Expr *Visit(
const Expr *E) {
1131 return ConstStmtVisitor<StructAccessBase, const Expr *>::Visit(E);
1134 const Expr *VisitStmt(
const Stmt *S) {
return nullptr; }
1149 const Expr *VisitDeclRefExpr(
const DeclRefExpr *E) {
1150 return IsExpectedRecordDecl(E) ? E :
nullptr;
1152 const Expr *VisitMemberExpr(
const MemberExpr *E) {
1153 if (IsExpectedRecordDecl(E) && E->
isArrow())
1155 const Expr *Res = Visit(E->
getBase());
1156 return !Res && IsExpectedRecordDecl(E) ? E : Res;
1158 const Expr *VisitCompoundLiteralExpr(
const CompoundLiteralExpr *E) {
1159 return IsExpectedRecordDecl(E) ? E :
nullptr;
1161 const Expr *VisitCallExpr(
const CallExpr *E) {
1162 return IsExpectedRecordDecl(E) ? E :
nullptr;
1165 const Expr *VisitArraySubscriptExpr(
const ArraySubscriptExpr *E) {
1166 if (IsExpectedRecordDecl(E))
1170 const Expr *VisitCastExpr(
const CastExpr *E) {
1172 return IsExpectedRecordDecl(E) ? E :
nullptr;
1175 const Expr *VisitParenExpr(
const ParenExpr *E) {
1178 const Expr *VisitUnaryAddrOf(
const UnaryOperator *E) {
1181 const Expr *VisitUnaryDeref(
const UnaryOperator *E) {
1193 unsigned FieldNo = 0;
1222 const Expr *StructBase = StructAccessBase(CountDecl).Visit(
Base);
1244 llvm::Value *Res =
nullptr;
1249 Res =
Addr.emitRawPointer(*
this);
1250 }
else if (StructBase->
isLValue()) {
1253 Res =
Addr.emitRawPointer(*
this);
1258 return Builder.CreateInBoundsGEP(
1280 const Expr *ArrayExprBase,
1281 llvm::Value *IndexVal,
QualType IndexType,
1283 assert(
SanOpts.has(SanitizerKind::ArrayBounds) &&
1284 "should not be called unless adding bounds checks");
1289 *
this, ArrayExprBase, ArrayExprBaseType, StrictFlexArraysLevel);
1292 BoundsVal,
getContext().getSizeType(), Accessed);
1297 llvm::Value *IndexVal,
1299 llvm::Value *BoundsVal,
1300 QualType BoundsType,
bool Accessed) {
1304 auto CheckKind = SanitizerKind::SO_ArrayBounds;
1305 auto CheckHandler = SanitizerHandler::OutOfBounds;
1317 llvm::Value *IndexInst =
Builder.CreateIntCast(IndexVal, Ty, IndexSigned);
1318 llvm::Value *BoundsInst =
Builder.CreateIntCast(BoundsVal, Ty,
false);
1320 llvm::Constant *StaticData[] = {
1326 llvm::Value *Check = Accessed ?
Builder.CreateICmpULT(IndexInst, BoundsInst)
1327 :
Builder.CreateICmpULE(IndexInst, BoundsInst);
1332 BoundsVal, llvm::ConstantInt::get(BoundsVal->getType(), 0));
1336 EmitCheck(std::make_pair(Check, CheckKind), CheckHandler, StaticData,
1345 const auto *ND = dyn_cast_if_present<NamedDecl>(D);
1355 llvm::raw_svector_ostream OS(Name);
1356 ND->printQualifiedName(OS, Policy);
1361 std::optional<llvm::AllocTokenMetadata> ATMD;
1365 const llvm::AllocTokenMode Mode =
1367 if (Mode == llvm::AllocTokenMode::TypeFuncHash ||
1368 Mode == llvm::AllocTokenMode::TypeFuncHashPointerSplit) {
1373 ATMD = llvm::AllocTokenMetadata{{},
false};
1383 auto *TypeNameMD = MDB.createString(ATMD->TypeName);
1384 auto *ContainsPtrC =
Builder.getInt1(ATMD->ContainsPointer);
1385 auto *ContainsPtrMD = MDB.createConstant(ContainsPtrC);
1389 if (ATMD->FunctionName)
1390 Ops.push_back(MDB.createString(*ATMD->FunctionName));
1391 return llvm::MDNode::get(
CGM.getLLVMContext(), Ops);
1395 assert(
SanOpts.has(SanitizerKind::AllocToken) &&
1396 "Only needed with -fsanitize=alloc-token");
1397 CB->setMetadata(llvm::LLVMContext::MD_alloc_token,
1407 assert(
SanOpts.has(SanitizerKind::AllocToken) &&
1408 "Only needed with -fsanitize=alloc-token");
1410 CB->setMetadata(llvm::LLVMContext::MD_alloc_token, MDN);
1415 bool isInc,
bool isPre) {
1418 llvm::Value *NextVal;
1420 uint64_t AmountVal = isInc ? 1 : -1;
1421 NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal,
true);
1424 NextVal =
Builder.CreateAdd(InVal.first, NextVal, isInc ?
"inc" :
"dec");
1427 llvm::APFloat FVal(
getContext().getFloatTypeSemantics(ElemTy), 1);
1433 NextVal =
Builder.CreateFAdd(InVal.first, NextVal, isInc ?
"inc" :
"dec");
1441 CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(*
this,
1446 return isPre ? IncVal : InVal;
1456 DI->EmitExplicitCastType(E->
getType());
1467 if (
auto *constantIdx = dyn_cast<llvm::ConstantInt>(idx)) {
1468 CharUnits offset = constantIdx->getZExtValue() * eltSize;
1482 assert(BO->
isAdditiveOp() &&
"Expect an addition or subtraction.");
1485 bool isSubtraction = BO->
getOpcode() == BO_Sub;
1488 llvm::Value *
index =
nullptr;
1492 std::swap(pointerOperand, indexOperand);
1504 BO, pointerOperand, pointer, indexOperand,
index, isSubtraction);
1511 nullptr, IsKnownNonNull);
1524 if (
const CastExpr *CE = dyn_cast<CastExpr>(E)) {
1525 if (
const auto *ECE = dyn_cast<ExplicitCastExpr>(CE))
1528 switch (CE->getCastKind()) {
1532 case CK_AddressSpaceConversion:
1533 if (
auto PtrTy = CE->getSubExpr()->getType()->getAs<
PointerType>()) {
1534 if (PtrTy->getPointeeType()->isVoidType())
1540 CE->getSubExpr(), &InnerBaseInfo, &InnerTBAAInfo, IsKnownNonNull);
1541 if (BaseInfo) *BaseInfo = InnerBaseInfo;
1542 if (TBAAInfo) *TBAAInfo = InnerTBAAInfo;
1548 E->
getType(), &TargetTypeBaseInfo, &TargetTypeTBAAInfo);
1556 BaseInfo->mergeForCast(TargetTypeBaseInfo);
1557 Addr.setAlignment(Align);
1561 if (CGF.
SanOpts.
has(SanitizerKind::CFIUnrelatedCast) &&
1562 CE->getCastKind() == CK_BitCast) {
1570 llvm::Type *ElemTy =
1572 Addr =
Addr.withElementType(ElemTy);
1573 if (CE->getCastKind() == CK_AddressSpaceConversion)
1583 case CK_ArrayToPointerDecay:
1587 case CK_UncheckedDerivedToBase:
1588 case CK_DerivedToBase: {
1595 CE->getSubExpr(), BaseInfo,
nullptr,
1597 CE->getCastKind() == CK_UncheckedDerivedToBase));
1598 auto Derived = CE->getSubExpr()->
getType()->getPointeeCXXRecordDecl();
1600 Addr, Derived, CE->path_begin(), CE->path_end(),
1613 if (UO->getOpcode() == UO_AddrOf) {
1614 LValue LV = CGF.
EmitLValue(UO->getSubExpr(), IsKnownNonNull);
1615 if (BaseInfo) *BaseInfo = LV.getBaseInfo();
1616 if (TBAAInfo) *TBAAInfo = LV.getTBAAInfo();
1617 return LV.getAddress();
1622 if (
auto *
Call = dyn_cast<CallExpr>(E)) {
1623 switch (
Call->getBuiltinCallee()) {
1626 case Builtin::BIaddressof:
1627 case Builtin::BI__addressof:
1628 case Builtin::BI__builtin_addressof: {
1630 if (BaseInfo) *BaseInfo = LV.getBaseInfo();
1631 if (TBAAInfo) *TBAAInfo = LV.getTBAAInfo();
1632 return LV.getAddress();
1638 if (
auto *BO = dyn_cast<BinaryOperator>(E)) {
1639 if (BO->isAdditiveOp())
1648 true, BaseInfo, TBAAInfo, IsKnownNonNull);
1658 if (IsKnownNonNull && !
Addr.isKnownNonNull())
1659 Addr.setKnownNonNull();
1666 return CGM.getCXXABI().EmitMemberPointerIsNotNull(*
this,
V, MPT);
1667 return Builder.CreateICmpNE(
V, llvm::Constant::getNullValue(
V->getType()));
1678 llvm::Value *
U = llvm::UndefValue::get(EltTy);
1693 llvm_unreachable(
"bad evaluation kind");
1718 if (
const auto *CE = dyn_cast<CastExpr>(
Base)) {
1719 Base = CE->getSubExpr();
1720 }
else if (
const auto *PE = dyn_cast<ParenExpr>(
Base)) {
1721 Base = PE->getSubExpr();
1722 }
else if (
const auto *UO = dyn_cast<UnaryOperator>(
Base)) {
1723 if (UO->getOpcode() == UO_Extension)
1724 Base = UO->getSubExpr();
1742 if (
const auto *ME = dyn_cast<MemberExpr>(E)) {
1745 SkippedChecks.
set(SanitizerKind::Alignment,
true);
1747 SkippedChecks.
set(SanitizerKind::Null,
true);
1774 CGM.runWithSufficientStackSpace(
1775 E->
getExprLoc(), [&] { LV = EmitLValueHelper(E, IsKnownNonNull); });
1782LValue CodeGenFunction::EmitLValueHelper(
const Expr *E,
1788 case Expr::ObjCPropertyRefExprClass:
1789 llvm_unreachable(
"cannot emit a property reference directly");
1791 case Expr::ObjCSelectorExprClass:
1793 case Expr::ObjCIsaExprClass:
1795 case Expr::BinaryOperatorClass:
1797 case Expr::CompoundAssignOperatorClass: {
1800 Ty = AT->getValueType();
1805 case Expr::CallExprClass:
1806 case Expr::CXXMemberCallExprClass:
1807 case Expr::CXXOperatorCallExprClass:
1808 case Expr::UserDefinedLiteralClass:
1810 case Expr::CXXRewrittenBinaryOperatorClass:
1813 case Expr::VAArgExprClass:
1815 case Expr::DeclRefExprClass:
1817 case Expr::ConstantExprClass: {
1823 case Expr::ParenExprClass:
1825 case Expr::GenericSelectionExprClass:
1828 case Expr::PredefinedExprClass:
1830 case Expr::StringLiteralClass:
1832 case Expr::ObjCEncodeExprClass:
1834 case Expr::PseudoObjectExprClass:
1836 case Expr::InitListExprClass:
1838 case Expr::CXXTemporaryObjectExprClass:
1839 case Expr::CXXConstructExprClass:
1841 case Expr::CXXBindTemporaryExprClass:
1843 case Expr::CXXUuidofExprClass:
1845 case Expr::LambdaExprClass:
1848 case Expr::ExprWithCleanupsClass: {
1850 RunCleanupsScope
Scope(*
this);
1851 LValue LV =
EmitLValue(cleanups->getSubExpr(), IsKnownNonNull);
1852 if (LV.isSimple()) {
1856 llvm::Value *
V =
Addr.getBasePointer();
1857 Scope.ForceCleanup({&
V});
1858 Addr.replaceBasePointer(
V);
1860 LV.getBaseInfo(), LV.getTBAAInfo());
1867 case Expr::CXXDefaultArgExprClass: {
1870 return EmitLValue(DAE->getExpr(), IsKnownNonNull);
1872 case Expr::CXXDefaultInitExprClass: {
1875 return EmitLValue(DIE->getExpr(), IsKnownNonNull);
1877 case Expr::CXXTypeidExprClass:
1880 case Expr::ObjCMessageExprClass:
1882 case Expr::ObjCIvarRefExprClass:
1884 case Expr::StmtExprClass:
1886 case Expr::UnaryOperatorClass:
1888 case Expr::ArraySubscriptExprClass:
1890 case Expr::MatrixSingleSubscriptExprClass:
1892 case Expr::MatrixSubscriptExprClass:
1894 case Expr::ArraySectionExprClass:
1896 case Expr::ExtVectorElementExprClass:
1898 case Expr::MatrixElementExprClass:
1900 case Expr::CXXThisExprClass:
1902 case Expr::MemberExprClass:
1904 case Expr::CompoundLiteralExprClass:
1906 case Expr::ConditionalOperatorClass:
1908 case Expr::BinaryConditionalOperatorClass:
1910 case Expr::ChooseExprClass:
1912 case Expr::OpaqueValueExprClass:
1914 case Expr::SubstNonTypeTemplateParmExprClass:
1917 case Expr::ImplicitCastExprClass:
1918 case Expr::CStyleCastExprClass:
1919 case Expr::CXXFunctionalCastExprClass:
1920 case Expr::CXXStaticCastExprClass:
1921 case Expr::CXXDynamicCastExprClass:
1922 case Expr::CXXReinterpretCastExprClass:
1923 case Expr::CXXConstCastExprClass:
1924 case Expr::CXXAddrspaceCastExprClass:
1925 case Expr::ObjCBridgedCastExprClass:
1928 case Expr::MaterializeTemporaryExprClass:
1931 case Expr::CoawaitExprClass:
1933 case Expr::CoyieldExprClass:
1935 case Expr::PackIndexingExprClass:
1937 case Expr::HLSLOutArgExprClass:
1938 llvm_unreachable(
"cannot emit a HLSL out argument directly");
1956 }
else if (
const auto *var = dyn_cast<VarDecl>(
Value)) {
1967 bool resultIsReference;
1973 resultIsReference =
false;
1979 resultIsReference =
true;
2000 auto *MD = dyn_cast_or_null<CXXMethodDecl>(
CurCodeDecl);
2001 if (
isLambdaMethod(MD) && MD->getOverloadedOperator() == OO_Call) {
2004 if (
const VarDecl *VD = dyn_cast<const VarDecl>(D)) {
2005 if (!VD->hasAttr<CUDADeviceAttr>()) {
2028 if (resultIsReference)
2055 assert(
Constant &&
"not a constant");
2078 llvm::APInt &End,
bool StrictEnums,
bool StrictBool,
2081 bool IsRegularCPlusPlusEnum =
2082 CGF.
getLangOpts().CPlusPlus && StrictEnums && ED && !ED->isFixed();
2083 if (!IsBool && !IsRegularCPlusPlusEnum)
2092 ED->getValueRange(End,
Min);
2097llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) {
2098 llvm::APInt
Min, End;
2100 bool StrictBoolEnabled =
CGM.getCodeGenOpts().getLoadBoolFromMem() ==
2103 CGM.getCodeGenOpts().StrictEnums,
2104 StrictBoolEnabled, IsBool))
2108 return MDHelper.createRange(
Min, End);
2116 }
else if (
CGM.getCodeGenOpts().isOptimizedBuild()) {
2117 if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty)) {
2118 Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
2119 Load->setMetadata(llvm::LLVMContext::MD_noundef,
2120 llvm::MDNode::get(
CGM.getLLVMContext(), {}));
2127 bool HasBoolCheck =
SanOpts.has(SanitizerKind::Bool);
2128 bool HasEnumCheck =
SanOpts.has(SanitizerKind::Enum);
2129 if (!HasBoolCheck && !HasEnumCheck)
2134 bool NeedsBoolCheck = HasBoolCheck && IsBool;
2136 if (!NeedsBoolCheck && !NeedsEnumCheck)
2146 if (NeedsEnumCheck &&
2147 getContext().isTypeIgnoredBySanitizer(SanitizerKind::Enum, Ty))
2150 llvm::APInt
Min, End;
2156 NeedsEnumCheck ? SanitizerKind::SO_Enum : SanitizerKind::SO_Bool;
2159 auto CheckHandler = SanitizerHandler::LoadInvalidValue;
2164 Check =
Builder.CreateICmpULE(
Value, llvm::ConstantInt::get(Ctx, End));
2166 llvm::Value *Upper =
2167 Builder.CreateICmpSLE(
Value, llvm::ConstantInt::get(Ctx, End));
2168 llvm::Value *Lower =
2170 Check =
Builder.CreateAnd(Upper, Lower);
2174 EmitCheck(std::make_pair(Check, Kind), CheckHandler, StaticArgs,
Value);
2183 bool isNontemporal) {
2184 if (
auto *GV = dyn_cast<llvm::GlobalValue>(
Addr.getBasePointer()))
2185 if (GV->isThreadLocal())
2191 if (ClangVecTy->isPackedVectorBoolType(
getContext())) {
2193 unsigned ValNumElems =
2196 auto *RawIntV =
Builder.CreateLoad(
Addr, Volatile,
"load_bits");
2197 const auto *RawIntTy = RawIntV->getType();
2198 assert(RawIntTy->isIntegerTy() &&
"compressed iN storage for bitvectors");
2200 auto *PaddedVecTy = llvm::FixedVectorType::get(
2201 Builder.getInt1Ty(), RawIntTy->getPrimitiveSizeInBits());
2202 llvm::Value *
V =
Builder.CreateBitCast(RawIntV, PaddedVecTy);
2215 if (VTy != NewVecTy) {
2217 llvm::Value *
V =
Builder.CreateLoad(Cast, Volatile,
"loadVecN");
2218 unsigned OldNumElements = VTy->getNumElements();
2220 std::iota(Mask.begin(), Mask.end(), 0);
2221 V =
Builder.CreateShuffleVector(
V, Mask,
"extractVec");
2236 llvm::LoadInst *Load =
Builder.CreateLoad(
Addr, Volatile);
2237 if (isNontemporal) {
2238 llvm::MDNode *Node = llvm::MDNode::get(
2239 Load->getContext(), llvm::ConstantAsMetadata::get(
Builder.getInt32(1)));
2240 Load->setMetadata(llvm::LLVMContext::MD_nontemporal, Node);
2243 CGM.DecorateInstructionWithTBAA(Load, TBAAInfo);
2255 Ty = AtomicTy->getValueType();
2263 if (StoreTy->isVectorTy() && StoreTy->getScalarSizeInBits() >
2268 unsigned MemNumElems = StoreTy->getPrimitiveSizeInBits();
2289 Ty = AtomicTy->getValueType();
2295 auto *PaddedVecTy = llvm::FixedVectorType::get(
2296 Builder.getInt1Ty(), RawIntTy->getPrimitiveSizeInBits());
2307 if (HasBoolRep &&
CGM.getCodeGenOpts().isConvertingBoolWithCmp0()) {
2321 bool IsVector =
true) {
2322 auto *ArrayTy = dyn_cast<llvm::ArrayType>(
Addr.getElementType());
2323 if (ArrayTy && IsVector) {
2324 auto ArrayElements = ArrayTy->getNumElements();
2325 auto *ArrayElementTy = ArrayTy->getElementType();
2328 ArrayElementTy = VectorTy->getElementType();
2329 ArrayElements *= VectorTy->getNumElements();
2331 auto *VectorTy = llvm::FixedVectorType::get(ArrayElementTy, ArrayElements);
2333 return Addr.withElementType(VectorTy);
2335 auto *VectorTy = dyn_cast<llvm::VectorType>(
Addr.getElementType());
2336 if (VectorTy && !IsVector) {
2337 auto *ArrayTy = llvm::ArrayType::get(
2338 VectorTy->getElementType(),
2341 return Addr.withElementType(ArrayTy);
2355 llvm::MatrixBuilder MB(CGF.
Builder);
2356 value = MB.CreateColumnMajorToRowMajorTransform(
2357 value, MatrixTy->getNumRows(), MatrixTy->getNumColumns());
2360 value->getType()->isVectorTy());
2362 lvalue.getBaseInfo(), lvalue.getTBAAInfo(), isInit,
2363 lvalue.isNontemporal());
2372 "Result must be a Constant Matrix");
2394 for (uint32_t &Idx : Indices) {
2396 unsigned Row = Idx / NumCols;
2397 unsigned Col = Idx % NumCols;
2399 Idx = MT->getColumnMajorFlattenedIndex(Row, Col);
2403 if (
Base.isSimple()) {
2407 MatAddr =
CGM.getHLSLRuntime().createBufferMatrixTempAddress(
Base, *
this);
2409 llvm::Constant *CV =
2412 CV, ResultType,
Base.getBaseInfo(),
2415 assert(
Base.isExtVectorElt() &&
"Can only subscript lvalue vec elts here!");
2417 llvm::Constant *BaseElts =
Base.getExtVectorElts();
2420 for (
unsigned Index : Indices)
2421 CElts.push_back(BaseElts->getAggregateElement(Index));
2422 llvm::Constant *CV = llvm::ConstantVector::get(CElts);
2433 bool isInit,
bool isNontemporal) {
2434 if (
auto *GV = dyn_cast<llvm::GlobalValue>(
Addr.getBasePointer()))
2435 if (GV->isThreadLocal())
2443 if (
auto *VecTy = dyn_cast<llvm::FixedVectorType>(SrcTy)) {
2445 CGM.getABIInfo().getOptimalVectorMemoryType(VecTy,
getLangOpts());
2446 if (!ClangVecTy->isPackedVectorBoolType(
getContext()) &&
2447 VecTy != NewVecTy) {
2449 VecTy->getNumElements());
2450 std::iota(Mask.begin(), Mask.begin() + VecTy->getNumElements(), 0);
2454 Mask,
"extractVec");
2457 if (
Addr.getElementType() != SrcTy)
2458 Addr =
Addr.withElementType(SrcTy);
2475 if (isNontemporal) {
2476 llvm::MDNode *Node =
2477 llvm::MDNode::get(Store->getContext(),
2478 llvm::ConstantAsMetadata::get(
Builder.getInt32(1)));
2479 Store->setMetadata(llvm::LLVMContext::MD_nontemporal, Node);
2482 CGM.DecorateInstructionWithTBAA(Store, TBAAInfo);
2501 assert(LV.getType()->isConstantMatrixType());
2511 LV.setAddress(
Addr);
2516 llvm::MatrixBuilder MB(CGF.
Builder);
2517 Value = MB.CreateRowMajorToColumnMajorTransform(
2518 Value, MatrixTy->getNumRows(), MatrixTy->getNumColumns());
2535 llvm_unreachable(
"bad evaluation kind");
2601 EltTy = MatTy->getElementType();
2602 if (
CGM.getCodeGenOpts().isOptimizedBuild()) {
2603 llvm::MatrixBuilder MB(
Builder);
2604 MB.CreateIndexAssumption(Idx, MatTy->getNumElementsFlattened());
2607 llvm::LoadInst *Load =
2609 llvm::Value *Elt =
Builder.CreateExtractElement(Load, Idx,
"matrixext");
2618 unsigned NumLanes = NumCols;
2622 llvm::Constant *ColConstsIndices =
nullptr;
2623 llvm::MatrixBuilder MB(
Builder);
2627 NumLanes = llvm::cast<llvm::FixedVectorType>(ColConstsIndices->getType())
2631 llvm::Type *RowTy = llvm::FixedVectorType::get(ElemTy, NumLanes);
2632 llvm::Value *
Result = llvm::PoisonValue::get(RowTy);
2634 for (
unsigned Col = 0; Col < NumLanes; ++Col) {
2635 llvm::Value *ColIdx;
2636 if (ColConstsIndices)
2637 ColIdx = ColConstsIndices->getAggregateElement(Col);
2639 ColIdx = llvm::ConstantInt::get(Row->getType(), Col);
2641 llvm::Value *EltIndex =
2642 MB.CreateIndex(Row, ColIdx, NumRows, NumCols, IsMatrixRowMajor);
2643 llvm::Value *Elt =
Builder.CreateExtractElement(MatrixVec, EltIndex);
2644 llvm::Value *Lane = llvm::ConstantInt::get(
Builder.getInt32Ty(), Col);
2651 assert(LV.
isBitField() &&
"Unknown LValue type!");
2670 const unsigned StorageSize =
2673 assert(
static_cast<unsigned>(Offset + Info.
Size) <= StorageSize);
2674 unsigned HighBits = StorageSize - Offset - Info.
Size;
2676 Val =
Builder.CreateShl(Val, HighBits,
"bf.shl");
2677 if (Offset + HighBits)
2678 Val =
Builder.CreateAShr(Val, Offset + HighBits,
"bf.ashr");
2681 Val =
Builder.CreateLShr(Val, Offset,
"bf.lshr");
2682 if (
static_cast<unsigned>(Offset) + Info.
Size < StorageSize)
2684 Val, llvm::APInt::getLowBitsSet(StorageSize, Info.
Size),
"bf.clear");
2700 llvm::Type *DstTy = llvm::FixedVectorType::get(Vec->getType(), 1);
2701 llvm::Value *
Zero = llvm::Constant::getNullValue(
CGM.Int64Ty);
2702 Vec =
Builder.CreateInsertElement(DstTy, Vec,
Zero,
"cast.splat");
2712 llvm::Value *Elt = llvm::ConstantInt::get(
SizeTy, InIdx);
2714 llvm::Value *Element =
Builder.CreateExtractElement(Vec, Elt);
2717 if (Element->getType()->getPrimitiveSizeInBits() >
2718 LVTy->getPrimitiveSizeInBits()) {
2720 CGM.getCodeGenOpts().isConvertingBoolWithCmp0())
2721 Element =
Builder.CreateICmpNE(
2722 Element, llvm::Constant::getNullValue(Element->getType()));
2724 Element =
Builder.CreateTrunc(Element, LVTy);
2734 for (
unsigned i = 0; i != NumResultElts; ++i)
2737 Vec =
Builder.CreateShuffleVector(Vec, Mask);
2740 if (
CGM.getCodeGenOpts().isConvertingBoolWithCmp0())
2741 Vec =
Builder.CreateICmpNE(Vec,
2742 llvm::Constant::getNullValue(Vec->getType()));
2754 llvm::Type *VectorElementTy =
CGM.getTypes().ConvertType(EQT);
2762 Builder.CreateConstInBoundsGEP(CastToPointerElement, ix,
2765 return VectorBasePtrPlusIx;
2771 "Bad type for register variable");
2776 llvm::Type *OrigTy =
CGM.getTypes().ConvertType(LV.
getType());
2777 llvm::Type *Ty = OrigTy;
2778 if (OrigTy->isPointerTy())
2779 Ty =
CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
2780 llvm::Type *Types[] = { Ty };
2782 llvm::Function *F =
CGM.getIntrinsic(llvm::Intrinsic::read_register, Types);
2784 F, llvm::MetadataAsValue::get(Ty->getContext(), RegName));
2785 if (OrigTy->isPointerTy())
2803 llvm::Type *ElemTy = DestAddrTy->getScalarType();
2805 CGM.getDataLayout().getPrefTypeAlign(ElemTy));
2807 assert(ElemTy->getScalarSizeInBits() >= 8 &&
2808 "vector element type must be at least byte-sized");
2811 if (Val->getType()->getPrimitiveSizeInBits() <
2812 ElemTy->getScalarSizeInBits())
2813 Val =
Builder.CreateZExt(Val, ElemTy->getScalarType());
2816 llvm::Value *
Zero = llvm::ConstantInt::get(
Int32Ty, 0);
2818 Builder.CreateGEP(DstAddr, {
Zero, Idx}, DestAddrTy, ElemAlign);
2826 llvm::Type *VecTy = Vec->getType();
2829 if (VecTy->isVectorTy() && SrcVal->getType()->getPrimitiveSizeInBits() <
2830 VecTy->getScalarSizeInBits())
2831 SrcVal =
Builder.CreateZExt(SrcVal, VecTy->getScalarType());
2833 auto *IRStoreTy = dyn_cast<llvm::IntegerType>(Vec->getType());
2835 auto *IRVecTy = llvm::FixedVectorType::get(
2836 Builder.getInt1Ty(), IRStoreTy->getPrimitiveSizeInBits());
2837 Vec =
Builder.CreateBitCast(Vec, IRVecTy);
2844 if (
auto *EltTy = dyn_cast<llvm::FixedVectorType>(SrcVal->getType());
2845 EltTy && EltTy->getNumElements() == 1)
2846 SrcVal =
Builder.CreateBitCast(SrcVal, EltTy->getElementType());
2852 Vec =
Builder.CreateBitCast(Vec, IRStoreTy);
2876 llvm::Type *ElemTy = DestAddrTy->getScalarType();
2878 CGM.getDataLayout().getPrefTypeAlign(ElemTy));
2880 assert(ElemTy->getScalarSizeInBits() >= 8 &&
2881 "matrix element type must be at least byte-sized");
2884 if (Val->getType()->getPrimitiveSizeInBits() <
2885 ElemTy->getScalarSizeInBits())
2886 Val =
Builder.CreateZExt(Val, ElemTy->getScalarType());
2889 llvm::Value *
Zero = llvm::ConstantInt::get(
Int32Ty, 0);
2891 Builder.CreateGEP(DstAddr, {
Zero, Idx}, DestAddrTy, ElemAlign);
2897 if (
CGM.getCodeGenOpts().isOptimizedBuild()) {
2899 llvm::MatrixBuilder MB(
Builder);
2900 MB.CreateIndexAssumption(Idx, MatTy->getNumElementsFlattened());
2905 Builder.CreateInsertElement(Load, InsertVal, Idx,
"matins");
2916 "Store through matrix row LValues is only implemented for HLSL!");
2922 unsigned NumLanes = NumCols;
2926 llvm::Type *ElemTy = DestAddrTy->getScalarType();
2930 assert(ElemTy->getScalarSizeInBits() >= 8 &&
2931 "matrix element type must be at least byte-sized");
2934 if (RowVal->getType()->getScalarType()->getPrimitiveSizeInBits() <
2935 ElemTy->getScalarSizeInBits()) {
2937 llvm::Type *StorageElmTy = llvm::FixedVectorType::get(
2938 ElemTy->getScalarType(), RowValVecTy->getNumElements());
2939 RowVal =
Builder.CreateZExt(RowVal, StorageElmTy);
2942 llvm::MatrixBuilder MB(
Builder);
2944 llvm::Constant *ColConstsIndices =
nullptr;
2948 llvm::cast<llvm::FixedVectorType>(ColConstsIndices->getType())
2953 for (
unsigned Col = 0; Col < NumLanes; ++Col) {
2954 llvm::Value *ColIdx;
2955 if (ColConstsIndices)
2956 ColIdx = ColConstsIndices->getAggregateElement(Col);
2958 ColIdx = llvm::ConstantInt::get(Row->getType(), Col);
2960 llvm::Value *EltIndex =
2961 MB.CreateIndex(Row, ColIdx, NumRows, NumCols, IsMatrixRowMajor);
2962 llvm::Value *Lane = llvm::ConstantInt::get(
Builder.getInt32Ty(), Col);
2963 llvm::Value *
Zero = llvm::ConstantInt::get(
Int32Ty, 0);
2964 llvm::Value *NewElt =
Builder.CreateExtractElement(RowVal, Lane);
2966 Builder.CreateGEP(DstAddr, {
Zero, EltIndex}, DestAddrTy, ElemAlign);
2973 assert(Dst.
isBitField() &&
"Unknown LValue type");
2988 llvm_unreachable(
"present but none");
3023 CGM.getObjCRuntime().EmitObjCWeakAssign(*
this, src, LvalueDst);
3036 RHS =
Builder.CreatePtrToInt(RHS, ResultType,
"sub.ptr.rhs.cast");
3038 ResultType,
"sub.ptr.lhs.cast");
3039 llvm::Value *BytesBetween =
Builder.CreateSub(LHS, RHS,
"ivar.offset");
3040 CGM.getObjCRuntime().EmitObjCIvarAssign(*
this, src, dst, BytesBetween);
3042 CGM.getObjCRuntime().EmitObjCGlobalAssign(*
this, src, LvalueDst,
3046 CGM.getObjCRuntime().EmitObjCStrongCastAssign(*
this, src, LvalueDst);
3050 assert(Src.
isScalar() &&
"Can't emit an agg store with this method");
3064 SrcVal =
Builder.CreateIntCast(SrcVal, Ptr.getElementType(),
3066 llvm::Value *MaskedVal = SrcVal;
3068 const bool UseVolatile =
3071 const unsigned StorageSize =
3076 if (StorageSize != Info.
Size) {
3077 assert(StorageSize > Info.
Size &&
"Invalid bitfield size.");
3084 SrcVal, llvm::APInt::getLowBitsSet(StorageSize, Info.
Size),
3088 SrcVal =
Builder.CreateShl(SrcVal, Offset,
"bf.shl");
3092 Val, ~llvm::APInt::getBitsSet(StorageSize, Offset, Offset + Info.
Size),
3096 SrcVal =
Builder.CreateOr(Val, SrcVal,
"bf.set");
3098 assert(Offset == 0);
3105 CGM.getCodeGenOpts().ForceAAPCSBitfieldLoad)
3106 Builder.CreateLoad(Ptr,
true,
"bf.load");
3115 llvm::Value *ResultVal = MaskedVal;
3119 assert(Info.
Size <= StorageSize);
3120 unsigned HighBits = StorageSize - Info.
Size;
3122 ResultVal =
Builder.CreateShl(ResultVal, HighBits,
"bf.result.shl");
3123 ResultVal =
Builder.CreateAShr(ResultVal, HighBits,
"bf.result.ashr");
3139 SrcVal->getType()->getScalarSizeInBits())
3148 if (!DestAddrTy->isVectorTy()) {
3150 "this should only occur for non-vector l-values");
3163 CGM.getDataLayout().getPrefTypeAlign(DestAddrTy->getScalarType()));
3164 llvm::Value *
Zero = llvm::ConstantInt::get(
Int32Ty, 0);
3166 for (
unsigned I = 0; I != NumSrcElts; ++I) {
3167 llvm::Value *Val = VTy ?
Builder.CreateExtractElement(
3168 SrcVal, llvm::ConstantInt::get(
Int32Ty, I))
3175 DstElemAddr =
Builder.CreateGEP(
3176 DstAddr, {
Zero, llvm::ConstantInt::get(
Int32Ty, FieldNo)},
3177 DestAddrTy, ElemAlign);
3186 llvm::Type *VecTy = Vec->getType();
3189 unsigned NumSrcElts = VTy->getNumElements();
3191 if (NumDstElts == NumSrcElts) {
3196 for (
unsigned i = 0; i != NumSrcElts; ++i)
3199 Vec =
Builder.CreateShuffleVector(SrcVal, Mask);
3200 }
else if (NumDstElts > NumSrcElts) {
3206 for (
unsigned i = 0; i != NumSrcElts; ++i)
3207 ExtMask.push_back(i);
3208 ExtMask.resize(NumDstElts, -1);
3209 llvm::Value *ExtSrcVal =
Builder.CreateShuffleVector(SrcVal, ExtMask);
3212 for (
unsigned i = 0; i != NumDstElts; ++i)
3222 for (
unsigned i = 0; i != NumSrcElts; ++i)
3224 Vec =
Builder.CreateShuffleVector(Vec, ExtSrcVal, Mask);
3227 llvm_unreachable(
"unexpected shorten vector length");
3233 llvm::Value *Elt = llvm::ConstantInt::get(
SizeTy, InIdx);
3235 Vec =
Builder.CreateInsertElement(Vec, SrcVal, Elt);
3245 "Bad type for register variable");
3248 assert(RegName &&
"Register LValue is not metadata");
3251 llvm::Type *OrigTy =
CGM.getTypes().ConvertType(Dst.
getType());
3252 llvm::Type *Ty = OrigTy;
3253 if (OrigTy->isPointerTy())
3254 Ty =
CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
3255 llvm::Type *Types[] = { Ty };
3257 llvm::Function *F =
CGM.getIntrinsic(llvm::Intrinsic::write_register, Types);
3259 if (OrigTy->isPointerTy())
3262 F, {llvm::MetadataAsValue::get(Ty->getContext(), RegName),
Value});
3270 bool IsMemberAccess=
false) {
3282 LV.setObjCIvar(
false);
3286 LV.setObjCIvar(
true);
3288 LV.setBaseIvarExp(Exp->getBase());
3293 if (
const auto *Exp = dyn_cast<DeclRefExpr>(E)) {
3294 if (
const auto *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
3295 if (VD->hasGlobalStorage()) {
3296 LV.setGlobalObjCRef(
true);
3304 if (
const auto *Exp = dyn_cast<UnaryOperator>(E)) {
3309 if (
const auto *Exp = dyn_cast<ParenExpr>(E)) {
3311 if (LV.isObjCIvar()) {
3318 LV.setObjCIvar(
false);
3323 if (
const auto *Exp = dyn_cast<GenericSelectionExpr>(E)) {
3328 if (
const auto *Exp = dyn_cast<ImplicitCastExpr>(E)) {
3333 if (
const auto *Exp = dyn_cast<CStyleCastExpr>(E)) {
3338 if (
const auto *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
3343 if (
const auto *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
3345 if (LV.isObjCIvar() && !LV.isObjCArray())
3348 LV.setObjCIvar(
false);
3349 else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
3352 LV.setGlobalObjCRef(
false);
3356 if (
const auto *Exp = dyn_cast<MemberExpr>(E)) {
3370 CGF, VD,
Addr, Loc);
3375 Addr =
Addr.withElementType(RealVarTy);
3381 std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
3382 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
3387 if (!Res || *Res == OMPDeclareTargetDeclAttr::MT_Local ||
3388 ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
3389 *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
3392 assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
3393 ((*Res == OMPDeclareTargetDeclAttr::MT_To ||
3394 *Res == OMPDeclareTargetDeclAttr::MT_Enter) &&
3396 "Expected link clause OR to clause with unified memory enabled.");
3406 llvm::LoadInst *Load =
3411 PTy, PointeeBaseInfo, PointeeTBAAInfo,
true);
3414 llvm::MDBuilder MDB(Ctx);
3416 if (
CGM.getTypes().getTargetAddressSpace(PTy) == 0 &&
3417 !
CGM.getCodeGenOpts().NullPointerIsValid)
3418 Load->setMetadata(llvm::LLVMContext::MD_nonnull,
3419 llvm::MDNode::get(Ctx, {}));
3425 llvm::LLVMContext::MD_align,
3426 llvm::MDNode::get(Ctx, MDB.createConstant(llvm::ConstantInt::get(
3427 Builder.getInt64Ty(), AlignVal))));
3432 true, PointeeBaseInfo,
3442 PointeeBaseInfo, PointeeTBAAInfo);
3452 BaseInfo, TBAAInfo);
3482 std::optional<LValue> LV =
3491 V = CGF.
Builder.CreateThreadLocalAddress(
V);
3499 VD->
hasAttr<OMPThreadPrivateDeclAttr>()) {
3514 if (FD->
hasAttr<WeakRefAttr>()) {
3529 if (
auto *GV = dyn_cast<llvm::GlobalValue>(
V))
3530 V = llvm::NoCFIValue::get(GV);
3537 llvm::Value *ThisValue) {
3550 AsmLabelAttr *
Asm = VD->
getAttr<AsmLabelAttr>();
3551 assert(
Asm->getLabel().size() < 64-Name.size() &&
3552 "Register name too big");
3553 Name.append(
Asm->getLabel());
3554 llvm::NamedMDNode *M =
3555 CGM.
getModule().getOrInsertNamedMetadata(Name);
3556 if (M->getNumOperands() == 0) {
3559 llvm::Metadata *Ops[] = {Str};
3566 llvm::MetadataAsValue::get(CGM.
getLLVMContext(), M->getOperand(0));
3609 case llvm::GlobalValue::ExternalLinkage:
3610 case llvm::GlobalValue::LinkOnceODRLinkage:
3611 case llvm::GlobalValue::WeakODRLinkage:
3612 case llvm::GlobalValue::InternalLinkage:
3613 case llvm::GlobalValue::PrivateLinkage:
3626 "Expected OpenMP captured region");
3627 assert(
CGM.getLangOpts().OpenMP &&
"Expected OpenMP to be enabled");
3630 It != LocalDeclMap.end())
3638 QualType DREType = DD->getType().getNonReferenceType();
3649 llvm::Type *ExpectedTy =
CGM.getTypes().ConvertTypeForMem(DDType);
3657 auto It = LocalDeclMap.find(DD);
3658 bool WasMapped = It != LocalDeclMap.end();
3661 if (DD->getType()->isReferenceType()) {
3667 It->second = MapAddr;
3669 LocalDeclMap.insert({DD, MapAddr});
3670 llvm::scope_exit Guard([&] {
3672 auto RestoreIt = LocalDeclMap.find(DD);
3673 assert(RestoreIt != LocalDeclMap.end() &&
"DD should still be in map");
3674 RestoreIt->second = SavedAddr;
3676 LocalDeclMap.erase(DD);
3688 "should not emit an unevaluated operand");
3690 if (
const auto *VD = dyn_cast<VarDecl>(ND)) {
3693 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
3701 (VD->getType()->isReferenceType() ||
3703 VD->getAnyInitializer(VD);
3705 E->
getLocation(), *VD->evaluateValue(), VD->getType());
3706 assert(Val &&
"failed to emit constant expression");
3709 if (!VD->getType()->isReferenceType()) {
3711 Addr =
CGM.createUnnamedGlobalFrom(*VD, Val,
3714 auto *PTy = llvm::PointerType::get(
3733 VD = VD->getCanonicalDecl();
3737 auto I = LocalDeclMap.find(VD);
3738 if (I != LocalDeclMap.end()) {
3740 if (VD->getType()->isReferenceType())
3748 CGM.getOpenMPRuntime().isNontemporalDecl(VD))
3765 CGM.getOpenMPRuntime().isNontemporalDecl(VD))
3781 "Should not use decl without marking it used!");
3783 if (ND->
hasAttr<WeakRefAttr>()) {
3789 if (
const auto *VD = dyn_cast<VarDecl>(ND)) {
3791 if (VD->hasLinkage() || VD->isStaticDataMember())
3797 auto iter = LocalDeclMap.find(VD);
3798 if (iter != LocalDeclMap.end()) {
3799 addr = iter->second;
3803 }
else if (VD->isStaticLocal()) {
3804 llvm::Constant *var =
CGM.getOrCreateStaticVarDecl(
3805 *VD,
CGM.getLLVMLinkageVarDefinition(VD));
3811 llvm_unreachable(
"DeclRefExpr for Decl not entered in LocalDeclMap?");
3822 VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
3829 bool isBlockByref = VD->isEscapingByref();
3835 LValue LV = VD->getType()->isReferenceType() ?
3839 bool isLocalStorage = VD->hasLocalStorage();
3841 bool NonGCable = isLocalStorage &&
3842 !VD->getType()->isReferenceType() &&
3849 bool isImpreciseLifetime =
3850 (isLocalStorage && !VD->hasAttr<ObjCPreciseLifetimeAttr>());
3851 if (isImpreciseLifetime)
3857 if (
const auto *FD = dyn_cast<FunctionDecl>(ND))
3863 if (
const auto *BD = dyn_cast<BindingDecl>(ND)) {
3865 auto ApplyNontemporal = [&](
LValue LV) {
3867 CGM.getOpenMPRuntime().isNontemporalDecl(BD))
3868 LV.setNontemporal(
true);
3873 auto It = LocalDeclMap.find(BD->getCanonicalDecl());
3874 if (It != LocalDeclMap.end()) {
3875 return ApplyNontemporal(
3882 CGM.getLangOpts().OpenMP) {
3883 auto NameIt = OMPPrivatizedBindings.find(
3885 if (NameIt != OMPPrivatizedBindings.end()) {
3907 if (
const auto *GD = dyn_cast<MSGuidDecl>(ND))
3911 if (
const auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) {
3915 if (AS != T.getAddressSpace()) {
3918 llvm::PointerType::get(
CGM.getLLVMContext(), TargetAS);
3919 llvm::Constant *ASC =
CGM.performAddrSpaceCast(ATPO.
getPointer(), PtrTy);
3926 llvm_unreachable(
"Unhandled DeclRefExpr");
3936 default: llvm_unreachable(
"Unknown unary operator lvalue!");
3939 assert(!T.isNull() &&
"CodeGenFunction::EmitUnaryOpLValue: Illegal type");
3961 assert(LV.
isSimple() &&
"real/imag on non-ordinary l-value");
3978 CGM.getTBAAInfoForSubobject(LV, T));
3985 bool isInc = E->
getOpcode() == UO_PreInc;
4008 assert(SL !=
nullptr &&
"No StringLiteral name in PredefinedExpr");
4009 StringRef FnName =
CurFn->getName();
4010 FnName.consume_front(
"\01");
4011 StringRef NameItems[] = {
4013 std::string GVName = llvm::join(NameItems, NameItems + 2,
".");
4014 if (
auto *BD = dyn_cast_or_null<BlockDecl>(
CurCodeDecl)) {
4015 std::string Name = std::string(SL->getString());
4016 if (!Name.empty()) {
4017 unsigned Discriminator =
4018 CGM.getCXXABI().getMangleContext().getBlockId(BD,
true);
4020 Name +=
"_" + Twine(Discriminator + 1).str();
4021 auto C =
CGM.GetAddrOfConstantCString(Name, GVName);
4024 auto C =
CGM.GetAddrOfConstantCString(std::string(FnName), GVName);
4028 auto C =
CGM.GetAddrOfConstantStringFromLiteral(SL, GVName);
4045 if (llvm::Constant *
C =
CGM.getTypeDescriptorFromMap(T))
4050 bool IsBitInt =
false;
4056 if (
const EnumType *ET = T->getAs<EnumType>())
4057 if (ET->getDecl()->isComplete())
4058 UnderlyingT = ET->getDecl()->getIntegerType();
4071 " non positive amount of bits in __BitInt type");
4073 " too many bits in __BitInt type");
4089 (
intptr_t)T.getAsOpaquePtr(), StringRef(),
4090 StringRef(), {}, Buffer, {});
4095 char S[6] = {
'\0',
'\0',
'\0',
'\0',
'\0',
'\0'};
4098 llvm::support::endian::write32(S + 1, Bits,
4100 ? llvm::endianness::big
4101 : llvm::endianness::little);
4102 StringRef Str = StringRef(S,
sizeof(S) /
sizeof(
decltype(S[0])));
4106 llvm::Constant *Components[] = {
4110 llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components);
4112 auto *GV =
new llvm::GlobalVariable(
4113 CGM.getModule(), Descriptor->getType(),
4114 true, llvm::GlobalVariable::PrivateLinkage, Descriptor);
4115 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4116 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(GV);
4119 CGM.setTypeDescriptorInMap(T, GV);
4127 if (
V->getType() == TargetTy)
4132 if (
V->getType()->isFloatingPointTy()) {
4133 unsigned Bits =
V->getType()->getPrimitiveSizeInBits().getFixedValue();
4134 if (Bits <= TargetTy->getIntegerBitWidth())
4140 if (
V->getType()->isIntegerTy() &&
4141 V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth())
4142 return Builder.CreateZExt(
V, TargetTy);
4145 if (!
V->getType()->isPointerTy()) {
4148 V = Ptr.getPointer();
4150 return Builder.CreatePtrToInt(
V, TargetTy);
4163 llvm::Constant *Filename;
4170 int PathComponentsToStrip =
4171 CGM.getCodeGenOpts().EmitCheckPathComponentsToStrip;
4172 if (PathComponentsToStrip < 0) {
4173 assert(PathComponentsToStrip !=
INT_MIN);
4174 int PathComponentsToKeep = -PathComponentsToStrip;
4175 auto I = llvm::sys::path::rbegin(FilenameString);
4176 auto E = llvm::sys::path::rend(FilenameString);
4177 while (I != E && --PathComponentsToKeep)
4180 FilenameString = FilenameString.substr(I - E);
4181 }
else if (PathComponentsToStrip > 0) {
4182 auto I = llvm::sys::path::begin(FilenameString);
4183 auto E = llvm::sys::path::end(FilenameString);
4184 while (I != E && PathComponentsToStrip--)
4189 FilenameString.substr(I - llvm::sys::path::begin(FilenameString));
4191 FilenameString = llvm::sys::path::filename(FilenameString);
4195 CGM.GetAddrOfConstantCString(std::string(FilenameString),
".src");
4196 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(
4198 FilenameGV.getPointer()->stripPointerCasts()));
4199 Filename = FilenameGV.getPointer();
4203 Filename = llvm::Constant::getNullValue(
Int8PtrTy);
4210 return llvm::ConstantStruct::getAnon(
Data);
4213llvm::GlobalVariable *
4215 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
4216 auto *InfoPtr =
new llvm::GlobalVariable(
4217 CGM.getModule(), Info->getType(),
4220 false, llvm::GlobalVariable::PrivateLinkage, Info,
"",
4221 nullptr, llvm::GlobalVariable::NotThreadLocal,
4222 CGM.getDataLayout().getDefaultGlobalsAddressSpace());
4223 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4224 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
4230enum class CheckRecoverableKind {
4241static CheckRecoverableKind
4243 if (Ordinal == SanitizerKind::SO_Vptr)
4244 return CheckRecoverableKind::AlwaysRecoverable;
4245 else if (Ordinal == SanitizerKind::SO_Return ||
4246 Ordinal == SanitizerKind::SO_Unreachable)
4247 return CheckRecoverableKind::Unrecoverable;
4249 return CheckRecoverableKind::Recoverable;
4253struct SanitizerHandlerInfo {
4254 char const *
const Name;
4260#define SANITIZER_CHECK(Enum, Name, Version, Msg) {#Name, Version},
4262#undef SANITIZER_CHECK
4266 llvm::FunctionType *FnType,
4269 CheckRecoverableKind RecoverKind,
bool IsFatal,
4270 llvm::BasicBlock *ContBB,
bool NoMerge) {
4271 assert(IsFatal || RecoverKind != CheckRecoverableKind::Unrecoverable);
4272 std::optional<ApplyDebugLocation> DL;
4273 if (!CGF.
Builder.getCurrentDebugLocation()) {
4277 bool NeedsAbortSuffix =
4278 IsFatal && RecoverKind != CheckRecoverableKind::Unrecoverable;
4280 bool HandlerPreserveAllRegs =
4283 const StringRef CheckName = CheckInfo.Name;
4284 std::string FnName =
"__ubsan_handle_" + CheckName.str();
4285 if (CheckInfo.Version && !MinimalRuntime)
4286 FnName +=
"_v" + llvm::utostr(CheckInfo.Version);
4288 FnName +=
"_minimal";
4289 if (NeedsAbortSuffix)
4291 if (HandlerPreserveAllRegs && !NeedsAbortSuffix)
4292 FnName +=
"_preserve";
4294 !IsFatal || RecoverKind == CheckRecoverableKind::AlwaysRecoverable;
4298 B.addAttribute(llvm::Attribute::NoReturn)
4299 .addAttribute(llvm::Attribute::NoUnwind);
4301 B.addUWTableAttr(llvm::UWTableKind::Default);
4306 llvm::AttributeList::FunctionIndex, B),
4312 HandlerCall->addFnAttr(llvm::Attribute::NoMerge);
4313 if (HandlerPreserveAllRegs && !NeedsAbortSuffix) {
4315 HandlerCall->setCallingConv(llvm::CallingConv::PreserveAll);
4318 HandlerCall->setDoesNotReturn();
4319 CGF.
Builder.CreateUnreachable();
4326 ArrayRef<std::pair<llvm::Value *, SanitizerKind::SanitizerOrdinal>> Checked,
4330 assert(Checked.size() > 0);
4331 assert(CheckHandler >= 0 &&
4335 llvm::Value *FatalCond =
nullptr;
4336 llvm::Value *RecoverableCond =
nullptr;
4337 llvm::Value *TrapCond =
nullptr;
4338 bool NoMerge =
false;
4345 for (
auto &[Check, Ord] : Checked) {
4346 llvm::Value *GuardedCheck = Check;
4347 if (
CGM.getCLOpts().ubsan_guard_checks ||
4348 (
CGM.getCodeGenOpts().SanitizeSkipHotCutoffs[Ord] > 0)) {
4350 CGM.getIntrinsic(llvm::Intrinsic::allow_ubsan_check),
4351 llvm::ConstantInt::get(
CGM.Int8Ty, Ord));
4356 llvm::Value *&Cond =
CGM.getCodeGenOpts().SanitizeTrap.has(Ord) ? TrapCond
4357 :
CGM.getCodeGenOpts().SanitizeRecover.has(Ord)
4360 Cond = Cond ?
Builder.CreateAnd(Cond, GuardedCheck) : GuardedCheck;
4362 if (!
CGM.getCodeGenOpts().SanitizeMergeHandlers.has(Ord))
4368 if (!FatalCond && !RecoverableCond)
4371 llvm::Value *JointCond;
4372 if (FatalCond && RecoverableCond)
4373 JointCond =
Builder.CreateAnd(FatalCond, RecoverableCond);
4375 JointCond = FatalCond ? FatalCond : RecoverableCond;
4379 assert(
SanOpts.has(Checked[0].second));
4381 for (
int i = 1, n = Checked.size(); i < n; ++i) {
4383 "All recoverable kinds in a single check must be same!");
4384 assert(
SanOpts.has(Checked[i].second));
4390 llvm::Instruction *Branch =
Builder.CreateCondBr(JointCond, Cont, Handlers);
4393 llvm::MDNode *Node = MDHelper.createLikelyBranchWeights();
4394 Branch->setMetadata(llvm::LLVMContext::MD_prof, Node);
4398 if (
CGM.getCodeGenOpts().SanitizeMinimalRuntime) {
4409 Args.reserve(DynamicArgs.size() + 1);
4410 ArgTypes.reserve(DynamicArgs.size() + 1);
4413 if (!StaticArgs.empty()) {
4415 Args.push_back(
Builder.CreateAddrSpaceCast(InfoPtr,
CGM.VoidPtrTy));
4416 ArgTypes.push_back(
CGM.VoidPtrTy);
4419 for (llvm::Value *DynamicArg : DynamicArgs) {
4424 llvm::FunctionType *FnType =
4425 llvm::FunctionType::get(
CGM.VoidTy, ArgTypes,
false);
4427 if (!FatalCond || !RecoverableCond) {
4431 (FatalCond !=
nullptr), Cont, NoMerge);
4435 llvm::BasicBlock *NonFatalHandlerBB =
4438 Builder.CreateCondBr(FatalCond, NonFatalHandlerBB, FatalHandlerBB);
4441 NonFatalHandlerBB, NoMerge);
4452 llvm::ConstantInt *TypeId, llvm::Value *Ptr,
4457 llvm::CondBrInst *BI =
Builder.CreateCondBr(Cond, Cont, CheckBB);
4460 llvm::MDNode *Node = MDHelper.createLikelyBranchWeights();
4461 BI->setMetadata(llvm::LLVMContext::MD_prof, Node);
4465 bool WithDiag = !
CGM.getCodeGenOpts().SanitizeTrap.has(Ordinal);
4467 llvm::CallInst *CheckCall;
4468 llvm::FunctionCallee SlowPathFn;
4472 SlowPathFn =
CGM.getModule().getOrInsertFunction(
4473 "__cfi_slowpath_diag",
4476 CheckCall =
Builder.CreateCall(
4480 SlowPathFn =
CGM.getModule().getOrInsertFunction(
4483 CheckCall =
Builder.CreateCall(SlowPathFn, {TypeId, Ptr});
4488 CheckCall->setDoesNotThrow();
4493std::array<llvm::Constant *, 3>
4497 llvm::ConstantInt::get(
Int8Ty, CheckKind),
4506 llvm::Module *M = &
CGM.getModule();
4508 QualType QInt64Ty =
C.getIntTypeForBitwidth(64,
false);
4510 auto *ArgCallsiteTypeId =
4514 auto *ArgCFICheckFailData =
4518 CGM.getTypes().arrangeBuiltinFunctionDeclaration(
C.VoidTy,
FnArgs);
4520 llvm::Function *F = llvm::Function::Create(
4522 llvm::GlobalValue::WeakAnyLinkage,
"__cfi_check", M);
4524 CGM.SetLLVMFunctionAttributesForDefinition(
nullptr, F);
4525 F->setAlignment(llvm::Align(4096));
4528 llvm::LLVMContext &Ctx = M->getContext();
4529 llvm::BasicBlock *BB = llvm::BasicBlock::Create(Ctx,
"entry", F);
4532 llvm::CallInst::Create(M->getFunction(
"__cfi_check_fail"), Args,
"", BB);
4533 llvm::ReturnInst::Create(Ctx,
nullptr, BB);
4544 auto CheckHandler = SanitizerHandler::CFICheckFail;
4551 {SanitizerKind::SO_CFIVCall, SanitizerKind::SO_CFINVCall,
4552 SanitizerKind::SO_CFIDerivedCast, SanitizerKind::SO_CFIUnrelatedCast,
4553 SanitizerKind::SO_CFIICall},
4564 llvm::Function *F = llvm::Function::Create(
4566 llvm::GlobalValue::WeakODRLinkage,
"__cfi_check_fail", &
CGM.getModule());
4569 CGM.SetLLVMFunctionAttributesForDefinition(
nullptr, F);
4570 F->setVisibility(llvm::GlobalValue::HiddenVisibility);
4584 CGM.getContext().VoidPtrTy, ArgData->getLocation());
4587 CGM.getContext().VoidPtrTy, ArgAddr->getLocation());
4590 llvm::Value *DataIsNotNullPtr =
4595 EmitTrapCheck(DataIsNotNullPtr, SanitizerHandler::CFICheckFail,
4598 llvm::StructType *SourceLocationTy =
4600 llvm::StructType *CfiCheckFailDataTy =
4603 llvm::Value *
V =
Builder.CreateConstGEP2_32(
4607 llvm::Value *CheckKind =
Builder.CreateLoad(CheckKindAddr);
4609 llvm::Value *AllVtables = llvm::MetadataAsValue::get(
4610 CGM.getLLVMContext(),
4611 llvm::MDString::get(
CGM.getLLVMContext(),
"all-vtables"));
4612 llvm::Value *ValidVtable =
Builder.CreateZExt(
4613 Builder.CreateCall(
CGM.getIntrinsic(llvm::Intrinsic::type_test),
4614 {Addr, AllVtables}),
4617 const std::pair<int, SanitizerKind::SanitizerOrdinal> CheckKinds[] = {
4624 for (
auto CheckKindOrdinalPair : CheckKinds) {
4625 int Kind = CheckKindOrdinalPair.first;
4632 Builder.CreateICmpNE(CheckKind, llvm::ConstantInt::get(
Int8Ty, Kind));
4633 if (
CGM.getLangOpts().Sanitize.has(Ordinal))
4634 EmitCheck(std::make_pair(Cond, Ordinal), SanitizerHandler::CFICheckFail,
4647 CGM.addUsedGlobal(F);
4651 if (
SanOpts.has(SanitizerKind::Unreachable)) {
4652 auto CheckOrdinal = SanitizerKind::SO_Unreachable;
4653 auto CheckHandler = SanitizerHandler::BuiltinUnreachable;
4669 if ((
int)TrapBBs.size() <= CheckHandlerID)
4670 TrapBBs.resize(CheckHandlerID + 1);
4672 llvm::BasicBlock *&TrapBB = TrapBBs[CheckHandlerID];
4674 llvm::DILocation *TrapLocation =
Builder.getCurrentDebugLocation();
4675 llvm::StringRef TrapMessage;
4676 llvm::StringRef TrapCategory;
4677 auto DebugTrapReasonKind =
CGM.getCodeGenOpts().getSanitizeDebugTrapReasons();
4679 DebugTrapReasonKind ==
4685 TrapCategory =
"Undefined Behavior Sanitizer";
4689 DebugTrapReasonKind !=
4693 TrapLocation, TrapCategory, TrapMessage);
4696 NoMerge = NoMerge || !
CGM.getCodeGenOpts().isOptimizedBuild() ||
4700 if (TrapBB && !NoMerge) {
4701 auto Call = TrapBB->begin();
4704 Call->applyMergedLocation(
Call->getDebugLoc(), TrapLocation);
4706 Builder.CreateCondBr(Checked, Cont, TrapBB,
4707 MDHelper.createLikelyBranchWeights());
4710 Builder.CreateCondBr(Checked, Cont, TrapBB,
4711 MDHelper.createLikelyBranchWeights());
4716 llvm::CallInst *TrapCall;
4717 if (
CGM.getCodeGenOpts().SanitizeTrapLoop)
4719 Builder.CreateCall(
CGM.getIntrinsic(llvm::Intrinsic::looptrap));
4721 TrapCall =
Builder.CreateCall(
4722 CGM.getIntrinsic(llvm::Intrinsic::ubsantrap),
4723 llvm::ConstantInt::get(
CGM.Int8Ty, CheckHandlerID));
4725 if (!
CGM.getCodeGenOpts().TrapFuncName.empty()) {
4726 auto A = llvm::Attribute::get(
getLLVMContext(),
"trap-func-name",
4727 CGM.getCodeGenOpts().TrapFuncName);
4728 TrapCall->addFnAttr(A);
4731 TrapCall->addFnAttr(llvm::Attribute::NoMerge);
4740 llvm::Function *TrapIntrinsic =
CGM.getIntrinsic(IntrID);
4741 llvm::CallInst *TrapCall =
Builder.CreateCall(TrapIntrinsic);
4743 if (!
CGM.getCodeGenOpts().TrapFuncName.empty()) {
4744 auto A = llvm::Attribute::get(
getLLVMContext(),
"trap-func-name",
4745 CGM.getCodeGenOpts().TrapFuncName);
4746 TrapCall->addFnAttr(A);
4750 TrapCall->addFnAttr(llvm::Attribute::NoMerge);
4751 if (TrapIntrinsic->doesNotReturn()) {
4756 Builder.ClearInsertionPoint();
4765 Builder.ClearInsertionPoint();
4773 "Array to pointer decay must have array source type!");
4782 Addr =
Addr.withElementType(NewTy);
4788 "Expected pointer to array");
4794 Builder.CreateStructuredGEP(NewTy,
Addr.emitRawPointer(*
this), {});
4808 if (TBAAInfo) *TBAAInfo =
CGM.getTBAAAccessInfo(EltType);
4817 const auto *CE = dyn_cast<CastExpr>(E);
4818 if (!CE || CE->getCastKind() != CK_ArrayToPointerDecay)
4830 llvm::Type *elemType,
4836 const llvm::Twine &name =
"arrayidx") {
4837 if (inbounds && CGF.
getLangOpts().EmitLogicalPointer)
4838 return CGF.
Builder.CreateStructuredGEP(elemType, ptr, indices);
4852 llvm::Type *elementType,
bool inbounds,
4855 const llvm::Twine &name =
"arrayidx") {
4856 if (inbounds && CGF.
getLangOpts().EmitLogicalPointer)
4859 indices.drop_front()),
4860 elementType, align);
4872 return D && D->
hasAttr<BPFPreserveStaticOffsetAttr>();
4879 if (PointeeType.
isNull())
4892 llvm::Function *Fn =
4894 llvm::CallInst *
Call = CGF.
Builder.CreateCall(Fn, {
Addr.emitRawPointer(CGF)});
4914 while (
const auto *ASE = dyn_cast<ArraySubscriptExpr>(E))
4916 if (
const auto *ME = dyn_cast<MemberExpr>(E))
4917 return ME->getMemberDecl()->hasAttr<BPFPreserveAccessIndexAttr>();
4919 if (
const auto *DRE = dyn_cast<DeclRefExpr>(E)) {
4920 const auto *VarDef = dyn_cast<VarDecl>(DRE->getDecl());
4924 const auto *PtrT = VarDef->getType()->getAs<
PointerType>();
4930 if (
const auto *RecT = dyn_cast<RecordType>(PointeeT))
4931 return RecT->getDecl()
4932 ->getMostRecentDecl()
4933 ->
hasAttr<BPFPreserveAccessIndexAttr>();
4946 const llvm::Twine &name =
"arrayidx") {
4949 for (
auto *idx : indices.drop_back())
4968 llvm::Value *eltPtr;
4969 auto LastIndex = dyn_cast<llvm::ConstantInt>(indices.back());
4976 signedIndices, loc, eltAlign, name);
4980 unsigned idx = LastIndex->getZExtValue();
4981 llvm::DIType *DbgInfo =
nullptr;
4984 eltPtr = CGF.
Builder.CreatePreserveArrayAccessIndex(
4996struct StructFieldAccess
4997 :
public ConstStmtVisitor<StructFieldAccess, const Expr *> {
4998 const Expr *VisitCastExpr(
const CastExpr *E) {
5003 const Expr *VisitParenExpr(
const ParenExpr *E) {
5023 if (FD1OuterRec != FD2OuterRec)
5025 return std::optional<int64_t>();
5029 return std::optional<int64_t>();
5033 return std::optional<int64_t>();
5035 return std::make_optional<int64_t>(FD1Offset - FD2Offset);
5044 llvm::Value *BoundsVal,
5047 assert(BoundsVal->getType()->isIntegerTy());
5048 assert(!PointeeTy.
isNull() &&
"pointee type is never null");
5050 "Sema guarantees a '__sized_by' pointee is a non-function type");
5055 assert(PointeeTy->
isVoidType() &&
"expected a 'void' incomplete pointee");
5064 unsigned CountWidth = BoundsVal->getType()->getIntegerBitWidth();
5068 CountSigned ? llvm::isIntN(CountWidth, ElemSizeQ)
5069 : llvm::isUIntN(CountWidth,
static_cast<uint64_t>(ElemSizeQ));
5074 return llvm::ConstantInt::get(BoundsVal->getType(), 0);
5076 llvm::Value *ElemSizeV =
5077 llvm::ConstantInt::get(BoundsVal->getType(), ElemSizeQ);
5082 return CountSigned ? CGF.
Builder.CreateSDiv(BoundsVal, ElemSizeV)
5083 : CGF.
Builder.CreateUDiv(BoundsVal, ElemSizeV);
5095 QualType IndexType, llvm::Value *IndexVal,
bool Accessed,
5096 bool FlexibleArray) {
5097 const auto *ME = dyn_cast<MemberExpr>(ArrayExpr->
IgnoreImpCasts());
5098 if (!ME || !ME->getMemberDecl()->getType()->isCountAttributedType())
5103 if (FlexibleArray &&
5104 !ME->isFlexibleArrayMemberLike(
getContext(), StrictFlexArraysLevel))
5112 if (std::optional<int64_t> Diff =
5131 llvm::Value *BoundsVal =
5133 Builder.getInt32(*Diff),
".counted_by.gep");
5135 ".counted_by.load");
5138 assert(CountAttributedTy &&
"expected FD to have a CountAttributedType");
5143 if (CountAttributedTy->isOrNull()) {
5146 llvm::Value *Ptr =
Builder.CreateLoad(ArrayInst);
5148 BoundsVal =
Builder.CreateSelect(
5149 IsNull, llvm::ConstantInt::get(BoundsType, 0), BoundsVal);
5156 if (CountAttributedTy->isCountInBytes())
5163 CountFD->
getType(), Accessed);
5171 llvm::Value *IdxPre =
5173 bool SignedIndices =
false;
5174 auto EmitIdxAfterBase = [&, IdxPre](
bool Promote) -> llvm::Value * {
5177 assert(E->
getRHS() == E->
getIdx() &&
"index was neither LHS nor RHS");
5183 SignedIndices |= IdxSigned;
5185 if (
SanOpts.has(SanitizerKind::ArrayBounds))
5189 if (Promote && Idx->getType() !=
IntPtrTy)
5202 auto *Idx = EmitIdxAfterBase(
false);
5203 assert(LHS.
isSimple() &&
"Can only subscript lvalue vectors here!");
5211 std::optional<LValue> LV;
5214 LV =
CGM.getHLSLRuntime().emitResourceArraySubscriptExpr(E, *
this);
5216 LV =
CGM.getHLSLRuntime().emitBufferArraySubscriptExpr(E, *
this,
5228 auto *Idx = EmitIdxAfterBase(
true);
5235 CGM.getTBAAInfoForSubobject(LV, EltType));
5247 auto *Idx = EmitIdxAfterBase(
true);
5257 Idx =
Builder.CreateMul(Idx, numElements);
5259 Idx =
Builder.CreateNSWMul(Idx, numElements);
5271 auto *Idx = EmitIdxAfterBase(
true);
5274 llvm::Value *InterfaceSizeVal =
5275 llvm::ConstantInt::get(Idx->getType(), InterfaceSize.
getQuantity());
5277 llvm::Value *ScaledIdx =
Builder.CreateMul(Idx, InterfaceSizeVal);
5283 llvm::Type *OrigBaseElemTy =
Addr.getElementType();
5288 llvm::Value *EltPtr =
5290 ScaledIdx,
false, SignedIndices, E->
getExprLoc());
5297 assert(Array->getType()->isArrayType() &&
5298 "Array to pointer decay must have array source type!");
5302 if (
const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
5306 auto *Idx = EmitIdxAfterBase(
true);
5308 if (
SanOpts.has(SanitizerKind::ArrayBounds))
5316 *
this, ArrayLV.
getAddress(), {CGM.getSize(CharUnits::Zero()), Idx},
5320 if (!
CGM.getCodeGenOpts().NewStructPathTBAA) {
5323 EltTBAAInfo =
CGM.getTBAAInfoForSubobject(ArrayLV, E->
getType());
5328 EltTBAAInfo =
CGM.getTBAAAccessInfo(E->
getType());
5349 const CastExpr *CountedByLoad =
nullptr;
5351 if (
SanOpts.has(SanitizerKind::ArrayBounds)) {
5352 StructFieldAccess Visitor;
5353 if (
const auto *CE =
5354 dyn_cast_if_present<CastExpr>(Visitor.Visit(E->
getBase()));
5355 CE && CE->getCastKind() == CK_LValueToRValue) {
5356 const auto *ME = dyn_cast<MemberExpr>(CE->
getSubExpr());
5357 if (ME && ME->getMemberDecl()->getType()->isCountAttributedType()) {
5375 CountedByME ? &FieldCapture :
nullptr);
5384 auto *Idx = EmitIdxAfterBase(
true);
5396 if (CountedByME && (CountedByFieldAddr.
isValid() ||
5429 MatAddr =
CGM.getHLSLRuntime().createBufferMatrixTempAddress(
Base, *
this);
5439 "incomplete matrix subscript expressions should be rejected during Sema");
5445 llvm::MatrixBuilder MB(
Builder);
5448 unsigned NumRows = MatrixTy->getNumRows();
5449 bool IsMatrixRowMajor =
5451 llvm::Value *FinalIdx =
5452 MB.CreateIndex(RowIdx, ColIdx, NumRows, NumCols, IsMatrixRowMajor);
5463 bool IsLowerBound) {
5465 if (
auto *ASE = dyn_cast<ArraySectionExpr>(
Base->IgnoreParenImpCasts())) {
5469 BaseInfo = BaseLVal.getBaseInfo();
5474 Addr =
Addr.withElementType(NewTy);
5480 "Expected pointer to array");
5490 BaseInfo.mergeForCast(TypeBaseInfo);
5496 dyn_cast<OMPArrayShapingExpr>(
Base->IgnoreParenImpCasts())) {
5499 QualType ShapedTy = OAShE->getShapedType();
5506 BaseInfo.mergeForCast(TypeBaseInfo);
5515 bool IsLowerBound) {
5518 "OpenACC Array section codegen not implemented");
5522 if (
auto *AT =
getContext().getAsArrayType(BaseTy))
5523 ResultExprTy = AT->getElementType();
5526 llvm::Value *Idx =
nullptr;
5534 LowerBound->getType()->hasSignedIntegerRepresentation());
5536 Idx = llvm::ConstantInt::getNullValue(
IntPtrTy);
5541 auto &
C =
CGM.getContext();
5543 llvm::APSInt ConstLength;
5546 if (std::optional<llvm::APSInt>
CL = Length->getIntegerConstantExpr(
C)) {
5553 if (std::optional<llvm::APSInt> LB =
5554 LowerBound->getIntegerConstantExpr(
C)) {
5556 LowerBound =
nullptr;
5561 else if (!LowerBound)
5564 if (Length || LowerBound) {
5565 auto *LowerBoundVal =
5569 LowerBound->getType()->hasSignedIntegerRepresentation())
5570 : llvm::ConstantInt::get(
IntPtrTy, ConstLowerBound);
5575 Length->getType()->hasSignedIntegerRepresentation())
5576 : llvm::ConstantInt::get(
IntPtrTy, ConstLength);
5577 Idx =
Builder.CreateAdd(LowerBoundVal, LengthVal,
"lb_add_len",
5580 if (Length && LowerBound) {
5582 Idx, llvm::ConstantInt::get(
IntPtrTy, 1),
"idx_sub_1",
5586 Idx = llvm::ConstantInt::get(
IntPtrTy, ConstLength + ConstLowerBound);
5592 if (
auto *VAT =
C.getAsVariableArrayType(ArrayTy)) {
5593 Length = VAT->getSizeExpr();
5594 if (std::optional<llvm::APSInt> L = Length->getIntegerConstantExpr(
C)) {
5599 auto *CAT =
C.getAsConstantArrayType(ArrayTy);
5600 assert(CAT &&
"unexpected type for array initializer");
5601 ConstLength = CAT->getSize();
5604 auto *LengthVal =
Builder.CreateIntCast(
5606 Length->getType()->hasSignedIntegerRepresentation());
5608 LengthVal, llvm::ConstantInt::get(
IntPtrTy, 1),
"len_sub_1",
5613 Idx = llvm::ConstantInt::get(
IntPtrTy, ConstLength);
5622 if (
auto *VLA =
getContext().getAsVariableArrayType(ResultExprTy)) {
5628 BaseTy, VLA->getElementType(), IsLowerBound);
5637 Idx =
Builder.CreateMul(Idx, NumElements);
5639 Idx =
Builder.CreateNSWMul(Idx, NumElements);
5648 assert(Array->getType()->isArrayType() &&
5649 "Array to pointer decay must have array source type!");
5653 if (
const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
5660 *
this, ArrayLV.
getAddress(), {CGM.getSize(CharUnits::Zero()), Idx},
5661 ResultExprTy, !
getLangOpts().PointerOverflowDefined,
5664 TBAAInfo =
CGM.getTBAAInfoForSubobject(ArrayLV, ResultExprTy);
5668 ResultExprTy, IsLowerBound);
5691 Base.getQuals().removeObjCGCAttr();
5700 "Result must be a vector");
5708 if (LTy->getScalarSizeInBits() > Vec->getType()->getScalarSizeInBits())
5709 Vec =
Builder.CreateZExt(Vec, LTy);
5710 Builder.CreateStore(Vec, VecMem);
5721 if (
Base.isSimple()) {
5722 llvm::Constant *CV =
5728 if (
Base.isMatrixRow()) {
5730 llvm::dyn_cast<llvm::ConstantInt>(
Base.getMatrixRowIdx())) {
5734 unsigned NumCols = Indices.size();
5736 unsigned Row = RowIdx->getZExtValue();
5740 QualType ElemQT = EVT->getElementType();
5743 for (
unsigned C = 0;
C < NumCols; ++
C) {
5744 unsigned Col = Indices[
C];
5745 unsigned Linear = Col * NumRows + Row;
5746 MatIndices.push_back(llvm::ConstantInt::get(
Int32Ty, Linear));
5749 llvm::Constant *ConstIdxs = llvm::ConstantVector::get(MatIndices);
5753 llvm::Constant *Cols =
5760 Base.getMatrixAddress(),
Base.getMatrixRowIdx(), Cols,
Base.getType(),
5764 assert(
Base.isExtVectorElt() &&
"Can only subscript lvalue vec elts here!");
5766 llvm::Constant *BaseElts =
Base.getExtVectorElts();
5769 for (
unsigned Index : Indices)
5770 CElts.push_back(BaseElts->getAggregateElement(Index));
5771 llvm::Constant *CV = llvm::ConstantVector::get(CElts);
5778 while (
auto *BaseMemberExpr = dyn_cast<MemberExpr>(UnderlyingBaseExpr))
5779 UnderlyingBaseExpr = BaseMemberExpr->getBase()->
IgnoreParens();
5792 return CGM.getHLSLRuntime().emitBufferMemberExpr(*
this, E);
5795 std::optional<LValue> LV;
5796 LV =
CGM.getHLSLRuntime().emitResourceMemberExpr(*
this, E);
5806 bool IsInBounds = !
getLangOpts().PointerOverflowDefined &&
5818 SkippedChecks.
set(SanitizerKind::Alignment,
true);
5820 SkippedChecks.
set(SanitizerKind::Null,
true);
5828 if (
auto *Field = dyn_cast<FieldDecl>(ND)) {
5836 CGM.getOpenMPRuntime().isNontemporalDecl(Field)) ||
5843 if (
const auto *FD = dyn_cast<FunctionDecl>(ND))
5846 llvm_unreachable(
"Unhandled member declaration!");
5853 llvm::Value *ThisValue) {
5854 bool HasExplicitObjectParameter =
false;
5855 const auto *MD = dyn_cast_if_present<CXXMethodDecl>(
CurCodeDecl);
5857 HasExplicitObjectParameter = MD->isExplicitObjectMemberFunction();
5858 assert(MD->getParent()->isLambda());
5859 assert(MD->getParent() == Field->getParent());
5862 if (HasExplicitObjectParameter) {
5864 auto It = LocalDeclMap.find(D);
5865 assert(It != LocalDeclMap.end() &&
"explicit parameter not loaded?");
5866 Address AddrOfExplicitObject = It->getSecond();
5877 if (ThisTy != LambdaTy) {
5880 LambdaLV.
getAddress(), ThisTy, BasePathArray.begin(),
5904 if (Offset.isZero())
5926 llvm::Type *StructType =
5932 {CGF.Builder.getSize(idx)}),
5947 const FieldDecl *field,
bool IsInBounds) {
5959 auto [DbgInfo, DIIndex] =
5974 if (RD->isDynamicClass())
5977 for (
const auto &
Base : RD->bases())
5997 CGM.getCodeGenOpts().AAPCSBitfieldWidth &&
6019 getContext().getCanonicalTagType(rec), field);
6027 llvm::Type *FieldIntTy = llvm::Type::getIntNTy(
getLLVMContext(), SS);
6028 Addr =
Addr.withElementType(FieldIntTy);
6063 assert(!FieldTBAAInfo.
Offset &&
6064 "Nonzero offset for an access with no base type!");
6077 FieldTBAAInfo.
Size =
6088 if (
CGM.getCodeGenOpts().StrictVTablePointers &&
6092 addr =
Builder.CreateLaunderInvariantGroup(addr);
6097 auto [DbgInfo, DIIndex] =
6133 if (field->
hasAttr<AnnotateAttr>())
6149 QualType FieldType = Field->getType();
6155 *
this,
Base.getAddress(), Field,
6160 V =
V.withElementType(llvmType);
6169 CGM.getTBAAInfoForSubobject(
Base, FieldType));
6210 assert(E->
isTransparent() &&
"non-transparent glvalue init list");
6218 const Expr *Operand) {
6219 if (
auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Operand->IgnoreParens())) {
6221 return std::nullopt;
6230std::optional<LValue> HandleConditionalOperatorLValueSimpleCase(
6232 const Expr *condExpr = E->
getCond();
6237 std::swap(Live, Dead);
6247 if (
auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Live->
IgnoreParens())) {
6258 return std::nullopt;
6260struct ConditionalInfo {
6261 llvm::BasicBlock *lhsBlock, *rhsBlock;
6262 std::optional<LValue> LHS, RHS;
6267template<
typename FuncTy>
6269 const AbstractConditionalOperator *E,
6270 const FuncTy &BranchGenFunc) {
6286 Info.lhsBlock = CGF.
Builder.GetInsertBlock();
6289 CGF.
Builder.CreateBr(endBlock);
6297 Info.rhsBlock = CGF.
Builder.GetInsertBlock();
6309 "Unexpected conditional operator!");
6314 if (HandleConditionalOperatorLValueSimpleCase(*
this, E))
6317 EmitConditionalBlocks(*
this, E, [](CodeGenFunction &CGF,
const Expr *E) {
6324 if (!
expr->isGLValue()) {
6327 "Unexpected conditional operator!");
6332 if (std::optional<LValue> Res =
6333 HandleConditionalOperatorLValueSimpleCase(*
this,
expr))
6336 ConditionalInfo Info = EmitConditionalBlocks(
6337 *
this,
expr, [](CodeGenFunction &CGF,
const Expr *E) {
6341 if ((Info.LHS && !Info.LHS->isSimple()) ||
6342 (Info.RHS && !Info.RHS->isSimple()))
6345 if (Info.LHS && Info.RHS) {
6346 Address lhsAddr = Info.LHS->getAddress();
6347 Address rhsAddr = Info.RHS->getAddress();
6349 lhsAddr, rhsAddr, Info.lhsBlock, Info.rhsBlock,
6352 std::max(Info.LHS->getBaseInfo().getAlignmentSource(),
6353 Info.RHS->getBaseInfo().getAlignmentSource());
6355 Info.LHS->getTBAAInfo(), Info.RHS->getTBAAInfo());
6359 assert((Info.LHS || Info.RHS) &&
6360 "both operands of glvalue conditional are throw-expressions?");
6361 return Info.LHS ? *Info.LHS : *Info.RHS;
6373 llvm::scope_exit RestoreCurCast([
this, Prev =
CurCast] {
CurCast = Prev; });
6378 case CK_LValueToRValueBitCast:
6379 case CK_ArrayToPointerDecay:
6380 case CK_FunctionToPointerDecay:
6381 case CK_NullToMemberPointer:
6382 case CK_NullToPointer:
6383 case CK_IntegralToPointer:
6384 case CK_PointerToIntegral:
6385 case CK_PointerToBoolean:
6386 case CK_IntegralCast:
6387 case CK_BooleanToSignedIntegral:
6388 case CK_IntegralToBoolean:
6389 case CK_IntegralToFloating:
6390 case CK_FloatingToIntegral:
6391 case CK_FloatingToBoolean:
6392 case CK_FloatingCast:
6393 case CK_FloatingRealToComplex:
6394 case CK_FloatingComplexToReal:
6395 case CK_FloatingComplexToBoolean:
6396 case CK_FloatingComplexCast:
6397 case CK_FloatingComplexToIntegralComplex:
6398 case CK_IntegralRealToComplex:
6399 case CK_IntegralComplexToReal:
6400 case CK_IntegralComplexToBoolean:
6401 case CK_IntegralComplexCast:
6402 case CK_IntegralComplexToFloatingComplex:
6403 case CK_DerivedToBaseMemberPointer:
6404 case CK_BaseToDerivedMemberPointer:
6405 case CK_MemberPointerToBoolean:
6406 case CK_ReinterpretMemberPointer:
6407 case CK_AnyPointerToBlockPointerCast:
6408 case CK_ARCProduceObject:
6409 case CK_ARCConsumeObject:
6410 case CK_ARCReclaimReturnedObject:
6411 case CK_ARCExtendBlockObject:
6412 case CK_CopyAndAutoreleaseBlockObject:
6413 case CK_IntToOCLSampler:
6414 case CK_FloatingToFixedPoint:
6415 case CK_FixedPointToFloating:
6416 case CK_FixedPointCast:
6417 case CK_FixedPointToBoolean:
6418 case CK_FixedPointToIntegral:
6419 case CK_IntegralToFixedPoint:
6421 case CK_CoopMatrixCast:
6422 case CK_HLSLVectorTruncation:
6423 case CK_HLSLMatrixTruncation:
6424 case CK_HLSLArrayRValue:
6425 case CK_HLSLElementwiseCast:
6426 case CK_HLSLAggregateSplatCast:
6430 llvm_unreachable(
"dependent cast kind in IR gen!");
6432 case CK_BuiltinFnToFnPtr:
6433 llvm_unreachable(
"builtin functions are handled elsewhere");
6436 case CK_NonAtomicToAtomic:
6437 case CK_AtomicToNonAtomic:
6447 case CK_ConstructorConversion:
6448 case CK_UserDefinedConversion:
6449 case CK_CPointerToObjCPointerCast:
6450 case CK_BlockPointerToObjCPointerCast:
6451 case CK_LValueToRValue:
6466 if (
V.getElementType() != T)
6473 case CK_UncheckedDerivedToBase:
6474 case CK_DerivedToBase: {
6488 CGM.getTBAAInfoForSubobject(LV, E->
getType()));
6492 case CK_BaseToDerived: {
6507 if (
SanOpts.has(SanitizerKind::CFIDerivedCast))
6513 CGM.getTBAAInfoForSubobject(LV, E->
getType()));
6515 case CK_LValueBitCast: {
6519 CGM.EmitExplicitCastExprType(CE,
this);
6524 if (
SanOpts.has(SanitizerKind::CFIUnrelatedCast))
6530 CGM.getTBAAInfoForSubobject(LV, E->
getType()));
6532 case CK_AddressSpaceConversion: {
6541 case CK_ObjCObjectLValueCast: {
6545 CGM.getTBAAInfoForSubobject(LV, E->
getType()));
6547 case CK_ZeroToOCLOpaqueType:
6548 llvm_unreachable(
"NULL to OpenCL opaque type lvalue cast is not valid");
6550 case CK_VectorSplat: {
6558 llvm_unreachable(
"Unhandled lvalue cast kind?");
6566std::pair<LValue, LValue>
6586 return std::make_pair(BaseLV, TempLV);
6595 llvm::Value *
Addr = TempLV.getAddress().getBasePointer();
6598 Address TmpAddr(
Addr, ElTy, TempLV.getAlignment());
6609 llvm::DenseMap<const OpaqueValueExpr*,LValue>::iterator
6610 it = OpaqueLValues.find(e);
6612 if (it != OpaqueLValues.end())
6615 assert(e->
isUnique() &&
"LValue for a nonunique OVE hasn't been emitted");
6623 llvm::DenseMap<const OpaqueValueExpr*,RValue>::iterator
6624 it = OpaqueRValues.find(e);
6626 if (it != OpaqueRValues.end())
6629 assert(e->
isUnique() &&
"RValue for a nonunique OVE hasn't been emitted");
6635 return OpaqueLValues.contains(E);
6636 return OpaqueRValues.contains(E);
6660 llvm_unreachable(
"bad evaluation kind");
6669 llvm::CallBase **CallOrInvoke) {
6670 llvm::CallBase *CallOrInvokeStorage;
6671 if (!CallOrInvoke) {
6672 CallOrInvoke = &CallOrInvokeStorage;
6675 llvm::scope_exit AddCoroElideSafeOnExit([&] {
6677 auto *I = *CallOrInvoke;
6679 I->addFnAttr(llvm::Attribute::CoroElideSafe);
6687 if (
const auto *CE = dyn_cast<CXXMemberCallExpr>(E))
6690 if (
const auto *CE = dyn_cast<CUDAKernelCallExpr>(E))
6695 if (
const auto *CE = dyn_cast<CXXOperatorCallExpr>(E))
6696 if (
const auto *MD =
6697 dyn_cast_if_present<CXXMethodDecl>(CE->getCalleeDecl());
6698 MD && MD->isImplicitObjectMemberFunction())
6713 nullptr, CallOrInvoke);
6719 llvm::CallBase **CallOrInvoke) {
6722 nullptr, CallOrInvoke);
6729 std::string NoBuiltinFD = (
"no-builtin-" + FD->
getName()).str();
6730 std::string NoBuiltins =
"no-builtins";
6733 std::string FDInlineName = (Ident +
".inline").str();
6735 bool IsPredefinedLibFunction =
6737 bool HasAttributeNoBuiltin =
6738 CGF.
CurFn->getAttributes().hasFnAttr(NoBuiltinFD) ||
6739 CGF.
CurFn->getAttributes().hasFnAttr(NoBuiltins);
6743 if (CGF.
CurFn->getName() != FDInlineName &&
6746 llvm::Function *Fn = llvm::cast<llvm::Function>(CalleePtr);
6747 llvm::Module *M = Fn->getParent();
6748 llvm::Function *Clone = M->getFunction(FDInlineName);
6750 Clone = llvm::Function::Create(Fn->getFunctionType(),
6751 llvm::GlobalValue::InternalLinkage,
6752 Fn->getAddressSpace(), FDInlineName, M);
6753 Clone->setCallingConv(Fn->getCallingConv());
6754 Clone->setAttributes(Fn->getAttributes());
6755 Clone->addFnAttr(llvm::Attribute::AlwaysInline);
6766 else if (!IsPredefinedLibFunction || !HasAttributeNoBuiltin)
6772 FD->
hasAttr<CUDAGlobalAttr>())
6780 if (DeviceKernelAttr::isOpenCLSpelling(FD->
getAttr<DeviceKernelAttr>()))
6793 auto ConvertFuncrefToPtr = [&](llvm::Value *CalleePtr) -> llvm::Value * {
6794 if (
auto *TET = dyn_cast<llvm::TargetExtType>(CalleePtr->getType());
6795 TET && TET->getName() ==
"wasm.funcref") {
6796 llvm::Function *ToPtr =
6797 CGM.getIntrinsic(llvm::Intrinsic::wasm_funcref_to_ptr);
6798 return Builder.CreateCall(ToPtr, {CalleePtr});
6804 if (
auto ICE = dyn_cast<ImplicitCastExpr>(E)) {
6805 if (ICE->getCastKind() == CK_FunctionToPointerDecay ||
6806 ICE->getCastKind() == CK_BuiltinFnToFnPtr) {
6812 if (ICE->getCastKind() == CK_LValueToRValue) {
6813 const Expr *SubExpr = ICE->getSubExpr();
6815 std::pair<llvm::Value *, CGPointerAuthInfo>
Result =
6822 if (
const auto *VD =
6835 }
else if (
auto DRE = dyn_cast<DeclRefExpr>(E)) {
6836 if (
auto FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
6839 }
else if (
auto ME = dyn_cast<MemberExpr>(E)) {
6840 if (
auto FD = dyn_cast<FunctionDecl>(ME->getMemberDecl())) {
6846 }
else if (
auto NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
6850 }
else if (
auto PDE = dyn_cast<CXXPseudoDestructorExpr>(E)) {
6855 llvm::Value *calleePtr;
6867 if (
const auto *VD =
6873 CGCallee callee(calleeInfo, ConvertFuncrefToPtr(calleePtr), pointerAuth);
6889 assert(E->
getOpcode() == BO_Assign &&
"unexpected binary l-value");
6952 llvm::Value *
Result =
nullptr;
6955 if (
SanOpts.has(SanitizerKind::ImplicitBitfieldConversion))
6970 CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(*
this,
6987 llvm_unreachable(
"bad evaluation kind");
7003 if (
CGM.getHLSLRuntime().emitGlobalResourceArray(*
this, E->
getRHS(), Slot))
7015 llvm::CallBase **CallOrInvoke) {
7023 "Can't have a scalar return unless the return type is a "
7036 &&
"binding l-value to type which needs a temporary");
7074 "Can't have a scalar return unless the return type is a "
7088 return CGM.getObjCRuntime().EmitIvarOffset(*
this,
Interface, Ivar);
7096 return Builder.CreateZExtOrTrunc(OffsetValue,
7101 llvm::Value *BaseValue,
7103 unsigned CVRQualifiers) {
7104 return CGM.getObjCRuntime().EmitObjCValueForIvar(*
this, ObjectTy, BaseValue,
7105 Ivar, CVRQualifiers);
7110 llvm::Value *BaseValue =
nullptr;
7121 ObjectTy = BaseExpr->
getType();
7143 llvm::CallBase **CallOrInvoke,
7148 "Call must have function pointer type!");
7150 const Decl *TargetDecl =
7153 assert((!isa_and_present<FunctionDecl>(TargetDecl) ||
7155 "trying to emit a call to an immediate function");
7165 if (
SanOpts.has(SanitizerKind::Function) &&
7168 if (llvm::Constant *PrefixSig =
7169 CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(
CGM)) {
7170 auto CheckOrdinal = SanitizerKind::SO_Function;
7171 auto CheckHandler = SanitizerHandler::FunctionTypeMismatch;
7175 llvm::Type *PrefixSigType = PrefixSig->getType();
7176 llvm::StructType *PrefixStructTy = llvm::StructType::get(
7177 CGM.getLLVMContext(), {PrefixSigType, Int32Ty},
true);
7179 llvm::Value *CalleePtr = Callee.getFunctionPointer();
7180 if (
CGM.getCodeGenOpts().PointerAuth.FunctionPointers) {
7183 Address(CalleePtr, CalleePtr->getType(),
7185 CalleePtr->getPointerAlignment(
CGM.getDataLayout())),
7186 Callee.getPointerAuthInfo(),
nullptr);
7187 CalleePtr =
Addr.emitRawPointer(*
this);
7199 llvm::Value *AlignedCalleePtr;
7200 if (
CGM.getTriple().isARM() ||
CGM.getTriple().isThumb()) {
7201 AlignedCalleePtr =
Builder.CreateIntrinsic(
7202 CalleePtr->getType(), llvm::Intrinsic::ptrmask,
7203 {CalleePtr, llvm::ConstantInt::getSigned(IntPtrTy, ~1)});
7205 AlignedCalleePtr = CalleePtr;
7208 llvm::Value *CalleePrefixStruct = AlignedCalleePtr;
7209 llvm::Value *CalleeSigPtr =
7210 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, -1, 0);
7211 llvm::Value *CalleeSig =
7213 llvm::Value *CalleeSigMatch =
Builder.CreateICmpEQ(CalleeSig, PrefixSig);
7217 Builder.CreateCondBr(CalleeSigMatch, TypeCheck, Cont);
7220 llvm::Value *CalleeTypeHash =
Builder.CreateAlignedLoad(
7222 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, -1, 1),
7224 llvm::Value *CalleeTypeHashMatch =
7225 Builder.CreateICmpEQ(CalleeTypeHash, TypeHash);
7228 EmitCheck(std::make_pair(CalleeTypeHashMatch, CheckOrdinal), CheckHandler,
7229 StaticData, {CalleePtr});
7238 if (
const auto *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl);
7239 FD && DeviceKernelAttr::isOpenCLSpelling(FD->getAttr<DeviceKernelAttr>()))
7240 CGM.getTargetCodeGenInfo().setOCLKernelStubCallingConvention(FnType);
7244 if (
SanOpts.has(SanitizerKind::CFIICall) &&
7246 auto CheckOrdinal = SanitizerKind::SO_CFIICall;
7247 auto CheckHandler = SanitizerHandler::CFICheckFail;
7251 llvm::Metadata *MD =
7252 CGM.CreateMetadataIdentifierForCFIFnType(
QualType(FnType, 0));
7254 llvm::Value *TypeId = llvm::MetadataAsValue::get(
getLLVMContext(), MD);
7256 llvm::Value *CalleePtr = Callee.getFunctionPointer();
7257 llvm::Value *TypeTest =
Builder.CreateCall(
7258 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CalleePtr, TypeId});
7260 auto CrossDsoTypeId =
CGM.CreateCrossDsoCfiTypeId(MD);
7263 if (
CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) {
7267 EmitCheck(std::make_pair(TypeTest, CheckOrdinal), CheckHandler,
7268 StaticData, {CalleePtr, llvm::UndefValue::get(
IntPtrTy)});
7277 bool StaticOperator =
false;
7278 if (
auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
7279 if (
const auto *MD =
7280 dyn_cast_if_present<CXXMethodDecl>(OCE->getCalleeDecl());
7281 MD && MD->isStatic())
7282 StaticOperator =
true;
7286 if (StaticOperator) {
7290 Arguments = drop_begin(Arguments, 1);
7292 EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), Arguments,
7299 *ResolvedFnInfo = &FnInfo;
7304 if (
CGM.getLangOpts().HIP && !
CGM.getLangOpts().CUDAIsDevice &&
7307 llvm::Value *Handle = Callee.getFunctionPointer();
7309 Address(Handle, Handle->getType(),
CGM.getPointerAlign()));
7310 Callee.setFunctionPointer(
Stub);
7317 if (
getLangOpts().OpenMPIsTargetDevice &&
CGM.getTriple().isGPU() &&
7321 while (CalleeExpr) {
7322 if ((DRE = dyn_cast<DeclRefExpr>(CalleeExpr)))
7324 if (
const auto *ME = dyn_cast<MemberExpr>(CalleeExpr))
7326 else if (
const auto *ASE = dyn_cast<ArraySubscriptExpr>(CalleeExpr))
7332 const auto *VD = DRE ? dyn_cast<VarDecl>(DRE->
getDecl()) :
nullptr;
7333 if (VD && VD->hasAttr<OMPTargetIndirectCallAttr>()) {
7334 auto *FuncPtrTy = llvm::PointerType::get(
7335 CGM.getLLVMContext(),
CGM.getDataLayout().getProgramAddressSpace());
7336 llvm::Type *RtlFnArgs[] = {FuncPtrTy};
7337 llvm::FunctionCallee DeviceRtlFn =
CGM.CreateRuntimeFunction(
7338 llvm::FunctionType::get(FuncPtrTy, RtlFnArgs,
false),
7339 "__llvm_omp_indirect_call_lookup");
7340 llvm::Value *
Func = Callee.getFunctionPointer();
7341 llvm::Type *BackupTy =
Func->getType();
7345 Callee.setFunctionPointer(
Func);
7349 llvm::CallBase *LocalCallOrInvoke =
nullptr;
7353 if (
auto *CalleeDecl = dyn_cast_or_null<FunctionDecl>(TargetDecl)) {
7354 if (CalleeDecl->hasAttr<RestrictAttr>() ||
7355 CalleeDecl->hasAttr<MallocSpanAttr>() ||
7356 CalleeDecl->hasAttr<AllocSizeAttr>()) {
7358 if (
SanOpts.has(SanitizerKind::AllocToken)) {
7365 *CallOrInvoke = LocalCallOrInvoke;
7384 bool IsInBounds = !
getLangOpts().PointerOverflowDefined &&
7387 E, BaseAddr, OffsetV, MPT, IsInBounds, &BaseInfo, &TBAAInfo);
7389 return MakeAddrLValue(MemberAddr, MPT->getPointeeType(), BaseInfo, TBAAInfo);
7406 llvm_unreachable(
"bad evaluation kind");
7410 assert(Val->getType()->isFPOrFPVectorTy());
7415 llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
7421 llvm::Type *EltTy = Val->getType()->getScalarType();
7422 if (!EltTy->isFloatTy() && !EltTy->isHalfTy())
7426 !
CGM.getCodeGenOpts().OpenCLCorrectlyRoundedDivSqrt) ||
7428 !
CGM.getCodeGenOpts().HIPCorrectlyRoundedDivSqrt)) {
7443 llvm::Type *EltTy = Val->getType()->getScalarType();
7444 if (!EltTy->isFloatTy() && !EltTy->isHalfTy())
7448 !
CGM.getCodeGenOpts().OpenCLCorrectlyRoundedDivSqrt) ||
7450 !
CGM.getCodeGenOpts().HIPCorrectlyRoundedDivSqrt)) {
7465 struct LValueOrRValue {
7479 LValueOrRValue result;
7493 const Expr *semantic = *i;
7497 if (
const auto *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
7499 if (ov->isUnique()) {
7500 assert(ov != resultExpr &&
7501 "A unique OVE cannot be used as the result expression");
7509 if (ov == resultExpr && ov->
isPRValue() && !forLValue &&
7514 opaqueData = OVMA::bind(CGF, ov, LV);
7519 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
7522 if (ov == resultExpr) {
7530 opaques.push_back(opaqueData);
7534 }
else if (semantic == resultExpr) {
7566 std::tuple<LValue, QualType, llvm::SmallVector<llvm::Value *, 4>>, 16>
7568 llvm::IntegerType *IdxTy = llvm::IntegerType::get(
getLLVMContext(), 32);
7569 WorkList.push_back({Val, Val.
getType(), {llvm::ConstantInt::get(IdxTy, 0)}});
7571 while (!WorkList.empty()) {
7572 auto [LVal, T, IdxList] = WorkList.pop_back_val();
7573 T = T.getCanonicalType().getUnqualifiedType();
7574 if (
const auto *CAT = dyn_cast<ConstantArrayType>(T)) {
7575 uint64_t Size = CAT->getZExtSize();
7576 for (int64_t I = Size - 1; I > -1; I--) {
7578 IdxListCopy.push_back(llvm::ConstantInt::get(IdxTy, I));
7579 WorkList.emplace_back(LVal, CAT->getElementType(), IdxListCopy);
7581 }
else if (
const auto *RT = dyn_cast<RecordType>(T)) {
7583 assert(!
Record->isUnion() &&
"Union types not supported in flat cast.");
7588 std::tuple<LValue, QualType, llvm::SmallVector<llvm::Value *, 4>>, 16>
7597 "HLSL doesn't support multiple inheritance.");
7600 IdxListCopy.push_back(llvm::ConstantInt::get(
7602 ReverseList.emplace_back(LVal,
Base->getType(), IdxListCopy);
7611 bool createdGEP =
false;
7612 for (
auto *FD :
Record->fields()) {
7613 if (FD->isBitField()) {
7614 if (FD->isUnnamedBitField())
7618 Address GEP =
Builder.CreateInBoundsGEP(LVal.getAddress(), IdxList,
7619 LLVMT, Align,
"gep");
7623 ReverseList.push_back({FieldLVal, FD->
getType(), {}});
7626 IdxListCopy.push_back(
7628 ReverseList.emplace_back(LVal, FD->getType(), IdxListCopy);
7632 std::reverse(ReverseList.begin(), ReverseList.end());
7633 llvm::append_range(WorkList, ReverseList);
7634 }
else if (
const auto *VT = dyn_cast<VectorType>(T)) {
7637 Address GEP =
Builder.CreateInBoundsGEP(LVal.getAddress(), IdxList, LLVMT,
7638 Align,
"vector.gep");
7640 for (
unsigned I = 0, E = VT->getNumElements(); I < E; I++) {
7641 llvm::Constant *Idx = llvm::ConstantInt::get(IdxTy, I);
7645 AccessList.emplace_back(LV);
7647 }
else if (
const auto *MT = dyn_cast<ConstantMatrixType>(T)) {
7655 Address GEP =
Builder.CreateInBoundsGEP(LVal.getAddress(), IdxList, LLVMT,
7656 Align,
"matrix.gep");
7659 unsigned NumRows = MT->getNumRows();
7660 unsigned NumCols = MT->getNumColumns();
7662 llvm::MatrixBuilder MB(
Builder);
7663 for (
unsigned Row = 0; Row < MT->getNumRows(); Row++) {
7664 for (
unsigned Col = 0; Col < MT->getNumColumns(); Col++) {
7665 llvm::Value *RowIdx = llvm::ConstantInt::get(IdxTy, Row);
7666 llvm::Value *ColIdx = llvm::ConstantInt::get(IdxTy, Col);
7667 llvm::Value *Idx = MB.CreateIndex(RowIdx, ColIdx, NumRows, NumCols,
7672 AccessList.emplace_back(LV);
7676 if (!IdxList.empty()) {
7679 Address GEP =
Builder.CreateInBoundsGEP(LVal.getAddress(), IdxList,
7680 LLVMT, Align,
"gep");
7683 AccessList.emplace_back(LVal);
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 SmallString< 64 > getAllocTokenFunctionName(const Decl *D, const ASTContext &Ctx)
Returns the qualified name of D for use as the function name in !alloc_token metadata,...
static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E, LValue &LV, bool IsMemberAccess=false)
static LValue EmitGlobalNamedRegister(const VarDecl *VD, CodeGenModule &CGM)
Named Registers are named metadata pointing to the register name which will be read from/written to a...
static bool getRangeForType(CodeGenFunction &CGF, QualType Ty, llvm::APInt &Min, llvm::APInt &End, bool StrictEnums, bool StrictBool, bool IsBool)
static llvm::Value * emitHashMix(CGBuilderTy &Builder, llvm::Value *Acc, llvm::Value *Ptr)
static const Expr * isSimpleArrayDecayOperand(const Expr *E)
isSimpleArrayDecayOperand - If the specified expr is a simple decay from an array to pointer,...
static bool getFieldOffsetInBits(CodeGenFunction &CGF, const RecordDecl *RD, const FieldDecl *Field, int64_t &Offset)
The offset of a field from the beginning of the record.
static bool hasBPFPreserveStaticOffset(const RecordDecl *D)
static Address emitRawAddrOfFieldStorage(CodeGenFunction &CGF, Address base, const FieldDecl *field, bool IsInBounds)
Drill down to the storage of a field without walking into reference types, and without respect for po...
static LValue EmitCapturedFieldLValue(CodeGenFunction &CGF, const FieldDecl *FD, llvm::Value *ThisValue)
static std::optional< LValue > EmitLValueOrThrowExpression(CodeGenFunction &CGF, const Expr *Operand)
Emit the operand of a glvalue conditional operator.
static llvm::Value * convertSizedByBoundToElementCount(CodeGenFunction &CGF, llvm::Value *BoundsVal, QualType PointeeTy, bool CountSigned)
Convert a '__sized_by' byte-count bound to an element-count bound so it can be compared against an el...
static CheckRecoverableKind getRecoverableKind(SanitizerKind::SanitizerOrdinal Ordinal)
static bool RecordContainsField(const RecordDecl *RD, const FieldDecl *Field)
Returns true if Field is reachable from RD either as a direct field or through a chain of nested reco...
static llvm::Value * emitArraySubscriptGEP(CodeGenFunction &CGF, llvm::Type *elemType, llvm::Value *ptr, ArrayRef< llvm::Value * > indices, bool inbounds, bool signedIndices, SourceLocation loc, const llvm::Twine &name="arrayidx")
static GlobalDecl getGlobalDeclForDirectCall(const FunctionDecl *FD)
static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF, const Expr *E, GlobalDecl GD)
static RawAddress MaybeConvertMatrixAddress(RawAddress Addr, CodeGenFunction &CGF, bool IsVector=true)
static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF, const PseudoObjectExpr *E, bool forLValue, AggValueSlot slot)
static Address wrapWithBPFPreserveStaticOffset(CodeGenFunction &CGF, Address &Addr)
static llvm::StringRef GetUBSanTrapForHandler(SanitizerHandler ID)
static llvm::Value * getArrayIndexingBound(CodeGenFunction &CGF, const Expr *Base, QualType &IndexedType, LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel)
If Base is known to point to the start of an array, return the length of that array.
static RValue EmitLoadOfMatrixLValue(LValue LV, SourceLocation Loc, CodeGenFunction &CGF)
static Address emitAddrOfFieldStorage(CodeGenFunction &CGF, Address base, const FieldDecl *field, bool IsInBounds)
Drill down to the storage of a field without walking into reference types, wrapping the address in an...
static std::optional< int64_t > getOffsetDifferenceInBits(CodeGenFunction &CGF, const FieldDecl *FD1, const FieldDecl *FD2)
Returns the relative offset difference between FD1 and FD2.
static CGCallee EmitDirectCallee(CodeGenFunction &CGF, GlobalDecl GD)
static LValue EmitThreadPrivateVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD, QualType T, Address Addr, llvm::Type *RealVarTy, SourceLocation Loc)
static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF, const Expr *E, const VarDecl *VD)
static bool hasAnyVptr(const QualType Type, const ASTContext &Context)
static bool IsPreserveAIArrayBase(CodeGenFunction &CGF, const Expr *ArrayBase)
Given an array base, check whether its member access belongs to a record with preserve_access_index a...
VariableTypeDescriptorKind
@ TK_Float
A floating-point type.
@ TK_Unknown
Any other type. The value representation is unspecified.
@ TK_Integer
An integer type.
@ TK_BitInt
An _BitInt(N) type.
static void EmitStoreOfMatrixScalar(llvm::Value *value, LValue lvalue, bool isInit, CodeGenFunction &CGF)
static Address EmitPointerWithAlignment(const Expr *E, LValueBaseInfo *BaseInfo, TBAAAccessInfo *TBAAInfo, KnownNonNull_t IsKnownNonNull, CodeGenFunction &CGF)
static Address emitPreserveStructAccess(CodeGenFunction &CGF, LValue base, Address addr, const FieldDecl *field)
const SanitizerHandlerInfo SanitizerHandlers[]
static void emitCheckHandlerCall(CodeGenFunction &CGF, llvm::FunctionType *FnType, ArrayRef< llvm::Value * > FnArgs, SanitizerHandler CheckHandler, CheckRecoverableKind RecoverKind, bool IsFatal, llvm::BasicBlock *ContBB, bool NoMerge)
static Address emitOMPArraySectionBase(CodeGenFunction &CGF, const Expr *Base, LValueBaseInfo &BaseInfo, TBAAAccessInfo &TBAAInfo, QualType BaseTy, QualType ElTy, bool IsLowerBound)
static mlir::Value emitPointerArithmetic(CIRGenFunction &cgf, const BinOpInfo &op, bool isSubtraction)
Emit pointer + index arithmetic.
static std::optional< LValue > emitDeclTargetVarDeclLValue(CIRGenFunction &cgf, const Expr *e, const VarDecl *vd)
static Address createReferenceTemporary(CIRGenFunction &cgf, const MaterializeTemporaryExpr *m, const Expr *inner)
static CharUnits getArrayElementAlign(CharUnits arrayAlign, mlir::Value idx, CharUnits eltSize)
static void pushTemporaryCleanup(CIRGenFunction &cgf, const MaterializeTemporaryExpr *m, const Expr *e, Address referenceTemporary)
static bool canEmitSpuriousReferenceToVariable(CIRGenFunction &cgf, const DeclRefExpr *e, const VarDecl *vd)
Determine whether we can emit a reference to vd from the current context, despite not necessarily hav...
static DeclRefExpr * tryToConvertMemberExprToDeclRefExpr(CIRGenFunction &cgf, const MemberExpr *me)
static Address emitAddrOfZeroSizeField(CIRGenFunction &cgf, Address base, const FieldDecl *field)
Get the address of a zero-sized field within a record.
static unsigned getCharWidth(tok::TokenKind kind, const TargetInfo &Target)
llvm::MachO::Record Record
Defines AST-level helper utilities for matrix types.
Defines the clang::Module class, which describes a module in the source code.
static const SanitizerMask AlwaysRecoverable
static const SanitizerMask Unrecoverable
#define LIST_SANITIZER_CHECKS
Defines the SourceManager interface.
static QualType getPointeeType(const MemRegion *R)
a trap message and trap category.
const LValueBase getLValueBase() const
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
SourceManager & getSourceManager()
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
uint64_t getFieldOffset(const ValueDecl *FD) const
Get the offset of a FieldDecl or IndirectFieldDecl, in bits.
static CanQualType getCanonicalType(QualType T)
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
Builtin::Context & BuiltinInfo
const LangOptions & getLangOpts() const
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>.
llvm::DenseMap< const CXXMethodDecl *, CXXCastPath > LambdaCastPaths
For capturing lambdas with an explicit object parameter whose type is derived from the lambda type,...
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
static bool isPFPField(const FieldDecl *Field)
const VariableArrayType * getAsVariableArrayType(QualType T) const
QualType getExtVectorType(QualType VectorType, unsigned NumElts) const
Return the unique reference to an extended vector type of the specified element type and size.
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
CanQualType getCanonicalTagType(const TagDecl *TD) const
unsigned getTargetAddressSpace(LangAS AS) const
bool isSentinelNullExpr(const Expr *E)
uint64_t getCharWidth() const
Return the size of the character type, in bits.
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
AbstractConditionalOperator - An abstract base class for ConditionalOperator and BinaryConditionalOpe...
Expr * getCond() const
getCond - Return the expression representing the condition for the ?
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
This class represents BOTH the OpenMP Array Section and OpenACC 'subarray', with a boolean differenti...
Expr * getBase()
Get base of the array section.
Expr * getLength()
Get length of array section.
static QualType getBaseOriginalType(const Expr *Base)
Return original type of the base expression for array section.
SourceLocation getExprLoc() const LLVM_READONLY
Expr * getLowerBound()
Get lower bound of array section.
bool isOpenACCArraySection() const
SourceLocation getColonLocFirst() const
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
SourceLocation getExprLoc() const LLVM_READONLY
Expr * getLHS()
An array access can be written A[4] or 4[A] (both are equivalent).
Represents an array type, per C99 6.7.5.2 - Array Declarators.
QualType getElementType() const
A builtin binary operation expression such as "x + y" or "x <= y".
SourceLocation getExprLoc() const
static bool isAdditiveOp(Opcode Opc)
A binding in a decomposition declaration.
Expr * getBinding() const
Get the expression to which this declaration is bound.
DecompositionDecl * getDecomposedDecl() const
Get the decomposition declaration that this binding represents a decomposition of.
A fixed int type of a specified bitwidth.
unsigned getNumBits() const
bool isPredefinedLibFunction(unsigned ID) const
Determines whether this builtin is a predefined libc/libm function, such as "malloc",...
Represents binding an expression to a temporary.
CXXTemporary * getTemporary()
const Expr * getSubExpr() const
Represents a call to a C++ constructor.
Represents a C++ destructor within a class.
Represents a C++ struct/union/class.
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
bool isStandardLayout() const
Determine whether this class is standard-layout per C++ [class]p7.
unsigned getNumBases() const
Retrieves the number of base classes of this class.
base_class_iterator bases_begin()
bool isDynamicClass() const
bool hasDefinition() const
const CXXRecordDecl * getStandardLayoutBaseWithFields() const
If this is a standard-layout class or union, any and all data members will be declared in the same ty...
A C++ typeid expression (C++ [expr.typeid]), which gets the type_info that corresponds to the supplie...
A Microsoft C++ __uuidof expression, which gets the _GUID that corresponds to the supplied type or ex...
MSGuidDecl * getGuidDecl() const
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
SourceLocation getBeginLoc() const
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
bool isCoroElideSafe() const
QualType getCallReturnType(const ASTContext &Ctx) const
getCallReturnType - Get the return type of the call expr.
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
path_iterator path_begin()
CastKind getCastKind() const
bool changesVolatileQualification() const
Return.
This is an opaque type for sizes expressed in character units.
CharUnits alignmentAtOffset(CharUnits offset) const
Given that this is a non-zero alignment value, what is the alignment at the given offset?
llvm::MaybeAlign getAsMaybeAlign() const
Returns Quantity as a valid llvm::Align or std::nullopt, Beware llvm::MaybeAlign assumes power of two...
llvm::Align getAsAlign() const
Returns Quantity as a valid llvm::Align, Beware llvm::Align assumes power of two 8-bit bytes.
QuantityType getQuantity() const
Get the raw integer representation of this quantity.
static CharUnits One()
Construct a CharUnits quantity of one.
CharUnits alignmentOfArrayElement(CharUnits elementSize) const
Given that this is the alignment of the first element of an array, return the minimum alignment of an...
static constexpr CharUnits fromQuantity(QuantityType Quantity)
Construct a CharUnits quantity from a raw integer type.
static CharUnits Zero()
Construct a CharUnits quantity of zero.
@ None
Trap Messages are omitted.
@ Detailed
Trap Message includes more context (e.g.
bool hasReducedDebugInfo() const
Check if type and variable info should be emitted.
@ Strict
In-memory bool values are assumed to be 0 or 1, and any other value is UB.
bool isOptimizedBuild() const
Are we building at -O1 or higher?
Like RawAddress, an abstract representation of an aligned address, but the pointer contained in this ...
llvm::Value * getBasePointer() const
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 withPointer(llvm::Value *NewPointer, KnownNonNull_t IsKnownNonNull) const
Return address with different pointer, but same element type and alignment.
Address withElementType(llvm::Type *ElemTy) const
Return address with different element type, but same pointer and alignment.
Address withAlignment(CharUnits NewAlignment) const
Return address with different alignment, but same pointer and element type.
llvm::PointerType * getType() const
Return the type of the pointer value.
static AggValueSlot ignored()
ignored - Returns an aggregate value slot indicating that the aggregate value is being ignored.
Address getAddress() const
void setExternallyDestructed(bool destructed=true)
static AggValueSlot forLValue(const LValue &LV, IsDestructed_t isDestructed, NeedsGCBarriers_t needsGC, IsAliased_t isAliased, Overlap_t mayOverlap, IsZeroed_t isZeroed=IsNotZeroed, IsSanitizerChecked_t isChecked=IsNotSanitizerChecked)
static AggValueSlot forAddr(Address addr, Qualifiers quals, IsDestructed_t isDestructed, NeedsGCBarriers_t needsGC, IsAliased_t isAliased, Overlap_t mayOverlap, IsZeroed_t isZeroed=IsNotZeroed, IsSanitizerChecked_t isChecked=IsNotSanitizerChecked)
forAddr - Make a slot for an aggregate value.
A scoped helper to set the current source atom group for CGDebugInfo::addInstToCurrentSourceAtom.
A scoped helper to set the current debug location to the specified location or preferred location of ...
static ApplyDebugLocation CreateArtificial(CodeGenFunction &CGF)
Apply TemporaryLocation if it is valid.
Address CreateConstInBoundsByteGEP(Address Addr, CharUnits Offset, const llvm::Twine &Name="")
Given a pointer to i8, adjust it by a given constant offset.
Address CreateGEP(CodeGenFunction &CGF, Address Addr, llvm::Value *Index, const llvm::Twine &Name="")
Address CreateConstGEP2_32(Address Addr, unsigned Idx0, unsigned Idx1, const llvm::Twine &Name="")
Address CreateConstArrayGEP(Address Addr, uint64_t Index, const llvm::Twine &Name="")
Given addr = [n x T]* ... produce name = getelementptr inbounds addr, i64 0, i64 index where i64 is a...
Address CreateStructGEP(Address Addr, unsigned Index, const llvm::Twine &Name="")
llvm::LoadInst * CreateLoad(Address Addr, const llvm::Twine &Name="")
Address CreateConstByteGEP(Address Addr, CharUnits Offset, const llvm::Twine &Name="")
Address CreatePreserveStructAccessIndex(Address Addr, unsigned Index, unsigned FieldIndex, llvm::MDNode *DbgInfo)
Address CreateAddrSpaceCast(Address Addr, llvm::Type *Ty, llvm::Type *ElementTy, const llvm::Twine &Name="")
virtual llvm::Function * getKernelStub(llvm::GlobalValue *Handle)=0
Get kernel stub by kernel handle.
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 registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D, llvm::FunctionCallee Dtor, llvm::Constant *Addr)=0
Emit code to force the execution of a destructor during global teardown.
virtual LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD, QualType LValType)=0
Emit a reference to a non-local thread_local variable (including triggering the initialization of all...
virtual bool canCallMismatchedFunctionType() const
Returns true if the target allows calling a function through a pointer with a different signature tha...
virtual bool usesThreadWrapperFunction(const VarDecl *VD) const =0
Abstract information about a function or function prototype.
const GlobalDecl getCalleeDecl() const
All available information about a concrete callee.
CGCalleeInfo getAbstractInfo() const
const CXXPseudoDestructorExpr * getPseudoDestructorExpr() const
bool isPseudoDestructor() const
static CGCallee forBuiltin(unsigned builtinID, const FunctionDecl *builtinDecl)
unsigned getBuiltinID() const
static CGCallee forDirect(llvm::Constant *functionPtr, const CGCalleeInfo &abstractInfo=CGCalleeInfo())
const FunctionDecl * getBuiltinDecl() const
static CGCallee forPseudoDestructor(const CXXPseudoDestructorExpr *E)
This class gathers all debug information during compilation and is responsible for emitting to llvm g...
llvm::DIType * getOrCreateStandaloneType(QualType Ty, SourceLocation Loc)
Emit standalone debug info for a type.
std::pair< llvm::DIType *, unsigned > getOrCreatePreserveAccessInfo(QualType Ty, const FieldDecl *Field)
Return the complete record type and field index for preserve-access intrinsics.
llvm::DILocation * CreateTrapFailureMessageFor(llvm::DebugLoc TrapLocation, StringRef Category, StringRef FailureMsg)
Create a debug location from TrapLocation that adds an artificial inline frame where the frame name i...
CGFunctionInfo - Class to encapsulate the information about a function definition.
std::optional< LValue > emitGlobalResourceArrayAsLValue(CodeGenFunction &CGF, const VarDecl *ArrayDecl)
RawAddress createBufferMatrixTempAddress(const LValue &LV, CodeGenFunction &CGF)
virtual Address getAddrOfThreadPrivate(CodeGenFunction &CGF, const VarDecl *VD, Address VDAddr, SourceLocation Loc)
Returns address of the threadprivate variable for the current thread.
virtual ConstantAddress getAddrOfDeclareTargetVar(const VarDecl *VD)
Returns the address of the variable marked as declare target with link clause OR as declare target wi...
bool hasRequiresUnifiedSharedMemory() const
Return whether the unified_shared_memory has been specified.
CGRecordLayout - This class handles struct and union layout info while lowering AST types to LLVM typ...
llvm::StructType * getLLVMType() const
Return the "complete object" LLVM type associated with this record.
const CGBitFieldInfo & getBitFieldInfo(const FieldDecl *FD) const
Return the BitFieldInfo that corresponds to the field FD.
unsigned getLLVMFieldNo(const FieldDecl *FD) const
Return llvm::StructType element number that corresponds to the field FD.
CallArgList - Type for representing both the value and type of arguments in a call.
void addWriteback(LValue srcLV, Address temporary, llvm::Value *toUse, const Expr *writebackExpr=nullptr)
void add(RValue rvalue, QualType type)
The scope of a CXXDefaultInitExpr.
An object to manage conditionally-evaluated expressions.
llvm::BasicBlock * getStartingBlock() const
Returns a block which will be executed prior to each evaluation of the conditional code.
static ConstantEmission forValue(llvm::Constant *C)
static ConstantEmission forReference(llvm::Constant *C)
A non-RAII class containing all the information about a bound opaque value.
static bool shouldBindAsLValue(const Expr *expr)
static OpaqueValueMappingData bind(CodeGenFunction &CGF, const OpaqueValueExpr *ov, const Expr *e)
An RAII object to set (and then clear) a mapping for an OpaqueValueExpr.
static bool shouldBindAsLValue(const Expr *expr)
RAII object to set/unset CodeGenFunction::IsSanitizerScope.
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
LValue EmitMatrixSubscriptExpr(const MatrixSubscriptExpr *E)
LValue EmitCoawaitLValue(const CoawaitExpr *E)
llvm::Value * GetVTablePtr(Address This, llvm::Type *VTableTy, const CXXRecordDecl *VTableClass, VTableAuthMode AuthMode=VTableAuthMode::Authenticate)
GetVTablePtr - Return the Value of the vtable pointer member pointed to by This.
llvm::Value * EmitObjCConsumeObject(QualType T, llvm::Value *Ptr)
Produce the code for a CK_ARCConsumeObject.
void EmitBoundsCheckImpl(const Expr *ArrayExpr, QualType ArrayBaseType, llvm::Value *IndexVal, QualType IndexType, llvm::Value *BoundsVal, QualType BoundsType, bool Accessed)
LValue EmitLoadOfReferenceLValue(LValue RefLVal)
void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock, llvm::BasicBlock *FalseBlock, uint64_t TrueCount, Stmt::Likelihood LH=Stmt::LH_None, const Expr *ConditionalOp=nullptr, const VarDecl *ConditionalDecl=nullptr)
EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g.
llvm::CallInst * EmitTrapCall(llvm::Intrinsic::ID IntrID, bool EnsureInsertPoint=true)
Emit a call to trap or debugtrap.
RValue EmitObjCMessageExpr(const ObjCMessageExpr *E, ReturnValueSlot Return=ReturnValueSlot())
llvm::Value * emitBoolVecConversion(llvm::Value *SrcVec, unsigned NumElementsDst, const llvm::Twine &Name="")
void EmitCXXConstructExpr(const CXXConstructExpr *E, AggValueSlot Dest)
llvm::GlobalVariable * EmitCheckStaticData(ArrayRef< llvm::Constant * > StaticArgs)
Emit a private unnamed_addr non-constant global containing static arguments for a UBSan runtime check...
LValue EmitCXXConstructLValue(const CXXConstructExpr *E)
llvm::Value * performAddrSpaceCast(llvm::Value *Src, llvm::Type *DestTy)
LValue EmitConditionalOperatorLValue(const AbstractConditionalOperator *E)
std::pair< LValue, llvm::Value * > EmitARCStoreAutoreleasing(const BinaryOperator *e)
ComplexPairTy EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV, bool isInc, bool isPre)
void SetDivFPAccuracy(llvm::Value *Val)
Set the minimum required accuracy of the given sqrt operation based on CodeGenOpts.
SanitizerSet SanOpts
Sanitizers enabled for this function.
CodeGenUtils::EvaluationOrder EvaluationOrder
@ UseSkipPath
Skip (false)
LValue EmitInitListLValue(const InitListExpr *E)
bool isUnderlyingBasePointerConstantNull(const Expr *E)
Check whether the underlying base pointer is a constant null.
void EmitARCInitWeak(Address addr, llvm::Value *value)
i8* @objc_initWeak(i8** addr, i8* value) Returns value.
LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E, bool Accessed=false)
Address LoadCXXThisAddress()
static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts=false)
ContainsLabel - Return true if the statement contains a label in it.
LValue EmitObjCMessageExprLValue(const ObjCMessageExpr *E)
llvm::Value * GetCountedByFieldExprGEP(const Expr *Base, const FieldDecl *FD, const FieldDecl *CountDecl)
void EmitComplexExprIntoLValue(const Expr *E, LValue dest, bool isInit)
EmitComplexExprIntoLValue - Emit the given expression of complex type and place its result into the s...
const CastExpr * CurCast
If a cast expression is being visited, this holds the current cast's expression.
llvm::Type * ConvertType(QualType T)
Address EmitCXXUuidofExpr(const CXXUuidofExpr *E)
void EmitSanitizerStatReport(llvm::SanitizerStatKind SSK)
static Destroyer destroyARCWeak
CGCapturedStmtInfo * CapturedStmtInfo
RValue EmitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E)
ComplexPairTy EmitLoadOfComplex(LValue src, SourceLocation loc)
EmitLoadOfComplex - Load a complex number from the specified l-value.
bool inSuspendBlock() const
llvm::Value * EmitARCRetain(QualType type, llvm::Value *value)
Produce the code to do a retain.
llvm::Value * EmitPointerAuthQualify(PointerAuthQualifier Qualifier, llvm::Value *Pointer, QualType ValueType, Address StorageAddress, bool IsKnownNonNull)
CleanupKind getARCCleanupKind()
Retrieves the default cleanup kind for an ARC cleanup.
void EmitAggFinalDestCopy(QualType Type, AggValueSlot Dest, const LValue &Src, ExprValueKind SrcKind)
EmitAggFinalDestCopy - Emit copy of the specified aggregate into destination address.
Address GetAddressOfBaseClass(Address Value, const CXXRecordDecl *Derived, CastExpr::path_const_iterator PathBegin, CastExpr::path_const_iterator PathEnd, bool NullCheckValue, SourceLocation Loc)
GetAddressOfBaseClass - This function will add the necessary delta to the load of 'this' and returns ...
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 ...
void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst)
RValue EmitBlockCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue, llvm::CallBase **CallOrInvoke)
LValue EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E)
void EmitCXXThrowExpr(const CXXThrowExpr *E, bool KeepInsertionPoint=true)
LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E)
RValue convertTempToRValue(Address addr, QualType type, SourceLocation Loc)
Given the address of a temporary variable, produce an r-value of its type.
LValue EmitObjCIsaExpr(const ObjCIsaExpr *E)
void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst, llvm::Value **Result=nullptr)
EmitStoreThroughBitfieldLValue - Store Src into Dst with same constraints as EmitStoreThroughLValue.
llvm::Constant * EmitCheckSourceLocation(SourceLocation Loc)
Emit a description of a source location in a format suitable for passing to a runtime sanitizer handl...
LValue EmitCXXUuidofLValue(const CXXUuidofExpr *E)
llvm::Value * EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV, bool isInc, bool isPre)
void SetSqrtFPAccuracy(llvm::Value *Val)
Set the minimum required accuracy of the given sqrt operation based on CodeGenOpts.
RValue EmitSimpleCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue, llvm::CallBase **CallOrInvoke=nullptr)
Emit a CallExpr without considering whether it might be a subclass.
static bool isNullPointerAllowed(TypeCheckKind TCK)
Determine whether the pointer type check TCK permits null pointers.
RValue EmitPseudoObjectRValue(const PseudoObjectExpr *e, AggValueSlot slot=AggValueSlot::ignored())
llvm::BasicBlock * createBasicBlock(const Twine &name="", llvm::Function *parent=nullptr, llvm::BasicBlock *before=nullptr)
createBasicBlock - Create an LLVM basic block.
void addInstToCurrentSourceAtom(llvm::Instruction *KeyInstruction, llvm::Value *Backup)
See CGDebugInfo::addInstToCurrentSourceAtom.
const LangOptions & getLangOpts() const
void EmitCfiCheckFail()
Emit a cross-DSO CFI failure handling function.
RValue EmitReferenceBindingToExpr(const Expr *E)
Emits a reference binding to the passed in expression.
llvm::Value * EmitARCStoreStrong(LValue lvalue, llvm::Value *value, bool resultIgnored)
Store into a strong object.
LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
LValue EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E)
LValue EmitLValueForIvar(QualType ObjectTy, llvm::Value *Base, const ObjCIvarDecl *Ivar, unsigned CVRQualifiers)
Address GetAddressOfDerivedClass(Address Value, const CXXRecordDecl *Derived, CastExpr::path_const_iterator PathBegin, CastExpr::path_const_iterator PathEnd, bool NullCheckValue)
void EmitIgnoredConditionalOperator(const AbstractConditionalOperator *E)
void EmitCountedByBoundsChecking(const Expr *ArrayExpr, QualType ArrayType, Address ArrayInst, QualType IndexType, llvm::Value *IndexVal, bool Accessed, bool FlexibleArray)
EmitCountedByBoundsChecking - If the array being accessed has a "counted_by" attribute,...
Address EmitFieldAnnotations(const FieldDecl *D, Address V)
Emit field annotations for the given field & value.
bool IsInPreserveFieldInfo
True if CodeGen currently emits the argument of __builtin_preserve_field_info.
void pushDestroy(QualType::DestructionKind dtorKind, Address addr, QualType type)
pushDestroy - Push the standard destructor for the given type as at least a normal cleanup.
void EmitScalarInit(const Expr *init, const ValueDecl *D, LValue lvalue, bool capturedByInit)
void EmitNullabilityCheck(LValue LHS, llvm::Value *RHS, SourceLocation Loc)
Given an assignment *LHS = RHS, emit a test that checks if RHS is nonnull, if LHS is marked _Nonnull.
llvm::Value * EmitPointerAuthUnqualify(PointerAuthQualifier Qualifier, llvm::Value *Pointer, QualType PointerType, Address StorageAddress, bool IsKnownNonNull)
void EmitDeclRefExprDbgValue(const DeclRefExpr *E, const APValue &Init)
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.
static Destroyer destroyCXXObject
Address EmitLoadOfPointer(Address Ptr, const PointerType *PtrTy, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr)
Load a pointer with type PtrTy stored at address Ptr.
RValue EmitLoadOfGlobalRegLValue(LValue LV)
Load of global named registers are always calls to intrinsics.
void EmitVTablePtrCheckForCast(QualType T, Address Derived, bool MayBeNull, CFITypeCheckKind TCK, SourceLocation Loc)
Derived is the presumed address of an object of type T after a cast.
TypeCheckKind
Situations in which we might emit a check for the suitability of a pointer or glvalue.
@ TCK_DowncastPointer
Checking the operand of a static_cast to a derived pointer type.
@ TCK_DowncastReference
Checking the operand of a static_cast to a derived reference type.
@ TCK_MemberAccess
Checking the object expression in a non-static data member access.
@ TCK_Store
Checking the destination of a store. Must be suitably sized and aligned.
@ TCK_UpcastToVirtualBase
Checking the operand of a cast to a virtual base object.
@ TCK_MemberCall
Checking the 'this' pointer for a call to a non-static member function.
@ TCK_DynamicOperation
Checking the operand of a dynamic_cast or a typeid expression.
@ TCK_ReferenceBinding
Checking the bound value in a reference binding.
@ TCK_Upcast
Checking the operand of a cast to a base object.
LValue EmitBinaryOperatorLValue(const BinaryOperator *E)
bool InNoMergeAttributedStmt
True if the current statement has nomerge attribute.
LValue EmitComplexCompoundAssignmentLValue(const CompoundAssignOperator *E)
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...
void maybeAttachRangeForLoad(llvm::LoadInst *Load, QualType Ty, SourceLocation Loc)
void EmitBitfieldConversionCheck(llvm::Value *Src, QualType SrcType, llvm::Value *Dst, QualType DstType, const CGBitFieldInfo &Info, SourceLocation Loc)
Emit a check that an [implicit] conversion of a bitfield.
LValue EmitPseudoObjectLValue(const PseudoObjectExpr *e)
llvm::Constant * EmitCheckTypeDescriptor(QualType T)
Emit a description of a type in a format suitable for passing to a runtime sanitizer handler.
LValue EmitOpaqueValueLValue(const OpaqueValueExpr *e)
llvm::Value * LoadPassedObjectSize(const Expr *E, QualType EltTy)
If E references a parameter with pass_object_size info or a constant array size modifier,...
llvm::Value * EmitIvarOffsetAsPointerDiff(const ObjCInterfaceDecl *Interface, const ObjCIvarDecl *Ivar)
RValue EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E, ReturnValueSlot ReturnValue, llvm::CallBase **CallOrInvoke)
RValue EmitLoadOfAnyValue(LValue V, AggValueSlot Slot=AggValueSlot::ignored(), SourceLocation Loc={})
Like EmitLoadOfLValue but also handles complex and aggregate types.
LValue EmitLValueForField(LValue Base, const FieldDecl *Field, bool IsInBounds=true)
RawAddress CreateDefaultAlignTempAlloca(llvm::Type *Ty, const Twine &Name="tmp")
CreateDefaultAlignedTempAlloca - This creates an alloca with the default ABI alignment of the given L...
const TargetInfo & getTarget() const
LValue EmitCompoundAssignmentLValue(const CompoundAssignOperator *E)
bool isInConditionalBranch() const
isInConditionalBranch - Return true if we're currently emitting one branch or the other of a conditio...
Address EmitCXXMemberDataPointerAddress(const Expr *E, Address base, llvm::Value *memberPtr, const MemberPointerType *memberPtrType, bool IsInBounds, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr)
Emit the address of a field using a member data pointer.
static bool isVptrCheckRequired(TypeCheckKind TCK, QualType Ty)
Determine whether the pointer type check TCK requires a vptr check.
CGCallee EmitCallee(const Expr *E)
void EmitIgnoredExpr(const Expr *E)
EmitIgnoredExpr - Emit an expression in a context which ignores the result.
RValue EmitCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue=ReturnValueSlot(), llvm::CallBase **CallOrInvoke=nullptr)
RValue EmitLoadOfLValue(LValue V, SourceLocation Loc)
EmitLoadOfLValue - Given an expression that represents a value lvalue, this method emits the address ...
LValue EmitMatrixSingleSubscriptExpr(const MatrixSingleSubscriptExpr *E)
LValue EmitArraySectionExpr(const ArraySectionExpr *E, bool IsLowerBound=true)
Address GetAddrOfBlockDecl(const VarDecl *var)
llvm::Value * EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy, QualType DstTy, SourceLocation Loc)
Emit a conversion from the specified complex type to the specified destination type,...
void pushCleanupAfterFullExpr(CleanupKind Kind, As... A)
Queue a cleanup to be pushed after finishing the current full-expression, potentially with an active ...
void EmitCfiCheckStub()
Emit a stub for the cross-DSO CFI check function.
RawAddress CreateIRTempWithoutCast(QualType T, const Twine &Name="tmp")
CreateIRTempWithoutCast - Create a temporary IR object of the given type, with appropriate alignment.
void pushFullExprCleanup(CleanupKind kind, As... A)
pushFullExprCleanup - Push a cleanup to be run at the end of the current full-expression.
std::array< llvm::Constant *, 3 > EmitCFICheckFailStaticArgs(CFITypeCheckKind CheckKind, SourceLocation Loc, QualType Type)
Build the static argument array {CheckKind, SourceLocation, TypeDescriptor} for a UBSan CFICheckFail ...
static Destroyer destroyARCStrongImprecise
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.
LValue EmitAggExprToLValue(const Expr *E)
EmitAggExprToLValue - Emit the computation of the specified expression of aggregate type into a tempo...
void SetFPAccuracy(llvm::Value *Val, float Accuracy)
SetFPAccuracy - Set the minimum required accuracy of the given floating point operation,...
Address mergeAddressesInConditionalExpr(Address LHS, Address RHS, llvm::BasicBlock *LHSBlock, llvm::BasicBlock *RHSBlock, llvm::BasicBlock *MergeBlock, QualType MergedType)
Address emitAddrOfImagComponent(Address complex, QualType complexType)
void EmitBoundsCheck(const Expr *ArrayExpr, const Expr *ArrayExprBase, llvm::Value *Index, QualType IndexType, bool Accessed)
Emit a check that Base points into an array object, which we can access at index Index.
llvm::Value * EvaluateExprAsBool(const Expr *E)
EvaluateExprAsBool - Perform the usual unary conversions on the specified expression and compare the ...
LValue EmitPredefinedLValue(const PredefinedExpr *E)
void EmitCheck(ArrayRef< std::pair< llvm::Value *, SanitizerKind::SanitizerOrdinal > > Checked, SanitizerHandler Check, ArrayRef< llvm::Constant * > StaticArgs, ArrayRef< llvm::Value * > DynamicArgs, const TrapReason *TR=nullptr)
Create a basic block that will either trap or call a handler function in the UBSan runtime with the p...
LValue EmitDeclRefLValue(const DeclRefExpr *E)
LValue EmitStringLiteralLValue(const StringLiteral *E)
AggValueSlot CreateAggTemp(QualType T, const Twine &Name="tmp", RawAddress *Alloca=nullptr)
CreateAggTemp - Create a temporary memory object for the given aggregate type.
RValue getOrCreateOpaqueRValueMapping(const OpaqueValueExpr *e)
Given an opaque value expression, return its RValue mapping if it exists, otherwise create one.
bool HaveInsertPoint() const
HaveInsertPoint - True if an insertion point is defined.
RValue EmitAtomicLoad(LValue LV, SourceLocation SL, AggValueSlot Slot=AggValueSlot::ignored())
CGDebugInfo * getDebugInfo()
llvm::Value * emitScalarConstant(const ConstantEmission &Constant, Expr *E)
llvm::Value * getTypeSize(QualType Ty)
Returns calculated size of the specified type.
bool EmitLifetimeStart(llvm::Value *Addr)
Emit a lifetime.begin marker if some criteria are satisfied.
LValue EmitUnsupportedLValue(const Expr *E, const char *Name)
EmitUnsupportedLValue - Emit a dummy l-value using the type of E and issue an ErrorUnsupported style ...
LValue MakeRawAddrLValue(llvm::Value *V, QualType T, CharUnits Alignment, AlignmentSource Source=AlignmentSource::Type)
Same as MakeAddrLValue above except that the pointer is known to be unsigned.
llvm::MDNode * buildAllocToken(QualType AllocType)
Build metadata used by the AllocToken instrumentation.
RValue EmitCXXMemberCallExpr(const CXXMemberCallExpr *E, ReturnValueSlot ReturnValue, llvm::CallBase **CallOrInvoke=nullptr)
LValue EmitLValueForFieldInitialization(LValue Base, const FieldDecl *Field)
EmitLValueForFieldInitialization - Like EmitLValueForField, except that if the Field is a reference,...
llvm::Value * EmitToMemory(llvm::Value *Value, QualType Ty)
EmitToMemory - Change a scalar value from its value representation to its in-memory representation.
Address emitBlockByrefAddress(Address baseAddr, const VarDecl *V, bool followForward=true)
BuildBlockByrefAddress - Computes the location of the data in a variable which is declared as __block...
llvm::AllocaInst * CreateTempAlloca(llvm::Type *Ty, const Twine &Name="tmp", llvm::Value *ArraySize=nullptr)
CreateTempAlloca - This creates an alloca and inserts it into the entry block if ArraySize is nullptr...
LValue getOrCreateOpaqueLValueMapping(const OpaqueValueExpr *e)
Given an opaque value expression, return its LValue mapping if it exists, otherwise create one.
bool EmitScalarRangeCheck(llvm::Value *Value, QualType Ty, SourceLocation Loc)
Check if the scalar Value is within the valid range for the given type Ty.
ComplexPairTy EmitComplexExpr(const Expr *E, bool IgnoreReal=false, bool IgnoreImag=false)
EmitComplexExpr - Emit the computation of the specified expression of complex type,...
RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee, ReturnValueSlot ReturnValue, const CallArgList &Args, llvm::CallBase **CallOrInvoke, bool IsMustTail, SourceLocation Loc, bool IsVirtualFunctionPointerThunk=false)
EmitCall - Generate a call of the given function, expecting the given result type,...
llvm::ConstantInt * getUBSanFunctionTypeHash(QualType T) const
Return a type hash constant for a function instrumented by -fsanitize=function.
LValue EmitHLSLArrayAssignLValue(const BinaryOperator *E)
RawAddress CreateMemTempWithoutCast(QualType T, const Twine &Name="tmp")
CreateMemTemp - Create a temporary memory object of the given type, with appropriate alignmen without...
LValue EmitVAArgExprLValue(const VAArgExpr *E)
bool IsInPreservedAIRegion
True if CodeGen currently emits code inside presereved access index region.
RValue EmitAnyExprToTemp(const Expr *E)
EmitAnyExprToTemp - Similarly to EmitAnyExpr(), however, the result will always be accessible even if...
VlaSizePair getVLASize(const VariableArrayType *vla)
Returns an LLVM value that corresponds to the size, in non-variably-sized elements,...
LValue EmitStmtExprLValue(const StmtExpr *E)
llvm::Value * EmitARCLoadWeakRetained(Address addr)
i8* @objc_loadWeakRetained(i8** addr)
llvm::CallInst * EmitNounwindRuntimeCall(llvm::FunctionCallee callee, const Twine &name="")
ASTContext & getContext() const
RawAddress CreateTempAllocaWithoutCast(llvm::Type *Ty, CharUnits align, const Twine &Name="tmp", llvm::Value *ArraySize=nullptr)
CreateTempAlloca - This creates a alloca and inserts it into the entry block.
llvm::Value * EmitWithOriginalRHSBitfieldAssignment(const BinaryOperator *E, llvm::Value **Previous, QualType *SrcType)
Retrieve the implicit cast expression of the rhs in a binary operator expression by passing pointers ...
llvm::Value * EmitLoadOfScalar(Address Addr, bool Volatile, QualType Ty, SourceLocation Loc, AlignmentSource Source=AlignmentSource::Type, bool isNontemporal=false)
EmitLoadOfScalar - Load a scalar value from an address, taking care to appropriately convert from the...
LValue EmitHLSLOutArgExpr(const HLSLOutArgExpr *E, CallArgList &Args, QualType Ty, bool IsImplicitObject=false)
void Destroyer(CodeGenFunction &CGF, Address addr, QualType ty)
void EmitStoreOfComplex(ComplexPairTy V, LValue dest, bool isInit)
EmitStoreOfComplex - Store a complex number into the specified l-value.
const Decl * CurFuncDecl
CurFuncDecl - Holds the Decl for the current outermost non-closure context.
LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E)
Address EmitAddressOfPFPField(Address RecordPtr, const PFPField &Field)
void EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit=false)
EmitStoreThroughLValue - Store the specified rvalue into the specified lvalue, where both are guarant...
Address EmitArrayToPointerDecay(const Expr *Array, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr)
void pushLifetimeExtendedDestroy(CleanupKind kind, Address addr, QualType type, Destroyer *destroyer, bool useEHCleanupForArray)
RValue EmitBuiltinExpr(const GlobalDecl GD, unsigned BuiltinID, const CallExpr *E, ReturnValueSlot ReturnValue)
RValue GetUndefRValue(QualType Ty)
GetUndefRValue - Get an appropriate 'undef' rvalue for the given type.
llvm::Instruction * getPostAllocaInsertPoint()
Return PostAllocaInsertPt.
void EmitAllocToken(llvm::CallBase *CB, QualType AllocType)
Emit and set additional metadata used by the AllocToken instrumentation.
LValue EmitComplexAssignmentLValue(const BinaryOperator *E)
Emit an l-value for an assignment (simple or compound) of complex type.
LValue EmitCastLValue(const CastExpr *E)
EmitCastLValue - Casts are never lvalues unless that cast is to a reference type.
llvm::Value * EmitPointerArithmetic(const BinaryOperator *BO, Expr *pointerOperand, llvm::Value *pointer, Expr *indexOperand, llvm::Value *index, bool isSubtraction)
Emit pointer + index arithmetic.
LValue EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E)
LValue EmitLoadOfPointerLValue(Address Ptr, const PointerType *PtrTy)
LValue EmitOMPCapturedBindingLValue(const BindingDecl *BD)
Emit an LValue for a structured binding captured in an OpenMP region.
llvm::Value * EmitCheckValue(llvm::Value *V)
Convert a value into a format suitable for passing to a runtime sanitizer handler.
void EmitAnyExprToMem(const Expr *E, Address Location, Qualifiers Quals, bool IsInitializer)
EmitAnyExprToMem - Emits the code necessary to evaluate an arbitrary expression into the given memory...
RValue EmitAnyExpr(const Expr *E, AggValueSlot aggSlot=AggValueSlot::ignored(), bool ignoreResult=false)
EmitAnyExpr - Emit code to compute the specified expression which can have any type.
LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E)
llvm::DenseMap< const ValueDecl *, FieldDecl * > LambdaCaptureFields
RValue EmitUnsupportedRValue(const Expr *E, const char *Name)
EmitUnsupportedRValue - Emit a dummy r-value using the type of E and issue an ErrorUnsupported style ...
llvm::CallInst * EmitRuntimeCall(llvm::FunctionCallee callee, const Twine &name="")
std::pair< LValue, LValue > EmitHLSLOutArgLValues(const HLSLOutArgExpr *E, QualType Ty)
LValue EmitObjCSelectorLValue(const ObjCSelectorExpr *E)
llvm::Type * ConvertTypeForMem(QualType T)
LValue EmitCallExprLValue(const CallExpr *E, llvm::CallBase **CallOrInvoke=nullptr)
RValue EmitLoadOfBitfieldLValue(LValue LV, SourceLocation Loc)
llvm::Value * EmitARCLoadWeak(Address addr)
i8* @objc_loadWeak(i8** addr) Essentially objc_autorelease(objc_loadWeakRetained(addr)).
LValue EmitLValueForLambdaField(const FieldDecl *Field)
void markStmtMaybeUsed(const Stmt *S)
CodeGenTypes & getTypes() const
static TypeEvaluationKind getEvaluationKind(QualType T)
getEvaluationKind - Return the TypeEvaluationKind of QualType T.
llvm::Value * EmitIvarOffset(const ObjCInterfaceDecl *Interface, const ObjCIvarDecl *Ivar)
bool IsSanitizerScope
True if CodeGen currently emits code implementing sanitizer checks.
void FlattenAccessAndTypeLValue(LValue LVal, SmallVectorImpl< LValue > &AccessList)
LValue EmitCoyieldLValue(const CoyieldExpr *E)
void EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc, LValue LV, QualType Type, SanitizerSet SkippedChecks=SanitizerSet(), llvm::Value *ArraySize=nullptr)
void EmitCfiSlowPathCheck(SanitizerKind::SanitizerOrdinal Ordinal, llvm::Value *Cond, llvm::ConstantInt *TypeId, llvm::Value *Ptr, ArrayRef< llvm::Constant * > StaticArgs)
Emit a slow path cross-DSO CFI check which calls __cfi_slowpath if Cond if false.
llvm::SmallVector< const ParmVarDecl *, 4 > FnArgs
Save Parameter Decl for coroutine.
void EmitCXXTemporary(const CXXTemporary *Temporary, QualType TempType, Address Ptr)
Emits all the code to cause the given temporary to be cleaned up.
llvm::Value * authPointerToPointerCast(llvm::Value *ResultPtr, QualType SourceType, QualType DestType)
LValue EmitUnaryOpLValue(const UnaryOperator *E)
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...
bool LValueIsSuitableForInlineAtomic(LValue Src)
An LValue is a candidate for having its loads and stores be made atomic if we are operating under /vo...
LValue EmitCheckedLValue(const Expr *E, TypeCheckKind TCK)
Same as EmitLValue but additionally we generate checking code to guard against undefined behavior.
RawAddress CreateMemTemp(QualType T, const Twine &Name="tmp", RawAddress *Alloca=nullptr)
CreateMemTemp - Create a temporary memory object of the given type, with appropriate alignmen and cas...
Address EmitLoadOfReference(LValue RefLVal, LValueBaseInfo *PointeeBaseInfo=nullptr, TBAAAccessInfo *PointeeTBAAInfo=nullptr)
RValue EmitRValueForField(LValue LV, const FieldDecl *FD, SourceLocation Loc)
llvm::Value * EmitObjCExtendObjectLifetime(QualType T, llvm::Value *Ptr)
LValue EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E)
llvm::Type * convertTypeForLoadStore(QualType ASTTy, llvm::Type *LLVMTy=nullptr)
bool sanitizePerformTypeCheck() const
Whether any type-checking sanitizers are enabled.
Address EmitExtVectorElementLValue(LValue V)
Generates lvalue for partial ext_vector access.
llvm::Value * EmitCheckedInBoundsGEP(llvm::Type *ElemTy, llvm::Value *Ptr, ArrayRef< llvm::Value * > IdxList, bool SignedIndices, bool IsSubtraction, SourceLocation Loc, const Twine &Name="")
Same as IRBuilder::CreateInBoundsGEP, but additionally emits a check to detect undefined behavior whe...
void EmitInitializationToLValue(const Expr *E, LValue LV, AggValueSlot::IsZeroed_t IsZeroed=AggValueSlot::IsNotZeroed)
EmitInitializationToLValue - Emit an initializer to an LValue.
void EmitAggExpr(const Expr *E, AggValueSlot AS)
EmitAggExpr - Emit the computation of the specified expression of aggregate type.
Address emitAddrOfRealComponent(Address complex, QualType complexType)
llvm::Value * EmitScalarExpr(const Expr *E, bool IgnoreResultAssign=false)
EmitScalarExpr - Emit the computation of the specified expression of LLVM scalar type,...
const FunctionDecl * getCurrentFunctionDecl() const
RValue EmitLoadOfExtVectorElementLValue(LValue V)
static bool hasAggregateEvaluationKind(QualType T)
static bool IsWrappedCXXThis(const Expr *E)
Check if E is a C++ "this" pointer wrapped in value-preserving casts.
void EmitCallArgs(CallArgList &Args, PrototypeWrapper Prototype, llvm::iterator_range< CallExpr::const_arg_iterator > ArgRange, AbstractCallee AC=AbstractCallee(), unsigned ParamsToSkip=0, EvaluationOrder Order=EvaluationOrder::Default)
EmitCallArgs - Emit call arguments for a function.
llvm::Value * EmitMatrixIndexExpr(const Expr *E)
LValue MakeAddrLValue(Address Addr, QualType T, AlignmentSource Source=AlignmentSource::Type)
void EmitTrapCheck(llvm::Value *Checked, SanitizerHandler CheckHandlerID, bool NoMerge=false, const TrapReason *TR=nullptr)
Create a basic block that will call the trap intrinsic, and emit a conditional branch to it,...
void EmitTrapCallAndMakeUnreachable()
Emit a call to '@llvm.trap()' and clear the current insert point.
void FinishFunction(SourceLocation EndLoc=SourceLocation())
FinishFunction - Complete IR generation of the current function.
void EmitAtomicStore(RValue rvalue, LValue lvalue, bool isInit)
llvm::Value * EmitFromMemory(llvm::Value *Value, QualType Ty)
EmitFromMemory - Change a scalar value from its memory representation to its value representation.
const CallExpr * MustTailCall
uint64_t getProfileCount(const Stmt *S)
Get the profiler's count for the given statement.
llvm::Value * EmitLoadOfCountedByField(const Expr *Base, const FieldDecl *FD, const FieldDecl *CountDecl)
Build an expression accessing the "counted_by" field.
Address GetAddrOfLocalVar(const VarDecl *VD)
GetAddrOfLocalVar - Return the address of a local variable.
void EmitUnreachable(SourceLocation Loc)
Emit a reached-unreachable diagnostic if Loc is valid and runtime checking is enabled.
bool ConstantFoldsToSimpleInteger(const Expr *Cond, bool &Result, bool AllowLabels=false)
ConstantFoldsToSimpleInteger - If the specified expression does not fold to a constant,...
void ErrorUnsupported(const Stmt *S, const char *Type)
ErrorUnsupported - Print out an error that codegen doesn't support the specified stmt yet.
LValue EmitCXXTypeidLValue(const CXXTypeidExpr *E)
llvm::Function * generateDestroyHelper(Address addr, QualType type, Destroyer *destroyer, bool useEHCleanupForArray, const VarDecl *VD)
generateDestroyHelper - Generates a helper function which, when invoked, destroys the given object.
LValue EmitMemberExpr(const MemberExpr *E)
std::pair< llvm::Value *, llvm::Value * > ComplexPairTy
Address ReturnValue
ReturnValue - The temporary alloca to hold the return value.
ConstantEmission tryEmitAsConstant(const DeclRefExpr *RefExpr)
Try to emit a reference to the given value without producing it as an l-value.
LValue EmitLValue(const Expr *E, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
EmitLValue - Emit code to compute a designator that specifies the location of the expression.
void EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst)
Store of global named registers are always calls to intrinsics.
bool isOpaqueValueEmitted(const OpaqueValueExpr *E)
isOpaqueValueEmitted - Return true if the opaque value expression has already been emitted.
std::pair< llvm::Value *, CGPointerAuthInfo > EmitOrigPointerRValue(const Expr *E)
Retrieve a pointer rvalue and its ptrauth info.
llvm::Value * EmitARCStoreWeak(Address addr, llvm::Value *value, bool ignored)
i8* @objc_storeWeak(i8** addr, i8* value) Returns value.
void EnsureInsertPoint()
EnsureInsertPoint - Ensure that an insertion point is defined so that emitted IR has a place to go.
llvm::LLVMContext & getLLVMContext()
RValue EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E, const CXXMethodDecl *MD, ReturnValueSlot ReturnValue, llvm::CallBase **CallOrInvoke)
static Destroyer destroyARCStrongPrecise
LValue EmitMatrixElementExpr(const MatrixElementExpr *E)
void incrementProfileCounter(const Stmt *S, llvm::Value *StepV=nullptr)
Increment the profiler's counter for the given statement by StepV.
static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts)
getAccessedFieldNo - Given an encoded value and a result number, return the input field number being ...
llvm::Value * EmitScalarConversion(llvm::Value *Src, QualType SrcTy, QualType DstTy, SourceLocation Loc)
Emit a conversion from the specified type to the specified destination type, both of which are LLVM s...
LoadedLValueCapture * CurLoadedLValueCapture
void EmitVariablyModifiedType(QualType Ty)
EmitVLASize - Capture all the sizes for the VLA expressions in the given variably-modified type and s...
static bool ShouldNullCheckClassCastValue(const CastExpr *Cast)
llvm::Value * EmitNonNullRValueCheck(RValue RV, QualType T)
Create a check that a scalar RValue is non-null.
void EmitStoreOfScalar(llvm::Value *Value, Address Addr, bool Volatile, QualType Ty, AlignmentSource Source=AlignmentSource::Type, bool isInit=false, bool isNontemporal=false)
EmitStoreOfScalar - Store a scalar value to an address, taking care to appropriately convert from the...
bool hasLabelBeenSeenInCurrentScope() const
Return true if a label was seen in the current scope.
llvm::Value * EmitDynamicCast(Address V, const CXXDynamicCastExpr *DCE)
void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false)
EmitBlock - Emit the given block.
LValue MakeNaturalAlignRawAddrLValue(llvm::Value *V, QualType T)
llvm::Value * EmitCXXTypeidExpr(const CXXTypeidExpr *E)
This class organizes the cross-function state that is used while generating LLVM code.
void EmitExplicitCastExprType(const ExplicitCastExpr *E, CodeGenFunction *CGF=nullptr)
Emit type info if type of an expression is a variably modified type.
CGHLSLRuntime & getHLSLRuntime()
Return a reference to the configured HLSL runtime.
llvm::Module & getModule() const
llvm::FunctionCallee CreateRuntimeFunction(llvm::FunctionType *Ty, StringRef Name, llvm::AttributeList ExtraAttrs=llvm::AttributeList(), bool Local=false, bool AssumeConvergent=false)
Create or return a runtime function declaration with the specified type and name.
CGDebugInfo * getModuleDebugInfo()
llvm::Constant * performAddrSpaceCast(llvm::Constant *Src, llvm::Type *DestTy)
llvm::Constant * getRawFunctionPointer(GlobalDecl GD, llvm::Type *Ty=nullptr)
Return a function pointer for a reference to the given function.
llvm::FunctionCallee getAddrAndTypeOfCXXStructor(GlobalDecl GD, const CGFunctionInfo *FnInfo=nullptr, llvm::FunctionType *FnType=nullptr, bool DontDefer=false, ForDefinition_t IsForDefinition=NotForDefinition)
llvm::Constant * GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty=nullptr, bool ForVTable=false, bool DontDefer=false, ForDefinition_t IsForDefinition=NotForDefinition)
Return the address of the given function.
llvm::Constant * getFunctionPointer(GlobalDecl GD, llvm::Type *Ty=nullptr)
Return the ABI-correct function pointer value for a reference to the given function.
const LangOptions & getLangOpts() const
CGCUDARuntime & getCUDARuntime()
Return a reference to the configured CUDA runtime.
CharUnits getNaturalTypeAlignment(QualType T, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr, bool forPointeeType=false)
CodeGenTypes & getTypes()
CGPointerAuthInfo getPointerAuthInfoForPointeeType(QualType type)
llvm::GlobalValue::LinkageTypes getLLVMLinkageVarDefinition(const VarDecl *VD)
Returns LLVM linkage for a declarator.
CGCXXABI & getCXXABI() const
ConstantAddress GetWeakRefReference(const ValueDecl *VD)
Get a reference to the target of VD.
CGOpenMPRuntime & getOpenMPRuntime()
Return a reference to the configured OpenMP runtime.
TBAAAccessInfo getTBAAAccessInfo(QualType AccessType)
getTBAAAccessInfo - Get TBAA information that describes an access to an object of the given type.
ASTContext & getContext() const
TBAAAccessInfo mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo, TBAAAccessInfo TargetInfo)
mergeTBAAInfoForCast - Get merged TBAA information for the purposes of type casts.
llvm::Constant * GetAddrOfGlobalVar(const VarDecl *D, llvm::Type *Ty=nullptr, ForDefinition_t IsForDefinition=NotForDefinition)
Return the llvm::Constant for the address of the given global variable.
const CodeGenOptions & getCodeGenOpts() const
StringRef getMangledName(GlobalDecl GD)
CharUnits getNaturalPointeeTypeAlignment(QualType T, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr)
llvm::LLVMContext & getLLVMContext()
llvm::Function * getIntrinsic(unsigned IID, ArrayRef< llvm::Type * > Tys={})
ConstantAddress GetAddrOfGlobalTemporary(const MaterializeTemporaryExpr *E, const Expr *Inner)
Returns a pointer to a global variable representing a temporary with static or thread storage duratio...
LangAS GetGlobalConstantAddressSpace() const
Return the AST address space of constant literal, which is used to emit the constant literal as globa...
const CGRecordLayout & getCGRecordLayout(const RecordDecl *)
getCGRecordLayout - Return record layout info for the given record decl.
llvm::Type * ConvertTypeForMem(QualType T)
ConvertTypeForMem - Convert type T into a llvm::Type.
A specialization of Address that requires the address to be an LLVM Constant.
llvm::Constant * getPointer() const
llvm::Constant * emitAbstract(const Expr *E, QualType T)
Emit the result of the given expression as an abstract constant, asserting that it succeeded.
llvm::Constant * tryEmitConstantExpr(const ConstantExpr *CE)
FunctionArgList - Type for representing both the decl and type of parameters to a function.
AlignmentSource getAlignmentSource() const
LValue - This represents an lvalue references.
llvm::Value * getMatrixRowIdx() const
static LValue MakeMatrixRow(Address Addr, llvm::Value *RowIdx, QualType MatrixTy, LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo)
Expr * getBaseIvarExp() const
llvm::Constant * getExtVectorElts() const
static LValue MakeGlobalReg(llvm::Value *V, CharUnits alignment, QualType type)
llvm::Constant * getMatrixRowElts() const
bool isObjCStrong() const
bool isMatrixRowSwizzle() const
bool isGlobalObjCRef() const
bool isVolatileQualified() const
RValue asAggregateRValue() const
llvm::Value * getPointer(CodeGenFunction &CGF) const
llvm::Value * getMatrixIdx() const
llvm::Value * getGlobalReg() const
static LValue MakeAddr(Address Addr, QualType type, ASTContext &Context, LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo)
const Qualifiers & getQuals() const
static LValue MakeExtVectorElt(Address Addr, llvm::Constant *Elts, QualType type, LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo)
Address getAddress() const
unsigned getVRQualifiers() const
bool isExtVectorElt() const
llvm::Value * getVectorIdx() const
void setNontemporal(bool Value)
LValueBaseInfo getBaseInfo() const
void setARCPreciseLifetime(ARCPreciseLifetime_t value)
const CGBitFieldInfo & getBitFieldInfo() const
bool isThreadLocalRef() const
KnownNonNull_t isKnownNonNull() const
TBAAAccessInfo getTBAAInfo() const
void setNonGC(bool Value)
static LValue MakeMatrixRowSwizzle(Address MatAddr, llvm::Value *RowIdx, llvm::Constant *Cols, QualType MatrixTy, LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo)
Address getVectorAddress() const
bool isNontemporal() const
static LValue MakeBitfield(Address Addr, const CGBitFieldInfo &Info, QualType type, LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo)
Create a new object to represent a bit-field access.
static LValue MakeVectorElt(Address vecAddress, llvm::Value *Idx, QualType type, LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo)
void setAddress(Address address)
Address getExtVectorAddress() const
static LValue MakeMatrixElt(Address matAddress, llvm::Value *Idx, QualType type, LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo)
Address getMatrixAddress() const
Address getBitFieldAddress() const
RValue - This trivial value class is used to represent the result of an expression that is evaluated.
static RValue get(llvm::Value *V)
static RValue getAggregate(Address addr, bool isVolatile=false)
Convert an Address to an RValue.
static RValue getComplex(llvm::Value *V1, llvm::Value *V2)
Address getAggregateAddress() const
getAggregateAddr() - Return the Value* of the address of the aggregate.
llvm::Value * getScalarVal() const
getScalarVal() - Return the Value* of this scalar value.
An abstract representation of an aligned address.
CharUnits getAlignment() const
Return the alignment of this pointer.
llvm::Type * getElementType() const
Return the type of the values stored in this address.
llvm::Value * getPointer() const
unsigned getAddressSpace() const
Return the address space that this address resides in.
ReturnValueSlot - Contains the address where the return value of a function can be stored,...
StringRef getCategory() const
StringRef getMessage() const
Complex values, per C99 6.2.5p11.
QualType getElementType() const
CompoundLiteralExpr - [C99 6.5.2.5].
const Expr * getInitializer() const
An expression that occurs in a constant context and the result of evaluating the expression.
Represents a concrete matrix type with constant number of rows and columns.
unsigned getNumColumns() const
Returns the number of columns in the matrix.
unsigned getNumRows() const
Returns the number of rows in the matrix.
Represents a sugar type with __counted_by or __sized_by annotations, including their _or_null variant...
RecordDecl * getOuterLexicalRecordContext()
Retrieve the outermost lexically enclosing record context.
A reference to a declared variable, function, enum, etc.
bool refersToEnclosingVariableOrCapture() const
Does this DeclRefExpr refer to an enclosing local or a captured variable?
static DeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc, QualType T, ExprValueKind VK, NamedDecl *FoundD=nullptr, const TemplateArgumentListInfo *TemplateArgs=nullptr, NonOdrUseReason NOUR=NOUR_None)
NonOdrUseReason isNonOdrUse() const
Is this expression a non-odr-use reference, and if so, why?
SourceLocation getLocation() const
Decl - This represents one declaration (or definition), e.g.
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required.
DeclContext * getDeclContext()
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
const Expr * getBase() const
ExplicitCastExpr - An explicit cast written in the source code.
This represents one expression.
const Expr * skipRValueSubobjectAdjustments(SmallVectorImpl< const Expr * > &CommaLHS, SmallVectorImpl< SubobjectAdjustment > &Adjustments) const
Walk outwards from an expression we want to bind a reference to and find the expression whose lifetim...
Expr * IgnoreParenNoopCasts(const ASTContext &Ctx) LLVM_READONLY
Skip past any parentheses and casts which do not change the value (including ptr->int casts of the sa...
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
bool EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsLValue - Evaluate an expression to see if we can fold it to an lvalue with link time known ...
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
Decl * getReferencedDeclOfCallee()
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
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...
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
bool isOBJCGCCandidate(ASTContext &Ctx) const
isOBJCGCCandidate - Return true if this expression may be used in a read/ write barrier.
ExtVectorElementExpr - This represents access to specific elements of a vector, and may occur on the ...
bool isArrow() const
isArrow - Return true if the base expression is a pointer to vector, return false if the base express...
void getEncodedElementAccess(SmallVectorImpl< uint32_t > &Elts) const
getEncodedElementAccess - Encode the elements accessed into an llvm aggregate Constant of ConstantInt...
ExtVectorType - Extended vector type.
Represents a member of a struct/union/class.
bool isBitField() const
Determines whether this field is a bitfield.
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
const FieldDecl * findCountedByField() const
Find the FieldDecl specified in a FAM's "counted_by" attribute.
const Expr * getSubExpr() const
Represents a function declaration or definition.
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
FunctionType - C99 6.7.5.3 - Function Declarators.
GlobalDecl - represents a global declaration.
const Decl * getDecl() const
This class represents temporary values used to represent inout and out arguments in HLSL.
const OpaqueValueExpr * getCastedTemporary() const
const OpaqueValueExpr * getOpaqueArgLValue() const
bool isInOut() const
returns true if the parameter is inout and false if the parameter is out.
const Expr * getWritebackCast() const
const Expr * getArgLValue() const
Return the l-value expression that was written as the argument in source.
static ImplicitParamDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, ImplicitParamKind ParamKind)
Create implicit parameter.
Describes an C or C++ initializer list.
bool isTransparent() const
Is this a transparent initializer list (that is, an InitListExpr that is purely syntactic,...
const Expr * getInit(unsigned Init) const
StrictFlexArraysLevelKind
std::optional< llvm::AllocTokenMode > AllocTokenMode
The allocation token mode.
Represents a prvalue temporary that is written into memory so that a reference can bind to it.
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
Expr * getSubExpr() const
Retrieve the temporary-generating subexpression whose value will be materialized into a glvalue.
ValueDecl * getExtendingDecl()
Get the declaration which triggered the lifetime-extension of this temporary, if any.
void getEncodedElementAccess(SmallVectorImpl< uint32_t > &Elts) const
getEncodedElementAccess - Encode the elements accessed into an llvm aggregate Constant of ConstantInt...
MatrixSingleSubscriptExpr - Matrix single subscript expression for the MatrixType extension when you ...
MatrixSubscriptExpr - Matrix subscript expression for the MatrixType extension.
bool isIncomplete() const
QualType getElementType() const
Returns type of the elements being stored in the matrix.
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
NonOdrUseReason isNonOdrUse() const
Is this expression a non-odr-use reference, and if so, why?
SourceLocation getExprLoc() const LLVM_READONLY
A pointer to member type per C++ 8.3.3 - Pointers to members.
bool isObjCBOOLType(QualType T) const
Returns true if.
This represents a decl that may have a name.
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
A C++ nested-name-specifier augmented with source location information.
ObjCEncodeExpr, used for @encode in Objective-C.
Represents an ObjC class declaration.
ObjCIvarDecl - Represents an ObjC instance variable.
ObjCIvarRefExpr - A reference to an ObjC instance variable.
const Expr * getBase() const
An expression that sends a message to the given Objective-C object or class.
const ObjCMethodDecl * getMethodDecl() const
QualType getReturnType() const
ObjCSelectorExpr used for @selector in Objective-C.
Selector getSelector() const
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Expr * getSourceExpr() const
The source expression of an opaque value expression is the expression which originally generated the ...
const Expr * getSubExpr() const
Pointer-authentication qualifiers.
PointerType - C99 6.7.5.1 - Pointer Declarators.
QualType getPointeeType() const
[C99 6.4.2.2] - A predefined identifier such as func.
StringRef getIdentKindName() const
PredefinedIdentKind getIdentKind() const
StringLiteral * getFunctionName()
Represents an unpacked "presumed" location which can be presented to the user.
unsigned getColumn() const
Return the presumed column number of this location.
const char * getFilename() const
Return the presumed filename of this location.
unsigned getLine() const
Return the presumed line number of this location.
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
semantics_iterator semantics_end()
semantics_iterator semantics_begin()
const Expr *const * const_semantics_iterator
Expr * getResultExpr()
Return the result-bearing expression, or null if there is none.
Expr * getSyntacticForm()
Return the syntactic form of this expression, i.e.
A (possibly-)qualified type.
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
PointerAuthQualifier getPointerAuth() const
QualType withoutLocalFastQualifiers() const
bool isNull() const
Return true if this QualType doesn't point to a type yet.
LangAS getAddressSpace() const
Return the address space of this type.
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
QualType withCVRQualifiers(unsigned CVR) const
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
bool isConstantStorage(const ASTContext &Ctx, bool ExcludeCtor, bool ExcludeDtor)
The collection of all-type qualifiers we support.
unsigned getCVRQualifiers() const
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
@ OCL_None
There is no lifetime qualification on this type.
@ OCL_Weak
Reading or writing from this object requires a barrier call.
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
void addCVRQualifiers(unsigned mask)
void addQualifiers(Qualifiers Q)
Add the qualifiers from the given set to this set.
void setAddressSpace(LangAS space)
PointerAuthQualifier getPointerAuth() const
ObjCLifetime getObjCLifetime() const
Represents a struct/union/class.
field_range fields() const
Scope - A scope is a transient data structure that is used while parsing the program.
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
PresumedLoc getPresumedLoc(SourceLocation Loc, bool UseLineDirectives=true) const
Returns the "presumed" location of a SourceLocation specifies.
StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
StmtClass getStmtClass() const
SourceLocation getBeginLoc() const LLVM_READONLY
StringLiteral - This represents a string literal expression, e.g.
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
The base class of the type hierarchy.
bool isBlockPointerType() const
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
bool isPackedVectorBoolType(const ASTContext &ctx) const
bool hasAttr(attr::Kind AK) const
Determine whether this type had the specified attribute applied to it (looking through top-level type...
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
const ArrayType * castAsArrayTypeUnsafe() const
A variant of castAs<> for array type which silently discards qualifiers from the outermost type.
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
bool isConstantArrayType() const
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
bool isFunctionPointerType() const
CXXRecordDecl * castAsCXXRecordDecl() const
bool isArithmeticType() const
bool isConstantMatrixType() const
bool isPointerType() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
const T * castAs() const
Member-template castAs<specific type>.
bool isReferenceType() const
bool isEnumeralType() const
bool isVariableArrayType() const
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
bool isExtVectorBoolType() const
bool isBitIntType() const
bool isConstantMatrixBoolType() const
bool isAnyComplexType() const
bool hasPointeeToCFIUncheckedCalleeFunctionType() const
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
bool isAtomicType() const
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
bool isObjectType() const
Determine whether this type is an object type.
bool isHLSLResourceRecord() const
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
bool isFunctionType() const
bool isObjCObjectPointerType() const
bool isVectorType() const
bool isFloatingType() const
bool isAnyPointerType() const
bool isSubscriptableVectorType() const
const T * getAs() const
Member-template getAs<specific type>'.
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
bool isRecordType() const
bool isHLSLResourceRecordArray() const
bool hasBooleanRepresentation() const
Determine whether this type has a boolean representation – i.e., it is a boolean type,...
bool isCFIUncheckedCalleeFunctionType() const
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
SourceLocation getExprLoc() const
Expr * getSubExpr() const
Represents a call to the builtin function __builtin_va_arg.
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Represents a variable declaration or definition.
TLSKind getTLSKind() const
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
@ TLS_Dynamic
TLS with a dynamic initializer.
@ TLS_None
Not a TLS variable.
Represents a C array with a specified size that is not an integer-constant-expression.
Represents a GCC generic vector type.
unsigned getNumElements() const
bool isAAPCS(const TargetInfo &TargetInfo)
Helper method to check if the underlying ABI is AAPCS.
QualType getFixedSizeElementType(const ASTContext &Ctx, const VariableArrayType *VLA)
Strip off the variably-modified array types wrapping VLA and return the first element type that has a...
bool onlyHasInlineBuiltinDeclaration(const FunctionDecl *FD)
Detect the unusual situation where an inline version of a builtin is shadowed by a non-inline version...
EvaluationOrder getCallArgEvaluationOrder(const CallExpr *E)
Returns the argument evaluation order the language requires for the given call.
ConstantEmissionKind checkVarTypeForConstantEmission(QualType Type)
Can we constant-emit a load of a reference to a variable of the given type?
bool isEmptyFieldForLayout(const ASTContext &Ctx, const FieldDecl *FD)
Return true iff the field is "empty", that is, either a zero-width bit-field or an isEmptyRecordForLa...
ConstantEmissionKind
How a reference to a variable can be emitted as a constant.
AlignmentSource
The source of the alignment of an l-value; an expression of confidence in the alignment actually matc...
@ Type
The l-value was considered opaque, so the alignment was determined from a type.
@ Decl
The l-value was an access to a declared entity or something equivalently strong, like the address of ...
@ EHCleanup
Denotes a cleanup that should run when a scope is exited using exceptional control flow (a throw stat...
static AlignmentSource getFieldAlignmentSource(AlignmentSource Source)
Given that the base address has the given alignment source, what's our confidence in the alignment of...
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const AstTypeMatcher< ArrayType > arrayType
const AstTypeMatcher< FunctionType > functionType
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
std::optional< llvm::AllocTokenMetadata > getAllocTokenMetadata(QualType T, const ASTContext &Ctx)
Get the information required for construction of an allocation token ID.
QualType inferPossibleType(const CallExpr *E, const ASTContext &Ctx, const CastExpr *CastE)
Infer the possible allocated type from an allocation call expression.
Top level wrappers for InstallAPI frontend operations.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
bool isa(CodeGen::Address addr)
@ OK_BitField
A bitfield object is a bitfield on a C or C++ record.
bool isMatrixRowMajor(const LangOptions &LangOpts, QualType T)
Returns true if matrices of T should be laid out in row-major order.
@ Asm
Assembly: we accept this only so that we can preprocess it.
StorageDuration
The storage duration for an object (per C++ [basic.stc]).
@ SD_Thread
Thread storage duration.
@ SD_Static
Static storage duration.
@ SD_FullExpression
Full-expression storage duration (for temporaries).
@ SD_Automatic
Automatic storage duration (most local variables).
@ SD_Dynamic
Dynamic storage duration.
@ Result
The result type of a method or function.
@ Dtor_Complete
Complete object dtor.
LangAS
Defines the address space values used by the address space qualifier of QualType.
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
SmallVector< CXXBaseSpecifier *, 4 > CXXCastPath
A simple array of base specifiers.
U cast(CodeGen::Address addr)
LangAS getLangASFromTargetAS(unsigned TargetAS)
@ Interface
The "__interface" keyword introduces the elaborated-type-specifier.
bool isLambdaMethod(const DeclContext *DC)
@ Other
Other implicit parameter.
@ NOUR_Unevaluated
This name appears in an unevaluated operand.
@ NOUR_Constant
This name appears as a potential result of an lvalue-to-rvalue conversion that is a constant expressi...
__INTPTR_TYPE__ intptr_t
A signed integer type with the property that any valid pointer to void can be converted to this type,...
int32_t uint32_t uint32_t __builtin_riscv_mhracc_i32 __builtin_riscv_mhraccu_u32 __builtin_riscv_mhraccsu_i32 __builtin_riscv_mhacc_h1_i32 __builtin_riscv_mhaccsu_h1_i32 __builtin_riscv_mulqr_i32 __builtin_riscv_mqrwacc_i64 __packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 __packed_splat2 __packed_splat4 uint16_t
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t int64_t
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t uint64_t __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 uint64_t
Structure with information about how a bitfield should be accessed.
CharUnits VolatileStorageOffset
The offset of the bitfield storage from the start of the struct.
unsigned VolatileOffset
The offset within a contiguous run of bitfields that are represented as a single "field" within the L...
unsigned Offset
The offset within a contiguous run of bitfields that are represented as a single "field" within the L...
unsigned VolatileStorageSize
The storage size in bits which should be used when accessing this bitfield.
unsigned Size
The total size of the bit-field, in bits, not including padding.
unsigned StorageSize
The storage size in bits which should be used when accessing this bitfield.
unsigned IsSigned
Whether the bit-field is signed.
Records the l-value that ScalarExprEmitter loads from when it emits a specific expression.
std::optional< LValue > LV
The recorded l-value, set if E was loaded by ScalarExprEmitter.
static Address getAddrOfThreadPrivate(CodeGenFunction &CGF, const VarDecl *VD, Address VDAddr, SourceLocation Loc)
Returns address of the threadprivate variable for the current thread.
llvm::PointerType * VoidPtrTy
llvm::IntegerType * Int64Ty
CharUnits getIntAlign() const
llvm::IntegerType * Int8Ty
i8, i16, i32, and i64
unsigned char PointerWidthInBits
The width of a pointer into the generic address space.
llvm::IntegerType * SizeTy
llvm::IntegerType * Int32Ty
llvm::IntegerType * IntPtrTy
llvm::PointerType * Int8PtrTy
CharUnits getPointerAlign() const
llvm::PointerType * DefaultPtrTy
llvm::MDNode * AccessType
AccessType - The final access type.
uint64_t Offset
Offset - The byte offset of the final access within the base one.
static TBAAAccessInfo getMayAliasInfo()
uint64_t Size
Size - The size of access, in bytes.
llvm::MDNode * BaseType
BaseType - The base/leading access type.
bool isIncomplete() const
EvalResult is a struct with detailed info about an evaluated expression.
APValue Val
Val - This is the value the expression can be folded to.
bool HasSideEffects
Whether the evaluated expression has side effects.
Describes how types, statements, expressions, and declarations should be printed.
unsigned SuppressInlineNamespace
Suppress printing parts of scope specifiers that correspond to inline namespaces.
@ Plain
E.g., (anonymous enum)/(unnamed struct)/etc.
unsigned AnonymousTagNameStyle
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.
An adjustment to be made to the temporary created when emitting a reference binding,...
@ DerivedToBaseAdjustment
@ MemberPointerAdjustment