Skip to content

Commit 06250aa

Browse files
committed
implement wraps attribute
Signed-off-by: Justin Stitt <[email protected]>
1 parent d21e731 commit 06250aa

20 files changed

+375
-26
lines changed

clang/docs/ReleaseNotes.rst

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -230,6 +230,16 @@ Attribute Changes in Clang
230230
instantiation by accidentally allowing it in C++ in some circumstances.
231231
(#GH106864)
232232

233+
- Introduced ``__attribute((wraps))__`` which can be added to type or variable
234+
declarations. Using an attributed type or variable in an arithmetic
235+
expression will define the overflow behavior for that expression as having
236+
two's complement wrap-around. These expressions cannot trigger integer
237+
overflow warnings or sanitizer warnings. They also cannot be optimized away
238+
by some eager UB optimizations.
239+
240+
This attribute is only valid for C, as there are built-in language
241+
alternatives for other languages.
242+
233243
Improvements to Clang's diagnostics
234244
-----------------------------------
235245

clang/include/clang/AST/Expr.h

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

4098+
/// Does one of the subexpressions have the wraps attribute?
4099+
bool hasWrappingOperand(const ASTContext &Ctx) const;
4100+
40984101
protected:
40994102
BinaryOperator(const ASTContext &Ctx, Expr *lhs, Expr *rhs, Opcode opc,
41004103
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
@@ -4790,3 +4790,10 @@ def ClspvLibclcBuiltin: InheritableAttr {
47904790
let Documentation = [ClspvLibclcBuiltinDoc];
47914791
let SimpleHandler = 1;
47924792
}
4793+
4794+
def Wraps : DeclOrTypeAttr {
4795+
let Spellings = [Clang<"wraps">];
4796+
let Subjects = SubjectList<[Var, TypedefName, Field]>;
4797+
let Documentation = [WrapsDocs];
4798+
let LangOpts = [COnly];
4799+
}

clang/include/clang/Basic/AttrDocs.td

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8415,3 +8415,71 @@ of ``nonallocating`` by the compiler.
84158415
}];
84168416
}
84178417

8418+
def WrapsDocs : Documentation {
8419+
let Category = DocCatField;
8420+
let Content = [{
8421+
This attribute can be used with type or variable declarations to denote that
8422+
arithmetic containing these marked components have defined overflow behavior.
8423+
Specifically, the behavior is defined as being consistent with two's complement
8424+
wrap-around. For the purposes of sanitizers or warnings that concern themselves
8425+
with the definedness of integer arithmetic, they will cease to instrument or
8426+
warn about arithmetic that directly involves a "wrapping" component.
8427+
8428+
For example, ``-fsanitize=signed-integer-overflow`` or ``-Winteger-overflow``
8429+
will not warn about suspicious overflowing arithmetic -- assuming correct usage
8430+
of the wraps attribute.
8431+
8432+
This example shows some basic usage of ``__attribute__((wraps))`` on a type
8433+
definition when building with ``-fsanitize=signed-integer-overflow``
8434+
8435+
.. code-block:: c
8436+
8437+
typedef int __attribute__((wraps)) wrapping_int;
8438+
8439+
void foo() {
8440+
wrapping_int a = INT_MAX;
8441+
++a; // no sanitizer warning
8442+
}
8443+
8444+
int main() { foo(); }
8445+
8446+
In the following example, we use ``__attribute__((wraps))`` on a variable to
8447+
disable overflow instrumentation for arithmetic expressions it appears in. We
8448+
do so with a popular overflow-checking pattern which we might not want to trip
8449+
sanitizers (like ``-fsanitize=unsigned-integer-overflow``).
8450+
8451+
.. code-block:: c
8452+
8453+
void foo(int offset) {
8454+
unsigned int A __attribute__((wraps)) = UINT_MAX;
8455+
8456+
// check for overflow using a common pattern, however we may accidentally
8457+
// perform a real overflow thus triggering sanitizers to step in. Since "A"
8458+
// is "wrapping", we can avoid sanitizer warnings.
8459+
if (A + offset < A) {
8460+
// handle overflow manually
8461+
// ...
8462+
return;
8463+
}
8464+
8465+
// now, handle non-overflow case ...
8466+
}
8467+
8468+
The above example demonstrates some of the power and elegance this attribute
8469+
provides. We can use code patterns we are already familiar with (like ``if (x +
8470+
y < x)``) while gaining control over the overflow behavior on a case-by-case
8471+
basis.
8472+
8473+
When combined with ``-fwrapv``, this attribute can still be applied as normal
8474+
but has no function apart from annotating types and variables for readers. This
8475+
is because ``-fwrapv`` defines all arithmetic as being "wrapping", rendering
8476+
this attribute's efforts redundant.
8477+
8478+
When using this attribute without ``-fwrapv`` and without any sanitizers, it
8479+
still has an impact on the definedness of arithmetic expressions containing
8480+
wrapping components. Since the behavior of said expressions is now technically
8481+
defined, the compiler will forgo some eager optimizations that are used on
8482+
expressions containing UB.
8483+
}];
8484+
}
8485+

clang/include/clang/Basic/DiagnosticGroups.td

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1576,3 +1576,9 @@ def ExtractAPIMisuse : DiagGroup<"extractapi-misuse">;
15761576
// Warnings about using the non-standard extension having an explicit specialization
15771577
// with a storage class specifier.
15781578
def ExplicitSpecializationStorageClass : DiagGroup<"explicit-specialization-storage-class">;
1579+
1580+
// Warnings regarding the usage of __attribute__((wraps)) on non-integer types.
1581+
def UselessWrapsAttr : DiagGroup<"useless-wraps-attribute">;
1582+
1583+
// Warnings about the wraps attribute getting implicitly discarded
1584+
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
@@ -2237,6 +2237,11 @@ bool BinaryOperator::isNullPointerArithmeticExtension(ASTContext &Ctx,
22372237
return true;
22382238
}
22392239

2240+
bool BinaryOperator::hasWrappingOperand(const ASTContext &Ctx) const {
2241+
return getLHS()->getType().hasWrapsAttr() ||
2242+
getRHS()->getType().hasWrapsAttr();
2243+
}
2244+
22402245
SourceLocExpr::SourceLocExpr(const ASTContext &Ctx, SourceLocIdentKind Kind,
22412246
QualType ResultTy, SourceLocation BLoc,
22422247
SourceLocation RParenLoc,
@@ -4844,6 +4849,8 @@ BinaryOperator::BinaryOperator(const ASTContext &Ctx, Expr *lhs, Expr *rhs,
48444849
if (hasStoredFPFeatures())
48454850
setStoredFPFeatures(FPFeatures);
48464851
setDependence(computeDependence(this));
4852+
if (hasWrappingOperand(Ctx))
4853+
setType(Ctx.getAttributedType(attr::Wraps, getType(), getType()));
48474854
}
48484855

48494856
BinaryOperator::BinaryOperator(const ASTContext &Ctx, Expr *lhs, Expr *rhs,
@@ -4862,6 +4869,8 @@ BinaryOperator::BinaryOperator(const ASTContext &Ctx, Expr *lhs, Expr *rhs,
48624869
if (hasStoredFPFeatures())
48634870
setStoredFPFeatures(FPFeatures);
48644871
setDependence(computeDependence(this));
4872+
if (hasWrappingOperand(Ctx))
4873+
setType(Ctx.getAttributedType(attr::Wraps, getType(), getType()));
48654874
}
48664875

48674876
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
@@ -2805,7 +2805,7 @@ static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
28052805
APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
28062806
Result = Value.trunc(LHS.getBitWidth());
28072807
if (Result.extend(BitWidth) != Value) {
2808-
if (Info.checkingForUndefinedBehavior())
2808+
if (Info.checkingForUndefinedBehavior() && !E->getType().hasWrapsAttr())
28092809
Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
28102810
diag::warn_integer_constant_overflow)
28112811
<< toString(Result, 10, Result.isSigned(), /*formatAsCLiteral=*/false,
@@ -14391,7 +14391,7 @@ bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
1439114391
if (!Result.isInt()) return Error(E);
1439214392
const APSInt &Value = Result.getInt();
1439314393
if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow()) {
14394-
if (Info.checkingForUndefinedBehavior())
14394+
if (Info.checkingForUndefinedBehavior() && !E->getType().hasWrapsAttr())
1439514395
Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
1439614396
diag::warn_integer_constant_overflow)
1439714397
<< 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)