llvmorg-github-actions[bot] wrote:
<!--LLVM PR SUMMARY COMMENT--> @llvm/pr-subscribers-clang-codegen Author: David Li (david-xl) <details> <summary>Changes</summary> Relands #<!-- -->241548 and #<!-- -->243991, reverted in #<!-- -->244677, with a fix. Three commits: #<!-- -->241548, unchanged #<!-- -->243991, unchanged New: use a pointer-free placement-new type only if it covers the whole allocation (please review this commit) A placement new may construct only a header, with pointers after it: ```c++ void *ptr = malloc(size + kPrefix); new (ptr) size_t(size); // pointers follow the header new (::operator new(n)) Header(...); // pointerful entries follow ``` Before the fix, such allocations wrongly got the pointer-free token. A pointer-free type from a placement new is now used only if: - the allocation size is a constant equal to the type's size, - it is an array new, or - the type ends in a flexible array member, or an array treated as one under -fstrict-flex-arrays (e.g. absl's CordRepFlat). Otherwise the cast heuristic and the fallback token apply, as before #<!-- -->241548. --- Patch is 31.19 KiB, truncated to 20.00 KiB below, full version: https://github.com/llvm/llvm-project/pull/244809.diff 8 Files Affected: - (modified) clang/docs/AllocToken.md (+17) - (modified) clang/docs/ReleaseNotes.md (+3) - (modified) clang/include/clang/AST/InferAlloc.h (+19-3) - (modified) clang/lib/AST/InferAlloc.cpp (+187-4) - (modified) clang/lib/CodeGen/CGBuiltin.cpp (+5-1) - (modified) clang/lib/CodeGen/CGExpr.cpp (+14-2) - (modified) clang/lib/CodeGen/CodeGenFunction.h (+6) - (modified) clang/test/CodeGenCXX/alloc-token.cpp (+359) ``````````diff diff --git a/clang/docs/AllocToken.md b/clang/docs/AllocToken.md index cca7136b652ab..c7a016e2fd9e7 100644 --- a/clang/docs/AllocToken.md +++ b/clang/docs/AllocToken.md @@ -56,6 +56,23 @@ The following command-line options affect generated token IDs: is of the form `2^k-1` (e.g. the default `SIZE_MAX`), all `k` bits are used and token IDs are in `[0, N]`, i.e. a token ID may be equal to `N`. +## Allocated Type Inference + +For `new` expressions the allocated type is known syntactically. For untyped +allocation functions such as `malloc`, the type is inferred heuristically from +the allocation call and its context, in this order: a `sizeof` in the size +argument, a placement `new` into the result, and a cast of the result. The +heuristics are syntactic: `sizeof` expressions and casts ignore control flow +and reassignments, and a placement `new` through a variable is only used if +the variable is initialized by the allocation call and otherwise only read +(variables that are reassigned, or whose address or reference is taken, are +not used for inference). Since a placement `new` may construct only a header +of the allocation, a pointer-free type from it is only used if the allocation +size is a constant equal to the type's size, for an array `new`, or if the type +ends in a flexible array member (or an array treated as one under +`-fstrict-flex-arrays`). If no type can be inferred, the allocation receives +the fallback token. + ## Querying Token IDs with `__builtin_infer_alloc_token` For use cases where the token ID must be known at compile time, Clang provides diff --git a/clang/docs/ReleaseNotes.md b/clang/docs/ReleaseNotes.md index 4f4cfaf7af73a..7809f7bb03694 100644 --- a/clang/docs/ReleaseNotes.md +++ b/clang/docs/ReleaseNotes.md @@ -1679,6 +1679,9 @@ The `alpha.cplusplus.UseAfterLifetimeEnd` checker was renamed to `alpha.core.Use normalize `cfi-icall` and `kcfi` function type metadata, leaving C++ class vtable, member-pointer, and `-fexperimental-call-graph-section` metadata canonical so whole-program devirtualization works reliably. (#GH242466) +- `-fsanitize=alloc-token` now also infers the allocated type from a placement + `new` into the result of an untyped allocation call, e.g. `new (malloc(n)) T` + or `void *p = malloc(n); new (p) T;`. ### Python Binding Changes diff --git a/clang/include/clang/AST/InferAlloc.h b/clang/include/clang/AST/InferAlloc.h index c3dc30204feaf..b9f86deec5a6c 100644 --- a/clang/include/clang/AST/InferAlloc.h +++ b/clang/include/clang/AST/InferAlloc.h @@ -15,15 +15,31 @@ #include "clang/AST/ASTContext.h" #include "clang/AST/Expr.h" +#include "llvm/ADT/DenseMap.h" +#include "llvm/ADT/STLFunctionalExtras.h" #include "llvm/Support/AllocToken.h" #include <optional> namespace clang { namespace infer_alloc { -/// Infer the possible allocated type from an allocation call expression. -QualType inferPossibleType(const CallExpr *E, const ASTContext &Ctx, - const CastExpr *CastE); +/// Infer the possible allocated type from an allocation call expression, in +/// this order: a sizeof in a size argument, a placement new into the result +/// (\p PlacementNewType, if given, maps the call to the type constructed into +/// its result, see collectPlacementNewTypes()), and finally a cast of the +/// result (\p CastE is the cast the call result is immediately used in, if +/// any). +QualType inferPossibleType( + const CallExpr *E, const ASTContext &Ctx, const CastExpr *CastE, + llvm::function_ref<QualType(const CallExpr *)> PlacementNewType = nullptr); + +/// Maps the allocation calls in \p Body whose result is used as placement-new +/// storage to the constructed type (null if different types are constructed +/// into it, or if a pointer-free type may not cover the whole allocation), +/// e.g. `void *mem = alloc(n); new (mem) T();`. A local variable is only used +/// if it is initialized by the call and otherwise only read. +llvm::DenseMap<const CallExpr *, QualType> +collectPlacementNewTypes(const Stmt *Body, const ASTContext &Ctx); /// Get the information required for construction of an allocation token ID. std::optional<llvm::AllocTokenMetadata> diff --git a/clang/lib/AST/InferAlloc.cpp b/clang/lib/AST/InferAlloc.cpp index 6c99a81d739f1..ff00eae209de7 100644 --- a/clang/lib/AST/InferAlloc.cpp +++ b/clang/lib/AST/InferAlloc.cpp @@ -12,12 +12,16 @@ #include "clang/AST/InferAlloc.h" #include "clang/AST/ASTContext.h" +#include "clang/AST/Attr.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclCXX.h" +#include "clang/AST/DynamicRecursiveASTVisitor.h" #include "clang/AST/Expr.h" +#include "clang/AST/ExprCXX.h" #include "clang/AST/Type.h" #include "clang/Basic/IdentifierTable.h" #include "llvm/ADT/SmallPtrSet.h" +#include "llvm/ADT/SmallVector.h" using namespace clang; using namespace infer_alloc; @@ -167,11 +171,11 @@ static QualType inferPossibleTypeFromCastExpr(const CallExpr *CallE, return QualType(); } -QualType infer_alloc::inferPossibleType(const CallExpr *E, - const ASTContext &Ctx, - const CastExpr *CastE) { +QualType infer_alloc::inferPossibleType( + const CallExpr *E, const ASTContext &Ctx, const CastExpr *CastE, + llvm::function_ref<QualType(const CallExpr *)> PlacementNewType) { QualType AllocType; - // First check arguments. + // First check arguments: a sizeof states what the allocation was sized for. for (const Expr *Arg : E->arguments()) { AllocType = inferPossibleTypeFromArithSizeofExpr(Arg); if (AllocType.isNull()) @@ -179,12 +183,191 @@ QualType infer_alloc::inferPossibleType(const CallExpr *E, if (!AllocType.isNull()) break; } + // Then check for a placement new into the result, which names the object + // constructed there and is stronger evidence than a cast of the result. + if (AllocType.isNull() && PlacementNewType) + AllocType = PlacementNewType(E); // Then check later casts. if (AllocType.isNull()) AllocType = inferPossibleTypeFromCastExpr(E, CastE); return AllocType; } +/// Strips parentheses and non-static field accesses of a by-value object +/// (e.g. the pointer member of a size-returning allocation result) from an +/// lvalue, down to the expression naming the object. Indirect member accesses +/// (`->`) name other storage and stop the walk. +static const Expr *stripFields(const Expr *E) { + E = E->IgnoreParens(); + while (const auto *ME = dyn_cast<MemberExpr>(E)) { + if (ME->isArrow() || !isa<FieldDecl>(ME->getMemberDecl())) + break; + // The base of a member of a temporary is a MaterializeTemporaryExpr. + E = ME->getBase()->IgnoreParenImpCasts(); + } + return E; +} + +/// The size allocated by \p CE if it is a constant: the arguments named by +/// alloc_size, or the only argument. +static std::optional<uint64_t> getConstantAllocSize(const CallExpr *CE, + const ASTContext &Ctx) { + SmallVector<const Expr *, 2> Args; + const FunctionDecl *FD = CE->getDirectCallee(); + if (const auto *A = FD ? FD->getAttr<AllocSizeAttr>() : nullptr) { + Args.push_back(CE->getArg(A->getElemSizeParam().getASTIndex())); + if (A->getNumElemsParam().isValid()) + Args.push_back(CE->getArg(A->getNumElemsParam().getASTIndex())); + } else if (CE->getNumArgs() == 1) { + Args.push_back(CE->getArg(0)); + } + if (Args.empty()) + return std::nullopt; + uint64_t Size = 1; + for (const Expr *Arg : Args) { + Expr::EvalResult R; + if (Arg->isValueDependent() || !Arg->EvaluateAsInt(R, Ctx)) + return std::nullopt; + Size *= R.Val.getInt().getZExtValue(); + } + return Size; +} + +/// Whether \p T ends in a flexible array member, or an array treated as one +/// under -fstrict-flex-arrays, possibly in its last field or only base. +static bool endsInFlexibleArray(QualType T, const ASTContext &Ctx) { + const RecordDecl *RD = T->getAsRecordDecl(); + while (RD && RD->isCompleteDefinition() && !RD->isUnion()) { + const FieldDecl *Last = nullptr; + for (const FieldDecl *FD : RD->fields()) + Last = FD; + if (!Last) { + const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD); + if (!CXXRD || CXXRD->getNumBases() != 1) + return false; + RD = CXXRD->bases_begin()->getType()->getAsRecordDecl(); + continue; + } + if (Last->getType()->isArrayType()) + return Decl::isFlexibleArrayMemberLike( + Ctx, Last, Last->getType(), + Ctx.getLangOpts().getStrictFlexArraysLevel(), + /*IgnoreTemplateOrMacroSubstitution=*/true); + RD = Last->getType()->getAsRecordDecl(); + } + return false; +} + +/// Whether the object \p NE constructs into the storage allocated by \p CE +/// describes all of it. It may construct only a header, with other data +/// (possibly pointers) after it, e.g. `new (malloc(n + 8)) size_t(n)`. A +/// pointer-free type is used only for a constant allocation of its size, an +/// array new, or a type ending in a flexible array, whose elements are assumed +/// to fill the rest. +static bool coversAllocation(const CallExpr *CE, const CXXNewExpr *NE, + const ASTContext &Ctx) { + QualType T = NE->getAllocatedType(); + llvm::SmallPtrSet<const RecordDecl *, 4> VisitedRD; + bool IncompleteType = false; + if (NE->isArray() || typeContainsPointer(T, VisitedRD, IncompleteType) || + IncompleteType) + return true; + std::optional<uint64_t> Size = getConstantAllocSize(CE, Ctx); + if (Size && *Size == uint64_t(Ctx.getTypeSizeInChars(T).getQuantity())) + return true; + return endsInFlexibleArray(T, Ctx); +} + +namespace { +/// Implements collectPlacementNewTypes(). A variable qualifies if every +/// reference to it other than its initializer is an lvalue-to-rvalue read. +class PlacementNewCollector : public ConstDynamicRecursiveASTVisitor { +public: + explicit PlacementNewCollector(const ASTContext &Ctx) : Ctx(Ctx) {} + + // Resolved after the traversal: a use that is not a read may follow the + // placement new and still disqualify the variable. + llvm::DenseMap<const CallExpr *, QualType> finish() && { + for (const auto &[VD, NE] : Uses) + if (const CallExpr *CE = Defs.lookup(VD)) + record(CE, NE); + return std::move(CallTypes); + } + + bool VisitVarDecl(const VarDecl *VD) override { + const Expr *Init = VD->getInit(); + if (Init && VD->hasLocalStorage() && !isa<ParmVarDecl>(VD)) + if (const auto *CE = + dyn_cast<CallExpr>(Init->IgnoreImplicit()->IgnoreParenCasts())) + Defs.try_emplace(VD, CE); + return true; + } + + // A read of the variable or of one of its fields. Traversal is pre-order, + // so the conversion is seen before the DeclRefExpr below it. + bool VisitImplicitCastExpr(const ImplicitCastExpr *ICE) override { + if (ICE->getCastKind() == CK_LValueToRValue) + if (const auto *DRE = + dyn_cast<DeclRefExpr>(stripFields(ICE->getSubExpr()))) + Reads.insert(DRE); + return true; + } + + // Any other reference may modify the variable. + bool VisitDeclRefExpr(const DeclRefExpr *DRE) override { + if (!Reads.contains(DRE)) + if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) + Defs.erase(VD); + return true; + } + + bool VisitCXXNewExpr(const CXXNewExpr *NE) override { + // Only the reserved placement form is known to construct into its + // argument; dependent new-expressions have no operator new yet. + const FunctionDecl *OperatorNew = NE->getOperatorNew(); + if (NE->getNumPlacementArgs() != 1 || !OperatorNew || + !OperatorNew->isReservedGlobalPlacementOperator()) + return true; + const Expr *Source = + stripFields(NE->getPlacementArg(0)->IgnoreParenCasts()); + if (const auto *CE = dyn_cast<CallExpr>(Source)) + record(CE, NE); + else if (const auto *DRE = dyn_cast<DeclRefExpr>(Source)) + if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) + Uses.emplace_back(VD, NE); + return true; + } + +private: + void record(const CallExpr *CE, const CXXNewExpr *NE) { + QualType T = + coversAllocation(CE, NE, Ctx) ? NE->getAllocatedType() : QualType(); + auto [It, Inserted] = CallTypes.try_emplace(CE, T); + // Different types constructed into the same storage: ambiguous. + if (!Inserted && !It->second.isNull() && + (T.isNull() || It->second.getCanonicalType() != T.getCanonicalType())) + It->second = QualType(); + } + + const ASTContext &Ctx; + + llvm::DenseMap<const CallExpr *, QualType> CallTypes; + // Variable -> the allocation call initializing it; erased on any use that + // is not a read. + llvm::DenseMap<const VarDecl *, const CallExpr *> Defs; + llvm::SmallPtrSet<const DeclRefExpr *, 16> Reads; + llvm::SmallVector<std::pair<const VarDecl *, const CXXNewExpr *>> Uses; +}; +} // namespace + +llvm::DenseMap<const CallExpr *, QualType> +infer_alloc::collectPlacementNewTypes(const Stmt *Body, const ASTContext &Ctx) { + PlacementNewCollector Collector(Ctx); + if (Body) + Collector.TraverseStmt(Body); + return std::move(Collector).finish(); +} + std::optional<llvm::AllocTokenMetadata> infer_alloc::getAllocTokenMetadata(QualType T, const ASTContext &Ctx) { llvm::AllocTokenMetadata ATMD; diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp index bdcd9ee43ce1c..7b78abdb71c39 100644 --- a/clang/lib/CodeGen/CGBuiltin.cpp +++ b/clang/lib/CodeGen/CGBuiltin.cpp @@ -24,6 +24,7 @@ #include "ConstantEmitter.h" #include "PatternInit.h" #include "TargetInfo.h" +#include "clang/AST/InferAlloc.h" #include "clang/AST/OSLog.h" #include "clang/AST/StmtVisitor.h" #include "clang/Basic/DiagnosticFrontend.h" @@ -4892,7 +4893,10 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl GD, unsigned BuiltinID, } case Builtin::BI__builtin_infer_alloc_token: { - llvm::MDNode *MDN = buildAllocToken(E); + // The builtin has no enclosing allocation whose placement-new uses could + // be inspected, so only the call-based inference applies. + llvm::MDNode *MDN = buildAllocToken( + infer_alloc::inferPossibleType(E, getContext(), CurCast)); llvm::Value *MDV = MetadataAsValue::get(getLLVMContext(), MDN); llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::alloc_token_id, {IntPtrTy}); diff --git a/clang/lib/CodeGen/CGExpr.cpp b/clang/lib/CodeGen/CGExpr.cpp index ae4b40b32d05c..3cbff3223cf7f 100644 --- a/clang/lib/CodeGen/CGExpr.cpp +++ b/clang/lib/CodeGen/CGExpr.cpp @@ -1407,8 +1407,20 @@ void CodeGenFunction::EmitAllocToken(llvm::CallBase *CB, QualType AllocType) { } llvm::MDNode *CodeGenFunction::buildAllocToken(const CallExpr *E) { - return buildAllocToken( - infer_alloc::inferPossibleType(E, getContext(), CurCast)); + // C has no placement new, so there is nothing to collect. + if (!getLangOpts().CPlusPlus) + return buildAllocToken( + infer_alloc::inferPossibleType(E, getContext(), CurCast)); + // The placement news of the enclosing function body are collected once, on + // the first allocation call that is not already typed by a sizeof. + auto PlacementNewType = [this](const CallExpr *Call) -> QualType { + if (!AllocTokenPlacementTypes) + AllocTokenPlacementTypes = infer_alloc::collectPlacementNewTypes( + CurCodeDecl ? CurCodeDecl->getBody() : nullptr, getContext()); + return AllocTokenPlacementTypes->lookup(Call); + }; + return buildAllocToken(infer_alloc::inferPossibleType( + E, getContext(), CurCast, PlacementNewType)); } void CodeGenFunction::EmitAllocToken(llvm::CallBase *CB, const CallExpr *E) { diff --git a/clang/lib/CodeGen/CodeGenFunction.h b/clang/lib/CodeGen/CodeGenFunction.h index c46c33a19cce2..5cd26898890f8 100644 --- a/clang/lib/CodeGen/CodeGenFunction.h +++ b/clang/lib/CodeGen/CodeGenFunction.h @@ -375,6 +375,12 @@ class CodeGenFunction : public CodeGenTypeCache { /// expression. const CastExpr *CurCast = nullptr; + /// Allocation calls of the current function body whose result is used as + /// placement-new storage, mapped to the constructed type; collected lazily + /// for -fsanitize=alloc-token type inference. + std::optional<llvm::DenseMap<const CallExpr *, QualType>> + AllocTokenPlacementTypes; + /// Save Parameter Decl for coroutine. llvm::SmallVector<const ParmVarDecl *, 4> FnArgs; diff --git a/clang/test/CodeGenCXX/alloc-token.cpp b/clang/test/CodeGenCXX/alloc-token.cpp index 057ca668c9dd3..edffd6a6c4143 100644 --- a/clang/test/CodeGenCXX/alloc-token.cpp +++ b/clang/test/CodeGenCXX/alloc-token.cpp @@ -4,6 +4,7 @@ extern "C" { void *aligned_alloc(size_t alignment, size_t size) __attribute__((malloc)); void *malloc(size_t size) __attribute__((malloc)); +void free(void *); void *calloc(size_t num, size_t size) __attribute__((malloc)); void *realloc(void *ptr, size_t size) __attribute__((malloc)); void *reallocarray(void *ptr, size_t nmemb, size_t size) __attribute__((malloc)); @@ -150,6 +151,364 @@ TestClass *test_new_class_array() { return arr; } +struct PlacedNoPtr { + long len; + unsigned char tag; + char data[1]; +}; + +struct PlacedWithPtr { + void *next; + long len; +}; + +// Allocation calls whose result is only named by a later placement new. The +// inference order is sizeof, then placement new, then cast. + +// CHECK-LABEL: define dso_local noundef ptr @_Z25test_placement_new_directv( +// CHECK: call noalias ptr @malloc(i64 noundef 64){{.*}} !alloc_token [[META_PLACEDNOPTR:![0-9]+]] +PlacedNoPtr *test_placement_new_direct() { + return new (malloc(64)) PlacedNoPtr(); +} + +// CHECK-LABEL: define dso_local noundef ptr @_Z24test_placement_new_arrayv( +// CHECK: call noalias ptr @malloc(i64 noundef 640){{.*}} !alloc_token [[META_PLACEDNOPTR]] +PlacedNoPtr *test_placement_new_array() { + void *mem = malloc(640); + return new (mem) PlacedNoPtr[10]; +} + +// A sizeof in the size argument states what the allocation was sized for and +// takes precedence: the placement new may construct only a header, with the +// elements placed by pointer arithmetic. +// CHECK-LABEL: define dso_local noundef ptr @_Z34test_placement_new_sizeof_prevailsv( +// CHECK: call noalias ptr @malloc(i64 noundef 40){{.*}} !alloc_token [[META_PLACEDWITHPTR:![0-9]+]] +// CHECK: call noalias ptr @malloc(i64 noundef 64){{.*}} !alloc_token [[META_CHAR:![0-9]+]] +long *test_placement_new_sizeof_prevails() { + void *mem = malloc(2 * sizeof(PlacedWithPtr) + sizeof(long)); + long *count = new (mem) long(2); + // The same holds for a sizeof of a character type. + void *bytes = malloc(sizeof(char) * 64); + sink = new (bytes) PlacedWithPtr(); + return count; +} + +// A cast of the result is weaker evidence than the placement new, whether the +// cast is to a raw storage pointer (char *, void *) or to a base class. +struct DerivedWithPtr : PlacedNoPtr { + void *next; +}; +// CHECK-LABEL: define dso_local void @_Z28test_placement_new_over_castv( +// CHECK: call noalias ptr @malloc(i64 noundef 64){{.*}} !alloc_token [[META_PLACEDWITHPTR]] +// CHECK: call { ptr, i64 } @__size_returning_new(i64 noundef 64){{.*}} !alloc_token [[META_PLACEDWITHPTR]] +// CHECK: call noalias ptr @malloc(i64 noundef 32){{.*}} !alloc_token [[META_DERIVEDWITHPTR:![0-9]+]] +void test_placement_new_over_cast() { + char *p1 = static_cast<char *>(malloc(64)); + sink = new (p1) PlacedWithPtr(); + // The member access is an implicit lvalue-to-rvalue cast to void *. + sink = new (__size_returning_new(64).p) PlacedWithPtr(); + auto *base = static_cast<PlacedNoPtr *>(malloc(32)); + sink = new (base) DerivedWithPtr(); +} + +// Storage constructed into with different types: no type is inferred. +// CHECK-LABEL: define dso_local void @_Z28test_placement_new_ambiguousi( +// CHECK: call noalias ptr @malloc(i64 noundef 64) +// CHECK-NOT: !alloc_token +// CHECK: ret void +void test_placement_new_ambiguous(int which) { + void *mem = malloc(64); + if (which) + sink = new (mem) PlacedNoPtr(); + else + sink = new (mem) PlacedWithPtr(); +} + +// A user-provided placement operator new may use its argument as allocator +// state rather than as the storage, so the allocation feeding it stays untyped +// (the custom operator new call itself is typed). +struct Arena {}; +void *operator new(size_t, Arena *); +Ar... [truncated] `````````` </details> https://github.com/llvm/llvm-project/pull/244809 _______________________________________________ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
