blob: 1257d521b13945982be3ce28dcb55c8a180fdfcc [file] [log] [blame]
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +00001//===--- RDFLiveness.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// Computation of the liveness information from the data-flow graph.
11//
12// The main functionality of this code is to compute block live-in
13// information. With the live-in information in place, the placement
14// of kill flags can also be recalculated.
15//
16// The block live-in calculation is based on the ideas from the following
17// publication:
18//
19// Dibyendu Das, Ramakrishna Upadrasta, Benoit Dupont de Dinechin.
20// "Efficient Liveness Computation Using Merge Sets and DJ-Graphs."
21// ACM Transactions on Architecture and Code Optimization, Association for
22// Computing Machinery, 2012, ACM TACO Special Issue on "High-Performance
23// and Embedded Architectures and Compilers", 8 (4),
24// <10.1145/2086696.2086706>. <hal-00647369>
25//
26#include "RDFGraph.h"
27#include "RDFLiveness.h"
28#include "llvm/ADT/SetVector.h"
29#include "llvm/CodeGen/MachineBasicBlock.h"
30#include "llvm/CodeGen/MachineDominanceFrontier.h"
31#include "llvm/CodeGen/MachineDominators.h"
32#include "llvm/CodeGen/MachineFunction.h"
33#include "llvm/CodeGen/MachineRegisterInfo.h"
34#include "llvm/Target/TargetRegisterInfo.h"
35
36using namespace llvm;
37using namespace rdf;
38
Benjamin Kramer922efd72016-05-27 10:06:40 +000039namespace llvm {
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +000040namespace rdf {
41 template<>
42 raw_ostream &operator<< (raw_ostream &OS, const Print<Liveness::RefMap> &P) {
43 OS << '{';
44 for (auto I : P.Obj) {
45 OS << ' ' << Print<RegisterRef>(I.first, P.G) << '{';
46 for (auto J = I.second.begin(), E = I.second.end(); J != E; ) {
47 OS << Print<NodeId>(*J, P.G);
48 if (++J != E)
49 OS << ',';
50 }
51 OS << '}';
52 }
53 OS << " }";
54 return OS;
55 }
Benjamin Kramer922efd72016-05-27 10:06:40 +000056} // namespace rdf
57} // namespace llvm
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +000058
59// The order in the returned sequence is the order of reaching defs in the
60// upward traversal: the first def is the closest to the given reference RefA,
61// the next one is further up, and so on.
62// The list ends at a reaching phi def, or when the reference from RefA is
63// covered by the defs in the list (see FullChain).
64// This function provides two modes of operation:
65// (1) Returning the sequence of reaching defs for a particular reference
66// node. This sequence will terminate at the first phi node [1].
67// (2) Returning a partial sequence of reaching defs, where the final goal
68// is to traverse past phi nodes to the actual defs arising from the code
69// itself.
70// In mode (2), the register reference for which the search was started
71// may be different from the reference node RefA, for which this call was
72// made, hence the argument RefRR, which holds the original register.
73// Also, some definitions may have already been encountered in a previous
74// call that will influence register covering. The register references
75// already defined are passed in through DefRRs.
76// In mode (1), the "continuation" considerations do not apply, and the
77// RefRR is the same as the register in RefA, and the set DefRRs is empty.
78//
79// [1] It is possible for multiple phi nodes to be included in the returned
80// sequence:
81// SubA = phi ...
82// SubB = phi ...
83// ... = SuperAB(rdef:SubA), SuperAB"(rdef:SubB)
84// However, these phi nodes are independent from one another in terms of
85// the data-flow.
86
87NodeList Liveness::getAllReachingDefs(RegisterRef RefRR,
88 NodeAddr<RefNode*> RefA, bool FullChain, const RegisterSet &DefRRs) {
89 SetVector<NodeId> DefQ;
90 SetVector<NodeId> Owners;
91
92 // The initial queue should not have reaching defs for shadows. The
93 // whole point of a shadow is that it will have a reaching def that
94 // is not aliased to the reaching defs of the related shadows.
95 NodeId Start = RefA.Id;
96 auto SNA = DFG.addr<RefNode*>(Start);
97 if (NodeId RD = SNA.Addr->getReachingDef())
98 DefQ.insert(RD);
99
100 // Collect all the reaching defs, going up until a phi node is encountered,
101 // or there are no more reaching defs. From this set, the actual set of
102 // reaching defs will be selected.
103 // The traversal upwards must go on until a covering def is encountered.
104 // It is possible that a collection of non-covering (individually) defs
105 // will be sufficient, but keep going until a covering one is found.
106 for (unsigned i = 0; i < DefQ.size(); ++i) {
107 auto TA = DFG.addr<DefNode*>(DefQ[i]);
108 if (TA.Addr->getFlags() & NodeAttrs::PhiRef)
109 continue;
110 // Stop at the covering/overwriting def of the initial register reference.
111 RegisterRef RR = TA.Addr->getRegRef();
Krzysztof Parzyszek1ff99522016-09-07 20:10:56 +0000112 if (RAI.covers(RR, RefRR))
113 if (!DFG.IsPreservingDef(TA))
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +0000114 continue;
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +0000115 // Get the next level of reaching defs. This will include multiple
116 // reaching defs for shadows.
117 for (auto S : DFG.getRelatedRefs(TA.Addr->getOwner(DFG), TA))
118 if (auto RD = NodeAddr<RefNode*>(S).Addr->getReachingDef())
119 DefQ.insert(RD);
120 }
121
122 // Remove all non-phi defs that are not aliased to RefRR, and collect
123 // the owners of the remaining defs.
124 SetVector<NodeId> Defs;
125 for (auto N : DefQ) {
126 auto TA = DFG.addr<DefNode*>(N);
127 bool IsPhi = TA.Addr->getFlags() & NodeAttrs::PhiRef;
128 if (!IsPhi && !RAI.alias(RefRR, TA.Addr->getRegRef()))
129 continue;
130 Defs.insert(TA.Id);
131 Owners.insert(TA.Addr->getOwner(DFG).Id);
132 }
133
134 // Return the MachineBasicBlock containing a given instruction.
135 auto Block = [this] (NodeAddr<InstrNode*> IA) -> MachineBasicBlock* {
136 if (IA.Addr->getKind() == NodeAttrs::Stmt)
137 return NodeAddr<StmtNode*>(IA).Addr->getCode()->getParent();
138 assert(IA.Addr->getKind() == NodeAttrs::Phi);
139 NodeAddr<PhiNode*> PA = IA;
140 NodeAddr<BlockNode*> BA = PA.Addr->getOwner(DFG);
141 return BA.Addr->getCode();
142 };
143 // Less(A,B) iff instruction A is further down in the dominator tree than B.
144 auto Less = [&Block,this] (NodeId A, NodeId B) -> bool {
145 if (A == B)
146 return false;
147 auto OA = DFG.addr<InstrNode*>(A), OB = DFG.addr<InstrNode*>(B);
148 MachineBasicBlock *BA = Block(OA), *BB = Block(OB);
149 if (BA != BB)
150 return MDT.dominates(BB, BA);
151 // They are in the same block.
152 bool StmtA = OA.Addr->getKind() == NodeAttrs::Stmt;
153 bool StmtB = OB.Addr->getKind() == NodeAttrs::Stmt;
154 if (StmtA) {
155 if (!StmtB) // OB is a phi and phis dominate statements.
156 return true;
157 auto CA = NodeAddr<StmtNode*>(OA).Addr->getCode();
158 auto CB = NodeAddr<StmtNode*>(OB).Addr->getCode();
159 // The order must be linear, so tie-break such equalities.
160 if (CA == CB)
161 return A < B;
162 return MDT.dominates(CB, CA);
163 } else {
164 // OA is a phi.
165 if (StmtB)
166 return false;
167 // Both are phis. There is no ordering between phis (in terms of
168 // the data-flow), so tie-break this via node id comparison.
169 return A < B;
170 }
171 };
172
173 std::vector<NodeId> Tmp(Owners.begin(), Owners.end());
174 std::sort(Tmp.begin(), Tmp.end(), Less);
175
176 // The vector is a list of instructions, so that defs coming from
177 // the same instruction don't need to be artificially ordered.
178 // Then, when computing the initial segment, and iterating over an
179 // instruction, pick the defs that contribute to the covering (i.e. is
180 // not covered by previously added defs). Check the defs individually,
181 // i.e. first check each def if is covered or not (without adding them
182 // to the tracking set), and then add all the selected ones.
183
184 // The reason for this is this example:
185 // *d1<A>, *d2<B>, ... Assume A and B are aliased (can happen in phi nodes).
186 // *d3<C> If A \incl BuC, and B \incl AuC, then *d2 would be
187 // covered if we added A first, and A would be covered
188 // if we added B first.
189
190 NodeList RDefs;
191 RegisterSet RRs = DefRRs;
192
193 auto DefInSet = [&Defs] (NodeAddr<RefNode*> TA) -> bool {
194 return TA.Addr->getKind() == NodeAttrs::Def &&
195 Defs.count(TA.Id);
196 };
197 for (auto T : Tmp) {
198 if (!FullChain && RAI.covers(RRs, RefRR))
199 break;
200 auto TA = DFG.addr<InstrNode*>(T);
201 bool IsPhi = DFG.IsCode<NodeAttrs::Phi>(TA);
202 NodeList Ds;
203 for (NodeAddr<DefNode*> DA : TA.Addr->members_if(DefInSet, DFG)) {
204 auto QR = DA.Addr->getRegRef();
205 // Add phi defs even if they are covered by subsequent defs. This is
206 // for cases where the reached use is not covered by any of the defs
207 // encountered so far: the phi def is needed to expose the liveness
208 // of that use to the entry of the block.
209 // Example:
210 // phi d1<R3>(,d2,), ... Phi def d1 is covered by d2.
211 // d2<R3>(d1,,u3), ...
212 // ..., u3<D1>(d2) This use needs to be live on entry.
213 if (FullChain || IsPhi || !RAI.covers(RRs, QR))
214 Ds.push_back(DA);
215 }
216 RDefs.insert(RDefs.end(), Ds.begin(), Ds.end());
217 for (NodeAddr<DefNode*> DA : Ds) {
218 // When collecting a full chain of definitions, do not consider phi
219 // defs to actually define a register.
220 uint16_t Flags = DA.Addr->getFlags();
221 if (!FullChain || !(Flags & NodeAttrs::PhiRef))
Krzysztof Parzyszek1ff99522016-09-07 20:10:56 +0000222 if (!(Flags & NodeAttrs::Preserving)) // Don't care about Undef here.
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +0000223 RRs.insert(DA.Addr->getRegRef());
224 }
225 }
226
227 return RDefs;
228}
229
230
231static const RegisterSet NoRegs;
232
233NodeList Liveness::getAllReachingDefs(NodeAddr<RefNode*> RefA) {
234 return getAllReachingDefs(RefA.Addr->getRegRef(), RefA, false, NoRegs);
235}
236
237
Krzysztof Parzyszekf5cbac92016-04-29 15:49:13 +0000238NodeSet Liveness::getAllReachingDefsRec(RegisterRef RefRR,
239 NodeAddr<RefNode*> RefA, NodeSet &Visited, const NodeSet &Defs) {
240 // Collect all defined registers. Do not consider phis to be defining
241 // anything, only collect "real" definitions.
242 RegisterSet DefRRs;
243 for (const auto D : Defs) {
244 const auto DA = DFG.addr<const DefNode*>(D);
245 if (!(DA.Addr->getFlags() & NodeAttrs::PhiRef))
246 DefRRs.insert(DA.Addr->getRegRef());
247 }
248
249 auto RDs = getAllReachingDefs(RefRR, RefA, true, DefRRs);
250 if (RDs.empty())
251 return Defs;
252
253 // Make a copy of the preexisting definitions and add the newly found ones.
254 NodeSet TmpDefs = Defs;
255 for (auto R : RDs)
256 TmpDefs.insert(R.Id);
257
258 NodeSet Result = Defs;
259
260 for (NodeAddr<DefNode*> DA : RDs) {
261 Result.insert(DA.Id);
262 if (!(DA.Addr->getFlags() & NodeAttrs::PhiRef))
263 continue;
264 NodeAddr<PhiNode*> PA = DA.Addr->getOwner(DFG);
265 if (Visited.count(PA.Id))
266 continue;
267 Visited.insert(PA.Id);
268 // Go over all phi uses and get the reaching defs for each use.
269 for (auto U : PA.Addr->members_if(DFG.IsRef<NodeAttrs::Use>, DFG)) {
270 const auto &T = getAllReachingDefsRec(RefRR, U, Visited, TmpDefs);
271 Result.insert(T.begin(), T.end());
272 }
273 }
274
275 return Result;
276}
277
278
279NodeSet Liveness::getAllReachedUses(RegisterRef RefRR,
280 NodeAddr<DefNode*> DefA, const RegisterSet &DefRRs) {
281 NodeSet Uses;
282
283 // If the original register is already covered by all the intervening
284 // defs, no more uses can be reached.
285 if (RAI.covers(DefRRs, RefRR))
286 return Uses;
287
288 // Add all directly reached uses.
289 NodeId U = DefA.Addr->getReachedUse();
290 while (U != 0) {
291 auto UA = DFG.addr<UseNode*>(U);
Krzysztof Parzyszek1ff99522016-09-07 20:10:56 +0000292 if (!(UA.Addr->getFlags() & NodeAttrs::Undef)) {
293 auto UR = UA.Addr->getRegRef();
294 if (RAI.alias(RefRR, UR) && !RAI.covers(DefRRs, UR))
295 Uses.insert(U);
296 }
Krzysztof Parzyszekf5cbac92016-04-29 15:49:13 +0000297 U = UA.Addr->getSibling();
298 }
299
300 // Traverse all reached defs.
301 for (NodeId D = DefA.Addr->getReachedDef(), NextD; D != 0; D = NextD) {
302 auto DA = DFG.addr<DefNode*>(D);
303 NextD = DA.Addr->getSibling();
304 auto DR = DA.Addr->getRegRef();
305 // If this def is already covered, it cannot reach anything new.
306 // Similarly, skip it if it is not aliased to the interesting register.
307 if (RAI.covers(DefRRs, DR) || !RAI.alias(RefRR, DR))
308 continue;
309 NodeSet T;
Krzysztof Parzyszek1ff99522016-09-07 20:10:56 +0000310 if (DFG.IsPreservingDef(DA)) {
Krzysztof Parzyszekf5cbac92016-04-29 15:49:13 +0000311 // If it is a preserving def, do not update the set of intervening defs.
312 T = getAllReachedUses(RefRR, DA, DefRRs);
313 } else {
314 RegisterSet NewDefRRs = DefRRs;
315 NewDefRRs.insert(DR);
316 T = getAllReachedUses(RefRR, DA, NewDefRRs);
317 }
318 Uses.insert(T.begin(), T.end());
319 }
320 return Uses;
321}
322
323
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +0000324void Liveness::computePhiInfo() {
Krzysztof Parzyszekf5cbac92016-04-29 15:49:13 +0000325 RealUseMap.clear();
326
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +0000327 NodeList Phis;
328 NodeAddr<FuncNode*> FA = DFG.getFunc();
329 auto Blocks = FA.Addr->members(DFG);
330 for (NodeAddr<BlockNode*> BA : Blocks) {
331 auto Ps = BA.Addr->members_if(DFG.IsCode<NodeAttrs::Phi>, DFG);
332 Phis.insert(Phis.end(), Ps.begin(), Ps.end());
333 }
334
335 // phi use -> (map: reaching phi -> set of registers defined in between)
336 std::map<NodeId,std::map<NodeId,RegisterSet>> PhiUp;
337 std::vector<NodeId> PhiUQ; // Work list of phis for upward propagation.
338
Krzysztof Parzyszek2db0c8b2016-09-07 20:37:05 +0000339 auto isEntryPhi = [this] (NodeId P) -> bool {
340 auto PA = DFG.addr<PhiNode*>(P);
341 NodeAddr<BlockNode*> BA = PA.Addr->getOwner(DFG);
342 MachineBasicBlock *BB = BA.Addr->getCode();
343 return BB == &BB->getParent()->front();
344 };
345
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +0000346 // Go over all phis.
347 for (NodeAddr<PhiNode*> PhiA : Phis) {
348 // Go over all defs and collect the reached uses that are non-phi uses
349 // (i.e. the "real uses").
350 auto &RealUses = RealUseMap[PhiA.Id];
351 auto PhiRefs = PhiA.Addr->members(DFG);
352
353 // Have a work queue of defs whose reached uses need to be found.
354 // For each def, add to the queue all reached (non-phi) defs.
355 SetVector<NodeId> DefQ;
356 NodeSet PhiDefs;
357 for (auto R : PhiRefs) {
358 if (!DFG.IsRef<NodeAttrs::Def>(R))
359 continue;
360 DefQ.insert(R.Id);
361 PhiDefs.insert(R.Id);
362 }
Krzysztof Parzyszek2db0c8b2016-09-07 20:37:05 +0000363
364 // Collect the super-set of all possible reached uses. This set will
365 // contain all uses reached from this phi, either directly from the
366 // phi defs, or (recursively) via non-phi defs reached by the phi defs.
367 // This set of uses will later be trimmed to only contain these uses that
368 // are actually reached by the phi defs.
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +0000369 for (unsigned i = 0; i < DefQ.size(); ++i) {
370 NodeAddr<DefNode*> DA = DFG.addr<DefNode*>(DefQ[i]);
Krzysztof Parzyszek2db0c8b2016-09-07 20:37:05 +0000371 // Visit all reached uses.
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +0000372 NodeId UN = DA.Addr->getReachedUse();
373 while (UN != 0) {
374 NodeAddr<UseNode*> A = DFG.addr<UseNode*>(UN);
Krzysztof Parzyszek1ff99522016-09-07 20:10:56 +0000375 uint16_t F = A.Addr->getFlags();
376 if ((F & (NodeAttrs::Undef | NodeAttrs::PhiRef)) == 0)
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +0000377 RealUses[getRestrictedRegRef(A)].insert(A.Id);
378 UN = A.Addr->getSibling();
379 }
Krzysztof Parzyszek2db0c8b2016-09-07 20:37:05 +0000380 // Visit all reached defs, and add them to the queue. These defs may
381 // override some of the uses collected here, but that will be handled
382 // later.
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +0000383 NodeId DN = DA.Addr->getReachedDef();
384 while (DN != 0) {
385 NodeAddr<DefNode*> A = DFG.addr<DefNode*>(DN);
386 for (auto T : DFG.getRelatedRefs(A.Addr->getOwner(DFG), A)) {
387 uint16_t Flags = NodeAddr<DefNode*>(T).Addr->getFlags();
388 // Must traverse the reached-def chain. Consider:
389 // def(D0) -> def(R0) -> def(R0) -> use(D0)
390 // The reachable use of D0 passes through a def of R0.
391 if (!(Flags & NodeAttrs::PhiRef))
392 DefQ.insert(T.Id);
393 }
394 DN = A.Addr->getSibling();
395 }
396 }
397 // Filter out these uses that appear to be reachable, but really
398 // are not. For example:
399 //
400 // R1:0 = d1
401 // = R1:0 u2 Reached by d1.
402 // R0 = d3
403 // = R1:0 u4 Still reached by d1: indirectly through
404 // the def d3.
405 // R1 = d5
406 // = R1:0 u6 Not reached by d1 (covered collectively
407 // by d3 and d5), but following reached
408 // defs and uses from d1 will lead here.
Krzysztof Parzyszek2db0c8b2016-09-07 20:37:05 +0000409 auto InPhiDefs = [&PhiDefs] (NodeAddr<DefNode*> DA) -> bool {
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +0000410 return PhiDefs.count(DA.Id);
411 };
412 for (auto UI = RealUses.begin(), UE = RealUses.end(); UI != UE; ) {
413 // For each reached register UI->first, there is a set UI->second, of
414 // uses of it. For each such use, check if it is reached by this phi,
415 // i.e. check if the set of its reaching uses intersects the set of
416 // this phi's defs.
Krzysztof Parzyszek2db0c8b2016-09-07 20:37:05 +0000417 NodeSet &Uses = UI->second;
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +0000418 for (auto I = Uses.begin(), E = Uses.end(); I != E; ) {
419 auto UA = DFG.addr<UseNode*>(*I);
420 NodeList RDs = getAllReachingDefs(UI->first, UA);
Krzysztof Parzyszek2db0c8b2016-09-07 20:37:05 +0000421 if (any_of(RDs, InPhiDefs))
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +0000422 ++I;
423 else
424 I = Uses.erase(I);
425 }
426 if (Uses.empty())
427 UI = RealUses.erase(UI);
428 else
429 ++UI;
430 }
431
432 // If this phi reaches some "real" uses, add it to the queue for upward
433 // propagation.
434 if (!RealUses.empty())
435 PhiUQ.push_back(PhiA.Id);
436
437 // Go over all phi uses and check if the reaching def is another phi.
438 // Collect the phis that are among the reaching defs of these uses.
Krzysztof Parzyszek2db0c8b2016-09-07 20:37:05 +0000439 // While traversing the list of reaching defs for each phi use, accumulate
440 // the set of registers defined between this phi (PhiA) and the owner phi
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +0000441 // of the reaching def.
Krzysztof Parzyszek2db0c8b2016-09-07 20:37:05 +0000442 NodeSet SeenUses;
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +0000443 for (auto I : PhiRefs) {
Krzysztof Parzyszek2db0c8b2016-09-07 20:37:05 +0000444 if (!DFG.IsRef<NodeAttrs::Use>(I) || SeenUses.count(I.Id))
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +0000445 continue;
446 NodeAddr<UseNode*> UA = I;
Krzysztof Parzyszek2db0c8b2016-09-07 20:37:05 +0000447 std::map<NodeId,RegisterSet> &PUM = PhiUp[UA.Id];
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +0000448 RegisterSet DefRRs;
Krzysztof Parzyszek2db0c8b2016-09-07 20:37:05 +0000449 NodeId RP = 0; // Phi node reached upwards.
450
451 for (NodeAddr<UseNode*> VA : DFG.getRelatedRefs(PhiA, UA)) {
452 SeenUses.insert(VA.Id);
453 for (NodeAddr<DefNode*> DA : getAllReachingDefs(VA)) {
454 if (DA.Addr->getFlags() & NodeAttrs::PhiRef) {
455 // For all related phi uses, if they are reached by a phi def,
456 // all the reaching defs must belong to the same phi node.
457 // The only exception to that are the function entry phis, but
458 // are not playing any role in the subsequent propagation.
459 NodeId P = DA.Addr->getOwner(DFG).Id;
460 if (RP == 0)
461 RP = P;
462 assert(P == RP || (isEntryPhi(P) && isEntryPhi(RP)));
463 } else
464 DefRRs.insert(DA.Addr->getRegRef());
465 }
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +0000466 }
Krzysztof Parzyszek2db0c8b2016-09-07 20:37:05 +0000467 // Do not add reaching information for entry phis. The data collection
468 // above was done under the assumption that registers on all phis
469 // contain all actual data-flow (i.e. a phi for R0 will not convey
470 // data-flow information for D0). This is not true for entry phis.
471 // They are not participating in the propagation anyway, so that is
472 // not a problem.
473 if (RP && !isEntryPhi(RP))
474 PUM[RP] = DefRRs;
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +0000475 }
476 }
477
478 if (Trace) {
Krzysztof Parzyszek2db0c8b2016-09-07 20:37:05 +0000479 dbgs() << "Phi-up-to-phi map with intervening defs:\n";
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +0000480 for (auto I : PhiUp) {
481 dbgs() << "phi " << Print<NodeId>(I.first, DFG) << " -> {";
482 for (auto R : I.second)
483 dbgs() << ' ' << Print<NodeId>(R.first, DFG)
484 << Print<RegisterSet>(R.second, DFG);
485 dbgs() << " }\n";
486 }
487 }
488
489 // Propagate the reached registers up in the phi chain.
490 //
491 // The following type of situation needs careful handling:
492 //
493 // phi d1<R1:0> (1)
494 // |
495 // ... d2<R1>
496 // |
497 // phi u3<R1:0> (2)
498 // |
499 // ... u4<R1>
500 //
501 // The phi node (2) defines a register pair R1:0, and reaches a "real"
502 // use u4 of just R1. The same phi node is also known to reach (upwards)
503 // the phi node (1). However, the use u4 is not reached by phi (1),
504 // because of the intervening definition d2 of R1. The data flow between
505 // phis (1) and (2) is restricted to R1:0 minus R1, i.e. R0.
506 //
507 // When propagating uses up the phi chains, get the all reaching defs
508 // for a given phi use, and traverse the list until the propagated ref
Krzysztof Parzyszek2db0c8b2016-09-07 20:37:05 +0000509 // is covered, or until reaching the final phi. Only assume that the
510 // reference reaches the phi in the latter case.
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +0000511
512 for (unsigned i = 0; i < PhiUQ.size(); ++i) {
513 auto PA = DFG.addr<PhiNode*>(PhiUQ[i]);
Krzysztof Parzyszek2db0c8b2016-09-07 20:37:05 +0000514 NodeList PUs = PA.Addr->members_if(DFG.IsRef<NodeAttrs::Use>, DFG);
515 RefMap &RUM = RealUseMap[PA.Id];
516
517 for (auto U : PUs) {
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +0000518 NodeAddr<UseNode*> UA = U;
Krzysztof Parzyszek2db0c8b2016-09-07 20:37:05 +0000519 std::map<NodeId,RegisterSet> &PUM = PhiUp[UA.Id];
520 for (const std::pair<NodeId,RegisterSet> &P : PUM) {
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +0000521 bool Changed = false;
Krzysztof Parzyszek2db0c8b2016-09-07 20:37:05 +0000522 RegisterSet MidDefs = P.second;
523
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +0000524 // Collect the set UpReached of uses that are reached by the current
525 // phi PA, and are not covered by any intervening def between PA and
Krzysztof Parzyszek2db0c8b2016-09-07 20:37:05 +0000526 // the upward phi P.
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +0000527 RegisterSet UpReached;
Krzysztof Parzyszek2db0c8b2016-09-07 20:37:05 +0000528 for (const std::pair<RegisterRef,NodeSet> &T : RUM) {
529 RegisterRef R = T.first;
530 if (!isRestrictedToRef(PA, UA, R))
531 R = getRestrictedRegRef(UA);
532 if (!RAI.covers(MidDefs, R))
533 UpReached.insert(R);
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +0000534 }
535 if (UpReached.empty())
536 continue;
Krzysztof Parzyszek2db0c8b2016-09-07 20:37:05 +0000537 // Update the set PRUs of real uses reached by the upward phi P with
538 // the actual set of uses (UpReached) that the P phi reaches.
539 RefMap &PRUs = RealUseMap[P.first];
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +0000540 for (auto R : UpReached) {
541 unsigned Z = PRUs[R].size();
Krzysztof Parzyszek2db0c8b2016-09-07 20:37:05 +0000542 PRUs[R].insert(RUM[R].begin(), RUM[R].end());
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +0000543 Changed |= (PRUs[R].size() != Z);
544 }
545 if (Changed)
Krzysztof Parzyszek2db0c8b2016-09-07 20:37:05 +0000546 PhiUQ.push_back(P.first);
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +0000547 }
548 }
549 }
550
551 if (Trace) {
552 dbgs() << "Real use map:\n";
553 for (auto I : RealUseMap) {
554 dbgs() << "phi " << Print<NodeId>(I.first, DFG);
555 NodeAddr<PhiNode*> PA = DFG.addr<PhiNode*>(I.first);
556 NodeList Ds = PA.Addr->members_if(DFG.IsRef<NodeAttrs::Def>, DFG);
557 if (!Ds.empty()) {
558 RegisterRef RR = NodeAddr<DefNode*>(Ds[0]).Addr->getRegRef();
559 dbgs() << '<' << Print<RegisterRef>(RR, DFG) << '>';
560 } else {
561 dbgs() << "<noreg>";
562 }
563 dbgs() << " -> " << Print<RefMap>(I.second, DFG) << '\n';
564 }
565 }
566}
567
568
569void Liveness::computeLiveIns() {
570 // Populate the node-to-block map. This speeds up the calculations
571 // significantly.
572 NBMap.clear();
573 for (NodeAddr<BlockNode*> BA : DFG.getFunc().Addr->members(DFG)) {
574 MachineBasicBlock *BB = BA.Addr->getCode();
575 for (NodeAddr<InstrNode*> IA : BA.Addr->members(DFG)) {
576 for (NodeAddr<RefNode*> RA : IA.Addr->members(DFG))
577 NBMap.insert(std::make_pair(RA.Id, BB));
578 NBMap.insert(std::make_pair(IA.Id, BB));
579 }
580 }
581
582 MachineFunction &MF = DFG.getMF();
583
584 // Compute IDF first, then the inverse.
585 decltype(IIDF) IDF;
586 for (auto &B : MF) {
587 auto F1 = MDF.find(&B);
588 if (F1 == MDF.end())
589 continue;
590 SetVector<MachineBasicBlock*> IDFB(F1->second.begin(), F1->second.end());
591 for (unsigned i = 0; i < IDFB.size(); ++i) {
592 auto F2 = MDF.find(IDFB[i]);
593 if (F2 != MDF.end())
594 IDFB.insert(F2->second.begin(), F2->second.end());
595 }
596 // Add B to the IDF(B). This will put B in the IIDF(B).
597 IDFB.insert(&B);
598 IDF[&B].insert(IDFB.begin(), IDFB.end());
599 }
600
601 for (auto I : IDF)
602 for (auto S : I.second)
603 IIDF[S].insert(I.first);
604
605 computePhiInfo();
606
607 NodeAddr<FuncNode*> FA = DFG.getFunc();
608 auto Blocks = FA.Addr->members(DFG);
609
610 // Build the phi live-on-entry map.
611 for (NodeAddr<BlockNode*> BA : Blocks) {
612 MachineBasicBlock *MB = BA.Addr->getCode();
613 auto &LON = PhiLON[MB];
614 for (auto P : BA.Addr->members_if(DFG.IsCode<NodeAttrs::Phi>, DFG))
615 for (auto S : RealUseMap[P.Id])
616 LON[S.first].insert(S.second.begin(), S.second.end());
617 }
618
619 if (Trace) {
620 dbgs() << "Phi live-on-entry map:\n";
621 for (auto I : PhiLON)
622 dbgs() << "block #" << I.first->getNumber() << " -> "
623 << Print<RefMap>(I.second, DFG) << '\n';
624 }
625
626 // Build the phi live-on-exit map. Each phi node has some set of reached
627 // "real" uses. Propagate this set backwards into the block predecessors
628 // through the reaching defs of the corresponding phi uses.
629 for (NodeAddr<BlockNode*> BA : Blocks) {
630 auto Phis = BA.Addr->members_if(DFG.IsCode<NodeAttrs::Phi>, DFG);
631 for (NodeAddr<PhiNode*> PA : Phis) {
632 auto &RUs = RealUseMap[PA.Id];
633 if (RUs.empty())
634 continue;
635
636 for (auto U : PA.Addr->members_if(DFG.IsRef<NodeAttrs::Use>, DFG)) {
637 NodeAddr<PhiUseNode*> UA = U;
638 if (UA.Addr->getReachingDef() == 0)
639 continue;
640
641 // Mark all reached "real" uses of P as live on exit in the
642 // predecessor.
643 // Remap all the RUs so that they have a correct reaching def.
644 auto PrA = DFG.addr<BlockNode*>(UA.Addr->getPredecessor());
645 auto &LOX = PhiLOX[PrA.Addr->getCode()];
646 for (auto R : RUs) {
647 RegisterRef RR = R.first;
Krzysztof Parzyszek2db0c8b2016-09-07 20:37:05 +0000648 if (!isRestrictedToRef(PA, UA, RR))
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +0000649 RR = getRestrictedRegRef(UA);
650 // The restricted ref may be different from the ref that was
651 // accessed in the "real use". This means that this phi use
652 // is not the one that carries this reference, so skip it.
653 if (!RAI.alias(R.first, RR))
654 continue;
655 for (auto D : getAllReachingDefs(RR, UA))
656 LOX[RR].insert(D.Id);
657 }
658 } // for U : phi uses
659 } // for P : Phis
660 } // for B : Blocks
661
662 if (Trace) {
663 dbgs() << "Phi live-on-exit map:\n";
664 for (auto I : PhiLOX)
665 dbgs() << "block #" << I.first->getNumber() << " -> "
666 << Print<RefMap>(I.second, DFG) << '\n';
667 }
668
669 RefMap LiveIn;
670 traverse(&MF.front(), LiveIn);
671
672 // Add function live-ins to the live-in set of the function entry block.
673 auto &EntryIn = LiveMap[&MF.front()];
674 for (auto I = MRI.livein_begin(), E = MRI.livein_end(); I != E; ++I)
675 EntryIn.insert({I->first,0});
676
677 if (Trace) {
678 // Dump the liveness map
679 for (auto &B : MF) {
680 BitVector LV(TRI.getNumRegs());
681 for (auto I = B.livein_begin(), E = B.livein_end(); I != E; ++I)
682 LV.set(I->PhysReg);
683 dbgs() << "BB#" << B.getNumber() << "\t rec = {";
684 for (int x = LV.find_first(); x >= 0; x = LV.find_next(x))
685 dbgs() << ' ' << Print<RegisterRef>({unsigned(x),0}, DFG);
686 dbgs() << " }\n";
687 dbgs() << "\tcomp = " << Print<RegisterSet>(LiveMap[&B], DFG) << '\n';
688 }
689 }
690}
691
692
693void Liveness::resetLiveIns() {
694 for (auto &B : DFG.getMF()) {
695 // Remove all live-ins.
696 std::vector<unsigned> T;
697 for (auto I = B.livein_begin(), E = B.livein_end(); I != E; ++I)
698 T.push_back(I->PhysReg);
699 for (auto I : T)
700 B.removeLiveIn(I);
701 // Add the newly computed live-ins.
702 auto &LiveIns = LiveMap[&B];
703 for (auto I : LiveIns) {
704 assert(I.Sub == 0);
705 B.addLiveIn(I.Reg);
706 }
707 }
708}
709
710
711void Liveness::resetKills() {
712 for (auto &B : DFG.getMF())
713 resetKills(&B);
714}
715
716
717void Liveness::resetKills(MachineBasicBlock *B) {
718 auto CopyLiveIns = [] (MachineBasicBlock *B, BitVector &LV) -> void {
719 for (auto I = B->livein_begin(), E = B->livein_end(); I != E; ++I)
720 LV.set(I->PhysReg);
721 };
722
723 BitVector LiveIn(TRI.getNumRegs()), Live(TRI.getNumRegs());
724 CopyLiveIns(B, LiveIn);
725 for (auto SI : B->successors())
726 CopyLiveIns(SI, Live);
727
728 for (auto I = B->rbegin(), E = B->rend(); I != E; ++I) {
729 MachineInstr *MI = &*I;
730 if (MI->isDebugValue())
731 continue;
732
733 MI->clearKillInfo();
734 for (auto &Op : MI->operands()) {
Krzysztof Parzyszekf69ff712016-06-02 14:30:09 +0000735 // An implicit def of a super-register may not necessarily start a
736 // live range of it, since an implicit use could be used to keep parts
737 // of it live. Instead of analyzing the implicit operands, ignore
738 // implicit defs.
739 if (!Op.isReg() || !Op.isDef() || Op.isImplicit())
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +0000740 continue;
741 unsigned R = Op.getReg();
742 if (!TargetRegisterInfo::isPhysicalRegister(R))
743 continue;
744 for (MCSubRegIterator SR(R, &TRI, true); SR.isValid(); ++SR)
745 Live.reset(*SR);
746 }
747 for (auto &Op : MI->operands()) {
748 if (!Op.isReg() || !Op.isUse())
749 continue;
750 unsigned R = Op.getReg();
751 if (!TargetRegisterInfo::isPhysicalRegister(R))
752 continue;
753 bool IsLive = false;
Krzysztof Parzyszek16331f02016-04-20 14:33:23 +0000754 for (MCRegAliasIterator AR(R, &TRI, true); AR.isValid(); ++AR) {
755 if (!Live[*AR])
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +0000756 continue;
757 IsLive = true;
758 break;
759 }
760 if (IsLive)
761 continue;
762 Op.setIsKill(true);
763 for (MCSubRegIterator SR(R, &TRI, true); SR.isValid(); ++SR)
764 Live.set(*SR);
765 }
766 }
767}
768
769
770// For shadows, determine if RR is aliased to a reaching def of any other
Krzysztof Parzyszek2db0c8b2016-09-07 20:37:05 +0000771// shadow associated with RA. The register ref on RA will be "larger" than
772// each individual reaching def, and to determine the data-flow between defs
773// and uses of RR it may be necessary to visit all shadows. If RR is not
774// aliased to the reaching def of any other shadow, then visiting only RA
775// is sufficient. In that sense, the data flow of RR would be restricted to
776// the reference RA.
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +0000777// For non-shadows, this function returns "true".
Krzysztof Parzyszek2db0c8b2016-09-07 20:37:05 +0000778bool Liveness::isRestrictedToRef(NodeAddr<InstrNode*> IA, NodeAddr<RefNode*> RA,
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +0000779 RegisterRef RR) const {
780 NodeId Start = RA.Id;
781 for (NodeAddr<RefNode*> TA = DFG.getNextShadow(IA, RA);
782 TA.Id != 0 && TA.Id != Start; TA = DFG.getNextShadow(IA, TA)) {
783 NodeId RD = TA.Addr->getReachingDef();
784 if (RD == 0)
785 continue;
786 if (RAI.alias(RR, DFG.addr<DefNode*>(RD).Addr->getRegRef()))
787 return false;
788 }
789 return true;
790}
791
792
793RegisterRef Liveness::getRestrictedRegRef(NodeAddr<RefNode*> RA) const {
794 assert(DFG.IsRef<NodeAttrs::Use>(RA));
795 if (RA.Addr->getFlags() & NodeAttrs::Shadow) {
796 NodeId RD = RA.Addr->getReachingDef();
797 assert(RD);
798 RA = DFG.addr<DefNode*>(RD);
799 }
800 return RA.Addr->getRegRef();
801}
802
803
804unsigned Liveness::getPhysReg(RegisterRef RR) const {
805 if (!TargetRegisterInfo::isPhysicalRegister(RR.Reg))
806 return 0;
807 return RR.Sub ? TRI.getSubReg(RR.Reg, RR.Sub) : RR.Reg;
808}
809
810
811// Helper function to obtain the basic block containing the reaching def
812// of the given use.
813MachineBasicBlock *Liveness::getBlockWithRef(NodeId RN) const {
814 auto F = NBMap.find(RN);
815 if (F != NBMap.end())
816 return F->second;
817 llvm_unreachable("Node id not in map");
818}
819
820
821void Liveness::traverse(MachineBasicBlock *B, RefMap &LiveIn) {
822 // The LiveIn map, for each (physical) register, contains the set of live
823 // reaching defs of that register that are live on entry to the associated
824 // block.
825
826 // The summary of the traversal algorithm:
827 //
828 // R is live-in in B, if there exists a U(R), such that rdef(R) dom B
829 // and (U \in IDF(B) or B dom U).
830 //
831 // for (C : children) {
832 // LU = {}
833 // traverse(C, LU)
834 // LiveUses += LU
835 // }
836 //
837 // LiveUses -= Defs(B);
838 // LiveUses += UpwardExposedUses(B);
839 // for (C : IIDF[B])
840 // for (U : LiveUses)
841 // if (Rdef(U) dom C)
842 // C.addLiveIn(U)
843 //
844
845 // Go up the dominator tree (depth-first).
846 MachineDomTreeNode *N = MDT.getNode(B);
847 for (auto I : *N) {
848 RefMap L;
849 MachineBasicBlock *SB = I->getBlock();
850 traverse(SB, L);
851
852 for (auto S : L)
853 LiveIn[S.first].insert(S.second.begin(), S.second.end());
854 }
855
856 if (Trace) {
857 dbgs() << LLVM_FUNCTION_NAME << " in BB#" << B->getNumber()
858 << " after recursion into";
859 for (auto I : *N)
860 dbgs() << ' ' << I->getBlock()->getNumber();
861 dbgs() << "\n LiveIn: " << Print<RefMap>(LiveIn, DFG);
862 dbgs() << "\n Local: " << Print<RegisterSet>(LiveMap[B], DFG) << '\n';
863 }
864
865 // Add phi uses that are live on exit from this block.
866 RefMap &PUs = PhiLOX[B];
867 for (auto S : PUs)
868 LiveIn[S.first].insert(S.second.begin(), S.second.end());
869
870 if (Trace) {
871 dbgs() << "after LOX\n";
872 dbgs() << " LiveIn: " << Print<RefMap>(LiveIn, DFG) << '\n';
873 dbgs() << " Local: " << Print<RegisterSet>(LiveMap[B], DFG) << '\n';
874 }
875
876 // Stop tracking all uses defined in this block: erase those records
877 // where the reaching def is located in B and which cover all reached
878 // uses.
879 auto Copy = LiveIn;
880 LiveIn.clear();
881
882 for (auto I : Copy) {
883 auto &Defs = LiveIn[I.first];
884 NodeSet Rest;
885 for (auto R : I.second) {
886 auto DA = DFG.addr<DefNode*>(R);
887 RegisterRef DDR = DA.Addr->getRegRef();
888 NodeAddr<InstrNode*> IA = DA.Addr->getOwner(DFG);
889 NodeAddr<BlockNode*> BA = IA.Addr->getOwner(DFG);
890 // Defs from a different block need to be preserved. Defs from this
891 // block will need to be processed further, except for phi defs, the
892 // liveness of which is handled through the PhiLON/PhiLOX maps.
893 if (B != BA.Addr->getCode())
894 Defs.insert(R);
895 else {
Krzysztof Parzyszek1ff99522016-09-07 20:10:56 +0000896 bool IsPreserving = DFG.IsPreservingDef(DA);
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +0000897 if (IA.Addr->getKind() != NodeAttrs::Phi && !IsPreserving) {
898 bool Covering = RAI.covers(DDR, I.first);
899 NodeId U = DA.Addr->getReachedUse();
900 while (U && Covering) {
901 auto DUA = DFG.addr<UseNode*>(U);
Krzysztof Parzyszek1ff99522016-09-07 20:10:56 +0000902 if (!(DUA.Addr->getFlags() & NodeAttrs::Undef)) {
903 RegisterRef Q = DUA.Addr->getRegRef();
904 Covering = RAI.covers(DA.Addr->getRegRef(), Q);
905 }
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +0000906 U = DUA.Addr->getSibling();
907 }
908 if (!Covering)
909 Rest.insert(R);
910 }
911 }
912 }
913
914 // Non-covering defs from B.
915 for (auto R : Rest) {
916 auto DA = DFG.addr<DefNode*>(R);
917 RegisterRef DRR = DA.Addr->getRegRef();
918 RegisterSet RRs;
919 for (NodeAddr<DefNode*> TA : getAllReachingDefs(DA)) {
920 NodeAddr<InstrNode*> IA = TA.Addr->getOwner(DFG);
921 NodeAddr<BlockNode*> BA = IA.Addr->getOwner(DFG);
922 // Preserving defs do not count towards covering.
923 if (!(TA.Addr->getFlags() & NodeAttrs::Preserving))
924 RRs.insert(TA.Addr->getRegRef());
925 if (BA.Addr->getCode() == B)
926 continue;
927 if (RAI.covers(RRs, DRR))
928 break;
929 Defs.insert(TA.Id);
930 }
931 }
932 }
933
934 emptify(LiveIn);
935
936 if (Trace) {
937 dbgs() << "after defs in block\n";
938 dbgs() << " LiveIn: " << Print<RefMap>(LiveIn, DFG) << '\n';
939 dbgs() << " Local: " << Print<RegisterSet>(LiveMap[B], DFG) << '\n';
940 }
941
942 // Scan the block for upward-exposed uses and add them to the tracking set.
943 for (auto I : DFG.getFunc().Addr->findBlock(B, DFG).Addr->members(DFG)) {
944 NodeAddr<InstrNode*> IA = I;
945 if (IA.Addr->getKind() != NodeAttrs::Stmt)
946 continue;
947 for (NodeAddr<UseNode*> UA : IA.Addr->members_if(DFG.IsUse, DFG)) {
948 RegisterRef RR = UA.Addr->getRegRef();
Krzysztof Parzyszek1ff99522016-09-07 20:10:56 +0000949 if (UA.Addr->getFlags() & NodeAttrs::Undef)
950 continue;
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +0000951 for (auto D : getAllReachingDefs(UA))
952 if (getBlockWithRef(D.Id) != B)
953 LiveIn[RR].insert(D.Id);
954 }
955 }
956
957 if (Trace) {
958 dbgs() << "after uses in block\n";
959 dbgs() << " LiveIn: " << Print<RefMap>(LiveIn, DFG) << '\n';
960 dbgs() << " Local: " << Print<RegisterSet>(LiveMap[B], DFG) << '\n';
961 }
962
963 // Phi uses should not be propagated up the dominator tree, since they
964 // are not dominated by their corresponding reaching defs.
965 auto &Local = LiveMap[B];
966 auto &LON = PhiLON[B];
967 for (auto R : LON)
968 Local.insert(R.first);
969
970 if (Trace) {
971 dbgs() << "after phi uses in block\n";
972 dbgs() << " LiveIn: " << Print<RefMap>(LiveIn, DFG) << '\n';
973 dbgs() << " Local: " << Print<RegisterSet>(Local, DFG) << '\n';
974 }
975
976 for (auto C : IIDF[B]) {
977 auto &LiveC = LiveMap[C];
978 for (auto S : LiveIn)
979 for (auto R : S.second)
980 if (MDT.properlyDominates(getBlockWithRef(R), C))
981 LiveC.insert(S.first);
982 }
983}
984
985
986void Liveness::emptify(RefMap &M) {
987 for (auto I = M.begin(), E = M.end(); I != E; )
988 I = I->second.empty() ? M.erase(I) : std::next(I);
989}
990