xref: /freebsd-src/contrib/llvm-project/llvm/lib/CodeGen/RDFLiveness.cpp (revision 06c3fb2749bda94cb5201f81ffdb8fa6c3161b2e)
10946e70aSDimitry Andric //===- RDFLiveness.cpp ----------------------------------------------------===//
20946e70aSDimitry Andric //
30946e70aSDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40946e70aSDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50946e70aSDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60946e70aSDimitry Andric //
70946e70aSDimitry Andric //===----------------------------------------------------------------------===//
80946e70aSDimitry Andric //
90946e70aSDimitry Andric // Computation of the liveness information from the data-flow graph.
100946e70aSDimitry Andric //
110946e70aSDimitry Andric // The main functionality of this code is to compute block live-in
120946e70aSDimitry Andric // information. With the live-in information in place, the placement
130946e70aSDimitry Andric // of kill flags can also be recalculated.
140946e70aSDimitry Andric //
150946e70aSDimitry Andric // The block live-in calculation is based on the ideas from the following
160946e70aSDimitry Andric // publication:
170946e70aSDimitry Andric //
180946e70aSDimitry Andric // Dibyendu Das, Ramakrishna Upadrasta, Benoit Dupont de Dinechin.
190946e70aSDimitry Andric // "Efficient Liveness Computation Using Merge Sets and DJ-Graphs."
200946e70aSDimitry Andric // ACM Transactions on Architecture and Code Optimization, Association for
210946e70aSDimitry Andric // Computing Machinery, 2012, ACM TACO Special Issue on "High-Performance
220946e70aSDimitry Andric // and Embedded Architectures and Compilers", 8 (4),
230946e70aSDimitry Andric // <10.1145/2086696.2086706>. <hal-00647369>
240946e70aSDimitry Andric //
250946e70aSDimitry Andric #include "llvm/ADT/BitVector.h"
26e8d8bef9SDimitry Andric #include "llvm/ADT/DenseMap.h"
270946e70aSDimitry Andric #include "llvm/ADT/STLExtras.h"
280946e70aSDimitry Andric #include "llvm/ADT/SetVector.h"
29e8d8bef9SDimitry Andric #include "llvm/ADT/SmallSet.h"
300946e70aSDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
310946e70aSDimitry Andric #include "llvm/CodeGen/MachineDominanceFrontier.h"
320946e70aSDimitry Andric #include "llvm/CodeGen/MachineDominators.h"
330946e70aSDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
340946e70aSDimitry Andric #include "llvm/CodeGen/MachineInstr.h"
350946e70aSDimitry Andric #include "llvm/CodeGen/RDFGraph.h"
36*06c3fb27SDimitry Andric #include "llvm/CodeGen/RDFLiveness.h"
370946e70aSDimitry Andric #include "llvm/CodeGen/RDFRegisters.h"
380946e70aSDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h"
390946e70aSDimitry Andric #include "llvm/MC/LaneBitmask.h"
400946e70aSDimitry Andric #include "llvm/MC/MCRegisterInfo.h"
410946e70aSDimitry Andric #include "llvm/Support/CommandLine.h"
420946e70aSDimitry Andric #include "llvm/Support/ErrorHandling.h"
430946e70aSDimitry Andric #include "llvm/Support/raw_ostream.h"
440946e70aSDimitry Andric #include <algorithm>
450946e70aSDimitry Andric #include <cassert>
460946e70aSDimitry Andric #include <cstdint>
470946e70aSDimitry Andric #include <iterator>
480946e70aSDimitry Andric #include <map>
49e8d8bef9SDimitry Andric #include <unordered_map>
500946e70aSDimitry Andric #include <utility>
510946e70aSDimitry Andric #include <vector>
520946e70aSDimitry Andric 
530946e70aSDimitry Andric using namespace llvm;
540946e70aSDimitry Andric 
550946e70aSDimitry Andric static cl::opt<unsigned> MaxRecNest("rdf-liveness-max-rec", cl::init(25),
56*06c3fb27SDimitry Andric                                     cl::Hidden,
57*06c3fb27SDimitry Andric                                     cl::desc("Maximum recursion level"));
580946e70aSDimitry Andric 
59*06c3fb27SDimitry Andric namespace llvm::rdf {
600946e70aSDimitry Andric 
operator <<(raw_ostream & OS,const Print<Liveness::RefMap> & P)610946e70aSDimitry Andric raw_ostream &operator<<(raw_ostream &OS, const Print<Liveness::RefMap> &P) {
620946e70aSDimitry Andric   OS << '{';
63fcaf7f86SDimitry Andric   for (const auto &I : P.Obj) {
640946e70aSDimitry Andric     OS << ' ' << printReg(I.first, &P.G.getTRI()) << '{';
650946e70aSDimitry Andric     for (auto J = I.second.begin(), E = I.second.end(); J != E;) {
66*06c3fb27SDimitry Andric       OS << Print(J->first, P.G) << PrintLaneMaskShort(J->second);
670946e70aSDimitry Andric       if (++J != E)
680946e70aSDimitry Andric         OS << ',';
690946e70aSDimitry Andric     }
700946e70aSDimitry Andric     OS << '}';
710946e70aSDimitry Andric   }
720946e70aSDimitry Andric   OS << " }";
730946e70aSDimitry Andric   return OS;
740946e70aSDimitry Andric }
750946e70aSDimitry Andric 
760946e70aSDimitry Andric // The order in the returned sequence is the order of reaching defs in the
770946e70aSDimitry Andric // upward traversal: the first def is the closest to the given reference RefA,
780946e70aSDimitry Andric // the next one is further up, and so on.
790946e70aSDimitry Andric // The list ends at a reaching phi def, or when the reference from RefA is
800946e70aSDimitry Andric // covered by the defs in the list (see FullChain).
810946e70aSDimitry Andric // This function provides two modes of operation:
820946e70aSDimitry Andric // (1) Returning the sequence of reaching defs for a particular reference
830946e70aSDimitry Andric // node. This sequence will terminate at the first phi node [1].
840946e70aSDimitry Andric // (2) Returning a partial sequence of reaching defs, where the final goal
850946e70aSDimitry Andric // is to traverse past phi nodes to the actual defs arising from the code
860946e70aSDimitry Andric // itself.
870946e70aSDimitry Andric // In mode (2), the register reference for which the search was started
880946e70aSDimitry Andric // may be different from the reference node RefA, for which this call was
890946e70aSDimitry Andric // made, hence the argument RefRR, which holds the original register.
900946e70aSDimitry Andric // Also, some definitions may have already been encountered in a previous
910946e70aSDimitry Andric // call that will influence register covering. The register references
920946e70aSDimitry Andric // already defined are passed in through DefRRs.
930946e70aSDimitry Andric // In mode (1), the "continuation" considerations do not apply, and the
940946e70aSDimitry Andric // RefRR is the same as the register in RefA, and the set DefRRs is empty.
950946e70aSDimitry Andric //
960946e70aSDimitry Andric // [1] It is possible for multiple phi nodes to be included in the returned
970946e70aSDimitry Andric // sequence:
980946e70aSDimitry Andric //   SubA = phi ...
990946e70aSDimitry Andric //   SubB = phi ...
1000946e70aSDimitry Andric //   ...  = SuperAB(rdef:SubA), SuperAB"(rdef:SubB)
1010946e70aSDimitry Andric // However, these phi nodes are independent from one another in terms of
1020946e70aSDimitry Andric // the data-flow.
1030946e70aSDimitry Andric 
getAllReachingDefs(RegisterRef RefRR,NodeAddr<RefNode * > RefA,bool TopShadows,bool FullChain,const RegisterAggr & DefRRs)1040946e70aSDimitry Andric NodeList Liveness::getAllReachingDefs(RegisterRef RefRR,
105*06c3fb27SDimitry Andric                                       NodeAddr<RefNode *> RefA, bool TopShadows,
106*06c3fb27SDimitry Andric                                       bool FullChain,
1070946e70aSDimitry Andric                                       const RegisterAggr &DefRRs) {
1080946e70aSDimitry Andric   NodeList RDefs; // Return value.
1090946e70aSDimitry Andric   SetVector<NodeId> DefQ;
110e8d8bef9SDimitry Andric   DenseMap<MachineInstr *, uint32_t> OrdMap;
1110946e70aSDimitry Andric 
1120946e70aSDimitry Andric   // Dead defs will be treated as if they were live, since they are actually
1130946e70aSDimitry Andric   // on the data-flow path. They cannot be ignored because even though they
1140946e70aSDimitry Andric   // do not generate meaningful values, they still modify registers.
1150946e70aSDimitry Andric 
1160946e70aSDimitry Andric   // If the reference is undefined, there is nothing to do.
1170946e70aSDimitry Andric   if (RefA.Addr->getFlags() & NodeAttrs::Undef)
1180946e70aSDimitry Andric     return RDefs;
1190946e70aSDimitry Andric 
1200946e70aSDimitry Andric   // The initial queue should not have reaching defs for shadows. The
1210946e70aSDimitry Andric   // whole point of a shadow is that it will have a reaching def that
1220946e70aSDimitry Andric   // is not aliased to the reaching defs of the related shadows.
1230946e70aSDimitry Andric   NodeId Start = RefA.Id;
1240946e70aSDimitry Andric   auto SNA = DFG.addr<RefNode *>(Start);
1250946e70aSDimitry Andric   if (NodeId RD = SNA.Addr->getReachingDef())
1260946e70aSDimitry Andric     DefQ.insert(RD);
1270946e70aSDimitry Andric   if (TopShadows) {
1280946e70aSDimitry Andric     for (auto S : DFG.getRelatedRefs(RefA.Addr->getOwner(DFG), RefA))
1290946e70aSDimitry Andric       if (NodeId RD = NodeAddr<RefNode *>(S).Addr->getReachingDef())
1300946e70aSDimitry Andric         DefQ.insert(RD);
1310946e70aSDimitry Andric   }
1320946e70aSDimitry Andric 
1330946e70aSDimitry Andric   // Collect all the reaching defs, going up until a phi node is encountered,
1340946e70aSDimitry Andric   // or there are no more reaching defs. From this set, the actual set of
1350946e70aSDimitry Andric   // reaching defs will be selected.
1360946e70aSDimitry Andric   // The traversal upwards must go on until a covering def is encountered.
1370946e70aSDimitry Andric   // It is possible that a collection of non-covering (individually) defs
1380946e70aSDimitry Andric   // will be sufficient, but keep going until a covering one is found.
1390946e70aSDimitry Andric   for (unsigned i = 0; i < DefQ.size(); ++i) {
1400946e70aSDimitry Andric     auto TA = DFG.addr<DefNode *>(DefQ[i]);
1410946e70aSDimitry Andric     if (TA.Addr->getFlags() & NodeAttrs::PhiRef)
1420946e70aSDimitry Andric       continue;
1430946e70aSDimitry Andric     // Stop at the covering/overwriting def of the initial register reference.
1440946e70aSDimitry Andric     RegisterRef RR = TA.Addr->getRegRef(DFG);
1450946e70aSDimitry Andric     if (!DFG.IsPreservingDef(TA))
1460946e70aSDimitry Andric       if (RegisterAggr::isCoverOf(RR, RefRR, PRI))
1470946e70aSDimitry Andric         continue;
1480946e70aSDimitry Andric     // Get the next level of reaching defs. This will include multiple
1490946e70aSDimitry Andric     // reaching defs for shadows.
1500946e70aSDimitry Andric     for (auto S : DFG.getRelatedRefs(TA.Addr->getOwner(DFG), TA))
1510946e70aSDimitry Andric       if (NodeId RD = NodeAddr<RefNode *>(S).Addr->getReachingDef())
1520946e70aSDimitry Andric         DefQ.insert(RD);
153e8d8bef9SDimitry Andric     // Don't visit sibling defs. They share the same reaching def (which
154e8d8bef9SDimitry Andric     // will be visited anyway), but they define something not aliased to
155e8d8bef9SDimitry Andric     // this ref.
1560946e70aSDimitry Andric   }
1570946e70aSDimitry Andric 
1580946e70aSDimitry Andric   // Return the MachineBasicBlock containing a given instruction.
1590946e70aSDimitry Andric   auto Block = [this](NodeAddr<InstrNode *> IA) -> MachineBasicBlock * {
1600946e70aSDimitry Andric     if (IA.Addr->getKind() == NodeAttrs::Stmt)
1610946e70aSDimitry Andric       return NodeAddr<StmtNode *>(IA).Addr->getCode()->getParent();
1620946e70aSDimitry Andric     assert(IA.Addr->getKind() == NodeAttrs::Phi);
1630946e70aSDimitry Andric     NodeAddr<PhiNode *> PA = IA;
1640946e70aSDimitry Andric     NodeAddr<BlockNode *> BA = PA.Addr->getOwner(DFG);
1650946e70aSDimitry Andric     return BA.Addr->getCode();
1660946e70aSDimitry Andric   };
167e8d8bef9SDimitry Andric 
168e8d8bef9SDimitry Andric   SmallSet<NodeId, 32> Defs;
169e8d8bef9SDimitry Andric 
170349cc55cSDimitry Andric   // Remove all non-phi defs that are not aliased to RefRR, and separate
171e8d8bef9SDimitry Andric   // the the remaining defs into buckets for containing blocks.
172e8d8bef9SDimitry Andric   std::map<NodeId, NodeAddr<InstrNode *>> Owners;
173e8d8bef9SDimitry Andric   std::map<MachineBasicBlock *, SmallVector<NodeId, 32>> Blocks;
174e8d8bef9SDimitry Andric   for (NodeId N : DefQ) {
175e8d8bef9SDimitry Andric     auto TA = DFG.addr<DefNode *>(N);
176e8d8bef9SDimitry Andric     bool IsPhi = TA.Addr->getFlags() & NodeAttrs::PhiRef;
177e8d8bef9SDimitry Andric     if (!IsPhi && !PRI.alias(RefRR, TA.Addr->getRegRef(DFG)))
178e8d8bef9SDimitry Andric       continue;
179e8d8bef9SDimitry Andric     Defs.insert(TA.Id);
180e8d8bef9SDimitry Andric     NodeAddr<InstrNode *> IA = TA.Addr->getOwner(DFG);
181e8d8bef9SDimitry Andric     Owners[TA.Id] = IA;
182e8d8bef9SDimitry Andric     Blocks[Block(IA)].push_back(IA.Id);
183e8d8bef9SDimitry Andric   }
184e8d8bef9SDimitry Andric 
185e8d8bef9SDimitry Andric   auto Precedes = [this, &OrdMap](NodeId A, NodeId B) {
1860946e70aSDimitry Andric     if (A == B)
1870946e70aSDimitry Andric       return false;
188e8d8bef9SDimitry Andric     NodeAddr<InstrNode *> OA = DFG.addr<InstrNode *>(A);
189e8d8bef9SDimitry Andric     NodeAddr<InstrNode *> OB = DFG.addr<InstrNode *>(B);
1900946e70aSDimitry Andric     bool StmtA = OA.Addr->getKind() == NodeAttrs::Stmt;
1910946e70aSDimitry Andric     bool StmtB = OB.Addr->getKind() == NodeAttrs::Stmt;
192e8d8bef9SDimitry Andric     if (StmtA && StmtB) {
193e8d8bef9SDimitry Andric       const MachineInstr *InA = NodeAddr<StmtNode *>(OA).Addr->getCode();
194e8d8bef9SDimitry Andric       const MachineInstr *InB = NodeAddr<StmtNode *>(OB).Addr->getCode();
195e8d8bef9SDimitry Andric       assert(InA->getParent() == InB->getParent());
196e8d8bef9SDimitry Andric       auto FA = OrdMap.find(InA);
197e8d8bef9SDimitry Andric       if (FA != OrdMap.end())
198e8d8bef9SDimitry Andric         return FA->second < OrdMap.find(InB)->second;
199e8d8bef9SDimitry Andric       const MachineBasicBlock *BB = InA->getParent();
200e8d8bef9SDimitry Andric       for (auto It = BB->begin(), E = BB->end(); It != E; ++It) {
201e8d8bef9SDimitry Andric         if (It == InA->getIterator())
2020946e70aSDimitry Andric           return true;
203e8d8bef9SDimitry Andric         if (It == InB->getIterator())
2040946e70aSDimitry Andric           return false;
205e8d8bef9SDimitry Andric       }
206e8d8bef9SDimitry Andric       llvm_unreachable("InA and InB should be in the same block");
207e8d8bef9SDimitry Andric     }
208e8d8bef9SDimitry Andric     // One of them is a phi node.
209e8d8bef9SDimitry Andric     if (!StmtA && !StmtB) {
210e8d8bef9SDimitry Andric       // Both are phis, which are unordered. Break the tie by id numbers.
2110946e70aSDimitry Andric       return A < B;
2120946e70aSDimitry Andric     }
213e8d8bef9SDimitry Andric     // Only one of them is a phi. Phis always precede statements.
214e8d8bef9SDimitry Andric     return !StmtA;
2150946e70aSDimitry Andric   };
2160946e70aSDimitry Andric 
217e8d8bef9SDimitry Andric   auto GetOrder = [&OrdMap](MachineBasicBlock &B) {
218e8d8bef9SDimitry Andric     uint32_t Pos = 0;
219e8d8bef9SDimitry Andric     for (MachineInstr &In : B)
220e8d8bef9SDimitry Andric       OrdMap.insert({&In, ++Pos});
221e8d8bef9SDimitry Andric   };
222e8d8bef9SDimitry Andric 
223e8d8bef9SDimitry Andric   // For each block, sort the nodes in it.
224e8d8bef9SDimitry Andric   std::vector<MachineBasicBlock *> TmpBB;
225e8d8bef9SDimitry Andric   for (auto &Bucket : Blocks) {
226e8d8bef9SDimitry Andric     TmpBB.push_back(Bucket.first);
227e8d8bef9SDimitry Andric     if (Bucket.second.size() > 2)
228e8d8bef9SDimitry Andric       GetOrder(*Bucket.first);
229e8d8bef9SDimitry Andric     llvm::sort(Bucket.second, Precedes);
230e8d8bef9SDimitry Andric   }
231e8d8bef9SDimitry Andric 
232e8d8bef9SDimitry Andric   // Sort the blocks with respect to dominance.
233e8d8bef9SDimitry Andric   llvm::sort(TmpBB,
234e8d8bef9SDimitry Andric              [this](auto A, auto B) { return MDT.properlyDominates(A, B); });
235e8d8bef9SDimitry Andric 
236e8d8bef9SDimitry Andric   std::vector<NodeId> TmpInst;
237fe6060f1SDimitry Andric   for (MachineBasicBlock *MBB : llvm::reverse(TmpBB)) {
238fe6060f1SDimitry Andric     auto &Bucket = Blocks[MBB];
239e8d8bef9SDimitry Andric     TmpInst.insert(TmpInst.end(), Bucket.rbegin(), Bucket.rend());
240e8d8bef9SDimitry Andric   }
2410946e70aSDimitry Andric 
2420946e70aSDimitry Andric   // The vector is a list of instructions, so that defs coming from
2430946e70aSDimitry Andric   // the same instruction don't need to be artificially ordered.
2440946e70aSDimitry Andric   // Then, when computing the initial segment, and iterating over an
2450946e70aSDimitry Andric   // instruction, pick the defs that contribute to the covering (i.e. is
2460946e70aSDimitry Andric   // not covered by previously added defs). Check the defs individually,
2470946e70aSDimitry Andric   // i.e. first check each def if is covered or not (without adding them
2480946e70aSDimitry Andric   // to the tracking set), and then add all the selected ones.
2490946e70aSDimitry Andric 
2500946e70aSDimitry Andric   // The reason for this is this example:
2510946e70aSDimitry Andric   // *d1<A>, *d2<B>, ... Assume A and B are aliased (can happen in phi nodes).
2520946e70aSDimitry Andric   // *d3<C>              If A \incl BuC, and B \incl AuC, then *d2 would be
2530946e70aSDimitry Andric   //                     covered if we added A first, and A would be covered
2540946e70aSDimitry Andric   //                     if we added B first.
255e8d8bef9SDimitry Andric   // In this example we want both A and B, because we don't want to give
256e8d8bef9SDimitry Andric   // either one priority over the other, since they belong to the same
257e8d8bef9SDimitry Andric   // statement.
2580946e70aSDimitry Andric 
2590946e70aSDimitry Andric   RegisterAggr RRs(DefRRs);
2600946e70aSDimitry Andric 
2610946e70aSDimitry Andric   auto DefInSet = [&Defs](NodeAddr<RefNode *> TA) -> bool {
262*06c3fb27SDimitry Andric     return TA.Addr->getKind() == NodeAttrs::Def && Defs.count(TA.Id);
2630946e70aSDimitry Andric   };
264e8d8bef9SDimitry Andric 
265e8d8bef9SDimitry Andric   for (NodeId T : TmpInst) {
2660946e70aSDimitry Andric     if (!FullChain && RRs.hasCoverOf(RefRR))
2670946e70aSDimitry Andric       break;
2680946e70aSDimitry Andric     auto TA = DFG.addr<InstrNode *>(T);
2690946e70aSDimitry Andric     bool IsPhi = DFG.IsCode<NodeAttrs::Phi>(TA);
2700946e70aSDimitry Andric     NodeList Ds;
2710946e70aSDimitry Andric     for (NodeAddr<DefNode *> DA : TA.Addr->members_if(DefInSet, DFG)) {
2720946e70aSDimitry Andric       RegisterRef QR = DA.Addr->getRegRef(DFG);
2730946e70aSDimitry Andric       // Add phi defs even if they are covered by subsequent defs. This is
2740946e70aSDimitry Andric       // for cases where the reached use is not covered by any of the defs
2750946e70aSDimitry Andric       // encountered so far: the phi def is needed to expose the liveness
2760946e70aSDimitry Andric       // of that use to the entry of the block.
2770946e70aSDimitry Andric       // Example:
2780946e70aSDimitry Andric       //   phi d1<R3>(,d2,), ...  Phi def d1 is covered by d2.
2790946e70aSDimitry Andric       //   d2<R3>(d1,,u3), ...
2800946e70aSDimitry Andric       //   ..., u3<D1>(d2)        This use needs to be live on entry.
2810946e70aSDimitry Andric       if (FullChain || IsPhi || !RRs.hasCoverOf(QR))
2820946e70aSDimitry Andric         Ds.push_back(DA);
2830946e70aSDimitry Andric     }
284e8d8bef9SDimitry Andric     llvm::append_range(RDefs, Ds);
2850946e70aSDimitry Andric     for (NodeAddr<DefNode *> DA : Ds) {
2860946e70aSDimitry Andric       // When collecting a full chain of definitions, do not consider phi
2870946e70aSDimitry Andric       // defs to actually define a register.
2880946e70aSDimitry Andric       uint16_t Flags = DA.Addr->getFlags();
2890946e70aSDimitry Andric       if (!FullChain || !(Flags & NodeAttrs::PhiRef))
2900946e70aSDimitry Andric         if (!(Flags & NodeAttrs::Preserving)) // Don't care about Undef here.
2910946e70aSDimitry Andric           RRs.insert(DA.Addr->getRegRef(DFG));
2920946e70aSDimitry Andric     }
2930946e70aSDimitry Andric   }
2940946e70aSDimitry Andric 
2950946e70aSDimitry Andric   auto DeadP = [](const NodeAddr<DefNode *> DA) -> bool {
2960946e70aSDimitry Andric     return DA.Addr->getFlags() & NodeAttrs::Dead;
2970946e70aSDimitry Andric   };
298e8d8bef9SDimitry Andric   llvm::erase_if(RDefs, DeadP);
2990946e70aSDimitry Andric 
3000946e70aSDimitry Andric   return RDefs;
3010946e70aSDimitry Andric }
3020946e70aSDimitry Andric 
3030946e70aSDimitry Andric std::pair<NodeSet, bool>
getAllReachingDefsRec(RegisterRef RefRR,NodeAddr<RefNode * > RefA,NodeSet & Visited,const NodeSet & Defs)3040946e70aSDimitry Andric Liveness::getAllReachingDefsRec(RegisterRef RefRR, NodeAddr<RefNode *> RefA,
3050946e70aSDimitry Andric                                 NodeSet &Visited, const NodeSet &Defs) {
3060946e70aSDimitry Andric   return getAllReachingDefsRecImpl(RefRR, RefA, Visited, Defs, 0, MaxRecNest);
3070946e70aSDimitry Andric }
3080946e70aSDimitry Andric 
3090946e70aSDimitry Andric std::pair<NodeSet, bool>
getAllReachingDefsRecImpl(RegisterRef RefRR,NodeAddr<RefNode * > RefA,NodeSet & Visited,const NodeSet & Defs,unsigned Nest,unsigned MaxNest)3100946e70aSDimitry Andric Liveness::getAllReachingDefsRecImpl(RegisterRef RefRR, NodeAddr<RefNode *> RefA,
311*06c3fb27SDimitry Andric                                     NodeSet &Visited, const NodeSet &Defs,
312*06c3fb27SDimitry Andric                                     unsigned Nest, unsigned MaxNest) {
3130946e70aSDimitry Andric   if (Nest > MaxNest)
3140946e70aSDimitry Andric     return {NodeSet(), false};
3150946e70aSDimitry Andric   // Collect all defined registers. Do not consider phis to be defining
3160946e70aSDimitry Andric   // anything, only collect "real" definitions.
3170946e70aSDimitry Andric   RegisterAggr DefRRs(PRI);
3180946e70aSDimitry Andric   for (NodeId D : Defs) {
3190946e70aSDimitry Andric     const auto DA = DFG.addr<const DefNode *>(D);
3200946e70aSDimitry Andric     if (!(DA.Addr->getFlags() & NodeAttrs::PhiRef))
3210946e70aSDimitry Andric       DefRRs.insert(DA.Addr->getRegRef(DFG));
3220946e70aSDimitry Andric   }
3230946e70aSDimitry Andric 
3240946e70aSDimitry Andric   NodeList RDs = getAllReachingDefs(RefRR, RefA, false, true, DefRRs);
3250946e70aSDimitry Andric   if (RDs.empty())
3260946e70aSDimitry Andric     return {Defs, true};
3270946e70aSDimitry Andric 
3280946e70aSDimitry Andric   // Make a copy of the preexisting definitions and add the newly found ones.
3290946e70aSDimitry Andric   NodeSet TmpDefs = Defs;
3300946e70aSDimitry Andric   for (NodeAddr<NodeBase *> R : RDs)
3310946e70aSDimitry Andric     TmpDefs.insert(R.Id);
3320946e70aSDimitry Andric 
3330946e70aSDimitry Andric   NodeSet Result = Defs;
3340946e70aSDimitry Andric 
3350946e70aSDimitry Andric   for (NodeAddr<DefNode *> DA : RDs) {
3360946e70aSDimitry Andric     Result.insert(DA.Id);
3370946e70aSDimitry Andric     if (!(DA.Addr->getFlags() & NodeAttrs::PhiRef))
3380946e70aSDimitry Andric       continue;
3390946e70aSDimitry Andric     NodeAddr<PhiNode *> PA = DA.Addr->getOwner(DFG);
34081ad6265SDimitry Andric     if (!Visited.insert(PA.Id).second)
3410946e70aSDimitry Andric       continue;
3420946e70aSDimitry Andric     // Go over all phi uses and get the reaching defs for each use.
3430946e70aSDimitry Andric     for (auto U : PA.Addr->members_if(DFG.IsRef<NodeAttrs::Use>, DFG)) {
3440946e70aSDimitry Andric       const auto &T = getAllReachingDefsRecImpl(RefRR, U, Visited, TmpDefs,
3450946e70aSDimitry Andric                                                 Nest + 1, MaxNest);
3460946e70aSDimitry Andric       if (!T.second)
3470946e70aSDimitry Andric         return {T.first, false};
3480946e70aSDimitry Andric       Result.insert(T.first.begin(), T.first.end());
3490946e70aSDimitry Andric     }
3500946e70aSDimitry Andric   }
3510946e70aSDimitry Andric 
3520946e70aSDimitry Andric   return {Result, true};
3530946e70aSDimitry Andric }
3540946e70aSDimitry Andric 
3550946e70aSDimitry Andric /// Find the nearest ref node aliased to RefRR, going upwards in the data
3560946e70aSDimitry Andric /// flow, starting from the instruction immediately preceding Inst.
getNearestAliasedRef(RegisterRef RefRR,NodeAddr<InstrNode * > IA)3570946e70aSDimitry Andric NodeAddr<RefNode *> Liveness::getNearestAliasedRef(RegisterRef RefRR,
3580946e70aSDimitry Andric                                                    NodeAddr<InstrNode *> IA) {
3590946e70aSDimitry Andric   NodeAddr<BlockNode *> BA = IA.Addr->getOwner(DFG);
3600946e70aSDimitry Andric   NodeList Ins = BA.Addr->members(DFG);
3610946e70aSDimitry Andric   NodeId FindId = IA.Id;
3620946e70aSDimitry Andric   auto E = Ins.rend();
363*06c3fb27SDimitry Andric   auto B =
364*06c3fb27SDimitry Andric       std::find_if(Ins.rbegin(), E, [FindId](const NodeAddr<InstrNode *> T) {
3650946e70aSDimitry Andric         return T.Id == FindId;
3660946e70aSDimitry Andric       });
3670946e70aSDimitry Andric   // Do not scan IA (which is what B would point to).
3680946e70aSDimitry Andric   if (B != E)
3690946e70aSDimitry Andric     ++B;
3700946e70aSDimitry Andric 
3710946e70aSDimitry Andric   do {
3720946e70aSDimitry Andric     // Process the range of instructions from B to E.
3730946e70aSDimitry Andric     for (NodeAddr<InstrNode *> I : make_range(B, E)) {
3740946e70aSDimitry Andric       NodeList Refs = I.Addr->members(DFG);
3750946e70aSDimitry Andric       NodeAddr<RefNode *> Clob, Use;
3760946e70aSDimitry Andric       // Scan all the refs in I aliased to RefRR, and return the one that
3770946e70aSDimitry Andric       // is the closest to the output of I, i.e. def > clobber > use.
3780946e70aSDimitry Andric       for (NodeAddr<RefNode *> R : Refs) {
3790946e70aSDimitry Andric         if (!PRI.alias(R.Addr->getRegRef(DFG), RefRR))
3800946e70aSDimitry Andric           continue;
3810946e70aSDimitry Andric         if (DFG.IsDef(R)) {
3820946e70aSDimitry Andric           // If it's a non-clobbering def, just return it.
3830946e70aSDimitry Andric           if (!(R.Addr->getFlags() & NodeAttrs::Clobbering))
3840946e70aSDimitry Andric             return R;
3850946e70aSDimitry Andric           Clob = R;
3860946e70aSDimitry Andric         } else {
3870946e70aSDimitry Andric           Use = R;
3880946e70aSDimitry Andric         }
3890946e70aSDimitry Andric       }
3900946e70aSDimitry Andric       if (Clob.Id != 0)
3910946e70aSDimitry Andric         return Clob;
3920946e70aSDimitry Andric       if (Use.Id != 0)
3930946e70aSDimitry Andric         return Use;
3940946e70aSDimitry Andric     }
3950946e70aSDimitry Andric 
3960946e70aSDimitry Andric     // Go up to the immediate dominator, if any.
3970946e70aSDimitry Andric     MachineBasicBlock *BB = BA.Addr->getCode();
3980946e70aSDimitry Andric     BA = NodeAddr<BlockNode *>();
3990946e70aSDimitry Andric     if (MachineDomTreeNode *N = MDT.getNode(BB)) {
4000946e70aSDimitry Andric       if ((N = N->getIDom()))
4010946e70aSDimitry Andric         BA = DFG.findBlock(N->getBlock());
4020946e70aSDimitry Andric     }
4030946e70aSDimitry Andric     if (!BA.Id)
4040946e70aSDimitry Andric       break;
4050946e70aSDimitry Andric 
4060946e70aSDimitry Andric     Ins = BA.Addr->members(DFG);
4070946e70aSDimitry Andric     B = Ins.rbegin();
4080946e70aSDimitry Andric     E = Ins.rend();
4090946e70aSDimitry Andric   } while (true);
4100946e70aSDimitry Andric 
4110946e70aSDimitry Andric   return NodeAddr<RefNode *>();
4120946e70aSDimitry Andric }
4130946e70aSDimitry Andric 
getAllReachedUses(RegisterRef RefRR,NodeAddr<DefNode * > DefA,const RegisterAggr & DefRRs)414*06c3fb27SDimitry Andric NodeSet Liveness::getAllReachedUses(RegisterRef RefRR, NodeAddr<DefNode *> DefA,
415*06c3fb27SDimitry Andric                                     const RegisterAggr &DefRRs) {
4160946e70aSDimitry Andric   NodeSet Uses;
4170946e70aSDimitry Andric 
4180946e70aSDimitry Andric   // If the original register is already covered by all the intervening
4190946e70aSDimitry Andric   // defs, no more uses can be reached.
4200946e70aSDimitry Andric   if (DefRRs.hasCoverOf(RefRR))
4210946e70aSDimitry Andric     return Uses;
4220946e70aSDimitry Andric 
4230946e70aSDimitry Andric   // Add all directly reached uses.
4240946e70aSDimitry Andric   // If the def is dead, it does not provide a value for any use.
4250946e70aSDimitry Andric   bool IsDead = DefA.Addr->getFlags() & NodeAttrs::Dead;
4260946e70aSDimitry Andric   NodeId U = !IsDead ? DefA.Addr->getReachedUse() : 0;
4270946e70aSDimitry Andric   while (U != 0) {
4280946e70aSDimitry Andric     auto UA = DFG.addr<UseNode *>(U);
4290946e70aSDimitry Andric     if (!(UA.Addr->getFlags() & NodeAttrs::Undef)) {
4300946e70aSDimitry Andric       RegisterRef UR = UA.Addr->getRegRef(DFG);
4310946e70aSDimitry Andric       if (PRI.alias(RefRR, UR) && !DefRRs.hasCoverOf(UR))
4320946e70aSDimitry Andric         Uses.insert(U);
4330946e70aSDimitry Andric     }
4340946e70aSDimitry Andric     U = UA.Addr->getSibling();
4350946e70aSDimitry Andric   }
4360946e70aSDimitry Andric 
4370946e70aSDimitry Andric   // Traverse all reached defs. This time dead defs cannot be ignored.
4380946e70aSDimitry Andric   for (NodeId D = DefA.Addr->getReachedDef(), NextD; D != 0; D = NextD) {
4390946e70aSDimitry Andric     auto DA = DFG.addr<DefNode *>(D);
4400946e70aSDimitry Andric     NextD = DA.Addr->getSibling();
4410946e70aSDimitry Andric     RegisterRef DR = DA.Addr->getRegRef(DFG);
4420946e70aSDimitry Andric     // If this def is already covered, it cannot reach anything new.
4430946e70aSDimitry Andric     // Similarly, skip it if it is not aliased to the interesting register.
4440946e70aSDimitry Andric     if (DefRRs.hasCoverOf(DR) || !PRI.alias(RefRR, DR))
4450946e70aSDimitry Andric       continue;
4460946e70aSDimitry Andric     NodeSet T;
4470946e70aSDimitry Andric     if (DFG.IsPreservingDef(DA)) {
4480946e70aSDimitry Andric       // If it is a preserving def, do not update the set of intervening defs.
4490946e70aSDimitry Andric       T = getAllReachedUses(RefRR, DA, DefRRs);
4500946e70aSDimitry Andric     } else {
4510946e70aSDimitry Andric       RegisterAggr NewDefRRs = DefRRs;
4520946e70aSDimitry Andric       NewDefRRs.insert(DR);
4530946e70aSDimitry Andric       T = getAllReachedUses(RefRR, DA, NewDefRRs);
4540946e70aSDimitry Andric     }
4550946e70aSDimitry Andric     Uses.insert(T.begin(), T.end());
4560946e70aSDimitry Andric   }
4570946e70aSDimitry Andric   return Uses;
4580946e70aSDimitry Andric }
4590946e70aSDimitry Andric 
computePhiInfo()4600946e70aSDimitry Andric void Liveness::computePhiInfo() {
4610946e70aSDimitry Andric   RealUseMap.clear();
4620946e70aSDimitry Andric 
4630946e70aSDimitry Andric   NodeList Phis;
4640946e70aSDimitry Andric   NodeAddr<FuncNode *> FA = DFG.getFunc();
4650946e70aSDimitry Andric   NodeList Blocks = FA.Addr->members(DFG);
4660946e70aSDimitry Andric   for (NodeAddr<BlockNode *> BA : Blocks) {
4670946e70aSDimitry Andric     auto Ps = BA.Addr->members_if(DFG.IsCode<NodeAttrs::Phi>, DFG);
468e8d8bef9SDimitry Andric     llvm::append_range(Phis, Ps);
4690946e70aSDimitry Andric   }
4700946e70aSDimitry Andric 
4710946e70aSDimitry Andric   // phi use -> (map: reaching phi -> set of registers defined in between)
4720946e70aSDimitry Andric   std::map<NodeId, std::map<NodeId, RegisterAggr>> PhiUp;
4730946e70aSDimitry Andric   std::vector<NodeId> PhiUQ; // Work list of phis for upward propagation.
474*06c3fb27SDimitry Andric   std::unordered_map<NodeId, RegisterAggr>
475*06c3fb27SDimitry Andric       PhiDRs; // Phi -> registers defined by it.
4760946e70aSDimitry Andric 
4770946e70aSDimitry Andric   // Go over all phis.
4780946e70aSDimitry Andric   for (NodeAddr<PhiNode *> PhiA : Phis) {
4790946e70aSDimitry Andric     // Go over all defs and collect the reached uses that are non-phi uses
4800946e70aSDimitry Andric     // (i.e. the "real uses").
4810946e70aSDimitry Andric     RefMap &RealUses = RealUseMap[PhiA.Id];
4820946e70aSDimitry Andric     NodeList PhiRefs = PhiA.Addr->members(DFG);
4830946e70aSDimitry Andric 
4840946e70aSDimitry Andric     // Have a work queue of defs whose reached uses need to be found.
4850946e70aSDimitry Andric     // For each def, add to the queue all reached (non-phi) defs.
4860946e70aSDimitry Andric     SetVector<NodeId> DefQ;
4870946e70aSDimitry Andric     NodeSet PhiDefs;
4880946e70aSDimitry Andric     RegisterAggr DRs(PRI);
4890946e70aSDimitry Andric     for (NodeAddr<RefNode *> R : PhiRefs) {
4900946e70aSDimitry Andric       if (!DFG.IsRef<NodeAttrs::Def>(R))
4910946e70aSDimitry Andric         continue;
4920946e70aSDimitry Andric       DRs.insert(R.Addr->getRegRef(DFG));
4930946e70aSDimitry Andric       DefQ.insert(R.Id);
4940946e70aSDimitry Andric       PhiDefs.insert(R.Id);
4950946e70aSDimitry Andric     }
4960946e70aSDimitry Andric     PhiDRs.insert(std::make_pair(PhiA.Id, DRs));
4970946e70aSDimitry Andric 
4980946e70aSDimitry Andric     // Collect the super-set of all possible reached uses. This set will
4990946e70aSDimitry Andric     // contain all uses reached from this phi, either directly from the
5000946e70aSDimitry Andric     // phi defs, or (recursively) via non-phi defs reached by the phi defs.
5010946e70aSDimitry Andric     // This set of uses will later be trimmed to only contain these uses that
5020946e70aSDimitry Andric     // are actually reached by the phi defs.
5030946e70aSDimitry Andric     for (unsigned i = 0; i < DefQ.size(); ++i) {
5040946e70aSDimitry Andric       NodeAddr<DefNode *> DA = DFG.addr<DefNode *>(DefQ[i]);
5050946e70aSDimitry Andric       // Visit all reached uses. Phi defs should not really have the "dead"
5060946e70aSDimitry Andric       // flag set, but check it anyway for consistency.
5070946e70aSDimitry Andric       bool IsDead = DA.Addr->getFlags() & NodeAttrs::Dead;
5080946e70aSDimitry Andric       NodeId UN = !IsDead ? DA.Addr->getReachedUse() : 0;
5090946e70aSDimitry Andric       while (UN != 0) {
5100946e70aSDimitry Andric         NodeAddr<UseNode *> A = DFG.addr<UseNode *>(UN);
5110946e70aSDimitry Andric         uint16_t F = A.Addr->getFlags();
5120946e70aSDimitry Andric         if ((F & (NodeAttrs::Undef | NodeAttrs::PhiRef)) == 0) {
513e8d8bef9SDimitry Andric           RegisterRef R = A.Addr->getRegRef(DFG);
5140946e70aSDimitry Andric           RealUses[R.Reg].insert({A.Id, R.Mask});
5150946e70aSDimitry Andric         }
5160946e70aSDimitry Andric         UN = A.Addr->getSibling();
5170946e70aSDimitry Andric       }
5180946e70aSDimitry Andric       // Visit all reached defs, and add them to the queue. These defs may
5190946e70aSDimitry Andric       // override some of the uses collected here, but that will be handled
5200946e70aSDimitry Andric       // later.
5210946e70aSDimitry Andric       NodeId DN = DA.Addr->getReachedDef();
5220946e70aSDimitry Andric       while (DN != 0) {
5230946e70aSDimitry Andric         NodeAddr<DefNode *> A = DFG.addr<DefNode *>(DN);
5240946e70aSDimitry Andric         for (auto T : DFG.getRelatedRefs(A.Addr->getOwner(DFG), A)) {
5250946e70aSDimitry Andric           uint16_t Flags = NodeAddr<DefNode *>(T).Addr->getFlags();
5260946e70aSDimitry Andric           // Must traverse the reached-def chain. Consider:
5270946e70aSDimitry Andric           //   def(D0) -> def(R0) -> def(R0) -> use(D0)
5280946e70aSDimitry Andric           // The reachable use of D0 passes through a def of R0.
5290946e70aSDimitry Andric           if (!(Flags & NodeAttrs::PhiRef))
5300946e70aSDimitry Andric             DefQ.insert(T.Id);
5310946e70aSDimitry Andric         }
5320946e70aSDimitry Andric         DN = A.Addr->getSibling();
5330946e70aSDimitry Andric       }
5340946e70aSDimitry Andric     }
5350946e70aSDimitry Andric     // Filter out these uses that appear to be reachable, but really
5360946e70aSDimitry Andric     // are not. For example:
5370946e70aSDimitry Andric     //
5380946e70aSDimitry Andric     // R1:0 =          d1
5390946e70aSDimitry Andric     //      = R1:0     u2     Reached by d1.
5400946e70aSDimitry Andric     //   R0 =          d3
5410946e70aSDimitry Andric     //      = R1:0     u4     Still reached by d1: indirectly through
5420946e70aSDimitry Andric     //                        the def d3.
5430946e70aSDimitry Andric     //   R1 =          d5
5440946e70aSDimitry Andric     //      = R1:0     u6     Not reached by d1 (covered collectively
5450946e70aSDimitry Andric     //                        by d3 and d5), but following reached
5460946e70aSDimitry Andric     //                        defs and uses from d1 will lead here.
5470946e70aSDimitry Andric     for (auto UI = RealUses.begin(), UE = RealUses.end(); UI != UE;) {
5480946e70aSDimitry Andric       // For each reached register UI->first, there is a set UI->second, of
5490946e70aSDimitry Andric       // uses of it. For each such use, check if it is reached by this phi,
5500946e70aSDimitry Andric       // i.e. check if the set of its reaching uses intersects the set of
5510946e70aSDimitry Andric       // this phi's defs.
5520946e70aSDimitry Andric       NodeRefSet Uses = UI->second;
5530946e70aSDimitry Andric       UI->second.clear();
5540946e70aSDimitry Andric       for (std::pair<NodeId, LaneBitmask> I : Uses) {
5550946e70aSDimitry Andric         auto UA = DFG.addr<UseNode *>(I.first);
5560946e70aSDimitry Andric         // Undef flag is checked above.
5570946e70aSDimitry Andric         assert((UA.Addr->getFlags() & NodeAttrs::Undef) == 0);
558*06c3fb27SDimitry Andric         RegisterRef UseR(UI->first, I.second); // Ref from Uses
559*06c3fb27SDimitry Andric         // R = intersection of the ref from the phi and the ref from Uses
560*06c3fb27SDimitry Andric         RegisterRef R = PhiDRs.at(PhiA.Id).intersectWith(UseR);
561*06c3fb27SDimitry Andric         if (!R)
562*06c3fb27SDimitry Andric           continue;
5630946e70aSDimitry Andric         // Calculate the exposed part of the reached use.
5640946e70aSDimitry Andric         RegisterAggr Covered(PRI);
5650946e70aSDimitry Andric         for (NodeAddr<DefNode *> DA : getAllReachingDefs(R, UA)) {
5660946e70aSDimitry Andric           if (PhiDefs.count(DA.Id))
5670946e70aSDimitry Andric             break;
5680946e70aSDimitry Andric           Covered.insert(DA.Addr->getRegRef(DFG));
5690946e70aSDimitry Andric         }
5700946e70aSDimitry Andric         if (RegisterRef RC = Covered.clearIn(R)) {
5710946e70aSDimitry Andric           // We are updating the map for register UI->first, so we need
5720946e70aSDimitry Andric           // to map RC to be expressed in terms of that register.
5730946e70aSDimitry Andric           RegisterRef S = PRI.mapTo(RC, UI->first);
5740946e70aSDimitry Andric           UI->second.insert({I.first, S.Mask});
5750946e70aSDimitry Andric         }
5760946e70aSDimitry Andric       }
5770946e70aSDimitry Andric       UI = UI->second.empty() ? RealUses.erase(UI) : std::next(UI);
5780946e70aSDimitry Andric     }
5790946e70aSDimitry Andric 
5800946e70aSDimitry Andric     // If this phi reaches some "real" uses, add it to the queue for upward
5810946e70aSDimitry Andric     // propagation.
5820946e70aSDimitry Andric     if (!RealUses.empty())
5830946e70aSDimitry Andric       PhiUQ.push_back(PhiA.Id);
5840946e70aSDimitry Andric 
5850946e70aSDimitry Andric     // Go over all phi uses and check if the reaching def is another phi.
5860946e70aSDimitry Andric     // Collect the phis that are among the reaching defs of these uses.
5870946e70aSDimitry Andric     // While traversing the list of reaching defs for each phi use, accumulate
5880946e70aSDimitry Andric     // the set of registers defined between this phi (PhiA) and the owner phi
5890946e70aSDimitry Andric     // of the reaching def.
5900946e70aSDimitry Andric     NodeSet SeenUses;
5910946e70aSDimitry Andric 
5920946e70aSDimitry Andric     for (auto I : PhiRefs) {
5930946e70aSDimitry Andric       if (!DFG.IsRef<NodeAttrs::Use>(I) || SeenUses.count(I.Id))
5940946e70aSDimitry Andric         continue;
5950946e70aSDimitry Andric       NodeAddr<PhiUseNode *> PUA = I;
5960946e70aSDimitry Andric       if (PUA.Addr->getReachingDef() == 0)
5970946e70aSDimitry Andric         continue;
5980946e70aSDimitry Andric 
5990946e70aSDimitry Andric       RegisterRef UR = PUA.Addr->getRegRef(DFG);
6000946e70aSDimitry Andric       NodeList Ds = getAllReachingDefs(UR, PUA, true, false, NoRegs);
6010946e70aSDimitry Andric       RegisterAggr DefRRs(PRI);
6020946e70aSDimitry Andric 
6030946e70aSDimitry Andric       for (NodeAddr<DefNode *> D : Ds) {
6040946e70aSDimitry Andric         if (D.Addr->getFlags() & NodeAttrs::PhiRef) {
6050946e70aSDimitry Andric           NodeId RP = D.Addr->getOwner(DFG).Id;
6060946e70aSDimitry Andric           std::map<NodeId, RegisterAggr> &M = PhiUp[PUA.Id];
6070946e70aSDimitry Andric           auto F = M.find(RP);
6080946e70aSDimitry Andric           if (F == M.end())
6090946e70aSDimitry Andric             M.insert(std::make_pair(RP, DefRRs));
6100946e70aSDimitry Andric           else
6110946e70aSDimitry Andric             F->second.insert(DefRRs);
6120946e70aSDimitry Andric         }
6130946e70aSDimitry Andric         DefRRs.insert(D.Addr->getRegRef(DFG));
6140946e70aSDimitry Andric       }
6150946e70aSDimitry Andric 
6160946e70aSDimitry Andric       for (NodeAddr<PhiUseNode *> T : DFG.getRelatedRefs(PhiA, PUA))
6170946e70aSDimitry Andric         SeenUses.insert(T.Id);
6180946e70aSDimitry Andric     }
6190946e70aSDimitry Andric   }
6200946e70aSDimitry Andric 
6210946e70aSDimitry Andric   if (Trace) {
6220946e70aSDimitry Andric     dbgs() << "Phi-up-to-phi map with intervening defs:\n";
6230946e70aSDimitry Andric     for (auto I : PhiUp) {
624bdd1243dSDimitry Andric       dbgs() << "phi " << Print(I.first, DFG) << " -> {";
6250946e70aSDimitry Andric       for (auto R : I.second)
626bdd1243dSDimitry Andric         dbgs() << ' ' << Print(R.first, DFG) << Print(R.second, DFG);
6270946e70aSDimitry Andric       dbgs() << " }\n";
6280946e70aSDimitry Andric     }
6290946e70aSDimitry Andric   }
6300946e70aSDimitry Andric 
6310946e70aSDimitry Andric   // Propagate the reached registers up in the phi chain.
6320946e70aSDimitry Andric   //
6330946e70aSDimitry Andric   // The following type of situation needs careful handling:
6340946e70aSDimitry Andric   //
6350946e70aSDimitry Andric   //   phi d1<R1:0>  (1)
6360946e70aSDimitry Andric   //        |
6370946e70aSDimitry Andric   //   ... d2<R1>
6380946e70aSDimitry Andric   //        |
6390946e70aSDimitry Andric   //   phi u3<R1:0>  (2)
6400946e70aSDimitry Andric   //        |
6410946e70aSDimitry Andric   //   ... u4<R1>
6420946e70aSDimitry Andric   //
6430946e70aSDimitry Andric   // The phi node (2) defines a register pair R1:0, and reaches a "real"
6440946e70aSDimitry Andric   // use u4 of just R1. The same phi node is also known to reach (upwards)
6450946e70aSDimitry Andric   // the phi node (1). However, the use u4 is not reached by phi (1),
6460946e70aSDimitry Andric   // because of the intervening definition d2 of R1. The data flow between
6470946e70aSDimitry Andric   // phis (1) and (2) is restricted to R1:0 minus R1, i.e. R0.
6480946e70aSDimitry Andric   //
6490946e70aSDimitry Andric   // When propagating uses up the phi chains, get the all reaching defs
6500946e70aSDimitry Andric   // for a given phi use, and traverse the list until the propagated ref
6510946e70aSDimitry Andric   // is covered, or until reaching the final phi. Only assume that the
6520946e70aSDimitry Andric   // reference reaches the phi in the latter case.
6530946e70aSDimitry Andric 
654e8d8bef9SDimitry Andric   // The operation "clearIn" can be expensive. For a given set of intervening
655e8d8bef9SDimitry Andric   // defs, cache the result of subtracting these defs from a given register
656e8d8bef9SDimitry Andric   // ref.
657*06c3fb27SDimitry Andric   using RefHash = std::hash<RegisterRef>;
658*06c3fb27SDimitry Andric   using RefEqual = std::equal_to<RegisterRef>;
659e8d8bef9SDimitry Andric   using SubMap = std::unordered_map<RegisterRef, RegisterRef>;
660e8d8bef9SDimitry Andric   std::unordered_map<RegisterAggr, SubMap> Subs;
661e8d8bef9SDimitry Andric   auto ClearIn = [](RegisterRef RR, const RegisterAggr &Mid, SubMap &SM) {
662e8d8bef9SDimitry Andric     if (Mid.empty())
663e8d8bef9SDimitry Andric       return RR;
664e8d8bef9SDimitry Andric     auto F = SM.find(RR);
665e8d8bef9SDimitry Andric     if (F != SM.end())
666e8d8bef9SDimitry Andric       return F->second;
667e8d8bef9SDimitry Andric     RegisterRef S = Mid.clearIn(RR);
668e8d8bef9SDimitry Andric     SM.insert({RR, S});
669e8d8bef9SDimitry Andric     return S;
670e8d8bef9SDimitry Andric   };
671e8d8bef9SDimitry Andric 
672e8d8bef9SDimitry Andric   // Go over all phis.
6730946e70aSDimitry Andric   for (unsigned i = 0; i < PhiUQ.size(); ++i) {
6740946e70aSDimitry Andric     auto PA = DFG.addr<PhiNode *>(PhiUQ[i]);
6750946e70aSDimitry Andric     NodeList PUs = PA.Addr->members_if(DFG.IsRef<NodeAttrs::Use>, DFG);
6760946e70aSDimitry Andric     RefMap &RUM = RealUseMap[PA.Id];
6770946e70aSDimitry Andric 
6780946e70aSDimitry Andric     for (NodeAddr<UseNode *> UA : PUs) {
6790946e70aSDimitry Andric       std::map<NodeId, RegisterAggr> &PUM = PhiUp[UA.Id];
680e8d8bef9SDimitry Andric       RegisterRef UR = UA.Addr->getRegRef(DFG);
6810946e70aSDimitry Andric       for (const std::pair<const NodeId, RegisterAggr> &P : PUM) {
6820946e70aSDimitry Andric         bool Changed = false;
6830946e70aSDimitry Andric         const RegisterAggr &MidDefs = P.second;
6840946e70aSDimitry Andric         // Collect the set PropUp of uses that are reached by the current
6850946e70aSDimitry Andric         // phi PA, and are not covered by any intervening def between the
6860946e70aSDimitry Andric         // currently visited use UA and the upward phi P.
6870946e70aSDimitry Andric 
6880946e70aSDimitry Andric         if (MidDefs.hasCoverOf(UR))
6890946e70aSDimitry Andric           continue;
690*06c3fb27SDimitry Andric         if (Subs.find(MidDefs) == Subs.end()) {
691*06c3fb27SDimitry Andric           Subs.insert({MidDefs, SubMap(1, RefHash(), RefEqual(PRI))});
692*06c3fb27SDimitry Andric         }
693*06c3fb27SDimitry Andric         SubMap &SM = Subs.at(MidDefs);
6940946e70aSDimitry Andric 
6950946e70aSDimitry Andric         // General algorithm:
6960946e70aSDimitry Andric         //   for each (R,U) : U is use node of R, U is reached by PA
6970946e70aSDimitry Andric         //     if MidDefs does not cover (R,U)
6980946e70aSDimitry Andric         //       then add (R-MidDefs,U) to RealUseMap[P]
6990946e70aSDimitry Andric         //
7000946e70aSDimitry Andric         for (const std::pair<const RegisterId, NodeRefSet> &T : RUM) {
7010946e70aSDimitry Andric           RegisterRef R(T.first);
7020946e70aSDimitry Andric           // The current phi (PA) could be a phi for a regmask. It could
7030946e70aSDimitry Andric           // reach a whole variety of uses that are not related to the
7040946e70aSDimitry Andric           // specific upward phi (P.first).
7050946e70aSDimitry Andric           const RegisterAggr &DRs = PhiDRs.at(P.first);
7060946e70aSDimitry Andric           if (!DRs.hasAliasOf(R))
7070946e70aSDimitry Andric             continue;
7080946e70aSDimitry Andric           R = PRI.mapTo(DRs.intersectWith(R), T.first);
7090946e70aSDimitry Andric           for (std::pair<NodeId, LaneBitmask> V : T.second) {
7100946e70aSDimitry Andric             LaneBitmask M = R.Mask & V.second;
7110946e70aSDimitry Andric             if (M.none())
7120946e70aSDimitry Andric               continue;
713e8d8bef9SDimitry Andric             if (RegisterRef SS = ClearIn(RegisterRef(R.Reg, M), MidDefs, SM)) {
7140946e70aSDimitry Andric               NodeRefSet &RS = RealUseMap[P.first][SS.Reg];
7150946e70aSDimitry Andric               Changed |= RS.insert({V.first, SS.Mask}).second;
7160946e70aSDimitry Andric             }
7170946e70aSDimitry Andric           }
7180946e70aSDimitry Andric         }
7190946e70aSDimitry Andric 
7200946e70aSDimitry Andric         if (Changed)
7210946e70aSDimitry Andric           PhiUQ.push_back(P.first);
7220946e70aSDimitry Andric       }
7230946e70aSDimitry Andric     }
7240946e70aSDimitry Andric   }
7250946e70aSDimitry Andric 
7260946e70aSDimitry Andric   if (Trace) {
7270946e70aSDimitry Andric     dbgs() << "Real use map:\n";
7280946e70aSDimitry Andric     for (auto I : RealUseMap) {
729bdd1243dSDimitry Andric       dbgs() << "phi " << Print(I.first, DFG);
7300946e70aSDimitry Andric       NodeAddr<PhiNode *> PA = DFG.addr<PhiNode *>(I.first);
7310946e70aSDimitry Andric       NodeList Ds = PA.Addr->members_if(DFG.IsRef<NodeAttrs::Def>, DFG);
7320946e70aSDimitry Andric       if (!Ds.empty()) {
7330946e70aSDimitry Andric         RegisterRef RR = NodeAddr<DefNode *>(Ds[0]).Addr->getRegRef(DFG);
734bdd1243dSDimitry Andric         dbgs() << '<' << Print(RR, DFG) << '>';
7350946e70aSDimitry Andric       } else {
7360946e70aSDimitry Andric         dbgs() << "<noreg>";
7370946e70aSDimitry Andric       }
738bdd1243dSDimitry Andric       dbgs() << " -> " << Print(I.second, DFG) << '\n';
7390946e70aSDimitry Andric     }
7400946e70aSDimitry Andric   }
7410946e70aSDimitry Andric }
7420946e70aSDimitry Andric 
computeLiveIns()7430946e70aSDimitry Andric void Liveness::computeLiveIns() {
7440946e70aSDimitry Andric   // Populate the node-to-block map. This speeds up the calculations
7450946e70aSDimitry Andric   // significantly.
7460946e70aSDimitry Andric   NBMap.clear();
7470946e70aSDimitry Andric   for (NodeAddr<BlockNode *> BA : DFG.getFunc().Addr->members(DFG)) {
7480946e70aSDimitry Andric     MachineBasicBlock *BB = BA.Addr->getCode();
7490946e70aSDimitry Andric     for (NodeAddr<InstrNode *> IA : BA.Addr->members(DFG)) {
7500946e70aSDimitry Andric       for (NodeAddr<RefNode *> RA : IA.Addr->members(DFG))
7510946e70aSDimitry Andric         NBMap.insert(std::make_pair(RA.Id, BB));
7520946e70aSDimitry Andric       NBMap.insert(std::make_pair(IA.Id, BB));
7530946e70aSDimitry Andric     }
7540946e70aSDimitry Andric   }
7550946e70aSDimitry Andric 
7560946e70aSDimitry Andric   MachineFunction &MF = DFG.getMF();
7570946e70aSDimitry Andric 
7580946e70aSDimitry Andric   // Compute IDF first, then the inverse.
7590946e70aSDimitry Andric   decltype(IIDF) IDF;
7600946e70aSDimitry Andric   for (MachineBasicBlock &B : MF) {
7610946e70aSDimitry Andric     auto F1 = MDF.find(&B);
7620946e70aSDimitry Andric     if (F1 == MDF.end())
7630946e70aSDimitry Andric       continue;
7640946e70aSDimitry Andric     SetVector<MachineBasicBlock *> IDFB(F1->second.begin(), F1->second.end());
7650946e70aSDimitry Andric     for (unsigned i = 0; i < IDFB.size(); ++i) {
7660946e70aSDimitry Andric       auto F2 = MDF.find(IDFB[i]);
7670946e70aSDimitry Andric       if (F2 != MDF.end())
7680946e70aSDimitry Andric         IDFB.insert(F2->second.begin(), F2->second.end());
7690946e70aSDimitry Andric     }
7700946e70aSDimitry Andric     // Add B to the IDF(B). This will put B in the IIDF(B).
7710946e70aSDimitry Andric     IDFB.insert(&B);
7720946e70aSDimitry Andric     IDF[&B].insert(IDFB.begin(), IDFB.end());
7730946e70aSDimitry Andric   }
7740946e70aSDimitry Andric 
7750946e70aSDimitry Andric   for (auto I : IDF)
776fcaf7f86SDimitry Andric     for (auto *S : I.second)
7770946e70aSDimitry Andric       IIDF[S].insert(I.first);
7780946e70aSDimitry Andric 
7790946e70aSDimitry Andric   computePhiInfo();
7800946e70aSDimitry Andric 
7810946e70aSDimitry Andric   NodeAddr<FuncNode *> FA = DFG.getFunc();
7820946e70aSDimitry Andric   NodeList Blocks = FA.Addr->members(DFG);
7830946e70aSDimitry Andric 
7840946e70aSDimitry Andric   // Build the phi live-on-entry map.
7850946e70aSDimitry Andric   for (NodeAddr<BlockNode *> BA : Blocks) {
7860946e70aSDimitry Andric     MachineBasicBlock *MB = BA.Addr->getCode();
7870946e70aSDimitry Andric     RefMap &LON = PhiLON[MB];
788*06c3fb27SDimitry Andric     for (auto P : BA.Addr->members_if(DFG.IsCode<NodeAttrs::Phi>, DFG)) {
7890946e70aSDimitry Andric       for (const RefMap::value_type &S : RealUseMap[P.Id])
7900946e70aSDimitry Andric         LON[S.first].insert(S.second.begin(), S.second.end());
7910946e70aSDimitry Andric     }
792*06c3fb27SDimitry Andric   }
7930946e70aSDimitry Andric 
7940946e70aSDimitry Andric   if (Trace) {
7950946e70aSDimitry Andric     dbgs() << "Phi live-on-entry map:\n";
7960946e70aSDimitry Andric     for (auto &I : PhiLON)
7970946e70aSDimitry Andric       dbgs() << "block #" << I.first->getNumber() << " -> "
798bdd1243dSDimitry Andric              << Print(I.second, DFG) << '\n';
7990946e70aSDimitry Andric   }
8000946e70aSDimitry Andric 
8010946e70aSDimitry Andric   // Build the phi live-on-exit map. Each phi node has some set of reached
8020946e70aSDimitry Andric   // "real" uses. Propagate this set backwards into the block predecessors
8030946e70aSDimitry Andric   // through the reaching defs of the corresponding phi uses.
8040946e70aSDimitry Andric   for (NodeAddr<BlockNode *> BA : Blocks) {
8050946e70aSDimitry Andric     NodeList Phis = BA.Addr->members_if(DFG.IsCode<NodeAttrs::Phi>, DFG);
8060946e70aSDimitry Andric     for (NodeAddr<PhiNode *> PA : Phis) {
8070946e70aSDimitry Andric       RefMap &RUs = RealUseMap[PA.Id];
8080946e70aSDimitry Andric       if (RUs.empty())
8090946e70aSDimitry Andric         continue;
8100946e70aSDimitry Andric 
8110946e70aSDimitry Andric       NodeSet SeenUses;
8120946e70aSDimitry Andric       for (auto U : PA.Addr->members_if(DFG.IsRef<NodeAttrs::Use>, DFG)) {
8130946e70aSDimitry Andric         if (!SeenUses.insert(U.Id).second)
8140946e70aSDimitry Andric           continue;
8150946e70aSDimitry Andric         NodeAddr<PhiUseNode *> PUA = U;
8160946e70aSDimitry Andric         if (PUA.Addr->getReachingDef() == 0)
8170946e70aSDimitry Andric           continue;
8180946e70aSDimitry Andric 
8190946e70aSDimitry Andric         // Each phi has some set (possibly empty) of reached "real" uses,
8200946e70aSDimitry Andric         // that is, uses that are part of the compiled program. Such a use
8210946e70aSDimitry Andric         // may be located in some farther block, but following a chain of
8220946e70aSDimitry Andric         // reaching defs will eventually lead to this phi.
8230946e70aSDimitry Andric         // Any chain of reaching defs may fork at a phi node, but there
8240946e70aSDimitry Andric         // will be a path upwards that will lead to this phi. Now, this
8250946e70aSDimitry Andric         // chain will need to fork at this phi, since some of the reached
8260946e70aSDimitry Andric         // uses may have definitions joining in from multiple predecessors.
8270946e70aSDimitry Andric         // For each reached "real" use, identify the set of reaching defs
8280946e70aSDimitry Andric         // coming from each predecessor P, and add them to PhiLOX[P].
8290946e70aSDimitry Andric         //
8300946e70aSDimitry Andric         auto PrA = DFG.addr<BlockNode *>(PUA.Addr->getPredecessor());
8310946e70aSDimitry Andric         RefMap &LOX = PhiLOX[PrA.Addr->getCode()];
8320946e70aSDimitry Andric 
8330946e70aSDimitry Andric         for (const std::pair<const RegisterId, NodeRefSet> &RS : RUs) {
8340946e70aSDimitry Andric           // We need to visit each individual use.
8350946e70aSDimitry Andric           for (std::pair<NodeId, LaneBitmask> P : RS.second) {
8360946e70aSDimitry Andric             // Create a register ref corresponding to the use, and find
8370946e70aSDimitry Andric             // all reaching defs starting from the phi use, and treating
8380946e70aSDimitry Andric             // all related shadows as a single use cluster.
8390946e70aSDimitry Andric             RegisterRef S(RS.first, P.second);
8400946e70aSDimitry Andric             NodeList Ds = getAllReachingDefs(S, PUA, true, false, NoRegs);
8410946e70aSDimitry Andric             for (NodeAddr<DefNode *> D : Ds) {
8420946e70aSDimitry Andric               // Calculate the mask corresponding to the visited def.
8430946e70aSDimitry Andric               RegisterAggr TA(PRI);
8440946e70aSDimitry Andric               TA.insert(D.Addr->getRegRef(DFG)).intersect(S);
8450946e70aSDimitry Andric               LaneBitmask TM = TA.makeRegRef().Mask;
8460946e70aSDimitry Andric               LOX[S.Reg].insert({D.Id, TM});
8470946e70aSDimitry Andric             }
8480946e70aSDimitry Andric           }
8490946e70aSDimitry Andric         }
8500946e70aSDimitry Andric 
8510946e70aSDimitry Andric         for (NodeAddr<PhiUseNode *> T : DFG.getRelatedRefs(PA, PUA))
8520946e70aSDimitry Andric           SeenUses.insert(T.Id);
8530946e70aSDimitry Andric       } // for U : phi uses
8540946e70aSDimitry Andric     }   // for P : Phis
8550946e70aSDimitry Andric   }     // for B : Blocks
8560946e70aSDimitry Andric 
8570946e70aSDimitry Andric   if (Trace) {
8580946e70aSDimitry Andric     dbgs() << "Phi live-on-exit map:\n";
8590946e70aSDimitry Andric     for (auto &I : PhiLOX)
8600946e70aSDimitry Andric       dbgs() << "block #" << I.first->getNumber() << " -> "
861bdd1243dSDimitry Andric              << Print(I.second, DFG) << '\n';
8620946e70aSDimitry Andric   }
8630946e70aSDimitry Andric 
8640946e70aSDimitry Andric   RefMap LiveIn;
8650946e70aSDimitry Andric   traverse(&MF.front(), LiveIn);
8660946e70aSDimitry Andric 
8670946e70aSDimitry Andric   // Add function live-ins to the live-in set of the function entry block.
8680946e70aSDimitry Andric   LiveMap[&MF.front()].insert(DFG.getLiveIns());
8690946e70aSDimitry Andric 
8700946e70aSDimitry Andric   if (Trace) {
8710946e70aSDimitry Andric     // Dump the liveness map
8720946e70aSDimitry Andric     for (MachineBasicBlock &B : MF) {
8730946e70aSDimitry Andric       std::vector<RegisterRef> LV;
874fe6060f1SDimitry Andric       for (const MachineBasicBlock::RegisterMaskPair &LI : B.liveins())
875fe6060f1SDimitry Andric         LV.push_back(RegisterRef(LI.PhysReg, LI.LaneMask));
876*06c3fb27SDimitry Andric       llvm::sort(LV, std::less<RegisterRef>(PRI));
8770946e70aSDimitry Andric       dbgs() << printMBBReference(B) << "\t rec = {";
8780946e70aSDimitry Andric       for (auto I : LV)
879bdd1243dSDimitry Andric         dbgs() << ' ' << Print(I, DFG);
8800946e70aSDimitry Andric       dbgs() << " }\n";
881bdd1243dSDimitry Andric       // dbgs() << "\tcomp = " << Print(LiveMap[&B], DFG) << '\n';
8820946e70aSDimitry Andric 
8830946e70aSDimitry Andric       LV.clear();
884*06c3fb27SDimitry Andric       for (RegisterRef RR : LiveMap[&B].refs())
885*06c3fb27SDimitry Andric         LV.push_back(RR);
886*06c3fb27SDimitry Andric       llvm::sort(LV, std::less<RegisterRef>(PRI));
8870946e70aSDimitry Andric       dbgs() << "\tcomp = {";
8880946e70aSDimitry Andric       for (auto I : LV)
889bdd1243dSDimitry Andric         dbgs() << ' ' << Print(I, DFG);
8900946e70aSDimitry Andric       dbgs() << " }\n";
8910946e70aSDimitry Andric     }
8920946e70aSDimitry Andric   }
8930946e70aSDimitry Andric }
8940946e70aSDimitry Andric 
resetLiveIns()8950946e70aSDimitry Andric void Liveness::resetLiveIns() {
8960946e70aSDimitry Andric   for (auto &B : DFG.getMF()) {
8970946e70aSDimitry Andric     // Remove all live-ins.
8980946e70aSDimitry Andric     std::vector<unsigned> T;
899fe6060f1SDimitry Andric     for (const MachineBasicBlock::RegisterMaskPair &LI : B.liveins())
900fe6060f1SDimitry Andric       T.push_back(LI.PhysReg);
9010946e70aSDimitry Andric     for (auto I : T)
9020946e70aSDimitry Andric       B.removeLiveIn(I);
9030946e70aSDimitry Andric     // Add the newly computed live-ins.
9040946e70aSDimitry Andric     const RegisterAggr &LiveIns = LiveMap[&B];
905*06c3fb27SDimitry Andric     for (RegisterRef R : LiveIns.refs())
9060946e70aSDimitry Andric       B.addLiveIn({MCPhysReg(R.Reg), R.Mask});
9070946e70aSDimitry Andric   }
9080946e70aSDimitry Andric }
9090946e70aSDimitry Andric 
resetKills()9100946e70aSDimitry Andric void Liveness::resetKills() {
9110946e70aSDimitry Andric   for (auto &B : DFG.getMF())
9120946e70aSDimitry Andric     resetKills(&B);
9130946e70aSDimitry Andric }
9140946e70aSDimitry Andric 
resetKills(MachineBasicBlock * B)9150946e70aSDimitry Andric void Liveness::resetKills(MachineBasicBlock *B) {
9160946e70aSDimitry Andric   auto CopyLiveIns = [this](MachineBasicBlock *B, BitVector &LV) -> void {
9170946e70aSDimitry Andric     for (auto I : B->liveins()) {
9180946e70aSDimitry Andric       MCSubRegIndexIterator S(I.PhysReg, &TRI);
9190946e70aSDimitry Andric       if (!S.isValid()) {
9200946e70aSDimitry Andric         LV.set(I.PhysReg);
9210946e70aSDimitry Andric         continue;
9220946e70aSDimitry Andric       }
9230946e70aSDimitry Andric       do {
9240946e70aSDimitry Andric         LaneBitmask M = TRI.getSubRegIndexLaneMask(S.getSubRegIndex());
9250946e70aSDimitry Andric         if ((M & I.LaneMask).any())
9260946e70aSDimitry Andric           LV.set(S.getSubReg());
9270946e70aSDimitry Andric         ++S;
9280946e70aSDimitry Andric       } while (S.isValid());
9290946e70aSDimitry Andric     }
9300946e70aSDimitry Andric   };
9310946e70aSDimitry Andric 
9320946e70aSDimitry Andric   BitVector LiveIn(TRI.getNumRegs()), Live(TRI.getNumRegs());
9330946e70aSDimitry Andric   CopyLiveIns(B, LiveIn);
934fcaf7f86SDimitry Andric   for (auto *SI : B->successors())
9350946e70aSDimitry Andric     CopyLiveIns(SI, Live);
9360946e70aSDimitry Andric 
937fe6060f1SDimitry Andric   for (MachineInstr &MI : llvm::reverse(*B)) {
938fe6060f1SDimitry Andric     if (MI.isDebugInstr())
9390946e70aSDimitry Andric       continue;
9400946e70aSDimitry Andric 
941fe6060f1SDimitry Andric     MI.clearKillInfo();
942*06c3fb27SDimitry Andric     for (auto &Op : MI.all_defs()) {
9430946e70aSDimitry Andric       // An implicit def of a super-register may not necessarily start a
9440946e70aSDimitry Andric       // live range of it, since an implicit use could be used to keep parts
9450946e70aSDimitry Andric       // of it live. Instead of analyzing the implicit operands, ignore
9460946e70aSDimitry Andric       // implicit defs.
947*06c3fb27SDimitry Andric       if (Op.isImplicit())
9480946e70aSDimitry Andric         continue;
9490946e70aSDimitry Andric       Register R = Op.getReg();
950bdd1243dSDimitry Andric       if (!R.isPhysical())
9510946e70aSDimitry Andric         continue;
952*06c3fb27SDimitry Andric       for (MCPhysReg SR : TRI.subregs_inclusive(R))
953*06c3fb27SDimitry Andric         Live.reset(SR);
9540946e70aSDimitry Andric     }
955*06c3fb27SDimitry Andric     for (auto &Op : MI.all_uses()) {
956*06c3fb27SDimitry Andric       if (Op.isUndef())
9570946e70aSDimitry Andric         continue;
9580946e70aSDimitry Andric       Register R = Op.getReg();
959bdd1243dSDimitry Andric       if (!R.isPhysical())
9600946e70aSDimitry Andric         continue;
9610946e70aSDimitry Andric       bool IsLive = false;
9620946e70aSDimitry Andric       for (MCRegAliasIterator AR(R, &TRI, true); AR.isValid(); ++AR) {
9630946e70aSDimitry Andric         if (!Live[*AR])
9640946e70aSDimitry Andric           continue;
9650946e70aSDimitry Andric         IsLive = true;
9660946e70aSDimitry Andric         break;
9670946e70aSDimitry Andric       }
9680946e70aSDimitry Andric       if (!IsLive)
9690946e70aSDimitry Andric         Op.setIsKill(true);
970*06c3fb27SDimitry Andric       for (MCPhysReg SR : TRI.subregs_inclusive(R))
971*06c3fb27SDimitry Andric         Live.set(SR);
9720946e70aSDimitry Andric     }
9730946e70aSDimitry Andric   }
9740946e70aSDimitry Andric }
9750946e70aSDimitry Andric 
9760946e70aSDimitry Andric // Helper function to obtain the basic block containing the reaching def
9770946e70aSDimitry Andric // of the given use.
getBlockWithRef(NodeId RN) const9780946e70aSDimitry Andric MachineBasicBlock *Liveness::getBlockWithRef(NodeId RN) const {
9790946e70aSDimitry Andric   auto F = NBMap.find(RN);
9800946e70aSDimitry Andric   if (F != NBMap.end())
9810946e70aSDimitry Andric     return F->second;
9820946e70aSDimitry Andric   llvm_unreachable("Node id not in map");
9830946e70aSDimitry Andric }
9840946e70aSDimitry Andric 
traverse(MachineBasicBlock * B,RefMap & LiveIn)9850946e70aSDimitry Andric void Liveness::traverse(MachineBasicBlock *B, RefMap &LiveIn) {
9860946e70aSDimitry Andric   // The LiveIn map, for each (physical) register, contains the set of live
9870946e70aSDimitry Andric   // reaching defs of that register that are live on entry to the associated
9880946e70aSDimitry Andric   // block.
9890946e70aSDimitry Andric 
9900946e70aSDimitry Andric   // The summary of the traversal algorithm:
9910946e70aSDimitry Andric   //
9920946e70aSDimitry Andric   // R is live-in in B, if there exists a U(R), such that rdef(R) dom B
9930946e70aSDimitry Andric   // and (U \in IDF(B) or B dom U).
9940946e70aSDimitry Andric   //
9950946e70aSDimitry Andric   // for (C : children) {
9960946e70aSDimitry Andric   //   LU = {}
9970946e70aSDimitry Andric   //   traverse(C, LU)
9980946e70aSDimitry Andric   //   LiveUses += LU
9990946e70aSDimitry Andric   // }
10000946e70aSDimitry Andric   //
10010946e70aSDimitry Andric   // LiveUses -= Defs(B);
10020946e70aSDimitry Andric   // LiveUses += UpwardExposedUses(B);
10030946e70aSDimitry Andric   // for (C : IIDF[B])
10040946e70aSDimitry Andric   //   for (U : LiveUses)
10050946e70aSDimitry Andric   //     if (Rdef(U) dom C)
10060946e70aSDimitry Andric   //       C.addLiveIn(U)
10070946e70aSDimitry Andric   //
10080946e70aSDimitry Andric 
10090946e70aSDimitry Andric   // Go up the dominator tree (depth-first).
10100946e70aSDimitry Andric   MachineDomTreeNode *N = MDT.getNode(B);
1011fcaf7f86SDimitry Andric   for (auto *I : *N) {
10120946e70aSDimitry Andric     RefMap L;
10130946e70aSDimitry Andric     MachineBasicBlock *SB = I->getBlock();
10140946e70aSDimitry Andric     traverse(SB, L);
10150946e70aSDimitry Andric 
10160946e70aSDimitry Andric     for (auto S : L)
10170946e70aSDimitry Andric       LiveIn[S.first].insert(S.second.begin(), S.second.end());
10180946e70aSDimitry Andric   }
10190946e70aSDimitry Andric 
10200946e70aSDimitry Andric   if (Trace) {
10210946e70aSDimitry Andric     dbgs() << "\n-- " << printMBBReference(*B) << ": " << __func__
10220946e70aSDimitry Andric            << " after recursion into: {";
1023fcaf7f86SDimitry Andric     for (auto *I : *N)
10240946e70aSDimitry Andric       dbgs() << ' ' << I->getBlock()->getNumber();
10250946e70aSDimitry Andric     dbgs() << " }\n";
1026bdd1243dSDimitry Andric     dbgs() << "  LiveIn: " << Print(LiveIn, DFG) << '\n';
1027bdd1243dSDimitry Andric     dbgs() << "  Local:  " << Print(LiveMap[B], DFG) << '\n';
10280946e70aSDimitry Andric   }
10290946e70aSDimitry Andric 
10300946e70aSDimitry Andric   // Add reaching defs of phi uses that are live on exit from this block.
10310946e70aSDimitry Andric   RefMap &PUs = PhiLOX[B];
10320946e70aSDimitry Andric   for (auto &S : PUs)
10330946e70aSDimitry Andric     LiveIn[S.first].insert(S.second.begin(), S.second.end());
10340946e70aSDimitry Andric 
10350946e70aSDimitry Andric   if (Trace) {
10360946e70aSDimitry Andric     dbgs() << "after LOX\n";
1037bdd1243dSDimitry Andric     dbgs() << "  LiveIn: " << Print(LiveIn, DFG) << '\n';
1038bdd1243dSDimitry Andric     dbgs() << "  Local:  " << Print(LiveMap[B], DFG) << '\n';
10390946e70aSDimitry Andric   }
10400946e70aSDimitry Andric 
10410946e70aSDimitry Andric   // The LiveIn map at this point has all defs that are live-on-exit from B,
10420946e70aSDimitry Andric   // as if they were live-on-entry to B. First, we need to filter out all
10430946e70aSDimitry Andric   // defs that are present in this block. Then we will add reaching defs of
10440946e70aSDimitry Andric   // all upward-exposed uses.
10450946e70aSDimitry Andric 
10460946e70aSDimitry Andric   // To filter out the defs, first make a copy of LiveIn, and then re-populate
10470946e70aSDimitry Andric   // LiveIn with the defs that should remain.
10480946e70aSDimitry Andric   RefMap LiveInCopy = LiveIn;
10490946e70aSDimitry Andric   LiveIn.clear();
10500946e70aSDimitry Andric 
10510946e70aSDimitry Andric   for (const std::pair<const RegisterId, NodeRefSet> &LE : LiveInCopy) {
10520946e70aSDimitry Andric     RegisterRef LRef(LE.first);
10530946e70aSDimitry Andric     NodeRefSet &NewDefs = LiveIn[LRef.Reg]; // To be filled.
10540946e70aSDimitry Andric     const NodeRefSet &OldDefs = LE.second;
10550946e70aSDimitry Andric     for (NodeRef OR : OldDefs) {
10560946e70aSDimitry Andric       // R is a def node that was live-on-exit
10570946e70aSDimitry Andric       auto DA = DFG.addr<DefNode *>(OR.first);
10580946e70aSDimitry Andric       NodeAddr<InstrNode *> IA = DA.Addr->getOwner(DFG);
10590946e70aSDimitry Andric       NodeAddr<BlockNode *> BA = IA.Addr->getOwner(DFG);
10600946e70aSDimitry Andric       if (B != BA.Addr->getCode()) {
10610946e70aSDimitry Andric         // Defs from a different block need to be preserved. Defs from this
10620946e70aSDimitry Andric         // block will need to be processed further, except for phi defs, the
10630946e70aSDimitry Andric         // liveness of which is handled through the PhiLON/PhiLOX maps.
10640946e70aSDimitry Andric         NewDefs.insert(OR);
10650946e70aSDimitry Andric         continue;
10660946e70aSDimitry Andric       }
10670946e70aSDimitry Andric 
10680946e70aSDimitry Andric       // Defs from this block need to stop the liveness from being
10690946e70aSDimitry Andric       // propagated upwards. This only applies to non-preserving defs,
10700946e70aSDimitry Andric       // and to the parts of the register actually covered by those defs.
10710946e70aSDimitry Andric       // (Note that phi defs should always be preserving.)
10720946e70aSDimitry Andric       RegisterAggr RRs(PRI);
10730946e70aSDimitry Andric       LRef.Mask = OR.second;
10740946e70aSDimitry Andric 
10750946e70aSDimitry Andric       if (!DFG.IsPreservingDef(DA)) {
10760946e70aSDimitry Andric         assert(!(IA.Addr->getFlags() & NodeAttrs::Phi));
10770946e70aSDimitry Andric         // DA is a non-phi def that is live-on-exit from this block, and
10780946e70aSDimitry Andric         // that is also located in this block. LRef is a register ref
10790946e70aSDimitry Andric         // whose use this def reaches. If DA covers LRef, then no part
10800946e70aSDimitry Andric         // of LRef is exposed upwards.A
10810946e70aSDimitry Andric         if (RRs.insert(DA.Addr->getRegRef(DFG)).hasCoverOf(LRef))
10820946e70aSDimitry Andric           continue;
10830946e70aSDimitry Andric       }
10840946e70aSDimitry Andric 
10850946e70aSDimitry Andric       // DA itself was not sufficient to cover LRef. In general, it is
10860946e70aSDimitry Andric       // the last in a chain of aliased defs before the exit from this block.
10870946e70aSDimitry Andric       // There could be other defs in this block that are a part of that
10880946e70aSDimitry Andric       // chain. Check that now: accumulate the registers from these defs,
10890946e70aSDimitry Andric       // and if they all together cover LRef, it is not live-on-entry.
10900946e70aSDimitry Andric       for (NodeAddr<DefNode *> TA : getAllReachingDefs(DA)) {
10910946e70aSDimitry Andric         // DefNode -> InstrNode -> BlockNode.
10920946e70aSDimitry Andric         NodeAddr<InstrNode *> ITA = TA.Addr->getOwner(DFG);
10930946e70aSDimitry Andric         NodeAddr<BlockNode *> BTA = ITA.Addr->getOwner(DFG);
10940946e70aSDimitry Andric         // Reaching defs are ordered in the upward direction.
10950946e70aSDimitry Andric         if (BTA.Addr->getCode() != B) {
10960946e70aSDimitry Andric           // We have reached past the beginning of B, and the accumulated
10970946e70aSDimitry Andric           // registers are not covering LRef. The first def from the
10980946e70aSDimitry Andric           // upward chain will be live.
10990946e70aSDimitry Andric           // Subtract all accumulated defs (RRs) from LRef.
11000946e70aSDimitry Andric           RegisterRef T = RRs.clearIn(LRef);
11010946e70aSDimitry Andric           assert(T);
11020946e70aSDimitry Andric           NewDefs.insert({TA.Id, T.Mask});
11030946e70aSDimitry Andric           break;
11040946e70aSDimitry Andric         }
11050946e70aSDimitry Andric 
11060946e70aSDimitry Andric         // TA is in B. Only add this def to the accumulated cover if it is
11070946e70aSDimitry Andric         // not preserving.
11080946e70aSDimitry Andric         if (!(TA.Addr->getFlags() & NodeAttrs::Preserving))
11090946e70aSDimitry Andric           RRs.insert(TA.Addr->getRegRef(DFG));
11100946e70aSDimitry Andric         // If this is enough to cover LRef, then stop.
11110946e70aSDimitry Andric         if (RRs.hasCoverOf(LRef))
11120946e70aSDimitry Andric           break;
11130946e70aSDimitry Andric       }
11140946e70aSDimitry Andric     }
11150946e70aSDimitry Andric   }
11160946e70aSDimitry Andric 
11170946e70aSDimitry Andric   emptify(LiveIn);
11180946e70aSDimitry Andric 
11190946e70aSDimitry Andric   if (Trace) {
11200946e70aSDimitry Andric     dbgs() << "after defs in block\n";
1121bdd1243dSDimitry Andric     dbgs() << "  LiveIn: " << Print(LiveIn, DFG) << '\n';
1122bdd1243dSDimitry Andric     dbgs() << "  Local:  " << Print(LiveMap[B], DFG) << '\n';
11230946e70aSDimitry Andric   }
11240946e70aSDimitry Andric 
11250946e70aSDimitry Andric   // Scan the block for upward-exposed uses and add them to the tracking set.
11260946e70aSDimitry Andric   for (auto I : DFG.getFunc().Addr->findBlock(B, DFG).Addr->members(DFG)) {
11270946e70aSDimitry Andric     NodeAddr<InstrNode *> IA = I;
11280946e70aSDimitry Andric     if (IA.Addr->getKind() != NodeAttrs::Stmt)
11290946e70aSDimitry Andric       continue;
11300946e70aSDimitry Andric     for (NodeAddr<UseNode *> UA : IA.Addr->members_if(DFG.IsUse, DFG)) {
11310946e70aSDimitry Andric       if (UA.Addr->getFlags() & NodeAttrs::Undef)
11320946e70aSDimitry Andric         continue;
1133e8d8bef9SDimitry Andric       RegisterRef RR = UA.Addr->getRegRef(DFG);
11340946e70aSDimitry Andric       for (NodeAddr<DefNode *> D : getAllReachingDefs(UA))
11350946e70aSDimitry Andric         if (getBlockWithRef(D.Id) != B)
11360946e70aSDimitry Andric           LiveIn[RR.Reg].insert({D.Id, RR.Mask});
11370946e70aSDimitry Andric     }
11380946e70aSDimitry Andric   }
11390946e70aSDimitry Andric 
11400946e70aSDimitry Andric   if (Trace) {
11410946e70aSDimitry Andric     dbgs() << "after uses in block\n";
1142bdd1243dSDimitry Andric     dbgs() << "  LiveIn: " << Print(LiveIn, DFG) << '\n';
1143bdd1243dSDimitry Andric     dbgs() << "  Local:  " << Print(LiveMap[B], DFG) << '\n';
11440946e70aSDimitry Andric   }
11450946e70aSDimitry Andric 
11460946e70aSDimitry Andric   // Phi uses should not be propagated up the dominator tree, since they
11470946e70aSDimitry Andric   // are not dominated by their corresponding reaching defs.
11480946e70aSDimitry Andric   RegisterAggr &Local = LiveMap[B];
11490946e70aSDimitry Andric   RefMap &LON = PhiLON[B];
11500946e70aSDimitry Andric   for (auto &R : LON) {
11510946e70aSDimitry Andric     LaneBitmask M;
11520946e70aSDimitry Andric     for (auto P : R.second)
11530946e70aSDimitry Andric       M |= P.second;
11540946e70aSDimitry Andric     Local.insert(RegisterRef(R.first, M));
11550946e70aSDimitry Andric   }
11560946e70aSDimitry Andric 
11570946e70aSDimitry Andric   if (Trace) {
11580946e70aSDimitry Andric     dbgs() << "after phi uses in block\n";
1159bdd1243dSDimitry Andric     dbgs() << "  LiveIn: " << Print(LiveIn, DFG) << '\n';
1160bdd1243dSDimitry Andric     dbgs() << "  Local:  " << Print(Local, DFG) << '\n';
11610946e70aSDimitry Andric   }
11620946e70aSDimitry Andric 
1163fcaf7f86SDimitry Andric   for (auto *C : IIDF[B]) {
11640946e70aSDimitry Andric     RegisterAggr &LiveC = LiveMap[C];
11650946e70aSDimitry Andric     for (const std::pair<const RegisterId, NodeRefSet> &S : LiveIn)
11660946e70aSDimitry Andric       for (auto R : S.second)
11670946e70aSDimitry Andric         if (MDT.properlyDominates(getBlockWithRef(R.first), C))
11680946e70aSDimitry Andric           LiveC.insert(RegisterRef(S.first, R.second));
11690946e70aSDimitry Andric   }
11700946e70aSDimitry Andric }
11710946e70aSDimitry Andric 
emptify(RefMap & M)11720946e70aSDimitry Andric void Liveness::emptify(RefMap &M) {
11730946e70aSDimitry Andric   for (auto I = M.begin(), E = M.end(); I != E;)
11740946e70aSDimitry Andric     I = I->second.empty() ? M.erase(I) : std::next(I);
11750946e70aSDimitry Andric }
1176*06c3fb27SDimitry Andric 
1177*06c3fb27SDimitry Andric } // namespace llvm::rdf
1178