LLVM 19.0.0git
AArch64SLSHardening.cpp
Go to the documentation of this file.
1//===- AArch64SLSHardening.cpp - Harden Straight Line Missspeculation -----===//
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 contains a pass to insert code to mitigate against side channel
10// vulnerabilities that may happen under straight line miss-speculation.
11//
12//===----------------------------------------------------------------------===//
13
14#include "AArch64InstrInfo.h"
15#include "AArch64Subtarget.h"
26#include "llvm/IR/DebugLoc.h"
27#include "llvm/Pass.h"
29#include "llvm/Support/Debug.h"
31#include <cassert>
32
33using namespace llvm;
34
35#define DEBUG_TYPE "aarch64-sls-hardening"
36
37#define AARCH64_SLS_HARDENING_NAME "AArch64 sls hardening pass"
38
39namespace {
40
41class AArch64SLSHardening : public MachineFunctionPass {
42public:
43 const TargetInstrInfo *TII;
45 const AArch64Subtarget *ST;
46
47 static char ID;
48
49 AArch64SLSHardening() : MachineFunctionPass(ID) {
51 }
52
53 bool runOnMachineFunction(MachineFunction &Fn) override;
54
55 StringRef getPassName() const override { return AARCH64_SLS_HARDENING_NAME; }
56
57private:
58 bool hardenReturnsAndBRs(MachineBasicBlock &MBB) const;
59 bool hardenBLRs(MachineBasicBlock &MBB) const;
62};
63
64} // end anonymous namespace
65
66char AArch64SLSHardening::ID = 0;
67
68INITIALIZE_PASS(AArch64SLSHardening, "aarch64-sls-hardening",
69 AARCH64_SLS_HARDENING_NAME, false, false)
70
71static void insertSpeculationBarrier(const AArch64Subtarget *ST,
76 assert(MBBI != MBB.begin() &&
77 "Must not insert SpeculationBarrierEndBB as only instruction in MBB.");
78 assert(std::prev(MBBI)->isBarrier() &&
79 "SpeculationBarrierEndBB must only follow unconditional control flow "
80 "instructions.");
81 assert(std::prev(MBBI)->isTerminator() &&
82 "SpeculationBarrierEndBB must only follow terminators.");
83 const TargetInstrInfo *TII = ST->getInstrInfo();
84 unsigned BarrierOpc = ST->hasSB() && !AlwaysUseISBDSB
85 ? AArch64::SpeculationBarrierSBEndBB
86 : AArch64::SpeculationBarrierISBDSBEndBB;
87 if (MBBI == MBB.end() ||
88 (MBBI->getOpcode() != AArch64::SpeculationBarrierSBEndBB &&
89 MBBI->getOpcode() != AArch64::SpeculationBarrierISBDSBEndBB))
90 BuildMI(MBB, MBBI, DL, TII->get(BarrierOpc));
91}
92
93bool AArch64SLSHardening::runOnMachineFunction(MachineFunction &MF) {
97
98 bool Modified = false;
99 for (auto &MBB : MF) {
100 Modified |= hardenReturnsAndBRs(MBB);
101 Modified |= hardenBLRs(MBB);
102 }
103
104 return Modified;
105}
106
107static bool isBLR(const MachineInstr &MI) {
108 switch (MI.getOpcode()) {
109 case AArch64::BLR:
110 case AArch64::BLRNoIP:
111 return true;
112 case AArch64::BLRAA:
113 case AArch64::BLRAB:
114 case AArch64::BLRAAZ:
115 case AArch64::BLRABZ:
116 llvm_unreachable("Currently, LLVM's code generator does not support "
117 "producing BLRA* instructions. Therefore, there's no "
118 "support in this pass for those instructions.");
119 }
120 return false;
121}
122
123bool AArch64SLSHardening::hardenReturnsAndBRs(MachineBasicBlock &MBB) const {
124 if (!ST->hardenSlsRetBr())
125 return false;
126 bool Modified = false;
129 for (; MBBI != E; MBBI = NextMBBI) {
130 MachineInstr &MI = *MBBI;
131 NextMBBI = std::next(MBBI);
132 if (MI.isReturn() || isIndirectBranchOpcode(MI.getOpcode())) {
133 assert(MI.isTerminator());
134 insertSpeculationBarrier(ST, MBB, std::next(MBBI), MI.getDebugLoc());
135 Modified = true;
136 }
137 }
138 return Modified;
139}
140
141static const char SLSBLRNamePrefix[] = "__llvm_slsblr_thunk_";
142
143static const struct ThunkNameAndReg {
144 const char* Name;
146} SLSBLRThunks[] = {
147 { "__llvm_slsblr_thunk_x0", AArch64::X0},
148 { "__llvm_slsblr_thunk_x1", AArch64::X1},
149 { "__llvm_slsblr_thunk_x2", AArch64::X2},
150 { "__llvm_slsblr_thunk_x3", AArch64::X3},
151 { "__llvm_slsblr_thunk_x4", AArch64::X4},
152 { "__llvm_slsblr_thunk_x5", AArch64::X5},
153 { "__llvm_slsblr_thunk_x6", AArch64::X6},
154 { "__llvm_slsblr_thunk_x7", AArch64::X7},
155 { "__llvm_slsblr_thunk_x8", AArch64::X8},
156 { "__llvm_slsblr_thunk_x9", AArch64::X9},
157 { "__llvm_slsblr_thunk_x10", AArch64::X10},
158 { "__llvm_slsblr_thunk_x11", AArch64::X11},
159 { "__llvm_slsblr_thunk_x12", AArch64::X12},
160 { "__llvm_slsblr_thunk_x13", AArch64::X13},
161 { "__llvm_slsblr_thunk_x14", AArch64::X14},
162 { "__llvm_slsblr_thunk_x15", AArch64::X15},
163 // X16 and X17 are deliberately missing, as the mitigation requires those
164 // register to not be used in BLR. See comment in ConvertBLRToBL for more
165 // details.
166 { "__llvm_slsblr_thunk_x18", AArch64::X18},
167 { "__llvm_slsblr_thunk_x19", AArch64::X19},
168 { "__llvm_slsblr_thunk_x20", AArch64::X20},
169 { "__llvm_slsblr_thunk_x21", AArch64::X21},
170 { "__llvm_slsblr_thunk_x22", AArch64::X22},
171 { "__llvm_slsblr_thunk_x23", AArch64::X23},
172 { "__llvm_slsblr_thunk_x24", AArch64::X24},
173 { "__llvm_slsblr_thunk_x25", AArch64::X25},
174 { "__llvm_slsblr_thunk_x26", AArch64::X26},
175 { "__llvm_slsblr_thunk_x27", AArch64::X27},
176 { "__llvm_slsblr_thunk_x28", AArch64::X28},
177 { "__llvm_slsblr_thunk_x29", AArch64::FP},
178 // X30 is deliberately missing, for similar reasons as X16 and X17 are
179 // missing.
180 { "__llvm_slsblr_thunk_x31", AArch64::XZR},
182
183namespace {
184struct SLSBLRThunkInserter : ThunkInserter<SLSBLRThunkInserter> {
185 const char *getThunkPrefix() { return SLSBLRNamePrefix; }
186 bool mayUseThunk(const MachineFunction &MF, bool InsertedThunks) {
187 if (InsertedThunks)
188 return false;
189 ComdatThunks &= !MF.getSubtarget<AArch64Subtarget>().hardenSlsNoComdat();
190 // FIXME: This could also check if there are any BLRs in the function
191 // to more accurately reflect if a thunk will be needed.
192 return MF.getSubtarget<AArch64Subtarget>().hardenSlsBlr();
193 }
194 bool insertThunks(MachineModuleInfo &MMI, MachineFunction &MF);
195 void populateThunk(MachineFunction &MF);
196
197private:
198 bool ComdatThunks = true;
199};
200} // namespace
201
202bool SLSBLRThunkInserter::insertThunks(MachineModuleInfo &MMI,
203 MachineFunction &MF) {
204 // FIXME: It probably would be possible to filter which thunks to produce
205 // based on which registers are actually used in BLR instructions in this
206 // function. But would that be a worthwhile optimization?
207 for (auto T : SLSBLRThunks)
208 createThunkFunction(MMI, T.Name, ComdatThunks);
209 return true;
210}
211
212void SLSBLRThunkInserter::populateThunk(MachineFunction &MF) {
213 // FIXME: How to better communicate Register number, rather than through
214 // name and lookup table?
215 assert(MF.getName().starts_with(getThunkPrefix()));
216 auto ThunkIt = llvm::find_if(
217 SLSBLRThunks, [&MF](auto T) { return T.Name == MF.getName(); });
218 assert(ThunkIt != std::end(SLSBLRThunks));
219 Register ThunkReg = ThunkIt->Reg;
220
221 const TargetInstrInfo *TII =
222 MF.getSubtarget<AArch64Subtarget>().getInstrInfo();
223
224 // Depending on whether this pass is in the same FunctionPassManager as the
225 // IR->MIR conversion, the thunk may be completely empty, or contain a single
226 // basic block with a single return instruction. Normalise it to contain a
227 // single empty basic block.
228 if (MF.size() == 1) {
229 assert(MF.front().size() == 1);
230 assert(MF.front().front().getOpcode() == AArch64::RET);
231 MF.front().erase(MF.front().begin());
232 } else {
233 assert(MF.size() == 0);
235 }
236
237 MachineBasicBlock *Entry = &MF.front();
238 Entry->clear();
239
240 // These thunks need to consist of the following instructions:
241 // __llvm_slsblr_thunk_xN:
242 // BR xN
243 // barrierInsts
244 Entry->addLiveIn(ThunkReg);
245 // MOV X16, ThunkReg == ORR X16, XZR, ThunkReg, LSL #0
246 BuildMI(Entry, DebugLoc(), TII->get(AArch64::ORRXrs), AArch64::X16)
247 .addReg(AArch64::XZR)
248 .addReg(ThunkReg)
249 .addImm(0);
250 BuildMI(Entry, DebugLoc(), TII->get(AArch64::BR)).addReg(AArch64::X16);
251 // Make sure the thunks do not make use of the SB extension in case there is
252 // a function somewhere that will call to it that for some reason disabled
253 // the SB extension locally on that function, even though it's enabled for
254 // the module otherwise. Therefore set AlwaysUseISBSDB to true.
255 insertSpeculationBarrier(&MF.getSubtarget<AArch64Subtarget>(), *Entry,
256 Entry->end(), DebugLoc(), true /*AlwaysUseISBDSB*/);
257}
258
259MachineBasicBlock &AArch64SLSHardening::ConvertBLRToBL(
261 // Transform a BLR to a BL as follows:
262 // Before:
263 // |-----------------------------|
264 // | ... |
265 // | instI |
266 // | BLR xN |
267 // | instJ |
268 // | ... |
269 // |-----------------------------|
270 //
271 // After:
272 // |-----------------------------|
273 // | ... |
274 // | instI |
275 // | BL __llvm_slsblr_thunk_xN |
276 // | instJ |
277 // | ... |
278 // |-----------------------------|
279 //
280 // __llvm_slsblr_thunk_xN:
281 // |-----------------------------|
282 // | BR xN |
283 // | barrierInsts |
284 // |-----------------------------|
285 //
286 // The __llvm_slsblr_thunk_xN thunks are created by the SLSBLRThunkInserter.
287 // This function merely needs to transform BLR xN into BL
288 // __llvm_slsblr_thunk_xN.
289 //
290 // Since linkers are allowed to clobber X16 and X17 on function calls, the
291 // above mitigation only works if the original BLR instruction was not
292 // BLR X16 nor BLR X17. Code generation before must make sure that no BLR
293 // X16|X17 was produced if the mitigation is enabled.
294
295 MachineInstr &BLR = *MBBI;
296 assert(isBLR(BLR));
297 unsigned BLOpcode;
299 bool RegIsKilled;
300 switch (BLR.getOpcode()) {
301 case AArch64::BLR:
302 case AArch64::BLRNoIP:
303 BLOpcode = AArch64::BL;
304 Reg = BLR.getOperand(0).getReg();
305 assert(Reg != AArch64::X16 && Reg != AArch64::X17 && Reg != AArch64::LR);
306 RegIsKilled = BLR.getOperand(0).isKill();
307 break;
308 case AArch64::BLRAA:
309 case AArch64::BLRAB:
310 case AArch64::BLRAAZ:
311 case AArch64::BLRABZ:
312 llvm_unreachable("BLRA instructions cannot yet be produced by LLVM, "
313 "therefore there is no need to support them for now.");
314 default:
315 llvm_unreachable("unhandled BLR");
316 }
317 DebugLoc DL = BLR.getDebugLoc();
318
319 // If we'd like to support also BLRAA and BLRAB instructions, we'd need
320 // a lot more different kind of thunks.
321 // For example, a
322 //
323 // BLRAA xN, xM
324 //
325 // instruction probably would need to be transformed to something like:
326 //
327 // BL __llvm_slsblraa_thunk_x<N>_x<M>
328 //
329 // __llvm_slsblraa_thunk_x<N>_x<M>:
330 // BRAA x<N>, x<M>
331 // barrierInsts
332 //
333 // Given that about 30 different values of N are possible and about 30
334 // different values of M are possible in the above, with the current way
335 // of producing indirect thunks, we'd be producing about 30 times 30, i.e.
336 // about 900 thunks (where most might not be actually called). This would
337 // multiply further by two to support both BLRAA and BLRAB variants of those
338 // instructions.
339 // If we'd want to support this, we'd probably need to look into a different
340 // way to produce thunk functions, based on which variants are actually
341 // needed, rather than producing all possible variants.
342 // So far, LLVM does never produce BLRA* instructions, so let's leave this
343 // for the future when LLVM can start producing BLRA* instructions.
344 MachineFunction &MF = *MBBI->getMF();
346 auto ThunkIt =
347 llvm::find_if(SLSBLRThunks, [Reg](auto T) { return T.Reg == Reg; });
348 assert (ThunkIt != std::end(SLSBLRThunks));
349 MCSymbol *Sym = Context.getOrCreateSymbol(ThunkIt->Name);
350
351 MachineInstr *BL = BuildMI(MBB, MBBI, DL, TII->get(BLOpcode)).addSym(Sym);
352
353 // Now copy the implicit operands from BLR to BL and copy other necessary
354 // info.
355 // However, both BLR and BL instructions implictly use SP and implicitly
356 // define LR. Blindly copying implicit operands would result in SP and LR
357 // operands to be present multiple times. While this may not be too much of
358 // an issue, let's avoid that for cleanliness, by removing those implicit
359 // operands from the BL created above before we copy over all implicit
360 // operands from the BLR.
361 int ImpLROpIdx = -1;
362 int ImpSPOpIdx = -1;
363 for (unsigned OpIdx = BL->getNumExplicitOperands();
364 OpIdx < BL->getNumOperands(); OpIdx++) {
365 MachineOperand Op = BL->getOperand(OpIdx);
366 if (!Op.isReg())
367 continue;
368 if (Op.getReg() == AArch64::LR && Op.isDef())
369 ImpLROpIdx = OpIdx;
370 if (Op.getReg() == AArch64::SP && !Op.isDef())
371 ImpSPOpIdx = OpIdx;
372 }
373 assert(ImpLROpIdx != -1);
374 assert(ImpSPOpIdx != -1);
375 int FirstOpIdxToRemove = std::max(ImpLROpIdx, ImpSPOpIdx);
376 int SecondOpIdxToRemove = std::min(ImpLROpIdx, ImpSPOpIdx);
377 BL->removeOperand(FirstOpIdxToRemove);
378 BL->removeOperand(SecondOpIdxToRemove);
379 // Now copy over the implicit operands from the original BLR
380 BL->copyImplicitOps(MF, BLR);
381 MF.moveCallSiteInfo(&BLR, BL);
382 // Also add the register called in the BLR as being used in the called thunk.
383 BL->addOperand(MachineOperand::CreateReg(Reg, false /*isDef*/, true /*isImp*/,
384 RegIsKilled /*isKill*/));
385 // Remove BLR instruction
386 MBB.erase(MBBI);
387
388 return MBB;
389}
390
391bool AArch64SLSHardening::hardenBLRs(MachineBasicBlock &MBB) const {
392 if (!ST->hardenSlsBlr())
393 return false;
394 bool Modified = false;
396 E = MBB.instr_end();
398 for (; MBBI != E; MBBI = NextMBBI) {
399 MachineInstr &MI = *MBBI;
400 NextMBBI = std::next(MBBI);
401 if (isBLR(MI)) {
402 ConvertBLRToBL(MBB, MBBI);
403 Modified = true;
404 }
405 }
406 return Modified;
407}
408
410 return new AArch64SLSHardening();
411}
412
413namespace {
414class AArch64IndirectThunks : public MachineFunctionPass {
415public:
416 static char ID;
417
418 AArch64IndirectThunks() : MachineFunctionPass(ID) {}
419
420 StringRef getPassName() const override { return "AArch64 Indirect Thunks"; }
421
422 bool doInitialization(Module &M) override;
423 bool runOnMachineFunction(MachineFunction &MF) override;
424
425private:
426 std::tuple<SLSBLRThunkInserter> TIs;
427
428 template <typename... ThunkInserterT>
429 static void initTIs(Module &M,
430 std::tuple<ThunkInserterT...> &ThunkInserters) {
431 (..., std::get<ThunkInserterT>(ThunkInserters).init(M));
432 }
433 template <typename... ThunkInserterT>
434 static bool runTIs(MachineModuleInfo &MMI, MachineFunction &MF,
435 std::tuple<ThunkInserterT...> &ThunkInserters) {
436 return (0 | ... | std::get<ThunkInserterT>(ThunkInserters).run(MMI, MF));
437 }
438};
439
440} // end anonymous namespace
441
442char AArch64IndirectThunks::ID = 0;
443
445 return new AArch64IndirectThunks();
446}
447
448bool AArch64IndirectThunks::doInitialization(Module &M) {
449 initTIs(M, TIs);
450 return false;
451}
452
453bool AArch64IndirectThunks::runOnMachineFunction(MachineFunction &MF) {
454 LLVM_DEBUG(dbgs() << getPassName() << '\n');
455 auto &MMI = getAnalysis<MachineModuleInfoWrapperPass>().getMMI();
456 return runTIs(MMI, MF, TIs);
457}
aarch64 promote const
#define AARCH64_SLS_HARDENING_NAME
static const struct ThunkNameAndReg SLSBLRThunks[]
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc bool AlwaysUseISBDSB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
MachineBasicBlock MachineBasicBlock::iterator MBBI
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_DEBUG(X)
Definition: Debug.h:101
Symbol * Sym
Definition: ELF_riscv.cpp:479
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
Contains a base class for Passes that inject an MI thunk.
unsigned const TargetRegisterInfo * TRI
LLVMContext & Context
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:38
This file declares the machine register scavenger class.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This class represents an Operation in the Expression.
A debug info location.
Definition: DebugLoc.h:33
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:311
Context object for machine code objects.
Definition: MCContext.h:76
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:40
instr_iterator instr_begin()
iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
Instructions::iterator instr_iterator
instr_iterator instr_end()
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
instr_iterator erase(instr_iterator I)
Remove an instruction from the instruction list and delete it.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
bool doInitialization(Module &) override
doInitialization - Virtual method overridden by subclasses to do any necessary initialization before ...
virtual bool runOnMachineFunction(MachineFunction &MF)=0
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
void push_back(MachineBasicBlock *MBB)
MCContext & getContext() const
unsigned size() const
const MachineBasicBlock & front() const
void moveCallSiteInfo(const MachineInstr *Old, const MachineInstr *New)
Move the call site info from Old to \New call site info.
MachineBasicBlock * CreateMachineBasicBlock(const BasicBlock *BB=nullptr, std::optional< UniqueBBID > BBID=std::nullopt)
CreateMachineBasicBlock - Allocate a new MachineBasicBlock.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & addSym(MCSymbol *Sym, unsigned char TargetFlags=0) const
const MachineInstrBuilder & addReg(Register RegNo, unsigned flags=0, unsigned SubReg=0) const
Add a new virtual register operand.
Representation of each machine instruction.
Definition: MachineInstr.h:69
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
Definition: MachineInstr.h:544
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
Definition: MachineInstr.h:473
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:554
This class contains meta information specific to a module.
MachineOperand class - Representation of each machine instruction operand.
Register getReg() const
getReg - Returns the register number.
static MachineOperand CreateReg(Register Reg, bool isDef, bool isImp=false, bool isKill=false, bool isDead=false, bool isUndef=false, bool isEarlyClobber=false, unsigned SubReg=0, bool isDebug=false, bool isInternalRead=false, bool isRenamable=false)
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
virtual StringRef getPassName() const
getPassName - Return a nice clean name for a pass.
Definition: Pass.cpp:81
Wrapper class representing virtual and physical registers.
Definition: Register.h:19
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition: StringRef.h:257
TargetInstrInfo - Interface to description of machine instruction set.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
virtual const TargetInstrInfo * getInstrInfo() const
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition: CallingConv.h:24
Reg
All possible values of the reg field in the ModR/M byte.
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
static bool isIndirectBranchOpcode(int Opc)
FunctionPass * createAArch64IndirectThunks()
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
void initializeAArch64SLSHardeningPass(PassRegistry &)
FunctionPass * createAArch64SLSHardeningPass()
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1758