LLVM 24.0.0git
AArch64MCLFIRewriter.cpp
Go to the documentation of this file.
1//===- AArch64MCLFIRewriter.cpp ---------------------------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the AArch64MCLFIRewriter class, the AArch64 specific
10// subclass of MCLFIRewriter.
11//
12//===----------------------------------------------------------------------===//
13
18
19#include "llvm/ADT/Twine.h"
20#include "llvm/MC/MCContext.h"
21#include "llvm/MC/MCInst.h"
23#include "llvm/MC/MCInstrDesc.h"
24#include "llvm/MC/MCInstrInfo.h"
25#include "llvm/MC/MCStreamer.h"
27#include "llvm/MC/MCSymbol.h"
28
29using namespace llvm;
30
31namespace llvm::AArch64 {
39 unsigned Inst;
40 bool IsPre;
42 unsigned BaseInst;
43};
45 unsigned Inst;
47 unsigned BaseInst;
48};
57
58// LFI addressing-mode codes (must match AArch64LFI.td's LFI_AM_* defs).
66
67#define GET_LFIVariantTable_DECL
68#define GET_PairVariantTable_DECL
69#define GET_SIMDPostTable_DECL
70#define GET_MemInfoTable_DECL
71#define GET_LFIVariantTable_IMPL
72#define GET_PairVariantTable_IMPL
73#define GET_SIMDPostTable_IMPL
74#define GET_MemInfoTable_IMPL
75// The LFI tables defined in AArch64LFI.td are emitted into this file alongside
76// the system operand tables (single -gen-searchable-tables output).
77#include "AArch64GenSystemOperands.inc"
78} // namespace llvm::AArch64
79
80// LFI reserved registers.
81static constexpr MCRegister LFIBaseReg = AArch64::X27;
82static constexpr MCRegister LFIAddrReg = AArch64::X28;
83static constexpr MCRegister LFIScratchReg = AArch64::X26;
84static constexpr MCRegister LFICtxReg = AArch64::X25;
85
86// Offset into the context register block (pointed to by LFICtxReg) where the
87// thread pointer is stored. This is a scaled offset (multiplied by 8 for
88// 64-bit loads), so a value of 2 means an actual byte offset of 16.
89static constexpr unsigned LFITPOffset = 2;
90
91// Byte offset from the context register where the syscall handler address is
92// stored.
93static constexpr int LFISyscallOffset = -8;
94
96 std::unique_ptr<MCRegisterInfo> &&RI,
97 std::unique_ptr<MCInstrInfo> &&II)
98 : MCLFIRewriter(Ctx, std::move(RI), std::move(II)),
99 CLOpts(AArch64_MC::getCLOpts(Ctx.getTargetOptions())) {}
100
101static bool isSyscall(const MCInst &Inst) {
102 return Inst.getOpcode() == AArch64::SVC;
103}
104
105static bool isPrivilegedTP(int64_t Reg) {
106 return Reg == AArch64SysReg::TPIDR_EL1 || Reg == AArch64SysReg::TPIDR_EL2 ||
107 Reg == AArch64SysReg::TPIDR_EL3;
108}
109
110static bool isTPRead(const MCInst &Inst) {
111 return Inst.getOpcode() == AArch64::MRS &&
112 Inst.getOperand(1).getImm() == AArch64SysReg::TPIDR_EL0;
113}
114
115static bool isTPWrite(const MCInst &Inst) {
116 return Inst.getOpcode() == AArch64::MSR &&
117 Inst.getOperand(0).getImm() == AArch64SysReg::TPIDR_EL0;
118}
119
120static bool isPrivilegedTPAccess(const MCInst &Inst) {
121 if (Inst.getOpcode() == AArch64::MRS)
122 return isPrivilegedTP(Inst.getOperand(1).getImm());
123 if (Inst.getOpcode() == AArch64::MSR)
124 return isPrivilegedTP(Inst.getOperand(0).getImm());
125 return false;
126}
127
128// Classification functions are limited to Armv8.1-A. Instructions outside of
129// this subset are not guaranteed to be rewritten and as a result may fail LFI
130// verification after compilation.
131
132// Instructions that have mayLoad/mayStore set in TableGen but don't actually
133// perform memory accesses.
134static bool isFakeMemAccess(const MCInst &Inst) {
135 switch (Inst.getOpcode()) {
136 case AArch64::CLREX:
137 case AArch64::DMB:
138 case AArch64::DSB:
139 case AArch64::ISB:
140 case AArch64::HINT:
141 // The range of sub-architectures supported by LFI do not include any load
142 // or store instructions in the HINT space.
143 return true;
144 default:
145 return false;
146 }
147}
148
149static bool mayPrefetch(const MCInst &Inst) {
150 switch (Inst.getOpcode()) {
151 case AArch64::PRFMl:
152 case AArch64::PRFMroW:
153 case AArch64::PRFMroX:
154 case AArch64::PRFMui:
155 case AArch64::PRFUMi:
156 return true;
157 default:
158 return false;
159 }
160}
161
162static bool isAuthenticatedBranch(unsigned Opcode) {
163 switch (Opcode) {
164 case AArch64::BRAA:
165 case AArch64::BRAAZ:
166 case AArch64::BRAB:
167 case AArch64::BRABZ:
168 return true;
169 default:
170 return false;
171 }
172}
173
174static bool isAuthenticatedCall(unsigned Opcode) {
175 switch (Opcode) {
176 case AArch64::BLRAA:
177 case AArch64::BLRAAZ:
178 case AArch64::BLRAB:
179 case AArch64::BLRABZ:
180 return true;
181 default:
182 return false;
183 }
184}
185
186static bool isAuthenticatedReturn(unsigned Opcode) {
187 return Opcode == AArch64::RETAA || Opcode == AArch64::RETAB;
188}
189
190static bool isExceptionReturn(unsigned Opcode) {
191 return Opcode == AArch64::ERET || Opcode == AArch64::ERETAA ||
192 Opcode == AArch64::ERETAB;
193}
194
195static bool pacWritesLR(const MCInst &Inst) {
196 switch (Inst.getOpcode()) {
197 case AArch64::AUTIASP:
198 case AArch64::AUTIBSP:
199 case AArch64::AUTIAZ:
200 case AArch64::AUTIBZ:
201 case AArch64::XPACLRI:
202 return true;
203 default:
204 return false;
205 }
206}
207
208static bool isBTIC(const MCInst &Inst) {
209 return Inst.getOpcode() == AArch64::HINT &&
210 Inst.getOperand(0).getImm() ==
211 getBTIHintNum(/*CallTarget=*/true, /*JumpTarget=*/false);
212}
213
214// User-mode DC/IC instructions that take a virtual address operand. Encoded as
215// SYSxt with op1=3, Cn=7, op2=1 where the Cm field selects the operation.
216static bool isVASysOp(const MCInst &Inst) {
217 if (Inst.getOpcode() != AArch64::SYSxt)
218 return false;
219 if (Inst.getOperand(0).getImm() != 3 || Inst.getOperand(1).getImm() != 7 ||
220 Inst.getOperand(3).getImm() != 1)
221 return false;
222 switch (Inst.getOperand(2).getImm()) {
223 case 4: // DC ZVA
224 case 5: // IC IVAU
225 case 10: // DC CVAC
226 case 11: // DC CVAU
227 case 12: // DC CVAP
228 case 13: // DC CVADP
229 case 14: // DC CIVAC
230 return true;
231 default:
232 return false;
233 }
234}
235
236static MCInst replaceRegAt(const MCInst &Inst, unsigned Idx,
237 MCRegister NewReg) {
238 MCInst New = Inst;
239 assert(New.getOperand(Idx).isReg());
240 New.getOperand(Idx).setReg(NewReg);
241 return New;
242}
243
244// AArch64 load/store opcode suffixes used throughout this file:
245// Ui: Unsigned immediate offset, scaled by access size: [Xn, #imm].
246// RoW: Register offset with 32-bit W register: [Xn, Wm, uxtw #shift].
247// RoX: Register offset with 64-bit X register: [Xn, Xm, lsl #shift].
248
249// Scalar load/store variant lookup. If Op is a scalar mem instruction with
250// addressing mode ExpectedMode, returns the RoW variant of the same family.
251// Returns INSTRUCTION_LIST_END otherwise.
252static unsigned convertVariantToRoW(unsigned Op, unsigned ExpectedMode) {
253 const AArch64::LFIVariantEntry *E = AArch64::lookupLFIVariantByOpcode(Op);
254 if (!E || E->AddrMode != ExpectedMode)
255 return AArch64::INSTRUCTION_LIST_END;
256 return E->RoWInst;
257}
258
259static unsigned convertRoXToRoW(unsigned Op, unsigned &Shift) {
260 Shift = 0;
261 const AArch64::LFIVariantEntry *E = AArch64::lookupLFIVariantByOpcode(Op);
262 if (!E || E->AddrMode != AArch64::LFI_AM_RoX)
263 return AArch64::INSTRUCTION_LIST_END;
264 Shift = E->Log2Size;
265 return E->RoWInst;
266}
267
268static bool getRoWShift(unsigned Op, unsigned &Shift) {
269 Shift = 0;
270 const AArch64::LFIVariantEntry *E = AArch64::lookupLFIVariantByOpcode(Op);
271 if (!E || E->AddrMode != AArch64::LFI_AM_RoW)
272 return false;
273 Shift = E->Log2Size;
274 return true;
275}
276
277// Pre/post-index conversion to base form. Both LDP/STP pair pre/post forms and
278// SIMD post-index forms come from generated lookup tables. The pair table sets
279// IsPre to distinguish pre-index from post-index. The SIMD table is
280// post-index-only so IsNoOffset is set to indicate the demoted base form takes
281// no immediate offset.
282static unsigned convertPrePostToBase(unsigned Op, bool &IsPre,
283 bool &IsNoOffset) {
284 IsPre = false;
285 IsNoOffset = false;
286 if (const auto *E = AArch64::lookupPairVariantByOpcode(Op)) {
287 IsPre = E->IsPre;
288 return E->BaseInst;
289 }
290 if (const auto *E = AArch64::lookupSIMDPostByOpcode(Op)) {
291 IsNoOffset = true;
292 return E->BaseInst;
293 }
294 return AArch64::INSTRUCTION_LIST_END;
295}
296
297bool AArch64MCLFIRewriter::mayModifySP(const MCInst &Inst) const {
298 return mayModifyRegister(Inst, AArch64::SP);
299}
300
301MCRegister AArch64MCLFIRewriter::mayModifyReserved(const MCInst &Inst) const {
302 for (MCRegister Reg : {LFIAddrReg, LFIBaseReg, LFICtxReg}) {
303 if (mayModifyRegister(Inst, Reg))
304 return Reg;
305 }
306 return {};
307}
308
310 if (Guard)
311 return;
312
313 // Flush a deferred LR guard before the label, since the label is a potential
314 // branch target and code reached through it may use LR for control flow.
315 if (DeferredLRGuard && LastSTI && !Symbol->isTemporary()) {
316 emitAddMask(AArch64::LR, AArch64::LR, Out, *LastSTI);
317 DeferredLRGuard = false;
318 }
319
320 // Invalidate guard state since the label is a potential branch target.
321 ActiveGuardReg = std::nullopt;
322}
323
325 // Flush a deferred LR guard at the end of the stream.
326 if (DeferredLRGuard && LastSTI) {
327 emitAddMask(AArch64::LR, AArch64::LR, Out, *LastSTI);
328 DeferredLRGuard = false;
329 }
330}
331
332void AArch64MCLFIRewriter::emitInst(const MCInst &Inst, MCStreamer &Out,
333 const MCSubtargetInfo &STI) {
334 // Invalidate the active guard if this instruction modifies the guarded
335 // register, modifies x28 itself, or may affect control flow.
336 if (ActiveGuardReg) {
337 const MCInstrDesc &Desc = InstInfo->get(Inst.getOpcode());
338 if (Desc.mayAffectControlFlow(Inst, *RegInfo) ||
339 mayModifyRegister(Inst, *ActiveGuardReg) ||
340 mayModifyRegister(Inst, getWRegFromXReg(*ActiveGuardReg)) ||
342 ActiveGuardReg = std::nullopt;
343 }
344
345 Out.emitInstruction(Inst, STI);
346}
347
348void AArch64MCLFIRewriter::emitAddMask(MCRegister Dest, MCRegister Src,
349 MCStreamer &Out,
350 const MCSubtargetInfo &STI) {
351 // If x28 already holds the guarded value of Src, this guard is redundant and
352 // can be skipped.
353 if (CLOpts.lfi_guard_elim && Dest == LFIAddrReg && ActiveGuardReg == Src)
354 return;
355
356 // add Dest, LFIBaseReg, W(Src), uxtw
357 emitInst(MCInstBuilder(AArch64::ADDXrx)
358 .addReg(Dest)
359 .addReg(LFIBaseReg)
360 .addReg(getWRegFromXReg(Src))
362 Out, STI);
363
364 // Record Src as the new active guard.
365 if (Dest == LFIAddrReg)
366 ActiveGuardReg = Src;
367}
368
369void AArch64MCLFIRewriter::emitBranch(unsigned Opcode, MCRegister Target,
370 MCStreamer &Out,
371 const MCSubtargetInfo &STI) {
372 emitInst(MCInstBuilder(Opcode).addReg(Target), Out, STI);
373}
374
375void AArch64MCLFIRewriter::emitPendingTLSDescCall(MCStreamer &Out,
376 const MCSubtargetInfo &STI) {
377 if (!PendingTLSDescCall)
378 return;
379 const MCExpr *Expr = PendingTLSDescCall;
380 PendingTLSDescCall = nullptr;
381 emitInst(MCInstBuilder(AArch64::TLSDESCCALL).addExpr(Expr), Out, STI);
382}
383
384void AArch64MCLFIRewriter::emitMov(MCRegister Dest, MCRegister Src,
385 MCStreamer &Out,
386 const MCSubtargetInfo &STI) {
387 // orr Dest, xzr, Src
388 emitInst(MCInstBuilder(AArch64::ORRXrs)
389 .addReg(Dest)
390 .addReg(AArch64::XZR)
391 .addReg(Src)
392 .addImm(0),
393 Out, STI);
394}
395
396void AArch64MCLFIRewriter::emitAddImm(MCRegister Dest, MCRegister Src,
397 int64_t Imm, MCStreamer &Out,
398 const MCSubtargetInfo &STI) {
399 assert(std::abs(Imm) <= 4095);
400 // add Dest, Src, Imm (or sub Dest, Src, -Imm for negative offsets)
401 unsigned Opcode = Imm >= 0 ? AArch64::ADDXri : AArch64::SUBXri;
402 emitInst(MCInstBuilder(Opcode)
403 .addReg(Dest)
404 .addReg(Src)
405 .addImm(std::abs(Imm))
406 .addImm(0), // shift
407 Out, STI);
408}
409
410void AArch64MCLFIRewriter::emitAddReg(MCRegister Dest, MCRegister Src1,
411 MCRegister Src2, unsigned Shift,
412 MCStreamer &Out,
413 const MCSubtargetInfo &STI) {
414 // add Dest, Src1, Src2, lsl #Shift
415 emitInst(MCInstBuilder(AArch64::ADDXrs)
416 .addReg(Dest)
417 .addReg(Src1)
418 .addReg(Src2)
420 Out, STI);
421}
422
423void AArch64MCLFIRewriter::emitAddRegExtend(MCRegister Dest, MCRegister Src1,
424 MCRegister Src2,
426 unsigned Shift, MCStreamer &Out,
427 const MCSubtargetInfo &STI) {
428 // add Dest, Src1, Src2, ExtType #Shift
429 unsigned Opcode = ExtType == AArch64_AM::SXTX || ExtType == AArch64_AM::UXTX
430 ? AArch64::ADDXrx64
431 : AArch64::ADDXrx;
432 emitInst(MCInstBuilder(Opcode).addReg(Dest).addReg(Src1).addReg(Src2).addImm(
433 AArch64_AM::getArithExtendImm(ExtType, Shift)),
434 Out, STI);
435}
436
437void AArch64MCLFIRewriter::emitMemRoW(unsigned Opcode, const MCOperand &DataOp,
438 MCRegister BaseReg, MCStreamer &Out,
439 const MCSubtargetInfo &STI) {
440 // Op DataOp, [LFIBaseReg, W(BaseReg), uxtw]
441 emitInst(MCInstBuilder(Opcode)
442 .addOperand(DataOp)
443 .addReg(LFIBaseReg)
444 .addReg(getWRegFromXReg(BaseReg))
445 .addImm(0) // S bit = 0 (UXTW).
446 .addImm(0), // Shift amount = 0 (unscaled).
447 Out, STI);
448}
449
450// {br,blr} xN
451// ->
452// add x28, x27, wN, uxtw
453// {br,blr} x28
454void AArch64MCLFIRewriter::rewriteIndirectBranch(const MCInst &Inst,
455 MCStreamer &Out,
456 const MCSubtargetInfo &STI) {
457 assert(Inst.getNumOperands() >= 1 && Inst.getOperand(0).isReg() &&
458 "expected register operand");
459 MCRegister BranchReg = Inst.getOperand(0).getReg();
460
461 // Guard the branch target through X28.
462 emitAddMask(LFIAddrReg, BranchReg, Out, STI);
463
464 emitPendingTLSDescCall(Out, STI);
465
466 emitBranch(Inst.getOpcode(), LFIAddrReg, Out, STI);
467}
468
469// ret xN (where xN != x30)
470// ->
471// add x28, x27, wN, uxtw
472// ret x28
473//
474// ret (x30) is safe since x30 is always within the sandbox.
475void AArch64MCLFIRewriter::rewriteReturn(const MCInst &Inst, MCStreamer &Out,
476 const MCSubtargetInfo &STI) {
477 assert(Inst.getNumOperands() >= 1 && Inst.getOperand(0).isReg() &&
478 "expected register operand");
479 // RET through LR is safe since LR is always within sandbox.
480 if (Inst.getOperand(0).getReg() != AArch64::LR)
481 rewriteIndirectBranch(Inst, Out, STI);
482 else
483 emitInst(Inst, Out, STI);
484}
485
486// modify x30
487// ->
488// modify x30
489// add x30, x27, w30, uxtw (deferred)
490void AArch64MCLFIRewriter::rewriteLRModification(const MCInst &Inst,
491 MCStreamer &Out,
492 const MCSubtargetInfo &STI) {
493 if (!isFakeMemAccess(Inst) &&
494 (mayLoad(Inst) || mayStore(Inst) || mayPrefetch(Inst)))
495 rewriteLoadStore(Inst, Out, STI);
496 else
497 emitInst(Inst, Out, STI);
498
499 // Defer the LR guard until the next control-flow instruction or label. This
500 // keeps a signed return address intact so that an authentication instruction
501 // can run before the mask destroys the PAC bits.
502 DeferredLRGuard = true;
503}
504
505// retaa / retab
506// ->
507// autiasp / autibsp
508// add x30, x27, w30, uxtw
509// ret
510void AArch64MCLFIRewriter::rewriteAuthenticatedReturn(
511 const MCInst &Inst, MCStreamer &Out, const MCSubtargetInfo &STI) {
512 emitInst(MCInstBuilder(Inst.getOpcode() == AArch64::RETAA ? AArch64::AUTIASP
513 : AArch64::AUTIBSP),
514 Out, STI);
515
516 emitAddMask(AArch64::LR, AArch64::LR, Out, STI);
517 emitBranch(AArch64::RET, AArch64::LR, Out, STI);
518}
519
520// {braa,brab,braaz,brabz} xN[, xM] (blra* for calls)
521// ->
522// {autia,autib,autiza,autizb} xN[, xM]
523// add x28, x27, wN, uxtw
524// {br,blr} x28
525void AArch64MCLFIRewriter::rewriteAuthenticatedBranchOrCall(
526 const MCInst &Inst, unsigned BranchOpcode, MCStreamer &Out,
527 const MCSubtargetInfo &STI) {
528 MCRegister TargetReg = Inst.getOperand(0).getReg();
529
530 // Select the authentication opcode for the target register.
531 unsigned AuthOpcode;
532 switch (Inst.getOpcode()) {
533 case AArch64::BRAA:
534 case AArch64::BLRAA:
535 AuthOpcode = AArch64::AUTIA;
536 break;
537 case AArch64::BRAB:
538 case AArch64::BLRAB:
539 AuthOpcode = AArch64::AUTIB;
540 break;
541 case AArch64::BRAAZ:
542 case AArch64::BLRAAZ:
543 AuthOpcode = AArch64::AUTIZA;
544 break;
545 case AArch64::BRABZ:
546 case AArch64::BLRABZ:
547 AuthOpcode = AArch64::AUTIZB;
548 break;
549 default:
550 llvm_unreachable("unexpected authenticated branch/call opcode");
551 }
552
553 MCInstBuilder Auth(AuthOpcode);
554 Auth.addReg(TargetReg); // dst
555 Auth.addReg(TargetReg); // src (tied to dst)
556 if (AuthOpcode == AArch64::AUTIA || AuthOpcode == AArch64::AUTIB)
557 Auth.addOperand(Inst.getOperand(1)); // modifier
558 emitInst(Auth, Out, STI);
559
560 // Guard the authenticated target and branch/call through x28.
561 emitAddMask(LFIAddrReg, TargetReg, Out, STI);
562 emitBranch(BranchOpcode, LFIAddrReg, Out, STI);
563}
564
565// svc #0
566// ->
567// mov x26, x30
568// ldur x30, [x25, #-8]
569// blr x30
570// add x30, x27, w26, uxtw
571void AArch64MCLFIRewriter::rewriteSyscall(const MCInst &, MCStreamer &Out,
572 const MCSubtargetInfo &STI) {
573 // Save LR to scratch.
574 emitMov(LFIScratchReg, AArch64::LR, Out, STI);
575
576 // Load syscall handler address from negative offset from context register.
577 emitInst(MCInstBuilder(AArch64::LDURXi)
578 .addReg(AArch64::LR)
579 .addReg(LFICtxReg)
580 .addImm(LFISyscallOffset),
581 Out, STI);
582
583 // Call the runtime.
584 emitBranch(AArch64::BLR, AArch64::LR, Out, STI);
585
586 // Restore LR with guard.
587 emitAddMask(AArch64::LR, LFIScratchReg, Out, STI);
588}
589
590// mrs xN, tpidr_el0
591// ->
592// ldr xN, [x25, #16]
593void AArch64MCLFIRewriter::rewriteTPRead(const MCInst &Inst, MCStreamer &Out,
594 const MCSubtargetInfo &STI) {
595 MCRegister DestReg = Inst.getOperand(0).getReg();
596
597 emitInst(MCInstBuilder(AArch64::LDRXui)
598 .addReg(DestReg)
599 .addReg(LFICtxReg)
600 .addImm(LFITPOffset),
601 Out, STI);
602}
603
604// msr tpidr_el0, xN
605// ->
606// str xN, [x25, #16]
607void AArch64MCLFIRewriter::rewriteTPWrite(const MCInst &Inst, MCStreamer &Out,
608 const MCSubtargetInfo &STI) {
609 MCRegister SrcReg = Inst.getOperand(1).getReg();
610
611 emitInst(MCInstBuilder(AArch64::STRXui)
612 .addReg(SrcReg)
613 .addReg(LFICtxReg)
614 .addImm(LFITPOffset),
615 Out, STI);
616}
617
618bool AArch64MCLFIRewriter::rewriteLoadStoreRoW(const MCInst &Inst,
619 MCStreamer &Out,
620 const MCSubtargetInfo &STI) {
621 unsigned Op = Inst.getOpcode();
622 unsigned MemOp;
623
624 // Case 1: Indexed load/store with zero immediate offset.
625 // ldr xN, [xM, #0] -> ldr xN, [x27, wM, uxtw]
626 if ((MemOp = convertVariantToRoW(Op, AArch64::LFI_AM_Ui)) !=
627 AArch64::INSTRUCTION_LIST_END) {
628 MCRegister BaseReg = Inst.getOperand(1).getReg();
629 if (BaseReg == AArch64::SP)
630 return false;
631 const MCOperand &OffsetOp = Inst.getOperand(2);
632 if (OffsetOp.isImm() && OffsetOp.getImm() == 0) {
633 emitMemRoW(MemOp, Inst.getOperand(0), BaseReg, Out, STI);
634 return true;
635 }
636 return false;
637 }
638
639 // Case 2: Pre-index load/store with writeback.
640 // ldr xN, [xM, #imm]! -> add xM, xM, #imm; ldr xN, [x27, wM, uxtw]
642 AArch64::INSTRUCTION_LIST_END) {
643 MCRegister BaseReg = Inst.getOperand(2).getReg();
644 if (BaseReg == AArch64::SP)
645 return false;
646 int64_t Imm = Inst.getOperand(3).getImm();
647 emitAddImm(BaseReg, BaseReg, Imm, Out, STI);
648 emitMemRoW(MemOp, Inst.getOperand(1), BaseReg, Out, STI);
649 return true;
650 }
651
652 // Case 3: Post-index load/store.
653 // ldr xN, [xM], #imm -> ldr xN, [x27, wM, uxtw]; add xM, xM, #imm
655 AArch64::INSTRUCTION_LIST_END) {
656 MCRegister BaseReg = Inst.getOperand(2).getReg();
657 if (BaseReg == AArch64::SP)
658 return false;
659 int64_t Imm = Inst.getOperand(3).getImm();
660 emitMemRoW(MemOp, Inst.getOperand(1), BaseReg, Out, STI);
661 emitAddImm(BaseReg, BaseReg, Imm, Out, STI);
662 return true;
663 }
664
665 // Case 4: Register-offset-X load/store.
666 // ldr xN, [xM1, xM2] -> add x26, xM1, xM2; ldr xN, [x27, w26, uxtw]
667 //
668 // In this case, even if xM1 is SP we must do a full rewrite, since an
669 // arbitrary register value is being added as the offset.
670 unsigned Shift;
671 if ((MemOp = convertRoXToRoW(Op, Shift)) != AArch64::INSTRUCTION_LIST_END) {
672 MCRegister Reg1 = Inst.getOperand(1).getReg();
673 MCRegister Reg2 = Inst.getOperand(2).getReg();
674 int64_t Extend = Inst.getOperand(3).getImm();
675 int64_t IsShift = Inst.getOperand(4).getImm();
676
677 if (!IsShift)
678 Shift = 0;
679
680 if (Extend)
681 emitAddRegExtend(LFIScratchReg, Reg1, Reg2, AArch64_AM::SXTX, Shift, Out,
682 STI);
683 else
684 emitAddReg(LFIScratchReg, Reg1, Reg2, Shift, Out, STI);
685 emitMemRoW(MemOp, Inst.getOperand(0), LFIScratchReg, Out, STI);
686 return true;
687 }
688
689 // Case 5: Register-offset-W load/store.
690 // ldr xN, [xM1, wM2, uxtw] -> add x26, xM1, wM2, uxtw;
691 // ldr xN, [x27, w26, uxtw]
692 if (getRoWShift(Op, Shift)) {
693 MCRegister Reg1 = Inst.getOperand(1).getReg();
694 MCRegister Reg2 = Inst.getOperand(2).getReg();
695 int64_t S = Inst.getOperand(3).getImm();
696 int64_t IsShift = Inst.getOperand(4).getImm();
697
698 if (!IsShift)
699 Shift = 0;
700
701 if (S)
702 emitAddRegExtend(LFIScratchReg, Reg1, Reg2, AArch64_AM::SXTW, Shift, Out,
703 STI);
704 else
705 emitAddRegExtend(LFIScratchReg, Reg1, Reg2, AArch64_AM::UXTW, Shift, Out,
706 STI);
707 emitMemRoW(Op, Inst.getOperand(0), LFIScratchReg, Out, STI);
708 return true;
709 }
710
711 return false;
712}
713
714void AArch64MCLFIRewriter::rewriteLoadStoreBase(const MCInst &Inst,
715 MCStreamer &Out,
716 const MCSubtargetInfo &STI) {
717 unsigned Opcode = Inst.getOpcode();
718 const AArch64::MemInfoEntry *Info = AArch64::lookupMemInfoByOpcode(Opcode);
719
720 if (!Info) {
721 warning(Inst, "unknown addressing mode for memory instruction in LFI");
722 return emitInst(Inst, Out, STI);
723 }
724
725 if (Info->IsLiteral)
726 return error(Inst, "PC-relative literal loads are not supported in LFI");
727
728 MCRegister BaseReg = Inst.getOperand(Info->BaseIdx).getReg();
729
730 // Stack accesses don't need address sandboxing, except when sp is modified
731 // with a non-zero register post-index operand.
732 bool BaseIsSP = BaseReg == AArch64::SP;
733 if (BaseIsSP) {
734 if (!Info->HasOffset || !Inst.getOperand(Info->OffsetIdx).isReg())
735 return emitInst(Inst, Out, STI);
736 MCRegister OffReg = Inst.getOperand(Info->OffsetIdx).getReg();
737 if (OffReg == AArch64::XZR || OffReg == AArch64::WZR)
738 return emitInst(Inst, Out, STI);
739 }
740
741 // Guard the base register, unless it is SP.
742 if (!BaseIsSP)
743 emitAddMask(LFIAddrReg, BaseReg, Out, STI);
744
745 if (!Info->IsPrePost) {
746 // Non-pre/post instruction: replace the base register operand.
747 MCInst NewInst = replaceRegAt(Inst, Info->BaseIdx, LFIAddrReg);
748 emitInst(NewInst, Out, STI);
749 return;
750 }
751
752 bool IsPre = false;
753 bool IsNoOffset = false;
754 unsigned BaseOpcode = convertPrePostToBase(Opcode, IsPre, IsNoOffset);
755
756 if (BaseOpcode == AArch64::INSTRUCTION_LIST_END)
757 return error(Inst, "unhandled pre/post-index instruction in LFI rewriter");
758
759 // Demote pre/post-index to base indexed form.
760 MCInstBuilder NewInst(BaseOpcode);
761 NewInst.setLoc(Inst.getLoc());
762
763 // Skip writeback operand (operand 0) and copy data operands up to base.
764 for (int I = 1; I < Info->BaseIdx; ++I)
765 NewInst.addOperand(Inst.getOperand(I));
766
767 // Add the access base register (LFIAddrReg or SP).
768 NewInst.addReg(BaseIsSP ? AArch64::SP : LFIAddrReg);
769
770 // For pre-index, include the offset; for post-index, use zero.
771 if (IsPre && Info->HasOffset)
772 NewInst.addOperand(Inst.getOperand(Info->OffsetIdx));
773 else if (!IsNoOffset)
774 NewInst.addImm(0);
775
776 emitInst(NewInst, Out, STI);
777
778 if (!Info->HasOffset)
779 return;
780
781 // Update the base register with the offset. If the base is SP, a register
782 // offset must be sandboxed (the result is otherwise unbounded), and ADDXrs
783 // cannot take SP, so the extended-register form via the scratch register is
784 // used.
785 const MCOperand &OffsetOp = Inst.getOperand(Info->OffsetIdx);
786 if (OffsetOp.isImm()) {
787 // Pair pre/post immediates are scaled by element size; other pre/post
788 // forms (scalar, SIMD) use the raw immediate (scale = 1).
789 int64_t Scale = 1;
790 if (const auto *E = AArch64::lookupPairVariantByOpcode(Opcode))
791 Scale = E->Scale;
792 int64_t Offset = OffsetOp.getImm() * Scale;
793 emitAddImm(BaseReg, BaseReg, Offset, Out, STI);
794 } else if (OffsetOp.isReg()) {
795 // SIMD post-index uses a register offset (XZR for natural offset).
796 MCRegister OffReg = OffsetOp.getReg();
797 if (OffReg == AArch64::XZR) {
798 if (const auto *E = AArch64::lookupSIMDPostByOpcode(Opcode))
799 emitAddImm(BaseReg, BaseReg, E->NaturalOffset, Out, STI);
800 } else if (OffReg != AArch64::WZR) {
801 if (BaseIsSP) {
802 emitAddRegExtend(LFIScratchReg, AArch64::SP, OffReg, AArch64_AM::UXTX,
803 0, Out, STI);
804 emitAddMask(AArch64::SP, LFIScratchReg, Out, STI);
805 } else {
806 emitAddReg(BaseReg, BaseReg, OffReg, 0, Out, STI);
807 }
808 }
809 }
810}
811
812void AArch64MCLFIRewriter::rewriteLoadStore(const MCInst &Inst, MCStreamer &Out,
813 const MCSubtargetInfo &STI) {
814 bool IsStore = mayStore(Inst);
815 bool IsLoad = mayLoad(Inst) || mayPrefetch(Inst);
816
817 bool SkipLoads = STI.hasFeature(AArch64::FeatureNoLFILoads);
818 bool SkipStores = STI.hasFeature(AArch64::FeatureNoLFIStores);
819
820 if ((!IsLoad || SkipLoads) && (!IsStore || SkipStores))
821 return emitInst(Inst, Out, STI);
822
823 if (rewriteLoadStoreRoW(Inst, Out, STI))
824 return;
825
826 rewriteLoadStoreBase(Inst, Out, STI);
827}
828
829// modify sp
830// ->
831// modify x26
832// add sp, x27, w26, uxtw
833void AArch64MCLFIRewriter::rewriteSPModification(const MCInst &Inst,
834 MCStreamer &Out,
835 const MCSubtargetInfo &STI) {
836 // Route through rewriteLRModification or rewriteLoadStore for memory
837 // accesses. Those helpers automatically handle dangerous stack modifications
838 // that can happen via register post-index.
839 if (mayLoad(Inst) || mayStore(Inst)) {
840 if (mayModifyRegister(Inst, AArch64::LR))
841 return rewriteLRModification(Inst, Out, STI);
842 return rewriteLoadStore(Inst, Out, STI);
843 }
844
845 // No stack sandboxing if sandboxing is disabled for both loads and stores.
846 bool SkipLoads = STI.hasFeature(AArch64::FeatureNoLFILoads);
847 bool SkipStores = STI.hasFeature(AArch64::FeatureNoLFIStores);
848 if (SkipLoads && SkipStores)
849 return emitInst(Inst, Out, STI);
850
851 // Special case: mov sp, xN -> add sp, x27, wN, uxtw
852 if (Inst.getOpcode() == AArch64::ADDXri && Inst.getOperand(2).getImm() == 0 &&
853 Inst.getOperand(3).getImm() == 0)
854 return emitAddMask(AArch64::SP, Inst.getOperand(1).getReg(), Out, STI);
855
856 // Redirect SP modification destination to scratch, then sandbox.
857 MCInst ModInst = replaceRegAt(Inst, 0, LFIScratchReg);
858 emitInst(ModInst, Out, STI);
859 emitAddMask(AArch64::SP, LFIScratchReg, Out, STI);
860}
861
862// {dc,ic} <op>, xN
863// ->
864// add x28, x27, wN, uxtw
865// {dc,ic} <op>, x28
866void AArch64MCLFIRewriter::rewriteVASysOp(const MCInst &Inst, MCStreamer &Out,
867 const MCSubtargetInfo &STI) {
868 MCRegister AddrReg = Inst.getOperand(4).getReg();
869
870 emitAddMask(LFIAddrReg, AddrReg, Out, STI);
871
872 emitInst(MCInstBuilder(AArch64::SYSxt)
873 .addOperand(Inst.getOperand(0))
874 .addOperand(Inst.getOperand(1))
875 .addOperand(Inst.getOperand(2))
876 .addOperand(Inst.getOperand(3))
877 .addReg(LFIAddrReg),
878 Out, STI);
879}
880
881// NOTE: when adding new rewrites, the size estimates in
882// AArch64InstrInfo::getLFIInstSizeInBytes must be updated to match.
883void AArch64MCLFIRewriter::doRewriteInst(const MCInst &Inst, MCStreamer &Out,
884 const MCSubtargetInfo &STI) {
885 if (Inst.getOpcode() == AArch64::TLSDESCCALL) {
886 PendingTLSDescCall = Inst.getOperand(0).getExpr();
887 return;
888 }
889
890 // Reserved register modification is an error.
891 if (MCRegister Reg = mayModifyReserved(Inst)) {
892 error(Inst, Twine("illegal modification of reserved LFI register ") +
893 RegInfo->getName(Reg));
894 return;
895 }
896
897 // System instructions.
898 if (isSyscall(Inst))
899 return rewriteSyscall(Inst, Out, STI);
900
901 if (isTPRead(Inst))
902 return rewriteTPRead(Inst, Out, STI);
903
904 if (isTPWrite(Inst))
905 return rewriteTPWrite(Inst, Out, STI);
906
907 if (isPrivilegedTPAccess(Inst)) {
908 error(Inst, "illegal access to privileged thread pointer register");
909 return;
910 }
911
912 if (isVASysOp(Inst))
913 return rewriteVASysOp(Inst, Out, STI);
914
915 // LFI routes all indirect branches through x28, including tail calls that
916 // would otherwise use x16/x17. AAPCS64 only allows for `bti c` landing
917 // pads for indirect calls though x16/x17.
918 // A BR through any other register (e.g., x28) cannot land on BTI C, so
919 // we promote call landing pads to BTI JC.
920 //
921 // br {x16,x17}
922 // ->
923 // add x28, x27, {w16,w17}, uxtw
924 // br x28
925 if (isBTIC(Inst))
926 return emitInst(MCInstBuilder(AArch64::HINT)
927 .addImm(getBTIHintNum(/*CallTarget=*/true,
928 /*JumpTarget=*/true)),
929 Out, STI);
930
931 if (isExceptionReturn(Inst.getOpcode())) {
932 error(Inst, "exception returns are not supported by LFI");
933 return;
934 }
935
936 // PAC authenticated returns expand to authenticate + guarded RET. The
937 // expansion emits its own LR guard, so discard any deferred guard: masking
938 // before the authentication would corrupt the signed return address.
939 if (isAuthenticatedReturn(Inst.getOpcode())) {
940 DeferredLRGuard = false;
941 return rewriteAuthenticatedReturn(Inst, Out, STI);
942 }
943
944 // Flush a deferred LR guard before any control-flow instruction, so that a
945 // modified LR is sandboxed before it can be used to transfer control.
946 if (DeferredLRGuard && (isReturn(Inst) || isIndirectBranch(Inst) ||
947 isCall(Inst) || isBranch(Inst))) {
948 emitAddMask(AArch64::LR, AArch64::LR, Out, STI);
949 DeferredLRGuard = false;
950 }
951
952 // PAC authenticated branches/calls expand to authenticate + guarded branch.
954 return rewriteAuthenticatedBranchOrCall(Inst, AArch64::BR, Out, STI);
955 if (isAuthenticatedCall(Inst.getOpcode()))
956 return rewriteAuthenticatedBranchOrCall(Inst, AArch64::BLR, Out, STI);
957
958 // Control flow.
959 switch (Inst.getOpcode()) {
960 case AArch64::RET:
961 return rewriteReturn(Inst, Out, STI);
962 case AArch64::BR:
963 case AArch64::BLR:
964 return rewriteIndirectBranch(Inst, Out, STI);
965 }
966
967 // Register modifications that require sandboxing.
968 if (mayModifySP(Inst))
969 return rewriteSPModification(Inst, Out, STI);
970
971 // Link register modification. This covers explicit writes to x30 as well as
972 // PAC instructions that write LR in place, which define LR implicitly.
973 if (explicitlyModifiesRegister(Inst, AArch64::LR) || pacWritesLR(Inst))
974 return rewriteLRModification(Inst, Out, STI);
975
976 // Memory access.
977 if (!isFakeMemAccess(Inst) &&
978 (mayLoad(Inst) || mayStore(Inst) || mayPrefetch(Inst)))
979 return rewriteLoadStore(Inst, Out, STI);
980
981 emitInst(Inst, Out, STI);
982}
983
984// This function is made available to the size estimator so that it can
985// classify Pre/Post-index instructions.
986bool llvm::isLFIPrePostMemAccess(unsigned Opcode) {
988 AArch64::INSTRUCTION_LIST_END)
989 return true;
991 AArch64::INSTRUCTION_LIST_END)
992 return true;
993 bool IsPre, IsNoOffset;
994 if (convertPrePostToBase(Opcode, IsPre, IsNoOffset) !=
995 AArch64::INSTRUCTION_LIST_END)
996 return true;
997 return false;
998}
999
1001 const MCSubtargetInfo &STI) {
1002 // Invalidate guard state if the rewriter was manually disabled.
1003 if (!Enabled)
1004 ActiveGuardReg = std::nullopt;
1005
1006 // This recursion guard prevents rewrite-recursion when we emit instructions
1007 // from inside the rewriter (such instructions should not be rewritten).
1008 if (!Enabled || Guard)
1009 return false;
1010 Guard = true;
1011
1012 // Record the subtarget so a deferred LR guard can be emitted from
1013 // onLabel/finish, which are not given an MCSubtargetInfo.
1014 LastSTI = &STI;
1015
1016 doRewriteInst(Inst, Out, STI);
1017
1018 Guard = false;
1019 return true;
1020}
static unsigned convertPrePostToBase(unsigned Op, bool &IsPre, bool &IsNoOffset)
static bool isFakeMemAccess(const MCInst &Inst)
static constexpr unsigned LFITPOffset
static constexpr MCRegister LFIScratchReg
static bool pacWritesLR(const MCInst &Inst)
static bool isPrivilegedTPAccess(const MCInst &Inst)
static bool isAuthenticatedBranch(unsigned Opcode)
static constexpr MCRegister LFICtxReg
static bool isPrivilegedTP(int64_t Reg)
static bool isBTIC(const MCInst &Inst)
static bool isAuthenticatedReturn(unsigned Opcode)
static bool getRoWShift(unsigned Op, unsigned &Shift)
static bool isVASysOp(const MCInst &Inst)
static bool isTPRead(const MCInst &Inst)
static bool mayPrefetch(const MCInst &Inst)
static bool isSyscall(const MCInst &Inst)
static MCInst replaceRegAt(const MCInst &Inst, unsigned Idx, MCRegister NewReg)
static unsigned convertVariantToRoW(unsigned Op, unsigned ExpectedMode)
static constexpr MCRegister LFIAddrReg
static unsigned convertRoXToRoW(unsigned Op, unsigned &Shift)
static bool isExceptionReturn(unsigned Opcode)
static constexpr MCRegister LFIBaseReg
static constexpr int LFISyscallOffset
static bool isTPWrite(const MCInst &Inst)
static bool isAuthenticatedCall(unsigned Opcode)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t Imm
static MCDisassembler::DecodeStatus addOperand(MCInst &Inst, const MCOperand &Opnd)
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
std::pair< Instruction::BinaryOps, Value * > OffsetOp
Find all possible pairs (BinOp, RHS) that BinOp V, RHS can be simplified.
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
uint64_t IntrinsicInst * II
#define error(X)
AArch64MCLFIRewriter(MCContext &Ctx, std::unique_ptr< MCRegisterInfo > &&RI, std::unique_ptr< MCInstrInfo > &&II)
void onLabel(const MCSymbol *Symbol, MCStreamer &Out) override
bool rewriteInst(const MCInst &Inst, MCStreamer &Out, const MCSubtargetInfo &STI) override
void finish(MCStreamer &Out) override
Context object for machine code objects.
Definition MCContext.h:84
Instances of this class represent a single low-level machine instruction.
Definition MCInst.h:188
unsigned getNumOperands() const
Definition MCInst.h:212
SMLoc getLoc() const
Definition MCInst.h:208
unsigned getOpcode() const
Definition MCInst.h:202
const MCOperand & getOperand(unsigned i) const
Definition MCInst.h:210
Describe properties that are true of each instruction in the target description file.
LLVM_ABI bool mayModifyRegister(const MCInst &Inst, MCRegister Reg) const
LLVM_ABI bool mayLoad(const MCInst &Inst) const
LLVM_ABI bool isIndirectBranch(const MCInst &Inst) const
LLVM_ABI void warning(const MCInst &Inst, const Twine &Msg)
LLVM_ABI bool isCall(const MCInst &Inst) const
LLVM_ABI bool isReturn(const MCInst &Inst) const
std::unique_ptr< MCRegisterInfo > RegInfo
LLVM_ABI bool mayStore(const MCInst &Inst) const
LLVM_ABI bool explicitlyModifiesRegister(const MCInst &Inst, MCRegister Reg) const
MCLFIRewriter(MCContext &Ctx, std::unique_ptr< MCRegisterInfo > &&RI, std::unique_ptr< MCInstrInfo > &&II)
LLVM_ABI bool isBranch(const MCInst &Inst) const
Instances of this class represent operands of the MCInst class.
Definition MCInst.h:40
int64_t getImm() const
Definition MCInst.h:84
bool isReg() const
Definition MCInst.h:65
MCRegister getReg() const
Returns the register number.
Definition MCInst.h:73
const MCExpr * getExpr() const
Definition MCInst.h:118
Wrapper class representing physical registers. Should be passed by value.
Definition MCRegister.h:41
Streaming machine code generation interface.
Definition MCStreamer.h:222
Generic base class for all target subtargets.
bool hasFeature(unsigned Feature) const
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition MCSymbol.h:42
Target - Wrapper for Target specific information.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
static unsigned getArithExtendImm(AArch64_AM::ShiftExtendType ET, unsigned Imm)
getArithExtendImm - Encode the extend type and shift amount for an arithmetic instruction: imm: 3-bit...
static unsigned getShifterImm(AArch64_AM::ShiftExtendType ST, unsigned Imm)
getShifterImm - Encode the shift type and amount: imm: 6-bit shift amount shifter: 000 ==> lsl 001 ==...
BaseReg
Stack frame base register. Bit 0 of FREInfo.Info.
Definition SFrame.h:77
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
static unsigned getBTIHintNum(bool CallTarget, bool JumpTarget)
Op::Description Desc
bool isLFIPrePostMemAccess(unsigned Opcode)
Returns true if Opcode is a pre- or post-indexed memory access that the LFI rewriter expands with a b...
DWARFExpression::Operation Op
static MCRegister getWRegFromXReg(MCRegister Reg)
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1933
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:879