LLVM 23.0.0git
X86SpeculativeExecutionSideEffectSuppression.cpp
Go to the documentation of this file.
1//===-- X86SpeculativeExecutionSideEffectSuppression.cpp ------------------===//
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/// \file
9///
10/// This file contains the X86 implementation of the speculative execution side
11/// effect suppression mitigation.
12///
13/// This must be used with the -mlvi-cfi flag in order to mitigate indirect
14/// branches and returns.
15//===----------------------------------------------------------------------===//
16
17#include "X86.h"
18#include "X86InstrInfo.h"
19#include "X86Subtarget.h"
20#include "llvm/ADT/Statistic.h"
24#include "llvm/Pass.h"
26using namespace llvm;
27
28#define DEBUG_TYPE "x86-seses"
29
30STATISTIC(NumLFENCEsInserted, "Number of lfence instructions inserted");
31
33 "x86-seses-enable-without-lvi-cfi",
34 cl::desc("Force enable speculative execution side effect suppression. "
35 "(Note: User must pass -mlvi-cfi in order to mitigate indirect "
36 "branches and returns.)"),
37 cl::init(false), cl::Hidden);
38
40 "x86-seses-one-lfence-per-bb",
42 "Omit all lfences other than the first to be placed in a basic block."),
43 cl::init(false), cl::Hidden);
44
46 "x86-seses-only-lfence-non-const",
47 cl::desc("Only lfence before groups of terminators where at least one "
48 "branch instruction has an input to the addressing mode that is a "
49 "register other than %rip."),
50 cl::init(false), cl::Hidden);
51
52static cl::opt<bool>
53 OmitBranchLFENCEs("x86-seses-omit-branch-lfences",
54 cl::desc("Omit all lfences before branch instructions."),
55 cl::init(false), cl::Hidden);
56
57namespace {
58
59constexpr StringRef X86SESESPassName =
60 "X86 Speculative Execution Side Effect Suppression";
61
62class X86SpeculativeExecutionSideEffectSuppressionLegacy
63 : public MachineFunctionPass {
64public:
65 X86SpeculativeExecutionSideEffectSuppressionLegacy()
67
68 static char ID;
69 StringRef getPassName() const override { return X86SESESPassName; }
70
71 bool runOnMachineFunction(MachineFunction &MF) override;
72};
73} // namespace
74
75char X86SpeculativeExecutionSideEffectSuppressionLegacy::ID = 0;
76
77// This function returns whether the passed instruction uses a memory addressing
78// mode that is constant. We treat all memory addressing modes that read
79// from a register that is not %rip as non-constant. Note that the use
80// of the EFLAGS register results in an addressing mode being considered
81// non-constant, therefore all JCC instructions will return false from this
82// function since one of their operands will always be the EFLAGS register.
84 for (const MachineOperand &MO : MI.uses())
85 if (MO.isReg() && X86::RIP != MO.getReg())
86 return false;
87 return true;
88}
89
90static bool
92
93 const auto &OptLevel = MF.getTarget().getOptLevel();
94 const X86Subtarget &Subtarget = MF.getSubtarget<X86Subtarget>();
95
96 // Check whether SESES needs to run as the fallback for LVI at O0, whether the
97 // user explicitly passed an SESES flag, or whether the SESES target feature
98 // was set.
100 !(Subtarget.useLVILoadHardening() && OptLevel == CodeGenOptLevel::None) &&
101 !Subtarget.useSpeculativeExecutionSideEffectSuppression())
102 return false;
103
104 LLVM_DEBUG(dbgs() << "********** " << X86SESESPassName << " : "
105 << MF.getName() << " **********\n");
106 bool Modified = false;
107 const X86InstrInfo *TII = Subtarget.getInstrInfo();
108 for (MachineBasicBlock &MBB : MF) {
109 MachineInstr *FirstTerminator = nullptr;
110 // Keep track of whether the previous instruction was an LFENCE to avoid
111 // adding redundant LFENCEs.
112 bool PrevInstIsLFENCE = false;
113 for (auto &MI : MBB) {
114
115 if (MI.getOpcode() == X86::LFENCE) {
116 PrevInstIsLFENCE = true;
117 continue;
118 }
119 // We want to put an LFENCE before any instruction that
120 // may load or store. This LFENCE is intended to avoid leaking any secret
121 // data due to a given load or store. This results in closing the cache
122 // and memory timing side channels. We will treat terminators that load
123 // or store separately.
124 if (MI.mayLoadOrStore() && !MI.isTerminator()) {
125 if (!PrevInstIsLFENCE) {
126 BuildMI(MBB, MI, DebugLoc(), TII->get(X86::LFENCE));
127 NumLFENCEsInserted++;
128 Modified = true;
129 }
131 break;
132 }
133 // The following section will be LFENCEing before groups of terminators
134 // that include branches. This will close the branch prediction side
135 // channels since we will prevent code executing after misspeculation as
136 // a result of the LFENCEs placed with this logic.
137
138 // Keep track of the first terminator in a basic block since if we need
139 // to LFENCE the terminators in this basic block we must add the
140 // instruction before the first terminator in the basic block (as
141 // opposed to before the terminator that indicates an LFENCE is
142 // required). An example of why this is necessary is that the
143 // X86InstrInfo::analyzeBranch method assumes all terminators are grouped
144 // together and terminates it's analysis once the first non-termintor
145 // instruction is found.
146 if (MI.isTerminator() && FirstTerminator == nullptr)
147 FirstTerminator = &MI;
148
149 // Look for branch instructions that will require an LFENCE to be put
150 // before this basic block's terminators.
151 if (!MI.isBranch() || OmitBranchLFENCEs) {
152 // This isn't a branch or we're not putting LFENCEs before branches.
153 PrevInstIsLFENCE = false;
154 continue;
155 }
156
158 // This is a branch, but it only has constant addressing mode and we're
159 // not adding LFENCEs before such branches.
160 PrevInstIsLFENCE = false;
161 continue;
162 }
163
164 // This branch requires adding an LFENCE.
165 if (!PrevInstIsLFENCE) {
166 assert(FirstTerminator && "Unknown terminator instruction");
167 BuildMI(MBB, FirstTerminator, DebugLoc(), TII->get(X86::LFENCE));
168 NumLFENCEsInserted++;
169 Modified = true;
170 }
171 break;
172 }
173 }
174
175 return Modified;
176}
177
178bool X86SpeculativeExecutionSideEffectSuppressionLegacy::runOnMachineFunction(
179 MachineFunction &MF) {
181}
182
190
193 return new X86SpeculativeExecutionSideEffectSuppressionLegacy();
194}
195
196INITIALIZE_PASS(X86SpeculativeExecutionSideEffectSuppressionLegacy, "x86-seses",
197 "X86 Speculative Execution Side Effect Suppression", false,
198 false)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:114
static cl::opt< bool > OmitBranchLFENCEs("x86-seses-omit-branch-lfences", cl::desc("Omit all lfences before branch instructions."), cl::init(false), cl::Hidden)
static bool runX86SpeculativeExecutionSideEffectSuppression(MachineFunction &MF)
static cl::opt< bool > OnlyLFENCENonConst("x86-seses-only-lfence-non-const", cl::desc("Only lfence before groups of terminators where at least one " "branch instruction has an input to the addressing mode that is a " "register other than %rip."), cl::init(false), cl::Hidden)
static cl::opt< bool > OneLFENCEPerBasicBlock("x86-seses-one-lfence-per-bb", cl::desc("Omit all lfences other than the first to be placed in a basic block."), cl::init(false), cl::Hidden)
static cl::opt< bool > EnableSpeculativeExecutionSideEffectSuppression("x86-seses-enable-without-lvi-cfi", cl::desc("Force enable speculative execution side effect suppression. " "(Note: User must pass -mlvi-cfi in order to mitigate indirect " "branches and returns.)"), cl::init(false), cl::Hidden)
static bool hasConstantAddressingMode(const MachineInstr &MI)
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
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.
const TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
Representation of each machine instruction.
MachineOperand class - Representation of each machine instruction operand.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:151
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
CodeGenOptLevel getOptLevel() const
Returns the optimization level: None, Less, Default, or Aggressive.
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
const X86InstrInfo * getInstrInfo() const override
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
FunctionPass * createX86SpeculativeExecutionSideEffectSuppressionLegacyPass()
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207