blob: d699ef50bf7a207eb17729070c99fc16286d36d4 [file] [log] [blame]
Jim Stichnothf7c9a142014-04-29 10:52:43 -07001//===- subzero/src/IceCfg.cpp - Control flow graph 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//
10// This file implements the Cfg class, including constant pool
11// management.
12//
13//===----------------------------------------------------------------------===//
14
15#include "IceCfg.h"
16#include "IceCfgNode.h"
Jim Stichnoth989a7032014-08-08 10:13:44 -070017#include "IceClFlags.h"
Jim Stichnothf7c9a142014-04-29 10:52:43 -070018#include "IceDefs.h"
19#include "IceInst.h"
Jim Stichnothd97c7df2014-06-04 11:57:08 -070020#include "IceLiveness.h"
Jim Stichnothf7c9a142014-04-29 10:52:43 -070021#include "IceOperand.h"
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -070022#include "IceTargetLowering.h"
Jim Stichnothf7c9a142014-04-29 10:52:43 -070023
24namespace Ice {
25
26Cfg::Cfg(GlobalContext *Ctx)
27 : Ctx(Ctx), FunctionName(""), ReturnType(IceType_void),
28 IsInternalLinkage(false), HasError(false), ErrorMessage(""), Entry(NULL),
Jim Stichnothd97c7df2014-06-04 11:57:08 -070029 NextInstNumber(1), Live(NULL),
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -070030 Target(TargetLowering::createLowering(Ctx->getTargetArch(), this)),
31 CurrentNode(NULL) {}
Jim Stichnothf7c9a142014-04-29 10:52:43 -070032
33Cfg::~Cfg() {}
34
35void Cfg::setError(const IceString &Message) {
36 HasError = true;
37 ErrorMessage = Message;
38 Ctx->getStrDump() << "ICE translation error: " << ErrorMessage << "\n";
39}
40
41CfgNode *Cfg::makeNode(const IceString &Name) {
42 SizeT LabelIndex = Nodes.size();
43 CfgNode *Node = CfgNode::create(this, LabelIndex, Name);
44 Nodes.push_back(Node);
45 return Node;
46}
47
48// Create a new Variable with a particular type and an optional
49// name. The Node argument is the node where the variable is defined.
50Variable *Cfg::makeVariable(Type Ty, const CfgNode *Node,
51 const IceString &Name) {
52 SizeT Index = Variables.size();
53 Variables.push_back(Variable::create(this, Ty, Node, Index, Name));
54 return Variables[Index];
55}
56
57void Cfg::addArg(Variable *Arg) {
58 Arg->setIsArg(this);
59 Args.push_back(Arg);
60}
61
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -070062// Returns whether the stack frame layout has been computed yet. This
63// is used for dumping the stack frame location of Variables.
64bool Cfg::hasComputedFrame() const { return getTarget()->hasComputedFrame(); }
65
66void Cfg::translate() {
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -070067 if (hasError())
68 return;
69
Jim Stichnothd97c7df2014-06-04 11:57:08 -070070 dump("Initial CFG");
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -070071
72 Timer T_translate;
73 // The set of translation passes and their order are determined by
74 // the target.
75 getTarget()->translate();
76 T_translate.printElapsedUs(getContext(), "translate()");
77
Jim Stichnothd97c7df2014-06-04 11:57:08 -070078 dump("Final output");
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -070079}
80
Jim Stichnothf7c9a142014-04-29 10:52:43 -070081void Cfg::computePredecessors() {
82 for (NodeList::iterator I = Nodes.begin(), E = Nodes.end(); I != E; ++I) {
83 (*I)->computePredecessors();
84 }
85}
86
Jim Stichnothd97c7df2014-06-04 11:57:08 -070087void Cfg::renumberInstructions() {
88 NextInstNumber = 1;
89 for (NodeList::iterator I = Nodes.begin(), E = Nodes.end(); I != E; ++I) {
90 (*I)->renumberInstructions();
91 }
92}
93
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -070094// placePhiLoads() must be called before placePhiStores().
95void Cfg::placePhiLoads() {
96 for (NodeList::iterator I = Nodes.begin(), E = Nodes.end(); I != E; ++I) {
97 (*I)->placePhiLoads();
98 }
99}
100
101// placePhiStores() must be called after placePhiLoads().
102void Cfg::placePhiStores() {
103 for (NodeList::iterator I = Nodes.begin(), E = Nodes.end(); I != E; ++I) {
104 (*I)->placePhiStores();
105 }
106}
107
108void Cfg::deletePhis() {
109 for (NodeList::iterator I = Nodes.begin(), E = Nodes.end(); I != E; ++I) {
110 (*I)->deletePhis();
111 }
112}
113
Matt Wala45a06232014-07-09 16:33:22 -0700114void Cfg::doArgLowering() {
115 getTarget()->lowerArguments();
116}
117
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700118void Cfg::doAddressOpt() {
119 for (NodeList::iterator I = Nodes.begin(), E = Nodes.end(); I != E; ++I) {
120 (*I)->doAddressOpt();
121 }
122}
123
Matt Walac3302742014-08-15 16:21:56 -0700124void Cfg::doNopInsertion() {
125 for (NodeList::iterator I = Nodes.begin(), E = Nodes.end(); I != E; ++I) {
126 (*I)->doNopInsertion();
127 }
128}
129
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700130void Cfg::genCode() {
131 for (NodeList::iterator I = Nodes.begin(), E = Nodes.end(); I != E; ++I) {
132 (*I)->genCode();
133 }
134}
135
136// Compute the stack frame layout.
137void Cfg::genFrame() {
138 getTarget()->addProlog(Entry);
139 // TODO: Consider folding epilog generation into the final
140 // emission/assembly pass to avoid an extra iteration over the node
141 // list. Or keep a separate list of exit nodes.
142 for (NodeList::iterator I = Nodes.begin(), E = Nodes.end(); I != E; ++I) {
143 CfgNode *Node = *I;
144 if (Node->getHasReturn())
145 getTarget()->addEpilog(Node);
146 }
147}
148
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700149// This is a lightweight version of live-range-end calculation. Marks
150// the last use of only those variables whose definition and uses are
151// completely with a single block. It is a quick single pass and
152// doesn't need to iterate until convergence.
153void Cfg::livenessLightweight() {
154 for (NodeList::iterator I = Nodes.begin(), E = Nodes.end(); I != E; ++I) {
155 (*I)->livenessLightweight();
156 }
157}
158
159void Cfg::liveness(LivenessMode Mode) {
160 Live.reset(new Liveness(this, Mode));
161 Live->init();
162 // Initialize with all nodes needing to be processed.
163 llvm::BitVector NeedToProcess(Nodes.size(), true);
164 while (NeedToProcess.any()) {
165 // Iterate in reverse topological order to speed up convergence.
166 for (NodeList::reverse_iterator I = Nodes.rbegin(), E = Nodes.rend();
167 I != E; ++I) {
168 CfgNode *Node = *I;
169 if (NeedToProcess[Node->getIndex()]) {
170 NeedToProcess[Node->getIndex()] = false;
171 bool Changed = Node->liveness(getLiveness());
172 if (Changed) {
173 // If the beginning-of-block liveness changed since the last
174 // iteration, mark all in-edges as needing to be processed.
175 const NodeList &InEdges = Node->getInEdges();
176 for (NodeList::const_iterator I1 = InEdges.begin(),
177 E1 = InEdges.end();
178 I1 != E1; ++I1) {
179 CfgNode *Pred = *I1;
180 NeedToProcess[Pred->getIndex()] = true;
181 }
182 }
183 }
184 }
185 }
186 if (Mode == Liveness_Intervals) {
187 // Reset each variable's live range.
188 for (VarList::const_iterator I = Variables.begin(), E = Variables.end();
189 I != E; ++I) {
190 if (Variable *Var = *I)
191 Var->resetLiveRange();
192 }
193 }
194 // Collect timing for just the portion that constructs the live
195 // range intervals based on the end-of-live-range computation, for a
196 // finer breakdown of the cost.
197 Timer T_liveRange;
198 // Make a final pass over instructions to delete dead instructions
199 // and build each Variable's live range.
200 for (NodeList::iterator I = Nodes.begin(), E = Nodes.end(); I != E; ++I) {
201 (*I)->livenessPostprocess(Mode, getLiveness());
202 }
203 if (Mode == Liveness_Intervals) {
204 // Special treatment for live in-args. Their liveness needs to
205 // extend beyond the beginning of the function, otherwise an arg
206 // whose only use is in the first instruction will end up having
207 // the trivial live range [1,1) and will *not* interfere with
208 // other arguments. So if the first instruction of the method is
209 // "r=arg1+arg2", both args may be assigned the same register.
210 for (SizeT I = 0; I < Args.size(); ++I) {
211 Variable *Arg = Args[I];
212 if (!Live->getLiveRange(Arg).isEmpty()) {
213 // Add live range [-1,0) with weight 0. TODO: Here and below,
214 // use better symbolic constants along the lines of
215 // Inst::NumberDeleted and Inst::NumberSentinel instead of -1
216 // and 0.
217 Live->addLiveRange(Arg, -1, 0, 0);
218 }
219 // Do the same for i64 args that may have been lowered into i32
220 // Lo and Hi components.
221 Variable *Lo = Arg->getLo();
222 if (Lo && !Live->getLiveRange(Lo).isEmpty())
223 Live->addLiveRange(Lo, -1, 0, 0);
224 Variable *Hi = Arg->getHi();
225 if (Hi && !Live->getLiveRange(Hi).isEmpty())
226 Live->addLiveRange(Hi, -1, 0, 0);
227 }
228 // Copy Liveness::LiveRanges into individual variables. TODO:
229 // Remove Variable::LiveRange and redirect to
230 // Liveness::LiveRanges. TODO: make sure Variable weights
231 // are applied properly.
232 SizeT NumVars = Variables.size();
233 for (SizeT i = 0; i < NumVars; ++i) {
234 Variable *Var = Variables[i];
235 Var->setLiveRange(Live->getLiveRange(Var));
236 if (Var->getWeight().isInf())
237 Var->setLiveRangeInfiniteWeight();
238 }
239 T_liveRange.printElapsedUs(getContext(), "live range construction");
240 dump();
241 }
242}
243
244// Traverse every Variable of every Inst and verify that it
245// appears within the Variable's computed live range.
246bool Cfg::validateLiveness() const {
247 bool Valid = true;
248 Ostream &Str = Ctx->getStrDump();
249 for (NodeList::const_iterator I1 = Nodes.begin(), E1 = Nodes.end(); I1 != E1;
250 ++I1) {
251 CfgNode *Node = *I1;
252 InstList &Insts = Node->getInsts();
253 for (InstList::const_iterator I2 = Insts.begin(), E2 = Insts.end();
254 I2 != E2; ++I2) {
255 Inst *Inst = *I2;
256 if (Inst->isDeleted())
257 continue;
258 if (llvm::isa<InstFakeKill>(Inst))
259 continue;
260 InstNumberT InstNumber = Inst->getNumber();
261 Variable *Dest = Inst->getDest();
262 if (Dest) {
263 // TODO: This instruction should actually begin Dest's live
264 // range, so we could probably test that this instruction is
265 // the beginning of some segment of Dest's live range. But
266 // this wouldn't work with non-SSA temporaries during
267 // lowering.
268 if (!Dest->getLiveRange().containsValue(InstNumber)) {
269 Valid = false;
270 Str << "Liveness error: inst " << Inst->getNumber() << " dest ";
271 Dest->dump(this);
272 Str << " live range " << Dest->getLiveRange() << "\n";
273 }
274 }
275 for (SizeT I = 0; I < Inst->getSrcSize(); ++I) {
276 Operand *Src = Inst->getSrc(I);
277 SizeT NumVars = Src->getNumVars();
278 for (SizeT J = 0; J < NumVars; ++J) {
279 const Variable *Var = Src->getVar(J);
280 if (!Var->getLiveRange().containsValue(InstNumber)) {
281 Valid = false;
282 Str << "Liveness error: inst " << Inst->getNumber() << " var ";
283 Var->dump(this);
284 Str << " live range " << Var->getLiveRange() << "\n";
285 }
286 }
287 }
288 }
289 }
290 return Valid;
291}
292
Jim Stichnothf7c9a142014-04-29 10:52:43 -0700293// ======================== Dump routines ======================== //
294
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700295void Cfg::emit() {
296 Ostream &Str = Ctx->getStrEmit();
297 Timer T_emit;
298 if (!Ctx->testAndSetHasEmittedFirstMethod()) {
299 // Print a helpful command for assembling the output.
300 // TODO: have the Target emit the header
301 // TODO: need a per-file emit in addition to per-CFG
302 Str << "# $LLVM_BIN_PATH/llvm-mc"
303 << " -arch=x86"
304 << " -x86-asm-syntax=intel"
305 << " -filetype=obj"
306 << " -o=MyObj.o"
307 << "\n\n";
308 }
309 Str << "\t.text\n";
Jim Stichnoth989a7032014-08-08 10:13:44 -0700310 IceString MangledName = getContext()->mangleName(getFunctionName());
311 if (Ctx->getFlags().FunctionSections)
Jim Stichnothbfb03e52014-08-26 10:29:05 -0700312 Str << "\t.section\t.text." << MangledName << ",\"ax\",@progbits\n";
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700313 if (!getInternal()) {
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700314 Str << "\t.globl\t" << MangledName << "\n";
315 Str << "\t.type\t" << MangledName << ",@function\n";
316 }
Jan Voungb17f61d2014-08-28 16:00:53 -0700317 Str << "\t.p2align " << getTarget()->getBundleAlignLog2Bytes() << ",0x";
318 llvm::ArrayRef<uint8_t> Pad = getTarget()->getNonExecBundlePadding();
319 for (llvm::ArrayRef<uint8_t>::iterator I = Pad.begin(), E = Pad.end();
320 I != E; ++I) {
321 Str.write_hex(*I);
322 }
323 Str << "\n";
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700324 for (NodeList::const_iterator I = Nodes.begin(), E = Nodes.end(); I != E;
325 ++I) {
326 (*I)->emit(this);
327 }
328 Str << "\n";
329 T_emit.printElapsedUs(Ctx, "emit()");
330}
331
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700332// Dumps the IR with an optional introductory message.
333void Cfg::dump(const IceString &Message) {
334 if (!Ctx->isVerbose())
335 return;
Jim Stichnothf7c9a142014-04-29 10:52:43 -0700336 Ostream &Str = Ctx->getStrDump();
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700337 if (!Message.empty())
338 Str << "================ " << Message << " ================\n";
Jim Stichnothf7c9a142014-04-29 10:52:43 -0700339 setCurrentNode(getEntryNode());
340 // Print function name+args
341 if (getContext()->isVerbose(IceV_Instructions)) {
342 Str << "define ";
343 if (getInternal())
344 Str << "internal ";
345 Str << ReturnType << " @" << getFunctionName() << "(";
346 for (SizeT i = 0; i < Args.size(); ++i) {
347 if (i > 0)
348 Str << ", ";
349 Str << Args[i]->getType() << " ";
350 Args[i]->dump(this);
351 }
352 Str << ") {\n";
353 }
354 setCurrentNode(NULL);
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700355 if (getContext()->isVerbose(IceV_Liveness)) {
356 // Print summary info about variables
357 for (VarList::const_iterator I = Variables.begin(), E = Variables.end();
358 I != E; ++I) {
359 Variable *Var = *I;
360 Str << "//"
361 << " multiblock=" << Var->isMultiblockLife() << " "
362 << " weight=" << Var->getWeight() << " ";
363 Var->dump(this);
Jim Stichnothca662e92014-07-10 15:32:36 -0700364 if (Variable *Pref = Var->getPreferredRegister()) {
365 Str << " pref=";
366 Pref->dump(this);
367 if (Var->getRegisterOverlap())
368 Str << ",overlap";
369 Str << " ";
370 }
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700371 Str << " LIVE=" << Var->getLiveRange() << "\n";
372 }
373 }
Jim Stichnothf7c9a142014-04-29 10:52:43 -0700374 // Print each basic block
375 for (NodeList::const_iterator I = Nodes.begin(), E = Nodes.end(); I != E;
376 ++I) {
377 (*I)->dump(this);
378 }
379 if (getContext()->isVerbose(IceV_Instructions)) {
380 Str << "}\n";
381 }
382}
383
384} // end of namespace Ice