Skip to content

Commit 6fb8f68

Browse files
committed
implement wraps attribute
Signed-off-by: Justin Stitt <[email protected]>
1 parent 8814b6d commit 6fb8f68

20 files changed

+376
-26
lines changed

clang/docs/ReleaseNotes.rst

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -249,6 +249,16 @@ Attribute Changes in Clang
249249
- Introduced a new attribute ``[[clang::coro_await_elidable]]`` on coroutine return types
250250
to express elideability at call sites where the coroutine is co_awaited as a prvalue.
251251

252+
- Introduced ``__attribute((wraps))__`` which can be added to type or variable
253+
declarations. Using an attributed type or variable in an arithmetic
254+
expression will define the overflow behavior for that expression as having
255+
two's complement wrap-around. These expressions cannot trigger integer
256+
overflow warnings or sanitizer warnings. They also cannot be optimized away
257+
by some eager UB optimizations.
258+
259+
This attribute is only valid for C, as there are built-in language
260+
alternatives for other languages.
261+
252262
Improvements to Clang's diagnostics
253263
-----------------------------------
254264

clang/include/clang/AST/Expr.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4098,6 +4098,9 @@ class BinaryOperator : public Expr {
40984098
return getFPFeaturesInEffect(LO).getAllowFEnvAccess();
40994099
}
41004100

4101+
/// Does one of the subexpressions have the wraps attribute?
4102+
bool hasWrappingOperand(const ASTContext &Ctx) const;
4103+
41014104
protected:
41024105
BinaryOperator(const ASTContext &Ctx, Expr *lhs, Expr *rhs, Opcode opc,
41034106
QualType ResTy, ExprValueKind VK, ExprObjectKind OK,

clang/include/clang/AST/Type.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1454,6 +1454,8 @@ class QualType {
14541454
return getQualifiers().hasStrongOrWeakObjCLifetime();
14551455
}
14561456

1457+
bool hasWrapsAttr() const;
1458+
14571459
// true when Type is objc's weak and weak is enabled but ARC isn't.
14581460
bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const;
14591461

clang/include/clang/Basic/Attr.td

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4796,3 +4796,10 @@ def ClspvLibclcBuiltin: InheritableAttr {
47964796
let Documentation = [ClspvLibclcBuiltinDoc];
47974797
let SimpleHandler = 1;
47984798
}
4799+
4800+
def Wraps : DeclOrTypeAttr {
4801+
let Spellings = [Clang<"wraps">];
4802+
let Subjects = SubjectList<[Var, TypedefName, Field]>;
4803+
let Documentation = [WrapsDocs];
4804+
let LangOpts = [COnly];
4805+
}

clang/include/clang/Basic/AttrDocs.td

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8446,3 +8446,72 @@ Declares that a function potentially allocates heap memory, and prevents any pot
84468446
of ``nonallocating`` by the compiler.
84478447
}];
84488448
}
8449+
8450+
def WrapsDocs : Documentation {
8451+
let Category = DocCatField;
8452+
let Content = [{
8453+
This attribute can be used with type or variable declarations to denote that
8454+
arithmetic containing these marked components have defined overflow behavior.
8455+
Specifically, the behavior is defined as being consistent with two's complement
8456+
wrap-around. For the purposes of sanitizers or warnings that concern themselves
8457+
with the definedness of integer arithmetic, they will cease to instrument or
8458+
warn about arithmetic that directly involves a "wrapping" component.
8459+
8460+
For example, ``-fsanitize=signed-integer-overflow`` or ``-Winteger-overflow``
8461+
will not warn about suspicious overflowing arithmetic -- assuming correct usage
8462+
of the wraps attribute.
8463+
8464+
This example shows some basic usage of ``__attribute__((wraps))`` on a type
8465+
definition when building with ``-fsanitize=signed-integer-overflow``
8466+
8467+
.. code-block:: c
8468+
8469+
typedef int __attribute__((wraps)) wrapping_int;
8470+
8471+
void foo() {
8472+
wrapping_int a = INT_MAX;
8473+
++a; // no sanitizer warning
8474+
}
8475+
8476+
int main() { foo(); }
8477+
8478+
In the following example, we use ``__attribute__((wraps))`` on a variable to
8479+
disable overflow instrumentation for arithmetic expressions it appears in. We
8480+
do so with a popular overflow-checking pattern which we might not want to trip
8481+
sanitizers (like ``-fsanitize=unsigned-integer-overflow``).
8482+
8483+
.. code-block:: c
8484+
8485+
void foo(int offset) {
8486+
unsigned int A __attribute__((wraps)) = UINT_MAX;
8487+
8488+
// check for overflow using a common pattern, however we may accidentally
8489+
// perform a real overflow thus triggering sanitizers to step in. Since "A"
8490+
// is "wrapping", we can avoid sanitizer warnings.
8491+
if (A + offset < A) {
8492+
// handle overflow manually
8493+
// ...
8494+
return;
8495+
}
8496+
8497+
// now, handle non-overflow case ...
8498+
}
8499+
8500+
The above example demonstrates some of the power and elegance this attribute
8501+
provides. We can use code patterns we are already familiar with (like ``if (x +
8502+
y < x)``) while gaining control over the overflow behavior on a case-by-case
8503+
basis.
8504+
8505+
When combined with ``-fwrapv``, this attribute can still be applied as normal
8506+
but has no function apart from annotating types and variables for readers. This
8507+
is because ``-fwrapv`` defines all arithmetic as being "wrapping", rendering
8508+
this attribute's efforts redundant.
8509+
8510+
When using this attribute without ``-fwrapv`` and without any sanitizers, it
8511+
still has an impact on the definedness of arithmetic expressions containing
8512+
wrapping components. Since the behavior of said expressions is now technically
8513+
defined, the compiler will forgo some eager optimizations that are used on
8514+
expressions containing UB.
8515+
}];
8516+
}
8517+

clang/include/clang/Basic/DiagnosticGroups.td

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1577,3 +1577,9 @@ def ExtractAPIMisuse : DiagGroup<"extractapi-misuse">;
15771577
// Warnings about using the non-standard extension having an explicit specialization
15781578
// with a storage class specifier.
15791579
def ExplicitSpecializationStorageClass : DiagGroup<"explicit-specialization-storage-class">;
1580+
1581+
// Warnings regarding the usage of __attribute__((wraps)) on non-integer types.
1582+
def UselessWrapsAttr : DiagGroup<"useless-wraps-attribute">;
1583+
1584+
// Warnings about the wraps attribute getting implicitly discarded
1585+
def ImpDiscardedWrapsAttr : DiagGroup<"implicitly-discarded-wraps-attribute">;

clang/include/clang/Basic/DiagnosticSemaKinds.td

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6633,6 +6633,13 @@ def warn_counted_by_attr_elt_type_unknown_size :
66336633
Warning<err_counted_by_attr_pointee_unknown_size.Summary>,
66346634
InGroup<BoundsSafetyCountedByEltTyUnknownSize>;
66356635

6636+
def warn_wraps_attr_var_decl_type_not_integer : Warning<
6637+
"using attribute 'wraps' with non-integer type '%0' has no function">,
6638+
InGroup<UselessWrapsAttr>;
6639+
def warn_wraps_attr_maybe_lost : Warning<
6640+
"'wraps' attribute may be implicitly discarded when converted to %0">,
6641+
InGroup<ImpDiscardedWrapsAttr>;
6642+
66366643
let CategoryName = "ARC Semantic Issue" in {
66376644

66386645
// ARC-mode diagnostics.

clang/lib/AST/Expr.cpp

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2240,6 +2240,11 @@ bool BinaryOperator::isNullPointerArithmeticExtension(ASTContext &Ctx,
22402240
return true;
22412241
}
22422242

2243+
bool BinaryOperator::hasWrappingOperand(const ASTContext &Ctx) const {
2244+
return getLHS()->getType().hasWrapsAttr() ||
2245+
getRHS()->getType().hasWrapsAttr();
2246+
}
2247+
22432248
SourceLocExpr::SourceLocExpr(const ASTContext &Ctx, SourceLocIdentKind Kind,
22442249
QualType ResultTy, SourceLocation BLoc,
22452250
SourceLocation RParenLoc,
@@ -4856,6 +4861,8 @@ BinaryOperator::BinaryOperator(const ASTContext &Ctx, Expr *lhs, Expr *rhs,
48564861
if (hasStoredFPFeatures())
48574862
setStoredFPFeatures(FPFeatures);
48584863
setDependence(computeDependence(this));
4864+
if (hasWrappingOperand(Ctx))
4865+
setType(Ctx.getAttributedType(attr::Wraps, getType(), getType()));
48594866
}
48604867

48614868
BinaryOperator::BinaryOperator(const ASTContext &Ctx, Expr *lhs, Expr *rhs,
@@ -4874,6 +4881,8 @@ BinaryOperator::BinaryOperator(const ASTContext &Ctx, Expr *lhs, Expr *rhs,
48744881
if (hasStoredFPFeatures())
48754882
setStoredFPFeatures(FPFeatures);
48764883
setDependence(computeDependence(this));
4884+
if (hasWrappingOperand(Ctx))
4885+
setType(Ctx.getAttributedType(attr::Wraps, getType(), getType()));
48774886
}
48784887

48794888
BinaryOperator *BinaryOperator::CreateEmpty(const ASTContext &C,

clang/lib/AST/ExprConstant.cpp

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2809,7 +2809,7 @@ static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
28092809
APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
28102810
Result = Value.trunc(LHS.getBitWidth());
28112811
if (Result.extend(BitWidth) != Value) {
2812-
if (Info.checkingForUndefinedBehavior())
2812+
if (Info.checkingForUndefinedBehavior() && !E->getType().hasWrapsAttr())
28132813
Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
28142814
diag::warn_integer_constant_overflow)
28152815
<< toString(Result, 10, Result.isSigned(), /*formatAsCLiteral=*/false,
@@ -14412,7 +14412,7 @@ bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
1441214412
if (!Result.isInt()) return Error(E);
1441314413
const APSInt &Value = Result.getInt();
1441414414
if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow()) {
14415-
if (Info.checkingForUndefinedBehavior())
14415+
if (Info.checkingForUndefinedBehavior() && !E->getType().hasWrapsAttr())
1441614416
Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
1441714417
diag::warn_integer_constant_overflow)
1441814418
<< toString(Value, 10, Value.isSigned(), /*formatAsCLiteral=*/false,

clang/lib/AST/Type.cpp

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2850,6 +2850,10 @@ bool QualType::isWebAssemblyFuncrefType() const {
28502850
getAddressSpace() == LangAS::wasm_funcref;
28512851
}
28522852

2853+
bool QualType::hasWrapsAttr() const {
2854+
return !isNull() && getTypePtr()->hasAttr(attr::Wraps);
2855+
}
2856+
28532857
QualType::PrimitiveDefaultInitializeKind
28542858
QualType::isNonTrivialToPrimitiveDefaultInitialize() const {
28552859
if (const auto *RT =

0 commit comments

Comments
 (0)