blob: 79ae8850ab930a8e4ae09a968e6bc4df48271441 [file] [log] [blame]
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001//===--- RDFGraph.h -------------------------------------------------------===//
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// for a non-SSA program representation (e.g. post-RA machine code).
12//
13//
14// *** Introduction
15//
16// The RDF graph is a collection of nodes, each of which denotes some element
17// of the program. There are two main types of such elements: code and refe-
18// rences. Conceptually, "code" is something that represents the structure
19// of the program, e.g. basic block or a statement, while "reference" is an
20// instance of accessing a register, e.g. a definition or a use. Nodes are
21// connected with each other based on the structure of the program (such as
22// blocks, instructions, etc.), and based on the data flow (e.g. reaching
23// definitions, reached uses, etc.). The single-reaching-definition principle
24// of SSA is generally observed, although, due to the non-SSA representation
25// of the program, there are some differences between the graph and a "pure"
26// SSA representation.
27//
28//
29// *** Implementation remarks
30//
31// Since the graph can contain a large number of nodes, memory consumption
32// was one of the major design considerations. As a result, there is a single
33// base class NodeBase which defines all members used by all possible derived
34// classes. The members are arranged in a union, and a derived class cannot
35// add any data members of its own. Each derived class only defines the
36// functional interface, i.e. member functions. NodeBase must be a POD,
37// which implies that all of its members must also be PODs.
38// Since nodes need to be connected with other nodes, pointers have been
39// replaced with 32-bit identifiers: each node has an id of type NodeId.
40// There are mapping functions in the graph that translate between actual
41// memory addresses and the corresponding identifiers.
42// A node id of 0 is equivalent to nullptr.
43//
44//
45// *** Structure of the graph
46//
47// A code node is always a collection of other nodes. For example, a code
48// node corresponding to a basic block will contain code nodes corresponding
49// to instructions. In turn, a code node corresponding to an instruction will
50// contain a list of reference nodes that correspond to the definitions and
51// uses of registers in that instruction. The members are arranged into a
52// circular list, which is yet another consequence of the effort to save
53// memory: for each member node it should be possible to obtain its owner,
54// and it should be possible to access all other members. There are other
55// ways to accomplish that, but the circular list seemed the most natural.
56//
57// +- CodeNode -+
58// | | <---------------------------------------------------+
59// +-+--------+-+ |
60// |FirstM |LastM |
61// | +-------------------------------------+ |
62// | | |
63// V V |
64// +----------+ Next +----------+ Next Next +----------+ Next |
65// | |----->| |-----> ... ----->| |----->-+
66// +- Member -+ +- Member -+ +- Member -+
67//
68// The order of members is such that related reference nodes (see below)
69// should be contiguous on the member list.
70//
71// A reference node is a node that encapsulates an access to a register,
72// in other words, data flowing into or out of a register. There are two
73// major kinds of reference nodes: defs and uses. A def node will contain
74// the id of the first reached use, and the id of the first reached def.
75// Each def and use will contain the id of the reaching def, and also the
76// id of the next reached def (for def nodes) or use (for use nodes).
77// The "next node sharing the same reaching def" is denoted as "sibling".
78// In summary:
79// - Def node contains: reaching def, sibling, first reached def, and first
80// reached use.
81// - Use node contains: reaching def and sibling.
82//
83// +-- DefNode --+
84// | R2 = ... | <---+--------------------+
85// ++---------+--+ | |
86// |Reached |Reached | |
87// |Def |Use | |
88// | | |Reaching |Reaching
89// | V |Def |Def
90// | +-- UseNode --+ Sib +-- UseNode --+ Sib Sib
91// | | ... = R2 |----->| ... = R2 |----> ... ----> 0
92// | +-------------+ +-------------+
93// V
94// +-- DefNode --+ Sib
95// | R2 = ... |----> ...
96// ++---------+--+
97// | |
98// | |
99// ... ...
100//
101// To get a full picture, the circular lists connecting blocks within a
102// function, instructions within a block, etc. should be superimposed with
103// the def-def, def-use links shown above.
104// To illustrate this, consider a small example in a pseudo-assembly:
105// foo:
106// add r2, r0, r1 ; r2 = r0+r1
107// addi r0, r2, 1 ; r0 = r2+1
108// ret r0 ; return value in r0
109//
110// The graph (in a format used by the debugging functions) would look like:
111//
112// DFG dump:[
113// f1: Function foo
114// b2: === BB#0 === preds(0), succs(0):
115// p3: phi [d4<r0>(,d12,u9):]
116// p5: phi [d6<r1>(,,u10):]
117// s7: add [d8<r2>(,,u13):, u9<r0>(d4):, u10<r1>(d6):]
118// s11: addi [d12<r0>(d4,,u15):, u13<r2>(d8):]
119// s14: ret [u15<r0>(d12):]
120// ]
121//
122// The f1, b2, p3, etc. are node ids. The letter is prepended to indicate the
123// kind of the node (i.e. f - function, b - basic block, p - phi, s - state-
124// ment, d - def, u - use).
125// The format of a def node is:
126// dN<R>(rd,d,u):sib,
127// where
128// N - numeric node id,
129// R - register being defined
130// rd - reaching def,
131// d - reached def,
132// u - reached use,
133// sib - sibling.
134// The format of a use node is:
135// uN<R>[!](rd):sib,
136// where
137// N - numeric node id,
138// R - register being used,
139// rd - reaching def,
140// sib - sibling.
141// Possible annotations (usually preceding the node id):
142// + - preserving def,
143// ~ - clobbering def,
144// " - shadow ref (follows the node id),
145// ! - fixed register (appears after register name).
146//
147// The circular lists are not explicit in the dump.
148//
149//
150// *** Node attributes
151//
152// NodeBase has a member "Attrs", which is the primary way of determining
153// the node's characteristics. The fields in this member decide whether
154// the node is a code node or a reference node (i.e. node's "type"), then
155// within each type, the "kind" determines what specifically this node
156// represents. The remaining bits, "flags", contain additional information
157// that is even more detailed than the "kind".
158// CodeNode's kinds are:
159// - Phi: Phi node, members are reference nodes.
160// - Stmt: Statement, members are reference nodes.
161// - Block: Basic block, members are instruction nodes (i.e. Phi or Stmt).
162// - Func: The whole function. The members are basic block nodes.
163// RefNode's kinds are:
164// - Use.
165// - Def.
166//
167// Meaning of flags:
168// - Preserving: applies only to defs. A preserving def is one that can
169// preserve some of the original bits among those that are included in
170// the register associated with that def. For example, if R0 is a 32-bit
171// register, but a def can only change the lower 16 bits, then it will
172// be marked as preserving.
173// - Shadow: a reference that has duplicates holding additional reaching
174// defs (see more below).
175// - Clobbering: applied only to defs, indicates that the value generated
176// by this def is unspecified. A typical example would be volatile registers
177// after function calls.
Krzysztof Parzyszek1ff99522016-09-07 20:10:56 +0000178// - Fixed: the register in this def/use cannot be replaced with any other
179// register. A typical case would be a parameter register to a call, or
180// the register with the return value from a function.
181// - Undef: the register in this reference the register is assumed to have
182// no pre-existing value, even if it appears to be reached by some def.
183// This is typically used to prevent keeping registers artificially live
184// in cases when they are defined via predicated instructions. For example:
185// r0 = add-if-true cond, r10, r11 (1)
186// r0 = add-if-false cond, r12, r13, r0<imp-use> (2)
187// ... = r0 (3)
188// Before (1), r0 is not intended to be live, and the use of r0 in (3) is
189// not meant to be reached by any def preceding (1). However, since the
190// defs in (1) and (2) are both preserving, these properties alone would
191// imply that the use in (3) may indeed be reached by some prior def.
192// Adding Undef flag to the def in (1) prevents that. The Undef flag
193// may be applied to both defs and uses.
Krzysztof Parzyszek586fc122016-09-27 18:24:33 +0000194// - Dead: applies only to defs. The value coming out of a "dead" def is
195// assumed to be unused, even if the def appears to be reaching other defs
196// or uses. The motivation for this flag comes from dead defs on function
197// calls: there is no way to determine if such a def is dead without
198// analyzing the target's ABI. Hence the graph should contain this info,
199// as it is unavailable otherwise. On the other hand, a def without any
200// uses on a typical instruction is not the intended target for this flag.
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000201//
202// *** Shadow references
203//
204// It may happen that a super-register can have two (or more) non-overlapping
205// sub-registers. When both of these sub-registers are defined and followed
206// by a use of the super-register, the use of the super-register will not
207// have a unique reaching def: both defs of the sub-registers need to be
208// accounted for. In such cases, a duplicate use of the super-register is
209// added and it points to the extra reaching def. Both uses are marked with
210// a flag "shadow". Example:
211// Assume t0 is a super-register of r0 and r1, r0 and r1 do not overlap:
212// set r0, 1 ; r0 = 1
213// set r1, 1 ; r1 = 1
214// addi t1, t0, 1 ; t1 = t0+1
215//
216// The DFG:
217// s1: set [d2<r0>(,,u9):]
218// s3: set [d4<r1>(,,u10):]
219// s5: addi [d6<t1>(,,):, u7"<t0>(d2):, u8"<t0>(d4):]
220//
221// The statement s5 has two use nodes for t0: u7" and u9". The quotation
222// mark " indicates that the node is a shadow.
223//
224#ifndef RDF_GRAPH_H
225#define RDF_GRAPH_H
226
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000227#include "llvm/Support/Allocator.h"
228#include "llvm/Support/Debug.h"
229#include "llvm/Support/raw_ostream.h"
230#include "llvm/Support/Timer.h"
Krzysztof Parzyszek29e93f32016-09-22 21:01:24 +0000231#include "llvm/Target/TargetRegisterInfo.h"
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000232
233#include <functional>
234#include <map>
235#include <set>
Krzysztof Parzyszek047149f2016-07-22 16:09:47 +0000236#include <unordered_map>
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000237#include <vector>
238
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000239namespace llvm {
240 class MachineBasicBlock;
241 class MachineFunction;
242 class MachineInstr;
243 class MachineOperand;
244 class MachineDominanceFrontier;
245 class MachineDominatorTree;
246 class TargetInstrInfo;
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000247
248namespace rdf {
249 typedef uint32_t NodeId;
250
Krzysztof Parzyszek29e93f32016-09-22 21:01:24 +0000251 struct DataFlowGraph;
252
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000253 struct NodeAttrs {
254 enum : uint16_t {
255 None = 0x0000, // Nothing
256
257 // Types: 2 bits
258 TypeMask = 0x0003,
259 Code = 0x0001, // 01, Container
260 Ref = 0x0002, // 10, Reference
261
262 // Kind: 3 bits
263 KindMask = 0x0007 << 2,
264 Def = 0x0001 << 2, // 001
265 Use = 0x0002 << 2, // 010
266 Phi = 0x0003 << 2, // 011
267 Stmt = 0x0004 << 2, // 100
268 Block = 0x0005 << 2, // 101
269 Func = 0x0006 << 2, // 110
270
Krzysztof Parzyszek586fc122016-09-27 18:24:33 +0000271 // Flags: 7 bits for now
272 FlagMask = 0x007F << 5,
273 Shadow = 0x0001 << 5, // 0000001, Has extra reaching defs.
274 Clobbering = 0x0002 << 5, // 0000010, Produces unspecified values.
275 PhiRef = 0x0004 << 5, // 0000100, Member of PhiNode.
276 Preserving = 0x0008 << 5, // 0001000, Def can keep original bits.
277 Fixed = 0x0010 << 5, // 0010000, Fixed register.
278 Undef = 0x0020 << 5, // 0100000, Has no pre-existing value.
279 Dead = 0x0040 << 5, // 1000000, Does not define a value.
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000280 };
281
282 static uint16_t type(uint16_t T) { return T & TypeMask; }
283 static uint16_t kind(uint16_t T) { return T & KindMask; }
284 static uint16_t flags(uint16_t T) { return T & FlagMask; }
285
286 static uint16_t set_type(uint16_t A, uint16_t T) {
287 return (A & ~TypeMask) | T;
288 }
289 static uint16_t set_kind(uint16_t A, uint16_t K) {
290 return (A & ~KindMask) | K;
291 }
292 static uint16_t set_flags(uint16_t A, uint16_t F) {
293 return (A & ~FlagMask) | F;
294 }
295
296 // Test if A contains B.
297 static bool contains(uint16_t A, uint16_t B) {
298 if (type(A) != Code)
299 return false;
300 uint16_t KB = kind(B);
301 switch (kind(A)) {
302 case Func:
303 return KB == Block;
304 case Block:
305 return KB == Phi || KB == Stmt;
306 case Phi:
307 case Stmt:
308 return type(B) == Ref;
309 }
310 return false;
311 }
312 };
313
Krzysztof Parzyszek55874cf2016-04-28 20:17:06 +0000314 struct BuildOptions {
315 enum : unsigned {
316 None = 0x00,
317 KeepDeadPhis = 0x01, // Do not remove dead phis during build.
318 };
319 };
320
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000321 template <typename T> struct NodeAddr {
322 NodeAddr() : Addr(nullptr), Id(0) {}
323 NodeAddr(T A, NodeId I) : Addr(A), Id(I) {}
324 NodeAddr(const NodeAddr&) = default;
325 NodeAddr &operator= (const NodeAddr&) = default;
326
327 bool operator== (const NodeAddr<T> &NA) const {
328 assert((Addr == NA.Addr) == (Id == NA.Id));
329 return Addr == NA.Addr;
330 }
331 bool operator!= (const NodeAddr<T> &NA) const {
332 return !operator==(NA);
333 }
334 // Type cast (casting constructor). The reason for having this class
335 // instead of std::pair.
336 template <typename S> NodeAddr(const NodeAddr<S> &NA)
337 : Addr(static_cast<T>(NA.Addr)), Id(NA.Id) {}
338
339 T Addr;
340 NodeId Id;
341 };
342
343 struct NodeBase;
344
345 // Fast memory allocation and translation between node id and node address.
346 // This is really the same idea as the one underlying the "bump pointer
347 // allocator", the difference being in the translation. A node id is
348 // composed of two components: the index of the block in which it was
349 // allocated, and the index within the block. With the default settings,
350 // where the number of nodes per block is 4096, the node id (minus 1) is:
351 //
352 // bit position: 11 0
353 // +----------------------------+--------------+
354 // | Index of the block |Index in block|
355 // +----------------------------+--------------+
356 //
357 // The actual node id is the above plus 1, to avoid creating a node id of 0.
358 //
359 // This method significantly improved the build time, compared to using maps
360 // (std::unordered_map or DenseMap) to translate between pointers and ids.
361 struct NodeAllocator {
362 // Amount of storage for a single node.
363 enum { NodeMemSize = 32 };
364 NodeAllocator(uint32_t NPB = 4096)
365 : NodesPerBlock(NPB), BitsPerIndex(Log2_32(NPB)),
366 IndexMask((1 << BitsPerIndex)-1), ActiveEnd(nullptr) {
367 assert(isPowerOf2_32(NPB));
368 }
369 NodeBase *ptr(NodeId N) const {
370 uint32_t N1 = N-1;
371 uint32_t BlockN = N1 >> BitsPerIndex;
372 uint32_t Offset = (N1 & IndexMask) * NodeMemSize;
373 return reinterpret_cast<NodeBase*>(Blocks[BlockN]+Offset);
374 }
375 NodeId id(const NodeBase *P) const;
376 NodeAddr<NodeBase*> New();
377 void clear();
378
379 private:
380 void startNewBlock();
381 bool needNewBlock();
382 uint32_t makeId(uint32_t Block, uint32_t Index) const {
383 // Add 1 to the id, to avoid the id of 0, which is treated as "null".
384 return ((Block << BitsPerIndex) | Index) + 1;
385 }
386
387 const uint32_t NodesPerBlock;
388 const uint32_t BitsPerIndex;
389 const uint32_t IndexMask;
390 char *ActiveEnd;
391 std::vector<char*> Blocks;
392 typedef BumpPtrAllocatorImpl<MallocAllocator, 65536> AllocatorTy;
393 AllocatorTy MemPool;
394 };
395
396 struct RegisterRef {
Krzysztof Parzyszek29e93f32016-09-22 21:01:24 +0000397 // For virtual registers, Reg and Sub have the usual meanings.
398 //
399 // Physical registers are assumed not to have any subregisters, and for
400 // them, Sub is the key of the LaneBitmask in the lane mask map in DFG.
401 // The case of Sub = 0 is treated as 'all lanes', i.e. lane mask of ~0.
402 // Use an key/map to access lane masks, since we only have uint32_t
403 // for it, and the LaneBitmask type can grow in the future.
404 //
405 // The case when Reg = 0 and Sub = 0 is reserved to mean "no register".
Krzysztof Parzyszekc51f2392016-09-22 20:56:39 +0000406 uint32_t Reg, Sub;
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000407
408 // No non-trivial constructors, since this will be a member of a union.
409 RegisterRef() = default;
410 RegisterRef(const RegisterRef &RR) = default;
411 RegisterRef &operator= (const RegisterRef &RR) = default;
412 bool operator== (const RegisterRef &RR) const {
413 return Reg == RR.Reg && Sub == RR.Sub;
414 }
415 bool operator!= (const RegisterRef &RR) const {
416 return !operator==(RR);
417 }
418 bool operator< (const RegisterRef &RR) const {
419 return Reg < RR.Reg || (Reg == RR.Reg && Sub < RR.Sub);
420 }
421 };
422 typedef std::set<RegisterRef> RegisterSet;
423
424 struct RegisterAliasInfo {
425 RegisterAliasInfo(const TargetRegisterInfo &tri) : TRI(tri) {}
426 virtual ~RegisterAliasInfo() {}
427
428 virtual std::vector<RegisterRef> getAliasSet(RegisterRef RR) const;
Krzysztof Parzyszek29e93f32016-09-22 21:01:24 +0000429 virtual bool alias(RegisterRef RA, RegisterRef RB,
430 const DataFlowGraph &DFG) const;
431 virtual bool covers(RegisterRef RA, RegisterRef RB,
432 const DataFlowGraph &DFG) const;
433 virtual bool covers(const RegisterSet &RRs, RegisterRef RR,
434 const DataFlowGraph &DFG) const;
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000435
436 const TargetRegisterInfo &TRI;
Krzysztof Parzyszek29e93f32016-09-22 21:01:24 +0000437
438 protected:
439 LaneBitmask getLaneMask(RegisterRef RR, const DataFlowGraph &DFG) const;
440
441 struct CommonRegister {
442 CommonRegister(unsigned RegA, LaneBitmask LA,
443 unsigned RegB, LaneBitmask LB,
444 const TargetRegisterInfo &TRI);
445 unsigned SuperReg;
446 LaneBitmask MaskA, MaskB;
447 };
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000448 };
449
450 struct TargetOperandInfo {
451 TargetOperandInfo(const TargetInstrInfo &tii) : TII(tii) {}
452 virtual ~TargetOperandInfo() {}
453 virtual bool isPreserving(const MachineInstr &In, unsigned OpNum) const;
454 virtual bool isClobbering(const MachineInstr &In, unsigned OpNum) const;
455 virtual bool isFixedReg(const MachineInstr &In, unsigned OpNum) const;
456
457 const TargetInstrInfo &TII;
458 };
459
Krzysztof Parzyszek29e93f32016-09-22 21:01:24 +0000460 // Template class for a map translating uint32_t into arbitrary types.
461 // The map will act like an indexed set: upon insertion of a new object,
462 // it will automatically assign a new index to it. Index of 0 is treated
463 // as invalid and is never allocated.
464 template <typename T, unsigned N = 32>
465 struct IndexedSet {
466 IndexedSet() : Map(N) {}
467 const T get(uint32_t Idx) const {
468 // Index Idx corresponds to Map[Idx-1].
469 assert(Idx != 0 && !Map.empty() && Idx-1 < Map.size());
470 return Map[Idx-1];
471 }
472 uint32_t insert(T Val) {
473 // Linear search.
474 auto F = find(Map, Val);
475 if (F != Map.end())
476 return *F;
477 Map.push_back(Val);
478 return Map.size(); // Return actual_index + 1.
479 }
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000480
Krzysztof Parzyszek29e93f32016-09-22 21:01:24 +0000481 private:
482 std::vector<T> Map;
483 };
484
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000485
486 struct NodeBase {
487 public:
488 // Make sure this is a POD.
489 NodeBase() = default;
490 uint16_t getType() const { return NodeAttrs::type(Attrs); }
491 uint16_t getKind() const { return NodeAttrs::kind(Attrs); }
492 uint16_t getFlags() const { return NodeAttrs::flags(Attrs); }
493 NodeId getNext() const { return Next; }
494
495 uint16_t getAttrs() const { return Attrs; }
496 void setAttrs(uint16_t A) { Attrs = A; }
497 void setFlags(uint16_t F) { setAttrs(NodeAttrs::set_flags(getAttrs(), F)); }
498
499 // Insert node NA after "this" in the circular chain.
500 void append(NodeAddr<NodeBase*> NA);
501 // Initialize all members to 0.
502 void init() { memset(this, 0, sizeof *this); }
503 void setNext(NodeId N) { Next = N; }
504
505 protected:
506 uint16_t Attrs;
507 uint16_t Reserved;
508 NodeId Next; // Id of the next node in the circular chain.
509 // Definitions of nested types. Using anonymous nested structs would make
510 // this class definition clearer, but unnamed structs are not a part of
511 // the standard.
512 struct Def_struct {
513 NodeId DD, DU; // Ids of the first reached def and use.
514 };
515 struct PhiU_struct {
516 NodeId PredB; // Id of the predecessor block for a phi use.
517 };
518 struct Code_struct {
519 void *CP; // Pointer to the actual code.
520 NodeId FirstM, LastM; // Id of the first member and last.
521 };
522 struct Ref_struct {
523 NodeId RD, Sib; // Ids of the reaching def and the sibling.
524 union {
525 Def_struct Def;
526 PhiU_struct PhiU;
527 };
528 union {
529 MachineOperand *Op; // Non-phi refs point to a machine operand.
530 RegisterRef RR; // Phi refs store register info directly.
531 };
532 };
533
534 // The actual payload.
535 union {
536 Ref_struct Ref;
537 Code_struct Code;
538 };
539 };
540 // The allocator allocates chunks of 32 bytes for each node. The fact that
541 // each node takes 32 bytes in memory is used for fast translation between
542 // the node id and the node address.
543 static_assert(sizeof(NodeBase) <= NodeAllocator::NodeMemSize,
544 "NodeBase must be at most NodeAllocator::NodeMemSize bytes");
545
546 typedef std::vector<NodeAddr<NodeBase*>> NodeList;
547 typedef std::set<NodeId> NodeSet;
548
549 struct RefNode : public NodeBase {
550 RefNode() = default;
551 RegisterRef getRegRef() const;
552 MachineOperand &getOp() {
553 assert(!(getFlags() & NodeAttrs::PhiRef));
554 return *Ref.Op;
555 }
556 void setRegRef(RegisterRef RR);
557 void setRegRef(MachineOperand *Op);
558 NodeId getReachingDef() const {
559 return Ref.RD;
560 }
561 void setReachingDef(NodeId RD) {
562 Ref.RD = RD;
563 }
564 NodeId getSibling() const {
565 return Ref.Sib;
566 }
567 void setSibling(NodeId Sib) {
568 Ref.Sib = Sib;
569 }
570 bool isUse() const {
571 assert(getType() == NodeAttrs::Ref);
572 return getKind() == NodeAttrs::Use;
573 }
574 bool isDef() const {
575 assert(getType() == NodeAttrs::Ref);
576 return getKind() == NodeAttrs::Def;
577 }
578
579 template <typename Predicate>
580 NodeAddr<RefNode*> getNextRef(RegisterRef RR, Predicate P, bool NextOnly,
581 const DataFlowGraph &G);
582 NodeAddr<NodeBase*> getOwner(const DataFlowGraph &G);
583 };
584
585 struct DefNode : public RefNode {
586 NodeId getReachedDef() const {
587 return Ref.Def.DD;
588 }
589 void setReachedDef(NodeId D) {
590 Ref.Def.DD = D;
591 }
592 NodeId getReachedUse() const {
593 return Ref.Def.DU;
594 }
595 void setReachedUse(NodeId U) {
596 Ref.Def.DU = U;
597 }
598
599 void linkToDef(NodeId Self, NodeAddr<DefNode*> DA);
600 };
601
602 struct UseNode : public RefNode {
603 void linkToDef(NodeId Self, NodeAddr<DefNode*> DA);
604 };
605
606 struct PhiUseNode : public UseNode {
607 NodeId getPredecessor() const {
608 assert(getFlags() & NodeAttrs::PhiRef);
609 return Ref.PhiU.PredB;
610 }
611 void setPredecessor(NodeId B) {
612 assert(getFlags() & NodeAttrs::PhiRef);
613 Ref.PhiU.PredB = B;
614 }
615 };
616
617 struct CodeNode : public NodeBase {
618 template <typename T> T getCode() const {
619 return static_cast<T>(Code.CP);
620 }
621 void setCode(void *C) {
622 Code.CP = C;
623 }
624
625 NodeAddr<NodeBase*> getFirstMember(const DataFlowGraph &G) const;
626 NodeAddr<NodeBase*> getLastMember(const DataFlowGraph &G) const;
627 void addMember(NodeAddr<NodeBase*> NA, const DataFlowGraph &G);
628 void addMemberAfter(NodeAddr<NodeBase*> MA, NodeAddr<NodeBase*> NA,
629 const DataFlowGraph &G);
630 void removeMember(NodeAddr<NodeBase*> NA, const DataFlowGraph &G);
631
632 NodeList members(const DataFlowGraph &G) const;
633 template <typename Predicate>
634 NodeList members_if(Predicate P, const DataFlowGraph &G) const;
635 };
636
637 struct InstrNode : public CodeNode {
638 NodeAddr<NodeBase*> getOwner(const DataFlowGraph &G);
639 };
640
641 struct PhiNode : public InstrNode {
642 MachineInstr *getCode() const {
643 return nullptr;
644 }
645 };
646
647 struct StmtNode : public InstrNode {
648 MachineInstr *getCode() const {
649 return CodeNode::getCode<MachineInstr*>();
650 }
651 };
652
653 struct BlockNode : public CodeNode {
654 MachineBasicBlock *getCode() const {
655 return CodeNode::getCode<MachineBasicBlock*>();
656 }
657 void addPhi(NodeAddr<PhiNode*> PA, const DataFlowGraph &G);
658 };
659
660 struct FuncNode : public CodeNode {
661 MachineFunction *getCode() const {
662 return CodeNode::getCode<MachineFunction*>();
663 }
664 NodeAddr<BlockNode*> findBlock(const MachineBasicBlock *BB,
665 const DataFlowGraph &G) const;
666 NodeAddr<BlockNode*> getEntryBlock(const DataFlowGraph &G);
667 };
668
669 struct DataFlowGraph {
670 DataFlowGraph(MachineFunction &mf, const TargetInstrInfo &tii,
671 const TargetRegisterInfo &tri, const MachineDominatorTree &mdt,
672 const MachineDominanceFrontier &mdf, const RegisterAliasInfo &rai,
673 const TargetOperandInfo &toi);
674
675 NodeBase *ptr(NodeId N) const;
676 template <typename T> T ptr(NodeId N) const {
677 return static_cast<T>(ptr(N));
678 }
679 NodeId id(const NodeBase *P) const;
680
681 template <typename T> NodeAddr<T> addr(NodeId N) const {
682 return { ptr<T>(N), N };
683 }
684
685 NodeAddr<FuncNode*> getFunc() const {
686 return Func;
687 }
688 MachineFunction &getMF() const {
689 return MF;
690 }
691 const TargetInstrInfo &getTII() const {
692 return TII;
693 }
694 const TargetRegisterInfo &getTRI() const {
695 return TRI;
696 }
697 const MachineDominatorTree &getDT() const {
698 return MDT;
699 }
700 const MachineDominanceFrontier &getDF() const {
701 return MDF;
702 }
703 const RegisterAliasInfo &getRAI() const {
704 return RAI;
705 }
706
Krzysztof Parzyszek29e93f32016-09-22 21:01:24 +0000707 LaneBitmask getLaneMaskForIndex(uint32_t K) const {
708 return LMMap.get(K);
709 }
710 uint32_t getIndexForLaneMask(LaneBitmask LM) {
711 return LMMap.insert(LM);
712 }
713
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000714 struct DefStack {
715 DefStack() = default;
716 bool empty() const { return Stack.empty() || top() == bottom(); }
717 private:
718 typedef NodeAddr<DefNode*> value_type;
719 struct Iterator {
720 typedef DefStack::value_type value_type;
721 Iterator &up() { Pos = DS.nextUp(Pos); return *this; }
722 Iterator &down() { Pos = DS.nextDown(Pos); return *this; }
723 value_type operator*() const {
724 assert(Pos >= 1);
725 return DS.Stack[Pos-1];
726 }
727 const value_type *operator->() const {
728 assert(Pos >= 1);
729 return &DS.Stack[Pos-1];
730 }
731 bool operator==(const Iterator &It) const { return Pos == It.Pos; }
732 bool operator!=(const Iterator &It) const { return Pos != It.Pos; }
733 private:
734 Iterator(const DefStack &S, bool Top);
735 // Pos-1 is the index in the StorageType object that corresponds to
736 // the top of the DefStack.
737 const DefStack &DS;
738 unsigned Pos;
739 friend struct DefStack;
740 };
741 public:
742 typedef Iterator iterator;
743 iterator top() const { return Iterator(*this, true); }
744 iterator bottom() const { return Iterator(*this, false); }
745 unsigned size() const;
746
747 void push(NodeAddr<DefNode*> DA) { Stack.push_back(DA); }
748 void pop();
749 void start_block(NodeId N);
750 void clear_block(NodeId N);
751 private:
752 friend struct Iterator;
753 typedef std::vector<value_type> StorageType;
754 bool isDelimiter(const StorageType::value_type &P, NodeId N = 0) const {
755 return (P.Addr == nullptr) && (N == 0 || P.Id == N);
756 }
757 unsigned nextUp(unsigned P) const;
758 unsigned nextDown(unsigned P) const;
759 StorageType Stack;
760 };
761
Krzysztof Parzyszek047149f2016-07-22 16:09:47 +0000762 struct RegisterRefHasher {
763 unsigned operator() (RegisterRef RR) const {
764 return RR.Reg | (RR.Sub << 24);
765 }
766 };
767 // Make this std::unordered_map for speed of accessing elements.
768 typedef std::unordered_map<RegisterRef,DefStack,RegisterRefHasher>
769 DefStackMap;
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000770
Krzysztof Parzyszek55874cf2016-04-28 20:17:06 +0000771 void build(unsigned Options = BuildOptions::None);
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000772 void pushDefs(NodeAddr<InstrNode*> IA, DefStackMap &DM);
773 void markBlock(NodeId B, DefStackMap &DefM);
774 void releaseBlock(NodeId B, DefStackMap &DefM);
775
776 NodeAddr<RefNode*> getNextRelated(NodeAddr<InstrNode*> IA,
777 NodeAddr<RefNode*> RA) const;
778 NodeAddr<RefNode*> getNextImp(NodeAddr<InstrNode*> IA,
779 NodeAddr<RefNode*> RA, bool Create);
780 NodeAddr<RefNode*> getNextImp(NodeAddr<InstrNode*> IA,
781 NodeAddr<RefNode*> RA) const;
782 NodeAddr<RefNode*> getNextShadow(NodeAddr<InstrNode*> IA,
783 NodeAddr<RefNode*> RA, bool Create);
784 NodeAddr<RefNode*> getNextShadow(NodeAddr<InstrNode*> IA,
785 NodeAddr<RefNode*> RA) const;
786
787 NodeList getRelatedRefs(NodeAddr<InstrNode*> IA,
788 NodeAddr<RefNode*> RA) const;
789
Krzysztof Parzyszek69e670d52016-01-18 20:41:34 +0000790 void unlinkUse(NodeAddr<UseNode*> UA, bool RemoveFromOwner) {
791 unlinkUseDF(UA);
792 if (RemoveFromOwner)
793 removeFromOwner(UA);
794 }
795 void unlinkDef(NodeAddr<DefNode*> DA, bool RemoveFromOwner) {
796 unlinkDefDF(DA);
797 if (RemoveFromOwner)
798 removeFromOwner(DA);
799 }
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000800
801 // Some useful filters.
802 template <uint16_t Kind>
803 static bool IsRef(const NodeAddr<NodeBase*> BA) {
804 return BA.Addr->getType() == NodeAttrs::Ref &&
805 BA.Addr->getKind() == Kind;
806 }
807 template <uint16_t Kind>
808 static bool IsCode(const NodeAddr<NodeBase*> BA) {
809 return BA.Addr->getType() == NodeAttrs::Code &&
810 BA.Addr->getKind() == Kind;
811 }
812 static bool IsDef(const NodeAddr<NodeBase*> BA) {
813 return BA.Addr->getType() == NodeAttrs::Ref &&
814 BA.Addr->getKind() == NodeAttrs::Def;
815 }
816 static bool IsUse(const NodeAddr<NodeBase*> BA) {
817 return BA.Addr->getType() == NodeAttrs::Ref &&
818 BA.Addr->getKind() == NodeAttrs::Use;
819 }
820 static bool IsPhi(const NodeAddr<NodeBase*> BA) {
821 return BA.Addr->getType() == NodeAttrs::Code &&
822 BA.Addr->getKind() == NodeAttrs::Phi;
823 }
Krzysztof Parzyszek1ff99522016-09-07 20:10:56 +0000824 static bool IsPreservingDef(const NodeAddr<DefNode*> DA) {
825 uint16_t Flags = DA.Addr->getFlags();
826 return (Flags & NodeAttrs::Preserving) && !(Flags & NodeAttrs::Undef);
827 }
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000828
829 private:
830 void reset();
831
Krzysztof Parzyszek1d322202016-09-27 18:18:44 +0000832 std::vector<uint32_t> getLandingPadLiveIns() const;
833
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000834 NodeAddr<NodeBase*> newNode(uint16_t Attrs);
835 NodeAddr<NodeBase*> cloneNode(const NodeAddr<NodeBase*> B);
836 NodeAddr<UseNode*> newUse(NodeAddr<InstrNode*> Owner,
837 MachineOperand &Op, uint16_t Flags = NodeAttrs::None);
838 NodeAddr<PhiUseNode*> newPhiUse(NodeAddr<PhiNode*> Owner,
839 RegisterRef RR, NodeAddr<BlockNode*> PredB,
840 uint16_t Flags = NodeAttrs::PhiRef);
841 NodeAddr<DefNode*> newDef(NodeAddr<InstrNode*> Owner,
842 MachineOperand &Op, uint16_t Flags = NodeAttrs::None);
843 NodeAddr<DefNode*> newDef(NodeAddr<InstrNode*> Owner,
844 RegisterRef RR, uint16_t Flags = NodeAttrs::PhiRef);
845 NodeAddr<PhiNode*> newPhi(NodeAddr<BlockNode*> Owner);
846 NodeAddr<StmtNode*> newStmt(NodeAddr<BlockNode*> Owner,
847 MachineInstr *MI);
848 NodeAddr<BlockNode*> newBlock(NodeAddr<FuncNode*> Owner,
849 MachineBasicBlock *BB);
850 NodeAddr<FuncNode*> newFunc(MachineFunction *MF);
851
852 template <typename Predicate>
853 std::pair<NodeAddr<RefNode*>,NodeAddr<RefNode*>>
854 locateNextRef(NodeAddr<InstrNode*> IA, NodeAddr<RefNode*> RA,
855 Predicate P) const;
856
857 typedef std::map<NodeId,RegisterSet> BlockRefsMap;
858
859 void buildStmt(NodeAddr<BlockNode*> BA, MachineInstr &In);
860 void buildBlockRefs(NodeAddr<BlockNode*> BA, BlockRefsMap &RefM);
861 void recordDefsForDF(BlockRefsMap &PhiM, BlockRefsMap &RefM,
862 NodeAddr<BlockNode*> BA);
863 void buildPhis(BlockRefsMap &PhiM, BlockRefsMap &RefM,
864 NodeAddr<BlockNode*> BA);
865 void removeUnusedPhis();
866
867 template <typename T> void linkRefUp(NodeAddr<InstrNode*> IA,
868 NodeAddr<T> TA, DefStack &DS);
869 void linkStmtRefs(DefStackMap &DefM, NodeAddr<StmtNode*> SA);
870 void linkBlockRefs(DefStackMap &DefM, NodeAddr<BlockNode*> BA);
871
Krzysztof Parzyszek69e670d52016-01-18 20:41:34 +0000872 void unlinkUseDF(NodeAddr<UseNode*> UA);
873 void unlinkDefDF(NodeAddr<DefNode*> DA);
874 void removeFromOwner(NodeAddr<RefNode*> RA) {
875 NodeAddr<InstrNode*> IA = RA.Addr->getOwner(*this);
876 IA.Addr->removeMember(RA, *this);
877 }
878
Krzysztof Parzyszek047149f2016-07-22 16:09:47 +0000879 NodeAddr<BlockNode*> findBlock(MachineBasicBlock *BB) {
880 return BlockNodes[BB];
881 }
882
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000883 TimerGroup TimeG;
884 NodeAddr<FuncNode*> Func;
885 NodeAllocator Memory;
Krzysztof Parzyszek047149f2016-07-22 16:09:47 +0000886 // Local map: MachineBasicBlock -> NodeAddr<BlockNode*>
887 std::map<MachineBasicBlock*,NodeAddr<BlockNode*>> BlockNodes;
Krzysztof Parzyszek29e93f32016-09-22 21:01:24 +0000888 // Lane mask map.
889 IndexedSet<LaneBitmask> LMMap;
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000890
891 MachineFunction &MF;
892 const TargetInstrInfo &TII;
893 const TargetRegisterInfo &TRI;
894 const MachineDominatorTree &MDT;
895 const MachineDominanceFrontier &MDF;
896 const RegisterAliasInfo &RAI;
897 const TargetOperandInfo &TOI;
898 }; // struct DataFlowGraph
899
900 template <typename Predicate>
901 NodeAddr<RefNode*> RefNode::getNextRef(RegisterRef RR, Predicate P,
902 bool NextOnly, const DataFlowGraph &G) {
903 // Get the "Next" reference in the circular list that references RR and
904 // satisfies predicate "Pred".
905 auto NA = G.addr<NodeBase*>(getNext());
906
907 while (NA.Addr != this) {
908 if (NA.Addr->getType() == NodeAttrs::Ref) {
909 NodeAddr<RefNode*> RA = NA;
910 if (RA.Addr->getRegRef() == RR && P(NA))
911 return NA;
912 if (NextOnly)
913 break;
914 NA = G.addr<NodeBase*>(NA.Addr->getNext());
915 } else {
916 // We've hit the beginning of the chain.
917 assert(NA.Addr->getType() == NodeAttrs::Code);
918 NodeAddr<CodeNode*> CA = NA;
919 NA = CA.Addr->getFirstMember(G);
920 }
921 }
922 // Return the equivalent of "nullptr" if such a node was not found.
923 return NodeAddr<RefNode*>();
924 }
925
926 template <typename Predicate>
927 NodeList CodeNode::members_if(Predicate P, const DataFlowGraph &G) const {
928 NodeList MM;
929 auto M = getFirstMember(G);
930 if (M.Id == 0)
931 return MM;
932
933 while (M.Addr != this) {
934 if (P(M))
935 MM.push_back(M);
936 M = G.addr<NodeBase*>(M.Addr->getNext());
937 }
938 return MM;
939 }
940
941
942 template <typename T> struct Print;
943 template <typename T>
944 raw_ostream &operator<< (raw_ostream &OS, const Print<T> &P);
945
946 template <typename T>
947 struct Print {
948 Print(const T &x, const DataFlowGraph &g) : Obj(x), G(g) {}
949 const T &Obj;
950 const DataFlowGraph &G;
951 };
952
953 template <typename T>
954 struct PrintNode : Print<NodeAddr<T>> {
955 PrintNode(const NodeAddr<T> &x, const DataFlowGraph &g)
956 : Print<NodeAddr<T>>(x, g) {}
957 };
958} // namespace rdf
Benjamin Kramer922efd72016-05-27 10:06:40 +0000959} // namespace llvm
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000960
961#endif // RDF_GRAPH_H