1 //===- bolt/Passes/DataflowAnalysis.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 //
9 // This file implements functions and classes used for data-flow analysis.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "bolt/Passes/DataflowAnalysis.h"
14 
15 #define DEBUG_TYPE "dataflow"
16 
17 namespace llvm {
18 
19 raw_ostream &operator<<(raw_ostream &OS, const BitVector &State) {
20   LLVM_DEBUG({
21     OS << "BitVector(";
22     const char *Sep = "";
23     if (State.count() > (State.size() >> 1)) {
24       OS << "all, except: ";
25       BitVector BV = State;
26       BV.flip();
27       for (int I = BV.find_first(); I != -1; I = BV.find_next(I)) {
28         OS << Sep << I;
29         Sep = " ";
30       }
31       OS << ")";
32       return OS;
33     }
34     for (int I = State.find_first(); I != -1; I = State.find_next(I)) {
35       OS << Sep << I;
36       Sep = " ";
37     }
38     OS << ")";
39     return OS;
40   });
41   OS << "BitVector";
42   return OS;
43 }
44 
45 namespace bolt {
46 
47 void doForAllPreds(const BinaryBasicBlock &BB,
48                    std::function<void(ProgramPoint)> Task) {
49   MCPlusBuilder *MIB = BB.getFunction()->getBinaryContext().MIB.get();
50   for (BinaryBasicBlock *Pred : BB.predecessors()) {
51     if (Pred->isValid())
52       Task(ProgramPoint::getLastPointAt(*Pred));
53   }
54   if (!BB.isLandingPad())
55     return;
56   for (BinaryBasicBlock *Thrower : BB.throwers()) {
57     for (MCInst &Inst : *Thrower) {
58       if (!MIB->isInvoke(Inst))
59         continue;
60       const Optional<MCPlus::MCLandingPad> EHInfo = MIB->getEHInfo(Inst);
61       if (!EHInfo || EHInfo->first != BB.getLabel())
62         continue;
63       Task(ProgramPoint(&Inst));
64     }
65   }
66 }
67 
68 /// Operates on all successors of a basic block.
69 void doForAllSuccs(const BinaryBasicBlock &BB,
70                    std::function<void(ProgramPoint)> Task) {
71   for (BinaryBasicBlock *Succ : BB.successors())
72     if (Succ->isValid())
73       Task(ProgramPoint::getFirstPointAt(*Succ));
74 }
75 
76 void RegStatePrinter::print(raw_ostream &OS, const BitVector &State) const {
77   if (State.all()) {
78     OS << "(all)";
79     return;
80   }
81   if (State.count() > (State.size() >> 1)) {
82     OS << "all, except: ";
83     BitVector BV = State;
84     BV.flip();
85     for (int I = BV.find_first(); I != -1; I = BV.find_next(I))
86       OS << BC.MRI->getName(I) << " ";
87     return;
88   }
89   for (int I = State.find_first(); I != -1; I = State.find_next(I))
90     OS << BC.MRI->getName(I) << " ";
91 }
92 
93 } // namespace bolt
94 } // namespace llvm
95