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