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