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