15ffd83dbSDimitry Andric //===-- X86SpeculativeExecutionSideEffectSuppression.cpp ------------------===//
25ffd83dbSDimitry Andric //
35ffd83dbSDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
45ffd83dbSDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
55ffd83dbSDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
65ffd83dbSDimitry Andric //
75ffd83dbSDimitry Andric //===----------------------------------------------------------------------===//
85ffd83dbSDimitry Andric /// \file
95ffd83dbSDimitry Andric ///
105ffd83dbSDimitry Andric /// This file contains the X86 implementation of the speculative execution side
115ffd83dbSDimitry Andric /// effect suppression mitigation.
125ffd83dbSDimitry Andric ///
135ffd83dbSDimitry Andric /// This must be used with the -mlvi-cfi flag in order to mitigate indirect
145ffd83dbSDimitry Andric /// branches and returns.
155ffd83dbSDimitry Andric //===----------------------------------------------------------------------===//
165ffd83dbSDimitry Andric 
175ffd83dbSDimitry Andric #include "X86.h"
185ffd83dbSDimitry Andric #include "X86InstrInfo.h"
195ffd83dbSDimitry Andric #include "X86Subtarget.h"
205ffd83dbSDimitry Andric #include "llvm/ADT/Statistic.h"
215ffd83dbSDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
225ffd83dbSDimitry Andric #include "llvm/CodeGen/MachineFunctionPass.h"
235ffd83dbSDimitry Andric #include "llvm/CodeGen/MachineInstrBuilder.h"
245ffd83dbSDimitry Andric #include "llvm/Pass.h"
255ffd83dbSDimitry Andric #include "llvm/Target/TargetMachine.h"
265ffd83dbSDimitry Andric using namespace llvm;
275ffd83dbSDimitry Andric 
285ffd83dbSDimitry Andric #define DEBUG_TYPE "x86-seses"
295ffd83dbSDimitry Andric 
305ffd83dbSDimitry Andric STATISTIC(NumLFENCEsInserted, "Number of lfence instructions inserted");
315ffd83dbSDimitry Andric 
325ffd83dbSDimitry Andric static cl::opt<bool> EnableSpeculativeExecutionSideEffectSuppression(
335ffd83dbSDimitry Andric     "x86-seses-enable-without-lvi-cfi",
345ffd83dbSDimitry Andric     cl::desc("Force enable speculative execution side effect suppression. "
355ffd83dbSDimitry Andric              "(Note: User must pass -mlvi-cfi in order to mitigate indirect "
365ffd83dbSDimitry Andric              "branches and returns.)"),
375ffd83dbSDimitry Andric     cl::init(false), cl::Hidden);
385ffd83dbSDimitry Andric 
395ffd83dbSDimitry Andric static cl::opt<bool> OneLFENCEPerBasicBlock(
405ffd83dbSDimitry Andric     "x86-seses-one-lfence-per-bb",
415ffd83dbSDimitry Andric     cl::desc(
425ffd83dbSDimitry Andric         "Omit all lfences other than the first to be placed in a basic block."),
435ffd83dbSDimitry Andric     cl::init(false), cl::Hidden);
445ffd83dbSDimitry Andric 
455ffd83dbSDimitry Andric static cl::opt<bool> OnlyLFENCENonConst(
465ffd83dbSDimitry Andric     "x86-seses-only-lfence-non-const",
475ffd83dbSDimitry Andric     cl::desc("Only lfence before groups of terminators where at least one "
485ffd83dbSDimitry Andric              "branch instruction has an input to the addressing mode that is a "
495ffd83dbSDimitry Andric              "register other than %rip."),
505ffd83dbSDimitry Andric     cl::init(false), cl::Hidden);
515ffd83dbSDimitry Andric 
525ffd83dbSDimitry Andric static cl::opt<bool>
535ffd83dbSDimitry Andric     OmitBranchLFENCEs("x86-seses-omit-branch-lfences",
545ffd83dbSDimitry Andric                       cl::desc("Omit all lfences before branch instructions."),
555ffd83dbSDimitry Andric                       cl::init(false), cl::Hidden);
565ffd83dbSDimitry Andric 
575ffd83dbSDimitry Andric namespace {
585ffd83dbSDimitry Andric 
595ffd83dbSDimitry Andric class X86SpeculativeExecutionSideEffectSuppression
605ffd83dbSDimitry Andric     : public MachineFunctionPass {
615ffd83dbSDimitry Andric public:
X86SpeculativeExecutionSideEffectSuppression()625ffd83dbSDimitry Andric   X86SpeculativeExecutionSideEffectSuppression() : MachineFunctionPass(ID) {}
635ffd83dbSDimitry Andric 
645ffd83dbSDimitry Andric   static char ID;
getPassName() const655ffd83dbSDimitry Andric   StringRef getPassName() const override {
665ffd83dbSDimitry Andric     return "X86 Speculative Execution Side Effect Suppression";
675ffd83dbSDimitry Andric   }
685ffd83dbSDimitry Andric 
695ffd83dbSDimitry Andric   bool runOnMachineFunction(MachineFunction &MF) override;
705ffd83dbSDimitry Andric };
715ffd83dbSDimitry Andric } // namespace
725ffd83dbSDimitry Andric 
735ffd83dbSDimitry Andric char X86SpeculativeExecutionSideEffectSuppression::ID = 0;
745ffd83dbSDimitry Andric 
755ffd83dbSDimitry Andric // This function returns whether the passed instruction uses a memory addressing
765ffd83dbSDimitry Andric // mode that is constant. We treat all memory addressing modes that read
775ffd83dbSDimitry Andric // from a register that is not %rip as non-constant. Note that the use
785ffd83dbSDimitry Andric // of the EFLAGS register results in an addressing mode being considered
795ffd83dbSDimitry Andric // non-constant, therefore all JCC instructions will return false from this
805ffd83dbSDimitry Andric // function since one of their operands will always be the EFLAGS register.
hasConstantAddressingMode(const MachineInstr & MI)815ffd83dbSDimitry Andric static bool hasConstantAddressingMode(const MachineInstr &MI) {
825ffd83dbSDimitry Andric   for (const MachineOperand &MO : MI.uses())
835ffd83dbSDimitry Andric     if (MO.isReg() && X86::RIP != MO.getReg())
845ffd83dbSDimitry Andric       return false;
855ffd83dbSDimitry Andric   return true;
865ffd83dbSDimitry Andric }
875ffd83dbSDimitry Andric 
runOnMachineFunction(MachineFunction & MF)885ffd83dbSDimitry Andric bool X86SpeculativeExecutionSideEffectSuppression::runOnMachineFunction(
895ffd83dbSDimitry Andric     MachineFunction &MF) {
905ffd83dbSDimitry Andric 
915ffd83dbSDimitry Andric   const auto &OptLevel = MF.getTarget().getOptLevel();
925ffd83dbSDimitry Andric   const X86Subtarget &Subtarget = MF.getSubtarget<X86Subtarget>();
935ffd83dbSDimitry Andric 
945ffd83dbSDimitry Andric   // Check whether SESES needs to run as the fallback for LVI at O0, whether the
955ffd83dbSDimitry Andric   // user explicitly passed an SESES flag, or whether the SESES target feature
965ffd83dbSDimitry Andric   // was set.
975ffd83dbSDimitry Andric   if (!EnableSpeculativeExecutionSideEffectSuppression &&
98*5f757f3fSDimitry Andric       !(Subtarget.useLVILoadHardening() && OptLevel == CodeGenOptLevel::None) &&
995ffd83dbSDimitry Andric       !Subtarget.useSpeculativeExecutionSideEffectSuppression())
1005ffd83dbSDimitry Andric     return false;
1015ffd83dbSDimitry Andric 
1025ffd83dbSDimitry Andric   LLVM_DEBUG(dbgs() << "********** " << getPassName() << " : " << MF.getName()
1035ffd83dbSDimitry Andric                     << " **********\n");
1045ffd83dbSDimitry Andric   bool Modified = false;
1055ffd83dbSDimitry Andric   const X86InstrInfo *TII = Subtarget.getInstrInfo();
1065ffd83dbSDimitry Andric   for (MachineBasicBlock &MBB : MF) {
1075ffd83dbSDimitry Andric     MachineInstr *FirstTerminator = nullptr;
1085ffd83dbSDimitry Andric     // Keep track of whether the previous instruction was an LFENCE to avoid
1095ffd83dbSDimitry Andric     // adding redundant LFENCEs.
1105ffd83dbSDimitry Andric     bool PrevInstIsLFENCE = false;
1115ffd83dbSDimitry Andric     for (auto &MI : MBB) {
1125ffd83dbSDimitry Andric 
1135ffd83dbSDimitry Andric       if (MI.getOpcode() == X86::LFENCE) {
1145ffd83dbSDimitry Andric         PrevInstIsLFENCE = true;
1155ffd83dbSDimitry Andric         continue;
1165ffd83dbSDimitry Andric       }
1175ffd83dbSDimitry Andric       // We want to put an LFENCE before any instruction that
1185ffd83dbSDimitry Andric       // may load or store. This LFENCE is intended to avoid leaking any secret
1195ffd83dbSDimitry Andric       // data due to a given load or store. This results in closing the cache
1205ffd83dbSDimitry Andric       // and memory timing side channels. We will treat terminators that load
1215ffd83dbSDimitry Andric       // or store separately.
1225ffd83dbSDimitry Andric       if (MI.mayLoadOrStore() && !MI.isTerminator()) {
1235ffd83dbSDimitry Andric         if (!PrevInstIsLFENCE) {
1245ffd83dbSDimitry Andric           BuildMI(MBB, MI, DebugLoc(), TII->get(X86::LFENCE));
1255ffd83dbSDimitry Andric           NumLFENCEsInserted++;
1265ffd83dbSDimitry Andric           Modified = true;
1275ffd83dbSDimitry Andric         }
1285ffd83dbSDimitry Andric         if (OneLFENCEPerBasicBlock)
1295ffd83dbSDimitry Andric           break;
1305ffd83dbSDimitry Andric       }
1315ffd83dbSDimitry Andric       // The following section will be LFENCEing before groups of terminators
1325ffd83dbSDimitry Andric       // that include branches. This will close the branch prediction side
1335ffd83dbSDimitry Andric       // channels since we will prevent code executing after misspeculation as
1345ffd83dbSDimitry Andric       // a result of the LFENCEs placed with this logic.
1355ffd83dbSDimitry Andric 
1365ffd83dbSDimitry Andric       // Keep track of the first terminator in a basic block since if we need
1375ffd83dbSDimitry Andric       // to LFENCE the terminators in this basic block we must add the
1385ffd83dbSDimitry Andric       // instruction before the first terminator in the basic block (as
1395ffd83dbSDimitry Andric       // opposed to before the terminator that indicates an LFENCE is
1405ffd83dbSDimitry Andric       // required). An example of why this is necessary is that the
1415ffd83dbSDimitry Andric       // X86InstrInfo::analyzeBranch method assumes all terminators are grouped
1425ffd83dbSDimitry Andric       // together and terminates it's analysis once the first non-termintor
1435ffd83dbSDimitry Andric       // instruction is found.
1445ffd83dbSDimitry Andric       if (MI.isTerminator() && FirstTerminator == nullptr)
1455ffd83dbSDimitry Andric         FirstTerminator = &MI;
1465ffd83dbSDimitry Andric 
1475ffd83dbSDimitry Andric       // Look for branch instructions that will require an LFENCE to be put
1485ffd83dbSDimitry Andric       // before this basic block's terminators.
1495ffd83dbSDimitry Andric       if (!MI.isBranch() || OmitBranchLFENCEs) {
1505ffd83dbSDimitry Andric         // This isn't a branch or we're not putting LFENCEs before branches.
1515ffd83dbSDimitry Andric         PrevInstIsLFENCE = false;
1525ffd83dbSDimitry Andric         continue;
1535ffd83dbSDimitry Andric       }
1545ffd83dbSDimitry Andric 
1555ffd83dbSDimitry Andric       if (OnlyLFENCENonConst && hasConstantAddressingMode(MI)) {
1565ffd83dbSDimitry Andric         // This is a branch, but it only has constant addressing mode and we're
1575ffd83dbSDimitry Andric         // not adding LFENCEs before such branches.
1585ffd83dbSDimitry Andric         PrevInstIsLFENCE = false;
1595ffd83dbSDimitry Andric         continue;
1605ffd83dbSDimitry Andric       }
1615ffd83dbSDimitry Andric 
1625ffd83dbSDimitry Andric       // This branch requires adding an LFENCE.
1635ffd83dbSDimitry Andric       if (!PrevInstIsLFENCE) {
164e8d8bef9SDimitry Andric         assert(FirstTerminator && "Unknown terminator instruction");
1655ffd83dbSDimitry Andric         BuildMI(MBB, FirstTerminator, DebugLoc(), TII->get(X86::LFENCE));
1665ffd83dbSDimitry Andric         NumLFENCEsInserted++;
1675ffd83dbSDimitry Andric         Modified = true;
1685ffd83dbSDimitry Andric       }
1695ffd83dbSDimitry Andric       break;
1705ffd83dbSDimitry Andric     }
1715ffd83dbSDimitry Andric   }
1725ffd83dbSDimitry Andric 
1735ffd83dbSDimitry Andric   return Modified;
1745ffd83dbSDimitry Andric }
1755ffd83dbSDimitry Andric 
createX86SpeculativeExecutionSideEffectSuppression()1765ffd83dbSDimitry Andric FunctionPass *llvm::createX86SpeculativeExecutionSideEffectSuppression() {
1775ffd83dbSDimitry Andric   return new X86SpeculativeExecutionSideEffectSuppression();
1785ffd83dbSDimitry Andric }
1795ffd83dbSDimitry Andric 
1805ffd83dbSDimitry Andric INITIALIZE_PASS(X86SpeculativeExecutionSideEffectSuppression, "x86-seses",
1815ffd83dbSDimitry Andric                 "X86 Speculative Execution Side Effect Suppression", false,
1825ffd83dbSDimitry Andric                 false)
183