Skip to content

Commit dee25a8

Browse files
authored
[TableGen] Validate the shift amount for !srl, !shl, and !sra operators. (#132492)
The C operator has undefined behavior for out of bounds shifts so we should check this.
1 parent d6fae7f commit dee25a8

File tree

2 files changed

+36
-3
lines changed

2 files changed

+36
-3
lines changed

llvm/lib/TableGen/Record.cpp

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1564,9 +1564,24 @@ const Init *BinOpInit::Fold(const Record *CurRec) const {
15641564
case AND: Result = LHSv & RHSv; break;
15651565
case OR: Result = LHSv | RHSv; break;
15661566
case XOR: Result = LHSv ^ RHSv; break;
1567-
case SHL: Result = (uint64_t)LHSv << (uint64_t)RHSv; break;
1568-
case SRA: Result = LHSv >> RHSv; break;
1569-
case SRL: Result = (uint64_t)LHSv >> (uint64_t)RHSv; break;
1567+
case SHL:
1568+
if (RHSv < 0 || RHSv >= 64)
1569+
PrintFatalError(CurRec->getLoc(),
1570+
"Illegal operation: out of bounds shift");
1571+
Result = (uint64_t)LHSv << (uint64_t)RHSv;
1572+
break;
1573+
case SRA:
1574+
if (RHSv < 0 || RHSv >= 64)
1575+
PrintFatalError(CurRec->getLoc(),
1576+
"Illegal operation: out of bounds shift");
1577+
Result = LHSv >> (uint64_t)RHSv;
1578+
break;
1579+
case SRL:
1580+
if (RHSv < 0 || RHSv >= 64)
1581+
PrintFatalError(CurRec->getLoc(),
1582+
"Illegal operation: out of bounds shift");
1583+
Result = (uint64_t)LHSv >> (uint64_t)RHSv;
1584+
break;
15701585
}
15711586
return IntInit::get(getRecordKeeper(), Result);
15721587
}

llvm/test/TableGen/math.td

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,9 @@
33
// RUN: not llvm-tblgen -DERROR2 %s 2>&1 | FileCheck --check-prefix=ERROR2 %s
44
// RUN: not llvm-tblgen -DERROR3 %s 2>&1 | FileCheck --check-prefix=ERROR3 %s
55
// RUN: not llvm-tblgen -DERROR4 %s 2>&1 | FileCheck --check-prefix=ERROR4 %s
6+
// RUN: not llvm-tblgen -DERROR5 %s 2>&1 | FileCheck --check-prefix=ERROR5 %s
7+
// RUN: not llvm-tblgen -DERROR6 %s 2>&1 | FileCheck --check-prefix=ERROR6 %s
8+
// RUN: not llvm-tblgen -DERROR7 %s 2>&1 | FileCheck --check-prefix=ERROR7 %s
69
// XFAIL: vg_leak
710

811
// CHECK: def shifts
@@ -143,3 +146,18 @@ def v954 : Int<!logtwo(-1)>;
143146
// CHECK: def vneg
144147
// CHECK: Value = -2
145148
def vneg : Int<!sub(v925.Value, 927)>;
149+
150+
#ifdef ERROR5
151+
// ERROR5: error: Illegal operation: out of bounds shift
152+
def vshl_neg : Int<!shl(1, -1)>;
153+
#endif
154+
155+
#ifdef ERROR6
156+
// ERROR6: error: Illegal operation: out of bounds shift
157+
def vsra_large : Int<!sra(1, 64)>;
158+
#endif
159+
160+
#ifdef ERROR7
161+
// ERROR7: error: Illegal operation: out of bounds shift
162+
def vsrl_large : Int<!srl(1, 100)>;
163+
#endif

0 commit comments

Comments
 (0)