1 //==-- X86LoadValueInjectionLoadHardening.cpp - LVI load hardening for x86 --=//
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 /// Description: This pass finds Load Value Injection (LVI) gadgets consisting
10 /// of a load from memory (i.e., SOURCE), and any operation that may transmit
11 /// the value loaded from memory over a covert channel, or use the value loaded
12 /// from memory to determine a branch/call target (i.e., SINK). After finding
13 /// all such gadgets in a given function, the pass minimally inserts LFENCE
14 /// instructions in such a manner that the following property is satisfied: for
15 /// all SOURCE+SINK pairs, all paths in the CFG from SOURCE to SINK contain at
16 /// least one LFENCE instruction. The algorithm that implements this minimal
17 /// insertion is influenced by an academic paper that minimally inserts memory
18 /// fences for high-performance concurrent programs:
19 ///         http://www.cs.ucr.edu/~lesani/companion/oopsla15/OOPSLA15.pdf
20 /// The algorithm implemented in this pass is as follows:
21 /// 1. Build a condensed CFG (i.e., a GadgetGraph) consisting only of the
22 /// following components:
23 ///    - SOURCE instructions (also includes function arguments)
24 ///    - SINK instructions
25 ///    - Basic block entry points
26 ///    - Basic block terminators
27 ///    - LFENCE instructions
28 /// 2. Analyze the GadgetGraph to determine which SOURCE+SINK pairs (i.e.,
29 /// gadgets) are already mitigated by existing LFENCEs. If all gadgets have been
30 /// mitigated, go to step 6.
31 /// 3. Use a heuristic or plugin to approximate minimal LFENCE insertion.
32 /// 4. Insert one LFENCE along each CFG edge that was cut in step 3.
33 /// 5. Go to step 2.
34 /// 6. If any LFENCEs were inserted, return `true` from runOnMachineFunction()
35 /// to tell LLVM that the function was modified.
36 ///
37 //===----------------------------------------------------------------------===//
38 
39 #include "ImmutableGraph.h"
40 #include "X86.h"
41 #include "X86Subtarget.h"
42 #include "X86TargetMachine.h"
43 #include "llvm/ADT/DenseMap.h"
44 #include "llvm/ADT/DenseSet.h"
45 #include "llvm/ADT/STLExtras.h"
46 #include "llvm/ADT/SmallSet.h"
47 #include "llvm/ADT/Statistic.h"
48 #include "llvm/ADT/StringRef.h"
49 #include "llvm/CodeGen/MachineBasicBlock.h"
50 #include "llvm/CodeGen/MachineDominanceFrontier.h"
51 #include "llvm/CodeGen/MachineDominators.h"
52 #include "llvm/CodeGen/MachineFunction.h"
53 #include "llvm/CodeGen/MachineFunctionPass.h"
54 #include "llvm/CodeGen/MachineInstr.h"
55 #include "llvm/CodeGen/MachineInstrBuilder.h"
56 #include "llvm/CodeGen/MachineLoopInfo.h"
57 #include "llvm/CodeGen/MachineRegisterInfo.h"
58 #include "llvm/CodeGen/RDFGraph.h"
59 #include "llvm/CodeGen/RDFLiveness.h"
60 #include "llvm/InitializePasses.h"
61 #include "llvm/Support/CommandLine.h"
62 #include "llvm/Support/DOTGraphTraits.h"
63 #include "llvm/Support/Debug.h"
64 #include "llvm/Support/DynamicLibrary.h"
65 #include "llvm/Support/GraphWriter.h"
66 #include "llvm/Support/raw_ostream.h"
67 
68 using namespace llvm;
69 
70 #define PASS_KEY "x86-lvi-load"
71 #define DEBUG_TYPE PASS_KEY
72 
73 STATISTIC(NumFences, "Number of LFENCEs inserted for LVI mitigation");
74 STATISTIC(NumFunctionsConsidered, "Number of functions analyzed");
75 STATISTIC(NumFunctionsMitigated, "Number of functions for which mitigations "
76                                  "were deployed");
77 STATISTIC(NumGadgets, "Number of LVI gadgets detected during analysis");
78 
79 static cl::opt<std::string> OptimizePluginPath(
80     PASS_KEY "-opt-plugin",
81     cl::desc("Specify a plugin to optimize LFENCE insertion"), cl::Hidden);
82 
83 static cl::opt<bool> NoConditionalBranches(
84     PASS_KEY "-no-cbranch",
85     cl::desc("Don't treat conditional branches as disclosure gadgets. This "
86              "may improve performance, at the cost of security."),
87     cl::init(false), cl::Hidden);
88 
89 static cl::opt<bool> EmitDot(
90     PASS_KEY "-dot",
91     cl::desc(
92         "For each function, emit a dot graph depicting potential LVI gadgets"),
93     cl::init(false), cl::Hidden);
94 
95 static cl::opt<bool> EmitDotOnly(
96     PASS_KEY "-dot-only",
97     cl::desc("For each function, emit a dot graph depicting potential LVI "
98              "gadgets, and do not insert any fences"),
99     cl::init(false), cl::Hidden);
100 
101 static cl::opt<bool> EmitDotVerify(
102     PASS_KEY "-dot-verify",
103     cl::desc("For each function, emit a dot graph to stdout depicting "
104              "potential LVI gadgets, used for testing purposes only"),
105     cl::init(false), cl::Hidden);
106 
107 static llvm::sys::DynamicLibrary OptimizeDL;
108 typedef int (*OptimizeCutT)(unsigned int *Nodes, unsigned int NodesSize,
109                             unsigned int *Edges, int *EdgeValues,
110                             int *CutEdges /* out */, unsigned int EdgesSize);
111 static OptimizeCutT OptimizeCut = nullptr;
112 
113 namespace {
114 
115 struct MachineGadgetGraph : ImmutableGraph<MachineInstr *, int> {
116   static constexpr int GadgetEdgeSentinel = -1;
117   static constexpr MachineInstr *const ArgNodeSentinel = nullptr;
118 
119   using GraphT = ImmutableGraph<MachineInstr *, int>;
120   using Node = typename GraphT::Node;
121   using Edge = typename GraphT::Edge;
122   using size_type = typename GraphT::size_type;
123   MachineGadgetGraph(std::unique_ptr<Node[]> Nodes,
124                      std::unique_ptr<Edge[]> Edges, size_type NodesSize,
125                      size_type EdgesSize, int NumFences = 0, int NumGadgets = 0)
126       : GraphT(std::move(Nodes), std::move(Edges), NodesSize, EdgesSize),
127         NumFences(NumFences), NumGadgets(NumGadgets) {}
128   static inline bool isCFGEdge(const Edge &E) {
129     return E.getValue() != GadgetEdgeSentinel;
130   }
131   static inline bool isGadgetEdge(const Edge &E) {
132     return E.getValue() == GadgetEdgeSentinel;
133   }
134   int NumFences;
135   int NumGadgets;
136 };
137 
138 class X86LoadValueInjectionLoadHardeningPass : public MachineFunctionPass {
139 public:
140   X86LoadValueInjectionLoadHardeningPass() : MachineFunctionPass(ID) {}
141 
142   StringRef getPassName() const override {
143     return "X86 Load Value Injection (LVI) Load Hardening";
144   }
145   void getAnalysisUsage(AnalysisUsage &AU) const override;
146   bool runOnMachineFunction(MachineFunction &MF) override;
147 
148   static char ID;
149 
150 private:
151   using GraphBuilder = ImmutableGraphBuilder<MachineGadgetGraph>;
152   using Edge = MachineGadgetGraph::Edge;
153   using Node = MachineGadgetGraph::Node;
154   using EdgeSet = MachineGadgetGraph::EdgeSet;
155   using NodeSet = MachineGadgetGraph::NodeSet;
156 
157   const X86Subtarget *STI;
158   const TargetInstrInfo *TII;
159   const TargetRegisterInfo *TRI;
160 
161   std::unique_ptr<MachineGadgetGraph>
162   getGadgetGraph(MachineFunction &MF, const MachineLoopInfo &MLI,
163                  const MachineDominatorTree &MDT,
164                  const MachineDominanceFrontier &MDF) const;
165   int hardenLoadsWithPlugin(MachineFunction &MF,
166                             std::unique_ptr<MachineGadgetGraph> Graph) const;
167   int hardenLoadsWithHeuristic(MachineFunction &MF,
168                                std::unique_ptr<MachineGadgetGraph> Graph) const;
169   int elimMitigatedEdgesAndNodes(MachineGadgetGraph &G,
170                                  EdgeSet &ElimEdges /* in, out */,
171                                  NodeSet &ElimNodes /* in, out */) const;
172   std::unique_ptr<MachineGadgetGraph>
173   trimMitigatedEdges(std::unique_ptr<MachineGadgetGraph> Graph) const;
174   int insertFences(MachineFunction &MF, MachineGadgetGraph &G,
175                    EdgeSet &CutEdges /* in, out */) const;
176   bool instrUsesRegToAccessMemory(const MachineInstr &I, unsigned Reg) const;
177   bool instrUsesRegToBranch(const MachineInstr &I, unsigned Reg) const;
178   inline bool isFence(const MachineInstr *MI) const {
179     return MI && (MI->getOpcode() == X86::LFENCE ||
180                   (STI->useLVIControlFlowIntegrity() && MI->isCall()));
181   }
182 };
183 
184 } // end anonymous namespace
185 
186 namespace llvm {
187 
188 template <>
189 struct GraphTraits<MachineGadgetGraph *>
190     : GraphTraits<ImmutableGraph<MachineInstr *, int> *> {};
191 
192 template <>
193 struct DOTGraphTraits<MachineGadgetGraph *> : DefaultDOTGraphTraits {
194   using GraphType = MachineGadgetGraph;
195   using Traits = llvm::GraphTraits<GraphType *>;
196   using NodeRef = typename Traits::NodeRef;
197   using EdgeRef = typename Traits::EdgeRef;
198   using ChildIteratorType = typename Traits::ChildIteratorType;
199   using ChildEdgeIteratorType = typename Traits::ChildEdgeIteratorType;
200 
201   DOTGraphTraits(bool IsSimple = false) : DefaultDOTGraphTraits(IsSimple) {}
202 
203   std::string getNodeLabel(NodeRef Node, GraphType *) {
204     if (Node->getValue() == MachineGadgetGraph::ArgNodeSentinel)
205       return "ARGS";
206 
207     std::string Str;
208     raw_string_ostream OS(Str);
209     OS << *Node->getValue();
210     return OS.str();
211   }
212 
213   static std::string getNodeAttributes(NodeRef Node, GraphType *) {
214     MachineInstr *MI = Node->getValue();
215     if (MI == MachineGadgetGraph::ArgNodeSentinel)
216       return "color = blue";
217     if (MI->getOpcode() == X86::LFENCE)
218       return "color = green";
219     return "";
220   }
221 
222   static std::string getEdgeAttributes(NodeRef, ChildIteratorType E,
223                                        GraphType *) {
224     int EdgeVal = (*E.getCurrent()).getValue();
225     return EdgeVal >= 0 ? "label = " + std::to_string(EdgeVal)
226                         : "color = red, style = \"dashed\"";
227   }
228 };
229 
230 } // end namespace llvm
231 
232 constexpr MachineInstr *MachineGadgetGraph::ArgNodeSentinel;
233 constexpr int MachineGadgetGraph::GadgetEdgeSentinel;
234 
235 char X86LoadValueInjectionLoadHardeningPass::ID = 0;
236 
237 void X86LoadValueInjectionLoadHardeningPass::getAnalysisUsage(
238     AnalysisUsage &AU) const {
239   MachineFunctionPass::getAnalysisUsage(AU);
240   AU.addRequired<MachineLoopInfo>();
241   AU.addRequired<MachineDominatorTree>();
242   AU.addRequired<MachineDominanceFrontier>();
243   AU.setPreservesCFG();
244 }
245 
246 static void writeGadgetGraph(raw_ostream &OS, MachineFunction &MF,
247                              MachineGadgetGraph *G) {
248   WriteGraph(OS, G, /*ShortNames*/ false,
249              "Speculative gadgets for \"" + MF.getName() + "\" function");
250 }
251 
252 bool X86LoadValueInjectionLoadHardeningPass::runOnMachineFunction(
253     MachineFunction &MF) {
254   LLVM_DEBUG(dbgs() << "***** " << getPassName() << " : " << MF.getName()
255                     << " *****\n");
256   STI = &MF.getSubtarget<X86Subtarget>();
257   if (!STI->useLVILoadHardening())
258     return false;
259 
260   // FIXME: support 32-bit
261   if (!STI->is64Bit())
262     report_fatal_error("LVI load hardening is only supported on 64-bit", false);
263 
264   // Don't skip functions with the "optnone" attr but participate in opt-bisect.
265   const Function &F = MF.getFunction();
266   if (!F.hasOptNone() && skipFunction(F))
267     return false;
268 
269   ++NumFunctionsConsidered;
270   TII = STI->getInstrInfo();
271   TRI = STI->getRegisterInfo();
272   LLVM_DEBUG(dbgs() << "Building gadget graph...\n");
273   const auto &MLI = getAnalysis<MachineLoopInfo>();
274   const auto &MDT = getAnalysis<MachineDominatorTree>();
275   const auto &MDF = getAnalysis<MachineDominanceFrontier>();
276   std::unique_ptr<MachineGadgetGraph> Graph = getGadgetGraph(MF, MLI, MDT, MDF);
277   LLVM_DEBUG(dbgs() << "Building gadget graph... Done\n");
278   if (Graph == nullptr)
279     return false; // didn't find any gadgets
280 
281   if (EmitDotVerify) {
282     writeGadgetGraph(outs(), MF, Graph.get());
283     return false;
284   }
285 
286   if (EmitDot || EmitDotOnly) {
287     LLVM_DEBUG(dbgs() << "Emitting gadget graph...\n");
288     std::error_code FileError;
289     std::string FileName = "lvi.";
290     FileName += MF.getName();
291     FileName += ".dot";
292     raw_fd_ostream FileOut(FileName, FileError);
293     if (FileError)
294       errs() << FileError.message();
295     writeGadgetGraph(FileOut, MF, Graph.get());
296     FileOut.close();
297     LLVM_DEBUG(dbgs() << "Emitting gadget graph... Done\n");
298     if (EmitDotOnly)
299       return false;
300   }
301 
302   int FencesInserted;
303   if (!OptimizePluginPath.empty()) {
304     if (!OptimizeDL.isValid()) {
305       std::string ErrorMsg;
306       OptimizeDL = llvm::sys::DynamicLibrary::getPermanentLibrary(
307           OptimizePluginPath.c_str(), &ErrorMsg);
308       if (!ErrorMsg.empty())
309         report_fatal_error(Twine("Failed to load opt plugin: \"") + ErrorMsg +
310                            "\"");
311       OptimizeCut = (OptimizeCutT)OptimizeDL.getAddressOfSymbol("optimize_cut");
312       if (!OptimizeCut)
313         report_fatal_error("Invalid optimization plugin");
314     }
315     FencesInserted = hardenLoadsWithPlugin(MF, std::move(Graph));
316   } else { // Use the default greedy heuristic
317     FencesInserted = hardenLoadsWithHeuristic(MF, std::move(Graph));
318   }
319 
320   if (FencesInserted > 0)
321     ++NumFunctionsMitigated;
322   NumFences += FencesInserted;
323   return (FencesInserted > 0);
324 }
325 
326 std::unique_ptr<MachineGadgetGraph>
327 X86LoadValueInjectionLoadHardeningPass::getGadgetGraph(
328     MachineFunction &MF, const MachineLoopInfo &MLI,
329     const MachineDominatorTree &MDT,
330     const MachineDominanceFrontier &MDF) const {
331   using namespace rdf;
332 
333   // Build the Register Dataflow Graph using the RDF framework
334   TargetOperandInfo TOI{*TII};
335   DataFlowGraph DFG{MF, *TII, *TRI, MDT, MDF, TOI};
336   DFG.build();
337   Liveness L{MF.getRegInfo(), DFG};
338   L.computePhiInfo();
339 
340   GraphBuilder Builder;
341   using GraphIter = typename GraphBuilder::BuilderNodeRef;
342   DenseMap<MachineInstr *, GraphIter> NodeMap;
343   int FenceCount = 0, GadgetCount = 0;
344   auto MaybeAddNode = [&NodeMap, &Builder](MachineInstr *MI) {
345     auto Ref = NodeMap.find(MI);
346     if (Ref == NodeMap.end()) {
347       auto I = Builder.addVertex(MI);
348       NodeMap[MI] = I;
349       return std::pair<GraphIter, bool>{I, true};
350     }
351     return std::pair<GraphIter, bool>{Ref->getSecond(), false};
352   };
353 
354   // The `Transmitters` map memoizes transmitters found for each def. If a def
355   // has not yet been analyzed, then it will not appear in the map. If a def
356   // has been analyzed and was determined not to have any transmitters, then
357   // its list of transmitters will be empty.
358   DenseMap<NodeId, std::vector<NodeId>> Transmitters;
359 
360   // Analyze all machine instructions to find gadgets and LFENCEs, adding
361   // each interesting value to `Nodes`
362   auto AnalyzeDef = [&](NodeAddr<DefNode *> SourceDef) {
363     SmallSet<NodeId, 8> UsesVisited, DefsVisited;
364     std::function<void(NodeAddr<DefNode *>)> AnalyzeDefUseChain =
365         [&](NodeAddr<DefNode *> Def) {
366           if (Transmitters.find(Def.Id) != Transmitters.end())
367             return; // Already analyzed `Def`
368 
369           // Use RDF to find all the uses of `Def`
370           rdf::NodeSet Uses;
371           RegisterRef DefReg = Def.Addr->getRegRef(DFG);
372           for (auto UseID : L.getAllReachedUses(DefReg, Def)) {
373             auto Use = DFG.addr<UseNode *>(UseID);
374             if (Use.Addr->getFlags() & NodeAttrs::PhiRef) { // phi node
375               NodeAddr<PhiNode *> Phi = Use.Addr->getOwner(DFG);
376               for (const auto& I : L.getRealUses(Phi.Id)) {
377                 if (DFG.getPRI().alias(RegisterRef(I.first), DefReg)) {
378                   for (const auto &UA : I.second)
379                     Uses.emplace(UA.first);
380                 }
381               }
382             } else { // not a phi node
383               Uses.emplace(UseID);
384             }
385           }
386 
387           // For each use of `Def`, we want to know whether:
388           // (1) The use can leak the Def'ed value,
389           // (2) The use can further propagate the Def'ed value to more defs
390           for (auto UseID : Uses) {
391             if (!UsesVisited.insert(UseID).second)
392               continue; // Already visited this use of `Def`
393 
394             auto Use = DFG.addr<UseNode *>(UseID);
395             assert(!(Use.Addr->getFlags() & NodeAttrs::PhiRef));
396             MachineOperand &UseMO = Use.Addr->getOp();
397             MachineInstr &UseMI = *UseMO.getParent();
398             assert(UseMO.isReg());
399 
400             // We naively assume that an instruction propagates any loaded
401             // uses to all defs unless the instruction is a call, in which
402             // case all arguments will be treated as gadget sources during
403             // analysis of the callee function.
404             if (UseMI.isCall())
405               continue;
406 
407             // Check whether this use can transmit (leak) its value.
408             if (instrUsesRegToAccessMemory(UseMI, UseMO.getReg()) ||
409                 (!NoConditionalBranches &&
410                  instrUsesRegToBranch(UseMI, UseMO.getReg()))) {
411               Transmitters[Def.Id].push_back(Use.Addr->getOwner(DFG).Id);
412               if (UseMI.mayLoad())
413                 continue; // Found a transmitting load -- no need to continue
414                           // traversing its defs (i.e., this load will become
415                           // a new gadget source anyways).
416             }
417 
418             // Check whether the use propagates to more defs.
419             NodeAddr<InstrNode *> Owner{Use.Addr->getOwner(DFG)};
420             rdf::NodeList AnalyzedChildDefs;
421             for (const auto &ChildDef :
422                  Owner.Addr->members_if(DataFlowGraph::IsDef, DFG)) {
423               if (!DefsVisited.insert(ChildDef.Id).second)
424                 continue; // Already visited this def
425               if (Def.Addr->getAttrs() & NodeAttrs::Dead)
426                 continue;
427               if (Def.Id == ChildDef.Id)
428                 continue; // `Def` uses itself (e.g., increment loop counter)
429 
430               AnalyzeDefUseChain(ChildDef);
431 
432               // `Def` inherits all of its child defs' transmitters.
433               for (auto TransmitterId : Transmitters[ChildDef.Id])
434                 Transmitters[Def.Id].push_back(TransmitterId);
435             }
436           }
437 
438           // Note that this statement adds `Def.Id` to the map if no
439           // transmitters were found for `Def`.
440           auto &DefTransmitters = Transmitters[Def.Id];
441 
442           // Remove duplicate transmitters
443           llvm::sort(DefTransmitters);
444           DefTransmitters.erase(
445               std::unique(DefTransmitters.begin(), DefTransmitters.end()),
446               DefTransmitters.end());
447         };
448 
449     // Find all of the transmitters
450     AnalyzeDefUseChain(SourceDef);
451     auto &SourceDefTransmitters = Transmitters[SourceDef.Id];
452     if (SourceDefTransmitters.empty())
453       return; // No transmitters for `SourceDef`
454 
455     MachineInstr *Source = SourceDef.Addr->getFlags() & NodeAttrs::PhiRef
456                                ? MachineGadgetGraph::ArgNodeSentinel
457                                : SourceDef.Addr->getOp().getParent();
458     auto GadgetSource = MaybeAddNode(Source);
459     // Each transmitter is a sink for `SourceDef`.
460     for (auto TransmitterId : SourceDefTransmitters) {
461       MachineInstr *Sink = DFG.addr<StmtNode *>(TransmitterId).Addr->getCode();
462       auto GadgetSink = MaybeAddNode(Sink);
463       // Add the gadget edge to the graph.
464       Builder.addEdge(MachineGadgetGraph::GadgetEdgeSentinel,
465                       GadgetSource.first, GadgetSink.first);
466       ++GadgetCount;
467     }
468   };
469 
470   LLVM_DEBUG(dbgs() << "Analyzing def-use chains to find gadgets\n");
471   // Analyze function arguments
472   NodeAddr<BlockNode *> EntryBlock = DFG.getFunc().Addr->getEntryBlock(DFG);
473   for (NodeAddr<PhiNode *> ArgPhi :
474        EntryBlock.Addr->members_if(DataFlowGraph::IsPhi, DFG)) {
475     NodeList Defs = ArgPhi.Addr->members_if(DataFlowGraph::IsDef, DFG);
476     llvm::for_each(Defs, AnalyzeDef);
477   }
478   // Analyze every instruction in MF
479   for (NodeAddr<BlockNode *> BA : DFG.getFunc().Addr->members(DFG)) {
480     for (NodeAddr<StmtNode *> SA :
481          BA.Addr->members_if(DataFlowGraph::IsCode<NodeAttrs::Stmt>, DFG)) {
482       MachineInstr *MI = SA.Addr->getCode();
483       if (isFence(MI)) {
484         MaybeAddNode(MI);
485         ++FenceCount;
486       } else if (MI->mayLoad()) {
487         NodeList Defs = SA.Addr->members_if(DataFlowGraph::IsDef, DFG);
488         llvm::for_each(Defs, AnalyzeDef);
489       }
490     }
491   }
492   LLVM_DEBUG(dbgs() << "Found " << FenceCount << " fences\n");
493   LLVM_DEBUG(dbgs() << "Found " << GadgetCount << " gadgets\n");
494   if (GadgetCount == 0)
495     return nullptr;
496   NumGadgets += GadgetCount;
497 
498   // Traverse CFG to build the rest of the graph
499   SmallSet<MachineBasicBlock *, 8> BlocksVisited;
500   std::function<void(MachineBasicBlock *, GraphIter, unsigned)> TraverseCFG =
501       [&](MachineBasicBlock *MBB, GraphIter GI, unsigned ParentDepth) {
502         unsigned LoopDepth = MLI.getLoopDepth(MBB);
503         if (!MBB->empty()) {
504           // Always add the first instruction in each block
505           auto NI = MBB->begin();
506           auto BeginBB = MaybeAddNode(&*NI);
507           Builder.addEdge(ParentDepth, GI, BeginBB.first);
508           if (!BlocksVisited.insert(MBB).second)
509             return;
510 
511           // Add any instructions within the block that are gadget components
512           GI = BeginBB.first;
513           while (++NI != MBB->end()) {
514             auto Ref = NodeMap.find(&*NI);
515             if (Ref != NodeMap.end()) {
516               Builder.addEdge(LoopDepth, GI, Ref->getSecond());
517               GI = Ref->getSecond();
518             }
519           }
520 
521           // Always add the terminator instruction, if one exists
522           auto T = MBB->getFirstTerminator();
523           if (T != MBB->end()) {
524             auto EndBB = MaybeAddNode(&*T);
525             if (EndBB.second)
526               Builder.addEdge(LoopDepth, GI, EndBB.first);
527             GI = EndBB.first;
528           }
529         }
530         for (MachineBasicBlock *Succ : MBB->successors())
531           TraverseCFG(Succ, GI, LoopDepth);
532       };
533   // ArgNodeSentinel is a pseudo-instruction that represents MF args in the
534   // GadgetGraph
535   GraphIter ArgNode = MaybeAddNode(MachineGadgetGraph::ArgNodeSentinel).first;
536   TraverseCFG(&MF.front(), ArgNode, 0);
537   std::unique_ptr<MachineGadgetGraph> G{Builder.get(FenceCount, GadgetCount)};
538   LLVM_DEBUG(dbgs() << "Found " << G->nodes_size() << " nodes\n");
539   return G;
540 }
541 
542 // Returns the number of remaining gadget edges that could not be eliminated
543 int X86LoadValueInjectionLoadHardeningPass::elimMitigatedEdgesAndNodes(
544     MachineGadgetGraph &G, EdgeSet &ElimEdges /* in, out */,
545     NodeSet &ElimNodes /* in, out */) const {
546   if (G.NumFences > 0) {
547     // Eliminate fences and CFG edges that ingress and egress the fence, as
548     // they are trivially mitigated.
549     for (const Edge &E : G.edges()) {
550       const Node *Dest = E.getDest();
551       if (isFence(Dest->getValue())) {
552         ElimNodes.insert(*Dest);
553         ElimEdges.insert(E);
554         for (const Edge &DE : Dest->edges())
555           ElimEdges.insert(DE);
556       }
557     }
558   }
559 
560   // Find and eliminate gadget edges that have been mitigated.
561   int MitigatedGadgets = 0, RemainingGadgets = 0;
562   NodeSet ReachableNodes{G};
563   for (const Node &RootN : G.nodes()) {
564     if (llvm::none_of(RootN.edges(), MachineGadgetGraph::isGadgetEdge))
565       continue; // skip this node if it isn't a gadget source
566 
567     // Find all of the nodes that are CFG-reachable from RootN using DFS
568     ReachableNodes.clear();
569     std::function<void(const Node *, bool)> FindReachableNodes =
570         [&](const Node *N, bool FirstNode) {
571           if (!FirstNode)
572             ReachableNodes.insert(*N);
573           for (const Edge &E : N->edges()) {
574             const Node *Dest = E.getDest();
575             if (MachineGadgetGraph::isCFGEdge(E) && !ElimEdges.contains(E) &&
576                 !ReachableNodes.contains(*Dest))
577               FindReachableNodes(Dest, false);
578           }
579         };
580     FindReachableNodes(&RootN, true);
581 
582     // Any gadget whose sink is unreachable has been mitigated
583     for (const Edge &E : RootN.edges()) {
584       if (MachineGadgetGraph::isGadgetEdge(E)) {
585         if (ReachableNodes.contains(*E.getDest())) {
586           // This gadget's sink is reachable
587           ++RemainingGadgets;
588         } else { // This gadget's sink is unreachable, and therefore mitigated
589           ++MitigatedGadgets;
590           ElimEdges.insert(E);
591         }
592       }
593     }
594   }
595   return RemainingGadgets;
596 }
597 
598 std::unique_ptr<MachineGadgetGraph>
599 X86LoadValueInjectionLoadHardeningPass::trimMitigatedEdges(
600     std::unique_ptr<MachineGadgetGraph> Graph) const {
601   NodeSet ElimNodes{*Graph};
602   EdgeSet ElimEdges{*Graph};
603   int RemainingGadgets =
604       elimMitigatedEdgesAndNodes(*Graph, ElimEdges, ElimNodes);
605   if (ElimEdges.empty() && ElimNodes.empty()) {
606     Graph->NumFences = 0;
607     Graph->NumGadgets = RemainingGadgets;
608   } else {
609     Graph = GraphBuilder::trim(*Graph, ElimNodes, ElimEdges, 0 /* NumFences */,
610                                RemainingGadgets);
611   }
612   return Graph;
613 }
614 
615 int X86LoadValueInjectionLoadHardeningPass::hardenLoadsWithPlugin(
616     MachineFunction &MF, std::unique_ptr<MachineGadgetGraph> Graph) const {
617   int FencesInserted = 0;
618 
619   do {
620     LLVM_DEBUG(dbgs() << "Eliminating mitigated paths...\n");
621     Graph = trimMitigatedEdges(std::move(Graph));
622     LLVM_DEBUG(dbgs() << "Eliminating mitigated paths... Done\n");
623     if (Graph->NumGadgets == 0)
624       break;
625 
626     LLVM_DEBUG(dbgs() << "Cutting edges...\n");
627     EdgeSet CutEdges{*Graph};
628     auto Nodes = std::make_unique<unsigned int[]>(Graph->nodes_size() +
629                                                   1 /* terminator node */);
630     auto Edges = std::make_unique<unsigned int[]>(Graph->edges_size());
631     auto EdgeCuts = std::make_unique<int[]>(Graph->edges_size());
632     auto EdgeValues = std::make_unique<int[]>(Graph->edges_size());
633     for (const Node &N : Graph->nodes()) {
634       Nodes[Graph->getNodeIndex(N)] = Graph->getEdgeIndex(*N.edges_begin());
635     }
636     Nodes[Graph->nodes_size()] = Graph->edges_size(); // terminator node
637     for (const Edge &E : Graph->edges()) {
638       Edges[Graph->getEdgeIndex(E)] = Graph->getNodeIndex(*E.getDest());
639       EdgeValues[Graph->getEdgeIndex(E)] = E.getValue();
640     }
641     OptimizeCut(Nodes.get(), Graph->nodes_size(), Edges.get(), EdgeValues.get(),
642                 EdgeCuts.get(), Graph->edges_size());
643     for (int I = 0; I < Graph->edges_size(); ++I)
644       if (EdgeCuts[I])
645         CutEdges.set(I);
646     LLVM_DEBUG(dbgs() << "Cutting edges... Done\n");
647     LLVM_DEBUG(dbgs() << "Cut " << CutEdges.count() << " edges\n");
648 
649     LLVM_DEBUG(dbgs() << "Inserting LFENCEs...\n");
650     FencesInserted += insertFences(MF, *Graph, CutEdges);
651     LLVM_DEBUG(dbgs() << "Inserting LFENCEs... Done\n");
652     LLVM_DEBUG(dbgs() << "Inserted " << FencesInserted << " fences\n");
653 
654     Graph = GraphBuilder::trim(*Graph, NodeSet{*Graph}, CutEdges);
655   } while (true);
656 
657   return FencesInserted;
658 }
659 
660 int X86LoadValueInjectionLoadHardeningPass::hardenLoadsWithHeuristic(
661     MachineFunction &MF, std::unique_ptr<MachineGadgetGraph> Graph) const {
662   // If `MF` does not have any fences, then no gadgets would have been
663   // mitigated at this point.
664   if (Graph->NumFences > 0) {
665     LLVM_DEBUG(dbgs() << "Eliminating mitigated paths...\n");
666     Graph = trimMitigatedEdges(std::move(Graph));
667     LLVM_DEBUG(dbgs() << "Eliminating mitigated paths... Done\n");
668   }
669 
670   if (Graph->NumGadgets == 0)
671     return 0;
672 
673   LLVM_DEBUG(dbgs() << "Cutting edges...\n");
674   EdgeSet CutEdges{*Graph};
675 
676   // Begin by collecting all ingress CFG edges for each node
677   DenseMap<const Node *, SmallVector<const Edge *, 2>> IngressEdgeMap;
678   for (const Edge &E : Graph->edges())
679     if (MachineGadgetGraph::isCFGEdge(E))
680       IngressEdgeMap[E.getDest()].push_back(&E);
681 
682   // For each gadget edge, make cuts that guarantee the gadget will be
683   // mitigated. A computationally efficient way to achieve this is to either:
684   // (a) cut all egress CFG edges from the gadget source, or
685   // (b) cut all ingress CFG edges to the gadget sink.
686   //
687   // Moreover, the algorithm tries not to make a cut into a loop by preferring
688   // to make a (b)-type cut if the gadget source resides at a greater loop depth
689   // than the gadget sink, or an (a)-type cut otherwise.
690   for (const Node &N : Graph->nodes()) {
691     for (const Edge &E : N.edges()) {
692       if (!MachineGadgetGraph::isGadgetEdge(E))
693         continue;
694 
695       SmallVector<const Edge *, 2> EgressEdges;
696       SmallVector<const Edge *, 2> &IngressEdges = IngressEdgeMap[E.getDest()];
697       for (const Edge &EgressEdge : N.edges())
698         if (MachineGadgetGraph::isCFGEdge(EgressEdge))
699           EgressEdges.push_back(&EgressEdge);
700 
701       int EgressCutCost = 0, IngressCutCost = 0;
702       for (const Edge *EgressEdge : EgressEdges)
703         if (!CutEdges.contains(*EgressEdge))
704           EgressCutCost += EgressEdge->getValue();
705       for (const Edge *IngressEdge : IngressEdges)
706         if (!CutEdges.contains(*IngressEdge))
707           IngressCutCost += IngressEdge->getValue();
708 
709       auto &EdgesToCut =
710           IngressCutCost < EgressCutCost ? IngressEdges : EgressEdges;
711       for (const Edge *E : EdgesToCut)
712         CutEdges.insert(*E);
713     }
714   }
715   LLVM_DEBUG(dbgs() << "Cutting edges... Done\n");
716   LLVM_DEBUG(dbgs() << "Cut " << CutEdges.count() << " edges\n");
717 
718   LLVM_DEBUG(dbgs() << "Inserting LFENCEs...\n");
719   int FencesInserted = insertFences(MF, *Graph, CutEdges);
720   LLVM_DEBUG(dbgs() << "Inserting LFENCEs... Done\n");
721   LLVM_DEBUG(dbgs() << "Inserted " << FencesInserted << " fences\n");
722 
723   return FencesInserted;
724 }
725 
726 int X86LoadValueInjectionLoadHardeningPass::insertFences(
727     MachineFunction &MF, MachineGadgetGraph &G,
728     EdgeSet &CutEdges /* in, out */) const {
729   int FencesInserted = 0;
730   for (const Node &N : G.nodes()) {
731     for (const Edge &E : N.edges()) {
732       if (CutEdges.contains(E)) {
733         MachineInstr *MI = N.getValue(), *Prev;
734         MachineBasicBlock *MBB;                  // Insert an LFENCE in this MBB
735         MachineBasicBlock::iterator InsertionPt; // ...at this point
736         if (MI == MachineGadgetGraph::ArgNodeSentinel) {
737           // insert LFENCE at beginning of entry block
738           MBB = &MF.front();
739           InsertionPt = MBB->begin();
740           Prev = nullptr;
741         } else if (MI->isBranch()) { // insert the LFENCE before the branch
742           MBB = MI->getParent();
743           InsertionPt = MI;
744           Prev = MI->getPrevNode();
745           // Remove all egress CFG edges from this branch because the inserted
746           // LFENCE prevents gadgets from crossing the branch.
747           for (const Edge &E : N.edges()) {
748             if (MachineGadgetGraph::isCFGEdge(E))
749               CutEdges.insert(E);
750           }
751         } else { // insert the LFENCE after the instruction
752           MBB = MI->getParent();
753           InsertionPt = MI->getNextNode() ? MI->getNextNode() : MBB->end();
754           Prev = InsertionPt == MBB->end()
755                      ? (MBB->empty() ? nullptr : &MBB->back())
756                      : InsertionPt->getPrevNode();
757         }
758         // Ensure this insertion is not redundant (two LFENCEs in sequence).
759         if ((InsertionPt == MBB->end() || !isFence(&*InsertionPt)) &&
760             (!Prev || !isFence(Prev))) {
761           BuildMI(*MBB, InsertionPt, DebugLoc(), TII->get(X86::LFENCE));
762           ++FencesInserted;
763         }
764       }
765     }
766   }
767   return FencesInserted;
768 }
769 
770 bool X86LoadValueInjectionLoadHardeningPass::instrUsesRegToAccessMemory(
771     const MachineInstr &MI, unsigned Reg) const {
772   if (!MI.mayLoadOrStore() || MI.getOpcode() == X86::MFENCE ||
773       MI.getOpcode() == X86::SFENCE || MI.getOpcode() == X86::LFENCE)
774     return false;
775 
776   // FIXME: This does not handle pseudo loading instruction like TCRETURN*
777   const MCInstrDesc &Desc = MI.getDesc();
778   int MemRefBeginIdx = X86II::getMemoryOperandNo(Desc.TSFlags);
779   if (MemRefBeginIdx < 0) {
780     LLVM_DEBUG(dbgs() << "Warning: unable to obtain memory operand for loading "
781                          "instruction:\n";
782                MI.print(dbgs()); dbgs() << '\n';);
783     return false;
784   }
785   MemRefBeginIdx += X86II::getOperandBias(Desc);
786 
787   const MachineOperand &BaseMO =
788       MI.getOperand(MemRefBeginIdx + X86::AddrBaseReg);
789   const MachineOperand &IndexMO =
790       MI.getOperand(MemRefBeginIdx + X86::AddrIndexReg);
791   return (BaseMO.isReg() && BaseMO.getReg() != X86::NoRegister &&
792           TRI->regsOverlap(BaseMO.getReg(), Reg)) ||
793          (IndexMO.isReg() && IndexMO.getReg() != X86::NoRegister &&
794           TRI->regsOverlap(IndexMO.getReg(), Reg));
795 }
796 
797 bool X86LoadValueInjectionLoadHardeningPass::instrUsesRegToBranch(
798     const MachineInstr &MI, unsigned Reg) const {
799   if (!MI.isConditionalBranch())
800     return false;
801   for (const MachineOperand &Use : MI.uses())
802     if (Use.isReg() && Use.getReg() == Reg)
803       return true;
804   return false;
805 }
806 
807 INITIALIZE_PASS_BEGIN(X86LoadValueInjectionLoadHardeningPass, PASS_KEY,
808                       "X86 LVI load hardening", false, false)
809 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
810 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
811 INITIALIZE_PASS_DEPENDENCY(MachineDominanceFrontier)
812 INITIALIZE_PASS_END(X86LoadValueInjectionLoadHardeningPass, PASS_KEY,
813                     "X86 LVI load hardening", false, false)
814 
815 FunctionPass *llvm::createX86LoadValueInjectionLoadHardeningPass() {
816   return new X86LoadValueInjectionLoadHardeningPass();
817 }
818