LLVM 24.0.0git
AArch64SpeculationHardening.cpp
Go to the documentation of this file.
1//===- AArch64SpeculationHardening.cpp - Harden Against 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 control flow miss-speculation.
11//
12// The pass implements tracking of control flow miss-speculation into a "taint"
13// register. That taint register can then be used to mask off registers with
14// sensitive data when executing under miss-speculation, a.k.a. "transient
15// execution".
16// This pass is aimed at mitigating against SpectreV1-style vulnerabilities.
17//
18// It also implements speculative load hardening, i.e. using the taint register
19// to automatically mask off loaded data.
20//
21// As a possible follow-on improvement, also an intrinsics-based approach as
22// explained at https://lwn.net/Articles/759423/ could be implemented on top of
23// the current design.
24//
25// For AArch64, the following implementation choices are made to implement the
26// tracking of control flow miss-speculation into a taint register:
27// Some of these are different than the implementation choices made in
28// the similar pass implemented in X86SpeculativeLoadHardening.cpp, as
29// the instruction set characteristics result in different trade-offs.
30// - The speculation hardening is done after register allocation. With a
31// relative abundance of registers, one register is reserved (X16) to be
32// the taint register. X16 is expected to not clash with other register
33// reservation mechanisms with very high probability because:
34// . The AArch64 ABI doesn't guarantee X16 to be retained across any call.
35// . The only way to request X16 to be used as a programmer is through
36// inline assembly. In the rare case a function explicitly demands to
37// use X16/W16, this pass falls back to hardening against speculation
38// by inserting a DSB SYS/ISB barrier pair which will prevent control
39// flow speculation.
40// - It is easy to insert mask operations at this late stage as we have
41// mask operations available that don't set flags.
42// - The taint variable contains all-ones when no miss-speculation is detected,
43// and contains all-zeros when miss-speculation is detected. Therefore, when
44// masking, an AND instruction (which only changes the register to be masked,
45// no other side effects) can easily be inserted anywhere that's needed.
46// - The tracking of miss-speculation is done by using a data-flow conditional
47// select instruction (CSEL) to evaluate the flags that were also used to
48// make conditional branch direction decisions. Speculation of the CSEL
49// instruction can be limited with a CSDB instruction - so the combination of
50// CSEL + a later CSDB gives the guarantee that the flags as used in the CSEL
51// aren't speculated. When conditional branch direction gets miss-speculated,
52// the semantics of the inserted CSEL instruction is such that the taint
53// register will contain all zero bits.
54// One key requirement for this to work is that the conditional branch is
55// followed by an execution of the CSEL instruction, where the CSEL
56// instruction needs to use the same flags status as the conditional branch.
57// This means that the conditional branches must not be implemented as one
58// of the AArch64 conditional branches that do not use the flags as input
59// (CB(N)Z and TB(N)Z). This is implemented by ensuring in the instruction
60// selectors to not produce these instructions when speculation hardening
61// is enabled. This pass will assert if it does encounter such an instruction.
62// - On function call boundaries, the miss-speculation state is transferred from
63// the taint register X16 to be encoded in the SP register as value 0.
64//
65// For the aspect of automatically hardening loads, using the taint register,
66// (a.k.a. speculative load hardening, see
67// https://llvm.org/docs/SpeculativeLoadHardening.html), the following
68// implementation choices are made for AArch64:
69// - Many of the optimizations described at
70// https://llvm.org/docs/SpeculativeLoadHardening.html to harden fewer
71// loads haven't been implemented yet - but for some of them there are
72// FIXMEs in the code.
73// - loads that load into general purpose (X or W) registers get hardened by
74// masking the loaded data. For loads that load into other registers, the
75// address loaded from gets hardened. It is expected that hardening the
76// loaded data may be more efficient; but masking data in registers other
77// than X or W is not easy and may result in being slower than just
78// hardening the X address register loaded from.
79// - On AArch64, CSDB instructions are inserted between the masking of the
80// register and its first use, to ensure there's no non-control-flow
81// speculation that might undermine the hardening mechanism.
82//
83// Future extensions/improvements could be:
84// - Implement this functionality using full speculation barriers, akin to the
85// x86-slh-lfence option. This may be more useful for the intrinsics-based
86// approach than for the SLH approach to masking.
87// Note that this pass already inserts the full speculation barriers if the
88// function for some niche reason makes use of X16/W16.
89// - no indirect branch misprediction gets protected/instrumented; but this
90// could be done for some indirect branches, such as switch jump tables.
91//===----------------------------------------------------------------------===//
92
93#include "AArch64Subtarget.h"
95#include "llvm/ADT/BitVector.h"
104#include "llvm/IR/DebugLoc.h"
105#include "llvm/Pass.h"
106#include "llvm/Support/Debug.h"
108#include <cassert>
109
110using namespace llvm;
111
112#define DEBUG_TYPE "aarch64-speculation-hardening"
113
114#define AARCH64_SPECULATION_HARDENING_NAME "AArch64 speculation hardening pass"
115
116namespace {
117
118class AArch64SpeculationHardening : public MachineFunctionPass {
119public:
120 const TargetInstrInfo *TII;
121 const TargetRegisterInfo *TRI;
122
123 static char ID;
124
125 AArch64SpeculationHardening() : MachineFunctionPass(ID) {}
126
127 bool runOnMachineFunction(MachineFunction &Fn) override;
128
129 void getAnalysisUsage(AnalysisUsage &AU) const override {
132 }
133
134 StringRef getPassName() const override {
136 }
137
138private:
139 unsigned MisspeculatingTaintReg;
140 unsigned MisspeculatingTaintReg32Bit;
141 bool UseControlFlowSpeculationBarrier;
142 BitVector RegsNeedingCSDBBeforeUse;
143 BitVector RegsAlreadyMasked;
144
145 bool functionUsesHardeningRegister(MachineFunction &MF) const;
146 bool instrumentControlFlow(MachineBasicBlock &MBB,
147 bool &UsesFullSpeculationBarrier);
148 bool endsWithCondControlFlow(MachineBasicBlock &MBB, MachineBasicBlock *&TBB,
149 MachineBasicBlock *&FBB,
150 AArch64CC::CondCode &CondCode) const;
151 void insertTrackingCode(MachineBasicBlock &SplitEdgeBB,
152 AArch64CC::CondCode &CondCode, DebugLoc DL) const;
153 void insertSPToRegTaintPropagation(MachineBasicBlock &MBB,
155 void insertRegToSPTaintPropagation(MachineBasicBlock &MBB,
157 unsigned TmpReg) const;
158 void insertFullSpeculationBarrier(MachineBasicBlock &MBB,
160 DebugLoc DL) const;
161
162 bool slhLoads(MachineBasicBlock &MBB);
163 bool makeGPRSpeculationSafe(MachineBasicBlock &MBB,
165 MachineInstr &MI, unsigned Reg);
166 bool lowerSpeculationSafeValuePseudos(MachineBasicBlock &MBB,
167 bool UsesFullSpeculationBarrier);
168 bool expandSpeculationSafeValue(MachineBasicBlock &MBB,
170 bool UsesFullSpeculationBarrier);
172 DebugLoc DL);
173};
174
175} // end anonymous namespace
176
177char AArch64SpeculationHardening::ID = 0;
178
179INITIALIZE_PASS(AArch64SpeculationHardening, "aarch64-speculation-hardening",
181
182bool AArch64SpeculationHardening::endsWithCondControlFlow(
184 AArch64CC::CondCode &CondCode) const {
185 SmallVector<MachineOperand, 1> analyzeBranchCondCode;
186 if (TII->analyzeBranch(MBB, TBB, FBB, analyzeBranchCondCode, false))
187 return false;
188
189 // Ignore if the BB ends in an unconditional branch/fall-through.
190 if (analyzeBranchCondCode.empty())
191 return false;
192
193 // If the BB ends with a single conditional branch, FBB will be set to
194 // nullptr (see API docs for TII->analyzeBranch). For the rest of the
195 // analysis we want the FBB block to be set always.
196 assert(TBB != nullptr);
197 if (FBB == nullptr)
198 FBB = MBB.getFallThrough();
199
200 // If both the true and the false condition jump to the same basic block,
201 // there isn't need for any protection - whether the branch is speculated
202 // correctly or not, we end up executing the architecturally correct code.
203 if (TBB == FBB)
204 return false;
205
206 assert(MBB.succ_size() == 2);
207 // translate analyzeBranchCondCode to CondCode.
208 assert(analyzeBranchCondCode.size() == 1 && "unknown Cond array format");
209 CondCode = AArch64CC::CondCode(analyzeBranchCondCode[0].getImm());
210 return true;
211}
212
213void AArch64SpeculationHardening::insertFullSpeculationBarrier(
215 DebugLoc DL) const {
216 // A full control flow speculation barrier consists of (DSB SYS + ISB)
217 BuildMI(MBB, MBBI, DL, TII->get(AArch64::DSB)).addImm(0xf);
218 BuildMI(MBB, MBBI, DL, TII->get(AArch64::ISB)).addImm(0xf);
219}
220
221void AArch64SpeculationHardening::insertTrackingCode(
222 MachineBasicBlock &SplitEdgeBB, AArch64CC::CondCode &CondCode,
223 DebugLoc DL) const {
224 if (UseControlFlowSpeculationBarrier) {
225 insertFullSpeculationBarrier(SplitEdgeBB, SplitEdgeBB.begin(), DL);
226 } else {
227 BuildMI(SplitEdgeBB, SplitEdgeBB.begin(), DL, TII->get(AArch64::CSELXr))
228 .addDef(MisspeculatingTaintReg)
229 .addUse(MisspeculatingTaintReg)
230 .addUse(AArch64::XZR)
231 .addImm(CondCode);
232 SplitEdgeBB.addLiveIn(AArch64::NZCV);
233 }
234}
235
236bool AArch64SpeculationHardening::instrumentControlFlow(
237 MachineBasicBlock &MBB, bool &UsesFullSpeculationBarrier) {
238 LLVM_DEBUG(dbgs() << "Instrument control flow tracking on MBB: " << MBB);
239
240 bool Modified = false;
241 MachineBasicBlock *TBB = nullptr;
242 MachineBasicBlock *FBB = nullptr;
244
245 if (!endsWithCondControlFlow(MBB, TBB, FBB, CondCode)) {
246 LLVM_DEBUG(dbgs() << "... doesn't end with CondControlFlow\n");
247 } else {
248 // Now insert:
249 // "CSEL MisSpeculatingR, MisSpeculatingR, XZR, cond" on the True edge and
250 // "CSEL MisSpeculatingR, MisSpeculatingR, XZR, Invertcond" on the False
251 // edge.
253
254 MachineBasicBlock *SplitEdgeTBB = MBB.SplitCriticalEdge(TBB, *this);
255 MachineBasicBlock *SplitEdgeFBB = MBB.SplitCriticalEdge(FBB, *this);
256
257 assert(SplitEdgeTBB != nullptr);
258 assert(SplitEdgeFBB != nullptr);
259
260 DebugLoc DL;
261 if (MBB.instr_end() != MBB.instr_begin())
262 DL = (--MBB.instr_end())->getDebugLoc();
263
264 insertTrackingCode(*SplitEdgeTBB, CondCode, DL);
265 insertTrackingCode(*SplitEdgeFBB, InvCondCode, DL);
266
267 LLVM_DEBUG(dbgs() << "SplitEdgeTBB: " << *SplitEdgeTBB << "\n");
268 LLVM_DEBUG(dbgs() << "SplitEdgeFBB: " << *SplitEdgeFBB << "\n");
269 Modified = true;
270 }
271
272 // Perform correct code generation around function calls and before returns.
273 // The below variables record the return/terminator instructions and the call
274 // instructions respectively; including which register is available as a
275 // temporary register just before the recorded instructions.
278 // if a temporary register is not available for at least one of the
279 // instructions for which we need to transfer taint to the stack pointer, we
280 // need to insert a full speculation barrier.
281 // TmpRegisterNotAvailableEverywhere tracks that condition.
282 bool TmpRegisterNotAvailableEverywhere = false;
283
284 RegScavenger RS;
285 RS.enterBasicBlockEnd(MBB);
286
287 for (MachineBasicBlock::iterator I = MBB.end(); I != MBB.begin(); ) {
288 MachineInstr &MI = *--I;
289 if (!MI.isReturn() && !MI.isCall())
290 continue;
291
292 // The RegScavenger represents registers available *after* the MI
293 // instruction pointed to by RS.getCurrentPosition().
294 // We need to have a register that is available *before* the MI is executed.
295 if (I == MBB.begin())
296 RS.enterBasicBlock(MBB);
297 else
298 RS.backward(I);
299 // FIXME: The below just finds *a* unused register. Maybe code could be
300 // optimized more if this looks for the register that isn't used for the
301 // longest time around this place, to enable more scheduling freedom. Not
302 // sure if that would actually result in a big performance difference
303 // though. Maybe RegisterScavenger::findSurvivorBackwards has some logic
304 // already to do this - but it's unclear if that could easily be used here.
305 Register TmpReg = RS.FindUnusedReg(&AArch64::GPR64commonRegClass);
306 LLVM_DEBUG(dbgs() << "RS finds "
307 << ((TmpReg == 0) ? "no register " : "register ");
308 if (TmpReg != 0) dbgs() << printReg(TmpReg, TRI) << " ";
309 dbgs() << "to be available at MI " << MI);
310 if (TmpReg == 0)
311 TmpRegisterNotAvailableEverywhere = true;
312 if (MI.isReturn())
313 ReturnInstructions.push_back({&MI, TmpReg});
314 else if (MI.isCall())
315 CallInstructions.push_back({&MI, TmpReg});
316 }
317
318 if (TmpRegisterNotAvailableEverywhere) {
319 // When a temporary register is not available everywhere in this basic
320 // basic block where a propagate-taint-to-sp operation is needed, just
321 // emit a full speculation barrier at the start of this basic block, which
322 // renders the taint/speculation tracking in this basic block unnecessary.
323 insertFullSpeculationBarrier(MBB, MBB.begin(),
324 (MBB.begin())->getDebugLoc());
325 UsesFullSpeculationBarrier = true;
326 Modified = true;
327 } else {
328 for (auto MI_Reg : ReturnInstructions) {
329 assert(MI_Reg.second != 0);
331 dbgs()
332 << " About to insert Reg to SP taint propagation with temp register "
333 << printReg(MI_Reg.second, TRI)
334 << " on instruction: " << *MI_Reg.first);
335 insertRegToSPTaintPropagation(MBB, MI_Reg.first, MI_Reg.second);
336 Modified = true;
337 }
338
339 for (auto MI_Reg : CallInstructions) {
340 assert(MI_Reg.second != 0);
341 LLVM_DEBUG(dbgs() << " About to insert Reg to SP and back taint "
342 "propagation with temp register "
343 << printReg(MI_Reg.second, TRI)
344 << " around instruction: " << *MI_Reg.first);
345 // Just after the call:
346 insertSPToRegTaintPropagation(
347 MBB, std::next((MachineBasicBlock::iterator)MI_Reg.first));
348 // Just before the call:
349 insertRegToSPTaintPropagation(MBB, MI_Reg.first, MI_Reg.second);
350 Modified = true;
351 }
352 }
353 return Modified;
354}
355
356void AArch64SpeculationHardening::insertSPToRegTaintPropagation(
357 MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI) const {
358 // If full control flow speculation barriers are used, emit a control flow
359 // barrier to block potential miss-speculation in flight coming in to this
360 // function.
361 if (UseControlFlowSpeculationBarrier) {
362 insertFullSpeculationBarrier(MBB, MBBI, DebugLoc());
363 return;
364 }
365
366 // CMP SP, #0 === SUBS xzr, SP, #0
367 BuildMI(MBB, MBBI, DebugLoc(), TII->get(AArch64::SUBSXri))
368 .addDef(AArch64::XZR)
369 .addUse(AArch64::SP)
370 .addImm(0)
371 .addImm(0); // no shift
372 // CSETM x16, NE === CSINV x16, xzr, xzr, EQ
373 BuildMI(MBB, MBBI, DebugLoc(), TII->get(AArch64::CSINVXr))
374 .addDef(MisspeculatingTaintReg)
375 .addUse(AArch64::XZR)
376 .addUse(AArch64::XZR)
378}
379
380void AArch64SpeculationHardening::insertRegToSPTaintPropagation(
381 MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
382 unsigned TmpReg) const {
383 // If full control flow speculation barriers are used, there will not be
384 // miss-speculation when returning from this function, and therefore, also
385 // no need to encode potential miss-speculation into the stack pointer.
386 if (UseControlFlowSpeculationBarrier)
387 return;
388
389 // mov Xtmp, SP === ADD Xtmp, SP, #0
390 BuildMI(MBB, MBBI, DebugLoc(), TII->get(AArch64::ADDXri))
391 .addDef(TmpReg)
392 .addUse(AArch64::SP)
393 .addImm(0)
394 .addImm(0); // no shift
395 // and Xtmp, Xtmp, TaintReg === AND Xtmp, Xtmp, TaintReg, #0
396 BuildMI(MBB, MBBI, DebugLoc(), TII->get(AArch64::ANDXrs))
397 .addDef(TmpReg, RegState::Renamable)
398 .addUse(TmpReg, RegState::Kill | RegState::Renamable)
399 .addUse(MisspeculatingTaintReg, RegState::Kill)
400 .addImm(0);
401 // mov SP, Xtmp === ADD SP, Xtmp, #0
402 BuildMI(MBB, MBBI, DebugLoc(), TII->get(AArch64::ADDXri))
403 .addDef(AArch64::SP)
404 .addUse(TmpReg, RegState::Kill)
405 .addImm(0)
406 .addImm(0); // no shift
407}
408
409bool AArch64SpeculationHardening::functionUsesHardeningRegister(
410 MachineFunction &MF) const {
411 for (MachineBasicBlock &MBB : MF) {
412 for (MachineInstr &MI : MBB) {
413 // treat function calls specially, as the hardening register does not
414 // need to remain live across function calls.
415 if (MI.isCall())
416 continue;
417 if (MI.readsRegister(MisspeculatingTaintReg, TRI) ||
418 MI.modifiesRegister(MisspeculatingTaintReg, TRI))
419 return true;
420 }
421 }
422 return false;
423}
424
425// Make GPR register Reg speculation-safe by putting it through the
426// SpeculationSafeValue pseudo instruction, if we can't prove that
427// the value in the register has already been hardened.
428bool AArch64SpeculationHardening::makeGPRSpeculationSafe(
429 MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, MachineInstr &MI,
430 unsigned Reg) {
431 assert(AArch64::GPR32allRegClass.contains(Reg) ||
432 AArch64::GPR64allRegClass.contains(Reg));
433
434 // Loads cannot directly load a value into the SP (nor WSP).
435 // Therefore, if Reg is SP or WSP, it is because the instruction loads from
436 // the stack through the stack pointer.
437 //
438 // Since the stack pointer is never dynamically controllable, don't harden it.
439 if (Reg == AArch64::SP || Reg == AArch64::WSP)
440 return false;
441
442 // Do not harden the register again if already hardened before.
443 if (RegsAlreadyMasked[Reg])
444 return false;
445
446 const bool Is64Bit = AArch64::GPR64allRegClass.contains(Reg);
447 LLVM_DEBUG(dbgs() << "About to harden register : " << Reg << "\n");
448 BuildMI(MBB, MBBI, MI.getDebugLoc(),
449 TII->get(Is64Bit ? AArch64::SpeculationSafeValueX
450 : AArch64::SpeculationSafeValueW))
451 .addDef(Reg)
452 .addUse(Reg);
453 RegsAlreadyMasked.set(Reg);
454 return true;
455}
456
457bool AArch64SpeculationHardening::slhLoads(MachineBasicBlock &MBB) {
458 bool Modified = false;
459
460 LLVM_DEBUG(dbgs() << "slhLoads running on MBB: " << MBB);
461
462 RegsAlreadyMasked.reset();
463
466 for (; MBBI != E; MBBI = NextMBBI) {
467 MachineInstr &MI = *MBBI;
468 NextMBBI = std::next(MBBI);
469 // Only harden loaded values or addresses used in loads.
470 if (!MI.mayLoad())
471 continue;
472
473 LLVM_DEBUG(dbgs() << "About to harden: " << MI);
474
475 // For general purpose register loads, harden the registers loaded into.
476 // For other loads, harden the address loaded from.
477 // Masking the loaded value is expected to result in less performance
478 // overhead, as the load can still execute speculatively in comparison to
479 // when the address loaded from gets masked. However, masking is only
480 // easy to do efficiently on GPR registers, so for loads into non-GPR
481 // registers (e.g. floating point loads), mask the address loaded from.
482 bool AllDefsAreGPR = llvm::all_of(MI.defs(), [&](MachineOperand &Op) {
483 return Op.isReg() && (AArch64::GPR32allRegClass.contains(Op.getReg()) ||
484 AArch64::GPR64allRegClass.contains(Op.getReg()));
485 });
486 // FIXME: it might be a worthwhile optimization to not mask loaded
487 // values if all the registers involved in address calculation are already
488 // hardened, leading to this load not able to execute on a miss-speculated
489 // path.
490 bool HardenLoadedData = AllDefsAreGPR;
491 bool HardenAddressLoadedFrom = !HardenLoadedData;
492
493 // First remove registers from AlreadyMaskedRegisters if their value is
494 // updated by this instruction - it makes them contain a new value that is
495 // not guaranteed to already have been masked.
496 for (MachineOperand Op : MI.defs())
497 for (MCRegAliasIterator AI(Op.getReg(), TRI, true); AI.isValid(); ++AI)
498 RegsAlreadyMasked.reset(*AI);
499
500 // FIXME: loads from the stack with an immediate offset from the stack
501 // pointer probably shouldn't be hardened, which could result in a
502 // significant optimization. See section "Don’t check loads from
503 // compile-time constant stack offsets", in
504 // https://llvm.org/docs/SpeculativeLoadHardening.html
505
506 if (HardenLoadedData)
507 for (auto Def : MI.defs()) {
508 if (Def.isDead())
509 // Do not mask a register that is not used further.
510 continue;
511 // FIXME: For pre/post-increment addressing modes, the base register
512 // used in address calculation is also defined by this instruction.
513 // It might be a worthwhile optimization to not harden that
514 // base register increment/decrement when the increment/decrement is
515 // an immediate.
516 Modified |= makeGPRSpeculationSafe(MBB, NextMBBI, MI, Def.getReg());
517 }
518
519 if (HardenAddressLoadedFrom)
520 for (auto Use : MI.uses()) {
521 if (!Use.isReg())
522 continue;
523 Register Reg = Use.getReg();
524 // Some loads of floating point data have implicit defs/uses on a
525 // super register of that floating point data. Some examples:
526 // $s0 = LDRSui $sp, 22, implicit-def $q0
527 // $q0 = LD1i64 $q0, 1, renamable $x0
528 // We need to filter out these uses for non-GPR register which occur
529 // because the load partially fills a non-GPR register with the loaded
530 // data. Just skipping all non-GPR registers is safe (for now) as all
531 // AArch64 load instructions only use GPR registers to perform the
532 // address calculation. FIXME: However that might change once we can
533 // produce SVE gather instructions.
534 if (!(AArch64::GPR32allRegClass.contains(Reg) ||
535 AArch64::GPR64allRegClass.contains(Reg)))
536 continue;
537 Modified |= makeGPRSpeculationSafe(MBB, MBBI, MI, Reg);
538 }
539 }
540 return Modified;
541}
542
543/// \brief If MBBI references a pseudo instruction that should be expanded
544/// here, do the expansion and return true. Otherwise return false.
545bool AArch64SpeculationHardening::expandSpeculationSafeValue(
546 MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
547 bool UsesFullSpeculationBarrier) {
548 MachineInstr &MI = *MBBI;
549 unsigned Opcode = MI.getOpcode();
550 bool Is64Bit = true;
551
552 switch (Opcode) {
553 default:
554 break;
555 case AArch64::SpeculationSafeValueW:
556 Is64Bit = false;
557 [[fallthrough]];
558 case AArch64::SpeculationSafeValueX:
559 // Just remove the SpeculationSafe pseudo's if control flow
560 // miss-speculation isn't happening because we're already inserting barriers
561 // to guarantee that.
562 if (!UseControlFlowSpeculationBarrier && !UsesFullSpeculationBarrier) {
563 Register DstReg = MI.getOperand(0).getReg();
564 Register SrcReg = MI.getOperand(1).getReg();
565 // Mark this register and all its aliasing registers as needing to be
566 // value speculation hardened before its next use, by using a CSDB
567 // barrier instruction.
568 for (MachineOperand Op : MI.defs())
569 for (MCRegAliasIterator AI(Op.getReg(), TRI, true); AI.isValid(); ++AI)
570 RegsNeedingCSDBBeforeUse.set(*AI);
571
572 // Mask off with taint state.
573 BuildMI(MBB, MBBI, MI.getDebugLoc(),
574 Is64Bit ? TII->get(AArch64::ANDXrs) : TII->get(AArch64::ANDWrs))
575 .addDef(DstReg)
576 .addUse(SrcReg, RegState::Kill)
577 .addUse(Is64Bit ? MisspeculatingTaintReg
578 : MisspeculatingTaintReg32Bit)
579 .addImm(0);
580 }
581 MI.eraseFromParent();
582 return true;
583 }
584 return false;
585}
586
587bool AArch64SpeculationHardening::insertCSDB(MachineBasicBlock &MBB,
589 DebugLoc DL) {
590 assert(!UseControlFlowSpeculationBarrier && "No need to insert CSDBs when "
591 "control flow miss-speculation "
592 "is already blocked");
593 // insert data value speculation barrier (CSDB)
594 BuildMI(MBB, MBBI, DL, TII->get(AArch64::HINT)).addImm(0x14);
595 RegsNeedingCSDBBeforeUse.reset();
596 return true;
597}
598
599bool AArch64SpeculationHardening::lowerSpeculationSafeValuePseudos(
600 MachineBasicBlock &MBB, bool UsesFullSpeculationBarrier) {
601 bool Modified = false;
602
603 RegsNeedingCSDBBeforeUse.reset();
604
605 // The following loop iterates over all instructions in the basic block,
606 // and performs 2 operations:
607 // 1. Insert a CSDB at this location if needed.
608 // 2. Expand the SpeculationSafeValuePseudo if the current instruction is
609 // one.
610 //
611 // The insertion of the CSDB is done as late as possible (i.e. just before
612 // the use of a masked register), in the hope that that will reduce the
613 // total number of CSDBs in a block when there are multiple masked registers
614 // in the block.
616 DebugLoc DL;
617 while (MBBI != E) {
618 MachineInstr &MI = *MBBI;
619 DL = MI.getDebugLoc();
620 MachineBasicBlock::iterator NMBBI = std::next(MBBI);
621
622 // First check if a CSDB needs to be inserted due to earlier registers
623 // that were masked and that are used by the next instruction.
624 // Also emit the barrier on any potential control flow changes.
625 bool NeedToEmitBarrier = false;
626 if (RegsNeedingCSDBBeforeUse.any() && (MI.isCall() || MI.isTerminator()))
627 NeedToEmitBarrier = true;
628 if (!NeedToEmitBarrier)
629 for (MachineOperand Op : MI.uses())
630 if (Op.isReg() && RegsNeedingCSDBBeforeUse[Op.getReg()]) {
631 NeedToEmitBarrier = true;
632 break;
633 }
634
635 if (NeedToEmitBarrier && !UsesFullSpeculationBarrier)
636 Modified |= insertCSDB(MBB, MBBI, DL);
637
638 Modified |=
639 expandSpeculationSafeValue(MBB, MBBI, UsesFullSpeculationBarrier);
640
641 MBBI = NMBBI;
642 }
643
644 if (RegsNeedingCSDBBeforeUse.any() && !UsesFullSpeculationBarrier)
645 Modified |= insertCSDB(MBB, MBBI, DL);
646
647 return Modified;
648}
649
650bool AArch64SpeculationHardening::runOnMachineFunction(MachineFunction &MF) {
651 if (!MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening))
652 return false;
653
654 MisspeculatingTaintReg = AArch64::X16;
655 MisspeculatingTaintReg32Bit = AArch64::W16;
658 RegsNeedingCSDBBeforeUse.resize(TRI->getNumRegs());
659 RegsAlreadyMasked.resize(TRI->getNumRegs());
660 UseControlFlowSpeculationBarrier = functionUsesHardeningRegister(MF);
661
662 bool Modified = false;
663
664 // Step 1: Enable automatic insertion of SpeculationSafeValue.
665 if (MF.getSubtarget<AArch64Subtarget>().getCLOpts().slh_loads) {
667 dbgs() << "***** AArch64SpeculationHardening - automatic insertion of "
668 "SpeculationSafeValue intrinsics *****\n");
669 for (auto &MBB : MF)
670 Modified |= slhLoads(MBB);
671 }
672
673 // 2. Add instrumentation code to function entry and exits.
675 dbgs()
676 << "***** AArch64SpeculationHardening - track control flow *****\n");
677
679 EntryBlocks.push_back(&MF.front());
680 for (const LandingPadInfo &LPI : MF.getLandingPads())
681 EntryBlocks.push_back(LPI.LandingPadBlock);
682 for (auto *Entry : EntryBlocks)
683 insertSPToRegTaintPropagation(
684 *Entry, Entry->SkipPHIsLabelsAndDebug(Entry->begin()));
685
686 // 3. Add instrumentation code to every basic block.
687 for (auto &MBB : MF) {
688 bool UsesFullSpeculationBarrier = false;
689 Modified |= instrumentControlFlow(MBB, UsesFullSpeculationBarrier);
690 Modified |=
691 lowerSpeculationSafeValuePseudos(MBB, UsesFullSpeculationBarrier);
692 }
693
694 return Modified;
695}
696
697/// \brief Returns an instance of the pseudo instruction expansion pass.
699 return new AArch64SpeculationHardening();
700}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
#define AARCH64_SPECULATION_HARDENING_NAME
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
MachineBasicBlock MachineBasicBlock::iterator MBBI
This file implements the BitVector class.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
if(PassOpts->AAPipeline)
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
const SmallVectorImpl< MachineOperand > MachineBasicBlock * TBB
This file declares the machine register scavenger class.
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
Definition Value.cpp:480
This file defines the SmallVector class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
Represent the analysis usage information of a pass.
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
BitVector & reset()
Reset all bits in the bitvector.
Definition BitVector.h:409
void resize(unsigned N, bool t=false)
Grow or shrink the bitvector.
Definition BitVector.h:355
BitVector & set()
Set all bits in the bitvector.
Definition BitVector.h:366
bool any() const
Returns true if any bit is set.
Definition BitVector.h:189
A debug info location.
Definition DebugLoc.h:126
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition Function.cpp:731
void addLiveIn(MCRegister PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
MachineBasicBlock * SplitCriticalEdge(MachineBasicBlock *Succ, Pass &P, MachineDomTreeUpdater *MDTU=nullptr)
MachineInstrBundleIterator< MachineInstr > iterator
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
Function & getFunction()
Return the LLVM function that this machine code represents.
const std::vector< LandingPadInfo > & getLandingPads() const
Return a reference to the landing pad info for the current function.
const MachineBasicBlock & front() const
const MachineInstrBuilder & addUse(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a virtual register use operand.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & addDef(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a virtual register definition operand.
Representation of each machine instruction.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
TargetInstrInfo - Interface to description of machine instruction set.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual const TargetInstrInfo * getInstrInfo() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
static CondCode getInvertedCondCode(CondCode Code)
@ Entry
Definition COFF.h:862
CondCode
ISD::CondCode enum - These are ordered carefully to make the bitfields below work out,...
NodeAddr< DefNode * > Def
Definition RDFGraph.h:384
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
This is an optimization pass for GlobalISel generic memory operations.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
MachineInstr * getImm(const MachineOperand &MO, const MachineRegisterInfo *MRI)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
DWARFExpression::Operation Op
FunctionPass * createAArch64SpeculationHardeningPass()
Returns an instance of the pseudo instruction expansion pass.
LLVM_ABI Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.