blob: a21ee2b914e257ca62178351e4c013259f3cd9df [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 Parzyszeka77fe4e2016-10-03 17:14:48 +0000227#include "llvm/ADT/BitVector.h"
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000228#include "llvm/Support/Allocator.h"
229#include "llvm/Support/Debug.h"
230#include "llvm/Support/raw_ostream.h"
231#include "llvm/Support/Timer.h"
Krzysztof Parzyszek29e93f32016-09-22 21:01:24 +0000232#include "llvm/Target/TargetRegisterInfo.h"
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000233
234#include <functional>
235#include <map>
236#include <set>
Krzysztof Parzyszek047149f2016-07-22 16:09:47 +0000237#include <unordered_map>
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000238#include <vector>
239
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +0000240// RDF uses uint32_t to refer to registers. This is to ensure that the type
241// size remains specific. In other places, registers are often stored using
242// unsigned.
243static_assert(sizeof(uint32_t) == sizeof(unsigned), "Those should be equal");
244
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000245namespace llvm {
246 class MachineBasicBlock;
247 class MachineFunction;
248 class MachineInstr;
249 class MachineOperand;
250 class MachineDominanceFrontier;
251 class MachineDominatorTree;
252 class TargetInstrInfo;
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000253
254namespace rdf {
255 typedef uint32_t NodeId;
256
Krzysztof Parzyszek29e93f32016-09-22 21:01:24 +0000257 struct DataFlowGraph;
258
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000259 struct NodeAttrs {
260 enum : uint16_t {
261 None = 0x0000, // Nothing
262
263 // Types: 2 bits
264 TypeMask = 0x0003,
265 Code = 0x0001, // 01, Container
266 Ref = 0x0002, // 10, Reference
267
268 // Kind: 3 bits
269 KindMask = 0x0007 << 2,
270 Def = 0x0001 << 2, // 001
271 Use = 0x0002 << 2, // 010
272 Phi = 0x0003 << 2, // 011
273 Stmt = 0x0004 << 2, // 100
274 Block = 0x0005 << 2, // 101
275 Func = 0x0006 << 2, // 110
276
Krzysztof Parzyszek586fc122016-09-27 18:24:33 +0000277 // Flags: 7 bits for now
278 FlagMask = 0x007F << 5,
279 Shadow = 0x0001 << 5, // 0000001, Has extra reaching defs.
280 Clobbering = 0x0002 << 5, // 0000010, Produces unspecified values.
281 PhiRef = 0x0004 << 5, // 0000100, Member of PhiNode.
282 Preserving = 0x0008 << 5, // 0001000, Def can keep original bits.
283 Fixed = 0x0010 << 5, // 0010000, Fixed register.
284 Undef = 0x0020 << 5, // 0100000, Has no pre-existing value.
285 Dead = 0x0040 << 5, // 1000000, Does not define a value.
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000286 };
287
288 static uint16_t type(uint16_t T) { return T & TypeMask; }
289 static uint16_t kind(uint16_t T) { return T & KindMask; }
290 static uint16_t flags(uint16_t T) { return T & FlagMask; }
291
292 static uint16_t set_type(uint16_t A, uint16_t T) {
293 return (A & ~TypeMask) | T;
294 }
295 static uint16_t set_kind(uint16_t A, uint16_t K) {
296 return (A & ~KindMask) | K;
297 }
298 static uint16_t set_flags(uint16_t A, uint16_t F) {
299 return (A & ~FlagMask) | F;
300 }
301
302 // Test if A contains B.
303 static bool contains(uint16_t A, uint16_t B) {
304 if (type(A) != Code)
305 return false;
306 uint16_t KB = kind(B);
307 switch (kind(A)) {
308 case Func:
309 return KB == Block;
310 case Block:
311 return KB == Phi || KB == Stmt;
312 case Phi:
313 case Stmt:
314 return type(B) == Ref;
315 }
316 return false;
317 }
318 };
319
Krzysztof Parzyszek55874cf2016-04-28 20:17:06 +0000320 struct BuildOptions {
321 enum : unsigned {
322 None = 0x00,
323 KeepDeadPhis = 0x01, // Do not remove dead phis during build.
324 };
325 };
326
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000327 template <typename T> struct NodeAddr {
328 NodeAddr() : Addr(nullptr), Id(0) {}
329 NodeAddr(T A, NodeId I) : Addr(A), Id(I) {}
330 NodeAddr(const NodeAddr&) = default;
331 NodeAddr &operator= (const NodeAddr&) = default;
332
333 bool operator== (const NodeAddr<T> &NA) const {
334 assert((Addr == NA.Addr) == (Id == NA.Id));
335 return Addr == NA.Addr;
336 }
337 bool operator!= (const NodeAddr<T> &NA) const {
338 return !operator==(NA);
339 }
340 // Type cast (casting constructor). The reason for having this class
341 // instead of std::pair.
342 template <typename S> NodeAddr(const NodeAddr<S> &NA)
343 : Addr(static_cast<T>(NA.Addr)), Id(NA.Id) {}
344
345 T Addr;
346 NodeId Id;
347 };
348
349 struct NodeBase;
350
351 // Fast memory allocation and translation between node id and node address.
352 // This is really the same idea as the one underlying the "bump pointer
353 // allocator", the difference being in the translation. A node id is
354 // composed of two components: the index of the block in which it was
355 // allocated, and the index within the block. With the default settings,
356 // where the number of nodes per block is 4096, the node id (minus 1) is:
357 //
358 // bit position: 11 0
359 // +----------------------------+--------------+
360 // | Index of the block |Index in block|
361 // +----------------------------+--------------+
362 //
363 // The actual node id is the above plus 1, to avoid creating a node id of 0.
364 //
365 // This method significantly improved the build time, compared to using maps
366 // (std::unordered_map or DenseMap) to translate between pointers and ids.
367 struct NodeAllocator {
368 // Amount of storage for a single node.
369 enum { NodeMemSize = 32 };
370 NodeAllocator(uint32_t NPB = 4096)
371 : NodesPerBlock(NPB), BitsPerIndex(Log2_32(NPB)),
372 IndexMask((1 << BitsPerIndex)-1), ActiveEnd(nullptr) {
373 assert(isPowerOf2_32(NPB));
374 }
375 NodeBase *ptr(NodeId N) const {
376 uint32_t N1 = N-1;
377 uint32_t BlockN = N1 >> BitsPerIndex;
378 uint32_t Offset = (N1 & IndexMask) * NodeMemSize;
379 return reinterpret_cast<NodeBase*>(Blocks[BlockN]+Offset);
380 }
381 NodeId id(const NodeBase *P) const;
382 NodeAddr<NodeBase*> New();
383 void clear();
384
385 private:
386 void startNewBlock();
387 bool needNewBlock();
388 uint32_t makeId(uint32_t Block, uint32_t Index) const {
389 // Add 1 to the id, to avoid the id of 0, which is treated as "null".
390 return ((Block << BitsPerIndex) | Index) + 1;
391 }
392
393 const uint32_t NodesPerBlock;
394 const uint32_t BitsPerIndex;
395 const uint32_t IndexMask;
396 char *ActiveEnd;
397 std::vector<char*> Blocks;
398 typedef BumpPtrAllocatorImpl<MallocAllocator, 65536> AllocatorTy;
399 AllocatorTy MemPool;
400 };
401
402 struct RegisterRef {
Krzysztof Parzyszek29e93f32016-09-22 21:01:24 +0000403 // For virtual registers, Reg and Sub have the usual meanings.
404 //
405 // Physical registers are assumed not to have any subregisters, and for
406 // them, Sub is the key of the LaneBitmask in the lane mask map in DFG.
407 // The case of Sub = 0 is treated as 'all lanes', i.e. lane mask of ~0.
408 // Use an key/map to access lane masks, since we only have uint32_t
409 // for it, and the LaneBitmask type can grow in the future.
410 //
411 // The case when Reg = 0 and Sub = 0 is reserved to mean "no register".
Krzysztof Parzyszekc51f2392016-09-22 20:56:39 +0000412 uint32_t Reg, Sub;
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000413
414 // No non-trivial constructors, since this will be a member of a union.
415 RegisterRef() = default;
416 RegisterRef(const RegisterRef &RR) = default;
417 RegisterRef &operator= (const RegisterRef &RR) = default;
418 bool operator== (const RegisterRef &RR) const {
419 return Reg == RR.Reg && Sub == RR.Sub;
420 }
421 bool operator!= (const RegisterRef &RR) const {
422 return !operator==(RR);
423 }
424 bool operator< (const RegisterRef &RR) const {
425 return Reg < RR.Reg || (Reg == RR.Reg && Sub < RR.Sub);
426 }
427 };
428 typedef std::set<RegisterRef> RegisterSet;
429
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000430 struct TargetOperandInfo {
431 TargetOperandInfo(const TargetInstrInfo &tii) : TII(tii) {}
432 virtual ~TargetOperandInfo() {}
433 virtual bool isPreserving(const MachineInstr &In, unsigned OpNum) const;
434 virtual bool isClobbering(const MachineInstr &In, unsigned OpNum) const;
435 virtual bool isFixedReg(const MachineInstr &In, unsigned OpNum) const;
436
437 const TargetInstrInfo &TII;
438 };
439
Krzysztof Parzyszek29e93f32016-09-22 21:01:24 +0000440 // Template class for a map translating uint32_t into arbitrary types.
441 // The map will act like an indexed set: upon insertion of a new object,
442 // it will automatically assign a new index to it. Index of 0 is treated
443 // as invalid and is never allocated.
444 template <typename T, unsigned N = 32>
445 struct IndexedSet {
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +0000446 IndexedSet() : Map() { Map.reserve(N); }
Krzysztof Parzyszek29e93f32016-09-22 21:01:24 +0000447 const T get(uint32_t Idx) const {
448 // Index Idx corresponds to Map[Idx-1].
449 assert(Idx != 0 && !Map.empty() && Idx-1 < Map.size());
450 return Map[Idx-1];
451 }
452 uint32_t insert(T Val) {
453 // Linear search.
454 auto F = find(Map, Val);
455 if (F != Map.end())
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +0000456 return F - Map.begin();
Krzysztof Parzyszek29e93f32016-09-22 21:01:24 +0000457 Map.push_back(Val);
458 return Map.size(); // Return actual_index + 1.
459 }
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000460
Krzysztof Parzyszek29e93f32016-09-22 21:01:24 +0000461 private:
462 std::vector<T> Map;
463 };
464
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +0000465 struct LaneMaskIndex : private IndexedSet<LaneBitmask> {
466 LaneBitmask getLaneMaskForIndex(uint32_t K) const {
467 return K == 0 ? ~LaneBitmask(0) : get(K);
468 }
469 uint32_t getIndexForLaneMask(LaneBitmask LM) {
470 assert(LM != LaneBitmask(0));
471 return LM == ~LaneBitmask(0) ? 0 : insert(LM);
472 }
473 };
474
475 struct RegisterAggr {
476 typedef std::pair<uint32_t,LaneBitmask> ValueType;
477
478 RegisterAggr(const LaneMaskIndex &m, const TargetRegisterInfo &tri)
479 : Masks(), ExpAliasUnits(tri.getNumRegUnits()), CheckUnits(false),
480 LMI(m), TRI(tri) {}
481 RegisterAggr(const RegisterAggr &RG)
482 : Masks(RG.Masks), ExpAliasUnits(RG.ExpAliasUnits),
483 CheckUnits(RG.CheckUnits), LMI(RG.LMI), TRI(RG.TRI) {}
484
485 bool empty() const { return Masks.empty(); }
486 bool hasAliasOf(RegisterRef RR) const;
487 bool hasCoverOf(RegisterRef RR) const;
488 static bool isCoverOf(RegisterRef RefA, RegisterRef RefB,
489 const LaneMaskIndex &LMI, const TargetRegisterInfo &TRI) {
490 return RegisterAggr(LMI, TRI).insert(RefA).hasCoverOf(RefB);
491 }
492
493 RegisterAggr &insert(RegisterRef RR);
494 RegisterAggr &insert(const RegisterAggr &RG);
495 RegisterAggr &clear(RegisterRef RR);
496
497 void print(raw_ostream &OS) const;
498
499 private:
500 typedef std::unordered_map<ValueType::first_type,
501 ValueType::second_type> MapType;
502 MapType Masks;
503 BitVector ExpAliasUnits; // Register units for explicit aliases.
504 bool CheckUnits;
505 const LaneMaskIndex &LMI;
506 const TargetRegisterInfo &TRI;
507
508 uint32_t getLargestSuperReg(uint32_t Reg) const;
509 void setMaskRaw(uint32_t Reg, LaneBitmask LM);
510 LaneBitmask composeMaskForReg(uint32_t Reg, LaneBitmask LM,
511 uint32_t SuperR) const;
512 };
513
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000514
515 struct NodeBase {
516 public:
517 // Make sure this is a POD.
518 NodeBase() = default;
519 uint16_t getType() const { return NodeAttrs::type(Attrs); }
520 uint16_t getKind() const { return NodeAttrs::kind(Attrs); }
521 uint16_t getFlags() const { return NodeAttrs::flags(Attrs); }
522 NodeId getNext() const { return Next; }
523
524 uint16_t getAttrs() const { return Attrs; }
525 void setAttrs(uint16_t A) { Attrs = A; }
526 void setFlags(uint16_t F) { setAttrs(NodeAttrs::set_flags(getAttrs(), F)); }
527
528 // Insert node NA after "this" in the circular chain.
529 void append(NodeAddr<NodeBase*> NA);
530 // Initialize all members to 0.
531 void init() { memset(this, 0, sizeof *this); }
532 void setNext(NodeId N) { Next = N; }
533
534 protected:
535 uint16_t Attrs;
536 uint16_t Reserved;
537 NodeId Next; // Id of the next node in the circular chain.
538 // Definitions of nested types. Using anonymous nested structs would make
539 // this class definition clearer, but unnamed structs are not a part of
540 // the standard.
541 struct Def_struct {
542 NodeId DD, DU; // Ids of the first reached def and use.
543 };
544 struct PhiU_struct {
545 NodeId PredB; // Id of the predecessor block for a phi use.
546 };
547 struct Code_struct {
548 void *CP; // Pointer to the actual code.
549 NodeId FirstM, LastM; // Id of the first member and last.
550 };
551 struct Ref_struct {
552 NodeId RD, Sib; // Ids of the reaching def and the sibling.
553 union {
554 Def_struct Def;
555 PhiU_struct PhiU;
556 };
557 union {
558 MachineOperand *Op; // Non-phi refs point to a machine operand.
559 RegisterRef RR; // Phi refs store register info directly.
560 };
561 };
562
563 // The actual payload.
564 union {
565 Ref_struct Ref;
566 Code_struct Code;
567 };
568 };
569 // The allocator allocates chunks of 32 bytes for each node. The fact that
570 // each node takes 32 bytes in memory is used for fast translation between
571 // the node id and the node address.
572 static_assert(sizeof(NodeBase) <= NodeAllocator::NodeMemSize,
573 "NodeBase must be at most NodeAllocator::NodeMemSize bytes");
574
575 typedef std::vector<NodeAddr<NodeBase*>> NodeList;
576 typedef std::set<NodeId> NodeSet;
577
578 struct RefNode : public NodeBase {
579 RefNode() = default;
580 RegisterRef getRegRef() const;
581 MachineOperand &getOp() {
582 assert(!(getFlags() & NodeAttrs::PhiRef));
583 return *Ref.Op;
584 }
585 void setRegRef(RegisterRef RR);
586 void setRegRef(MachineOperand *Op);
587 NodeId getReachingDef() const {
588 return Ref.RD;
589 }
590 void setReachingDef(NodeId RD) {
591 Ref.RD = RD;
592 }
593 NodeId getSibling() const {
594 return Ref.Sib;
595 }
596 void setSibling(NodeId Sib) {
597 Ref.Sib = Sib;
598 }
599 bool isUse() const {
600 assert(getType() == NodeAttrs::Ref);
601 return getKind() == NodeAttrs::Use;
602 }
603 bool isDef() const {
604 assert(getType() == NodeAttrs::Ref);
605 return getKind() == NodeAttrs::Def;
606 }
607
608 template <typename Predicate>
609 NodeAddr<RefNode*> getNextRef(RegisterRef RR, Predicate P, bool NextOnly,
610 const DataFlowGraph &G);
611 NodeAddr<NodeBase*> getOwner(const DataFlowGraph &G);
612 };
613
614 struct DefNode : public RefNode {
615 NodeId getReachedDef() const {
616 return Ref.Def.DD;
617 }
618 void setReachedDef(NodeId D) {
619 Ref.Def.DD = D;
620 }
621 NodeId getReachedUse() const {
622 return Ref.Def.DU;
623 }
624 void setReachedUse(NodeId U) {
625 Ref.Def.DU = U;
626 }
627
628 void linkToDef(NodeId Self, NodeAddr<DefNode*> DA);
629 };
630
631 struct UseNode : public RefNode {
632 void linkToDef(NodeId Self, NodeAddr<DefNode*> DA);
633 };
634
635 struct PhiUseNode : public UseNode {
636 NodeId getPredecessor() const {
637 assert(getFlags() & NodeAttrs::PhiRef);
638 return Ref.PhiU.PredB;
639 }
640 void setPredecessor(NodeId B) {
641 assert(getFlags() & NodeAttrs::PhiRef);
642 Ref.PhiU.PredB = B;
643 }
644 };
645
646 struct CodeNode : public NodeBase {
647 template <typename T> T getCode() const {
648 return static_cast<T>(Code.CP);
649 }
650 void setCode(void *C) {
651 Code.CP = C;
652 }
653
654 NodeAddr<NodeBase*> getFirstMember(const DataFlowGraph &G) const;
655 NodeAddr<NodeBase*> getLastMember(const DataFlowGraph &G) const;
656 void addMember(NodeAddr<NodeBase*> NA, const DataFlowGraph &G);
657 void addMemberAfter(NodeAddr<NodeBase*> MA, NodeAddr<NodeBase*> NA,
658 const DataFlowGraph &G);
659 void removeMember(NodeAddr<NodeBase*> NA, const DataFlowGraph &G);
660
661 NodeList members(const DataFlowGraph &G) const;
662 template <typename Predicate>
663 NodeList members_if(Predicate P, const DataFlowGraph &G) const;
664 };
665
666 struct InstrNode : public CodeNode {
667 NodeAddr<NodeBase*> getOwner(const DataFlowGraph &G);
668 };
669
670 struct PhiNode : public InstrNode {
671 MachineInstr *getCode() const {
672 return nullptr;
673 }
674 };
675
676 struct StmtNode : public InstrNode {
677 MachineInstr *getCode() const {
678 return CodeNode::getCode<MachineInstr*>();
679 }
680 };
681
682 struct BlockNode : public CodeNode {
683 MachineBasicBlock *getCode() const {
684 return CodeNode::getCode<MachineBasicBlock*>();
685 }
686 void addPhi(NodeAddr<PhiNode*> PA, const DataFlowGraph &G);
687 };
688
689 struct FuncNode : public CodeNode {
690 MachineFunction *getCode() const {
691 return CodeNode::getCode<MachineFunction*>();
692 }
693 NodeAddr<BlockNode*> findBlock(const MachineBasicBlock *BB,
694 const DataFlowGraph &G) const;
695 NodeAddr<BlockNode*> getEntryBlock(const DataFlowGraph &G);
696 };
697
698 struct DataFlowGraph {
699 DataFlowGraph(MachineFunction &mf, const TargetInstrInfo &tii,
700 const TargetRegisterInfo &tri, const MachineDominatorTree &mdt,
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +0000701 const MachineDominanceFrontier &mdf, const TargetOperandInfo &toi);
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000702
703 NodeBase *ptr(NodeId N) const;
704 template <typename T> T ptr(NodeId N) const {
705 return static_cast<T>(ptr(N));
706 }
707 NodeId id(const NodeBase *P) const;
708
709 template <typename T> NodeAddr<T> addr(NodeId N) const {
710 return { ptr<T>(N), N };
711 }
712
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +0000713 NodeAddr<FuncNode*> getFunc() const { return Func; }
714 MachineFunction &getMF() const { return MF; }
715 LaneMaskIndex &getLMI() { return LMI; }
716 const LaneMaskIndex &getLMI() const { return LMI; }
717 const TargetInstrInfo &getTII() const { return TII; }
718 const TargetRegisterInfo &getTRI() const { return TRI; }
719 const MachineDominatorTree &getDT() const { return MDT; }
720 const MachineDominanceFrontier &getDF() const { return MDF; }
Krzysztof Parzyszek29e93f32016-09-22 21:01:24 +0000721
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000722 struct DefStack {
723 DefStack() = default;
724 bool empty() const { return Stack.empty() || top() == bottom(); }
725 private:
726 typedef NodeAddr<DefNode*> value_type;
727 struct Iterator {
728 typedef DefStack::value_type value_type;
729 Iterator &up() { Pos = DS.nextUp(Pos); return *this; }
730 Iterator &down() { Pos = DS.nextDown(Pos); return *this; }
731 value_type operator*() const {
732 assert(Pos >= 1);
733 return DS.Stack[Pos-1];
734 }
735 const value_type *operator->() const {
736 assert(Pos >= 1);
737 return &DS.Stack[Pos-1];
738 }
739 bool operator==(const Iterator &It) const { return Pos == It.Pos; }
740 bool operator!=(const Iterator &It) const { return Pos != It.Pos; }
741 private:
742 Iterator(const DefStack &S, bool Top);
743 // Pos-1 is the index in the StorageType object that corresponds to
744 // the top of the DefStack.
745 const DefStack &DS;
746 unsigned Pos;
747 friend struct DefStack;
748 };
749 public:
750 typedef Iterator iterator;
751 iterator top() const { return Iterator(*this, true); }
752 iterator bottom() const { return Iterator(*this, false); }
753 unsigned size() const;
754
755 void push(NodeAddr<DefNode*> DA) { Stack.push_back(DA); }
756 void pop();
757 void start_block(NodeId N);
758 void clear_block(NodeId N);
759 private:
760 friend struct Iterator;
761 typedef std::vector<value_type> StorageType;
762 bool isDelimiter(const StorageType::value_type &P, NodeId N = 0) const {
763 return (P.Addr == nullptr) && (N == 0 || P.Id == N);
764 }
765 unsigned nextUp(unsigned P) const;
766 unsigned nextDown(unsigned P) const;
767 StorageType Stack;
768 };
769
Krzysztof Parzyszek047149f2016-07-22 16:09:47 +0000770 // Make this std::unordered_map for speed of accessing elements.
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +0000771 // Map: Register (physical or virtual) -> DefStack
772 typedef std::unordered_map<uint32_t,DefStack> DefStackMap;
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000773
Krzysztof Parzyszek55874cf2016-04-28 20:17:06 +0000774 void build(unsigned Options = BuildOptions::None);
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000775 void pushDefs(NodeAddr<InstrNode*> IA, DefStackMap &DM);
776 void markBlock(NodeId B, DefStackMap &DefM);
777 void releaseBlock(NodeId B, DefStackMap &DefM);
778
779 NodeAddr<RefNode*> getNextRelated(NodeAddr<InstrNode*> IA,
780 NodeAddr<RefNode*> RA) const;
781 NodeAddr<RefNode*> getNextImp(NodeAddr<InstrNode*> IA,
782 NodeAddr<RefNode*> RA, bool Create);
783 NodeAddr<RefNode*> getNextImp(NodeAddr<InstrNode*> IA,
784 NodeAddr<RefNode*> RA) const;
785 NodeAddr<RefNode*> getNextShadow(NodeAddr<InstrNode*> IA,
786 NodeAddr<RefNode*> RA, bool Create);
787 NodeAddr<RefNode*> getNextShadow(NodeAddr<InstrNode*> IA,
788 NodeAddr<RefNode*> RA) const;
789
790 NodeList getRelatedRefs(NodeAddr<InstrNode*> IA,
791 NodeAddr<RefNode*> RA) const;
792
Krzysztof Parzyszek69e670d52016-01-18 20:41:34 +0000793 void unlinkUse(NodeAddr<UseNode*> UA, bool RemoveFromOwner) {
794 unlinkUseDF(UA);
795 if (RemoveFromOwner)
796 removeFromOwner(UA);
797 }
798 void unlinkDef(NodeAddr<DefNode*> DA, bool RemoveFromOwner) {
799 unlinkDefDF(DA);
800 if (RemoveFromOwner)
801 removeFromOwner(DA);
802 }
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000803
804 // Some useful filters.
805 template <uint16_t Kind>
806 static bool IsRef(const NodeAddr<NodeBase*> BA) {
807 return BA.Addr->getType() == NodeAttrs::Ref &&
808 BA.Addr->getKind() == Kind;
809 }
810 template <uint16_t Kind>
811 static bool IsCode(const NodeAddr<NodeBase*> BA) {
812 return BA.Addr->getType() == NodeAttrs::Code &&
813 BA.Addr->getKind() == Kind;
814 }
815 static bool IsDef(const NodeAddr<NodeBase*> BA) {
816 return BA.Addr->getType() == NodeAttrs::Ref &&
817 BA.Addr->getKind() == NodeAttrs::Def;
818 }
819 static bool IsUse(const NodeAddr<NodeBase*> BA) {
820 return BA.Addr->getType() == NodeAttrs::Ref &&
821 BA.Addr->getKind() == NodeAttrs::Use;
822 }
823 static bool IsPhi(const NodeAddr<NodeBase*> BA) {
824 return BA.Addr->getType() == NodeAttrs::Code &&
825 BA.Addr->getKind() == NodeAttrs::Phi;
826 }
Krzysztof Parzyszek1ff99522016-09-07 20:10:56 +0000827 static bool IsPreservingDef(const NodeAddr<DefNode*> DA) {
828 uint16_t Flags = DA.Addr->getFlags();
829 return (Flags & NodeAttrs::Preserving) && !(Flags & NodeAttrs::Undef);
830 }
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000831
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +0000832 // Register aliasing.
833 bool alias(RegisterRef RA, RegisterRef RB) const;
834
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000835 private:
836 void reset();
837
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +0000838 RegisterSet getAliasSet(uint32_t Reg) const;
839 RegisterSet getLandingPadLiveIns() const;
Krzysztof Parzyszek1d322202016-09-27 18:18:44 +0000840
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000841 NodeAddr<NodeBase*> newNode(uint16_t Attrs);
842 NodeAddr<NodeBase*> cloneNode(const NodeAddr<NodeBase*> B);
843 NodeAddr<UseNode*> newUse(NodeAddr<InstrNode*> Owner,
844 MachineOperand &Op, uint16_t Flags = NodeAttrs::None);
845 NodeAddr<PhiUseNode*> newPhiUse(NodeAddr<PhiNode*> Owner,
846 RegisterRef RR, NodeAddr<BlockNode*> PredB,
847 uint16_t Flags = NodeAttrs::PhiRef);
848 NodeAddr<DefNode*> newDef(NodeAddr<InstrNode*> Owner,
849 MachineOperand &Op, uint16_t Flags = NodeAttrs::None);
850 NodeAddr<DefNode*> newDef(NodeAddr<InstrNode*> Owner,
851 RegisterRef RR, uint16_t Flags = NodeAttrs::PhiRef);
852 NodeAddr<PhiNode*> newPhi(NodeAddr<BlockNode*> Owner);
853 NodeAddr<StmtNode*> newStmt(NodeAddr<BlockNode*> Owner,
854 MachineInstr *MI);
855 NodeAddr<BlockNode*> newBlock(NodeAddr<FuncNode*> Owner,
856 MachineBasicBlock *BB);
857 NodeAddr<FuncNode*> newFunc(MachineFunction *MF);
858
859 template <typename Predicate>
860 std::pair<NodeAddr<RefNode*>,NodeAddr<RefNode*>>
861 locateNextRef(NodeAddr<InstrNode*> IA, NodeAddr<RefNode*> RA,
862 Predicate P) const;
863
864 typedef std::map<NodeId,RegisterSet> BlockRefsMap;
865
866 void buildStmt(NodeAddr<BlockNode*> BA, MachineInstr &In);
867 void buildBlockRefs(NodeAddr<BlockNode*> BA, BlockRefsMap &RefM);
868 void recordDefsForDF(BlockRefsMap &PhiM, BlockRefsMap &RefM,
869 NodeAddr<BlockNode*> BA);
870 void buildPhis(BlockRefsMap &PhiM, BlockRefsMap &RefM,
871 NodeAddr<BlockNode*> BA);
872 void removeUnusedPhis();
873
874 template <typename T> void linkRefUp(NodeAddr<InstrNode*> IA,
875 NodeAddr<T> TA, DefStack &DS);
876 void linkStmtRefs(DefStackMap &DefM, NodeAddr<StmtNode*> SA);
877 void linkBlockRefs(DefStackMap &DefM, NodeAddr<BlockNode*> BA);
878
Krzysztof Parzyszek69e670d52016-01-18 20:41:34 +0000879 void unlinkUseDF(NodeAddr<UseNode*> UA);
880 void unlinkDefDF(NodeAddr<DefNode*> DA);
881 void removeFromOwner(NodeAddr<RefNode*> RA) {
882 NodeAddr<InstrNode*> IA = RA.Addr->getOwner(*this);
883 IA.Addr->removeMember(RA, *this);
884 }
885
Krzysztof Parzyszek047149f2016-07-22 16:09:47 +0000886 NodeAddr<BlockNode*> findBlock(MachineBasicBlock *BB) {
887 return BlockNodes[BB];
888 }
889
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000890 TimerGroup TimeG;
891 NodeAddr<FuncNode*> Func;
892 NodeAllocator Memory;
Krzysztof Parzyszek047149f2016-07-22 16:09:47 +0000893 // Local map: MachineBasicBlock -> NodeAddr<BlockNode*>
894 std::map<MachineBasicBlock*,NodeAddr<BlockNode*>> BlockNodes;
Krzysztof Parzyszek29e93f32016-09-22 21:01:24 +0000895 // Lane mask map.
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +0000896 LaneMaskIndex LMI;
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000897
898 MachineFunction &MF;
899 const TargetInstrInfo &TII;
900 const TargetRegisterInfo &TRI;
901 const MachineDominatorTree &MDT;
902 const MachineDominanceFrontier &MDF;
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000903 const TargetOperandInfo &TOI;
904 }; // struct DataFlowGraph
905
906 template <typename Predicate>
907 NodeAddr<RefNode*> RefNode::getNextRef(RegisterRef RR, Predicate P,
908 bool NextOnly, const DataFlowGraph &G) {
909 // Get the "Next" reference in the circular list that references RR and
910 // satisfies predicate "Pred".
911 auto NA = G.addr<NodeBase*>(getNext());
912
913 while (NA.Addr != this) {
914 if (NA.Addr->getType() == NodeAttrs::Ref) {
915 NodeAddr<RefNode*> RA = NA;
916 if (RA.Addr->getRegRef() == RR && P(NA))
917 return NA;
918 if (NextOnly)
919 break;
920 NA = G.addr<NodeBase*>(NA.Addr->getNext());
921 } else {
922 // We've hit the beginning of the chain.
923 assert(NA.Addr->getType() == NodeAttrs::Code);
924 NodeAddr<CodeNode*> CA = NA;
925 NA = CA.Addr->getFirstMember(G);
926 }
927 }
928 // Return the equivalent of "nullptr" if such a node was not found.
929 return NodeAddr<RefNode*>();
930 }
931
932 template <typename Predicate>
933 NodeList CodeNode::members_if(Predicate P, const DataFlowGraph &G) const {
934 NodeList MM;
935 auto M = getFirstMember(G);
936 if (M.Id == 0)
937 return MM;
938
939 while (M.Addr != this) {
940 if (P(M))
941 MM.push_back(M);
942 M = G.addr<NodeBase*>(M.Addr->getNext());
943 }
944 return MM;
945 }
946
947
948 template <typename T> struct Print;
949 template <typename T>
950 raw_ostream &operator<< (raw_ostream &OS, const Print<T> &P);
951
952 template <typename T>
953 struct Print {
954 Print(const T &x, const DataFlowGraph &g) : Obj(x), G(g) {}
955 const T &Obj;
956 const DataFlowGraph &G;
957 };
958
959 template <typename T>
960 struct PrintNode : Print<NodeAddr<T>> {
961 PrintNode(const NodeAddr<T> &x, const DataFlowGraph &g)
962 : Print<NodeAddr<T>>(x, g) {}
963 };
964} // namespace rdf
Benjamin Kramer922efd72016-05-27 10:06:40 +0000965} // namespace llvm
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000966
967#endif // RDF_GRAPH_H