blob: e5cfc7a96b47c74f07795a7ec757f83005d9cf81 [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"
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +000013#include "llvm/ADT/SetVector.h"
Eugene Zelenkob2ca1b32017-01-04 02:02:05 +000014#include "llvm/ADT/STLExtras.h"
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +000015#include "llvm/CodeGen/MachineBasicBlock.h"
16#include "llvm/CodeGen/MachineDominanceFrontier.h"
17#include "llvm/CodeGen/MachineDominators.h"
18#include "llvm/CodeGen/MachineFunction.h"
Eugene Zelenkob2ca1b32017-01-04 02:02:05 +000019#include "llvm/CodeGen/MachineInstr.h"
20#include "llvm/CodeGen/MachineOperand.h"
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +000021#include "llvm/CodeGen/MachineRegisterInfo.h"
Eugene Zelenkob2ca1b32017-01-04 02:02:05 +000022#include "llvm/IR/Function.h"
23#include "llvm/MC/LaneBitmask.h"
24#include "llvm/MC/MCInstrDesc.h"
25#include "llvm/MC/MCRegisterInfo.h"
26#include "llvm/Support/ErrorHandling.h"
27#include "llvm/Support/raw_ostream.h"
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +000028#include "llvm/Target/TargetInstrInfo.h"
Krzysztof Parzyszek1d322202016-09-27 18:18:44 +000029#include "llvm/Target/TargetLowering.h"
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +000030#include "llvm/Target/TargetRegisterInfo.h"
Eugene Zelenkob2ca1b32017-01-04 02:02:05 +000031#include <algorithm>
32#include <cassert>
33#include <cstdint>
34#include <cstring>
35#include <iterator>
36#include <utility>
37#include <vector>
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +000038
39using namespace llvm;
40using namespace rdf;
41
42// Printing functions. Have them here first, so that the rest of the code
43// can use them.
Benjamin Kramer922efd72016-05-27 10:06:40 +000044namespace llvm {
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +000045namespace rdf {
46
Krzysztof Parzyszek7bb63ac2016-10-19 16:30:56 +000047raw_ostream &operator<< (raw_ostream &OS, const PrintLaneMaskOpt &P) {
Krzysztof Parzyszek91b5cf82016-12-15 14:36:06 +000048 if (!P.Mask.all())
Krzysztof Parzyszek7bb63ac2016-10-19 16:30:56 +000049 OS << ':' << PrintLaneMask(P.Mask);
50 return OS;
51}
52
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +000053template<>
54raw_ostream &operator<< (raw_ostream &OS, const Print<RegisterRef> &P) {
55 auto &TRI = P.G.getTRI();
56 if (P.Obj.Reg > 0 && P.Obj.Reg < TRI.getNumRegs())
57 OS << TRI.getName(P.Obj.Reg);
58 else
59 OS << '#' << P.Obj.Reg;
Krzysztof Parzyszek7bb63ac2016-10-19 16:30:56 +000060 OS << PrintLaneMaskOpt(P.Obj.Mask);
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +000061 return OS;
62}
63
64template<>
65raw_ostream &operator<< (raw_ostream &OS, const Print<NodeId> &P) {
66 auto NA = P.G.addr<NodeBase*>(P.Obj);
67 uint16_t Attrs = NA.Addr->getAttrs();
68 uint16_t Kind = NodeAttrs::kind(Attrs);
69 uint16_t Flags = NodeAttrs::flags(Attrs);
70 switch (NodeAttrs::type(Attrs)) {
71 case NodeAttrs::Code:
72 switch (Kind) {
73 case NodeAttrs::Func: OS << 'f'; break;
74 case NodeAttrs::Block: OS << 'b'; break;
75 case NodeAttrs::Stmt: OS << 's'; break;
76 case NodeAttrs::Phi: OS << 'p'; break;
77 default: OS << "c?"; break;
78 }
79 break;
80 case NodeAttrs::Ref:
Krzysztof Parzyszek1ff99522016-09-07 20:10:56 +000081 if (Flags & NodeAttrs::Undef)
82 OS << '/';
Krzysztof Parzyszek586fc122016-09-27 18:24:33 +000083 if (Flags & NodeAttrs::Dead)
84 OS << '\\';
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +000085 if (Flags & NodeAttrs::Preserving)
86 OS << '+';
87 if (Flags & NodeAttrs::Clobbering)
88 OS << '~';
89 switch (Kind) {
90 case NodeAttrs::Use: OS << 'u'; break;
91 case NodeAttrs::Def: OS << 'd'; break;
92 case NodeAttrs::Block: OS << 'b'; break;
93 default: OS << "r?"; break;
94 }
95 break;
96 default:
97 OS << '?';
98 break;
99 }
100 OS << P.Obj;
101 if (Flags & NodeAttrs::Shadow)
102 OS << '"';
103 return OS;
104}
105
Eugene Zelenkob2ca1b32017-01-04 02:02:05 +0000106static void printRefHeader(raw_ostream &OS, const NodeAddr<RefNode*> RA,
107 const DataFlowGraph &G) {
108 OS << Print<NodeId>(RA.Id, G) << '<'
109 << Print<RegisterRef>(RA.Addr->getRegRef(G), G) << '>';
110 if (RA.Addr->getFlags() & NodeAttrs::Fixed)
111 OS << '!';
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000112}
113
114template<>
115raw_ostream &operator<< (raw_ostream &OS, const Print<NodeAddr<DefNode*>> &P) {
116 printRefHeader(OS, P.Obj, P.G);
117 OS << '(';
118 if (NodeId N = P.Obj.Addr->getReachingDef())
119 OS << Print<NodeId>(N, P.G);
120 OS << ',';
121 if (NodeId N = P.Obj.Addr->getReachedDef())
122 OS << Print<NodeId>(N, P.G);
123 OS << ',';
124 if (NodeId N = P.Obj.Addr->getReachedUse())
125 OS << Print<NodeId>(N, P.G);
126 OS << "):";
127 if (NodeId N = P.Obj.Addr->getSibling())
128 OS << Print<NodeId>(N, P.G);
129 return OS;
130}
131
132template<>
133raw_ostream &operator<< (raw_ostream &OS, const Print<NodeAddr<UseNode*>> &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->getSibling())
140 OS << Print<NodeId>(N, P.G);
141 return OS;
142}
143
144template<>
145raw_ostream &operator<< (raw_ostream &OS,
146 const Print<NodeAddr<PhiUseNode*>> &P) {
147 printRefHeader(OS, P.Obj, P.G);
148 OS << '(';
149 if (NodeId N = P.Obj.Addr->getReachingDef())
150 OS << Print<NodeId>(N, P.G);
151 OS << ',';
152 if (NodeId N = P.Obj.Addr->getPredecessor())
153 OS << Print<NodeId>(N, P.G);
154 OS << "):";
155 if (NodeId N = P.Obj.Addr->getSibling())
156 OS << Print<NodeId>(N, P.G);
157 return OS;
158}
159
160template<>
161raw_ostream &operator<< (raw_ostream &OS, const Print<NodeAddr<RefNode*>> &P) {
162 switch (P.Obj.Addr->getKind()) {
163 case NodeAttrs::Def:
164 OS << PrintNode<DefNode*>(P.Obj, P.G);
165 break;
166 case NodeAttrs::Use:
167 if (P.Obj.Addr->getFlags() & NodeAttrs::PhiRef)
168 OS << PrintNode<PhiUseNode*>(P.Obj, P.G);
169 else
170 OS << PrintNode<UseNode*>(P.Obj, P.G);
171 break;
172 }
173 return OS;
174}
175
176template<>
177raw_ostream &operator<< (raw_ostream &OS, const Print<NodeList> &P) {
178 unsigned N = P.Obj.size();
179 for (auto I : P.Obj) {
180 OS << Print<NodeId>(I.Id, P.G);
181 if (--N)
182 OS << ' ';
183 }
184 return OS;
185}
186
187template<>
188raw_ostream &operator<< (raw_ostream &OS, const Print<NodeSet> &P) {
189 unsigned N = P.Obj.size();
190 for (auto I : P.Obj) {
191 OS << Print<NodeId>(I, P.G);
192 if (--N)
193 OS << ' ';
194 }
195 return OS;
196}
197
198namespace {
Eugene Zelenkob2ca1b32017-01-04 02:02:05 +0000199
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000200 template <typename T>
201 struct PrintListV {
202 PrintListV(const NodeList &L, const DataFlowGraph &G) : List(L), G(G) {}
Eugene Zelenkob2ca1b32017-01-04 02:02:05 +0000203
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000204 typedef T Type;
205 const NodeList &List;
206 const DataFlowGraph &G;
207 };
208
209 template <typename T>
210 raw_ostream &operator<< (raw_ostream &OS, const PrintListV<T> &P) {
211 unsigned N = P.List.size();
212 for (NodeAddr<T> A : P.List) {
213 OS << PrintNode<T>(A, P.G);
214 if (--N)
215 OS << ", ";
216 }
217 return OS;
218 }
Eugene Zelenkob2ca1b32017-01-04 02:02:05 +0000219
220} // end anonymous namespace
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000221
222template<>
223raw_ostream &operator<< (raw_ostream &OS, const Print<NodeAddr<PhiNode*>> &P) {
224 OS << Print<NodeId>(P.Obj.Id, P.G) << ": phi ["
225 << PrintListV<RefNode*>(P.Obj.Addr->members(P.G), P.G) << ']';
226 return OS;
227}
228
229template<>
230raw_ostream &operator<< (raw_ostream &OS,
231 const Print<NodeAddr<StmtNode*>> &P) {
Krzysztof Parzyszek670e0ca2016-09-22 20:58:19 +0000232 const MachineInstr &MI = *P.Obj.Addr->getCode();
233 unsigned Opc = MI.getOpcode();
234 OS << Print<NodeId>(P.Obj.Id, P.G) << ": " << P.G.getTII().getName(Opc);
Krzysztof Parzyszekab26e2d2016-10-03 17:54:33 +0000235 // Print the target for calls and branches (for readability).
236 if (MI.isCall() || MI.isBranch()) {
237 MachineInstr::const_mop_iterator T =
Eugene Zelenkob2ca1b32017-01-04 02:02:05 +0000238 llvm::find_if(MI.operands(),
239 [] (const MachineOperand &Op) -> bool {
240 return Op.isMBB() || Op.isGlobal() || Op.isSymbol();
241 });
Krzysztof Parzyszekab26e2d2016-10-03 17:54:33 +0000242 if (T != MI.operands_end()) {
243 OS << ' ';
244 if (T->isMBB())
245 OS << "BB#" << T->getMBB()->getNumber();
246 else if (T->isGlobal())
247 OS << T->getGlobal()->getName();
248 else if (T->isSymbol())
249 OS << T->getSymbolName();
Krzysztof Parzyszek670e0ca2016-09-22 20:58:19 +0000250 }
251 }
252 OS << " [" << PrintListV<RefNode*>(P.Obj.Addr->members(P.G), P.G) << ']';
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000253 return OS;
254}
255
256template<>
257raw_ostream &operator<< (raw_ostream &OS,
258 const Print<NodeAddr<InstrNode*>> &P) {
259 switch (P.Obj.Addr->getKind()) {
260 case NodeAttrs::Phi:
261 OS << PrintNode<PhiNode*>(P.Obj, P.G);
262 break;
263 case NodeAttrs::Stmt:
264 OS << PrintNode<StmtNode*>(P.Obj, P.G);
265 break;
266 default:
267 OS << "instr? " << Print<NodeId>(P.Obj.Id, P.G);
268 break;
269 }
270 return OS;
271}
272
273template<>
274raw_ostream &operator<< (raw_ostream &OS,
275 const Print<NodeAddr<BlockNode*>> &P) {
Krzysztof Parzyszek61d90322016-10-06 13:05:13 +0000276 MachineBasicBlock *BB = P.Obj.Addr->getCode();
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000277 unsigned NP = BB->pred_size();
278 std::vector<int> Ns;
Malcolm Parsons17d266b2017-01-13 17:12:16 +0000279 auto PrintBBs = [&OS] (std::vector<int> Ns) -> void {
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000280 unsigned N = Ns.size();
Krzysztof Parzyszek61d90322016-10-06 13:05:13 +0000281 for (int I : Ns) {
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000282 OS << "BB#" << I;
283 if (--N)
284 OS << ", ";
285 }
286 };
287
Krzysztof Parzyszekab26e2d2016-10-03 17:54:33 +0000288 OS << Print<NodeId>(P.Obj.Id, P.G) << ": --- BB#" << BB->getNumber()
289 << " --- preds(" << NP << "): ";
Krzysztof Parzyszek61d90322016-10-06 13:05:13 +0000290 for (MachineBasicBlock *B : BB->predecessors())
291 Ns.push_back(B->getNumber());
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000292 PrintBBs(Ns);
293
294 unsigned NS = BB->succ_size();
295 OS << " succs(" << NS << "): ";
296 Ns.clear();
Krzysztof Parzyszek61d90322016-10-06 13:05:13 +0000297 for (MachineBasicBlock *B : BB->successors())
298 Ns.push_back(B->getNumber());
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000299 PrintBBs(Ns);
300 OS << '\n';
301
302 for (auto I : P.Obj.Addr->members(P.G))
303 OS << PrintNode<InstrNode*>(I, P.G) << '\n';
304 return OS;
305}
306
307template<>
308raw_ostream &operator<< (raw_ostream &OS,
309 const Print<NodeAddr<FuncNode*>> &P) {
310 OS << "DFG dump:[\n" << Print<NodeId>(P.Obj.Id, P.G) << ": Function: "
311 << P.Obj.Addr->getCode()->getName() << '\n';
312 for (auto I : P.Obj.Addr->members(P.G))
313 OS << PrintNode<BlockNode*>(I, P.G) << '\n';
314 OS << "]\n";
315 return OS;
316}
317
318template<>
319raw_ostream &operator<< (raw_ostream &OS, const Print<RegisterSet> &P) {
320 OS << '{';
321 for (auto I : P.Obj)
322 OS << ' ' << Print<RegisterRef>(I, P.G);
323 OS << " }";
324 return OS;
325}
326
327template<>
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +0000328raw_ostream &operator<< (raw_ostream &OS, const Print<RegisterAggr> &P) {
329 P.Obj.print(OS);
330 return OS;
331}
332
333template<>
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000334raw_ostream &operator<< (raw_ostream &OS,
335 const Print<DataFlowGraph::DefStack> &P) {
336 for (auto I = P.Obj.top(), E = P.Obj.bottom(); I != E; ) {
337 OS << Print<NodeId>(I->Id, P.G)
Krzysztof Parzyszek445bd122016-10-14 17:57:55 +0000338 << '<' << Print<RegisterRef>(I->Addr->getRegRef(P.G), P.G) << '>';
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000339 I.down();
340 if (I != E)
341 OS << ' ';
342 }
343 return OS;
344}
345
Eugene Zelenkob2ca1b32017-01-04 02:02:05 +0000346} // end namespace rdf
347} // end namespace llvm
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000348
349// Node allocation functions.
350//
351// Node allocator is like a slab memory allocator: it allocates blocks of
352// memory in sizes that are multiples of the size of a node. Each block has
353// the same size. Nodes are allocated from the currently active block, and
354// when it becomes full, a new one is created.
355// There is a mapping scheme between node id and its location in a block,
356// and within that block is described in the header file.
357//
358void NodeAllocator::startNewBlock() {
359 void *T = MemPool.Allocate(NodesPerBlock*NodeMemSize, NodeMemSize);
360 char *P = static_cast<char*>(T);
361 Blocks.push_back(P);
362 // Check if the block index is still within the allowed range, i.e. less
363 // than 2^N, where N is the number of bits in NodeId for the block index.
364 // BitsPerIndex is the number of bits per node index.
Simon Pilgrim99c6c292016-01-18 21:11:19 +0000365 assert((Blocks.size() < ((size_t)1 << (8*sizeof(NodeId)-BitsPerIndex))) &&
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000366 "Out of bits for block index");
367 ActiveEnd = P;
368}
369
370bool NodeAllocator::needNewBlock() {
371 if (Blocks.empty())
372 return true;
373
374 char *ActiveBegin = Blocks.back();
375 uint32_t Index = (ActiveEnd-ActiveBegin)/NodeMemSize;
376 return Index >= NodesPerBlock;
377}
378
379NodeAddr<NodeBase*> NodeAllocator::New() {
380 if (needNewBlock())
381 startNewBlock();
382
383 uint32_t ActiveB = Blocks.size()-1;
384 uint32_t Index = (ActiveEnd - Blocks[ActiveB])/NodeMemSize;
385 NodeAddr<NodeBase*> NA = { reinterpret_cast<NodeBase*>(ActiveEnd),
386 makeId(ActiveB, Index) };
387 ActiveEnd += NodeMemSize;
388 return NA;
389}
390
391NodeId NodeAllocator::id(const NodeBase *P) const {
392 uintptr_t A = reinterpret_cast<uintptr_t>(P);
393 for (unsigned i = 0, n = Blocks.size(); i != n; ++i) {
394 uintptr_t B = reinterpret_cast<uintptr_t>(Blocks[i]);
395 if (A < B || A >= B + NodesPerBlock*NodeMemSize)
396 continue;
397 uint32_t Idx = (A-B)/NodeMemSize;
398 return makeId(i, Idx);
399 }
400 llvm_unreachable("Invalid node address");
401}
402
403void NodeAllocator::clear() {
404 MemPool.Reset();
405 Blocks.clear();
406 ActiveEnd = nullptr;
407}
408
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000409// Insert node NA after "this" in the circular chain.
410void NodeBase::append(NodeAddr<NodeBase*> NA) {
411 NodeId Nx = Next;
412 // If NA is already "next", do nothing.
413 if (Next != NA.Id) {
414 Next = NA.Id;
415 NA.Addr->Next = Nx;
416 }
417}
418
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000419// Fundamental node manipulator functions.
420
421// Obtain the register reference from a reference node.
Krzysztof Parzyszek445bd122016-10-14 17:57:55 +0000422RegisterRef RefNode::getRegRef(const DataFlowGraph &G) const {
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000423 assert(NodeAttrs::type(Attrs) == NodeAttrs::Ref);
424 if (NodeAttrs::flags(Attrs) & NodeAttrs::PhiRef)
Krzysztof Parzyszek445bd122016-10-14 17:57:55 +0000425 return G.unpack(Ref.PR);
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000426 assert(Ref.Op != nullptr);
Krzysztof Parzyszek445bd122016-10-14 17:57:55 +0000427 return G.makeRegRef(Ref.Op->getReg(), Ref.Op->getSubReg());
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000428}
429
430// Set the register reference in the reference node directly (for references
431// in phi nodes).
Krzysztof Parzyszek445bd122016-10-14 17:57:55 +0000432void RefNode::setRegRef(RegisterRef RR, DataFlowGraph &G) {
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000433 assert(NodeAttrs::type(Attrs) == NodeAttrs::Ref);
434 assert(NodeAttrs::flags(Attrs) & NodeAttrs::PhiRef);
Krzysztof Parzyszek445bd122016-10-14 17:57:55 +0000435 Ref.PR = G.pack(RR);
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000436}
437
438// Set the register reference in the reference node based on a machine
439// operand (for references in statement nodes).
Krzysztof Parzyszek445bd122016-10-14 17:57:55 +0000440void RefNode::setRegRef(MachineOperand *Op, DataFlowGraph &G) {
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000441 assert(NodeAttrs::type(Attrs) == NodeAttrs::Ref);
442 assert(!(NodeAttrs::flags(Attrs) & NodeAttrs::PhiRef));
Krzysztof Parzyszek445bd122016-10-14 17:57:55 +0000443 (void)G;
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000444 Ref.Op = Op;
445}
446
447// Get the owner of a given reference node.
448NodeAddr<NodeBase*> RefNode::getOwner(const DataFlowGraph &G) {
449 NodeAddr<NodeBase*> NA = G.addr<NodeBase*>(getNext());
450
451 while (NA.Addr != this) {
452 if (NA.Addr->getType() == NodeAttrs::Code)
453 return NA;
454 NA = G.addr<NodeBase*>(NA.Addr->getNext());
455 }
456 llvm_unreachable("No owner in circular list");
457}
458
459// Connect the def node to the reaching def node.
460void DefNode::linkToDef(NodeId Self, NodeAddr<DefNode*> DA) {
461 Ref.RD = DA.Id;
462 Ref.Sib = DA.Addr->getReachedDef();
463 DA.Addr->setReachedDef(Self);
464}
465
466// Connect the use node to the reaching def node.
467void UseNode::linkToDef(NodeId Self, NodeAddr<DefNode*> DA) {
468 Ref.RD = DA.Id;
469 Ref.Sib = DA.Addr->getReachedUse();
470 DA.Addr->setReachedUse(Self);
471}
472
473// Get the first member of the code node.
474NodeAddr<NodeBase*> CodeNode::getFirstMember(const DataFlowGraph &G) const {
475 if (Code.FirstM == 0)
476 return NodeAddr<NodeBase*>();
477 return G.addr<NodeBase*>(Code.FirstM);
478}
479
480// Get the last member of the code node.
481NodeAddr<NodeBase*> CodeNode::getLastMember(const DataFlowGraph &G) const {
482 if (Code.LastM == 0)
483 return NodeAddr<NodeBase*>();
484 return G.addr<NodeBase*>(Code.LastM);
485}
486
487// Add node NA at the end of the member list of the given code node.
488void CodeNode::addMember(NodeAddr<NodeBase*> NA, const DataFlowGraph &G) {
Krzysztof Parzyszek61d90322016-10-06 13:05:13 +0000489 NodeAddr<NodeBase*> ML = getLastMember(G);
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000490 if (ML.Id != 0) {
491 ML.Addr->append(NA);
492 } else {
493 Code.FirstM = NA.Id;
494 NodeId Self = G.id(this);
495 NA.Addr->setNext(Self);
496 }
497 Code.LastM = NA.Id;
498}
499
500// Add node NA after member node MA in the given code node.
501void CodeNode::addMemberAfter(NodeAddr<NodeBase*> MA, NodeAddr<NodeBase*> NA,
502 const DataFlowGraph &G) {
503 MA.Addr->append(NA);
504 if (Code.LastM == MA.Id)
505 Code.LastM = NA.Id;
506}
507
508// Remove member node NA from the given code node.
509void CodeNode::removeMember(NodeAddr<NodeBase*> NA, const DataFlowGraph &G) {
Krzysztof Parzyszek61d90322016-10-06 13:05:13 +0000510 NodeAddr<NodeBase*> MA = getFirstMember(G);
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000511 assert(MA.Id != 0);
512
513 // Special handling if the member to remove is the first member.
514 if (MA.Id == NA.Id) {
515 if (Code.LastM == MA.Id) {
516 // If it is the only member, set both first and last to 0.
517 Code.FirstM = Code.LastM = 0;
518 } else {
519 // Otherwise, advance the first member.
520 Code.FirstM = MA.Addr->getNext();
521 }
522 return;
523 }
524
525 while (MA.Addr != this) {
526 NodeId MX = MA.Addr->getNext();
527 if (MX == NA.Id) {
528 MA.Addr->setNext(NA.Addr->getNext());
529 // If the member to remove happens to be the last one, update the
530 // LastM indicator.
531 if (Code.LastM == NA.Id)
532 Code.LastM = MA.Id;
533 return;
534 }
535 MA = G.addr<NodeBase*>(MX);
536 }
537 llvm_unreachable("No such member");
538}
539
540// Return the list of all members of the code node.
541NodeList CodeNode::members(const DataFlowGraph &G) const {
542 static auto True = [] (NodeAddr<NodeBase*>) -> bool { return true; };
543 return members_if(True, G);
544}
545
546// Return the owner of the given instr node.
547NodeAddr<NodeBase*> InstrNode::getOwner(const DataFlowGraph &G) {
548 NodeAddr<NodeBase*> NA = G.addr<NodeBase*>(getNext());
549
550 while (NA.Addr != this) {
551 assert(NA.Addr->getType() == NodeAttrs::Code);
552 if (NA.Addr->getKind() == NodeAttrs::Block)
553 return NA;
554 NA = G.addr<NodeBase*>(NA.Addr->getNext());
555 }
556 llvm_unreachable("No owner in circular list");
557}
558
559// Add the phi node PA to the given block node.
560void BlockNode::addPhi(NodeAddr<PhiNode*> PA, const DataFlowGraph &G) {
Krzysztof Parzyszek61d90322016-10-06 13:05:13 +0000561 NodeAddr<NodeBase*> M = getFirstMember(G);
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000562 if (M.Id == 0) {
563 addMember(PA, G);
564 return;
565 }
566
567 assert(M.Addr->getType() == NodeAttrs::Code);
568 if (M.Addr->getKind() == NodeAttrs::Stmt) {
569 // If the first member of the block is a statement, insert the phi as
570 // the first member.
571 Code.FirstM = PA.Id;
572 PA.Addr->setNext(M.Id);
573 } else {
574 // If the first member is a phi, find the last phi, and append PA to it.
575 assert(M.Addr->getKind() == NodeAttrs::Phi);
576 NodeAddr<NodeBase*> MN = M;
577 do {
578 M = MN;
579 MN = G.addr<NodeBase*>(M.Addr->getNext());
580 assert(MN.Addr->getType() == NodeAttrs::Code);
581 } while (MN.Addr->getKind() == NodeAttrs::Phi);
582
583 // M is the last phi.
584 addMemberAfter(M, PA, G);
585 }
586}
587
588// Find the block node corresponding to the machine basic block BB in the
589// given func node.
590NodeAddr<BlockNode*> FuncNode::findBlock(const MachineBasicBlock *BB,
591 const DataFlowGraph &G) const {
592 auto EqBB = [BB] (NodeAddr<NodeBase*> NA) -> bool {
593 return NodeAddr<BlockNode*>(NA).Addr->getCode() == BB;
594 };
595 NodeList Ms = members_if(EqBB, G);
596 if (!Ms.empty())
597 return Ms[0];
598 return NodeAddr<BlockNode*>();
599}
600
601// Get the block node for the entry block in the given function.
602NodeAddr<BlockNode*> FuncNode::getEntryBlock(const DataFlowGraph &G) {
603 MachineBasicBlock *EntryB = &getCode()->front();
604 return findBlock(EntryB, G);
605}
606
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000607// Target operand information.
608//
609
610// For a given instruction, check if there are any bits of RR that can remain
611// unchanged across this def.
612bool TargetOperandInfo::isPreserving(const MachineInstr &In, unsigned OpNum)
613 const {
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +0000614 return TII.isPredicated(In);
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000615}
616
617// Check if the definition of RR produces an unspecified value.
618bool TargetOperandInfo::isClobbering(const MachineInstr &In, unsigned OpNum)
619 const {
620 if (In.isCall())
621 if (In.getOperand(OpNum).isImplicit())
622 return true;
623 return false;
624}
625
Krzysztof Parzyszekc5a4e262016-04-28 20:33:33 +0000626// Check if the given instruction specifically requires
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000627bool TargetOperandInfo::isFixedReg(const MachineInstr &In, unsigned OpNum)
628 const {
Krzysztof Parzyszekc5a4e262016-04-28 20:33:33 +0000629 if (In.isCall() || In.isReturn() || In.isInlineAsm())
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000630 return true;
Krzysztof Parzyszekbf90d5a2016-04-28 20:40:08 +0000631 // Check for a tail call.
632 if (In.isBranch())
Krzysztof Parzyszek61d90322016-10-06 13:05:13 +0000633 for (const MachineOperand &O : In.operands())
Krzysztof Parzyszekbf90d5a2016-04-28 20:40:08 +0000634 if (O.isGlobal() || O.isSymbol())
635 return true;
636
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000637 const MCInstrDesc &D = In.getDesc();
638 if (!D.getImplicitDefs() && !D.getImplicitUses())
639 return false;
640 const MachineOperand &Op = In.getOperand(OpNum);
641 // If there is a sub-register, treat the operand as non-fixed. Currently,
642 // fixed registers are those that are listed in the descriptor as implicit
643 // uses or defs, and those lists do not allow sub-registers.
644 if (Op.getSubReg() != 0)
645 return false;
Krzysztof Parzyszek6e7fa992016-10-21 19:12:13 +0000646 RegisterId Reg = Op.getReg();
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000647 const MCPhysReg *ImpR = Op.isDef() ? D.getImplicitDefs()
648 : D.getImplicitUses();
649 if (!ImpR)
650 return false;
651 while (*ImpR)
652 if (*ImpR++ == Reg)
653 return true;
654 return false;
655}
656
Krzysztof Parzyszek445bd122016-10-14 17:57:55 +0000657RegisterRef RegisterAggr::normalize(RegisterRef RR) const {
Krzysztof Parzyszek6e7fa992016-10-21 19:12:13 +0000658 RegisterId SuperReg = RR.Reg;
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +0000659 while (true) {
660 MCSuperRegIterator SR(SuperReg, &TRI, false);
661 if (!SR.isValid())
Krzysztof Parzyszek445bd122016-10-14 17:57:55 +0000662 break;
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +0000663 SuperReg = *SR;
664 }
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +0000665
Krzysztof Parzyszek445bd122016-10-14 17:57:55 +0000666 const TargetRegisterClass &RC = *TRI.getMinimalPhysRegClass(RR.Reg);
Krzysztof Parzyszek77a45572016-12-08 20:33:45 +0000667 LaneBitmask Common = RR.Mask & RC.LaneMask;
668 uint32_t Sub = TRI.getSubRegIndex(SuperReg, RR.Reg);
669 LaneBitmask SuperMask = TRI.composeSubRegIndexLaneMask(Sub, Common);
Krzysztof Parzyszek445bd122016-10-14 17:57:55 +0000670 return RegisterRef(SuperReg, SuperMask);
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +0000671}
672
673bool RegisterAggr::hasAliasOf(RegisterRef RR) const {
Krzysztof Parzyszek445bd122016-10-14 17:57:55 +0000674 RegisterRef NR = normalize(RR);
675 auto F = Masks.find(NR.Reg);
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +0000676 if (F != Masks.end()) {
Krzysztof Parzyszekea9f8ce2016-12-16 19:11:56 +0000677 if ((F->second & NR.Mask).any())
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +0000678 return true;
679 }
680 if (CheckUnits) {
681 for (MCRegUnitIterator U(RR.Reg, &TRI); U.isValid(); ++U)
682 if (ExpAliasUnits.test(*U))
683 return true;
684 }
685 return false;
686}
687
688bool RegisterAggr::hasCoverOf(RegisterRef RR) const {
Krzysztof Parzyszek445bd122016-10-14 17:57:55 +0000689 // Always have a cover for empty lane mask.
690 RegisterRef NR = normalize(RR);
Krzysztof Parzyszek91b5cf82016-12-15 14:36:06 +0000691 if (NR.Mask.none())
Krzysztof Parzyszek445bd122016-10-14 17:57:55 +0000692 return true;
693 auto F = Masks.find(NR.Reg);
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +0000694 if (F == Masks.end())
695 return false;
Krzysztof Parzyszek445bd122016-10-14 17:57:55 +0000696 return (NR.Mask & F->second) == NR.Mask;
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +0000697}
698
699RegisterAggr &RegisterAggr::insert(RegisterRef RR) {
Krzysztof Parzyszek445bd122016-10-14 17:57:55 +0000700 RegisterRef NR = normalize(RR);
701 auto F = Masks.find(NR.Reg);
702 if (F == Masks.end())
703 Masks.insert({NR.Reg, NR.Mask});
704 else
705 F->second |= NR.Mask;
706
707 // Visit all register units to see if there are any that were created
708 // by explicit aliases. Add those that were to the bit vector.
709 for (MCRegUnitIterator U(RR.Reg, &TRI); U.isValid(); ++U) {
710 MCRegUnitRootIterator R(*U, &TRI);
711 ++R;
712 if (!R.isValid())
713 continue;
714 ExpAliasUnits.set(*U);
715 CheckUnits = true;
716 }
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +0000717 return *this;
718}
719
720RegisterAggr &RegisterAggr::insert(const RegisterAggr &RG) {
Krzysztof Parzyszek6e7fa992016-10-21 19:12:13 +0000721 for (std::pair<RegisterId,LaneBitmask> P : RG.Masks)
Krzysztof Parzyszek445bd122016-10-14 17:57:55 +0000722 insert(RegisterRef(P.first, P.second));
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +0000723 return *this;
724}
725
726RegisterAggr &RegisterAggr::clear(RegisterRef RR) {
Krzysztof Parzyszek445bd122016-10-14 17:57:55 +0000727 RegisterRef NR = normalize(RR);
728 auto F = Masks.find(NR.Reg);
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +0000729 if (F == Masks.end())
730 return *this;
Krzysztof Parzyszek445bd122016-10-14 17:57:55 +0000731 LaneBitmask NewM = F->second & ~NR.Mask;
Krzysztof Parzyszek91b5cf82016-12-15 14:36:06 +0000732 if (NewM.none())
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +0000733 Masks.erase(F);
734 else
735 F->second = NewM;
736 return *this;
737}
738
Krzysztof Parzyszek7bb63ac2016-10-19 16:30:56 +0000739RegisterAggr &RegisterAggr::clear(const RegisterAggr &RG) {
Krzysztof Parzyszek6e7fa992016-10-21 19:12:13 +0000740 for (std::pair<RegisterId,LaneBitmask> P : RG.Masks)
Krzysztof Parzyszek7bb63ac2016-10-19 16:30:56 +0000741 clear(RegisterRef(P.first, P.second));
742 return *this;
743}
744
745RegisterRef RegisterAggr::clearIn(RegisterRef RR) const {
746 RegisterAggr T(TRI);
747 T.insert(RR).clear(*this);
748 if (T.empty())
749 return RegisterRef();
750 return RegisterRef(T.begin()->first, T.begin()->second);
751}
752
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +0000753void RegisterAggr::print(raw_ostream &OS) const {
754 OS << '{';
755 for (auto I : Masks)
Krzysztof Parzyszek7bb63ac2016-10-19 16:30:56 +0000756 OS << ' ' << PrintReg(I.first, &TRI) << PrintLaneMaskOpt(I.second);
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +0000757 OS << " }";
758}
759
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000760//
761// The data flow graph construction.
762//
763
764DataFlowGraph::DataFlowGraph(MachineFunction &mf, const TargetInstrInfo &tii,
765 const TargetRegisterInfo &tri, const MachineDominatorTree &mdt,
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +0000766 const MachineDominanceFrontier &mdf, const TargetOperandInfo &toi)
Krzysztof Parzyszekb561cf92017-01-30 16:20:30 +0000767 : MF(mf), TII(tii), TRI(tri), MDT(mdt), MDF(mdf), TOI(toi), LiveIns(TRI) {
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000768}
769
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000770// The implementation of the definition stack.
771// Each register reference has its own definition stack. In particular,
772// for a register references "Reg" and "Reg:subreg" will each have their
773// own definition stacks.
774
775// Construct a stack iterator.
776DataFlowGraph::DefStack::Iterator::Iterator(const DataFlowGraph::DefStack &S,
777 bool Top) : DS(S) {
778 if (!Top) {
779 // Initialize to bottom.
780 Pos = 0;
781 return;
782 }
783 // Initialize to the top, i.e. top-most non-delimiter (or 0, if empty).
784 Pos = DS.Stack.size();
785 while (Pos > 0 && DS.isDelimiter(DS.Stack[Pos-1]))
786 Pos--;
787}
788
789// Return the size of the stack, including block delimiters.
790unsigned DataFlowGraph::DefStack::size() const {
791 unsigned S = 0;
792 for (auto I = top(), E = bottom(); I != E; I.down())
793 S++;
794 return S;
795}
796
797// Remove the top entry from the stack. Remove all intervening delimiters
798// so that after this, the stack is either empty, or the top of the stack
799// is a non-delimiter.
800void DataFlowGraph::DefStack::pop() {
801 assert(!empty());
802 unsigned P = nextDown(Stack.size());
803 Stack.resize(P);
804}
805
806// Push a delimiter for block node N on the stack.
807void DataFlowGraph::DefStack::start_block(NodeId N) {
808 assert(N != 0);
809 Stack.push_back(NodeAddr<DefNode*>(nullptr, N));
810}
811
812// Remove all nodes from the top of the stack, until the delimited for
813// block node N is encountered. Remove the delimiter as well. In effect,
814// this will remove from the stack all definitions from block N.
815void DataFlowGraph::DefStack::clear_block(NodeId N) {
816 assert(N != 0);
817 unsigned P = Stack.size();
818 while (P > 0) {
819 bool Found = isDelimiter(Stack[P-1], N);
820 P--;
821 if (Found)
822 break;
823 }
824 // This will also remove the delimiter, if found.
825 Stack.resize(P);
826}
827
828// Move the stack iterator up by one.
829unsigned DataFlowGraph::DefStack::nextUp(unsigned P) const {
830 // Get the next valid position after P (skipping all delimiters).
831 // The input position P does not have to point to a non-delimiter.
832 unsigned SS = Stack.size();
833 bool IsDelim;
Krzysztof Parzyszek8dca45e2016-01-12 16:51:55 +0000834 assert(P < SS);
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000835 do {
836 P++;
837 IsDelim = isDelimiter(Stack[P-1]);
838 } while (P < SS && IsDelim);
839 assert(!IsDelim);
840 return P;
841}
842
843// Move the stack iterator down by one.
844unsigned DataFlowGraph::DefStack::nextDown(unsigned P) const {
845 // Get the preceding valid position before P (skipping all delimiters).
846 // The input position P does not have to point to a non-delimiter.
847 assert(P > 0 && P <= Stack.size());
848 bool IsDelim = isDelimiter(Stack[P-1]);
849 do {
850 if (--P == 0)
851 break;
852 IsDelim = isDelimiter(Stack[P-1]);
853 } while (P > 0 && IsDelim);
854 assert(!IsDelim);
855 return P;
856}
857
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +0000858// Register information.
859
860// Get the list of references aliased to RR. Lane masks are ignored.
Krzysztof Parzyszek6e7fa992016-10-21 19:12:13 +0000861RegisterSet DataFlowGraph::getAliasSet(RegisterId Reg) const {
Krzysztof Parzyszek445bd122016-10-14 17:57:55 +0000862 // Do not include RR in the alias set.
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +0000863 RegisterSet AS;
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +0000864 assert(TargetRegisterInfo::isPhysicalRegister(Reg));
865
866 for (MCRegAliasIterator AI(Reg, &TRI, false); AI.isValid(); ++AI)
Krzysztof Parzyszek445bd122016-10-14 17:57:55 +0000867 AS.insert(RegisterRef(*AI));
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +0000868 return AS;
869}
870
871RegisterSet DataFlowGraph::getLandingPadLiveIns() const {
872 RegisterSet LR;
Krzysztof Parzyszek1d322202016-09-27 18:18:44 +0000873 const Function &F = *MF.getFunction();
874 const Constant *PF = F.hasPersonalityFn() ? F.getPersonalityFn()
875 : nullptr;
876 const TargetLowering &TLI = *MF.getSubtarget().getTargetLowering();
Krzysztof Parzyszek6e7fa992016-10-21 19:12:13 +0000877 if (RegisterId R = TLI.getExceptionPointerRegister(PF))
Krzysztof Parzyszek445bd122016-10-14 17:57:55 +0000878 LR.insert(RegisterRef(R));
Krzysztof Parzyszek6e7fa992016-10-21 19:12:13 +0000879 if (RegisterId R = TLI.getExceptionSelectorRegister(PF))
Krzysztof Parzyszek445bd122016-10-14 17:57:55 +0000880 LR.insert(RegisterRef(R));
Krzysztof Parzyszek1d322202016-09-27 18:18:44 +0000881 return LR;
882}
883
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000884// Node management functions.
885
886// Get the pointer to the node with the id N.
887NodeBase *DataFlowGraph::ptr(NodeId N) const {
888 if (N == 0)
889 return nullptr;
890 return Memory.ptr(N);
891}
892
893// Get the id of the node at the address P.
894NodeId DataFlowGraph::id(const NodeBase *P) const {
895 if (P == nullptr)
896 return 0;
897 return Memory.id(P);
898}
899
900// Allocate a new node and set the attributes to Attrs.
901NodeAddr<NodeBase*> DataFlowGraph::newNode(uint16_t Attrs) {
902 NodeAddr<NodeBase*> P = Memory.New();
903 P.Addr->init();
904 P.Addr->setAttrs(Attrs);
905 return P;
906}
907
908// Make a copy of the given node B, except for the data-flow links, which
909// are set to 0.
910NodeAddr<NodeBase*> DataFlowGraph::cloneNode(const NodeAddr<NodeBase*> B) {
911 NodeAddr<NodeBase*> NA = newNode(0);
912 memcpy(NA.Addr, B.Addr, sizeof(NodeBase));
913 // Ref nodes need to have the data-flow links reset.
914 if (NA.Addr->getType() == NodeAttrs::Ref) {
915 NodeAddr<RefNode*> RA = NA;
916 RA.Addr->setReachingDef(0);
917 RA.Addr->setSibling(0);
918 if (NA.Addr->getKind() == NodeAttrs::Def) {
919 NodeAddr<DefNode*> DA = NA;
920 DA.Addr->setReachedDef(0);
921 DA.Addr->setReachedUse(0);
922 }
923 }
924 return NA;
925}
926
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000927// Allocation routines for specific node types/kinds.
928
929NodeAddr<UseNode*> DataFlowGraph::newUse(NodeAddr<InstrNode*> Owner,
930 MachineOperand &Op, uint16_t Flags) {
931 NodeAddr<UseNode*> UA = newNode(NodeAttrs::Ref | NodeAttrs::Use | Flags);
Krzysztof Parzyszek445bd122016-10-14 17:57:55 +0000932 UA.Addr->setRegRef(&Op, *this);
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000933 return UA;
934}
935
936NodeAddr<PhiUseNode*> DataFlowGraph::newPhiUse(NodeAddr<PhiNode*> Owner,
937 RegisterRef RR, NodeAddr<BlockNode*> PredB, uint16_t Flags) {
938 NodeAddr<PhiUseNode*> PUA = newNode(NodeAttrs::Ref | NodeAttrs::Use | Flags);
939 assert(Flags & NodeAttrs::PhiRef);
Krzysztof Parzyszek445bd122016-10-14 17:57:55 +0000940 PUA.Addr->setRegRef(RR, *this);
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000941 PUA.Addr->setPredecessor(PredB.Id);
942 return PUA;
943}
944
945NodeAddr<DefNode*> DataFlowGraph::newDef(NodeAddr<InstrNode*> Owner,
946 MachineOperand &Op, uint16_t Flags) {
947 NodeAddr<DefNode*> DA = newNode(NodeAttrs::Ref | NodeAttrs::Def | Flags);
Krzysztof Parzyszek445bd122016-10-14 17:57:55 +0000948 DA.Addr->setRegRef(&Op, *this);
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000949 return DA;
950}
951
952NodeAddr<DefNode*> DataFlowGraph::newDef(NodeAddr<InstrNode*> Owner,
953 RegisterRef RR, uint16_t Flags) {
954 NodeAddr<DefNode*> DA = newNode(NodeAttrs::Ref | NodeAttrs::Def | Flags);
955 assert(Flags & NodeAttrs::PhiRef);
Krzysztof Parzyszek445bd122016-10-14 17:57:55 +0000956 DA.Addr->setRegRef(RR, *this);
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000957 return DA;
958}
959
960NodeAddr<PhiNode*> DataFlowGraph::newPhi(NodeAddr<BlockNode*> Owner) {
961 NodeAddr<PhiNode*> PA = newNode(NodeAttrs::Code | NodeAttrs::Phi);
962 Owner.Addr->addPhi(PA, *this);
963 return PA;
964}
965
966NodeAddr<StmtNode*> DataFlowGraph::newStmt(NodeAddr<BlockNode*> Owner,
967 MachineInstr *MI) {
968 NodeAddr<StmtNode*> SA = newNode(NodeAttrs::Code | NodeAttrs::Stmt);
969 SA.Addr->setCode(MI);
970 Owner.Addr->addMember(SA, *this);
971 return SA;
972}
973
974NodeAddr<BlockNode*> DataFlowGraph::newBlock(NodeAddr<FuncNode*> Owner,
975 MachineBasicBlock *BB) {
976 NodeAddr<BlockNode*> BA = newNode(NodeAttrs::Code | NodeAttrs::Block);
977 BA.Addr->setCode(BB);
978 Owner.Addr->addMember(BA, *this);
979 return BA;
980}
981
982NodeAddr<FuncNode*> DataFlowGraph::newFunc(MachineFunction *MF) {
983 NodeAddr<FuncNode*> FA = newNode(NodeAttrs::Code | NodeAttrs::Func);
984 FA.Addr->setCode(MF);
985 return FA;
986}
987
988// Build the data flow graph.
Krzysztof Parzyszek55874cf2016-04-28 20:17:06 +0000989void DataFlowGraph::build(unsigned Options) {
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000990 reset();
991 Func = newFunc(&MF);
992
993 if (MF.empty())
994 return;
995
Krzysztof Parzyszek61d90322016-10-06 13:05:13 +0000996 for (MachineBasicBlock &B : MF) {
997 NodeAddr<BlockNode*> BA = newBlock(Func, &B);
Krzysztof Parzyszek047149f2016-07-22 16:09:47 +0000998 BlockNodes.insert(std::make_pair(&B, BA));
Krzysztof Parzyszek61d90322016-10-06 13:05:13 +0000999 for (MachineInstr &I : B) {
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001000 if (I.isDebugValue())
1001 continue;
1002 buildStmt(BA, I);
1003 }
1004 }
1005
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001006 NodeAddr<BlockNode*> EA = Func.Addr->getEntryBlock(*this);
Krzysztof Parzyszek1d322202016-09-27 18:18:44 +00001007 NodeList Blocks = Func.Addr->members(*this);
1008
1009 // Collect information about block references.
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001010 BlockRefsMap RefM;
1011 buildBlockRefs(EA, RefM);
1012
Krzysztof Parzyszekb561cf92017-01-30 16:20:30 +00001013 // Collect function live-ins and entry block live-ins.
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001014 MachineRegisterInfo &MRI = MF.getRegInfo();
Krzysztof Parzyszekb561cf92017-01-30 16:20:30 +00001015 MachineBasicBlock &EntryB = *EA.Addr->getCode();
1016 assert(EntryB.pred_empty() && "Function entry block has predecessors");
1017 for (auto I = MRI.livein_begin(), E = MRI.livein_end(); I != E; ++I)
1018 LiveIns.insert(RegisterRef(I->first));
1019 for (auto I : EntryB.liveins())
1020 LiveIns.insert(RegisterRef(I.PhysReg, I.LaneMask));
1021
1022 // Add function-entry phi nodes for the live-in registers.
1023 for (std::pair<RegisterId,LaneBitmask> P : LiveIns) {
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001024 NodeAddr<PhiNode*> PA = newPhi(EA);
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001025 uint16_t PhiFlags = NodeAttrs::PhiRef | NodeAttrs::Preserving;
Krzysztof Parzyszekb561cf92017-01-30 16:20:30 +00001026 RegisterRef RR(P.first, P.second);
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001027 NodeAddr<DefNode*> DA = newDef(PA, RR, PhiFlags);
1028 PA.Addr->addMember(DA, *this);
1029 }
1030
Krzysztof Parzyszek1d322202016-09-27 18:18:44 +00001031 // Add phis for landing pads.
1032 // Landing pads, unlike usual backs blocks, are not entered through
1033 // branches in the program, or fall-throughs from other blocks. They
1034 // are entered from the exception handling runtime and target's ABI
1035 // may define certain registers as defined on entry to such a block.
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +00001036 RegisterSet EHRegs = getLandingPadLiveIns();
Krzysztof Parzyszek1d322202016-09-27 18:18:44 +00001037 if (!EHRegs.empty()) {
1038 for (NodeAddr<BlockNode*> BA : Blocks) {
1039 const MachineBasicBlock &B = *BA.Addr->getCode();
1040 if (!B.isEHPad())
1041 continue;
1042
1043 // Prepare a list of NodeIds of the block's predecessors.
1044 NodeList Preds;
1045 for (MachineBasicBlock *PB : B.predecessors())
1046 Preds.push_back(findBlock(PB));
1047
1048 // Build phi nodes for each live-in.
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +00001049 for (RegisterRef RR : EHRegs) {
Krzysztof Parzyszek1d322202016-09-27 18:18:44 +00001050 NodeAddr<PhiNode*> PA = newPhi(BA);
1051 uint16_t PhiFlags = NodeAttrs::PhiRef | NodeAttrs::Preserving;
1052 // Add def:
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +00001053 NodeAddr<DefNode*> DA = newDef(PA, RR, PhiFlags);
Krzysztof Parzyszek1d322202016-09-27 18:18:44 +00001054 PA.Addr->addMember(DA, *this);
1055 // Add uses (no reaching defs for phi uses):
1056 for (NodeAddr<BlockNode*> PBA : Preds) {
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +00001057 NodeAddr<PhiUseNode*> PUA = newPhiUse(PA, RR, PBA);
Krzysztof Parzyszek1d322202016-09-27 18:18:44 +00001058 PA.Addr->addMember(PUA, *this);
1059 }
1060 }
1061 }
1062 }
1063
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001064 // Build a map "PhiM" which will contain, for each block, the set
1065 // of references that will require phi definitions in that block.
1066 BlockRefsMap PhiM;
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001067 for (NodeAddr<BlockNode*> BA : Blocks)
1068 recordDefsForDF(PhiM, RefM, BA);
1069 for (NodeAddr<BlockNode*> BA : Blocks)
1070 buildPhis(PhiM, RefM, BA);
1071
1072 // Link all the refs. This will recursively traverse the dominator tree.
1073 DefStackMap DM;
1074 linkBlockRefs(DM, EA);
1075
1076 // Finally, remove all unused phi nodes.
Krzysztof Parzyszek55874cf2016-04-28 20:17:06 +00001077 if (!(Options & BuildOptions::KeepDeadPhis))
1078 removeUnusedPhis();
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001079}
1080
Krzysztof Parzyszek445bd122016-10-14 17:57:55 +00001081RegisterRef DataFlowGraph::makeRegRef(unsigned Reg, unsigned Sub) const {
1082 assert(TargetRegisterInfo::isPhysicalRegister(Reg));
Krzysztof Parzyszek775a2092016-10-14 19:06:25 +00001083 if (Sub != 0)
1084 Reg = TRI.getSubReg(Reg, Sub);
Krzysztof Parzyszek445bd122016-10-14 17:57:55 +00001085 return RegisterRef(Reg);
1086}
1087
Krzysztof Parzyszek7bb63ac2016-10-19 16:30:56 +00001088RegisterRef DataFlowGraph::normalizeRef(RegisterRef RR) const {
1089 // FIXME copied from RegisterAggr
Krzysztof Parzyszek6e7fa992016-10-21 19:12:13 +00001090 RegisterId SuperReg = RR.Reg;
Krzysztof Parzyszek7bb63ac2016-10-19 16:30:56 +00001091 while (true) {
1092 MCSuperRegIterator SR(SuperReg, &TRI, false);
1093 if (!SR.isValid())
1094 break;
1095 SuperReg = *SR;
1096 }
1097
1098 uint32_t Sub = TRI.getSubRegIndex(SuperReg, RR.Reg);
1099 const TargetRegisterClass &RC = *TRI.getMinimalPhysRegClass(RR.Reg);
1100 LaneBitmask SuperMask = RR.Mask &
1101 TRI.composeSubRegIndexLaneMask(Sub, RC.LaneMask);
1102 return RegisterRef(SuperReg, SuperMask);
1103}
1104
1105RegisterRef DataFlowGraph::restrictRef(RegisterRef AR, RegisterRef BR) const {
1106 if (AR.Reg == BR.Reg) {
1107 LaneBitmask M = AR.Mask & BR.Mask;
Krzysztof Parzyszekea9f8ce2016-12-16 19:11:56 +00001108 return M.any() ? RegisterRef(AR.Reg, M) : RegisterRef();
Krzysztof Parzyszek7bb63ac2016-10-19 16:30:56 +00001109 }
1110#ifndef NDEBUG
1111 RegisterRef NAR = normalizeRef(AR);
1112 RegisterRef NBR = normalizeRef(BR);
1113 assert(NAR.Reg != NBR.Reg);
1114#endif
1115 // This isn't strictly correct, because the overlap may happen in the
1116 // part masked out.
1117 if (TRI.regsOverlap(AR.Reg, BR.Reg))
1118 return AR;
1119 return RegisterRef();
1120}
1121
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001122// For each stack in the map DefM, push the delimiter for block B on it.
1123void DataFlowGraph::markBlock(NodeId B, DefStackMap &DefM) {
1124 // Push block delimiters.
1125 for (auto I = DefM.begin(), E = DefM.end(); I != E; ++I)
1126 I->second.start_block(B);
1127}
1128
1129// Remove all definitions coming from block B from each stack in DefM.
1130void DataFlowGraph::releaseBlock(NodeId B, DefStackMap &DefM) {
1131 // Pop all defs from this block from the definition stack. Defs that were
1132 // added to the map during the traversal of instructions will not have a
1133 // delimiter, but for those, the whole stack will be emptied.
1134 for (auto I = DefM.begin(), E = DefM.end(); I != E; ++I)
1135 I->second.clear_block(B);
1136
1137 // Finally, remove empty stacks from the map.
1138 for (auto I = DefM.begin(), E = DefM.end(), NextI = I; I != E; I = NextI) {
1139 NextI = std::next(I);
1140 // This preserves the validity of iterators other than I.
1141 if (I->second.empty())
1142 DefM.erase(I);
1143 }
1144}
1145
1146// Push all definitions from the instruction node IA to an appropriate
1147// stack in DefM.
1148void DataFlowGraph::pushDefs(NodeAddr<InstrNode*> IA, DefStackMap &DefM) {
1149 NodeList Defs = IA.Addr->members_if(IsDef, *this);
1150 NodeSet Visited;
1151#ifndef NDEBUG
1152 RegisterSet Defined;
1153#endif
1154
1155 // The important objectives of this function are:
1156 // - to be able to handle instructions both while the graph is being
1157 // constructed, and after the graph has been constructed, and
1158 // - maintain proper ordering of definitions on the stack for each
1159 // register reference:
1160 // - if there are two or more related defs in IA (i.e. coming from
1161 // the same machine operand), then only push one def on the stack,
1162 // - if there are multiple unrelated defs of non-overlapping
1163 // subregisters of S, then the stack for S will have both (in an
1164 // unspecified order), but the order does not matter from the data-
1165 // -flow perspective.
1166
1167 for (NodeAddr<DefNode*> DA : Defs) {
1168 if (Visited.count(DA.Id))
1169 continue;
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +00001170
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001171 NodeList Rel = getRelatedRefs(IA, DA);
1172 NodeAddr<DefNode*> PDA = Rel.front();
Krzysztof Parzyszek445bd122016-10-14 17:57:55 +00001173 RegisterRef RR = PDA.Addr->getRegRef(*this);
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001174#ifndef NDEBUG
1175 // Assert if the register is defined in two or more unrelated defs.
1176 // This could happen if there are two or more def operands defining it.
1177 if (!Defined.insert(RR).second) {
Krzysztof Parzyszek61d90322016-10-06 13:05:13 +00001178 MachineInstr *MI = NodeAddr<StmtNode*>(IA).Addr->getCode();
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001179 dbgs() << "Multiple definitions of register: "
1180 << Print<RegisterRef>(RR, *this) << " in\n " << *MI
1181 << "in BB#" << MI->getParent()->getNumber() << '\n';
1182 llvm_unreachable(nullptr);
1183 }
1184#endif
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +00001185 // Push the definition on the stack for the register and all aliases.
1186 // The def stack traversal in linkNodeUp will check the exact aliasing.
1187 DefM[RR.Reg].push(DA);
1188 for (RegisterRef A : getAliasSet(RR.Reg /*FIXME? use RegisterRef*/)) {
1189 // Check that we don't push the same def twice.
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001190 assert(A != RR);
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +00001191 DefM[A.Reg].push(DA);
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001192 }
1193 // Mark all the related defs as visited.
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +00001194 for (NodeAddr<NodeBase*> T : Rel)
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001195 Visited.insert(T.Id);
1196 }
1197}
1198
1199// Return the list of all reference nodes related to RA, including RA itself.
1200// See "getNextRelated" for the meaning of a "related reference".
1201NodeList DataFlowGraph::getRelatedRefs(NodeAddr<InstrNode*> IA,
1202 NodeAddr<RefNode*> RA) const {
1203 assert(IA.Id != 0 && RA.Id != 0);
1204
1205 NodeList Refs;
1206 NodeId Start = RA.Id;
1207 do {
1208 Refs.push_back(RA);
1209 RA = getNextRelated(IA, RA);
1210 } while (RA.Id != 0 && RA.Id != Start);
1211 return Refs;
1212}
1213
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +00001214// Return true if RA and RB overlap, false otherwise.
1215bool DataFlowGraph::alias(RegisterRef RA, RegisterRef RB) const {
Krzysztof Parzyszek445bd122016-10-14 17:57:55 +00001216 assert(TargetRegisterInfo::isPhysicalRegister(RA.Reg));
1217 assert(TargetRegisterInfo::isPhysicalRegister(RB.Reg));
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +00001218
Krzysztof Parzyszek445bd122016-10-14 17:57:55 +00001219 MCRegUnitMaskIterator UMA(RA.Reg, &TRI);
1220 MCRegUnitMaskIterator UMB(RB.Reg, &TRI);
1221 // Reg units are returned in the numerical order.
1222 while (UMA.isValid() && UMB.isValid()) {
1223 std::pair<uint32_t,LaneBitmask> PA = *UMA;
1224 std::pair<uint32_t,LaneBitmask> PB = *UMB;
Krzysztof Parzyszek445bd122016-10-14 17:57:55 +00001225 if (PA.first == PB.first) {
Krzysztof Parzyszek77a45572016-12-08 20:33:45 +00001226 // Lane mask of 0 (given by the iterator) should be treated as "full".
1227 // This can happen when the register has only one unit, or when the
1228 // unit corresponds to explicit aliasing. In such cases, the lane mask
1229 // from RegisterRef should be ignored.
Krzysztof Parzyszek91b5cf82016-12-15 14:36:06 +00001230 if (PA.second.none() || PB.second.none())
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +00001231 return true;
Krzysztof Parzyszek77a45572016-12-08 20:33:45 +00001232
1233 // At this point the common unit corresponds to a subregister. The lane
1234 // masks correspond to the lane mask of that unit within the original
1235 // register, for example assuming register quadruple q0 = r3:0, and
1236 // a register pair d1 = r3:2, the lane mask of r2 in q0 may be 0b0100,
1237 // while the lane mask of r2 in d1 may be 0b0001.
1238 LaneBitmask LA = PA.second & RA.Mask;
1239 LaneBitmask LB = PB.second & RB.Mask;
Krzysztof Parzyszekea9f8ce2016-12-16 19:11:56 +00001240 if (LA.any() && LB.any()) {
Krzysztof Parzyszek77a45572016-12-08 20:33:45 +00001241 unsigned Root = *MCRegUnitRootIterator(PA.first, &TRI);
1242 // If register units were guaranteed to only have 1 bit in any lane
1243 // mask, the code below would not be necessary. This is because LA
1244 // and LB would have at most 1 bit set each, and that bit would be
1245 // guaranteed to correspond to the given register unit.
1246 uint32_t SubA = TRI.getSubRegIndex(RA.Reg, Root);
1247 uint32_t SubB = TRI.getSubRegIndex(RB.Reg, Root);
1248 const TargetRegisterClass &RC = *TRI.getMinimalPhysRegClass(Root);
1249 LaneBitmask MaskA = TRI.reverseComposeSubRegIndexLaneMask(SubA, LA);
1250 LaneBitmask MaskB = TRI.reverseComposeSubRegIndexLaneMask(SubB, LB);
Krzysztof Parzyszekea9f8ce2016-12-16 19:11:56 +00001251 if ((MaskA & MaskB & RC.LaneMask).any())
Krzysztof Parzyszek77a45572016-12-08 20:33:45 +00001252 return true;
1253 }
1254
Krzysztof Parzyszek445bd122016-10-14 17:57:55 +00001255 ++UMA;
1256 ++UMB;
1257 continue;
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +00001258 }
Krzysztof Parzyszek445bd122016-10-14 17:57:55 +00001259 if (PA.first < PB.first)
1260 ++UMA;
1261 else if (PB.first < PA.first)
1262 ++UMB;
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +00001263 }
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +00001264 return false;
1265}
1266
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001267// Clear all information in the graph.
1268void DataFlowGraph::reset() {
1269 Memory.clear();
Krzysztof Parzyszek047149f2016-07-22 16:09:47 +00001270 BlockNodes.clear();
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001271 Func = NodeAddr<FuncNode*>();
1272}
1273
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001274// Return the next reference node in the instruction node IA that is related
1275// to RA. Conceptually, two reference nodes are related if they refer to the
1276// same instance of a register access, but differ in flags or other minor
1277// characteristics. Specific examples of related nodes are shadow reference
1278// nodes.
1279// Return the equivalent of nullptr if there are no more related references.
1280NodeAddr<RefNode*> DataFlowGraph::getNextRelated(NodeAddr<InstrNode*> IA,
1281 NodeAddr<RefNode*> RA) const {
1282 assert(IA.Id != 0 && RA.Id != 0);
1283
Krzysztof Parzyszek445bd122016-10-14 17:57:55 +00001284 auto Related = [this,RA](NodeAddr<RefNode*> TA) -> bool {
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001285 if (TA.Addr->getKind() != RA.Addr->getKind())
1286 return false;
Krzysztof Parzyszek445bd122016-10-14 17:57:55 +00001287 if (TA.Addr->getRegRef(*this) != RA.Addr->getRegRef(*this))
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001288 return false;
1289 return true;
1290 };
1291 auto RelatedStmt = [&Related,RA](NodeAddr<RefNode*> TA) -> bool {
1292 return Related(TA) &&
1293 &RA.Addr->getOp() == &TA.Addr->getOp();
1294 };
1295 auto RelatedPhi = [&Related,RA](NodeAddr<RefNode*> TA) -> bool {
1296 if (!Related(TA))
1297 return false;
1298 if (TA.Addr->getKind() != NodeAttrs::Use)
1299 return true;
1300 // For phi uses, compare predecessor blocks.
1301 const NodeAddr<const PhiUseNode*> TUA = TA;
1302 const NodeAddr<const PhiUseNode*> RUA = RA;
1303 return TUA.Addr->getPredecessor() == RUA.Addr->getPredecessor();
1304 };
1305
Krzysztof Parzyszek445bd122016-10-14 17:57:55 +00001306 RegisterRef RR = RA.Addr->getRegRef(*this);
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001307 if (IA.Addr->getKind() == NodeAttrs::Stmt)
1308 return RA.Addr->getNextRef(RR, RelatedStmt, true, *this);
1309 return RA.Addr->getNextRef(RR, RelatedPhi, true, *this);
1310}
1311
1312// Find the next node related to RA in IA that satisfies condition P.
1313// If such a node was found, return a pair where the second element is the
1314// located node. If such a node does not exist, return a pair where the
1315// first element is the element after which such a node should be inserted,
1316// and the second element is a null-address.
1317template <typename Predicate>
1318std::pair<NodeAddr<RefNode*>,NodeAddr<RefNode*>>
1319DataFlowGraph::locateNextRef(NodeAddr<InstrNode*> IA, NodeAddr<RefNode*> RA,
1320 Predicate P) const {
1321 assert(IA.Id != 0 && RA.Id != 0);
1322
1323 NodeAddr<RefNode*> NA;
1324 NodeId Start = RA.Id;
1325 while (true) {
1326 NA = getNextRelated(IA, RA);
1327 if (NA.Id == 0 || NA.Id == Start)
1328 break;
1329 if (P(NA))
1330 break;
1331 RA = NA;
1332 }
1333
1334 if (NA.Id != 0 && NA.Id != Start)
1335 return std::make_pair(RA, NA);
1336 return std::make_pair(RA, NodeAddr<RefNode*>());
1337}
1338
1339// Get the next shadow node in IA corresponding to RA, and optionally create
1340// such a node if it does not exist.
1341NodeAddr<RefNode*> DataFlowGraph::getNextShadow(NodeAddr<InstrNode*> IA,
1342 NodeAddr<RefNode*> RA, bool Create) {
1343 assert(IA.Id != 0 && RA.Id != 0);
1344
1345 uint16_t Flags = RA.Addr->getFlags() | NodeAttrs::Shadow;
1346 auto IsShadow = [Flags] (NodeAddr<RefNode*> TA) -> bool {
1347 return TA.Addr->getFlags() == Flags;
1348 };
1349 auto Loc = locateNextRef(IA, RA, IsShadow);
1350 if (Loc.second.Id != 0 || !Create)
1351 return Loc.second;
1352
1353 // Create a copy of RA and mark is as shadow.
1354 NodeAddr<RefNode*> NA = cloneNode(RA);
1355 NA.Addr->setFlags(Flags | NodeAttrs::Shadow);
1356 IA.Addr->addMemberAfter(Loc.first, NA, *this);
1357 return NA;
1358}
1359
1360// Get the next shadow node in IA corresponding to RA. Return null-address
1361// if such a node does not exist.
1362NodeAddr<RefNode*> DataFlowGraph::getNextShadow(NodeAddr<InstrNode*> IA,
1363 NodeAddr<RefNode*> RA) const {
1364 assert(IA.Id != 0 && RA.Id != 0);
1365 uint16_t Flags = RA.Addr->getFlags() | NodeAttrs::Shadow;
1366 auto IsShadow = [Flags] (NodeAddr<RefNode*> TA) -> bool {
1367 return TA.Addr->getFlags() == Flags;
1368 };
1369 return locateNextRef(IA, RA, IsShadow).second;
1370}
1371
1372// Create a new statement node in the block node BA that corresponds to
1373// the machine instruction MI.
1374void DataFlowGraph::buildStmt(NodeAddr<BlockNode*> BA, MachineInstr &In) {
Krzysztof Parzyszek61d90322016-10-06 13:05:13 +00001375 NodeAddr<StmtNode*> SA = newStmt(BA, &In);
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001376
Krzysztof Parzyszekbf90d5a2016-04-28 20:40:08 +00001377 auto isCall = [] (const MachineInstr &In) -> bool {
1378 if (In.isCall())
1379 return true;
1380 // Is tail call?
1381 if (In.isBranch())
Krzysztof Parzyszek61d90322016-10-06 13:05:13 +00001382 for (const MachineOperand &Op : In.operands())
Krzysztof Parzyszekbf90d5a2016-04-28 20:40:08 +00001383 if (Op.isGlobal() || Op.isSymbol())
1384 return true;
1385 return false;
1386 };
1387
Krzysztof Parzyszek1ff99522016-09-07 20:10:56 +00001388 auto isDefUndef = [this] (const MachineInstr &In, RegisterRef DR) -> bool {
1389 // This instruction defines DR. Check if there is a use operand that
1390 // would make DR live on entry to the instruction.
1391 for (const MachineOperand &UseOp : In.operands()) {
1392 if (!UseOp.isReg() || !UseOp.isUse() || UseOp.isUndef())
1393 continue;
Krzysztof Parzyszek445bd122016-10-14 17:57:55 +00001394 RegisterRef UR = makeRegRef(UseOp.getReg(), UseOp.getSubReg());
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +00001395 if (alias(DR, UR))
Krzysztof Parzyszek1ff99522016-09-07 20:10:56 +00001396 return false;
1397 }
1398 return true;
1399 };
1400
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001401 // Collect a set of registers that this instruction implicitly uses
1402 // or defines. Implicit operands from an instruction will be ignored
1403 // unless they are listed here.
1404 RegisterSet ImpUses, ImpDefs;
1405 if (const uint16_t *ImpD = In.getDesc().getImplicitDefs())
1406 while (uint16_t R = *ImpD++)
Krzysztof Parzyszek445bd122016-10-14 17:57:55 +00001407 ImpDefs.insert(RegisterRef(R));
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001408 if (const uint16_t *ImpU = In.getDesc().getImplicitUses())
1409 while (uint16_t R = *ImpU++)
Krzysztof Parzyszek445bd122016-10-14 17:57:55 +00001410 ImpUses.insert(RegisterRef(R));
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001411
Krzysztof Parzyszek586fc122016-09-27 18:24:33 +00001412 bool IsCall = isCall(In);
1413 bool NeedsImplicit = IsCall || In.isInlineAsm() || In.isReturn();
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001414 bool IsPredicated = TII.isPredicated(In);
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001415 unsigned NumOps = In.getNumOperands();
1416
1417 // Avoid duplicate implicit defs. This will not detect cases of implicit
1418 // defs that define registers that overlap, but it is not clear how to
1419 // interpret that in the absence of explicit defs. Overlapping explicit
1420 // defs are likely illegal already.
1421 RegisterSet DoneDefs;
1422 // Process explicit defs first.
1423 for (unsigned OpN = 0; OpN < NumOps; ++OpN) {
1424 MachineOperand &Op = In.getOperand(OpN);
1425 if (!Op.isReg() || !Op.isDef() || Op.isImplicit())
1426 continue;
Krzysztof Parzyszek445bd122016-10-14 17:57:55 +00001427 RegisterRef RR = makeRegRef(Op.getReg(), Op.getSubReg());
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001428 uint16_t Flags = NodeAttrs::None;
Krzysztof Parzyszek1ff99522016-09-07 20:10:56 +00001429 if (TOI.isPreserving(In, OpN)) {
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001430 Flags |= NodeAttrs::Preserving;
Krzysztof Parzyszek1ff99522016-09-07 20:10:56 +00001431 // If the def is preserving, check if it is also undefined.
1432 if (isDefUndef(In, RR))
1433 Flags |= NodeAttrs::Undef;
1434 }
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001435 if (TOI.isClobbering(In, OpN))
1436 Flags |= NodeAttrs::Clobbering;
1437 if (TOI.isFixedReg(In, OpN))
1438 Flags |= NodeAttrs::Fixed;
Krzysztof Parzyszek586fc122016-09-27 18:24:33 +00001439 if (IsCall && Op.isDead())
1440 Flags |= NodeAttrs::Dead;
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001441 NodeAddr<DefNode*> DA = newDef(SA, Op, Flags);
1442 SA.Addr->addMember(DA, *this);
1443 DoneDefs.insert(RR);
1444 }
1445
1446 // Process implicit defs, skipping those that have already been added
1447 // as explicit.
1448 for (unsigned OpN = 0; OpN < NumOps; ++OpN) {
1449 MachineOperand &Op = In.getOperand(OpN);
1450 if (!Op.isReg() || !Op.isDef() || !Op.isImplicit())
1451 continue;
Krzysztof Parzyszek445bd122016-10-14 17:57:55 +00001452 RegisterRef RR = makeRegRef(Op.getReg(), Op.getSubReg());
Krzysztof Parzyszekbf90d5a2016-04-28 20:40:08 +00001453 if (!NeedsImplicit && !ImpDefs.count(RR))
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001454 continue;
1455 if (DoneDefs.count(RR))
1456 continue;
1457 uint16_t Flags = NodeAttrs::None;
Krzysztof Parzyszek1ff99522016-09-07 20:10:56 +00001458 if (TOI.isPreserving(In, OpN)) {
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001459 Flags |= NodeAttrs::Preserving;
Krzysztof Parzyszek1ff99522016-09-07 20:10:56 +00001460 // If the def is preserving, check if it is also undefined.
1461 if (isDefUndef(In, RR))
1462 Flags |= NodeAttrs::Undef;
1463 }
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001464 if (TOI.isClobbering(In, OpN))
1465 Flags |= NodeAttrs::Clobbering;
1466 if (TOI.isFixedReg(In, OpN))
1467 Flags |= NodeAttrs::Fixed;
Krzysztof Parzyszek586fc122016-09-27 18:24:33 +00001468 if (IsCall && Op.isDead())
1469 Flags |= NodeAttrs::Dead;
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001470 NodeAddr<DefNode*> DA = newDef(SA, Op, Flags);
1471 SA.Addr->addMember(DA, *this);
1472 DoneDefs.insert(RR);
1473 }
1474
1475 for (unsigned OpN = 0; OpN < NumOps; ++OpN) {
1476 MachineOperand &Op = In.getOperand(OpN);
Krzysztof Parzyszek1ff99522016-09-07 20:10:56 +00001477 if (!Op.isReg() || !Op.isUse())
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001478 continue;
Krzysztof Parzyszek445bd122016-10-14 17:57:55 +00001479 RegisterRef RR = makeRegRef(Op.getReg(), Op.getSubReg());
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001480 // Add implicit uses on return and call instructions, and on predicated
1481 // instructions regardless of whether or not they appear in the instruction
1482 // descriptor's list.
1483 bool Implicit = Op.isImplicit();
Krzysztof Parzyszekbf90d5a2016-04-28 20:40:08 +00001484 bool TakeImplicit = NeedsImplicit || IsPredicated;
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001485 if (Implicit && !TakeImplicit && !ImpUses.count(RR))
1486 continue;
1487 uint16_t Flags = NodeAttrs::None;
Krzysztof Parzyszek1ff99522016-09-07 20:10:56 +00001488 if (Op.isUndef())
1489 Flags |= NodeAttrs::Undef;
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001490 if (TOI.isFixedReg(In, OpN))
1491 Flags |= NodeAttrs::Fixed;
1492 NodeAddr<UseNode*> UA = newUse(SA, Op, Flags);
1493 SA.Addr->addMember(UA, *this);
1494 }
1495}
1496
1497// Build a map that for each block will have the set of all references from
1498// that block, and from all blocks dominated by it.
1499void DataFlowGraph::buildBlockRefs(NodeAddr<BlockNode*> BA,
1500 BlockRefsMap &RefM) {
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +00001501 RegisterSet &Refs = RefM[BA.Id];
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001502 MachineDomTreeNode *N = MDT.getNode(BA.Addr->getCode());
1503 assert(N);
1504 for (auto I : *N) {
1505 MachineBasicBlock *SB = I->getBlock();
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +00001506 NodeAddr<BlockNode*> SBA = findBlock(SB);
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001507 buildBlockRefs(SBA, RefM);
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +00001508 const RegisterSet &RefsS = RefM[SBA.Id];
1509 Refs.insert(RefsS.begin(), RefsS.end());
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001510 }
1511
1512 for (NodeAddr<InstrNode*> IA : BA.Addr->members(*this))
1513 for (NodeAddr<RefNode*> RA : IA.Addr->members(*this))
Krzysztof Parzyszek445bd122016-10-14 17:57:55 +00001514 Refs.insert(RA.Addr->getRegRef(*this));
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001515}
1516
1517// Scan all defs in the block node BA and record in PhiM the locations of
1518// phi nodes corresponding to these defs.
1519void DataFlowGraph::recordDefsForDF(BlockRefsMap &PhiM, BlockRefsMap &RefM,
1520 NodeAddr<BlockNode*> BA) {
1521 // Check all defs from block BA and record them in each block in BA's
1522 // iterated dominance frontier. This information will later be used to
1523 // create phi nodes.
1524 MachineBasicBlock *BB = BA.Addr->getCode();
1525 assert(BB);
1526 auto DFLoc = MDF.find(BB);
1527 if (DFLoc == MDF.end() || DFLoc->second.empty())
1528 return;
1529
1530 // Traverse all instructions in the block and collect the set of all
1531 // defined references. For each reference there will be a phi created
1532 // in the block's iterated dominance frontier.
1533 // This is done to make sure that each defined reference gets only one
1534 // phi node, even if it is defined multiple times.
1535 RegisterSet Defs;
Krzysztof Parzyszek61d90322016-10-06 13:05:13 +00001536 for (NodeAddr<InstrNode*> IA : BA.Addr->members(*this))
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001537 for (NodeAddr<RefNode*> RA : IA.Addr->members_if(IsDef, *this))
Krzysztof Parzyszek445bd122016-10-14 17:57:55 +00001538 Defs.insert(RA.Addr->getRegRef(*this));
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001539
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +00001540 // Calculate the iterated dominance frontier of BB.
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001541 const MachineDominanceFrontier::DomSetType &DF = DFLoc->second;
1542 SetVector<MachineBasicBlock*> IDF(DF.begin(), DF.end());
1543 for (unsigned i = 0; i < IDF.size(); ++i) {
1544 auto F = MDF.find(IDF[i]);
1545 if (F != MDF.end())
1546 IDF.insert(F->second.begin(), F->second.end());
1547 }
1548
1549 // Get the register references that are reachable from this block.
1550 RegisterSet &Refs = RefM[BA.Id];
1551 for (auto DB : IDF) {
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +00001552 NodeAddr<BlockNode*> DBA = findBlock(DB);
1553 const RegisterSet &RefsD = RefM[DBA.Id];
1554 Refs.insert(RefsD.begin(), RefsD.end());
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001555 }
1556
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +00001557 // Finally, add the set of defs to each block in the iterated dominance
1558 // frontier.
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001559 for (auto DB : IDF) {
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +00001560 NodeAddr<BlockNode*> DBA = findBlock(DB);
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001561 PhiM[DBA.Id].insert(Defs.begin(), Defs.end());
1562 }
1563}
1564
1565// Given the locations of phi nodes in the map PhiM, create the phi nodes
1566// that are located in the block node BA.
1567void DataFlowGraph::buildPhis(BlockRefsMap &PhiM, BlockRefsMap &RefM,
1568 NodeAddr<BlockNode*> BA) {
1569 // Check if this blocks has any DF defs, i.e. if there are any defs
1570 // that this block is in the iterated dominance frontier of.
1571 auto HasDF = PhiM.find(BA.Id);
1572 if (HasDF == PhiM.end() || HasDF->second.empty())
1573 return;
1574
1575 // First, remove all R in Refs in such that there exists T in Refs
1576 // such that T covers R. In other words, only leave those refs that
1577 // are not covered by another ref (i.e. maximal with respect to covering).
1578
1579 auto MaxCoverIn = [this] (RegisterRef RR, RegisterSet &RRs) -> RegisterRef {
Krzysztof Parzyszek61d90322016-10-06 13:05:13 +00001580 for (RegisterRef I : RRs)
Krzysztof Parzyszek445bd122016-10-14 17:57:55 +00001581 if (I != RR && RegisterAggr::isCoverOf(I, RR, TRI))
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001582 RR = I;
1583 return RR;
1584 };
1585
1586 RegisterSet MaxDF;
Krzysztof Parzyszek61d90322016-10-06 13:05:13 +00001587 for (RegisterRef I : HasDF->second)
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001588 MaxDF.insert(MaxCoverIn(I, HasDF->second));
1589
1590 std::vector<RegisterRef> MaxRefs;
Krzysztof Parzyszek61d90322016-10-06 13:05:13 +00001591 RegisterSet &RefB = RefM[BA.Id];
1592 for (RegisterRef I : MaxDF)
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001593 MaxRefs.push_back(MaxCoverIn(I, RefB));
1594
1595 // Now, for each R in MaxRefs, get the alias closure of R. If the closure
1596 // only has R in it, create a phi a def for R. Otherwise, create a phi,
1597 // and add a def for each S in the closure.
1598
1599 // Sort the refs so that the phis will be created in a deterministic order.
1600 std::sort(MaxRefs.begin(), MaxRefs.end());
1601 // Remove duplicates.
1602 auto NewEnd = std::unique(MaxRefs.begin(), MaxRefs.end());
1603 MaxRefs.erase(NewEnd, MaxRefs.end());
1604
1605 auto Aliased = [this,&MaxRefs](RegisterRef RR,
1606 std::vector<unsigned> &Closure) -> bool {
Krzysztof Parzyszek61d90322016-10-06 13:05:13 +00001607 for (unsigned I : Closure)
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +00001608 if (alias(RR, MaxRefs[I]))
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001609 return true;
1610 return false;
1611 };
1612
1613 // Prepare a list of NodeIds of the block's predecessors.
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +00001614 NodeList Preds;
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001615 const MachineBasicBlock *MBB = BA.Addr->getCode();
Krzysztof Parzyszek61d90322016-10-06 13:05:13 +00001616 for (MachineBasicBlock *PB : MBB->predecessors())
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +00001617 Preds.push_back(findBlock(PB));
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001618
1619 while (!MaxRefs.empty()) {
1620 // Put the first element in the closure, and then add all subsequent
1621 // elements from MaxRefs to it, if they alias at least one element
1622 // already in the closure.
1623 // ClosureIdx: vector of indices in MaxRefs of members of the closure.
1624 std::vector<unsigned> ClosureIdx = { 0 };
1625 for (unsigned i = 1; i != MaxRefs.size(); ++i)
1626 if (Aliased(MaxRefs[i], ClosureIdx))
1627 ClosureIdx.push_back(i);
1628
1629 // Build a phi for the closure.
1630 unsigned CS = ClosureIdx.size();
1631 NodeAddr<PhiNode*> PA = newPhi(BA);
1632
1633 // Add defs.
1634 for (unsigned X = 0; X != CS; ++X) {
1635 RegisterRef RR = MaxRefs[ClosureIdx[X]];
1636 uint16_t PhiFlags = NodeAttrs::PhiRef | NodeAttrs::Preserving;
1637 NodeAddr<DefNode*> DA = newDef(PA, RR, PhiFlags);
1638 PA.Addr->addMember(DA, *this);
1639 }
1640 // Add phi uses.
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +00001641 for (NodeAddr<BlockNode*> PBA : Preds) {
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001642 for (unsigned X = 0; X != CS; ++X) {
1643 RegisterRef RR = MaxRefs[ClosureIdx[X]];
1644 NodeAddr<PhiUseNode*> PUA = newPhiUse(PA, RR, PBA);
1645 PA.Addr->addMember(PUA, *this);
1646 }
1647 }
1648
1649 // Erase from MaxRefs all elements in the closure.
1650 auto Begin = MaxRefs.begin();
1651 for (unsigned i = ClosureIdx.size(); i != 0; --i)
1652 MaxRefs.erase(Begin + ClosureIdx[i-1]);
1653 }
1654}
1655
1656// Remove any unneeded phi nodes that were created during the build process.
1657void DataFlowGraph::removeUnusedPhis() {
1658 // This will remove unused phis, i.e. phis where each def does not reach
1659 // any uses or other defs. This will not detect or remove circular phi
1660 // chains that are otherwise dead. Unused/dead phis are created during
1661 // the build process and this function is intended to remove these cases
1662 // that are easily determinable to be unnecessary.
1663
1664 SetVector<NodeId> PhiQ;
1665 for (NodeAddr<BlockNode*> BA : Func.Addr->members(*this)) {
1666 for (auto P : BA.Addr->members_if(IsPhi, *this))
1667 PhiQ.insert(P.Id);
1668 }
1669
1670 static auto HasUsedDef = [](NodeList &Ms) -> bool {
Krzysztof Parzyszek61d90322016-10-06 13:05:13 +00001671 for (NodeAddr<NodeBase*> M : Ms) {
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001672 if (M.Addr->getKind() != NodeAttrs::Def)
1673 continue;
1674 NodeAddr<DefNode*> DA = M;
1675 if (DA.Addr->getReachedDef() != 0 || DA.Addr->getReachedUse() != 0)
1676 return true;
1677 }
1678 return false;
1679 };
1680
1681 // Any phi, if it is removed, may affect other phis (make them dead).
1682 // For each removed phi, collect the potentially affected phis and add
1683 // them back to the queue.
1684 while (!PhiQ.empty()) {
1685 auto PA = addr<PhiNode*>(PhiQ[0]);
1686 PhiQ.remove(PA.Id);
1687 NodeList Refs = PA.Addr->members(*this);
1688 if (HasUsedDef(Refs))
1689 continue;
1690 for (NodeAddr<RefNode*> RA : Refs) {
1691 if (NodeId RD = RA.Addr->getReachingDef()) {
1692 auto RDA = addr<DefNode*>(RD);
1693 NodeAddr<InstrNode*> OA = RDA.Addr->getOwner(*this);
1694 if (IsPhi(OA))
1695 PhiQ.insert(OA.Id);
1696 }
1697 if (RA.Addr->isDef())
Krzysztof Parzyszek69e670d52016-01-18 20:41:34 +00001698 unlinkDef(RA, true);
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001699 else
Krzysztof Parzyszek69e670d52016-01-18 20:41:34 +00001700 unlinkUse(RA, true);
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001701 }
1702 NodeAddr<BlockNode*> BA = PA.Addr->getOwner(*this);
1703 BA.Addr->removeMember(PA, *this);
1704 }
1705}
1706
1707// For a given reference node TA in an instruction node IA, connect the
1708// reaching def of TA to the appropriate def node. Create any shadow nodes
1709// as appropriate.
1710template <typename T>
1711void DataFlowGraph::linkRefUp(NodeAddr<InstrNode*> IA, NodeAddr<T> TA,
1712 DefStack &DS) {
1713 if (DS.empty())
1714 return;
Krzysztof Parzyszek445bd122016-10-14 17:57:55 +00001715 RegisterRef RR = TA.Addr->getRegRef(*this);
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001716 NodeAddr<T> TAP;
1717
1718 // References from the def stack that have been examined so far.
Krzysztof Parzyszek445bd122016-10-14 17:57:55 +00001719 RegisterAggr Defs(TRI);
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001720
1721 for (auto I = DS.top(), E = DS.bottom(); I != E; I.down()) {
Krzysztof Parzyszek445bd122016-10-14 17:57:55 +00001722 RegisterRef QR = I->Addr->getRegRef(*this);
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +00001723
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001724 // Skip all defs that are aliased to any of the defs that we have already
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +00001725 // seen. If this completes a cover of RR, stop the stack traversal.
1726 bool Alias = Defs.hasAliasOf(QR);
1727 bool Cover = Defs.insert(QR).hasCoverOf(RR);
1728 if (Alias) {
1729 if (Cover)
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001730 break;
1731 continue;
1732 }
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +00001733
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001734 // The reaching def.
1735 NodeAddr<DefNode*> RDA = *I;
1736
1737 // Pick the reached node.
1738 if (TAP.Id == 0) {
1739 TAP = TA;
1740 } else {
1741 // Mark the existing ref as "shadow" and create a new shadow.
1742 TAP.Addr->setFlags(TAP.Addr->getFlags() | NodeAttrs::Shadow);
1743 TAP = getNextShadow(IA, TAP, true);
1744 }
1745
1746 // Create the link.
1747 TAP.Addr->linkToDef(TAP.Id, RDA);
1748
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +00001749 if (Cover)
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001750 break;
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001751 }
1752}
1753
1754// Create data-flow links for all reference nodes in the statement node SA.
1755void DataFlowGraph::linkStmtRefs(DefStackMap &DefM, NodeAddr<StmtNode*> SA) {
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +00001756#ifndef NDEBUG
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001757 RegisterSet Defs;
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +00001758#endif
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001759
1760 // Link all nodes (upwards in the data-flow) with their reaching defs.
1761 for (NodeAddr<RefNode*> RA : SA.Addr->members(*this)) {
1762 uint16_t Kind = RA.Addr->getKind();
1763 assert(Kind == NodeAttrs::Def || Kind == NodeAttrs::Use);
Krzysztof Parzyszek445bd122016-10-14 17:57:55 +00001764 RegisterRef RR = RA.Addr->getRegRef(*this);
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +00001765#ifndef NDEBUG
1766 // Do not expect multiple defs of the same reference.
1767 assert(Kind != NodeAttrs::Def || !Defs.count(RR));
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001768 Defs.insert(RR);
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +00001769#endif
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001770
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +00001771 auto F = DefM.find(RR.Reg);
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001772 if (F == DefM.end())
1773 continue;
1774 DefStack &DS = F->second;
1775 if (Kind == NodeAttrs::Use)
1776 linkRefUp<UseNode*>(SA, RA, DS);
1777 else if (Kind == NodeAttrs::Def)
1778 linkRefUp<DefNode*>(SA, RA, DS);
1779 else
1780 llvm_unreachable("Unexpected node in instruction");
1781 }
1782}
1783
1784// Create data-flow links for all instructions in the block node BA. This
1785// will include updating any phi nodes in BA.
1786void DataFlowGraph::linkBlockRefs(DefStackMap &DefM, NodeAddr<BlockNode*> BA) {
1787 // Push block delimiters.
1788 markBlock(BA.Id, DefM);
1789
Krzysztof Parzyszek89757432016-05-05 22:00:44 +00001790 assert(BA.Addr && "block node address is needed to create a data-flow link");
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001791 // For each non-phi instruction in the block, link all the defs and uses
1792 // to their reaching defs. For any member of the block (including phis),
1793 // push the defs on the corresponding stacks.
1794 for (NodeAddr<InstrNode*> IA : BA.Addr->members(*this)) {
1795 // Ignore phi nodes here. They will be linked part by part from the
1796 // predecessors.
1797 if (IA.Addr->getKind() == NodeAttrs::Stmt)
1798 linkStmtRefs(DefM, IA);
1799
1800 // Push the definitions on the stack.
1801 pushDefs(IA, DefM);
1802 }
1803
1804 // Recursively process all children in the dominator tree.
1805 MachineDomTreeNode *N = MDT.getNode(BA.Addr->getCode());
1806 for (auto I : *N) {
1807 MachineBasicBlock *SB = I->getBlock();
Krzysztof Parzyszek61d90322016-10-06 13:05:13 +00001808 NodeAddr<BlockNode*> SBA = findBlock(SB);
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001809 linkBlockRefs(DefM, SBA);
1810 }
1811
1812 // Link the phi uses from the successor blocks.
1813 auto IsUseForBA = [BA](NodeAddr<NodeBase*> NA) -> bool {
1814 if (NA.Addr->getKind() != NodeAttrs::Use)
1815 return false;
1816 assert(NA.Addr->getFlags() & NodeAttrs::PhiRef);
1817 NodeAddr<PhiUseNode*> PUA = NA;
1818 return PUA.Addr->getPredecessor() == BA.Id;
1819 };
Krzysztof Parzyszek1d322202016-09-27 18:18:44 +00001820
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +00001821 RegisterSet EHLiveIns = getLandingPadLiveIns();
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001822 MachineBasicBlock *MBB = BA.Addr->getCode();
Krzysztof Parzyszek1d322202016-09-27 18:18:44 +00001823
Krzysztof Parzyszek61d90322016-10-06 13:05:13 +00001824 for (MachineBasicBlock *SB : MBB->successors()) {
Krzysztof Parzyszek1d322202016-09-27 18:18:44 +00001825 bool IsEHPad = SB->isEHPad();
1826 NodeAddr<BlockNode*> SBA = findBlock(SB);
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001827 for (NodeAddr<InstrNode*> IA : SBA.Addr->members_if(IsPhi, *this)) {
Krzysztof Parzyszek1d322202016-09-27 18:18:44 +00001828 // Do not link phi uses for landing pad live-ins.
1829 if (IsEHPad) {
1830 // Find what register this phi is for.
1831 NodeAddr<RefNode*> RA = IA.Addr->getFirstMember(*this);
1832 assert(RA.Id != 0);
Krzysztof Parzyszek445bd122016-10-14 17:57:55 +00001833 if (EHLiveIns.count(RA.Addr->getRegRef(*this)))
Krzysztof Parzyszek1d322202016-09-27 18:18:44 +00001834 continue;
1835 }
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001836 // Go over each phi use associated with MBB, and link it.
1837 for (auto U : IA.Addr->members_if(IsUseForBA, *this)) {
1838 NodeAddr<PhiUseNode*> PUA = U;
Krzysztof Parzyszek445bd122016-10-14 17:57:55 +00001839 RegisterRef RR = PUA.Addr->getRegRef(*this);
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +00001840 linkRefUp<UseNode*>(IA, PUA, DefM[RR.Reg]);
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001841 }
1842 }
1843 }
1844
1845 // Pop all defs from this block from the definition stacks.
1846 releaseBlock(BA.Id, DefM);
1847}
1848
1849// Remove the use node UA from any data-flow and structural links.
Krzysztof Parzyszek69e670d52016-01-18 20:41:34 +00001850void DataFlowGraph::unlinkUseDF(NodeAddr<UseNode*> UA) {
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001851 NodeId RD = UA.Addr->getReachingDef();
1852 NodeId Sib = UA.Addr->getSibling();
1853
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001854 if (RD == 0) {
1855 assert(Sib == 0);
1856 return;
1857 }
1858
1859 auto RDA = addr<DefNode*>(RD);
1860 auto TA = addr<UseNode*>(RDA.Addr->getReachedUse());
1861 if (TA.Id == UA.Id) {
1862 RDA.Addr->setReachedUse(Sib);
1863 return;
1864 }
1865
1866 while (TA.Id != 0) {
1867 NodeId S = TA.Addr->getSibling();
1868 if (S == UA.Id) {
1869 TA.Addr->setSibling(UA.Addr->getSibling());
1870 return;
1871 }
1872 TA = addr<UseNode*>(S);
1873 }
1874}
1875
1876// Remove the def node DA from any data-flow and structural links.
Krzysztof Parzyszek69e670d52016-01-18 20:41:34 +00001877void DataFlowGraph::unlinkDefDF(NodeAddr<DefNode*> DA) {
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001878 //
1879 // RD
1880 // | reached
1881 // | def
1882 // :
1883 // .
1884 // +----+
1885 // ... -- | DA | -- ... -- 0 : sibling chain of DA
1886 // +----+
1887 // | | reached
1888 // | : def
1889 // | .
1890 // | ... : Siblings (defs)
1891 // |
1892 // : reached
1893 // . use
1894 // ... : sibling chain of reached uses
1895
1896 NodeId RD = DA.Addr->getReachingDef();
1897
1898 // Visit all siblings of the reached def and reset their reaching defs.
1899 // Also, defs reached by DA are now "promoted" to being reached by RD,
1900 // so all of them will need to be spliced into the sibling chain where
1901 // DA belongs.
1902 auto getAllNodes = [this] (NodeId N) -> NodeList {
1903 NodeList Res;
1904 while (N) {
1905 auto RA = addr<RefNode*>(N);
1906 // Keep the nodes in the exact sibling order.
1907 Res.push_back(RA);
1908 N = RA.Addr->getSibling();
1909 }
1910 return Res;
1911 };
1912 NodeList ReachedDefs = getAllNodes(DA.Addr->getReachedDef());
1913 NodeList ReachedUses = getAllNodes(DA.Addr->getReachedUse());
1914
1915 if (RD == 0) {
1916 for (NodeAddr<RefNode*> I : ReachedDefs)
1917 I.Addr->setSibling(0);
1918 for (NodeAddr<RefNode*> I : ReachedUses)
1919 I.Addr->setSibling(0);
1920 }
1921 for (NodeAddr<DefNode*> I : ReachedDefs)
1922 I.Addr->setReachingDef(RD);
1923 for (NodeAddr<UseNode*> I : ReachedUses)
1924 I.Addr->setReachingDef(RD);
1925
1926 NodeId Sib = DA.Addr->getSibling();
1927 if (RD == 0) {
1928 assert(Sib == 0);
1929 return;
1930 }
1931
1932 // Update the reaching def node and remove DA from the sibling list.
1933 auto RDA = addr<DefNode*>(RD);
1934 auto TA = addr<DefNode*>(RDA.Addr->getReachedDef());
1935 if (TA.Id == DA.Id) {
1936 // If DA is the first reached def, just update the RD's reached def
1937 // to the DA's sibling.
1938 RDA.Addr->setReachedDef(Sib);
1939 } else {
1940 // Otherwise, traverse the sibling list of the reached defs and remove
1941 // DA from it.
1942 while (TA.Id != 0) {
1943 NodeId S = TA.Addr->getSibling();
1944 if (S == DA.Id) {
1945 TA.Addr->setSibling(Sib);
1946 break;
1947 }
1948 TA = addr<DefNode*>(S);
1949 }
1950 }
1951
1952 // Splice the DA's reached defs into the RDA's reached def chain.
1953 if (!ReachedDefs.empty()) {
1954 auto Last = NodeAddr<DefNode*>(ReachedDefs.back());
1955 Last.Addr->setSibling(RDA.Addr->getReachedDef());
1956 RDA.Addr->setReachedDef(ReachedDefs.front().Id);
1957 }
1958 // Splice the DA's reached uses into the RDA's reached use chain.
1959 if (!ReachedUses.empty()) {
1960 auto Last = NodeAddr<UseNode*>(ReachedUses.back());
1961 Last.Addr->setSibling(RDA.Addr->getReachedUse());
1962 RDA.Addr->setReachedUse(ReachedUses.front().Id);
1963 }
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001964}