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