Skip to content

Commit cf77e61

Browse files
committed
[BOLT] Introduce helpers to match MCInsts one at a time (NFC)
Introduce matchInst helper function to capture and/or match the operands of MCInst. Unlike the existing `MCPlusBuilder::MCInstMatcher` machinery, matchInst is intended for the use cases when precise control over the instruction order is required. For example, when validating PtrAuth hardening, all registers are usually considered unsafe after a function call, even though callee-saved registers should preserve their old values *under normal operation*.
1 parent 9745bc9 commit cf77e61

File tree

2 files changed

+162
-56
lines changed

2 files changed

+162
-56
lines changed

bolt/include/bolt/Core/MCInstUtils.h

Lines changed: 128 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -162,6 +162,134 @@ static inline raw_ostream &operator<<(raw_ostream &OS,
162162
return Ref.print(OS);
163163
}
164164

165+
/// Instruction-matching helpers operating on a single instruction at a time.
166+
///
167+
/// Unlike MCPlusBuilder::MCInstMatcher, this matchInst() function focuses on
168+
/// the cases where a precise control over the instruction order is important:
169+
///
170+
/// // Bring the short names into the local scope:
171+
/// using namespace MCInstMatcher;
172+
/// // Declare the registers to capture:
173+
/// Reg Xn, Xm;
174+
/// // Capture the 0th and 1st operands, match the 2nd operand against the
175+
/// // just captured Xm register, match the 3rd operand against literal 0:
176+
/// if (!matchInst(MaybeAdd, AArch64::ADDXrs, Xm, Xn, Xm, Imm(0))
177+
/// return AArch64::NoRegister;
178+
/// // Match the 0th operand against Xm:
179+
/// if (!matchInst(MaybeBr, AArch64::BR, Xm))
180+
/// return AArch64::NoRegister;
181+
/// // Return the matched register:
182+
/// return Xm.get();
183+
namespace MCInstMatcher {
184+
185+
// The base class to match an operand of type T.
186+
//
187+
// The subclasses of OpMatcher are intended to be allocated on the stack and
188+
// to only be used by passing them to matchInst() and by calling their get()
189+
// function, thus the peculiar `mutable` specifiers: to make the calling code
190+
// compact and readable, the templated matchInst() function has to accept both
191+
// long-lived Imm/Reg wrappers declared as local variables (intended to capture
192+
// the first operand's value and match the subsequent operands, whether inside
193+
// a single instruction or across multiple instructions), as well as temporary
194+
// wrappers around literal values to match, f.e. Imm(42) or Reg(AArch64::XZR).
195+
template <typename T> class OpMatcher {
196+
mutable std::optional<T> Value;
197+
mutable std::optional<T> SavedValue;
198+
199+
// Remember/restore the last Value - to be called by matchInst.
200+
void remember() const { SavedValue = Value; }
201+
void restore() const { Value = SavedValue; }
202+
203+
template <class... OpMatchers>
204+
friend bool matchInst(const MCInst &, unsigned, const OpMatchers &...);
205+
206+
protected:
207+
OpMatcher(std::optional<T> ValueToMatch) : Value(ValueToMatch) {}
208+
209+
bool matchValue(T OpValue) const {
210+
// Check that OpValue does not contradict the existing Value.
211+
bool MatchResult = !Value || *Value == OpValue;
212+
// If MatchResult is false, all matchers will be reset before returning from
213+
// matchInst, including this one, thus no need to assign conditionally.
214+
Value = OpValue;
215+
216+
return MatchResult;
217+
}
218+
219+
public:
220+
/// Returns the captured value.
221+
T get() const {
222+
assert(Value.has_value());
223+
return *Value;
224+
}
225+
};
226+
227+
class Reg : public OpMatcher<MCPhysReg> {
228+
bool matches(const MCOperand &Op) const {
229+
if (!Op.isReg())
230+
return false;
231+
232+
return matchValue(Op.getReg());
233+
}
234+
235+
template <class... OpMatchers>
236+
friend bool matchInst(const MCInst &, unsigned, const OpMatchers &...);
237+
238+
public:
239+
Reg(std::optional<MCPhysReg> RegToMatch = std::nullopt)
240+
: OpMatcher<MCPhysReg>(RegToMatch) {}
241+
};
242+
243+
class Imm : public OpMatcher<int64_t> {
244+
bool matches(const MCOperand &Op) const {
245+
if (!Op.isImm())
246+
return false;
247+
248+
return matchValue(Op.getImm());
249+
}
250+
251+
template <class... OpMatchers>
252+
friend bool matchInst(const MCInst &, unsigned, const OpMatchers &...);
253+
254+
public:
255+
Imm(std::optional<int64_t> ImmToMatch = std::nullopt)
256+
: OpMatcher<int64_t>(ImmToMatch) {}
257+
};
258+
259+
/// Tries to match Inst and updates Ops on success.
260+
///
261+
/// If Inst has the specified Opcode and its operand list prefix matches Ops,
262+
/// this function returns true and updates Ops, otherwise false is returned and
263+
/// values of Ops are kept as before matchInst was called.
264+
///
265+
/// Please note that while Ops are technically passed by a const reference to
266+
/// make invocations like `matchInst(MI, Opcode, Imm(42))` possible, all their
267+
/// fields are marked mutable.
268+
template <class... OpMatchers>
269+
bool matchInst(const MCInst &Inst, unsigned Opcode, const OpMatchers &...Ops) {
270+
if (Inst.getOpcode() != Opcode)
271+
return false;
272+
assert(sizeof...(Ops) <= Inst.getNumOperands() &&
273+
"Too many operands are matched for the Opcode");
274+
275+
// Ask each matcher to remember its current value in case of rollback.
276+
(Ops.remember(), ...);
277+
278+
// Check if all matchers match the corresponding operands.
279+
auto It = Inst.begin();
280+
auto AllMatched = (Ops.matches(*(It++)) && ... && true);
281+
282+
// If match failed, restore the original captured values.
283+
if (!AllMatched) {
284+
(Ops.restore(), ...);
285+
return false;
286+
}
287+
288+
return true;
289+
}
290+
291+
} // namespace MCInstMatcher
292+
165293
} // namespace bolt
166294
} // namespace llvm
167295

bolt/lib/Target/AArch64/AArch64MCPlusBuilder.cpp

Lines changed: 34 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
#include "Utils/AArch64BaseInfo.h"
2020
#include "bolt/Core/BinaryBasicBlock.h"
2121
#include "bolt/Core/BinaryFunction.h"
22+
#include "bolt/Core/MCInstUtils.h"
2223
#include "bolt/Core/MCPlusBuilder.h"
2324
#include "llvm/BinaryFormat/ELF.h"
2425
#include "llvm/MC/MCContext.h"
@@ -390,81 +391,58 @@ class AArch64MCPlusBuilder : public MCPlusBuilder {
390391

391392
// Iterate over the instructions of BB in reverse order, matching opcodes
392393
// and operands.
393-
MCPhysReg TestedReg = 0;
394-
MCPhysReg ScratchReg = 0;
394+
395395
auto It = BB.end();
396-
auto StepAndGetOpcode = [&It, &BB]() -> int {
397-
if (It == BB.begin())
398-
return -1;
399-
--It;
400-
return It->getOpcode();
396+
auto StepBack = [&]() {
397+
while (It != BB.begin()) {
398+
--It;
399+
if (!isCFI(*It))
400+
return true;
401+
}
402+
return false;
401403
};
402-
403-
switch (StepAndGetOpcode()) {
404-
default:
405-
// Not matched the branch instruction.
404+
// Step to the last non-CFI instruction.
405+
if (!StepBack())
406406
return std::nullopt;
407-
case AArch64::Bcc:
408-
// Bcc EQ, .Lon_success
409-
if (It->getOperand(0).getImm() != AArch64CC::EQ)
410-
return std::nullopt;
411-
// Not checking .Lon_success (see above).
412407

413-
// SUBSXrs XZR, TestedReg, ScratchReg, 0 (used by "CMP reg, reg" alias)
414-
if (StepAndGetOpcode() != AArch64::SUBSXrs ||
415-
It->getOperand(0).getReg() != AArch64::XZR ||
416-
It->getOperand(3).getImm() != 0)
408+
using namespace llvm::bolt::MCInstMatcher;
409+
Reg TestedReg;
410+
Reg ScratchReg;
411+
412+
if (matchInst(*It, AArch64::Bcc, Imm(AArch64CC::EQ) /*, .Lon_success*/)) {
413+
if (!StepBack() || !matchInst(*It, AArch64::SUBSXrs, Reg(AArch64::XZR),
414+
TestedReg, ScratchReg, Imm(0)))
417415
return std::nullopt;
418-
TestedReg = It->getOperand(1).getReg();
419-
ScratchReg = It->getOperand(2).getReg();
420416

421417
// Either XPAC(I|D) ScratchReg, ScratchReg
422418
// or XPACLRI
423-
switch (StepAndGetOpcode()) {
424-
default:
419+
if (!StepBack())
425420
return std::nullopt;
426-
case AArch64::XPACLRI:
421+
if (matchInst(*It, AArch64::XPACLRI)) {
427422
// No operands to check, but using XPACLRI forces TestedReg to be X30.
428-
if (TestedReg != AArch64::LR)
429-
return std::nullopt;
430-
break;
431-
case AArch64::XPACI:
432-
case AArch64::XPACD:
433-
if (It->getOperand(0).getReg() != ScratchReg ||
434-
It->getOperand(1).getReg() != ScratchReg)
423+
if (TestedReg.get() != AArch64::LR)
435424
return std::nullopt;
436-
break;
425+
} else if (!matchInst(*It, AArch64::XPACI, ScratchReg, ScratchReg) &&
426+
!matchInst(*It, AArch64::XPACD, ScratchReg, ScratchReg)) {
427+
return std::nullopt;
437428
}
438429

439-
// ORRXrs ScratchReg, XZR, TestedReg, 0 (used by "MOV reg, reg" alias)
440-
if (StepAndGetOpcode() != AArch64::ORRXrs)
430+
if (!StepBack() || !matchInst(*It, AArch64::ORRXrs, ScratchReg,
431+
Reg(AArch64::XZR), TestedReg, Imm(0)))
441432
return std::nullopt;
442-
if (It->getOperand(0).getReg() != ScratchReg ||
443-
It->getOperand(1).getReg() != AArch64::XZR ||
444-
It->getOperand(2).getReg() != TestedReg ||
445-
It->getOperand(3).getImm() != 0)
446-
return std::nullopt;
447-
448-
return std::make_pair(TestedReg, &*It);
449433

450-
case AArch64::TBZX:
451-
// TBZX ScratchReg, 62, .Lon_success
452-
ScratchReg = It->getOperand(0).getReg();
453-
if (It->getOperand(1).getImm() != 62)
454-
return std::nullopt;
455-
// Not checking .Lon_success (see above).
434+
return std::make_pair(TestedReg.get(), &*It);
435+
}
456436

457-
// EORXrs ScratchReg, TestedReg, TestedReg, 1
458-
if (StepAndGetOpcode() != AArch64::EORXrs)
459-
return std::nullopt;
460-
TestedReg = It->getOperand(1).getReg();
461-
if (It->getOperand(0).getReg() != ScratchReg ||
462-
It->getOperand(2).getReg() != TestedReg ||
463-
It->getOperand(3).getImm() != 1)
437+
if (matchInst(*It, AArch64::TBZX, ScratchReg, Imm(62) /*, .Lon_success*/)) {
438+
if (!StepBack() || !matchInst(*It, AArch64::EORXrs, Reg(ScratchReg),
439+
TestedReg, TestedReg, Imm(1)))
464440
return std::nullopt;
465441

466-
return std::make_pair(TestedReg, &*It);
442+
return std::make_pair(TestedReg.get(), &*It);
467443
}
444+
445+
return std::nullopt;
468446
}
469447

470448
std::optional<MCPhysReg> getAuthCheckedReg(const MCInst &Inst,

0 commit comments

Comments
 (0)