blob: b7530781eaf277cfc439a56ffa3ef6de78c9cc4a [file] [log] [blame]
Jim Stichnothf7c9a142014-04-29 10:52:43 -07001//===- subzero/src/IceCfgNode.cpp - Basic block (node) implementation -----===//
2//
3// The Subzero Code Generator
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -070010// This file implements the CfgNode class, including the complexities
11// of instruction insertion and in-edge calculation.
Jim Stichnothf7c9a142014-04-29 10:52:43 -070012//
13//===----------------------------------------------------------------------===//
14
Jan Voung7e1e4852014-10-24 10:29:30 -070015#include "assembler.h"
Jim Stichnothf7c9a142014-04-29 10:52:43 -070016#include "IceCfg.h"
17#include "IceCfgNode.h"
18#include "IceInst.h"
Jim Stichnothd97c7df2014-06-04 11:57:08 -070019#include "IceLiveness.h"
Jim Stichnothf7c9a142014-04-29 10:52:43 -070020#include "IceOperand.h"
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -070021#include "IceTargetLowering.h"
Jim Stichnothf7c9a142014-04-29 10:52:43 -070022
23namespace Ice {
24
25CfgNode::CfgNode(Cfg *Func, SizeT LabelNumber, IceString Name)
Jim Stichnoth47752552014-10-13 17:15:08 -070026 : Func(Func), Number(LabelNumber), Name(Name), HasReturn(false),
Jim Stichnoth336f6c42014-10-30 15:01:31 -070027 NeedsPlacement(false), InstCountEstimate(0) {}
Jim Stichnothf7c9a142014-04-29 10:52:43 -070028
29// Returns the name the node was created with. If no name was given,
30// it synthesizes a (hopefully) unique name.
31IceString CfgNode::getName() const {
32 if (!Name.empty())
33 return Name;
Jim Stichnoth088b2be2014-10-23 12:02:08 -070034 return "__" + std::to_string(getIndex());
Jim Stichnothf7c9a142014-04-29 10:52:43 -070035}
36
37// Adds an instruction to either the Phi list or the regular
38// instruction list. Validates that all Phis are added before all
39// regular instructions.
40void CfgNode::appendInst(Inst *Inst) {
Jim Stichnoth47752552014-10-13 17:15:08 -070041 ++InstCountEstimate;
Jim Stichnothf7c9a142014-04-29 10:52:43 -070042 if (InstPhi *Phi = llvm::dyn_cast<InstPhi>(Inst)) {
43 if (!Insts.empty()) {
44 Func->setError("Phi instruction added to the middle of a block");
45 return;
46 }
47 Phis.push_back(Phi);
48 } else {
49 Insts.push_back(Inst);
50 }
Jim Stichnothf7c9a142014-04-29 10:52:43 -070051}
52
Jim Stichnothd97c7df2014-06-04 11:57:08 -070053// Renumbers the non-deleted instructions in the node. This needs to
54// be done in preparation for live range analysis. The instruction
55// numbers in a block must be monotonically increasing. The range of
56// instruction numbers in a block, from lowest to highest, must not
57// overlap with the range of any other block.
58void CfgNode::renumberInstructions() {
Jim Stichnoth47752552014-10-13 17:15:08 -070059 InstNumberT FirstNumber = Func->getNextInstNumber();
Jim Stichnothf44f3712014-10-01 14:05:51 -070060 for (InstPhi *I : Phis)
61 I->renumber(Func);
62 for (Inst *I : Insts)
63 I->renumber(Func);
Jim Stichnoth47752552014-10-13 17:15:08 -070064 InstCountEstimate = Func->getNextInstNumber() - FirstNumber;
Jim Stichnothd97c7df2014-06-04 11:57:08 -070065}
66
Jim Stichnoth088b2be2014-10-23 12:02:08 -070067// When a node is created, the OutEdges are immediately known, but the
Jim Stichnothf7c9a142014-04-29 10:52:43 -070068// InEdges have to be built up incrementally. After the CFG has been
69// constructed, the computePredecessors() pass finalizes it by
70// creating the InEdges list.
71void CfgNode::computePredecessors() {
72 OutEdges = (*Insts.rbegin())->getTerminatorEdges();
Jim Stichnothf44f3712014-10-01 14:05:51 -070073 for (CfgNode *Succ : OutEdges)
74 Succ->InEdges.push_back(this);
Jim Stichnothf7c9a142014-04-29 10:52:43 -070075}
76
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -070077// This does part 1 of Phi lowering, by creating a new dest variable
78// for each Phi instruction, replacing the Phi instruction's dest with
79// that variable, and adding an explicit assignment of the old dest to
80// the new dest. For example,
81// a=phi(...)
82// changes to
83// "a_phi=phi(...); a=a_phi".
84//
85// This is in preparation for part 2 which deletes the Phi
86// instructions and appends assignment instructions to predecessor
87// blocks. Note that this transformation preserves SSA form.
88void CfgNode::placePhiLoads() {
Jim Stichnothf44f3712014-10-01 14:05:51 -070089 for (InstPhi *I : Phis)
90 Insts.insert(Insts.begin(), I->lower(Func));
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -070091}
92
93// This does part 2 of Phi lowering. For each Phi instruction at each
94// out-edge, create a corresponding assignment instruction, and add
95// all the assignments near the end of this block. They need to be
96// added before any branch instruction, and also if the block ends
97// with a compare instruction followed by a branch instruction that we
98// may want to fuse, it's better to insert the new assignments before
Jan Voungc820ddf2014-07-29 14:38:51 -070099// the compare instruction. The tryOptimizedCmpxchgCmpBr() method
100// assumes this ordering of instructions.
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700101//
102// Note that this transformation takes the Phi dest variables out of
103// SSA form, as there may be assignments to the dest variable in
104// multiple blocks.
105//
106// TODO: Defer this pass until after register allocation, then split
107// critical edges, add the assignments, and lower them. This should
108// reduce the amount of shuffling at the end of each block.
109void CfgNode::placePhiStores() {
Jim Stichnothe5a5be72014-09-10 11:51:38 -0700110 // Find the insertion point.
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700111 InstList::iterator InsertionPoint = Insts.end();
Jim Stichnothe5a5be72014-09-10 11:51:38 -0700112 // Every block must end in a terminator instruction, and therefore
113 // must have at least one instruction, so it's valid to decrement
114 // InsertionPoint (but assert just in case).
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700115 assert(InsertionPoint != Insts.begin());
116 --InsertionPoint;
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700117 // Confirm that InsertionPoint is a terminator instruction. Calling
118 // getTerminatorEdges() on a non-terminator instruction will cause
119 // an llvm_unreachable().
120 (void)(*InsertionPoint)->getTerminatorEdges();
Jim Stichnothe5a5be72014-09-10 11:51:38 -0700121 // SafeInsertionPoint is always immediately before the terminator
122 // instruction. If the block ends in a compare and conditional
123 // branch, it's better to place the Phi store before the compare so
124 // as not to interfere with compare/branch fusing. However, if the
125 // compare instruction's dest operand is the same as the new
126 // assignment statement's source operand, this can't be done due to
127 // data dependences, so we need to fall back to the
128 // SafeInsertionPoint. To illustrate:
129 // ; <label>:95
130 // %97 = load i8* %96, align 1
131 // %98 = icmp ne i8 %97, 0
132 // br i1 %98, label %99, label %2132
133 // ; <label>:99
134 // %100 = phi i8 [ %97, %95 ], [ %110, %108 ]
135 // %101 = phi i1 [ %98, %95 ], [ %111, %108 ]
136 // would be Phi-lowered as:
137 // ; <label>:95
138 // %97 = load i8* %96, align 1
139 // %100_phi = %97 ; can be at InsertionPoint
140 // %98 = icmp ne i8 %97, 0
141 // %101_phi = %98 ; must be at SafeInsertionPoint
142 // br i1 %98, label %99, label %2132
143 // ; <label>:99
144 // %100 = %100_phi
145 // %101 = %101_phi
146 //
147 // TODO(stichnot): It may be possible to bypass this whole
148 // SafeInsertionPoint mechanism. If a source basic block ends in a
149 // conditional branch:
150 // labelSource:
151 // ...
152 // br i1 %foo, label %labelTrue, label %labelFalse
153 // and a branch target has a Phi involving the branch operand:
154 // labelTrue:
155 // %bar = phi i1 [ %foo, %labelSource ], ...
156 // then we actually know the constant i1 value of the Phi operand:
157 // labelTrue:
158 // %bar = phi i1 [ true, %labelSource ], ...
159 // It seems that this optimization should be done by clang or opt,
160 // but we could also do it here.
161 InstList::iterator SafeInsertionPoint = InsertionPoint;
162 // Keep track of the dest variable of a compare instruction, so that
163 // we insert the new instruction at the SafeInsertionPoint if the
164 // compare's dest matches the Phi-lowered assignment's source.
165 Variable *CmpInstDest = NULL;
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700166 // If the current insertion point is at a conditional branch
167 // instruction, and the previous instruction is a compare
168 // instruction, then we move the insertion point before the compare
169 // instruction so as not to interfere with compare/branch fusing.
170 if (InstBr *Branch = llvm::dyn_cast<InstBr>(*InsertionPoint)) {
171 if (!Branch->isUnconditional()) {
172 if (InsertionPoint != Insts.begin()) {
173 --InsertionPoint;
Jim Stichnothe5a5be72014-09-10 11:51:38 -0700174 if (llvm::isa<InstIcmp>(*InsertionPoint) ||
175 llvm::isa<InstFcmp>(*InsertionPoint)) {
176 CmpInstDest = (*InsertionPoint)->getDest();
177 } else {
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700178 ++InsertionPoint;
179 }
180 }
181 }
182 }
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700183
184 // Consider every out-edge.
Jim Stichnothf44f3712014-10-01 14:05:51 -0700185 for (CfgNode *Succ : OutEdges) {
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700186 // Consider every Phi instruction at the out-edge.
Jim Stichnothf44f3712014-10-01 14:05:51 -0700187 for (InstPhi *I : Succ->Phis) {
188 Operand *Operand = I->getOperandForTarget(this);
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700189 assert(Operand);
Jim Stichnothf44f3712014-10-01 14:05:51 -0700190 Variable *Dest = I->getDest();
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700191 assert(Dest);
192 InstAssign *NewInst = InstAssign::create(Func, Dest, Operand);
Jim Stichnothe5a5be72014-09-10 11:51:38 -0700193 if (CmpInstDest == Operand)
194 Insts.insert(SafeInsertionPoint, NewInst);
195 else
196 Insts.insert(InsertionPoint, NewInst);
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700197 }
198 }
199}
200
201// Deletes the phi instructions after the loads and stores are placed.
202void CfgNode::deletePhis() {
Jim Stichnothf44f3712014-10-01 14:05:51 -0700203 for (InstPhi *I : Phis)
204 I->setDeleted();
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700205}
206
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700207// Splits the edge from Pred to this node by creating a new node and
208// hooking up the in and out edges appropriately. (The EdgeIndex
209// parameter is only used to make the new node's name unique when
210// there are multiple edges between the same pair of nodes.) The new
211// node's instruction list is initialized to the empty list, with no
212// terminator instruction. If there are multiple edges from Pred to
213// this node, only one edge is split, and the particular choice of
214// edge is undefined. This could happen with a switch instruction, or
215// a conditional branch that weirdly has both branches to the same
216// place. TODO(stichnot,kschimpf): Figure out whether this is legal
217// in the LLVM IR or the PNaCl bitcode, and if so, we need to
218// establish a strong relationship among the ordering of Pred's
219// out-edge list, this node's in-edge list, and the Phi instruction's
220// operand list.
221CfgNode *CfgNode::splitIncomingEdge(CfgNode *Pred, SizeT EdgeIndex) {
222 CfgNode *NewNode =
223 Func->makeNode("split_" + Pred->getName() + "_" + getName() + "_" +
224 std::to_string(EdgeIndex));
225 // The new node is added to the end of the node list, and will later
226 // need to be sorted into a reasonable topological order.
227 NewNode->setNeedsPlacement(true);
228 // Repoint Pred's out-edge.
229 bool Found = false;
230 for (auto I = Pred->OutEdges.begin(), E = Pred->OutEdges.end();
231 !Found && I != E; ++I) {
232 if (*I == this) {
233 *I = NewNode;
234 NewNode->InEdges.push_back(Pred);
235 Found = true;
236 }
237 }
238 assert(Found);
239 // Repoint this node's in-edge.
240 Found = false;
241 for (auto I = InEdges.begin(), E = InEdges.end(); !Found && I != E; ++I) {
242 if (*I == Pred) {
243 *I = NewNode;
244 NewNode->OutEdges.push_back(this);
245 Found = true;
246 }
247 }
248 assert(Found);
249 // Repoint a suitable branch instruction's target.
250 Found = false;
251 for (auto I = Pred->getInsts().rbegin(), E = Pred->getInsts().rend();
252 !Found && I != E; ++I) {
253 if (!(*I)->isDeleted()) {
254 Found = (*I)->repointEdge(this, NewNode);
255 }
256 }
257 assert(Found);
258 return NewNode;
259}
260
261namespace {
262
263// Helper function used by advancedPhiLowering().
264bool sameVarOrReg(const Variable *Var, const Operand *Opnd) {
265 if (Var == Opnd)
266 return true;
267 if (const auto Var2 = llvm::dyn_cast<Variable>(Opnd)) {
268 if (Var->hasReg() && Var->getRegNum() == Var2->getRegNum())
269 return true;
270 }
271 return false;
272}
273
274} // end of anonymous namespace
275
276// This the "advanced" version of Phi lowering for a basic block, in
277// contrast to the simple version that lowers through assignments
278// involving temporaries.
279//
280// All Phi instructions in a basic block are conceptually executed in
281// parallel. However, if we lower Phis early and commit to a
282// sequential ordering, we may end up creating unnecessary
283// interferences which lead to worse register allocation. Delaying
284// Phi scheduling until after register allocation can help unless
285// there are no free registers for shuffling registers or stack slots
286// and spilling becomes necessary.
287//
288// The advanced Phi lowering starts by finding a topological sort of
289// the Phi instructions, where "A=B" comes before "B=C" due to the
290// anti-dependence on B. If a topological sort is not possible due to
291// a cycle, the cycle is broken by introducing a non-parallel
292// temporary. For example, a cycle arising from a permutation like
293// "A=B;B=C;C=A" can become "T=A;A=B;B=C;C=T". All else being equal,
294// prefer to schedule assignments with register-allocated Src operands
295// earlier, in case that register becomes free afterwards, and prefer
296// to schedule assignments with register-allocated Dest variables
297// later, to keep that register free for longer.
298//
299// Once the ordering is determined, the Cfg edge is split and the
300// assignment list is lowered by the target lowering layer. The
301// specific placement of the new node within the Cfg node list is
302// deferred until later, including after empty node contraction.
303void CfgNode::advancedPhiLowering() {
304 if (getPhis().empty())
305 return;
306
307 // Count the number of non-deleted Phi instructions.
308 struct {
309 InstPhi *Phi;
310 Variable *Dest;
311 Operand *Src;
312 bool Processed;
313 size_t NumPred; // number of entries whose Src is this Dest
314 int32_t Weight; // preference for topological order
315 } Desc[getPhis().size()];
316
317 size_t NumPhis = 0;
318 for (InstPhi *Inst : getPhis()) {
319 if (!Inst->isDeleted()) {
320 Desc[NumPhis].Phi = Inst;
321 Desc[NumPhis].Dest = Inst->getDest();
322 ++NumPhis;
323 }
324 }
325 if (NumPhis == 0)
326 return;
327
328 SizeT InEdgeIndex = 0;
329 for (CfgNode *Pred : InEdges) {
330 CfgNode *Split = splitIncomingEdge(Pred, InEdgeIndex++);
331 AssignList Assignments;
332 SizeT Remaining = NumPhis;
333
334 // First pass computes Src and initializes NumPred.
335 for (size_t I = 0; I < NumPhis; ++I) {
336 Variable *Dest = Desc[I].Dest;
337 Operand *Src = Desc[I].Phi->getOperandForTarget(Pred);
338 Desc[I].Src = Src;
339 Desc[I].Processed = false;
340 Desc[I].NumPred = 0;
341 // Cherry-pick any trivial assignments, so that they don't
342 // contribute to the running complexity of the topological sort.
343 if (sameVarOrReg(Dest, Src)) {
344 Desc[I].Processed = true;
345 --Remaining;
346 if (Dest != Src)
347 // If Dest and Src are syntactically the same, don't bother
348 // adding the assignment, because in all respects it would
349 // be redundant, and if Dest/Src are on the stack, the
350 // target lowering may naively decide to lower it using a
351 // temporary register.
352 Assignments.push_back(InstAssign::create(Func, Dest, Src));
353 }
354 }
355 // Second pass computes NumPred by comparing every pair of Phi
356 // instructions.
357 for (size_t I = 0; I < NumPhis; ++I) {
358 if (Desc[I].Processed)
359 continue;
360 const Variable *Dest = Desc[I].Dest;
361 for (size_t J = 0; J < NumPhis; ++J) {
362 if (Desc[J].Processed)
363 continue;
364 if (I != J) {
365 // There shouldn't be two Phis with the same Dest variable
366 // or register.
367 assert(!sameVarOrReg(Dest, Desc[J].Dest));
368 }
369 const Operand *Src = Desc[J].Src;
370 if (sameVarOrReg(Dest, Src))
371 ++Desc[I].NumPred;
372 }
373 }
374
375 // Another pass to compute initial Weight values.
376
377 // Always pick NumPred=0 over NumPred>0.
378 const int32_t WeightNoPreds = 4;
379 // Prefer Src as a register because the register might free up.
380 const int32_t WeightSrcIsReg = 2;
381 // Prefer Dest not as a register because the register stays free
382 // longer.
383 const int32_t WeightDestNotReg = 1;
384
385 for (size_t I = 0; I < NumPhis; ++I) {
386 if (Desc[I].Processed)
387 continue;
388 int32_t Weight = 0;
389 if (Desc[I].NumPred == 0)
390 Weight += WeightNoPreds;
391 if (auto Var = llvm::dyn_cast<Variable>(Desc[I].Src))
392 if (Var->hasReg())
393 Weight += WeightSrcIsReg;
394 if (!Desc[I].Dest->hasReg())
395 Weight += WeightDestNotReg;
396 Desc[I].Weight = Weight;
397 }
398
399 // Repeatedly choose and process the best candidate in the
400 // topological sort, until no candidates remain. This
401 // implementation is O(N^2) where N is the number of Phi
402 // instructions, but with a small constant factor compared to a
403 // likely implementation of O(N) topological sort.
404 for (; Remaining; --Remaining) {
405 size_t BestIndex = 0;
406 int32_t BestWeight = -1;
407 // Find the best candidate.
408 for (size_t I = 0; I < NumPhis; ++I) {
409 if (Desc[I].Processed)
410 continue;
411 int32_t Weight = 0;
412 Weight = Desc[I].Weight;
413 if (Weight > BestWeight) {
414 BestIndex = I;
415 BestWeight = Weight;
416 }
417 }
418 assert(BestWeight >= 0);
419 assert(Desc[BestIndex].NumPred <= 1);
420 Variable *Dest = Desc[BestIndex].Dest;
421 Operand *Src = Desc[BestIndex].Src;
422 assert(!sameVarOrReg(Dest, Src));
423 // Break a cycle by introducing a temporary.
424 if (Desc[BestIndex].NumPred) {
425 bool Found = false;
426 // If the target instruction "A=B" is part of a cycle, find
427 // the "X=A" assignment in the cycle because it will have to
428 // be rewritten as "X=tmp".
429 for (size_t J = 0; !Found && J < NumPhis; ++J) {
430 if (Desc[J].Processed)
431 continue;
432 Operand *OtherSrc = Desc[J].Src;
433 if (Desc[J].NumPred && sameVarOrReg(Dest, OtherSrc)) {
434 SizeT VarNum = Func->getNumVariables();
435 Variable *Tmp = Func->makeVariable(
436 OtherSrc->getType(), "__split_" + std::to_string(VarNum));
437 Tmp->setNeedsStackSlot();
438 Assignments.push_back(InstAssign::create(Func, Tmp, OtherSrc));
439 Desc[J].Src = Tmp;
440 Found = true;
441 }
442 }
443 assert(Found);
444 }
445 // Now that a cycle (if any) has been broken, create the actual
446 // assignment.
447 Assignments.push_back(InstAssign::create(Func, Dest, Src));
448 // Update NumPred for all Phi assignments using this Phi's Src
449 // as their Dest variable. Also update Weight if NumPred
450 // dropped from 1 to 0.
451 if (auto Var = llvm::dyn_cast<Variable>(Src)) {
452 for (size_t I = 0; I < NumPhis; ++I) {
453 if (Desc[I].Processed)
454 continue;
455 if (sameVarOrReg(Var, Desc[I].Dest)) {
456 if (--Desc[I].NumPred == 0)
457 Desc[I].Weight += WeightNoPreds;
458 }
459 }
460 }
461 Desc[BestIndex].Processed = true;
462 }
463
464 Func->getTarget()->lowerPhiAssignments(Split, Assignments);
465
466 // Renumber the instructions to be monotonically increasing so
467 // that addNode() doesn't assert when multi-definitions are added
468 // out of order.
469 Split->renumberInstructions();
470 Func->getVMetadata()->addNode(Split);
471 }
472
473 for (InstPhi *Inst : getPhis())
474 Inst->setDeleted();
475}
476
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700477// Does address mode optimization. Pass each instruction to the
478// TargetLowering object. If it returns a new instruction
479// (representing the optimized address mode), then insert the new
480// instruction and delete the old.
481void CfgNode::doAddressOpt() {
482 TargetLowering *Target = Func->getTarget();
483 LoweringContext &Context = Target->getContext();
484 Context.init(this);
485 while (!Context.atEnd()) {
486 Target->doAddressOpt();
487 }
488}
489
Matt Walac3302742014-08-15 16:21:56 -0700490void CfgNode::doNopInsertion() {
491 TargetLowering *Target = Func->getTarget();
492 LoweringContext &Context = Target->getContext();
493 Context.init(this);
494 while (!Context.atEnd()) {
495 Target->doNopInsertion();
496 // Ensure Cur=Next, so that the nops are inserted before the current
497 // instruction rather than after.
498 Context.advanceNext();
499 Context.advanceCur();
500 }
501 // Insert before all instructions.
502 Context.setInsertPoint(getInsts().begin());
503 Context.advanceNext();
504 Context.advanceCur();
505 Target->doNopInsertion();
506}
507
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700508// Drives the target lowering. Passes the current instruction and the
509// next non-deleted instruction for target lowering.
510void CfgNode::genCode() {
511 TargetLowering *Target = Func->getTarget();
512 LoweringContext &Context = Target->getContext();
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700513 // Lower the regular instructions.
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700514 Context.init(this);
515 while (!Context.atEnd()) {
516 InstList::iterator Orig = Context.getCur();
517 if (llvm::isa<InstRet>(*Orig))
518 setHasReturn();
519 Target->lower();
520 // Ensure target lowering actually moved the cursor.
521 assert(Context.getCur() != Orig);
522 }
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700523 // Do preliminary lowering of the Phi instructions.
524 Target->prelowerPhis();
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700525}
526
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700527void CfgNode::livenessLightweight() {
528 SizeT NumVars = Func->getNumVariables();
Jim Stichnoth47752552014-10-13 17:15:08 -0700529 LivenessBV Live(NumVars);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700530 // Process regular instructions in reverse order.
Jim Stichnothf44f3712014-10-01 14:05:51 -0700531 // TODO(stichnot): Use llvm::make_range with LLVM 3.5.
532 for (auto I = Insts.rbegin(), E = Insts.rend(); I != E; ++I) {
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700533 if ((*I)->isDeleted())
534 continue;
Jim Stichnoth144cdce2014-09-22 16:02:59 -0700535 (*I)->livenessLightweight(Func, Live);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700536 }
Jim Stichnothf44f3712014-10-01 14:05:51 -0700537 for (InstPhi *I : Phis) {
538 if (I->isDeleted())
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700539 continue;
Jim Stichnothf44f3712014-10-01 14:05:51 -0700540 I->livenessLightweight(Func, Live);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700541 }
542}
543
544// Performs liveness analysis on the block. Returns true if the
545// incoming liveness changed from before, false if it stayed the same.
546// (If it changes, the node's predecessors need to be processed
547// again.)
548bool CfgNode::liveness(Liveness *Liveness) {
549 SizeT NumVars = Liveness->getNumVarsInNode(this);
Jim Stichnoth47752552014-10-13 17:15:08 -0700550 LivenessBV Live(NumVars);
551 LiveBeginEndMap *LiveBegin = NULL;
552 LiveBeginEndMap *LiveEnd = NULL;
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700553 // Mark the beginning and ending of each variable's live range
554 // with the sentinel instruction number 0.
Jim Stichnoth47752552014-10-13 17:15:08 -0700555 if (Liveness->getMode() == Liveness_Intervals) {
556 LiveBegin = Liveness->getLiveBegin(this);
557 LiveEnd = Liveness->getLiveEnd(this);
558 LiveBegin->clear();
559 LiveEnd->clear();
560 // Guess that the number of live ranges beginning is roughly the
561 // number of instructions, and same for live ranges ending.
562 LiveBegin->reserve(getInstCountEstimate());
563 LiveEnd->reserve(getInstCountEstimate());
564 }
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700565 // Initialize Live to be the union of all successors' LiveIn.
Jim Stichnothf44f3712014-10-01 14:05:51 -0700566 for (CfgNode *Succ : OutEdges) {
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700567 Live |= Liveness->getLiveIn(Succ);
568 // Mark corresponding argument of phis in successor as live.
Jim Stichnothf44f3712014-10-01 14:05:51 -0700569 for (InstPhi *I : Succ->Phis)
570 I->livenessPhiOperand(Live, this, Liveness);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700571 }
572 Liveness->getLiveOut(this) = Live;
573
574 // Process regular instructions in reverse order.
Jim Stichnothf44f3712014-10-01 14:05:51 -0700575 for (auto I = Insts.rbegin(), E = Insts.rend(); I != E; ++I) {
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700576 if ((*I)->isDeleted())
577 continue;
Jim Stichnoth47752552014-10-13 17:15:08 -0700578 (*I)->liveness((*I)->getNumber(), Live, Liveness, LiveBegin, LiveEnd);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700579 }
580 // Process phis in forward order so that we can override the
581 // instruction number to be that of the earliest phi instruction in
582 // the block.
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700583 SizeT NumNonDeadPhis = 0;
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700584 InstNumberT FirstPhiNumber = Inst::NumberSentinel;
Jim Stichnothf44f3712014-10-01 14:05:51 -0700585 for (InstPhi *I : Phis) {
586 if (I->isDeleted())
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700587 continue;
588 if (FirstPhiNumber == Inst::NumberSentinel)
Jim Stichnothf44f3712014-10-01 14:05:51 -0700589 FirstPhiNumber = I->getNumber();
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700590 if (I->liveness(FirstPhiNumber, Live, Liveness, LiveBegin, LiveEnd))
591 ++NumNonDeadPhis;
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700592 }
593
594 // When using the sparse representation, after traversing the
595 // instructions in the block, the Live bitvector should only contain
596 // set bits for global variables upon block entry. We validate this
597 // by shrinking the Live vector and then testing it against the
598 // pre-shrunk version. (The shrinking is required, but the
599 // validation is not.)
Jim Stichnoth47752552014-10-13 17:15:08 -0700600 LivenessBV LiveOrig = Live;
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700601 Live.resize(Liveness->getNumGlobalVars());
602 // Non-global arguments in the entry node are allowed to be live on
603 // entry.
604 bool IsEntry = (Func->getEntryNode() == this);
605 if (!(IsEntry || Live == LiveOrig)) {
606 // This is a fatal liveness consistency error. Print some
607 // diagnostics and abort.
608 Ostream &Str = Func->getContext()->getStrDump();
Jim Stichnoth800dab22014-09-20 12:25:02 -0700609 Func->resetCurrentNode();
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700610 Str << "LiveOrig-Live =";
611 for (SizeT i = Live.size(); i < LiveOrig.size(); ++i) {
612 if (LiveOrig.test(i)) {
613 Str << " ";
614 Liveness->getVariable(i, this)->dump(Func);
615 }
616 }
617 Str << "\n";
618 llvm_unreachable("Fatal inconsistency in liveness analysis");
619 }
620
621 bool Changed = false;
Jim Stichnoth47752552014-10-13 17:15:08 -0700622 LivenessBV &LiveIn = Liveness->getLiveIn(this);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700623 // Add in current LiveIn
624 Live |= LiveIn;
625 // Check result, set LiveIn=Live
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700626 SizeT &PrevNumNonDeadPhis = Liveness->getNumNonDeadPhis(this);
627 bool LiveInChanged = (Live != LiveIn);
628 Changed = (NumNonDeadPhis != PrevNumNonDeadPhis || LiveInChanged);
629 if (LiveInChanged)
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700630 LiveIn = Live;
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700631 PrevNumNonDeadPhis = NumNonDeadPhis;
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700632 return Changed;
633}
634
635// Now that basic liveness is complete, remove dead instructions that
636// were tentatively marked as dead, and compute actual live ranges.
637// It is assumed that within a single basic block, a live range begins
638// at most once and ends at most once. This is certainly true for
639// pure SSA form. It is also true once phis are lowered, since each
640// assignment to the phi-based temporary is in a different basic
641// block, and there is a single read that ends the live in the basic
642// block that contained the actual phi instruction.
643void CfgNode::livenessPostprocess(LivenessMode Mode, Liveness *Liveness) {
644 InstNumberT FirstInstNum = Inst::NumberSentinel;
645 InstNumberT LastInstNum = Inst::NumberSentinel;
646 // Process phis in any order. Process only Dest operands.
Jim Stichnothf44f3712014-10-01 14:05:51 -0700647 for (InstPhi *I : Phis) {
648 I->deleteIfDead();
649 if (I->isDeleted())
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700650 continue;
651 if (FirstInstNum == Inst::NumberSentinel)
Jim Stichnothf44f3712014-10-01 14:05:51 -0700652 FirstInstNum = I->getNumber();
653 assert(I->getNumber() > LastInstNum);
654 LastInstNum = I->getNumber();
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700655 }
656 // Process instructions
Jim Stichnothf44f3712014-10-01 14:05:51 -0700657 for (Inst *I : Insts) {
658 I->deleteIfDead();
659 if (I->isDeleted())
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700660 continue;
661 if (FirstInstNum == Inst::NumberSentinel)
Jim Stichnothf44f3712014-10-01 14:05:51 -0700662 FirstInstNum = I->getNumber();
663 assert(I->getNumber() > LastInstNum);
664 LastInstNum = I->getNumber();
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700665 // Create fake live ranges for a Kill instruction, but only if the
666 // linked instruction is still alive.
667 if (Mode == Liveness_Intervals) {
Jim Stichnothf44f3712014-10-01 14:05:51 -0700668 if (InstFakeKill *Kill = llvm::dyn_cast<InstFakeKill>(I)) {
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700669 if (!Kill->getLinked()->isDeleted()) {
Jim Stichnothf44f3712014-10-01 14:05:51 -0700670 SizeT NumSrcs = I->getSrcSize();
671 for (SizeT Src = 0; Src < NumSrcs; ++Src) {
672 Variable *Var = llvm::cast<Variable>(I->getSrc(Src));
673 InstNumberT InstNumber = I->getNumber();
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700674 Var->addLiveRange(InstNumber, InstNumber, 1);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700675 }
676 }
677 }
678 }
679 }
680 if (Mode != Liveness_Intervals)
681 return;
Jim Stichnothd14b1a02014-10-08 08:28:36 -0700682 TimerMarker T1(TimerStack::TT_liveRangeCtor, Func);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700683
684 SizeT NumVars = Liveness->getNumVarsInNode(this);
Jim Stichnoth47752552014-10-13 17:15:08 -0700685 LivenessBV &LiveIn = Liveness->getLiveIn(this);
686 LivenessBV &LiveOut = Liveness->getLiveOut(this);
687 LiveBeginEndMap &MapBegin = *Liveness->getLiveBegin(this);
688 LiveBeginEndMap &MapEnd = *Liveness->getLiveEnd(this);
689 std::sort(MapBegin.begin(), MapBegin.end());
690 std::sort(MapEnd.begin(), MapEnd.end());
691 // Verify there are no duplicates.
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700692 struct ComparePair {
693 bool operator()(const LiveBeginEndMapEntry &A,
694 const LiveBeginEndMapEntry &B) {
695 return A.first == B.first;
696 }
697 };
698 assert(std::adjacent_find(MapBegin.begin(), MapBegin.end(), ComparePair()) ==
Jim Stichnoth47752552014-10-13 17:15:08 -0700699 MapBegin.end());
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700700 assert(std::adjacent_find(MapEnd.begin(), MapEnd.end(), ComparePair()) ==
Jim Stichnoth47752552014-10-13 17:15:08 -0700701 MapEnd.end());
702
703 LivenessBV LiveInAndOut = LiveIn;
704 LiveInAndOut &= LiveOut;
705
706 // Iterate in parallel across the sorted MapBegin[] and MapEnd[].
707 auto IBB = MapBegin.begin(), IEB = MapEnd.begin();
708 auto IBE = MapBegin.end(), IEE = MapEnd.end();
709 while (IBB != IBE || IEB != IEE) {
710 SizeT i1 = IBB == IBE ? NumVars : IBB->first;
711 SizeT i2 = IEB == IEE ? NumVars : IEB->first;
712 SizeT i = std::min(i1, i2);
713 // i1 is the Variable number of the next MapBegin entry, and i2 is
714 // the Variable number of the next MapEnd entry. If i1==i2, then
715 // the Variable's live range begins and ends in this block. If
716 // i1<i2, then i1's live range begins at instruction IBB->second
717 // and extends through the end of the block. If i1>i2, then i2's
718 // live range begins at the first instruction of the block and
719 // ends at IEB->second. In any case, we choose the lesser of i1
720 // and i2 and proceed accordingly.
721 InstNumberT LB = i == i1 ? IBB->second : FirstInstNum;
722 InstNumberT LE = i == i2 ? IEB->second : LastInstNum + 1;
723
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700724 Variable *Var = Liveness->getVariable(i, this);
Jim Stichnoth47752552014-10-13 17:15:08 -0700725 if (!Var->getIgnoreLiveness()) {
726 if (LB > LE) {
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700727 Var->addLiveRange(FirstInstNum, LE, 1);
728 Var->addLiveRange(LB, LastInstNum + 1, 1);
Jim Stichnoth47752552014-10-13 17:15:08 -0700729 // Assert that Var is a global variable by checking that its
730 // liveness index is less than the number of globals. This
731 // ensures that the LiveInAndOut[] access is valid.
732 assert(i < Liveness->getNumGlobalVars());
733 LiveInAndOut[i] = false;
734 } else {
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700735 Var->addLiveRange(LB, LE, 1);
Jim Stichnoth47752552014-10-13 17:15:08 -0700736 }
737 }
738 if (i == i1)
739 ++IBB;
740 if (i == i2)
741 ++IEB;
742 }
743 // Process the variables that are live across the entire block.
744 for (int i = LiveInAndOut.find_first(); i != -1;
745 i = LiveInAndOut.find_next(i)) {
746 Variable *Var = Liveness->getVariable(i, this);
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700747 Var->addLiveRange(FirstInstNum, LastInstNum + 1, 1);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700748 }
749}
750
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700751// If this node contains only deleted instructions, and ends in an
752// unconditional branch, contract the node by repointing all its
753// in-edges to its successor.
754void CfgNode::contractIfEmpty() {
755 if (InEdges.size() == 0)
756 return;
757 Inst *Branch = NULL;
758 for (Inst *I : Insts) {
Jim Stichnoth3d44fe82014-11-01 10:10:18 -0700759 if (I->isDeleted())
760 continue;
761 if (I->isUnconditionalBranch())
762 Branch = I;
763 else if (!I->isRedundantAssign())
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700764 return;
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700765 }
766 Branch->setDeleted();
767 assert(OutEdges.size() == 1);
768 // Repoint all this node's in-edges to this node's successor.
769 for (CfgNode *Pred : InEdges) {
770 for (auto I = Pred->OutEdges.begin(), E = Pred->OutEdges.end(); I != E;
771 ++I) {
772 if (*I == this) {
773 *I = OutEdges[0];
774 OutEdges[0]->InEdges.push_back(Pred);
775 }
776 }
777 for (Inst *I : Pred->getInsts()) {
778 if (!I->isDeleted())
779 I->repointEdge(this, OutEdges[0]);
780 }
781 }
782 InEdges.clear();
783 // Don't bother removing the single out-edge, which would also
784 // require finding the corresponding in-edge in the successor and
785 // removing it.
786}
787
Jim Stichnothff9c7062014-09-18 04:50:49 -0700788void CfgNode::doBranchOpt(const CfgNode *NextNode) {
789 TargetLowering *Target = Func->getTarget();
790 // Check every instruction for a branch optimization opportunity.
791 // It may be more efficient to iterate in reverse and stop after the
792 // first opportunity, unless there is some target lowering where we
793 // have the possibility of multiple such optimizations per block
794 // (currently not the case for x86 lowering).
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700795 for (Inst *I : Insts) {
796 if (!I->isDeleted()) {
797 Target->doBranchOpt(I, NextNode);
798 }
799 }
Jim Stichnothff9c7062014-09-18 04:50:49 -0700800}
801
Jim Stichnothf7c9a142014-04-29 10:52:43 -0700802// ======================== Dump routines ======================== //
803
Jim Stichnoth3d44fe82014-11-01 10:10:18 -0700804namespace {
805
806// Helper functions for emit().
807
808void emitRegisterUsage(Ostream &Str, const Cfg *Func, const CfgNode *Node,
809 bool IsLiveIn, std::vector<SizeT> &LiveRegCount) {
810 Liveness *Liveness = Func->getLiveness();
811 const LivenessBV *Live;
812 if (IsLiveIn) {
813 Live = &Liveness->getLiveIn(Node);
814 Str << "\t\t\t\t# LiveIn=";
815 } else {
816 Live = &Liveness->getLiveOut(Node);
817 Str << "\t\t\t\t# LiveOut=";
818 }
819 if (!Live->empty()) {
820 bool First = true;
821 for (SizeT i = 0; i < Live->size(); ++i) {
822 if ((*Live)[i]) {
823 Variable *Var = Liveness->getVariable(i, Node);
824 if (Var->hasReg()) {
825 if (IsLiveIn)
826 ++LiveRegCount[Var->getRegNum()];
827 if (!First)
828 Str << ",";
829 First = false;
830 Var->emit(Func);
831 }
832 }
833 }
834 }
835 Str << "\n";
836}
837
838void emitLiveRangesEnded(Ostream &Str, const Cfg *Func, const Inst *Instr,
839 std::vector<SizeT> &LiveRegCount) {
840 bool First = true;
841 Variable *Dest = Instr->getDest();
842 if (Dest && Dest->hasReg())
843 ++LiveRegCount[Dest->getRegNum()];
844 for (SizeT I = 0; I < Instr->getSrcSize(); ++I) {
845 Operand *Src = Instr->getSrc(I);
846 SizeT NumVars = Src->getNumVars();
847 for (SizeT J = 0; J < NumVars; ++J) {
848 const Variable *Var = Src->getVar(J);
849 if (Var->hasReg()) {
850 if (Instr->isLastUse(Var) &&
851 --LiveRegCount[Var->getRegNum()] == 0) {
852 if (First)
853 Str << " \t# END=";
854 else
855 Str << ",";
856 Var->emit(Func);
857 First = false;
858 }
859 }
860 }
861 }
862}
863
864} // end of anonymous namespace
865
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700866void CfgNode::emit(Cfg *Func) const {
867 Func->setCurrentNode(this);
868 Ostream &Str = Func->getContext()->getStrEmit();
Jim Stichnoth3d44fe82014-11-01 10:10:18 -0700869 Liveness *Liveness = Func->getLiveness();
870 bool DecorateAsm = Liveness && Func->getContext()->getFlags().DecorateAsm;
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700871 if (Func->getEntryNode() == this) {
872 Str << Func->getContext()->mangleName(Func->getFunctionName()) << ":\n";
873 }
874 Str << getAsmName() << ":\n";
Jan Voung7e1e4852014-10-24 10:29:30 -0700875 if (Func->useIntegratedAssembler()) {
876 Assembler *Asm = Func->getAssembler<Assembler>();
877 Asm->BindCfgNodeLabel(getIndex());
878 }
Jim Stichnoth3d44fe82014-11-01 10:10:18 -0700879 std::vector<SizeT> LiveRegCount(Func->getTarget()->getNumRegisters());
880 if (DecorateAsm)
881 emitRegisterUsage(Str, Func, this, true, LiveRegCount);
882
Jim Stichnothf44f3712014-10-01 14:05:51 -0700883 for (InstPhi *Phi : Phis) {
Jim Stichnothb56c8f42014-09-26 09:28:46 -0700884 if (Phi->isDeleted())
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700885 continue;
886 // Emitting a Phi instruction should cause an error.
Jim Stichnothb56c8f42014-09-26 09:28:46 -0700887 Inst *Instr = Phi;
888 Instr->emit(Func);
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700889 }
Jim Stichnothf44f3712014-10-01 14:05:51 -0700890 for (Inst *I : Insts) {
891 if (I->isDeleted())
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700892 continue;
Jim Stichnoth3d44fe82014-11-01 10:10:18 -0700893 if (I->isRedundantAssign()) {
894 Variable *Dest = I->getDest();
895 if (DecorateAsm && Dest->hasReg() && !I->isLastUse(I->getSrc(0)))
896 ++LiveRegCount[Dest->getRegNum()];
897 continue;
898 }
Jan Voung7e1e4852014-10-24 10:29:30 -0700899 if (Func->useIntegratedAssembler()) {
Jim Stichnothf44f3712014-10-01 14:05:51 -0700900 I->emitIAS(Func);
Jan Voung8acded02014-09-22 18:02:25 -0700901 } else {
Jim Stichnothf44f3712014-10-01 14:05:51 -0700902 I->emit(Func);
Jim Stichnoth3d44fe82014-11-01 10:10:18 -0700903 if (DecorateAsm)
904 emitLiveRangesEnded(Str, Func, I, LiveRegCount);
Jim Stichnoth120b4122014-10-27 09:51:55 -0700905 Str << "\n";
Jan Voung8acded02014-09-22 18:02:25 -0700906 }
Jim Stichnoth18735602014-09-16 19:59:35 -0700907 // Update emitted instruction count, plus fill/spill count for
908 // Variable operands without a physical register.
Jim Stichnothf44f3712014-10-01 14:05:51 -0700909 if (uint32_t Count = I->getEmitInstCount()) {
Jim Stichnoth18735602014-09-16 19:59:35 -0700910 Func->getContext()->statsUpdateEmitted(Count);
Jim Stichnothf44f3712014-10-01 14:05:51 -0700911 if (Variable *Dest = I->getDest()) {
Jim Stichnoth18735602014-09-16 19:59:35 -0700912 if (!Dest->hasReg())
913 Func->getContext()->statsUpdateFills();
914 }
Jim Stichnothf44f3712014-10-01 14:05:51 -0700915 for (SizeT S = 0; S < I->getSrcSize(); ++S) {
916 if (Variable *Src = llvm::dyn_cast<Variable>(I->getSrc(S))) {
Jim Stichnoth18735602014-09-16 19:59:35 -0700917 if (!Src->hasReg())
918 Func->getContext()->statsUpdateSpills();
919 }
920 }
921 }
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700922 }
Jim Stichnoth3d44fe82014-11-01 10:10:18 -0700923 if (DecorateAsm)
924 emitRegisterUsage(Str, Func, this, false, LiveRegCount);
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700925}
926
Jim Stichnothf7c9a142014-04-29 10:52:43 -0700927void CfgNode::dump(Cfg *Func) const {
928 Func->setCurrentNode(this);
929 Ostream &Str = Func->getContext()->getStrDump();
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700930 Liveness *Liveness = Func->getLiveness();
Jim Stichnothf7c9a142014-04-29 10:52:43 -0700931 if (Func->getContext()->isVerbose(IceV_Instructions)) {
932 Str << getName() << ":\n";
933 }
934 // Dump list of predecessor nodes.
935 if (Func->getContext()->isVerbose(IceV_Preds) && !InEdges.empty()) {
936 Str << " // preds = ";
Jim Stichnothf44f3712014-10-01 14:05:51 -0700937 bool First = true;
938 for (CfgNode *I : InEdges) {
Jim Stichnoth8363a062014-10-07 10:02:38 -0700939 if (!First)
Jim Stichnothf7c9a142014-04-29 10:52:43 -0700940 Str << ", ";
Jim Stichnothf44f3712014-10-01 14:05:51 -0700941 First = false;
942 Str << "%" << I->getName();
Jim Stichnothf7c9a142014-04-29 10:52:43 -0700943 }
944 Str << "\n";
945 }
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700946 // Dump the live-in variables.
Jim Stichnoth47752552014-10-13 17:15:08 -0700947 LivenessBV LiveIn;
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700948 if (Liveness)
949 LiveIn = Liveness->getLiveIn(this);
950 if (Func->getContext()->isVerbose(IceV_Liveness) && !LiveIn.empty()) {
951 Str << " // LiveIn:";
952 for (SizeT i = 0; i < LiveIn.size(); ++i) {
953 if (LiveIn[i]) {
Jim Stichnoth088b2be2014-10-23 12:02:08 -0700954 Variable *Var = Liveness->getVariable(i, this);
955 Str << " %" << Var->getName();
956 if (Func->getContext()->isVerbose(IceV_RegOrigins) && Var->hasReg()) {
957 Str << ":" << Func->getTarget()->getRegName(Var->getRegNum(),
958 Var->getType());
959 }
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700960 }
961 }
962 Str << "\n";
963 }
Jim Stichnothf7c9a142014-04-29 10:52:43 -0700964 // Dump each instruction.
965 if (Func->getContext()->isVerbose(IceV_Instructions)) {
Jim Stichnothf44f3712014-10-01 14:05:51 -0700966 for (InstPhi *I : Phis)
967 I->dumpDecorated(Func);
968 for (Inst *I : Insts)
969 I->dumpDecorated(Func);
Jim Stichnothf7c9a142014-04-29 10:52:43 -0700970 }
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700971 // Dump the live-out variables.
Jim Stichnoth47752552014-10-13 17:15:08 -0700972 LivenessBV LiveOut;
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700973 if (Liveness)
974 LiveOut = Liveness->getLiveOut(this);
975 if (Func->getContext()->isVerbose(IceV_Liveness) && !LiveOut.empty()) {
976 Str << " // LiveOut:";
977 for (SizeT i = 0; i < LiveOut.size(); ++i) {
978 if (LiveOut[i]) {
Jim Stichnoth088b2be2014-10-23 12:02:08 -0700979 Variable *Var = Liveness->getVariable(i, this);
980 Str << " %" << Var->getName();
981 if (Func->getContext()->isVerbose(IceV_RegOrigins) && Var->hasReg()) {
982 Str << ":" << Func->getTarget()->getRegName(Var->getRegNum(),
983 Var->getType());
984 }
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700985 }
986 }
987 Str << "\n";
988 }
Jim Stichnothf7c9a142014-04-29 10:52:43 -0700989 // Dump list of successor nodes.
990 if (Func->getContext()->isVerbose(IceV_Succs)) {
991 Str << " // succs = ";
Jim Stichnothf44f3712014-10-01 14:05:51 -0700992 bool First = true;
993 for (CfgNode *I : OutEdges) {
Jim Stichnoth8363a062014-10-07 10:02:38 -0700994 if (!First)
Jim Stichnothf7c9a142014-04-29 10:52:43 -0700995 Str << ", ";
Jim Stichnothf44f3712014-10-01 14:05:51 -0700996 First = false;
997 Str << "%" << I->getName();
Jim Stichnothf7c9a142014-04-29 10:52:43 -0700998 }
999 Str << "\n";
1000 }
1001}
1002
1003} // end of namespace Ice