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