blob: d57224b9f14a2949e5aa5f04061114054eab42eb [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//===----------------------------------------------------------------------===//
Andrew Scull9612d322015-07-06 14:53:25 -07009///
10/// \file
11/// This file implements the CfgNode class, including the complexities
12/// of instruction insertion and in-edge calculation.
13///
Jim Stichnothf7c9a142014-04-29 10:52:43 -070014//===----------------------------------------------------------------------===//
15
John Porto67f8de92015-06-25 10:14:17 -070016#include "IceCfgNode.h"
17
John Portoaff4ccf2015-06-10 16:35:06 -070018#include "IceAssembler.h"
Jim Stichnothf7c9a142014-04-29 10:52:43 -070019#include "IceCfg.h"
John Portof8b4cc82015-06-09 18:06:19 -070020#include "IceGlobalInits.h"
Jim Stichnothf7c9a142014-04-29 10:52:43 -070021#include "IceInst.h"
John Portoec3f5652015-08-31 15:07:09 -070022#include "IceInstVarIter.h"
Jim Stichnothd97c7df2014-06-04 11:57:08 -070023#include "IceLiveness.h"
Jim Stichnothf7c9a142014-04-29 10:52:43 -070024#include "IceOperand.h"
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -070025#include "IceTargetLowering.h"
Jim Stichnothf7c9a142014-04-29 10:52:43 -070026
27namespace Ice {
28
Jim Stichnoth668a7a32014-12-10 15:32:25 -080029CfgNode::CfgNode(Cfg *Func, SizeT LabelNumber)
Jim Stichnotheafb56c2015-06-22 10:35:22 -070030 : Func(Func), Number(LabelNumber) {}
Jim Stichnothf7c9a142014-04-29 10:52:43 -070031
32// Returns the name the node was created with. If no name was given,
33// it synthesizes a (hopefully) unique name.
34IceString CfgNode::getName() const {
Jim Stichnoth668a7a32014-12-10 15:32:25 -080035 if (NameIndex >= 0)
Jim Stichnoth9a04c072014-12-11 15:51:42 -080036 return Func->getIdentifierName(NameIndex);
Jim Stichnoth088b2be2014-10-23 12:02:08 -070037 return "__" + std::to_string(getIndex());
Jim Stichnothf7c9a142014-04-29 10:52:43 -070038}
39
40// Adds an instruction to either the Phi list or the regular
41// instruction list. Validates that all Phis are added before all
42// regular instructions.
43void CfgNode::appendInst(Inst *Inst) {
Jim Stichnoth47752552014-10-13 17:15:08 -070044 ++InstCountEstimate;
Jim Stichnothf7c9a142014-04-29 10:52:43 -070045 if (InstPhi *Phi = llvm::dyn_cast<InstPhi>(Inst)) {
46 if (!Insts.empty()) {
47 Func->setError("Phi instruction added to the middle of a block");
48 return;
49 }
50 Phis.push_back(Phi);
51 } else {
52 Insts.push_back(Inst);
53 }
Jim Stichnothf7c9a142014-04-29 10:52:43 -070054}
55
Jim Stichnothd97c7df2014-06-04 11:57:08 -070056// Renumbers the non-deleted instructions in the node. This needs to
57// be done in preparation for live range analysis. The instruction
58// numbers in a block must be monotonically increasing. The range of
59// instruction numbers in a block, from lowest to highest, must not
60// overlap with the range of any other block.
61void CfgNode::renumberInstructions() {
Jim Stichnoth47752552014-10-13 17:15:08 -070062 InstNumberT FirstNumber = Func->getNextInstNumber();
Jim Stichnoth29841e82014-12-23 12:26:24 -080063 for (Inst &I : Phis)
64 I.renumber(Func);
65 for (Inst &I : Insts)
66 I.renumber(Func);
Jim Stichnoth47752552014-10-13 17:15:08 -070067 InstCountEstimate = Func->getNextInstNumber() - FirstNumber;
Jim Stichnothd97c7df2014-06-04 11:57:08 -070068}
69
Jim Stichnoth088b2be2014-10-23 12:02:08 -070070// When a node is created, the OutEdges are immediately known, but the
Jim Stichnothf7c9a142014-04-29 10:52:43 -070071// InEdges have to be built up incrementally. After the CFG has been
72// constructed, the computePredecessors() pass finalizes it by
73// creating the InEdges list.
74void CfgNode::computePredecessors() {
Jim Stichnothf44f3712014-10-01 14:05:51 -070075 for (CfgNode *Succ : OutEdges)
76 Succ->InEdges.push_back(this);
Jim Stichnothf7c9a142014-04-29 10:52:43 -070077}
78
Jim Stichnoth69d3f9c2015-03-23 10:33:38 -070079void CfgNode::computeSuccessors() {
80 OutEdges = Insts.rbegin()->getTerminatorEdges();
81}
82
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -070083// This does part 1 of Phi lowering, by creating a new dest variable
84// for each Phi instruction, replacing the Phi instruction's dest with
85// that variable, and adding an explicit assignment of the old dest to
86// the new dest. For example,
87// a=phi(...)
88// changes to
89// "a_phi=phi(...); a=a_phi".
90//
91// This is in preparation for part 2 which deletes the Phi
92// instructions and appends assignment instructions to predecessor
93// blocks. Note that this transformation preserves SSA form.
94void CfgNode::placePhiLoads() {
Jim Stichnoth29841e82014-12-23 12:26:24 -080095 for (Inst &I : Phis) {
96 auto Phi = llvm::dyn_cast<InstPhi>(&I);
Jim Stichnoth1502e592014-12-11 09:22:45 -080097 Insts.insert(Insts.begin(), Phi->lower(Func));
98 }
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -070099}
100
101// This does part 2 of Phi lowering. For each Phi instruction at each
102// out-edge, create a corresponding assignment instruction, and add
103// all the assignments near the end of this block. They need to be
104// added before any branch instruction, and also if the block ends
105// with a compare instruction followed by a branch instruction that we
106// may want to fuse, it's better to insert the new assignments before
Jan Voungc820ddf2014-07-29 14:38:51 -0700107// the compare instruction. The tryOptimizedCmpxchgCmpBr() method
108// assumes this ordering of instructions.
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700109//
110// Note that this transformation takes the Phi dest variables out of
111// SSA form, as there may be assignments to the dest variable in
112// multiple blocks.
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700113void CfgNode::placePhiStores() {
Jim Stichnothe5a5be72014-09-10 11:51:38 -0700114 // Find the insertion point.
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700115 InstList::iterator InsertionPoint = Insts.end();
Jim Stichnothe5a5be72014-09-10 11:51:38 -0700116 // Every block must end in a terminator instruction, and therefore
117 // must have at least one instruction, so it's valid to decrement
118 // InsertionPoint (but assert just in case).
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700119 assert(InsertionPoint != Insts.begin());
120 --InsertionPoint;
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700121 // Confirm that InsertionPoint is a terminator instruction. Calling
122 // getTerminatorEdges() on a non-terminator instruction will cause
123 // an llvm_unreachable().
Jim Stichnoth607e9f02014-11-06 13:32:05 -0800124 (void)InsertionPoint->getTerminatorEdges();
Jim Stichnothe5a5be72014-09-10 11:51:38 -0700125 // SafeInsertionPoint is always immediately before the terminator
126 // instruction. If the block ends in a compare and conditional
127 // branch, it's better to place the Phi store before the compare so
128 // as not to interfere with compare/branch fusing. However, if the
129 // compare instruction's dest operand is the same as the new
130 // assignment statement's source operand, this can't be done due to
131 // data dependences, so we need to fall back to the
132 // SafeInsertionPoint. To illustrate:
133 // ; <label>:95
134 // %97 = load i8* %96, align 1
135 // %98 = icmp ne i8 %97, 0
136 // br i1 %98, label %99, label %2132
137 // ; <label>:99
138 // %100 = phi i8 [ %97, %95 ], [ %110, %108 ]
139 // %101 = phi i1 [ %98, %95 ], [ %111, %108 ]
140 // would be Phi-lowered as:
141 // ; <label>:95
142 // %97 = load i8* %96, align 1
143 // %100_phi = %97 ; can be at InsertionPoint
144 // %98 = icmp ne i8 %97, 0
145 // %101_phi = %98 ; must be at SafeInsertionPoint
146 // br i1 %98, label %99, label %2132
147 // ; <label>:99
148 // %100 = %100_phi
149 // %101 = %101_phi
150 //
151 // TODO(stichnot): It may be possible to bypass this whole
152 // SafeInsertionPoint mechanism. If a source basic block ends in a
153 // conditional branch:
154 // labelSource:
155 // ...
156 // br i1 %foo, label %labelTrue, label %labelFalse
157 // and a branch target has a Phi involving the branch operand:
158 // labelTrue:
159 // %bar = phi i1 [ %foo, %labelSource ], ...
160 // then we actually know the constant i1 value of the Phi operand:
161 // labelTrue:
162 // %bar = phi i1 [ true, %labelSource ], ...
163 // It seems that this optimization should be done by clang or opt,
164 // but we could also do it here.
165 InstList::iterator SafeInsertionPoint = InsertionPoint;
166 // Keep track of the dest variable of a compare instruction, so that
167 // we insert the new instruction at the SafeInsertionPoint if the
168 // compare's dest matches the Phi-lowered assignment's source.
Jim Stichnothae953202014-12-20 06:17:49 -0800169 Variable *CmpInstDest = nullptr;
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700170 // If the current insertion point is at a conditional branch
171 // instruction, and the previous instruction is a compare
172 // instruction, then we move the insertion point before the compare
173 // instruction so as not to interfere with compare/branch fusing.
Jim Stichnoth607e9f02014-11-06 13:32:05 -0800174 if (InstBr *Branch = llvm::dyn_cast<InstBr>(InsertionPoint)) {
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700175 if (!Branch->isUnconditional()) {
176 if (InsertionPoint != Insts.begin()) {
177 --InsertionPoint;
Jim Stichnoth607e9f02014-11-06 13:32:05 -0800178 if (llvm::isa<InstIcmp>(InsertionPoint) ||
179 llvm::isa<InstFcmp>(InsertionPoint)) {
180 CmpInstDest = InsertionPoint->getDest();
Jim Stichnothe5a5be72014-09-10 11:51:38 -0700181 } else {
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700182 ++InsertionPoint;
183 }
184 }
185 }
186 }
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700187
188 // Consider every out-edge.
Jim Stichnothf44f3712014-10-01 14:05:51 -0700189 for (CfgNode *Succ : OutEdges) {
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700190 // Consider every Phi instruction at the out-edge.
Jim Stichnoth29841e82014-12-23 12:26:24 -0800191 for (Inst &I : Succ->Phis) {
192 auto Phi = llvm::dyn_cast<InstPhi>(&I);
Jim Stichnoth1502e592014-12-11 09:22:45 -0800193 Operand *Operand = Phi->getOperandForTarget(this);
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700194 assert(Operand);
Jim Stichnoth29841e82014-12-23 12:26:24 -0800195 Variable *Dest = I.getDest();
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700196 assert(Dest);
197 InstAssign *NewInst = InstAssign::create(Func, Dest, Operand);
Jim Stichnothe5a5be72014-09-10 11:51:38 -0700198 if (CmpInstDest == Operand)
199 Insts.insert(SafeInsertionPoint, NewInst);
200 else
201 Insts.insert(InsertionPoint, NewInst);
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700202 }
203 }
204}
205
206// Deletes the phi instructions after the loads and stores are placed.
207void CfgNode::deletePhis() {
Jim Stichnoth29841e82014-12-23 12:26:24 -0800208 for (Inst &I : Phis)
209 I.setDeleted();
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700210}
211
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700212// Splits the edge from Pred to this node by creating a new node and
213// hooking up the in and out edges appropriately. (The EdgeIndex
214// parameter is only used to make the new node's name unique when
215// there are multiple edges between the same pair of nodes.) The new
216// node's instruction list is initialized to the empty list, with no
Andrew Scull87f80c12015-07-20 10:19:16 -0700217// terminator instruction. There must not be multiple edges from Pred
218// to this node so all Inst::getTerminatorEdges implementations must
219// not contain duplicates.
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700220CfgNode *CfgNode::splitIncomingEdge(CfgNode *Pred, SizeT EdgeIndex) {
Jim Stichnoth668a7a32014-12-10 15:32:25 -0800221 CfgNode *NewNode = Func->makeNode();
Andrew Scullaa6c1092015-09-03 17:50:30 -0700222 // Depth is the minimum as it works if both are the same, but if one is
223 // outside the loop and the other is inside, the new node should be placed
224 // outside and not be executed multiple times within the loop.
225 NewNode->setLoopNestDepth(
226 std::min(getLoopNestDepth(), Pred->getLoopNestDepth()));
Jim Stichnoth20b71f52015-06-24 15:52:24 -0700227 if (BuildDefs::dump())
Jim Stichnoth668a7a32014-12-10 15:32:25 -0800228 NewNode->setName("split_" + Pred->getName() + "_" + getName() + "_" +
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700229 std::to_string(EdgeIndex));
230 // The new node is added to the end of the node list, and will later
231 // need to be sorted into a reasonable topological order.
232 NewNode->setNeedsPlacement(true);
233 // Repoint Pred's out-edge.
234 bool Found = false;
Andrew Scull87f80c12015-07-20 10:19:16 -0700235 for (CfgNode *&I : Pred->OutEdges) {
236 if (I == this) {
237 I = NewNode;
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700238 NewNode->InEdges.push_back(Pred);
239 Found = true;
Andrew Scull87f80c12015-07-20 10:19:16 -0700240 break;
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700241 }
242 }
243 assert(Found);
Jim Stichnotha8d47132015-09-08 14:43:38 -0700244 (void)Found;
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700245 // Repoint this node's in-edge.
246 Found = false;
Andrew Scull87f80c12015-07-20 10:19:16 -0700247 for (CfgNode *&I : InEdges) {
248 if (I == Pred) {
249 I = NewNode;
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700250 NewNode->OutEdges.push_back(this);
251 Found = true;
Andrew Scull87f80c12015-07-20 10:19:16 -0700252 break;
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700253 }
254 }
255 assert(Found);
Jim Stichnotha8d47132015-09-08 14:43:38 -0700256 (void)Found;
Andrew Scull87f80c12015-07-20 10:19:16 -0700257 // Repoint all suitable branch instructions' target and return.
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700258 Found = false;
Andrew Scull87f80c12015-07-20 10:19:16 -0700259 for (Inst &I : Pred->getInsts())
260 if (!I.isDeleted() && I.repointEdges(this, NewNode))
261 Found = true;
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700262 assert(Found);
Jim Stichnotha8d47132015-09-08 14:43:38 -0700263 (void)Found;
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700264 return NewNode;
265}
266
267namespace {
268
269// Helper function used by advancedPhiLowering().
270bool sameVarOrReg(const Variable *Var, const Operand *Opnd) {
271 if (Var == Opnd)
272 return true;
273 if (const auto Var2 = llvm::dyn_cast<Variable>(Opnd)) {
274 if (Var->hasReg() && Var->getRegNum() == Var2->getRegNum())
275 return true;
276 }
277 return false;
278}
279
280} // end of anonymous namespace
281
Jim Stichnotha3f57b92015-07-30 12:46:04 -0700282// This the "advanced" version of Phi lowering for a basic block, in contrast to
283// the simple version that lowers through assignments involving temporaries.
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700284//
Jim Stichnotha3f57b92015-07-30 12:46:04 -0700285// All Phi instructions in a basic block are conceptually executed in parallel.
286// However, if we lower Phis early and commit to a sequential ordering, we may
287// end up creating unnecessary interferences which lead to worse register
288// allocation. Delaying Phi scheduling until after register allocation can help
289// unless there are no free registers for shuffling registers or stack slots and
290// spilling becomes necessary.
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700291//
Jim Stichnotha3f57b92015-07-30 12:46:04 -0700292// The advanced Phi lowering starts by finding a topological sort of the Phi
293// instructions, where "A=B" comes before "B=C" due to the anti-dependence on B.
294// Preexisting register assignments are considered in the topological sort. If
295// a topological sort is not possible due to a cycle, the cycle is broken by
296// introducing a non-parallel temporary. For example, a cycle arising from a
297// permutation like "A=B;B=C;C=A" can become "T=A;A=B;B=C;C=T". All else being
298// equal, prefer to schedule assignments with register-allocated Src operands
299// earlier, in case that register becomes free afterwards, and prefer to
300// schedule assignments with register-allocated Dest variables later, to keep
301// that register free for longer.
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700302//
Jim Stichnotha3f57b92015-07-30 12:46:04 -0700303// Once the ordering is determined, the Cfg edge is split and the assignment
304// list is lowered by the target lowering layer. Since the assignment lowering
305// may create new infinite-weight temporaries, a follow-on register allocation
306// pass will be needed. To prepare for this, liveness (including live range
307// calculation) of the split nodes needs to be calculated, and liveness of the
308// original node need to be updated to "undo" the effects of the phi
309// assignments.
310
311// The specific placement of the new node within the Cfg node list is deferred
312// until later, including after empty node contraction.
313//
314// After phi assignments are lowered across all blocks, another register
315// allocation pass is run, focusing only on pre-colored and infinite-weight
316// variables, similar to Om1 register allocation (except without the need to
317// specially compute these variables' live ranges, since they have already been
318// precisely calculated). The register allocator in this mode needs the ability
319// to forcibly spill and reload registers in case none are naturally available.
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700320void CfgNode::advancedPhiLowering() {
321 if (getPhis().empty())
322 return;
323
324 // Count the number of non-deleted Phi instructions.
JF Bastienf2e93b62015-01-22 14:30:57 -0800325 struct PhiDesc {
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700326 InstPhi *Phi;
327 Variable *Dest;
328 Operand *Src;
329 bool Processed;
330 size_t NumPred; // number of entries whose Src is this Dest
331 int32_t Weight; // preference for topological order
JF Bastienf2e93b62015-01-22 14:30:57 -0800332 };
333 llvm::SmallVector<PhiDesc, 32> Desc(getPhis().size());
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700334
335 size_t NumPhis = 0;
Jim Stichnoth29841e82014-12-23 12:26:24 -0800336 for (Inst &I : Phis) {
Jim Stichnotha3f57b92015-07-30 12:46:04 -0700337 auto *Inst = llvm::dyn_cast<InstPhi>(&I);
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700338 if (!Inst->isDeleted()) {
Jim Stichnotha3f57b92015-07-30 12:46:04 -0700339 Variable *Dest = Inst->getDest();
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700340 Desc[NumPhis].Phi = Inst;
Jim Stichnotha3f57b92015-07-30 12:46:04 -0700341 Desc[NumPhis].Dest = Dest;
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700342 ++NumPhis;
Jim Stichnotha3f57b92015-07-30 12:46:04 -0700343 // Undo the effect of the phi instruction on this node's live-in set by
344 // marking the phi dest variable as live on entry.
345 SizeT VarNum = Func->getLiveness()->getLiveIndex(Dest->getIndex());
346 assert(!Func->getLiveness()->getLiveIn(this)[VarNum]);
347 Func->getLiveness()->getLiveIn(this)[VarNum] = true;
348 Inst->setDeleted();
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700349 }
350 }
351 if (NumPhis == 0)
352 return;
353
354 SizeT InEdgeIndex = 0;
355 for (CfgNode *Pred : InEdges) {
356 CfgNode *Split = splitIncomingEdge(Pred, InEdgeIndex++);
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700357 SizeT Remaining = NumPhis;
358
359 // First pass computes Src and initializes NumPred.
360 for (size_t I = 0; I < NumPhis; ++I) {
361 Variable *Dest = Desc[I].Dest;
362 Operand *Src = Desc[I].Phi->getOperandForTarget(Pred);
363 Desc[I].Src = Src;
364 Desc[I].Processed = false;
365 Desc[I].NumPred = 0;
366 // Cherry-pick any trivial assignments, so that they don't
367 // contribute to the running complexity of the topological sort.
368 if (sameVarOrReg(Dest, Src)) {
369 Desc[I].Processed = true;
370 --Remaining;
371 if (Dest != Src)
372 // If Dest and Src are syntactically the same, don't bother
373 // adding the assignment, because in all respects it would
374 // be redundant, and if Dest/Src are on the stack, the
375 // target lowering may naively decide to lower it using a
376 // temporary register.
Jim Stichnotha3f57b92015-07-30 12:46:04 -0700377 Split->appendInst(InstAssign::create(Func, Dest, Src));
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700378 }
379 }
380 // Second pass computes NumPred by comparing every pair of Phi
381 // instructions.
382 for (size_t I = 0; I < NumPhis; ++I) {
383 if (Desc[I].Processed)
384 continue;
385 const Variable *Dest = Desc[I].Dest;
386 for (size_t J = 0; J < NumPhis; ++J) {
387 if (Desc[J].Processed)
388 continue;
389 if (I != J) {
390 // There shouldn't be two Phis with the same Dest variable
391 // or register.
392 assert(!sameVarOrReg(Dest, Desc[J].Dest));
393 }
394 const Operand *Src = Desc[J].Src;
395 if (sameVarOrReg(Dest, Src))
396 ++Desc[I].NumPred;
397 }
398 }
399
400 // Another pass to compute initial Weight values.
401
402 // Always pick NumPred=0 over NumPred>0.
Jim Stichnotha3f57b92015-07-30 12:46:04 -0700403 constexpr int32_t WeightNoPreds = 4;
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700404 // Prefer Src as a register because the register might free up.
Jim Stichnotha3f57b92015-07-30 12:46:04 -0700405 constexpr int32_t WeightSrcIsReg = 2;
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700406 // Prefer Dest not as a register because the register stays free
407 // longer.
Jim Stichnotha3f57b92015-07-30 12:46:04 -0700408 constexpr int32_t WeightDestNotReg = 1;
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700409
410 for (size_t I = 0; I < NumPhis; ++I) {
411 if (Desc[I].Processed)
412 continue;
413 int32_t Weight = 0;
414 if (Desc[I].NumPred == 0)
415 Weight += WeightNoPreds;
416 if (auto Var = llvm::dyn_cast<Variable>(Desc[I].Src))
417 if (Var->hasReg())
418 Weight += WeightSrcIsReg;
419 if (!Desc[I].Dest->hasReg())
420 Weight += WeightDestNotReg;
421 Desc[I].Weight = Weight;
422 }
423
424 // Repeatedly choose and process the best candidate in the
425 // topological sort, until no candidates remain. This
426 // implementation is O(N^2) where N is the number of Phi
427 // instructions, but with a small constant factor compared to a
428 // likely implementation of O(N) topological sort.
429 for (; Remaining; --Remaining) {
430 size_t BestIndex = 0;
431 int32_t BestWeight = -1;
432 // Find the best candidate.
433 for (size_t I = 0; I < NumPhis; ++I) {
434 if (Desc[I].Processed)
435 continue;
436 int32_t Weight = 0;
437 Weight = Desc[I].Weight;
438 if (Weight > BestWeight) {
439 BestIndex = I;
440 BestWeight = Weight;
441 }
442 }
443 assert(BestWeight >= 0);
444 assert(Desc[BestIndex].NumPred <= 1);
445 Variable *Dest = Desc[BestIndex].Dest;
446 Operand *Src = Desc[BestIndex].Src;
447 assert(!sameVarOrReg(Dest, Src));
448 // Break a cycle by introducing a temporary.
449 if (Desc[BestIndex].NumPred) {
450 bool Found = false;
451 // If the target instruction "A=B" is part of a cycle, find
452 // the "X=A" assignment in the cycle because it will have to
453 // be rewritten as "X=tmp".
454 for (size_t J = 0; !Found && J < NumPhis; ++J) {
455 if (Desc[J].Processed)
456 continue;
457 Operand *OtherSrc = Desc[J].Src;
458 if (Desc[J].NumPred && sameVarOrReg(Dest, OtherSrc)) {
459 SizeT VarNum = Func->getNumVariables();
Jim Stichnoth9a04c072014-12-11 15:51:42 -0800460 Variable *Tmp = Func->makeVariable(OtherSrc->getType());
Jim Stichnoth20b71f52015-06-24 15:52:24 -0700461 if (BuildDefs::dump())
Jim Stichnoth9a04c072014-12-11 15:51:42 -0800462 Tmp->setName(Func, "__split_" + std::to_string(VarNum));
Jim Stichnotha3f57b92015-07-30 12:46:04 -0700463 Split->appendInst(InstAssign::create(Func, Tmp, OtherSrc));
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700464 Desc[J].Src = Tmp;
465 Found = true;
466 }
467 }
468 assert(Found);
469 }
470 // Now that a cycle (if any) has been broken, create the actual
471 // assignment.
Jim Stichnotha3f57b92015-07-30 12:46:04 -0700472 Split->appendInst(InstAssign::create(Func, Dest, Src));
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700473 // Update NumPred for all Phi assignments using this Phi's Src
474 // as their Dest variable. Also update Weight if NumPred
475 // dropped from 1 to 0.
476 if (auto Var = llvm::dyn_cast<Variable>(Src)) {
477 for (size_t I = 0; I < NumPhis; ++I) {
478 if (Desc[I].Processed)
479 continue;
480 if (sameVarOrReg(Var, Desc[I].Dest)) {
481 if (--Desc[I].NumPred == 0)
482 Desc[I].Weight += WeightNoPreds;
483 }
484 }
485 }
486 Desc[BestIndex].Processed = true;
487 }
Jim Stichnotha3f57b92015-07-30 12:46:04 -0700488 Split->appendInst(InstBr::create(Func, this));
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700489
Jim Stichnotha3f57b92015-07-30 12:46:04 -0700490 Split->genCode();
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700491 Func->getVMetadata()->addNode(Split);
492 }
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700493}
494
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700495// Does address mode optimization. Pass each instruction to the
496// TargetLowering object. If it returns a new instruction
497// (representing the optimized address mode), then insert the new
498// instruction and delete the old.
499void CfgNode::doAddressOpt() {
500 TargetLowering *Target = Func->getTarget();
501 LoweringContext &Context = Target->getContext();
502 Context.init(this);
503 while (!Context.atEnd()) {
504 Target->doAddressOpt();
505 }
506}
507
Qining Luaee5fa82015-08-20 14:59:03 -0700508void CfgNode::doNopInsertion(RandomNumberGenerator &RNG) {
Matt Walac3302742014-08-15 16:21:56 -0700509 TargetLowering *Target = Func->getTarget();
510 LoweringContext &Context = Target->getContext();
511 Context.init(this);
Qining Lu969f6a32015-07-31 09:58:34 -0700512 Context.setInsertPoint(Context.getCur());
513 // Do not insert nop in bundle locked instructions.
514 bool PauseNopInsertion = false;
Matt Walac3302742014-08-15 16:21:56 -0700515 while (!Context.atEnd()) {
Qining Lu969f6a32015-07-31 09:58:34 -0700516 if (llvm::isa<InstBundleLock>(Context.getCur())) {
517 PauseNopInsertion = true;
518 } else if (llvm::isa<InstBundleUnlock>(Context.getCur())) {
519 PauseNopInsertion = false;
520 }
521 if (!PauseNopInsertion)
Qining Luaee5fa82015-08-20 14:59:03 -0700522 Target->doNopInsertion(RNG);
Matt Walac3302742014-08-15 16:21:56 -0700523 // Ensure Cur=Next, so that the nops are inserted before the current
524 // instruction rather than after.
Matt Walac3302742014-08-15 16:21:56 -0700525 Context.advanceCur();
Qining Lu969f6a32015-07-31 09:58:34 -0700526 Context.advanceNext();
Matt Walac3302742014-08-15 16:21:56 -0700527 }
Matt Walac3302742014-08-15 16:21:56 -0700528}
529
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700530// Drives the target lowering. Passes the current instruction and the
531// next non-deleted instruction for target lowering.
532void CfgNode::genCode() {
533 TargetLowering *Target = Func->getTarget();
534 LoweringContext &Context = Target->getContext();
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700535 // Lower the regular instructions.
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700536 Context.init(this);
Jim Stichnotha59ae6f2015-05-17 10:11:41 -0700537 Target->initNodeForLowering(this);
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700538 while (!Context.atEnd()) {
539 InstList::iterator Orig = Context.getCur();
540 if (llvm::isa<InstRet>(*Orig))
541 setHasReturn();
542 Target->lower();
543 // Ensure target lowering actually moved the cursor.
544 assert(Context.getCur() != Orig);
545 }
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700546 // Do preliminary lowering of the Phi instructions.
547 Target->prelowerPhis();
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700548}
549
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700550void CfgNode::livenessLightweight() {
551 SizeT NumVars = Func->getNumVariables();
Jim Stichnoth47752552014-10-13 17:15:08 -0700552 LivenessBV Live(NumVars);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700553 // Process regular instructions in reverse order.
Jim Stichnoth7e571362015-01-09 11:43:26 -0800554 for (Inst &I : reverse_range(Insts)) {
555 if (I.isDeleted())
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700556 continue;
Jim Stichnoth7e571362015-01-09 11:43:26 -0800557 I.livenessLightweight(Func, Live);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700558 }
Jim Stichnoth29841e82014-12-23 12:26:24 -0800559 for (Inst &I : Phis) {
560 if (I.isDeleted())
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700561 continue;
Jim Stichnoth29841e82014-12-23 12:26:24 -0800562 I.livenessLightweight(Func, Live);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700563 }
564}
565
566// Performs liveness analysis on the block. Returns true if the
567// incoming liveness changed from before, false if it stayed the same.
568// (If it changes, the node's predecessors need to be processed
569// again.)
570bool CfgNode::liveness(Liveness *Liveness) {
571 SizeT NumVars = Liveness->getNumVarsInNode(this);
Jim Stichnoth47752552014-10-13 17:15:08 -0700572 LivenessBV Live(NumVars);
Jim Stichnothae953202014-12-20 06:17:49 -0800573 LiveBeginEndMap *LiveBegin = nullptr;
574 LiveBeginEndMap *LiveEnd = nullptr;
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700575 // Mark the beginning and ending of each variable's live range
576 // with the sentinel instruction number 0.
Jim Stichnoth47752552014-10-13 17:15:08 -0700577 if (Liveness->getMode() == Liveness_Intervals) {
578 LiveBegin = Liveness->getLiveBegin(this);
579 LiveEnd = Liveness->getLiveEnd(this);
580 LiveBegin->clear();
581 LiveEnd->clear();
582 // Guess that the number of live ranges beginning is roughly the
583 // number of instructions, and same for live ranges ending.
584 LiveBegin->reserve(getInstCountEstimate());
585 LiveEnd->reserve(getInstCountEstimate());
586 }
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700587 // Initialize Live to be the union of all successors' LiveIn.
Jim Stichnothf44f3712014-10-01 14:05:51 -0700588 for (CfgNode *Succ : OutEdges) {
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700589 Live |= Liveness->getLiveIn(Succ);
590 // Mark corresponding argument of phis in successor as live.
Jim Stichnoth29841e82014-12-23 12:26:24 -0800591 for (Inst &I : Succ->Phis) {
Jim Stichnoth552490c2015-08-05 16:21:42 -0700592 if (I.isDeleted())
593 continue;
Jim Stichnoth29841e82014-12-23 12:26:24 -0800594 auto Phi = llvm::dyn_cast<InstPhi>(&I);
Jim Stichnoth1502e592014-12-11 09:22:45 -0800595 Phi->livenessPhiOperand(Live, this, Liveness);
596 }
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700597 }
598 Liveness->getLiveOut(this) = Live;
599
600 // Process regular instructions in reverse order.
Jim Stichnoth7e571362015-01-09 11:43:26 -0800601 for (Inst &I : reverse_range(Insts)) {
602 if (I.isDeleted())
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700603 continue;
Jim Stichnoth7e571362015-01-09 11:43:26 -0800604 I.liveness(I.getNumber(), Live, Liveness, LiveBegin, LiveEnd);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700605 }
606 // Process phis in forward order so that we can override the
607 // instruction number to be that of the earliest phi instruction in
608 // the block.
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700609 SizeT NumNonDeadPhis = 0;
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700610 InstNumberT FirstPhiNumber = Inst::NumberSentinel;
Jim Stichnoth29841e82014-12-23 12:26:24 -0800611 for (Inst &I : Phis) {
612 if (I.isDeleted())
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700613 continue;
614 if (FirstPhiNumber == Inst::NumberSentinel)
Jim Stichnoth29841e82014-12-23 12:26:24 -0800615 FirstPhiNumber = I.getNumber();
616 if (I.liveness(FirstPhiNumber, Live, Liveness, LiveBegin, LiveEnd))
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700617 ++NumNonDeadPhis;
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700618 }
619
620 // When using the sparse representation, after traversing the
621 // instructions in the block, the Live bitvector should only contain
622 // set bits for global variables upon block entry. We validate this
623 // by shrinking the Live vector and then testing it against the
624 // pre-shrunk version. (The shrinking is required, but the
625 // validation is not.)
Jim Stichnoth47752552014-10-13 17:15:08 -0700626 LivenessBV LiveOrig = Live;
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700627 Live.resize(Liveness->getNumGlobalVars());
Jim Stichnothb3bfcbc2015-08-01 18:46:12 -0700628 if (Live != LiveOrig) {
Jim Stichnoth20b71f52015-06-24 15:52:24 -0700629 if (BuildDefs::dump()) {
Jim Stichnoth69d3f9c2015-03-23 10:33:38 -0700630 // This is a fatal liveness consistency error. Print some
631 // diagnostics and abort.
632 Ostream &Str = Func->getContext()->getStrDump();
633 Func->resetCurrentNode();
634 Str << "LiveOrig-Live =";
635 for (SizeT i = Live.size(); i < LiveOrig.size(); ++i) {
636 if (LiveOrig.test(i)) {
637 Str << " ";
638 Liveness->getVariable(i, this)->dump(Func);
639 }
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700640 }
Jim Stichnoth69d3f9c2015-03-23 10:33:38 -0700641 Str << "\n";
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700642 }
Jim Stichnoth69d3f9c2015-03-23 10:33:38 -0700643 llvm::report_fatal_error("Fatal inconsistency in liveness analysis");
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700644 }
645
646 bool Changed = false;
Jim Stichnoth47752552014-10-13 17:15:08 -0700647 LivenessBV &LiveIn = Liveness->getLiveIn(this);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700648 // Add in current LiveIn
649 Live |= LiveIn;
650 // Check result, set LiveIn=Live
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700651 SizeT &PrevNumNonDeadPhis = Liveness->getNumNonDeadPhis(this);
652 bool LiveInChanged = (Live != LiveIn);
653 Changed = (NumNonDeadPhis != PrevNumNonDeadPhis || LiveInChanged);
654 if (LiveInChanged)
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700655 LiveIn = Live;
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700656 PrevNumNonDeadPhis = NumNonDeadPhis;
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700657 return Changed;
658}
659
Jim Stichnothe5b73e62014-12-15 09:58:51 -0800660// Once basic liveness is complete, compute actual live ranges. It is
661// assumed that within a single basic block, a live range begins at
662// most once and ends at most once. This is certainly true for pure
663// SSA form. It is also true once phis are lowered, since each
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700664// assignment to the phi-based temporary is in a different basic
665// block, and there is a single read that ends the live in the basic
666// block that contained the actual phi instruction.
Jim Stichnothe5b73e62014-12-15 09:58:51 -0800667void CfgNode::livenessAddIntervals(Liveness *Liveness, InstNumberT FirstInstNum,
668 InstNumberT LastInstNum) {
669 TimerMarker T1(TimerStack::TT_liveRange, Func);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700670
671 SizeT NumVars = Liveness->getNumVarsInNode(this);
Jim Stichnoth47752552014-10-13 17:15:08 -0700672 LivenessBV &LiveIn = Liveness->getLiveIn(this);
673 LivenessBV &LiveOut = Liveness->getLiveOut(this);
674 LiveBeginEndMap &MapBegin = *Liveness->getLiveBegin(this);
675 LiveBeginEndMap &MapEnd = *Liveness->getLiveEnd(this);
676 std::sort(MapBegin.begin(), MapBegin.end());
677 std::sort(MapEnd.begin(), MapEnd.end());
678 // Verify there are no duplicates.
Jim Stichnothf9df4522015-08-06 17:50:14 -0700679 auto ComparePair =
680 [](const LiveBeginEndMapEntry &A, const LiveBeginEndMapEntry &B) {
681 return A.first == B.first;
682 };
Jim Stichnoth992f91d2015-08-10 11:18:38 -0700683 (void)ComparePair;
Jim Stichnothf9df4522015-08-06 17:50:14 -0700684 assert(std::adjacent_find(MapBegin.begin(), MapBegin.end(), ComparePair) ==
Jim Stichnoth47752552014-10-13 17:15:08 -0700685 MapBegin.end());
Jim Stichnothf9df4522015-08-06 17:50:14 -0700686 assert(std::adjacent_find(MapEnd.begin(), MapEnd.end(), ComparePair) ==
Jim Stichnoth47752552014-10-13 17:15:08 -0700687 MapEnd.end());
688
689 LivenessBV LiveInAndOut = LiveIn;
690 LiveInAndOut &= LiveOut;
691
692 // Iterate in parallel across the sorted MapBegin[] and MapEnd[].
693 auto IBB = MapBegin.begin(), IEB = MapEnd.begin();
694 auto IBE = MapBegin.end(), IEE = MapEnd.end();
695 while (IBB != IBE || IEB != IEE) {
696 SizeT i1 = IBB == IBE ? NumVars : IBB->first;
697 SizeT i2 = IEB == IEE ? NumVars : IEB->first;
698 SizeT i = std::min(i1, i2);
699 // i1 is the Variable number of the next MapBegin entry, and i2 is
700 // the Variable number of the next MapEnd entry. If i1==i2, then
701 // the Variable's live range begins and ends in this block. If
702 // i1<i2, then i1's live range begins at instruction IBB->second
703 // and extends through the end of the block. If i1>i2, then i2's
704 // live range begins at the first instruction of the block and
705 // ends at IEB->second. In any case, we choose the lesser of i1
706 // and i2 and proceed accordingly.
707 InstNumberT LB = i == i1 ? IBB->second : FirstInstNum;
708 InstNumberT LE = i == i2 ? IEB->second : LastInstNum + 1;
709
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700710 Variable *Var = Liveness->getVariable(i, this);
Jim Stichnothf9df4522015-08-06 17:50:14 -0700711 if (LB > LE) {
Andrew Scull11c9a322015-08-28 14:24:14 -0700712 Var->addLiveRange(FirstInstNum, LE);
713 Var->addLiveRange(LB, LastInstNum + 1);
Jim Stichnothf9df4522015-08-06 17:50:14 -0700714 // Assert that Var is a global variable by checking that its
715 // liveness index is less than the number of globals. This
716 // ensures that the LiveInAndOut[] access is valid.
717 assert(i < Liveness->getNumGlobalVars());
718 LiveInAndOut[i] = false;
719 } else {
Andrew Scull11c9a322015-08-28 14:24:14 -0700720 Var->addLiveRange(LB, LE);
Jim Stichnoth47752552014-10-13 17:15:08 -0700721 }
722 if (i == i1)
723 ++IBB;
724 if (i == i2)
725 ++IEB;
726 }
727 // Process the variables that are live across the entire block.
728 for (int i = LiveInAndOut.find_first(); i != -1;
729 i = LiveInAndOut.find_next(i)) {
730 Variable *Var = Liveness->getVariable(i, this);
Jim Stichnoth552490c2015-08-05 16:21:42 -0700731 if (Liveness->getRangeMask(Var->getIndex()))
Andrew Scull11c9a322015-08-28 14:24:14 -0700732 Var->addLiveRange(FirstInstNum, LastInstNum + 1);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700733 }
734}
735
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700736// If this node contains only deleted instructions, and ends in an
737// unconditional branch, contract the node by repointing all its
738// in-edges to its successor.
739void CfgNode::contractIfEmpty() {
Jim Stichnothbfb410d2014-11-05 16:04:05 -0800740 if (InEdges.empty())
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700741 return;
Jim Stichnothae953202014-12-20 06:17:49 -0800742 Inst *Branch = nullptr;
Jim Stichnoth29841e82014-12-23 12:26:24 -0800743 for (Inst &I : Insts) {
744 if (I.isDeleted())
Jim Stichnoth3d44fe82014-11-01 10:10:18 -0700745 continue;
Jim Stichnoth29841e82014-12-23 12:26:24 -0800746 if (I.isUnconditionalBranch())
747 Branch = &I;
748 else if (!I.isRedundantAssign())
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700749 return;
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700750 }
751 Branch->setDeleted();
752 assert(OutEdges.size() == 1);
Andrew Scull713278a2015-07-22 17:17:02 -0700753 CfgNode *Successor = OutEdges.front();
Jim Stichnothbfb410d2014-11-05 16:04:05 -0800754 // Repoint all this node's in-edges to this node's successor, unless
755 // this node's successor is actually itself (in which case the
756 // statement "OutEdges.front()->InEdges.push_back(Pred)" could
757 // invalidate the iterator over this->InEdges).
Andrew Scull713278a2015-07-22 17:17:02 -0700758 if (Successor != this) {
Jim Stichnothbfb410d2014-11-05 16:04:05 -0800759 for (CfgNode *Pred : InEdges) {
Andrew Scull713278a2015-07-22 17:17:02 -0700760 for (CfgNode *&I : Pred->OutEdges) {
761 if (I == this) {
762 I = Successor;
763 Successor->InEdges.push_back(Pred);
Jim Stichnothbfb410d2014-11-05 16:04:05 -0800764 }
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700765 }
Jim Stichnoth29841e82014-12-23 12:26:24 -0800766 for (Inst &I : Pred->getInsts()) {
767 if (!I.isDeleted())
Andrew Scull713278a2015-07-22 17:17:02 -0700768 I.repointEdges(this, Successor);
Jim Stichnothbfb410d2014-11-05 16:04:05 -0800769 }
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700770 }
Andrew Scull713278a2015-07-22 17:17:02 -0700771
772 // Remove the in-edge to the successor to allow node reordering to make
773 // better decisions. For example it's more helpful to place a node after
774 // a reachable predecessor than an unreachable one (like the one we just
775 // contracted).
776 Successor->InEdges.erase(
777 std::find(Successor->InEdges.begin(), Successor->InEdges.end(), this));
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700778 }
779 InEdges.clear();
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700780}
781
Jim Stichnothff9c7062014-09-18 04:50:49 -0700782void CfgNode::doBranchOpt(const CfgNode *NextNode) {
783 TargetLowering *Target = Func->getTarget();
Andrew Scull713278a2015-07-22 17:17:02 -0700784 // Find the first opportunity for branch optimization (which will be the last
785 // instruction in the block) and stop. This is sufficient unless there is some
786 // target lowering where we have the possibility of multiple optimizations per
787 // block. Take care with switch lowering as there are multiple unconditional
788 // branches and only the last can be deleted.
789 for (Inst &I : reverse_range(Insts)) {
Jim Stichnoth29841e82014-12-23 12:26:24 -0800790 if (!I.isDeleted()) {
791 Target->doBranchOpt(&I, NextNode);
Andrew Scull713278a2015-07-22 17:17:02 -0700792 return;
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700793 }
794 }
Jim Stichnothff9c7062014-09-18 04:50:49 -0700795}
796
Jim Stichnothf7c9a142014-04-29 10:52:43 -0700797// ======================== Dump routines ======================== //
798
Jim Stichnoth3d44fe82014-11-01 10:10:18 -0700799namespace {
800
801// Helper functions for emit().
802
803void emitRegisterUsage(Ostream &Str, const Cfg *Func, const CfgNode *Node,
804 bool IsLiveIn, std::vector<SizeT> &LiveRegCount) {
Jim Stichnoth20b71f52015-06-24 15:52:24 -0700805 if (!BuildDefs::dump())
Karl Schimpfb6c96af2014-11-17 10:58:39 -0800806 return;
Jim Stichnoth3d44fe82014-11-01 10:10:18 -0700807 Liveness *Liveness = Func->getLiveness();
808 const LivenessBV *Live;
809 if (IsLiveIn) {
810 Live = &Liveness->getLiveIn(Node);
811 Str << "\t\t\t\t# LiveIn=";
812 } else {
813 Live = &Liveness->getLiveOut(Node);
814 Str << "\t\t\t\t# LiveOut=";
815 }
816 if (!Live->empty()) {
Jim Stichnoth9a05aea2015-05-26 16:01:23 -0700817 std::vector<Variable *> LiveRegs;
Jim Stichnoth3d44fe82014-11-01 10:10:18 -0700818 for (SizeT i = 0; i < Live->size(); ++i) {
819 if ((*Live)[i]) {
820 Variable *Var = Liveness->getVariable(i, Node);
821 if (Var->hasReg()) {
822 if (IsLiveIn)
823 ++LiveRegCount[Var->getRegNum()];
Jim Stichnoth9a05aea2015-05-26 16:01:23 -0700824 LiveRegs.push_back(Var);
Jim Stichnoth3d44fe82014-11-01 10:10:18 -0700825 }
826 }
827 }
Jim Stichnoth9a05aea2015-05-26 16:01:23 -0700828 // Sort the variables by regnum so they are always printed in a
829 // familiar order.
830 std::sort(LiveRegs.begin(), LiveRegs.end(),
831 [](const Variable *V1, const Variable *V2) {
Jim Stichnoth8e6bf6e2015-06-03 15:58:12 -0700832 return V1->getRegNum() < V2->getRegNum();
833 });
Jim Stichnoth9a05aea2015-05-26 16:01:23 -0700834 bool First = true;
835 for (Variable *Var : LiveRegs) {
836 if (!First)
837 Str << ",";
838 First = false;
839 Var->emit(Func);
840 }
Jim Stichnoth3d44fe82014-11-01 10:10:18 -0700841 }
842 Str << "\n";
843}
844
845void emitLiveRangesEnded(Ostream &Str, const Cfg *Func, const Inst *Instr,
846 std::vector<SizeT> &LiveRegCount) {
Jim Stichnoth20b71f52015-06-24 15:52:24 -0700847 if (!BuildDefs::dump())
Karl Schimpfb6c96af2014-11-17 10:58:39 -0800848 return;
Jim Stichnoth3d44fe82014-11-01 10:10:18 -0700849 bool First = true;
850 Variable *Dest = Instr->getDest();
Jim Stichnothb82baf22015-05-27 10:41:07 -0700851 // Normally we increment the live count for the dest register. But
852 // we shouldn't if the instruction's IsDestNonKillable flag is set,
853 // because this means that the target lowering created this
854 // instruction as a non-SSA assignment; i.e., a different, previous
855 // instruction started the dest variable's live range.
856 if (!Instr->isDestNonKillable() && Dest && Dest->hasReg())
Jim Stichnoth3d44fe82014-11-01 10:10:18 -0700857 ++LiveRegCount[Dest->getRegNum()];
John Portoec3f5652015-08-31 15:07:09 -0700858 FOREACH_VAR_IN_INST(Var, *Instr) {
859 bool ShouldReport = Instr->isLastUse(Var);
860 if (ShouldReport && Var->hasReg()) {
861 // Don't report end of live range until the live count reaches 0.
862 SizeT NewCount = --LiveRegCount[Var->getRegNum()];
863 if (NewCount)
864 ShouldReport = false;
865 }
866 if (ShouldReport) {
867 if (First)
868 Str << " \t# END=";
869 else
870 Str << ",";
871 Var->emit(Func);
872 First = false;
Jim Stichnoth3d44fe82014-11-01 10:10:18 -0700873 }
874 }
875}
876
Jan Voung0faec4c2014-11-05 17:29:56 -0800877void updateStats(Cfg *Func, const Inst *I) {
Jim Stichnoth20b71f52015-06-24 15:52:24 -0700878 if (!BuildDefs::dump())
Jim Stichnoth9f42d8c2015-02-20 09:20:14 -0800879 return;
Jan Voung0faec4c2014-11-05 17:29:56 -0800880 // Update emitted instruction count, plus fill/spill count for
881 // Variable operands without a physical register.
882 if (uint32_t Count = I->getEmitInstCount()) {
883 Func->getContext()->statsUpdateEmitted(Count);
884 if (Variable *Dest = I->getDest()) {
885 if (!Dest->hasReg())
886 Func->getContext()->statsUpdateFills();
887 }
888 for (SizeT S = 0; S < I->getSrcSize(); ++S) {
889 if (Variable *Src = llvm::dyn_cast<Variable>(I->getSrc(S))) {
890 if (!Src->hasReg())
891 Func->getContext()->statsUpdateSpills();
892 }
893 }
894 }
895}
896
Jim Stichnoth3d44fe82014-11-01 10:10:18 -0700897} // end of anonymous namespace
898
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700899void CfgNode::emit(Cfg *Func) const {
Jim Stichnoth20b71f52015-06-24 15:52:24 -0700900 if (!BuildDefs::dump())
Karl Schimpfb6c96af2014-11-17 10:58:39 -0800901 return;
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700902 Func->setCurrentNode(this);
903 Ostream &Str = Func->getContext()->getStrEmit();
Jim Stichnoth3d44fe82014-11-01 10:10:18 -0700904 Liveness *Liveness = Func->getLiveness();
Karl Schimpfdf80eb82015-02-09 14:20:22 -0800905 bool DecorateAsm =
906 Liveness && Func->getContext()->getFlags().getDecorateAsm();
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700907 Str << getAsmName() << ":\n";
Jim Stichnothb82baf22015-05-27 10:41:07 -0700908 // LiveRegCount keeps track of the number of currently live
909 // variables that each register is assigned to. Normally that would
910 // be only 0 or 1, but the register allocator's AllowOverlap
911 // inference allows it to be greater than 1 for short periods.
Jim Stichnoth3d44fe82014-11-01 10:10:18 -0700912 std::vector<SizeT> LiveRegCount(Func->getTarget()->getNumRegisters());
Jim Stichnoth4175b2a2015-04-30 12:26:22 -0700913 if (DecorateAsm) {
Jim Stichnotha3f57b92015-07-30 12:46:04 -0700914 constexpr bool IsLiveIn = true;
Jim Stichnoth4175b2a2015-04-30 12:26:22 -0700915 emitRegisterUsage(Str, Func, this, IsLiveIn, LiveRegCount);
916 }
Jim Stichnoth3d44fe82014-11-01 10:10:18 -0700917
Jim Stichnoth29841e82014-12-23 12:26:24 -0800918 for (const Inst &I : Phis) {
919 if (I.isDeleted())
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700920 continue;
921 // Emitting a Phi instruction should cause an error.
Jim Stichnoth29841e82014-12-23 12:26:24 -0800922 I.emit(Func);
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700923 }
Jim Stichnoth29841e82014-12-23 12:26:24 -0800924 for (const Inst &I : Insts) {
925 if (I.isDeleted())
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700926 continue;
Jim Stichnothb82baf22015-05-27 10:41:07 -0700927 if (I.isRedundantAssign()) {
928 // Usually, redundant assignments end the live range of the src
929 // variable and begin the live range of the dest variable, with
930 // no net effect on the liveness of their register. However, if
931 // the register allocator infers the AllowOverlap condition,
932 // then this may be a redundant assignment that does not end the
933 // src variable's live range, in which case the active variable
934 // count for that register needs to be bumped. That normally
935 // would have happened as part of emitLiveRangesEnded(), but
936 // that isn't called for redundant assignments.
937 Variable *Dest = I.getDest();
938 if (DecorateAsm && Dest->hasReg() && !I.isLastUse(I.getSrc(0)))
939 ++LiveRegCount[Dest->getRegNum()];
Jim Stichnoth3d44fe82014-11-01 10:10:18 -0700940 continue;
Jim Stichnothb82baf22015-05-27 10:41:07 -0700941 }
Jim Stichnoth29841e82014-12-23 12:26:24 -0800942 I.emit(Func);
Jan Voung0faec4c2014-11-05 17:29:56 -0800943 if (DecorateAsm)
Jim Stichnoth29841e82014-12-23 12:26:24 -0800944 emitLiveRangesEnded(Str, Func, &I, LiveRegCount);
Jan Voung0faec4c2014-11-05 17:29:56 -0800945 Str << "\n";
Jim Stichnoth29841e82014-12-23 12:26:24 -0800946 updateStats(Func, &I);
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700947 }
Jim Stichnoth4175b2a2015-04-30 12:26:22 -0700948 if (DecorateAsm) {
Jim Stichnotha3f57b92015-07-30 12:46:04 -0700949 constexpr bool IsLiveIn = false;
Jim Stichnoth4175b2a2015-04-30 12:26:22 -0700950 emitRegisterUsage(Str, Func, this, IsLiveIn, LiveRegCount);
951 }
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700952}
953
Jim Stichnoth9f42d8c2015-02-20 09:20:14 -0800954// Helper class for emitIAS().
955namespace {
956class BundleEmitHelper {
957 BundleEmitHelper() = delete;
958 BundleEmitHelper(const BundleEmitHelper &) = delete;
959 BundleEmitHelper &operator=(const BundleEmitHelper &) = delete;
960
961public:
Jim Stichnoth9738a9e2015-02-23 16:39:06 -0800962 BundleEmitHelper(Assembler *Asm, TargetLowering *Target,
963 const InstList &Insts)
964 : Asm(Asm), Target(Target), End(Insts.end()), BundleLockStart(End),
Jim Stichnoth9f42d8c2015-02-20 09:20:14 -0800965 BundleSize(1 << Asm->getBundleAlignLog2Bytes()),
Jim Stichnotheafb56c2015-06-22 10:35:22 -0700966 BundleMaskLo(BundleSize - 1), BundleMaskHi(~BundleMaskLo) {}
Jim Stichnoth9f42d8c2015-02-20 09:20:14 -0800967 // Check whether we're currently within a bundle_lock region.
968 bool isInBundleLockRegion() const { return BundleLockStart != End; }
969 // Check whether the current bundle_lock region has the align_to_end
970 // option.
971 bool isAlignToEnd() const {
972 assert(isInBundleLockRegion());
973 return llvm::cast<InstBundleLock>(getBundleLockStart())->getOption() ==
974 InstBundleLock::Opt_AlignToEnd;
975 }
976 // Check whether the entire bundle_lock region falls within the same
977 // bundle.
978 bool isSameBundle() const {
979 assert(isInBundleLockRegion());
980 return SizeSnapshotPre == SizeSnapshotPost ||
981 (SizeSnapshotPre & BundleMaskHi) ==
982 ((SizeSnapshotPost - 1) & BundleMaskHi);
983 }
984 // Get the bundle alignment of the first instruction of the
985 // bundle_lock region.
986 intptr_t getPreAlignment() const {
987 assert(isInBundleLockRegion());
988 return SizeSnapshotPre & BundleMaskLo;
989 }
990 // Get the bundle alignment of the first instruction past the
991 // bundle_lock region.
992 intptr_t getPostAlignment() const {
993 assert(isInBundleLockRegion());
994 return SizeSnapshotPost & BundleMaskLo;
995 }
996 // Get the iterator pointing to the bundle_lock instruction, e.g. to
997 // roll back the instruction iteration to that point.
998 InstList::const_iterator getBundleLockStart() const {
999 assert(isInBundleLockRegion());
1000 return BundleLockStart;
1001 }
1002 // Set up bookkeeping when the bundle_lock instruction is first
1003 // processed.
1004 void enterBundleLock(InstList::const_iterator I) {
1005 assert(!isInBundleLockRegion());
1006 BundleLockStart = I;
1007 SizeSnapshotPre = Asm->getBufferSize();
1008 Asm->setPreliminary(true);
Jim Stichnoth9738a9e2015-02-23 16:39:06 -08001009 Target->snapshotEmitState();
Jim Stichnoth9f42d8c2015-02-20 09:20:14 -08001010 assert(isInBundleLockRegion());
1011 }
1012 // Update bookkeeping when the bundle_unlock instruction is
1013 // processed.
1014 void enterBundleUnlock() {
1015 assert(isInBundleLockRegion());
1016 SizeSnapshotPost = Asm->getBufferSize();
1017 }
1018 // Update bookkeeping when we are completely finished with the
1019 // bundle_lock region.
1020 void leaveBundleLockRegion() { BundleLockStart = End; }
1021 // Check whether the instruction sequence fits within the current
1022 // bundle, and if not, add nop padding to the end of the current
1023 // bundle.
1024 void padToNextBundle() {
1025 assert(isInBundleLockRegion());
1026 if (!isSameBundle()) {
1027 intptr_t PadToNextBundle = BundleSize - getPreAlignment();
1028 Asm->padWithNop(PadToNextBundle);
1029 SizeSnapshotPre += PadToNextBundle;
1030 SizeSnapshotPost += PadToNextBundle;
1031 assert((Asm->getBufferSize() & BundleMaskLo) == 0);
1032 assert(Asm->getBufferSize() == SizeSnapshotPre);
1033 }
1034 }
1035 // If align_to_end is specified, add padding such that the
1036 // instruction sequences ends precisely at a bundle boundary.
1037 void padForAlignToEnd() {
1038 assert(isInBundleLockRegion());
1039 if (isAlignToEnd()) {
1040 if (intptr_t Offset = getPostAlignment()) {
1041 Asm->padWithNop(BundleSize - Offset);
1042 SizeSnapshotPre = Asm->getBufferSize();
1043 }
1044 }
1045 }
1046 // Update bookkeeping when rolling back for the second pass.
1047 void rollback() {
1048 assert(isInBundleLockRegion());
1049 Asm->setBufferSize(SizeSnapshotPre);
1050 Asm->setPreliminary(false);
Jim Stichnoth9738a9e2015-02-23 16:39:06 -08001051 Target->rollbackEmitState();
Jim Stichnoth9f42d8c2015-02-20 09:20:14 -08001052 }
1053
1054private:
1055 Assembler *const Asm;
Jim Stichnoth9738a9e2015-02-23 16:39:06 -08001056 TargetLowering *const Target;
Jim Stichnoth9f42d8c2015-02-20 09:20:14 -08001057 // End is a sentinel value such that BundleLockStart==End implies
1058 // that we are not in a bundle_lock region.
1059 const InstList::const_iterator End;
1060 InstList::const_iterator BundleLockStart;
1061 const intptr_t BundleSize;
1062 // Masking with BundleMaskLo identifies an address's bundle offset.
1063 const intptr_t BundleMaskLo;
1064 // Masking with BundleMaskHi identifies an address's bundle.
1065 const intptr_t BundleMaskHi;
Jim Stichnotheafb56c2015-06-22 10:35:22 -07001066 intptr_t SizeSnapshotPre = 0;
1067 intptr_t SizeSnapshotPost = 0;
Jim Stichnoth9f42d8c2015-02-20 09:20:14 -08001068};
1069
1070} // end of anonymous namespace
1071
Jan Voung0faec4c2014-11-05 17:29:56 -08001072void CfgNode::emitIAS(Cfg *Func) const {
1073 Func->setCurrentNode(this);
Jim Stichnothbbca7542015-02-11 16:08:31 -08001074 Assembler *Asm = Func->getAssembler<>();
Jim Stichnoth9f42d8c2015-02-20 09:20:14 -08001075 // TODO(stichnot): When sandboxing, defer binding the node label
1076 // until just before the first instruction is emitted, to reduce the
1077 // chance that a padding nop is a branch target.
John Portoaff4ccf2015-06-10 16:35:06 -07001078 Asm->bindCfgNodeLabel(getIndex());
Jim Stichnoth29841e82014-12-23 12:26:24 -08001079 for (const Inst &I : Phis) {
1080 if (I.isDeleted())
Jan Voung0faec4c2014-11-05 17:29:56 -08001081 continue;
1082 // Emitting a Phi instruction should cause an error.
Jim Stichnoth29841e82014-12-23 12:26:24 -08001083 I.emitIAS(Func);
Jan Voung0faec4c2014-11-05 17:29:56 -08001084 }
Jim Stichnoth9f42d8c2015-02-20 09:20:14 -08001085
1086 // Do the simple emission if not sandboxed.
1087 if (!Func->getContext()->getFlags().getUseSandboxing()) {
1088 for (const Inst &I : Insts) {
1089 if (!I.isDeleted() && !I.isRedundantAssign()) {
1090 I.emitIAS(Func);
1091 updateStats(Func, &I);
1092 }
1093 }
1094 return;
Jan Voung0faec4c2014-11-05 17:29:56 -08001095 }
Jim Stichnoth9f42d8c2015-02-20 09:20:14 -08001096
1097 // The remainder of the function handles emission with sandboxing.
1098 // There are explicit bundle_lock regions delimited by bundle_lock
1099 // and bundle_unlock instructions. All other instructions are
1100 // treated as an implicit one-instruction bundle_lock region.
1101 // Emission is done twice for each bundle_lock region. The first
1102 // pass is a preliminary pass, after which we can figure out what
1103 // nop padding is needed, then roll back, and make the final pass.
1104 //
1105 // Ideally, the first pass would be speculative and the second pass
1106 // would only be done if nop padding were needed, but the structure
1107 // of the integrated assembler makes it hard to roll back the state
1108 // of label bindings, label links, and relocation fixups. Instead,
1109 // the first pass just disables all mutation of that state.
1110
Jim Stichnoth9738a9e2015-02-23 16:39:06 -08001111 BundleEmitHelper Helper(Asm, Func->getTarget(), Insts);
Jim Stichnoth9f42d8c2015-02-20 09:20:14 -08001112 InstList::const_iterator End = Insts.end();
1113 // Retrying indicates that we had to roll back to the bundle_lock
1114 // instruction to apply padding before the bundle_lock sequence.
1115 bool Retrying = false;
1116 for (InstList::const_iterator I = Insts.begin(); I != End; ++I) {
1117 if (I->isDeleted() || I->isRedundantAssign())
1118 continue;
1119
1120 if (llvm::isa<InstBundleLock>(I)) {
1121 // Set up the initial bundle_lock state. This should not happen
1122 // while retrying, because the retry rolls back to the
1123 // instruction following the bundle_lock instruction.
1124 assert(!Retrying);
1125 Helper.enterBundleLock(I);
1126 continue;
1127 }
1128
1129 if (llvm::isa<InstBundleUnlock>(I)) {
1130 Helper.enterBundleUnlock();
1131 if (Retrying) {
1132 // Make sure all instructions are in the same bundle.
1133 assert(Helper.isSameBundle());
1134 // If align_to_end is specified, make sure the next
1135 // instruction begins the bundle.
1136 assert(!Helper.isAlignToEnd() || Helper.getPostAlignment() == 0);
1137 Helper.leaveBundleLockRegion();
1138 Retrying = false;
1139 } else {
1140 // This is the first pass, so roll back for the retry pass.
1141 Helper.rollback();
1142 // Pad to the next bundle if the instruction sequence crossed
1143 // a bundle boundary.
1144 Helper.padToNextBundle();
1145 // Insert additional padding to make AlignToEnd work.
1146 Helper.padForAlignToEnd();
1147 // Prepare for the retry pass after padding is done.
1148 Retrying = true;
1149 I = Helper.getBundleLockStart();
1150 }
1151 continue;
1152 }
1153
1154 // I points to a non bundle_lock/bundle_unlock instruction.
1155 if (Helper.isInBundleLockRegion()) {
1156 I->emitIAS(Func);
1157 // Only update stats during the final pass.
1158 if (Retrying)
1159 updateStats(Func, I);
1160 } else {
1161 // Treat it as though there were an implicit bundle_lock and
1162 // bundle_unlock wrapping the instruction.
1163 Helper.enterBundleLock(I);
1164 I->emitIAS(Func);
1165 Helper.enterBundleUnlock();
1166 Helper.rollback();
1167 Helper.padToNextBundle();
1168 I->emitIAS(Func);
1169 updateStats(Func, I);
1170 Helper.leaveBundleLockRegion();
1171 }
1172 }
1173
1174 // Don't allow bundle locking across basic blocks, to keep the
1175 // backtracking mechanism simple.
1176 assert(!Helper.isInBundleLockRegion());
1177 assert(!Retrying);
Jan Voung0faec4c2014-11-05 17:29:56 -08001178}
1179
Jim Stichnothf7c9a142014-04-29 10:52:43 -07001180void CfgNode::dump(Cfg *Func) const {
Jim Stichnoth20b71f52015-06-24 15:52:24 -07001181 if (!BuildDefs::dump())
Karl Schimpfb6c96af2014-11-17 10:58:39 -08001182 return;
Jim Stichnothf7c9a142014-04-29 10:52:43 -07001183 Func->setCurrentNode(this);
1184 Ostream &Str = Func->getContext()->getStrDump();
Jim Stichnothd97c7df2014-06-04 11:57:08 -07001185 Liveness *Liveness = Func->getLiveness();
Andrew Scullaa6c1092015-09-03 17:50:30 -07001186 if (Func->isVerbose(IceV_Instructions) || Func->isVerbose(IceV_Loop))
Jim Stichnothf7c9a142014-04-29 10:52:43 -07001187 Str << getName() << ":\n";
Andrew Scullaa6c1092015-09-03 17:50:30 -07001188 // Dump the loop nest depth
1189 if (Func->isVerbose(IceV_Loop))
1190 Str << " // LoopNestDepth = " << getLoopNestDepth() << "\n";
Jim Stichnothf7c9a142014-04-29 10:52:43 -07001191 // Dump list of predecessor nodes.
Jim Stichnothfa4efea2015-01-27 05:06:03 -08001192 if (Func->isVerbose(IceV_Preds) && !InEdges.empty()) {
Jim Stichnothf7c9a142014-04-29 10:52:43 -07001193 Str << " // preds = ";
Jim Stichnothf44f3712014-10-01 14:05:51 -07001194 bool First = true;
1195 for (CfgNode *I : InEdges) {
Jim Stichnoth8363a062014-10-07 10:02:38 -07001196 if (!First)
Jim Stichnothf7c9a142014-04-29 10:52:43 -07001197 Str << ", ";
Jim Stichnothf44f3712014-10-01 14:05:51 -07001198 First = false;
1199 Str << "%" << I->getName();
Jim Stichnothf7c9a142014-04-29 10:52:43 -07001200 }
1201 Str << "\n";
1202 }
Jim Stichnothd97c7df2014-06-04 11:57:08 -07001203 // Dump the live-in variables.
Jim Stichnoth47752552014-10-13 17:15:08 -07001204 LivenessBV LiveIn;
Jim Stichnothd97c7df2014-06-04 11:57:08 -07001205 if (Liveness)
1206 LiveIn = Liveness->getLiveIn(this);
Jim Stichnothfa4efea2015-01-27 05:06:03 -08001207 if (Func->isVerbose(IceV_Liveness) && !LiveIn.empty()) {
Jim Stichnothd97c7df2014-06-04 11:57:08 -07001208 Str << " // LiveIn:";
1209 for (SizeT i = 0; i < LiveIn.size(); ++i) {
1210 if (LiveIn[i]) {
Jim Stichnoth088b2be2014-10-23 12:02:08 -07001211 Variable *Var = Liveness->getVariable(i, this);
Jim Stichnoth9a04c072014-12-11 15:51:42 -08001212 Str << " %" << Var->getName(Func);
Jim Stichnothfa4efea2015-01-27 05:06:03 -08001213 if (Func->isVerbose(IceV_RegOrigins) && Var->hasReg()) {
Jim Stichnothdd842db2015-01-27 12:53:53 -08001214 Str << ":"
1215 << Func->getTarget()->getRegName(Var->getRegNum(),
1216 Var->getType());
Jim Stichnoth088b2be2014-10-23 12:02:08 -07001217 }
Jim Stichnothd97c7df2014-06-04 11:57:08 -07001218 }
1219 }
1220 Str << "\n";
1221 }
Jim Stichnothf7c9a142014-04-29 10:52:43 -07001222 // Dump each instruction.
Jim Stichnothfa4efea2015-01-27 05:06:03 -08001223 if (Func->isVerbose(IceV_Instructions)) {
Jim Stichnoth29841e82014-12-23 12:26:24 -08001224 for (const Inst &I : Phis)
1225 I.dumpDecorated(Func);
1226 for (const Inst &I : Insts)
1227 I.dumpDecorated(Func);
Jim Stichnothf7c9a142014-04-29 10:52:43 -07001228 }
Jim Stichnothd97c7df2014-06-04 11:57:08 -07001229 // Dump the live-out variables.
Jim Stichnoth47752552014-10-13 17:15:08 -07001230 LivenessBV LiveOut;
Jim Stichnothd97c7df2014-06-04 11:57:08 -07001231 if (Liveness)
1232 LiveOut = Liveness->getLiveOut(this);
Jim Stichnothfa4efea2015-01-27 05:06:03 -08001233 if (Func->isVerbose(IceV_Liveness) && !LiveOut.empty()) {
Jim Stichnothd97c7df2014-06-04 11:57:08 -07001234 Str << " // LiveOut:";
1235 for (SizeT i = 0; i < LiveOut.size(); ++i) {
1236 if (LiveOut[i]) {
Jim Stichnoth088b2be2014-10-23 12:02:08 -07001237 Variable *Var = Liveness->getVariable(i, this);
Jim Stichnoth9a04c072014-12-11 15:51:42 -08001238 Str << " %" << Var->getName(Func);
Jim Stichnothfa4efea2015-01-27 05:06:03 -08001239 if (Func->isVerbose(IceV_RegOrigins) && Var->hasReg()) {
Jim Stichnothdd842db2015-01-27 12:53:53 -08001240 Str << ":"
1241 << Func->getTarget()->getRegName(Var->getRegNum(),
1242 Var->getType());
Jim Stichnoth088b2be2014-10-23 12:02:08 -07001243 }
Jim Stichnothd97c7df2014-06-04 11:57:08 -07001244 }
1245 }
1246 Str << "\n";
1247 }
Jim Stichnothf7c9a142014-04-29 10:52:43 -07001248 // Dump list of successor nodes.
Jim Stichnothfa4efea2015-01-27 05:06:03 -08001249 if (Func->isVerbose(IceV_Succs)) {
Jim Stichnothf7c9a142014-04-29 10:52:43 -07001250 Str << " // succs = ";
Jim Stichnothf44f3712014-10-01 14:05:51 -07001251 bool First = true;
1252 for (CfgNode *I : OutEdges) {
Jim Stichnoth8363a062014-10-07 10:02:38 -07001253 if (!First)
Jim Stichnothf7c9a142014-04-29 10:52:43 -07001254 Str << ", ";
Jim Stichnothf44f3712014-10-01 14:05:51 -07001255 First = false;
1256 Str << "%" << I->getName();
Jim Stichnothf7c9a142014-04-29 10:52:43 -07001257 }
1258 Str << "\n";
1259 }
1260}
1261
John Portof8b4cc82015-06-09 18:06:19 -07001262void CfgNode::profileExecutionCount(VariableDeclaration *Var) {
1263 constexpr char RMW_I64[] = "llvm.nacl.atomic.rmw.i64";
1264
1265 GlobalContext *Context = Func->getContext();
1266
1267 bool BadIntrinsic = false;
1268 const Intrinsics::FullIntrinsicInfo *Info =
1269 Context->getIntrinsicsInfo().find(RMW_I64, BadIntrinsic);
1270 assert(!BadIntrinsic);
1271 assert(Info != nullptr);
1272
1273 Operand *RMWI64Name = Context->getConstantExternSym(RMW_I64);
John Porto8b1a7052015-06-17 13:20:08 -07001274 constexpr RelocOffsetT Offset = 0;
1275 constexpr bool SuppressMangling = true;
1276 Constant *Counter =
1277 Context->getConstantSym(Offset, Var->getName(), SuppressMangling);
John Portof8b4cc82015-06-09 18:06:19 -07001278 Constant *AtomicRMWOp = Context->getConstantInt32(Intrinsics::AtomicAdd);
1279 Constant *One = Context->getConstantInt64(1);
1280 Constant *OrderAcquireRelease =
1281 Context->getConstantInt32(Intrinsics::MemoryOrderAcquireRelease);
1282
1283 InstIntrinsicCall *Inst = InstIntrinsicCall::create(
1284 Func, 5, Func->makeVariable(IceType_i64), RMWI64Name, Info->Info);
1285 Inst->addArg(AtomicRMWOp);
1286 Inst->addArg(Counter);
1287 Inst->addArg(One);
1288 Inst->addArg(OrderAcquireRelease);
1289 Insts.push_front(Inst);
1290}
1291
Jim Stichnothf7c9a142014-04-29 10:52:43 -07001292} // end of namespace Ice