xref: /llvm-project/llvm/lib/CodeGen/RDFGraph.cpp (revision 859b05b02d3fd9ab6b77f2bed8df6902fe704806)
1 //===- RDFGraph.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 // Target-independent, SSA-based data flow graph for register data flow (RDF).
10 //
11 #include "llvm/ADT/BitVector.h"
12 #include "llvm/ADT/STLExtras.h"
13 #include "llvm/ADT/SetVector.h"
14 #include "llvm/CodeGen/MachineBasicBlock.h"
15 #include "llvm/CodeGen/MachineDominanceFrontier.h"
16 #include "llvm/CodeGen/MachineDominators.h"
17 #include "llvm/CodeGen/MachineFunction.h"
18 #include "llvm/CodeGen/MachineInstr.h"
19 #include "llvm/CodeGen/MachineOperand.h"
20 #include "llvm/CodeGen/MachineRegisterInfo.h"
21 #include "llvm/CodeGen/RDFGraph.h"
22 #include "llvm/CodeGen/RDFRegisters.h"
23 #include "llvm/CodeGen/TargetInstrInfo.h"
24 #include "llvm/CodeGen/TargetLowering.h"
25 #include "llvm/CodeGen/TargetRegisterInfo.h"
26 #include "llvm/CodeGen/TargetSubtargetInfo.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/MC/LaneBitmask.h"
29 #include "llvm/MC/MCInstrDesc.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include <algorithm>
33 #include <cassert>
34 #include <cstdint>
35 #include <cstring>
36 #include <iterator>
37 #include <set>
38 #include <utility>
39 #include <vector>
40 
41 using namespace llvm;
42 using namespace rdf;
43 
44 // Printing functions. Have them here first, so that the rest of the code
45 // can use them.
46 namespace llvm {
47 namespace rdf {
48 
49 raw_ostream &operator<<(raw_ostream &OS, const Print<RegisterRef> &P) {
50   P.G.getPRI().print(OS, P.Obj);
51   return OS;
52 }
53 
54 raw_ostream &operator<<(raw_ostream &OS, const Print<NodeId> &P) {
55   auto NA = P.G.addr<NodeBase *>(P.Obj);
56   uint16_t Attrs = NA.Addr->getAttrs();
57   uint16_t Kind = NodeAttrs::kind(Attrs);
58   uint16_t Flags = NodeAttrs::flags(Attrs);
59   switch (NodeAttrs::type(Attrs)) {
60   case NodeAttrs::Code:
61     switch (Kind) {
62     case NodeAttrs::Func:
63       OS << 'f';
64       break;
65     case NodeAttrs::Block:
66       OS << 'b';
67       break;
68     case NodeAttrs::Stmt:
69       OS << 's';
70       break;
71     case NodeAttrs::Phi:
72       OS << 'p';
73       break;
74     default:
75       OS << "c?";
76       break;
77     }
78     break;
79   case NodeAttrs::Ref:
80     if (Flags & NodeAttrs::Undef)
81       OS << '/';
82     if (Flags & NodeAttrs::Dead)
83       OS << '\\';
84     if (Flags & NodeAttrs::Preserving)
85       OS << '+';
86     if (Flags & NodeAttrs::Clobbering)
87       OS << '~';
88     switch (Kind) {
89     case NodeAttrs::Use:
90       OS << 'u';
91       break;
92     case NodeAttrs::Def:
93       OS << 'd';
94       break;
95     case NodeAttrs::Block:
96       OS << 'b';
97       break;
98     default:
99       OS << "r?";
100       break;
101     }
102     break;
103   default:
104     OS << '?';
105     break;
106   }
107   OS << P.Obj;
108   if (Flags & NodeAttrs::Shadow)
109     OS << '"';
110   return OS;
111 }
112 
113 static void printRefHeader(raw_ostream &OS, const NodeAddr<RefNode *> RA,
114                            const DataFlowGraph &G) {
115   OS << Print(RA.Id, G) << '<' << Print(RA.Addr->getRegRef(G), G) << '>';
116   if (RA.Addr->getFlags() & NodeAttrs::Fixed)
117     OS << '!';
118 }
119 
120 raw_ostream &operator<<(raw_ostream &OS, const Print<NodeAddr<DefNode *>> &P) {
121   printRefHeader(OS, P.Obj, P.G);
122   OS << '(';
123   if (NodeId N = P.Obj.Addr->getReachingDef())
124     OS << Print(N, P.G);
125   OS << ',';
126   if (NodeId N = P.Obj.Addr->getReachedDef())
127     OS << Print(N, P.G);
128   OS << ',';
129   if (NodeId N = P.Obj.Addr->getReachedUse())
130     OS << Print(N, P.G);
131   OS << "):";
132   if (NodeId N = P.Obj.Addr->getSibling())
133     OS << Print(N, P.G);
134   return OS;
135 }
136 
137 raw_ostream &operator<<(raw_ostream &OS, const Print<NodeAddr<UseNode *>> &P) {
138   printRefHeader(OS, P.Obj, P.G);
139   OS << '(';
140   if (NodeId N = P.Obj.Addr->getReachingDef())
141     OS << Print(N, P.G);
142   OS << "):";
143   if (NodeId N = P.Obj.Addr->getSibling())
144     OS << Print(N, P.G);
145   return OS;
146 }
147 
148 raw_ostream &operator<<(raw_ostream &OS,
149                         const Print<NodeAddr<PhiUseNode *>> &P) {
150   printRefHeader(OS, P.Obj, P.G);
151   OS << '(';
152   if (NodeId N = P.Obj.Addr->getReachingDef())
153     OS << Print(N, P.G);
154   OS << ',';
155   if (NodeId N = P.Obj.Addr->getPredecessor())
156     OS << Print(N, P.G);
157   OS << "):";
158   if (NodeId N = P.Obj.Addr->getSibling())
159     OS << Print(N, P.G);
160   return OS;
161 }
162 
163 raw_ostream &operator<<(raw_ostream &OS, const Print<NodeAddr<RefNode *>> &P) {
164   switch (P.Obj.Addr->getKind()) {
165   case NodeAttrs::Def:
166     OS << PrintNode<DefNode *>(P.Obj, P.G);
167     break;
168   case NodeAttrs::Use:
169     if (P.Obj.Addr->getFlags() & NodeAttrs::PhiRef)
170       OS << PrintNode<PhiUseNode *>(P.Obj, P.G);
171     else
172       OS << PrintNode<UseNode *>(P.Obj, P.G);
173     break;
174   }
175   return OS;
176 }
177 
178 raw_ostream &operator<<(raw_ostream &OS, const Print<NodeList> &P) {
179   unsigned N = P.Obj.size();
180   for (auto I : P.Obj) {
181     OS << Print(I.Id, P.G);
182     if (--N)
183       OS << ' ';
184   }
185   return OS;
186 }
187 
188 raw_ostream &operator<<(raw_ostream &OS, const Print<NodeSet> &P) {
189   unsigned N = P.Obj.size();
190   for (auto I : P.Obj) {
191     OS << Print(I, P.G);
192     if (--N)
193       OS << ' ';
194   }
195   return OS;
196 }
197 
198 namespace {
199 
200 template <typename T> struct PrintListV {
201   PrintListV(const NodeList &L, const DataFlowGraph &G) : List(L), G(G) {}
202 
203   using Type = T;
204   const NodeList &List;
205   const DataFlowGraph &G;
206 };
207 
208 template <typename T>
209 raw_ostream &operator<<(raw_ostream &OS, const PrintListV<T> &P) {
210   unsigned N = P.List.size();
211   for (NodeAddr<T> A : P.List) {
212     OS << PrintNode<T>(A, P.G);
213     if (--N)
214       OS << ", ";
215   }
216   return OS;
217 }
218 
219 } // end anonymous namespace
220 
221 raw_ostream &operator<<(raw_ostream &OS, const Print<NodeAddr<PhiNode *>> &P) {
222   OS << Print(P.Obj.Id, P.G) << ": phi ["
223      << PrintListV<RefNode *>(P.Obj.Addr->members(P.G), P.G) << ']';
224   return OS;
225 }
226 
227 raw_ostream &operator<<(raw_ostream &OS, const Print<NodeAddr<StmtNode *>> &P) {
228   const MachineInstr &MI = *P.Obj.Addr->getCode();
229   unsigned Opc = MI.getOpcode();
230   OS << Print(P.Obj.Id, P.G) << ": " << P.G.getTII().getName(Opc);
231   // Print the target for calls and branches (for readability).
232   if (MI.isCall() || MI.isBranch()) {
233     MachineInstr::const_mop_iterator T =
234         llvm::find_if(MI.operands(), [](const MachineOperand &Op) -> bool {
235           return Op.isMBB() || Op.isGlobal() || Op.isSymbol();
236         });
237     if (T != MI.operands_end()) {
238       OS << ' ';
239       if (T->isMBB())
240         OS << printMBBReference(*T->getMBB());
241       else if (T->isGlobal())
242         OS << T->getGlobal()->getName();
243       else if (T->isSymbol())
244         OS << T->getSymbolName();
245     }
246   }
247   OS << " [" << PrintListV<RefNode *>(P.Obj.Addr->members(P.G), P.G) << ']';
248   return OS;
249 }
250 
251 raw_ostream &operator<<(raw_ostream &OS,
252                         const Print<NodeAddr<InstrNode *>> &P) {
253   switch (P.Obj.Addr->getKind()) {
254   case NodeAttrs::Phi:
255     OS << PrintNode<PhiNode *>(P.Obj, P.G);
256     break;
257   case NodeAttrs::Stmt:
258     OS << PrintNode<StmtNode *>(P.Obj, P.G);
259     break;
260   default:
261     OS << "instr? " << Print(P.Obj.Id, P.G);
262     break;
263   }
264   return OS;
265 }
266 
267 raw_ostream &operator<<(raw_ostream &OS,
268                         const Print<NodeAddr<BlockNode *>> &P) {
269   MachineBasicBlock *BB = P.Obj.Addr->getCode();
270   unsigned NP = BB->pred_size();
271   std::vector<int> Ns;
272   auto PrintBBs = [&OS](std::vector<int> Ns) -> void {
273     unsigned N = Ns.size();
274     for (int I : Ns) {
275       OS << "%bb." << I;
276       if (--N)
277         OS << ", ";
278     }
279   };
280 
281   OS << Print(P.Obj.Id, P.G) << ": --- " << printMBBReference(*BB)
282      << " --- preds(" << NP << "): ";
283   for (MachineBasicBlock *B : BB->predecessors())
284     Ns.push_back(B->getNumber());
285   PrintBBs(Ns);
286 
287   unsigned NS = BB->succ_size();
288   OS << "  succs(" << NS << "): ";
289   Ns.clear();
290   for (MachineBasicBlock *B : BB->successors())
291     Ns.push_back(B->getNumber());
292   PrintBBs(Ns);
293   OS << '\n';
294 
295   for (auto I : P.Obj.Addr->members(P.G))
296     OS << PrintNode<InstrNode *>(I, P.G) << '\n';
297   return OS;
298 }
299 
300 raw_ostream &operator<<(raw_ostream &OS, const Print<NodeAddr<FuncNode *>> &P) {
301   OS << "DFG dump:[\n"
302      << Print(P.Obj.Id, P.G)
303      << ": Function: " << P.Obj.Addr->getCode()->getName() << '\n';
304   for (auto I : P.Obj.Addr->members(P.G))
305     OS << PrintNode<BlockNode *>(I, P.G) << '\n';
306   OS << "]\n";
307   return OS;
308 }
309 
310 raw_ostream &operator<<(raw_ostream &OS, const Print<RegisterSet> &P) {
311   OS << '{';
312   for (auto I : P.Obj)
313     OS << ' ' << Print(I, P.G);
314   OS << " }";
315   return OS;
316 }
317 
318 raw_ostream &operator<<(raw_ostream &OS, const Print<RegisterAggr> &P) {
319   OS << P.Obj;
320   return OS;
321 }
322 
323 raw_ostream &operator<<(raw_ostream &OS,
324                         const Print<DataFlowGraph::DefStack> &P) {
325   for (auto I = P.Obj.top(), E = P.Obj.bottom(); I != E;) {
326     OS << Print(I->Id, P.G) << '<' << Print(I->Addr->getRegRef(P.G), P.G)
327        << '>';
328     I.down();
329     if (I != E)
330       OS << ' ';
331   }
332   return OS;
333 }
334 
335 } // end namespace rdf
336 } // end namespace llvm
337 
338 // Node allocation functions.
339 //
340 // Node allocator is like a slab memory allocator: it allocates blocks of
341 // memory in sizes that are multiples of the size of a node. Each block has
342 // the same size. Nodes are allocated from the currently active block, and
343 // when it becomes full, a new one is created.
344 // There is a mapping scheme between node id and its location in a block,
345 // and within that block is described in the header file.
346 //
347 void NodeAllocator::startNewBlock() {
348   void *T = MemPool.Allocate(NodesPerBlock * NodeMemSize, NodeMemSize);
349   char *P = static_cast<char *>(T);
350   Blocks.push_back(P);
351   // Check if the block index is still within the allowed range, i.e. less
352   // than 2^N, where N is the number of bits in NodeId for the block index.
353   // BitsPerIndex is the number of bits per node index.
354   assert((Blocks.size() < ((size_t)1 << (8 * sizeof(NodeId) - BitsPerIndex))) &&
355          "Out of bits for block index");
356   ActiveEnd = P;
357 }
358 
359 bool NodeAllocator::needNewBlock() {
360   if (Blocks.empty())
361     return true;
362 
363   char *ActiveBegin = Blocks.back();
364   uint32_t Index = (ActiveEnd - ActiveBegin) / NodeMemSize;
365   return Index >= NodesPerBlock;
366 }
367 
368 NodeAddr<NodeBase *> NodeAllocator::New() {
369   if (needNewBlock())
370     startNewBlock();
371 
372   uint32_t ActiveB = Blocks.size() - 1;
373   uint32_t Index = (ActiveEnd - Blocks[ActiveB]) / NodeMemSize;
374   NodeAddr<NodeBase *> NA = {reinterpret_cast<NodeBase *>(ActiveEnd),
375                              makeId(ActiveB, Index)};
376   ActiveEnd += NodeMemSize;
377   return NA;
378 }
379 
380 NodeId NodeAllocator::id(const NodeBase *P) const {
381   uintptr_t A = reinterpret_cast<uintptr_t>(P);
382   for (unsigned i = 0, n = Blocks.size(); i != n; ++i) {
383     uintptr_t B = reinterpret_cast<uintptr_t>(Blocks[i]);
384     if (A < B || A >= B + NodesPerBlock * NodeMemSize)
385       continue;
386     uint32_t Idx = (A - B) / NodeMemSize;
387     return makeId(i, Idx);
388   }
389   llvm_unreachable("Invalid node address");
390 }
391 
392 void NodeAllocator::clear() {
393   MemPool.Reset();
394   Blocks.clear();
395   ActiveEnd = nullptr;
396 }
397 
398 // Insert node NA after "this" in the circular chain.
399 void NodeBase::append(NodeAddr<NodeBase *> NA) {
400   NodeId Nx = Next;
401   // If NA is already "next", do nothing.
402   if (Next != NA.Id) {
403     Next = NA.Id;
404     NA.Addr->Next = Nx;
405   }
406 }
407 
408 // Fundamental node manipulator functions.
409 
410 // Obtain the register reference from a reference node.
411 RegisterRef RefNode::getRegRef(const DataFlowGraph &G) const {
412   assert(NodeAttrs::type(Attrs) == NodeAttrs::Ref);
413   if (NodeAttrs::flags(Attrs) & NodeAttrs::PhiRef)
414     return G.unpack(Ref.PR);
415   assert(Ref.Op != nullptr);
416   return G.makeRegRef(*Ref.Op);
417 }
418 
419 // Set the register reference in the reference node directly (for references
420 // in phi nodes).
421 void RefNode::setRegRef(RegisterRef RR, DataFlowGraph &G) {
422   assert(NodeAttrs::type(Attrs) == NodeAttrs::Ref);
423   assert(NodeAttrs::flags(Attrs) & NodeAttrs::PhiRef);
424   Ref.PR = G.pack(RR);
425 }
426 
427 // Set the register reference in the reference node based on a machine
428 // operand (for references in statement nodes).
429 void RefNode::setRegRef(MachineOperand *Op, DataFlowGraph &G) {
430   assert(NodeAttrs::type(Attrs) == NodeAttrs::Ref);
431   assert(!(NodeAttrs::flags(Attrs) & NodeAttrs::PhiRef));
432   (void)G;
433   Ref.Op = Op;
434 }
435 
436 // Get the owner of a given reference node.
437 NodeAddr<NodeBase *> RefNode::getOwner(const DataFlowGraph &G) {
438   NodeAddr<NodeBase *> NA = G.addr<NodeBase *>(getNext());
439 
440   while (NA.Addr != this) {
441     if (NA.Addr->getType() == NodeAttrs::Code)
442       return NA;
443     NA = G.addr<NodeBase *>(NA.Addr->getNext());
444   }
445   llvm_unreachable("No owner in circular list");
446 }
447 
448 // Connect the def node to the reaching def node.
449 void DefNode::linkToDef(NodeId Self, NodeAddr<DefNode *> DA) {
450   Ref.RD = DA.Id;
451   Ref.Sib = DA.Addr->getReachedDef();
452   DA.Addr->setReachedDef(Self);
453 }
454 
455 // Connect the use node to the reaching def node.
456 void UseNode::linkToDef(NodeId Self, NodeAddr<DefNode *> DA) {
457   Ref.RD = DA.Id;
458   Ref.Sib = DA.Addr->getReachedUse();
459   DA.Addr->setReachedUse(Self);
460 }
461 
462 // Get the first member of the code node.
463 NodeAddr<NodeBase *> CodeNode::getFirstMember(const DataFlowGraph &G) const {
464   if (Code.FirstM == 0)
465     return NodeAddr<NodeBase *>();
466   return G.addr<NodeBase *>(Code.FirstM);
467 }
468 
469 // Get the last member of the code node.
470 NodeAddr<NodeBase *> CodeNode::getLastMember(const DataFlowGraph &G) const {
471   if (Code.LastM == 0)
472     return NodeAddr<NodeBase *>();
473   return G.addr<NodeBase *>(Code.LastM);
474 }
475 
476 // Add node NA at the end of the member list of the given code node.
477 void CodeNode::addMember(NodeAddr<NodeBase *> NA, const DataFlowGraph &G) {
478   NodeAddr<NodeBase *> ML = getLastMember(G);
479   if (ML.Id != 0) {
480     ML.Addr->append(NA);
481   } else {
482     Code.FirstM = NA.Id;
483     NodeId Self = G.id(this);
484     NA.Addr->setNext(Self);
485   }
486   Code.LastM = NA.Id;
487 }
488 
489 // Add node NA after member node MA in the given code node.
490 void CodeNode::addMemberAfter(NodeAddr<NodeBase *> MA, NodeAddr<NodeBase *> NA,
491                               const DataFlowGraph &G) {
492   MA.Addr->append(NA);
493   if (Code.LastM == MA.Id)
494     Code.LastM = NA.Id;
495 }
496 
497 // Remove member node NA from the given code node.
498 void CodeNode::removeMember(NodeAddr<NodeBase *> NA, const DataFlowGraph &G) {
499   NodeAddr<NodeBase *> MA = getFirstMember(G);
500   assert(MA.Id != 0);
501 
502   // Special handling if the member to remove is the first member.
503   if (MA.Id == NA.Id) {
504     if (Code.LastM == MA.Id) {
505       // If it is the only member, set both first and last to 0.
506       Code.FirstM = Code.LastM = 0;
507     } else {
508       // Otherwise, advance the first member.
509       Code.FirstM = MA.Addr->getNext();
510     }
511     return;
512   }
513 
514   while (MA.Addr != this) {
515     NodeId MX = MA.Addr->getNext();
516     if (MX == NA.Id) {
517       MA.Addr->setNext(NA.Addr->getNext());
518       // If the member to remove happens to be the last one, update the
519       // LastM indicator.
520       if (Code.LastM == NA.Id)
521         Code.LastM = MA.Id;
522       return;
523     }
524     MA = G.addr<NodeBase *>(MX);
525   }
526   llvm_unreachable("No such member");
527 }
528 
529 // Return the list of all members of the code node.
530 NodeList CodeNode::members(const DataFlowGraph &G) const {
531   static auto True = [](NodeAddr<NodeBase *>) -> bool { return true; };
532   return members_if(True, G);
533 }
534 
535 // Return the owner of the given instr node.
536 NodeAddr<NodeBase *> InstrNode::getOwner(const DataFlowGraph &G) {
537   NodeAddr<NodeBase *> NA = G.addr<NodeBase *>(getNext());
538 
539   while (NA.Addr != this) {
540     assert(NA.Addr->getType() == NodeAttrs::Code);
541     if (NA.Addr->getKind() == NodeAttrs::Block)
542       return NA;
543     NA = G.addr<NodeBase *>(NA.Addr->getNext());
544   }
545   llvm_unreachable("No owner in circular list");
546 }
547 
548 // Add the phi node PA to the given block node.
549 void BlockNode::addPhi(NodeAddr<PhiNode *> PA, const DataFlowGraph &G) {
550   NodeAddr<NodeBase *> M = getFirstMember(G);
551   if (M.Id == 0) {
552     addMember(PA, G);
553     return;
554   }
555 
556   assert(M.Addr->getType() == NodeAttrs::Code);
557   if (M.Addr->getKind() == NodeAttrs::Stmt) {
558     // If the first member of the block is a statement, insert the phi as
559     // the first member.
560     Code.FirstM = PA.Id;
561     PA.Addr->setNext(M.Id);
562   } else {
563     // If the first member is a phi, find the last phi, and append PA to it.
564     assert(M.Addr->getKind() == NodeAttrs::Phi);
565     NodeAddr<NodeBase *> MN = M;
566     do {
567       M = MN;
568       MN = G.addr<NodeBase *>(M.Addr->getNext());
569       assert(MN.Addr->getType() == NodeAttrs::Code);
570     } while (MN.Addr->getKind() == NodeAttrs::Phi);
571 
572     // M is the last phi.
573     addMemberAfter(M, PA, G);
574   }
575 }
576 
577 // Find the block node corresponding to the machine basic block BB in the
578 // given func node.
579 NodeAddr<BlockNode *> FuncNode::findBlock(const MachineBasicBlock *BB,
580                                           const DataFlowGraph &G) const {
581   auto EqBB = [BB](NodeAddr<NodeBase *> NA) -> bool {
582     return NodeAddr<BlockNode *>(NA).Addr->getCode() == BB;
583   };
584   NodeList Ms = members_if(EqBB, G);
585   if (!Ms.empty())
586     return Ms[0];
587   return NodeAddr<BlockNode *>();
588 }
589 
590 // Get the block node for the entry block in the given function.
591 NodeAddr<BlockNode *> FuncNode::getEntryBlock(const DataFlowGraph &G) {
592   MachineBasicBlock *EntryB = &getCode()->front();
593   return findBlock(EntryB, G);
594 }
595 
596 // Target operand information.
597 //
598 
599 // For a given instruction, check if there are any bits of RR that can remain
600 // unchanged across this def.
601 bool TargetOperandInfo::isPreserving(const MachineInstr &In,
602                                      unsigned OpNum) const {
603   return TII.isPredicated(In);
604 }
605 
606 // Check if the definition of RR produces an unspecified value.
607 bool TargetOperandInfo::isClobbering(const MachineInstr &In,
608                                      unsigned OpNum) const {
609   const MachineOperand &Op = In.getOperand(OpNum);
610   if (Op.isRegMask())
611     return true;
612   assert(Op.isReg());
613   if (In.isCall())
614     if (Op.isDef() && Op.isDead())
615       return true;
616   return false;
617 }
618 
619 // Check if the given instruction specifically requires
620 bool TargetOperandInfo::isFixedReg(const MachineInstr &In,
621                                    unsigned OpNum) const {
622   if (In.isCall() || In.isReturn() || In.isInlineAsm())
623     return true;
624   // Check for a tail call.
625   if (In.isBranch())
626     for (const MachineOperand &O : In.operands())
627       if (O.isGlobal() || O.isSymbol())
628         return true;
629 
630   const MCInstrDesc &D = In.getDesc();
631   if (D.implicit_defs().empty() && D.implicit_uses().empty())
632     return false;
633   const MachineOperand &Op = In.getOperand(OpNum);
634   // If there is a sub-register, treat the operand as non-fixed. Currently,
635   // fixed registers are those that are listed in the descriptor as implicit
636   // uses or defs, and those lists do not allow sub-registers.
637   if (Op.getSubReg() != 0)
638     return false;
639   Register Reg = Op.getReg();
640   ArrayRef<MCPhysReg> ImpOps =
641       Op.isDef() ? D.implicit_defs() : D.implicit_uses();
642   return is_contained(ImpOps, Reg);
643 }
644 
645 //
646 // The data flow graph construction.
647 //
648 
649 DataFlowGraph::DataFlowGraph(MachineFunction &mf, const TargetInstrInfo &tii,
650                              const TargetRegisterInfo &tri,
651                              const MachineDominatorTree &mdt,
652                              const MachineDominanceFrontier &mdf)
653     : DefaultTOI(std::make_unique<TargetOperandInfo>(tii)), MF(mf), TII(tii),
654       TRI(tri), PRI(tri, mf), MDT(mdt), MDF(mdf), TOI(*DefaultTOI),
655       LiveIns(PRI) {}
656 
657 DataFlowGraph::DataFlowGraph(MachineFunction &mf, const TargetInstrInfo &tii,
658                              const TargetRegisterInfo &tri,
659                              const MachineDominatorTree &mdt,
660                              const MachineDominanceFrontier &mdf,
661                              const TargetOperandInfo &toi)
662     : MF(mf), TII(tii), TRI(tri), PRI(tri, mf), MDT(mdt), MDF(mdf), TOI(toi),
663       LiveIns(PRI) {}
664 
665 // The implementation of the definition stack.
666 // Each register reference has its own definition stack. In particular,
667 // for a register references "Reg" and "Reg:subreg" will each have their
668 // own definition stacks.
669 
670 // Construct a stack iterator.
671 DataFlowGraph::DefStack::Iterator::Iterator(const DataFlowGraph::DefStack &S,
672                                             bool Top)
673     : DS(S) {
674   if (!Top) {
675     // Initialize to bottom.
676     Pos = 0;
677     return;
678   }
679   // Initialize to the top, i.e. top-most non-delimiter (or 0, if empty).
680   Pos = DS.Stack.size();
681   while (Pos > 0 && DS.isDelimiter(DS.Stack[Pos - 1]))
682     Pos--;
683 }
684 
685 // Return the size of the stack, including block delimiters.
686 unsigned DataFlowGraph::DefStack::size() const {
687   unsigned S = 0;
688   for (auto I = top(), E = bottom(); I != E; I.down())
689     S++;
690   return S;
691 }
692 
693 // Remove the top entry from the stack. Remove all intervening delimiters
694 // so that after this, the stack is either empty, or the top of the stack
695 // is a non-delimiter.
696 void DataFlowGraph::DefStack::pop() {
697   assert(!empty());
698   unsigned P = nextDown(Stack.size());
699   Stack.resize(P);
700 }
701 
702 // Push a delimiter for block node N on the stack.
703 void DataFlowGraph::DefStack::start_block(NodeId N) {
704   assert(N != 0);
705   Stack.push_back(NodeAddr<DefNode *>(nullptr, N));
706 }
707 
708 // Remove all nodes from the top of the stack, until the delimited for
709 // block node N is encountered. Remove the delimiter as well. In effect,
710 // this will remove from the stack all definitions from block N.
711 void DataFlowGraph::DefStack::clear_block(NodeId N) {
712   assert(N != 0);
713   unsigned P = Stack.size();
714   while (P > 0) {
715     bool Found = isDelimiter(Stack[P - 1], N);
716     P--;
717     if (Found)
718       break;
719   }
720   // This will also remove the delimiter, if found.
721   Stack.resize(P);
722 }
723 
724 // Move the stack iterator up by one.
725 unsigned DataFlowGraph::DefStack::nextUp(unsigned P) const {
726   // Get the next valid position after P (skipping all delimiters).
727   // The input position P does not have to point to a non-delimiter.
728   unsigned SS = Stack.size();
729   bool IsDelim;
730   assert(P < SS);
731   do {
732     P++;
733     IsDelim = isDelimiter(Stack[P - 1]);
734   } while (P < SS && IsDelim);
735   assert(!IsDelim);
736   return P;
737 }
738 
739 // Move the stack iterator down by one.
740 unsigned DataFlowGraph::DefStack::nextDown(unsigned P) const {
741   // Get the preceding valid position before P (skipping all delimiters).
742   // The input position P does not have to point to a non-delimiter.
743   assert(P > 0 && P <= Stack.size());
744   bool IsDelim = isDelimiter(Stack[P - 1]);
745   do {
746     if (--P == 0)
747       break;
748     IsDelim = isDelimiter(Stack[P - 1]);
749   } while (P > 0 && IsDelim);
750   assert(!IsDelim);
751   return P;
752 }
753 
754 // Register information.
755 
756 RegisterAggr DataFlowGraph::getLandingPadLiveIns() const {
757   RegisterAggr LR(getPRI());
758   const Function &F = MF.getFunction();
759   const Constant *PF = F.hasPersonalityFn() ? F.getPersonalityFn() : nullptr;
760   const TargetLowering &TLI = *MF.getSubtarget().getTargetLowering();
761   if (RegisterId R = TLI.getExceptionPointerRegister(PF))
762     LR.insert(RegisterRef(R));
763   if (!isFuncletEHPersonality(classifyEHPersonality(PF))) {
764     if (RegisterId R = TLI.getExceptionSelectorRegister(PF))
765       LR.insert(RegisterRef(R));
766   }
767   return LR;
768 }
769 
770 // Node management functions.
771 
772 // Get the pointer to the node with the id N.
773 NodeBase *DataFlowGraph::ptr(NodeId N) const {
774   if (N == 0)
775     return nullptr;
776   return Memory.ptr(N);
777 }
778 
779 // Get the id of the node at the address P.
780 NodeId DataFlowGraph::id(const NodeBase *P) const {
781   if (P == nullptr)
782     return 0;
783   return Memory.id(P);
784 }
785 
786 // Allocate a new node and set the attributes to Attrs.
787 NodeAddr<NodeBase *> DataFlowGraph::newNode(uint16_t Attrs) {
788   NodeAddr<NodeBase *> P = Memory.New();
789   P.Addr->init();
790   P.Addr->setAttrs(Attrs);
791   return P;
792 }
793 
794 // Make a copy of the given node B, except for the data-flow links, which
795 // are set to 0.
796 NodeAddr<NodeBase *> DataFlowGraph::cloneNode(const NodeAddr<NodeBase *> B) {
797   NodeAddr<NodeBase *> NA = newNode(0);
798   memcpy(NA.Addr, B.Addr, sizeof(NodeBase));
799   // Ref nodes need to have the data-flow links reset.
800   if (NA.Addr->getType() == NodeAttrs::Ref) {
801     NodeAddr<RefNode *> RA = NA;
802     RA.Addr->setReachingDef(0);
803     RA.Addr->setSibling(0);
804     if (NA.Addr->getKind() == NodeAttrs::Def) {
805       NodeAddr<DefNode *> DA = NA;
806       DA.Addr->setReachedDef(0);
807       DA.Addr->setReachedUse(0);
808     }
809   }
810   return NA;
811 }
812 
813 // Allocation routines for specific node types/kinds.
814 
815 NodeAddr<UseNode *> DataFlowGraph::newUse(NodeAddr<InstrNode *> Owner,
816                                           MachineOperand &Op, uint16_t Flags) {
817   NodeAddr<UseNode *> UA = newNode(NodeAttrs::Ref | NodeAttrs::Use | Flags);
818   UA.Addr->setRegRef(&Op, *this);
819   return UA;
820 }
821 
822 NodeAddr<PhiUseNode *> DataFlowGraph::newPhiUse(NodeAddr<PhiNode *> Owner,
823                                                 RegisterRef RR,
824                                                 NodeAddr<BlockNode *> PredB,
825                                                 uint16_t Flags) {
826   NodeAddr<PhiUseNode *> PUA = newNode(NodeAttrs::Ref | NodeAttrs::Use | Flags);
827   assert(Flags & NodeAttrs::PhiRef);
828   PUA.Addr->setRegRef(RR, *this);
829   PUA.Addr->setPredecessor(PredB.Id);
830   return PUA;
831 }
832 
833 NodeAddr<DefNode *> DataFlowGraph::newDef(NodeAddr<InstrNode *> Owner,
834                                           MachineOperand &Op, uint16_t Flags) {
835   NodeAddr<DefNode *> DA = newNode(NodeAttrs::Ref | NodeAttrs::Def | Flags);
836   DA.Addr->setRegRef(&Op, *this);
837   return DA;
838 }
839 
840 NodeAddr<DefNode *> DataFlowGraph::newDef(NodeAddr<InstrNode *> Owner,
841                                           RegisterRef RR, uint16_t Flags) {
842   NodeAddr<DefNode *> DA = newNode(NodeAttrs::Ref | NodeAttrs::Def | Flags);
843   assert(Flags & NodeAttrs::PhiRef);
844   DA.Addr->setRegRef(RR, *this);
845   return DA;
846 }
847 
848 NodeAddr<PhiNode *> DataFlowGraph::newPhi(NodeAddr<BlockNode *> Owner) {
849   NodeAddr<PhiNode *> PA = newNode(NodeAttrs::Code | NodeAttrs::Phi);
850   Owner.Addr->addPhi(PA, *this);
851   return PA;
852 }
853 
854 NodeAddr<StmtNode *> DataFlowGraph::newStmt(NodeAddr<BlockNode *> Owner,
855                                             MachineInstr *MI) {
856   NodeAddr<StmtNode *> SA = newNode(NodeAttrs::Code | NodeAttrs::Stmt);
857   SA.Addr->setCode(MI);
858   Owner.Addr->addMember(SA, *this);
859   return SA;
860 }
861 
862 NodeAddr<BlockNode *> DataFlowGraph::newBlock(NodeAddr<FuncNode *> Owner,
863                                               MachineBasicBlock *BB) {
864   NodeAddr<BlockNode *> BA = newNode(NodeAttrs::Code | NodeAttrs::Block);
865   BA.Addr->setCode(BB);
866   Owner.Addr->addMember(BA, *this);
867   return BA;
868 }
869 
870 NodeAddr<FuncNode *> DataFlowGraph::newFunc(MachineFunction *MF) {
871   NodeAddr<FuncNode *> FA = newNode(NodeAttrs::Code | NodeAttrs::Func);
872   FA.Addr->setCode(MF);
873   return FA;
874 }
875 
876 // Build the data flow graph.
877 void DataFlowGraph::build(unsigned Options) {
878   reset();
879   Func = newFunc(&MF);
880 
881   if (MF.empty())
882     return;
883 
884   for (MachineBasicBlock &B : MF) {
885     NodeAddr<BlockNode *> BA = newBlock(Func, &B);
886     BlockNodes.insert(std::make_pair(&B, BA));
887     for (MachineInstr &I : B) {
888       if (I.isDebugInstr())
889         continue;
890       buildStmt(BA, I);
891     }
892   }
893 
894   NodeAddr<BlockNode *> EA = Func.Addr->getEntryBlock(*this);
895   NodeList Blocks = Func.Addr->members(*this);
896 
897   // Collect information about block references.
898   RegisterSet AllRefs(getPRI());
899   for (NodeAddr<BlockNode *> BA : Blocks)
900     for (NodeAddr<InstrNode *> IA : BA.Addr->members(*this))
901       for (NodeAddr<RefNode *> RA : IA.Addr->members(*this))
902         AllRefs.insert(RA.Addr->getRegRef(*this));
903 
904   // Collect function live-ins and entry block live-ins.
905   MachineRegisterInfo &MRI = MF.getRegInfo();
906   MachineBasicBlock &EntryB = *EA.Addr->getCode();
907   assert(EntryB.pred_empty() && "Function entry block has predecessors");
908   for (std::pair<unsigned, unsigned> P : MRI.liveins())
909     LiveIns.insert(RegisterRef(P.first));
910   if (MRI.tracksLiveness()) {
911     for (auto I : EntryB.liveins())
912       LiveIns.insert(RegisterRef(I.PhysReg, I.LaneMask));
913   }
914 
915   // Add function-entry phi nodes for the live-in registers.
916   for (RegisterRef RR : LiveIns.refs()) {
917     NodeAddr<PhiNode *> PA = newPhi(EA);
918     uint16_t PhiFlags = NodeAttrs::PhiRef | NodeAttrs::Preserving;
919     NodeAddr<DefNode *> DA = newDef(PA, RR, PhiFlags);
920     PA.Addr->addMember(DA, *this);
921   }
922 
923   // Add phis for landing pads.
924   // Landing pads, unlike usual backs blocks, are not entered through
925   // branches in the program, or fall-throughs from other blocks. They
926   // are entered from the exception handling runtime and target's ABI
927   // may define certain registers as defined on entry to such a block.
928   RegisterAggr EHRegs = getLandingPadLiveIns();
929   if (!EHRegs.empty()) {
930     for (NodeAddr<BlockNode *> BA : Blocks) {
931       const MachineBasicBlock &B = *BA.Addr->getCode();
932       if (!B.isEHPad())
933         continue;
934 
935       // Prepare a list of NodeIds of the block's predecessors.
936       NodeList Preds;
937       for (MachineBasicBlock *PB : B.predecessors())
938         Preds.push_back(findBlock(PB));
939 
940       // Build phi nodes for each live-in.
941       for (RegisterRef RR : EHRegs.refs()) {
942         NodeAddr<PhiNode *> PA = newPhi(BA);
943         uint16_t PhiFlags = NodeAttrs::PhiRef | NodeAttrs::Preserving;
944         // Add def:
945         NodeAddr<DefNode *> DA = newDef(PA, RR, PhiFlags);
946         PA.Addr->addMember(DA, *this);
947         // Add uses (no reaching defs for phi uses):
948         for (NodeAddr<BlockNode *> PBA : Preds) {
949           NodeAddr<PhiUseNode *> PUA = newPhiUse(PA, RR, PBA);
950           PA.Addr->addMember(PUA, *this);
951         }
952       }
953     }
954   }
955 
956   // Build a map "PhiM" which will contain, for each block, the set
957   // of references that will require phi definitions in that block.
958   BlockRefsMap PhiM(getPRI());
959   for (NodeAddr<BlockNode *> BA : Blocks)
960     recordDefsForDF(PhiM, BA);
961   for (NodeAddr<BlockNode *> BA : Blocks)
962     buildPhis(PhiM, AllRefs, BA);
963 
964   // Link all the refs. This will recursively traverse the dominator tree.
965   DefStackMap DM;
966   linkBlockRefs(DM, EA);
967 
968   // Finally, remove all unused phi nodes.
969   if (!(Options & BuildOptions::KeepDeadPhis))
970     removeUnusedPhis();
971 }
972 
973 RegisterRef DataFlowGraph::makeRegRef(unsigned Reg, unsigned Sub) const {
974   assert(RegisterRef::isRegId(Reg) || RegisterRef::isMaskId(Reg));
975   assert(Reg != 0);
976   if (Sub != 0)
977     Reg = TRI.getSubReg(Reg, Sub);
978   return RegisterRef(Reg);
979 }
980 
981 RegisterRef DataFlowGraph::makeRegRef(const MachineOperand &Op) const {
982   assert(Op.isReg() || Op.isRegMask());
983   if (Op.isReg())
984     return makeRegRef(Op.getReg(), Op.getSubReg());
985   return RegisterRef(getPRI().getRegMaskId(Op.getRegMask()),
986                      LaneBitmask::getAll());
987 }
988 
989 // For each stack in the map DefM, push the delimiter for block B on it.
990 void DataFlowGraph::markBlock(NodeId B, DefStackMap &DefM) {
991   // Push block delimiters.
992   for (auto &P : DefM)
993     P.second.start_block(B);
994 }
995 
996 // Remove all definitions coming from block B from each stack in DefM.
997 void DataFlowGraph::releaseBlock(NodeId B, DefStackMap &DefM) {
998   // Pop all defs from this block from the definition stack. Defs that were
999   // added to the map during the traversal of instructions will not have a
1000   // delimiter, but for those, the whole stack will be emptied.
1001   for (auto &P : DefM)
1002     P.second.clear_block(B);
1003 
1004   // Finally, remove empty stacks from the map.
1005   for (auto I = DefM.begin(), E = DefM.end(), NextI = I; I != E; I = NextI) {
1006     NextI = std::next(I);
1007     // This preserves the validity of iterators other than I.
1008     if (I->second.empty())
1009       DefM.erase(I);
1010   }
1011 }
1012 
1013 // Push all definitions from the instruction node IA to an appropriate
1014 // stack in DefM.
1015 void DataFlowGraph::pushAllDefs(NodeAddr<InstrNode *> IA, DefStackMap &DefM) {
1016   pushClobbers(IA, DefM);
1017   pushDefs(IA, DefM);
1018 }
1019 
1020 // Push all definitions from the instruction node IA to an appropriate
1021 // stack in DefM.
1022 void DataFlowGraph::pushClobbers(NodeAddr<InstrNode *> IA, DefStackMap &DefM) {
1023   NodeSet Visited;
1024   std::set<RegisterId> Defined;
1025 
1026   // The important objectives of this function are:
1027   // - to be able to handle instructions both while the graph is being
1028   //   constructed, and after the graph has been constructed, and
1029   // - maintain proper ordering of definitions on the stack for each
1030   //   register reference:
1031   //   - if there are two or more related defs in IA (i.e. coming from
1032   //     the same machine operand), then only push one def on the stack,
1033   //   - if there are multiple unrelated defs of non-overlapping
1034   //     subregisters of S, then the stack for S will have both (in an
1035   //     unspecified order), but the order does not matter from the data-
1036   //     -flow perspective.
1037 
1038   for (NodeAddr<DefNode *> DA : IA.Addr->members_if(IsDef, *this)) {
1039     if (Visited.count(DA.Id))
1040       continue;
1041     if (!(DA.Addr->getFlags() & NodeAttrs::Clobbering))
1042       continue;
1043 
1044     NodeList Rel = getRelatedRefs(IA, DA);
1045     NodeAddr<DefNode *> PDA = Rel.front();
1046     RegisterRef RR = PDA.Addr->getRegRef(*this);
1047 
1048     // Push the definition on the stack for the register and all aliases.
1049     // The def stack traversal in linkNodeUp will check the exact aliasing.
1050     DefM[RR.Reg].push(DA);
1051     Defined.insert(RR.Reg);
1052     for (RegisterId A : getPRI().getAliasSet(RR.Reg)) {
1053       // Check that we don't push the same def twice.
1054       assert(A != RR.Reg);
1055       if (!Defined.count(A))
1056         DefM[A].push(DA);
1057     }
1058     // Mark all the related defs as visited.
1059     for (NodeAddr<NodeBase *> T : Rel)
1060       Visited.insert(T.Id);
1061   }
1062 }
1063 
1064 // Push all definitions from the instruction node IA to an appropriate
1065 // stack in DefM.
1066 void DataFlowGraph::pushDefs(NodeAddr<InstrNode *> IA, DefStackMap &DefM) {
1067   NodeSet Visited;
1068 #ifndef NDEBUG
1069   std::set<RegisterId> Defined;
1070 #endif
1071 
1072   // The important objectives of this function are:
1073   // - to be able to handle instructions both while the graph is being
1074   //   constructed, and after the graph has been constructed, and
1075   // - maintain proper ordering of definitions on the stack for each
1076   //   register reference:
1077   //   - if there are two or more related defs in IA (i.e. coming from
1078   //     the same machine operand), then only push one def on the stack,
1079   //   - if there are multiple unrelated defs of non-overlapping
1080   //     subregisters of S, then the stack for S will have both (in an
1081   //     unspecified order), but the order does not matter from the data-
1082   //     -flow perspective.
1083 
1084   for (NodeAddr<DefNode *> DA : IA.Addr->members_if(IsDef, *this)) {
1085     if (Visited.count(DA.Id))
1086       continue;
1087     if (DA.Addr->getFlags() & NodeAttrs::Clobbering)
1088       continue;
1089 
1090     NodeList Rel = getRelatedRefs(IA, DA);
1091     NodeAddr<DefNode *> PDA = Rel.front();
1092     RegisterRef RR = PDA.Addr->getRegRef(*this);
1093 #ifndef NDEBUG
1094     // Assert if the register is defined in two or more unrelated defs.
1095     // This could happen if there are two or more def operands defining it.
1096     if (!Defined.insert(RR.Reg).second) {
1097       MachineInstr *MI = NodeAddr<StmtNode *>(IA).Addr->getCode();
1098       dbgs() << "Multiple definitions of register: " << Print(RR, *this)
1099              << " in\n  " << *MI << "in " << printMBBReference(*MI->getParent())
1100              << '\n';
1101       llvm_unreachable(nullptr);
1102     }
1103 #endif
1104     // Push the definition on the stack for the register and all aliases.
1105     // The def stack traversal in linkNodeUp will check the exact aliasing.
1106     DefM[RR.Reg].push(DA);
1107     for (RegisterId A : getPRI().getAliasSet(RR.Reg)) {
1108       // Check that we don't push the same def twice.
1109       assert(A != RR.Reg);
1110       DefM[A].push(DA);
1111     }
1112     // Mark all the related defs as visited.
1113     for (NodeAddr<NodeBase *> T : Rel)
1114       Visited.insert(T.Id);
1115   }
1116 }
1117 
1118 // Return the list of all reference nodes related to RA, including RA itself.
1119 // See "getNextRelated" for the meaning of a "related reference".
1120 NodeList DataFlowGraph::getRelatedRefs(NodeAddr<InstrNode *> IA,
1121                                        NodeAddr<RefNode *> RA) const {
1122   assert(IA.Id != 0 && RA.Id != 0);
1123 
1124   NodeList Refs;
1125   NodeId Start = RA.Id;
1126   do {
1127     Refs.push_back(RA);
1128     RA = getNextRelated(IA, RA);
1129   } while (RA.Id != 0 && RA.Id != Start);
1130   return Refs;
1131 }
1132 
1133 // Clear all information in the graph.
1134 void DataFlowGraph::reset() {
1135   Memory.clear();
1136   BlockNodes.clear();
1137   Func = NodeAddr<FuncNode *>();
1138 }
1139 
1140 // Return the next reference node in the instruction node IA that is related
1141 // to RA. Conceptually, two reference nodes are related if they refer to the
1142 // same instance of a register access, but differ in flags or other minor
1143 // characteristics. Specific examples of related nodes are shadow reference
1144 // nodes.
1145 // Return the equivalent of nullptr if there are no more related references.
1146 NodeAddr<RefNode *>
1147 DataFlowGraph::getNextRelated(NodeAddr<InstrNode *> IA,
1148                               NodeAddr<RefNode *> RA) const {
1149   assert(IA.Id != 0 && RA.Id != 0);
1150 
1151   auto Related = [this, RA](NodeAddr<RefNode *> TA) -> bool {
1152     if (TA.Addr->getKind() != RA.Addr->getKind())
1153       return false;
1154     if (!getPRI().equal_to(TA.Addr->getRegRef(*this),
1155                            RA.Addr->getRegRef(*this))) {
1156       return false;
1157     }
1158     return true;
1159   };
1160   auto RelatedStmt = [&Related, RA](NodeAddr<RefNode *> TA) -> bool {
1161     return Related(TA) && &RA.Addr->getOp() == &TA.Addr->getOp();
1162   };
1163   auto RelatedPhi = [&Related, RA](NodeAddr<RefNode *> TA) -> bool {
1164     if (!Related(TA))
1165       return false;
1166     if (TA.Addr->getKind() != NodeAttrs::Use)
1167       return true;
1168     // For phi uses, compare predecessor blocks.
1169     const NodeAddr<const PhiUseNode *> TUA = TA;
1170     const NodeAddr<const PhiUseNode *> RUA = RA;
1171     return TUA.Addr->getPredecessor() == RUA.Addr->getPredecessor();
1172   };
1173 
1174   RegisterRef RR = RA.Addr->getRegRef(*this);
1175   if (IA.Addr->getKind() == NodeAttrs::Stmt)
1176     return RA.Addr->getNextRef(RR, RelatedStmt, true, *this);
1177   return RA.Addr->getNextRef(RR, RelatedPhi, true, *this);
1178 }
1179 
1180 // Find the next node related to RA in IA that satisfies condition P.
1181 // If such a node was found, return a pair where the second element is the
1182 // located node. If such a node does not exist, return a pair where the
1183 // first element is the element after which such a node should be inserted,
1184 // and the second element is a null-address.
1185 template <typename Predicate>
1186 std::pair<NodeAddr<RefNode *>, NodeAddr<RefNode *>>
1187 DataFlowGraph::locateNextRef(NodeAddr<InstrNode *> IA, NodeAddr<RefNode *> RA,
1188                              Predicate P) const {
1189   assert(IA.Id != 0 && RA.Id != 0);
1190 
1191   NodeAddr<RefNode *> NA;
1192   NodeId Start = RA.Id;
1193   while (true) {
1194     NA = getNextRelated(IA, RA);
1195     if (NA.Id == 0 || NA.Id == Start)
1196       break;
1197     if (P(NA))
1198       break;
1199     RA = NA;
1200   }
1201 
1202   if (NA.Id != 0 && NA.Id != Start)
1203     return std::make_pair(RA, NA);
1204   return std::make_pair(RA, NodeAddr<RefNode *>());
1205 }
1206 
1207 // Get the next shadow node in IA corresponding to RA, and optionally create
1208 // such a node if it does not exist.
1209 NodeAddr<RefNode *> DataFlowGraph::getNextShadow(NodeAddr<InstrNode *> IA,
1210                                                  NodeAddr<RefNode *> RA,
1211                                                  bool Create) {
1212   assert(IA.Id != 0 && RA.Id != 0);
1213 
1214   uint16_t Flags = RA.Addr->getFlags() | NodeAttrs::Shadow;
1215   auto IsShadow = [Flags](NodeAddr<RefNode *> TA) -> bool {
1216     return TA.Addr->getFlags() == Flags;
1217   };
1218   auto Loc = locateNextRef(IA, RA, IsShadow);
1219   if (Loc.second.Id != 0 || !Create)
1220     return Loc.second;
1221 
1222   // Create a copy of RA and mark is as shadow.
1223   NodeAddr<RefNode *> NA = cloneNode(RA);
1224   NA.Addr->setFlags(Flags | NodeAttrs::Shadow);
1225   IA.Addr->addMemberAfter(Loc.first, NA, *this);
1226   return NA;
1227 }
1228 
1229 // Get the next shadow node in IA corresponding to RA. Return null-address
1230 // if such a node does not exist.
1231 NodeAddr<RefNode *> DataFlowGraph::getNextShadow(NodeAddr<InstrNode *> IA,
1232                                                  NodeAddr<RefNode *> RA) const {
1233   assert(IA.Id != 0 && RA.Id != 0);
1234   uint16_t Flags = RA.Addr->getFlags() | NodeAttrs::Shadow;
1235   auto IsShadow = [Flags](NodeAddr<RefNode *> TA) -> bool {
1236     return TA.Addr->getFlags() == Flags;
1237   };
1238   return locateNextRef(IA, RA, IsShadow).second;
1239 }
1240 
1241 // Create a new statement node in the block node BA that corresponds to
1242 // the machine instruction MI.
1243 void DataFlowGraph::buildStmt(NodeAddr<BlockNode *> BA, MachineInstr &In) {
1244   NodeAddr<StmtNode *> SA = newStmt(BA, &In);
1245 
1246   auto isCall = [](const MachineInstr &In) -> bool {
1247     if (In.isCall())
1248       return true;
1249     // Is tail call?
1250     if (In.isBranch()) {
1251       for (const MachineOperand &Op : In.operands())
1252         if (Op.isGlobal() || Op.isSymbol())
1253           return true;
1254       // Assume indirect branches are calls. This is for the purpose of
1255       // keeping implicit operands, and so it won't hurt on intra-function
1256       // indirect branches.
1257       if (In.isIndirectBranch())
1258         return true;
1259     }
1260     return false;
1261   };
1262 
1263   auto isDefUndef = [this](const MachineInstr &In, RegisterRef DR) -> bool {
1264     // This instruction defines DR. Check if there is a use operand that
1265     // would make DR live on entry to the instruction.
1266     for (const MachineOperand &Op : In.all_uses()) {
1267       if (Op.getReg() == 0 || Op.isUndef())
1268         continue;
1269       RegisterRef UR = makeRegRef(Op);
1270       if (getPRI().alias(DR, UR))
1271         return false;
1272     }
1273     return true;
1274   };
1275 
1276   bool IsCall = isCall(In);
1277   unsigned NumOps = In.getNumOperands();
1278 
1279   // Avoid duplicate implicit defs. This will not detect cases of implicit
1280   // defs that define registers that overlap, but it is not clear how to
1281   // interpret that in the absence of explicit defs. Overlapping explicit
1282   // defs are likely illegal already.
1283   BitVector DoneDefs(TRI.getNumRegs());
1284   // Process explicit defs first.
1285   for (unsigned OpN = 0; OpN < NumOps; ++OpN) {
1286     MachineOperand &Op = In.getOperand(OpN);
1287     if (!Op.isReg() || !Op.isDef() || Op.isImplicit())
1288       continue;
1289     Register R = Op.getReg();
1290     if (!R || !R.isPhysical())
1291       continue;
1292     uint16_t Flags = NodeAttrs::None;
1293     if (TOI.isPreserving(In, OpN)) {
1294       Flags |= NodeAttrs::Preserving;
1295       // If the def is preserving, check if it is also undefined.
1296       if (isDefUndef(In, makeRegRef(Op)))
1297         Flags |= NodeAttrs::Undef;
1298     }
1299     if (TOI.isClobbering(In, OpN))
1300       Flags |= NodeAttrs::Clobbering;
1301     if (TOI.isFixedReg(In, OpN))
1302       Flags |= NodeAttrs::Fixed;
1303     if (IsCall && Op.isDead())
1304       Flags |= NodeAttrs::Dead;
1305     NodeAddr<DefNode *> DA = newDef(SA, Op, Flags);
1306     SA.Addr->addMember(DA, *this);
1307     assert(!DoneDefs.test(R));
1308     DoneDefs.set(R);
1309   }
1310 
1311   // Process reg-masks (as clobbers).
1312   BitVector DoneClobbers(TRI.getNumRegs());
1313   for (unsigned OpN = 0; OpN < NumOps; ++OpN) {
1314     MachineOperand &Op = In.getOperand(OpN);
1315     if (!Op.isRegMask())
1316       continue;
1317     uint16_t Flags = NodeAttrs::Clobbering | NodeAttrs::Fixed | NodeAttrs::Dead;
1318     NodeAddr<DefNode *> DA = newDef(SA, Op, Flags);
1319     SA.Addr->addMember(DA, *this);
1320     // Record all clobbered registers in DoneDefs.
1321     const uint32_t *RM = Op.getRegMask();
1322     for (unsigned i = 1, e = TRI.getNumRegs(); i != e; ++i)
1323       if (!(RM[i / 32] & (1u << (i % 32))))
1324         DoneClobbers.set(i);
1325   }
1326 
1327   // Process implicit defs, skipping those that have already been added
1328   // as explicit.
1329   for (unsigned OpN = 0; OpN < NumOps; ++OpN) {
1330     MachineOperand &Op = In.getOperand(OpN);
1331     if (!Op.isReg() || !Op.isDef() || !Op.isImplicit())
1332       continue;
1333     Register R = Op.getReg();
1334     if (!R || !R.isPhysical() || DoneDefs.test(R))
1335       continue;
1336     RegisterRef RR = makeRegRef(Op);
1337     uint16_t Flags = NodeAttrs::None;
1338     if (TOI.isPreserving(In, OpN)) {
1339       Flags |= NodeAttrs::Preserving;
1340       // If the def is preserving, check if it is also undefined.
1341       if (isDefUndef(In, RR))
1342         Flags |= NodeAttrs::Undef;
1343     }
1344     if (TOI.isClobbering(In, OpN))
1345       Flags |= NodeAttrs::Clobbering;
1346     if (TOI.isFixedReg(In, OpN))
1347       Flags |= NodeAttrs::Fixed;
1348     if (IsCall && Op.isDead()) {
1349       if (DoneClobbers.test(R))
1350         continue;
1351       Flags |= NodeAttrs::Dead;
1352     }
1353     NodeAddr<DefNode *> DA = newDef(SA, Op, Flags);
1354     SA.Addr->addMember(DA, *this);
1355     DoneDefs.set(R);
1356   }
1357 
1358   for (unsigned OpN = 0; OpN < NumOps; ++OpN) {
1359     MachineOperand &Op = In.getOperand(OpN);
1360     if (!Op.isReg() || !Op.isUse())
1361       continue;
1362     Register R = Op.getReg();
1363     if (!R || !R.isPhysical())
1364       continue;
1365     uint16_t Flags = NodeAttrs::None;
1366     if (Op.isUndef())
1367       Flags |= NodeAttrs::Undef;
1368     if (TOI.isFixedReg(In, OpN))
1369       Flags |= NodeAttrs::Fixed;
1370     NodeAddr<UseNode *> UA = newUse(SA, Op, Flags);
1371     SA.Addr->addMember(UA, *this);
1372   }
1373 }
1374 
1375 // Scan all defs in the block node BA and record in PhiM the locations of
1376 // phi nodes corresponding to these defs.
1377 void DataFlowGraph::recordDefsForDF(BlockRefsMap &PhiM,
1378                                     NodeAddr<BlockNode *> BA) {
1379   // Check all defs from block BA and record them in each block in BA's
1380   // iterated dominance frontier. This information will later be used to
1381   // create phi nodes.
1382   MachineBasicBlock *BB = BA.Addr->getCode();
1383   assert(BB);
1384   auto DFLoc = MDF.find(BB);
1385   if (DFLoc == MDF.end() || DFLoc->second.empty())
1386     return;
1387 
1388   // Traverse all instructions in the block and collect the set of all
1389   // defined references. For each reference there will be a phi created
1390   // in the block's iterated dominance frontier.
1391   // This is done to make sure that each defined reference gets only one
1392   // phi node, even if it is defined multiple times.
1393   RegisterAggr Defs(getPRI());
1394   for (NodeAddr<InstrNode *> IA : BA.Addr->members(*this))
1395     for (NodeAddr<RefNode *> RA : IA.Addr->members_if(IsDef, *this))
1396       Defs.insert(RA.Addr->getRegRef(*this));
1397 
1398   // Calculate the iterated dominance frontier of BB.
1399   const MachineDominanceFrontier::DomSetType &DF = DFLoc->second;
1400   SetVector<MachineBasicBlock *> IDF(DF.begin(), DF.end());
1401   for (unsigned i = 0; i < IDF.size(); ++i) {
1402     auto F = MDF.find(IDF[i]);
1403     if (F != MDF.end())
1404       IDF.insert(F->second.begin(), F->second.end());
1405   }
1406 
1407   // Finally, add the set of defs to each block in the iterated dominance
1408   // frontier.
1409   for (auto *DB : IDF) {
1410     NodeAddr<BlockNode *> DBA = findBlock(DB);
1411     PhiM[DBA.Id].insert(Defs);
1412   }
1413 }
1414 
1415 // Given the locations of phi nodes in the map PhiM, create the phi nodes
1416 // that are located in the block node BA.
1417 void DataFlowGraph::buildPhis(BlockRefsMap &PhiM, RegisterSet &AllRefs,
1418                               NodeAddr<BlockNode *> BA) {
1419   // Check if this blocks has any DF defs, i.e. if there are any defs
1420   // that this block is in the iterated dominance frontier of.
1421   auto HasDF = PhiM.find(BA.Id);
1422   if (HasDF == PhiM.end() || HasDF->second.empty())
1423     return;
1424 
1425   // Prepare a list of NodeIds of the block's predecessors.
1426   NodeList Preds;
1427   const MachineBasicBlock *MBB = BA.Addr->getCode();
1428   for (MachineBasicBlock *PB : MBB->predecessors())
1429     Preds.push_back(findBlock(PB));
1430 
1431   const RegisterAggr &Defs = PhiM[BA.Id];
1432   uint16_t PhiFlags = NodeAttrs::PhiRef | NodeAttrs::Preserving;
1433 
1434   for (RegisterRef RR : Defs.refs()) {
1435     NodeAddr<PhiNode *> PA = newPhi(BA);
1436     PA.Addr->addMember(newDef(PA, RR, PhiFlags), *this);
1437 
1438     // Add phi uses.
1439     for (NodeAddr<BlockNode *> PBA : Preds) {
1440       PA.Addr->addMember(newPhiUse(PA, RR, PBA), *this);
1441     }
1442   }
1443 }
1444 
1445 // Remove any unneeded phi nodes that were created during the build process.
1446 void DataFlowGraph::removeUnusedPhis() {
1447   // This will remove unused phis, i.e. phis where each def does not reach
1448   // any uses or other defs. This will not detect or remove circular phi
1449   // chains that are otherwise dead. Unused/dead phis are created during
1450   // the build process and this function is intended to remove these cases
1451   // that are easily determinable to be unnecessary.
1452 
1453   SetVector<NodeId> PhiQ;
1454   for (NodeAddr<BlockNode *> BA : Func.Addr->members(*this)) {
1455     for (auto P : BA.Addr->members_if(IsPhi, *this))
1456       PhiQ.insert(P.Id);
1457   }
1458 
1459   static auto HasUsedDef = [](NodeList &Ms) -> bool {
1460     for (NodeAddr<NodeBase *> M : Ms) {
1461       if (M.Addr->getKind() != NodeAttrs::Def)
1462         continue;
1463       NodeAddr<DefNode *> DA = M;
1464       if (DA.Addr->getReachedDef() != 0 || DA.Addr->getReachedUse() != 0)
1465         return true;
1466     }
1467     return false;
1468   };
1469 
1470   // Any phi, if it is removed, may affect other phis (make them dead).
1471   // For each removed phi, collect the potentially affected phis and add
1472   // them back to the queue.
1473   while (!PhiQ.empty()) {
1474     auto PA = addr<PhiNode *>(PhiQ[0]);
1475     PhiQ.remove(PA.Id);
1476     NodeList Refs = PA.Addr->members(*this);
1477     if (HasUsedDef(Refs))
1478       continue;
1479     for (NodeAddr<RefNode *> RA : Refs) {
1480       if (NodeId RD = RA.Addr->getReachingDef()) {
1481         auto RDA = addr<DefNode *>(RD);
1482         NodeAddr<InstrNode *> OA = RDA.Addr->getOwner(*this);
1483         if (IsPhi(OA))
1484           PhiQ.insert(OA.Id);
1485       }
1486       if (RA.Addr->isDef())
1487         unlinkDef(RA, true);
1488       else
1489         unlinkUse(RA, true);
1490     }
1491     NodeAddr<BlockNode *> BA = PA.Addr->getOwner(*this);
1492     BA.Addr->removeMember(PA, *this);
1493   }
1494 }
1495 
1496 // For a given reference node TA in an instruction node IA, connect the
1497 // reaching def of TA to the appropriate def node. Create any shadow nodes
1498 // as appropriate.
1499 template <typename T>
1500 void DataFlowGraph::linkRefUp(NodeAddr<InstrNode *> IA, NodeAddr<T> TA,
1501                               DefStack &DS) {
1502   if (DS.empty())
1503     return;
1504   RegisterRef RR = TA.Addr->getRegRef(*this);
1505   NodeAddr<T> TAP;
1506 
1507   // References from the def stack that have been examined so far.
1508   RegisterAggr Defs(getPRI());
1509 
1510   for (auto I = DS.top(), E = DS.bottom(); I != E; I.down()) {
1511     RegisterRef QR = I->Addr->getRegRef(*this);
1512 
1513     // Skip all defs that are aliased to any of the defs that we have already
1514     // seen. If this completes a cover of RR, stop the stack traversal.
1515     bool Alias = Defs.hasAliasOf(QR);
1516     bool Cover = Defs.insert(QR).hasCoverOf(RR);
1517     if (Alias) {
1518       if (Cover)
1519         break;
1520       continue;
1521     }
1522 
1523     // The reaching def.
1524     NodeAddr<DefNode *> RDA = *I;
1525 
1526     // Pick the reached node.
1527     if (TAP.Id == 0) {
1528       TAP = TA;
1529     } else {
1530       // Mark the existing ref as "shadow" and create a new shadow.
1531       TAP.Addr->setFlags(TAP.Addr->getFlags() | NodeAttrs::Shadow);
1532       TAP = getNextShadow(IA, TAP, true);
1533     }
1534 
1535     // Create the link.
1536     TAP.Addr->linkToDef(TAP.Id, RDA);
1537 
1538     if (Cover)
1539       break;
1540   }
1541 }
1542 
1543 // Create data-flow links for all reference nodes in the statement node SA.
1544 template <typename Predicate>
1545 void DataFlowGraph::linkStmtRefs(DefStackMap &DefM, NodeAddr<StmtNode *> SA,
1546                                  Predicate P) {
1547 #ifndef NDEBUG
1548   RegisterSet Defs(getPRI());
1549 #endif
1550 
1551   // Link all nodes (upwards in the data-flow) with their reaching defs.
1552   for (NodeAddr<RefNode *> RA : SA.Addr->members_if(P, *this)) {
1553     uint16_t Kind = RA.Addr->getKind();
1554     assert(Kind == NodeAttrs::Def || Kind == NodeAttrs::Use);
1555     RegisterRef RR = RA.Addr->getRegRef(*this);
1556 #ifndef NDEBUG
1557     // Do not expect multiple defs of the same reference.
1558     assert(Kind != NodeAttrs::Def || !Defs.count(RR));
1559     Defs.insert(RR);
1560 #endif
1561 
1562     auto F = DefM.find(RR.Reg);
1563     if (F == DefM.end())
1564       continue;
1565     DefStack &DS = F->second;
1566     if (Kind == NodeAttrs::Use)
1567       linkRefUp<UseNode *>(SA, RA, DS);
1568     else if (Kind == NodeAttrs::Def)
1569       linkRefUp<DefNode *>(SA, RA, DS);
1570     else
1571       llvm_unreachable("Unexpected node in instruction");
1572   }
1573 }
1574 
1575 // Create data-flow links for all instructions in the block node BA. This
1576 // will include updating any phi nodes in BA.
1577 void DataFlowGraph::linkBlockRefs(DefStackMap &DefM, NodeAddr<BlockNode *> BA) {
1578   // Push block delimiters.
1579   markBlock(BA.Id, DefM);
1580 
1581   auto IsClobber = [](NodeAddr<RefNode *> RA) -> bool {
1582     return IsDef(RA) && (RA.Addr->getFlags() & NodeAttrs::Clobbering);
1583   };
1584   auto IsNoClobber = [](NodeAddr<RefNode *> RA) -> bool {
1585     return IsDef(RA) && !(RA.Addr->getFlags() & NodeAttrs::Clobbering);
1586   };
1587 
1588   assert(BA.Addr && "block node address is needed to create a data-flow link");
1589   // For each non-phi instruction in the block, link all the defs and uses
1590   // to their reaching defs. For any member of the block (including phis),
1591   // push the defs on the corresponding stacks.
1592   for (NodeAddr<InstrNode *> IA : BA.Addr->members(*this)) {
1593     // Ignore phi nodes here. They will be linked part by part from the
1594     // predecessors.
1595     if (IA.Addr->getKind() == NodeAttrs::Stmt) {
1596       linkStmtRefs(DefM, IA, IsUse);
1597       linkStmtRefs(DefM, IA, IsClobber);
1598     }
1599 
1600     // Push the definitions on the stack.
1601     pushClobbers(IA, DefM);
1602 
1603     if (IA.Addr->getKind() == NodeAttrs::Stmt)
1604       linkStmtRefs(DefM, IA, IsNoClobber);
1605 
1606     pushDefs(IA, DefM);
1607   }
1608 
1609   // Recursively process all children in the dominator tree.
1610   MachineDomTreeNode *N = MDT.getNode(BA.Addr->getCode());
1611   for (auto *I : *N) {
1612     MachineBasicBlock *SB = I->getBlock();
1613     NodeAddr<BlockNode *> SBA = findBlock(SB);
1614     linkBlockRefs(DefM, SBA);
1615   }
1616 
1617   // Link the phi uses from the successor blocks.
1618   auto IsUseForBA = [BA](NodeAddr<NodeBase *> NA) -> bool {
1619     if (NA.Addr->getKind() != NodeAttrs::Use)
1620       return false;
1621     assert(NA.Addr->getFlags() & NodeAttrs::PhiRef);
1622     NodeAddr<PhiUseNode *> PUA = NA;
1623     return PUA.Addr->getPredecessor() == BA.Id;
1624   };
1625 
1626   RegisterAggr EHLiveIns = getLandingPadLiveIns();
1627   MachineBasicBlock *MBB = BA.Addr->getCode();
1628 
1629   for (MachineBasicBlock *SB : MBB->successors()) {
1630     bool IsEHPad = SB->isEHPad();
1631     NodeAddr<BlockNode *> SBA = findBlock(SB);
1632     for (NodeAddr<InstrNode *> IA : SBA.Addr->members_if(IsPhi, *this)) {
1633       // Do not link phi uses for landing pad live-ins.
1634       if (IsEHPad) {
1635         // Find what register this phi is for.
1636         NodeAddr<RefNode *> RA = IA.Addr->getFirstMember(*this);
1637         assert(RA.Id != 0);
1638         if (EHLiveIns.hasCoverOf(RA.Addr->getRegRef(*this)))
1639           continue;
1640       }
1641       // Go over each phi use associated with MBB, and link it.
1642       for (auto U : IA.Addr->members_if(IsUseForBA, *this)) {
1643         NodeAddr<PhiUseNode *> PUA = U;
1644         RegisterRef RR = PUA.Addr->getRegRef(*this);
1645         linkRefUp<UseNode *>(IA, PUA, DefM[RR.Reg]);
1646       }
1647     }
1648   }
1649 
1650   // Pop all defs from this block from the definition stacks.
1651   releaseBlock(BA.Id, DefM);
1652 }
1653 
1654 // Remove the use node UA from any data-flow and structural links.
1655 void DataFlowGraph::unlinkUseDF(NodeAddr<UseNode *> UA) {
1656   NodeId RD = UA.Addr->getReachingDef();
1657   NodeId Sib = UA.Addr->getSibling();
1658 
1659   if (RD == 0) {
1660     assert(Sib == 0);
1661     return;
1662   }
1663 
1664   auto RDA = addr<DefNode *>(RD);
1665   auto TA = addr<UseNode *>(RDA.Addr->getReachedUse());
1666   if (TA.Id == UA.Id) {
1667     RDA.Addr->setReachedUse(Sib);
1668     return;
1669   }
1670 
1671   while (TA.Id != 0) {
1672     NodeId S = TA.Addr->getSibling();
1673     if (S == UA.Id) {
1674       TA.Addr->setSibling(UA.Addr->getSibling());
1675       return;
1676     }
1677     TA = addr<UseNode *>(S);
1678   }
1679 }
1680 
1681 // Remove the def node DA from any data-flow and structural links.
1682 void DataFlowGraph::unlinkDefDF(NodeAddr<DefNode *> DA) {
1683   //
1684   //         RD
1685   //         | reached
1686   //         | def
1687   //         :
1688   //         .
1689   //        +----+
1690   // ... -- | DA | -- ... -- 0  : sibling chain of DA
1691   //        +----+
1692   //         |  | reached
1693   //         |  : def
1694   //         |  .
1695   //         | ...  : Siblings (defs)
1696   //         |
1697   //         : reached
1698   //         . use
1699   //        ... : sibling chain of reached uses
1700 
1701   NodeId RD = DA.Addr->getReachingDef();
1702 
1703   // Visit all siblings of the reached def and reset their reaching defs.
1704   // Also, defs reached by DA are now "promoted" to being reached by RD,
1705   // so all of them will need to be spliced into the sibling chain where
1706   // DA belongs.
1707   auto getAllNodes = [this](NodeId N) -> NodeList {
1708     NodeList Res;
1709     while (N) {
1710       auto RA = addr<RefNode *>(N);
1711       // Keep the nodes in the exact sibling order.
1712       Res.push_back(RA);
1713       N = RA.Addr->getSibling();
1714     }
1715     return Res;
1716   };
1717   NodeList ReachedDefs = getAllNodes(DA.Addr->getReachedDef());
1718   NodeList ReachedUses = getAllNodes(DA.Addr->getReachedUse());
1719 
1720   if (RD == 0) {
1721     for (NodeAddr<RefNode *> I : ReachedDefs)
1722       I.Addr->setSibling(0);
1723     for (NodeAddr<RefNode *> I : ReachedUses)
1724       I.Addr->setSibling(0);
1725   }
1726   for (NodeAddr<DefNode *> I : ReachedDefs)
1727     I.Addr->setReachingDef(RD);
1728   for (NodeAddr<UseNode *> I : ReachedUses)
1729     I.Addr->setReachingDef(RD);
1730 
1731   NodeId Sib = DA.Addr->getSibling();
1732   if (RD == 0) {
1733     assert(Sib == 0);
1734     return;
1735   }
1736 
1737   // Update the reaching def node and remove DA from the sibling list.
1738   auto RDA = addr<DefNode *>(RD);
1739   auto TA = addr<DefNode *>(RDA.Addr->getReachedDef());
1740   if (TA.Id == DA.Id) {
1741     // If DA is the first reached def, just update the RD's reached def
1742     // to the DA's sibling.
1743     RDA.Addr->setReachedDef(Sib);
1744   } else {
1745     // Otherwise, traverse the sibling list of the reached defs and remove
1746     // DA from it.
1747     while (TA.Id != 0) {
1748       NodeId S = TA.Addr->getSibling();
1749       if (S == DA.Id) {
1750         TA.Addr->setSibling(Sib);
1751         break;
1752       }
1753       TA = addr<DefNode *>(S);
1754     }
1755   }
1756 
1757   // Splice the DA's reached defs into the RDA's reached def chain.
1758   if (!ReachedDefs.empty()) {
1759     auto Last = NodeAddr<DefNode *>(ReachedDefs.back());
1760     Last.Addr->setSibling(RDA.Addr->getReachedDef());
1761     RDA.Addr->setReachedDef(ReachedDefs.front().Id);
1762   }
1763   // Splice the DA's reached uses into the RDA's reached use chain.
1764   if (!ReachedUses.empty()) {
1765     auto Last = NodeAddr<UseNode *>(ReachedUses.back());
1766     Last.Addr->setSibling(RDA.Addr->getReachedUse());
1767     RDA.Addr->setReachedUse(ReachedUses.front().Id);
1768   }
1769 }
1770