1 //===-- LegalizeTypes.cpp - Common code for DAG type legalizer ------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the SelectionDAG::LegalizeTypes method. It transforms
11 // an arbitrary well-formed SelectionDAG to only consist of legal types. This
12 // is common code shared among the LegalizeTypes*.cpp files.
14 //===----------------------------------------------------------------------===//
16 #include "LegalizeTypes.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Support/CommandLine.h"
20 #include "llvm/Support/MathExtras.h"
25 ViewLegalizeTypesDAGs("view-legalize-types-dags", cl::Hidden,
26 cl::desc("Pop up a window to show dags before legalize types"));
28 static const bool ViewLegalizeTypesDAGs = 0;
33 /// run - This is the main entry point for the type legalizer. This does a
34 /// top-down traversal of the dag, legalizing types as it goes.
35 void DAGTypeLegalizer::run() {
36 // Create a dummy node (which is not added to allnodes), that adds a reference
37 // to the root node, preventing it from being deleted, and tracking any
38 // changes of the root.
39 HandleSDNode Dummy(DAG.getRoot());
41 // The root of the dag may dangle to deleted nodes until the type legalizer is
42 // done. Set it to null to avoid confusion.
43 DAG.setRoot(SDOperand());
45 // Walk all nodes in the graph, assigning them a NodeID of 'ReadyToProcess'
46 // (and remembering them) if they are leaves and assigning 'NewNode' if
48 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
49 E = DAG.allnodes_end(); I != E; ++I) {
50 if (I->getNumOperands() == 0) {
51 I->setNodeId(ReadyToProcess);
52 Worklist.push_back(I);
54 I->setNodeId(NewNode);
58 // Now that we have a set of nodes to process, handle them all.
59 while (!Worklist.empty()) {
60 SDNode *N = Worklist.back();
62 assert(N->getNodeId() == ReadyToProcess &&
63 "Node should be ready if on worklist!");
65 // Scan the values produced by the node, checking to see if any result
68 unsigned NumResults = N->getNumValues();
70 MVT::ValueType ResultVT = N->getValueType(i);
71 switch (getTypeAction(ResultVT)) {
73 assert(false && "Unknown action!");
83 FloatToIntResult(N, i);
86 ScalarizeResult(N, i);
92 } while (++i < NumResults);
94 // Scan the operand list for the node, handling any nodes with operands that
97 unsigned NumOperands = N->getNumOperands();
98 bool NeedsRevisit = false;
99 for (i = 0; i != NumOperands; ++i) {
100 MVT::ValueType OpVT = N->getOperand(i).getValueType();
101 switch (getTypeAction(OpVT)) {
103 assert(false && "Unknown action!");
107 NeedsRevisit = PromoteOperand(N, i);
110 NeedsRevisit = ExpandOperand(N, i);
113 NeedsRevisit = FloatToIntOperand(N, i);
116 NeedsRevisit = ScalarizeOperand(N, i);
119 NeedsRevisit = SplitOperand(N, i);
125 // If the node needs revisiting, don't add all users to the worklist etc.
129 if (i == NumOperands)
130 DEBUG(cerr << "Legally typed node: "; N->dump(&DAG); cerr << "\n");
134 // If we reach here, the node was processed, potentially creating new nodes.
135 // Mark it as processed and add its users to the worklist as appropriate.
136 N->setNodeId(Processed);
138 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
140 SDNode *User = UI->getUser();
141 int NodeID = User->getNodeId();
142 assert(NodeID != ReadyToProcess && NodeID != Processed &&
143 "Invalid node id for user of unprocessed node!");
145 // This node has two options: it can either be a new node or its Node ID
146 // may be a count of the number of operands it has that are not ready.
148 User->setNodeId(NodeID-1);
150 // If this was the last use it was waiting on, add it to the ready list.
151 if (NodeID-1 == ReadyToProcess)
152 Worklist.push_back(User);
156 // Otherwise, this node is new: this is the first operand of it that
157 // became ready. Its new NodeID is the number of operands it has minus 1
158 // (as this node is now processed).
159 assert(NodeID == NewNode && "Unknown node ID!");
160 User->setNodeId(User->getNumOperands()-1);
162 // If the node only has a single operand, it is now ready.
163 if (User->getNumOperands() == 1)
164 Worklist.push_back(User);
168 // If the root changed (e.g. it was a dead load, update the root).
169 DAG.setRoot(Dummy.getValue());
173 // Remove dead nodes. This is important to do for cleanliness but also before
174 // the checking loop below. Implicit folding by the DAG.getNode operators can
175 // cause unreachable nodes to be around with their flags set to new.
176 DAG.RemoveDeadNodes();
178 // In a debug build, scan all the nodes to make sure we found them all. This
179 // ensures that there are no cycles and that everything got processed.
181 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
182 E = DAG.allnodes_end(); I != E; ++I) {
185 // Check that all result types are legal.
186 for (unsigned i = 0, NumVals = I->getNumValues(); i < NumVals; ++i)
187 if (!isTypeLegal(I->getValueType(i))) {
188 cerr << "Result type " << i << " illegal!\n";
192 // Check that all operand types are legal.
193 for (unsigned i = 0, NumOps = I->getNumOperands(); i < NumOps; ++i)
194 if (!isTypeLegal(I->getOperand(i).getValueType())) {
195 cerr << "Operand type " << i << " illegal!\n";
199 if (I->getNodeId() != Processed) {
200 if (I->getNodeId() == NewNode)
201 cerr << "New node not 'noticed'?\n";
202 else if (I->getNodeId() > 0)
203 cerr << "Operand not processed?\n";
204 else if (I->getNodeId() == ReadyToProcess)
205 cerr << "Not added to worklist?\n";
210 I->dump(&DAG); cerr << "\n";
217 /// AnalyzeNewNode - The specified node is the root of a subtree of potentially
218 /// new nodes. Correct any processed operands (this may change the node) and
219 /// calculate the NodeId.
220 void DAGTypeLegalizer::AnalyzeNewNode(SDNode *&N) {
221 // If this was an existing node that is already done, we're done.
222 if (N->getNodeId() != NewNode)
225 // Okay, we know that this node is new. Recursively walk all of its operands
226 // to see if they are new also. The depth of this walk is bounded by the size
227 // of the new tree that was constructed (usually 2-3 nodes), so we don't worry
228 // about revisiting of nodes.
230 // As we walk the operands, keep track of the number of nodes that are
231 // processed. If non-zero, this will become the new nodeid of this node.
232 // Already processed operands may need to be remapped to the node that
233 // replaced them, which can result in our node changing. Since remapping
234 // is rare, the code tries to minimize overhead in the non-remapping case.
236 SmallVector<SDOperand, 8> NewOps;
237 unsigned NumProcessed = 0;
238 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
239 SDOperand OrigOp = N->getOperand(i);
240 SDOperand Op = OrigOp;
242 if (Op.Val->getNodeId() == Processed)
245 if (Op.Val->getNodeId() == NewNode)
246 AnalyzeNewNode(Op.Val);
247 else if (Op.Val->getNodeId() == Processed)
250 if (!NewOps.empty()) {
251 // Some previous operand changed. Add this one to the list.
252 NewOps.push_back(Op);
253 } else if (Op != OrigOp) {
254 // This is the first operand to change - add all operands so far.
255 for (unsigned j = 0; j < i; ++j)
256 NewOps.push_back(N->getOperand(j));
257 NewOps.push_back(Op);
261 // Some operands changed - update the node.
263 N = DAG.UpdateNodeOperands(SDOperand(N, 0), &NewOps[0], NewOps.size()).Val;
265 N->setNodeId(N->getNumOperands()-NumProcessed);
266 if (N->getNodeId() == ReadyToProcess)
267 Worklist.push_back(N);
270 void DAGTypeLegalizer::SanityCheck(SDNode *N) {
271 for (SmallVector<SDNode*, 128>::iterator I = Worklist.begin(),
272 E = Worklist.end(); I != E; ++I)
275 for (DenseMap<SDOperandImpl, SDOperand>::iterator I = ReplacedNodes.begin(),
276 E = ReplacedNodes.end(); I != E; ++I) {
277 assert(I->first.Val != N);
278 assert(I->second.Val != N);
281 for (DenseMap<SDOperandImpl, SDOperand>::iterator I = PromotedNodes.begin(),
282 E = PromotedNodes.end(); I != E; ++I) {
283 assert(I->first.Val != N);
284 assert(I->second.Val != N);
287 for (DenseMap<SDOperandImpl, SDOperand>::iterator
288 I = FloatToIntedNodes.begin(),
289 E = FloatToIntedNodes.end(); I != E; ++I) {
290 assert(I->first.Val != N);
291 assert(I->second.Val != N);
294 for (DenseMap<SDOperandImpl, SDOperand>::iterator I = ScalarizedNodes.begin(),
295 E = ScalarizedNodes.end(); I != E; ++I) {
296 assert(I->first.Val != N);
297 assert(I->second.Val != N);
300 for (DenseMap<SDOperandImpl, std::pair<SDOperand, SDOperand> >::iterator
301 I = ExpandedNodes.begin(), E = ExpandedNodes.end(); I != E; ++I) {
302 assert(I->first.Val != N);
303 assert(I->second.first.Val != N);
304 assert(I->second.second.Val != N);
307 for (DenseMap<SDOperandImpl, std::pair<SDOperand, SDOperand> >::iterator
308 I = SplitNodes.begin(), E = SplitNodes.end(); I != E; ++I) {
309 assert(I->first.Val != N);
310 assert(I->second.first.Val != N);
311 assert(I->second.second.Val != N);
316 /// NodeUpdateListener - This class is a DAGUpdateListener that listens for
317 /// updates to nodes and recomputes their ready state.
318 class VISIBILITY_HIDDEN NodeUpdateListener :
319 public SelectionDAG::DAGUpdateListener {
320 DAGTypeLegalizer &DTL;
322 NodeUpdateListener(DAGTypeLegalizer &dtl) : DTL(dtl) {}
324 virtual void NodeDeleted(SDNode *N) {
326 assert(N->getNodeId() != DAGTypeLegalizer::Processed &&
327 N->getNodeId() != DAGTypeLegalizer::ReadyToProcess &&
328 "RAUW deleted processed node!");
334 virtual void NodeUpdated(SDNode *N) {
335 // Node updates can mean pretty much anything. It is possible that an
336 // operand was set to something already processed (f.e.) in which case
337 // this node could become ready. Recompute its flags.
338 assert(N->getNodeId() != DAGTypeLegalizer::Processed &&
339 N->getNodeId() != DAGTypeLegalizer::ReadyToProcess &&
340 "RAUW updated processed node!");
341 DTL.ReanalyzeNode(N);
347 /// ReplaceValueWith - The specified value was legalized to the specified other
348 /// value. If they are different, update the DAG and NodeIDs replacing any uses
349 /// of From to use To instead.
350 void DAGTypeLegalizer::ReplaceValueWith(SDOperand From, SDOperand To) {
351 if (From == To) return;
353 // If expansion produced new nodes, make sure they are properly marked.
354 AnalyzeNewNode(To.Val);
356 // Anything that used the old node should now use the new one. Note that this
357 // can potentially cause recursive merging.
358 NodeUpdateListener NUL(*this);
359 DAG.ReplaceAllUsesOfValueWith(From, To, &NUL);
361 // The old node may still be present in ExpandedNodes or PromotedNodes.
362 // Inform them about the replacement.
363 ReplacedNodes[From] = To;
366 /// ReplaceNodeWith - Replace uses of the 'from' node's results with the 'to'
367 /// node's results. The from and to node must define identical result types.
368 void DAGTypeLegalizer::ReplaceNodeWith(SDNode *From, SDNode *To) {
369 if (From == To) return;
371 // If expansion produced new nodes, make sure they are properly marked.
374 assert(From->getNumValues() == To->getNumValues() &&
375 "Node results don't match");
377 // Anything that used the old node should now use the new one. Note that this
378 // can potentially cause recursive merging.
379 NodeUpdateListener NUL(*this);
380 DAG.ReplaceAllUsesWith(From, To, &NUL);
382 // The old node may still be present in ExpandedNodes or PromotedNodes.
383 // Inform them about the replacement.
384 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) {
385 assert(From->getValueType(i) == To->getValueType(i) &&
386 "Node results don't match");
387 ReplacedNodes[SDOperand(From, i)] = SDOperand(To, i);
392 /// RemapNode - If the specified value was already legalized to another value,
393 /// replace it by that value.
394 void DAGTypeLegalizer::RemapNode(SDOperand &N) {
395 DenseMap<SDOperandImpl, SDOperand>::iterator I = ReplacedNodes.find(N);
396 if (I != ReplacedNodes.end()) {
397 // Use path compression to speed up future lookups if values get multiply
398 // replaced with other values.
399 RemapNode(I->second);
404 void DAGTypeLegalizer::SetPromotedOp(SDOperand Op, SDOperand Result) {
405 AnalyzeNewNode(Result.Val);
407 SDOperand &OpEntry = PromotedNodes[Op];
408 assert(OpEntry.Val == 0 && "Node is already promoted!");
412 void DAGTypeLegalizer::SetIntegerOp(SDOperand Op, SDOperand Result) {
413 AnalyzeNewNode(Result.Val);
415 SDOperand &OpEntry = FloatToIntedNodes[Op];
416 assert(OpEntry.Val == 0 && "Node is already converted to integer!");
420 void DAGTypeLegalizer::SetScalarizedOp(SDOperand Op, SDOperand Result) {
421 AnalyzeNewNode(Result.Val);
423 SDOperand &OpEntry = ScalarizedNodes[Op];
424 assert(OpEntry.Val == 0 && "Node is already scalarized!");
428 void DAGTypeLegalizer::GetExpandedOp(SDOperand Op, SDOperand &Lo,
430 std::pair<SDOperand, SDOperand> &Entry = ExpandedNodes[Op];
431 RemapNode(Entry.first);
432 RemapNode(Entry.second);
433 assert(Entry.first.Val && "Operand isn't expanded");
438 void DAGTypeLegalizer::SetExpandedOp(SDOperand Op, SDOperand Lo, SDOperand Hi) {
439 // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
440 AnalyzeNewNode(Lo.Val);
441 AnalyzeNewNode(Hi.Val);
443 // Remember that this is the result of the node.
444 std::pair<SDOperand, SDOperand> &Entry = ExpandedNodes[Op];
445 assert(Entry.first.Val == 0 && "Node already expanded");
450 void DAGTypeLegalizer::GetSplitOp(SDOperand Op, SDOperand &Lo, SDOperand &Hi) {
451 std::pair<SDOperand, SDOperand> &Entry = SplitNodes[Op];
452 RemapNode(Entry.first);
453 RemapNode(Entry.second);
454 assert(Entry.first.Val && "Operand isn't split");
459 void DAGTypeLegalizer::SetSplitOp(SDOperand Op, SDOperand Lo, SDOperand Hi) {
460 // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
461 AnalyzeNewNode(Lo.Val);
462 AnalyzeNewNode(Hi.Val);
464 // Remember that this is the result of the node.
465 std::pair<SDOperand, SDOperand> &Entry = SplitNodes[Op];
466 assert(Entry.first.Val == 0 && "Node already split");
472 /// BitConvertToInteger - Convert to an integer of the same size.
473 SDOperand DAGTypeLegalizer::BitConvertToInteger(SDOperand Op) {
474 return DAG.getNode(ISD::BIT_CONVERT,
475 MVT::getIntegerType(MVT::getSizeInBits(Op.getValueType())),
479 SDOperand DAGTypeLegalizer::CreateStackStoreLoad(SDOperand Op,
480 MVT::ValueType DestVT) {
481 // Create the stack frame object.
482 SDOperand FIPtr = DAG.CreateStackTemporary(DestVT);
484 // Emit a store to the stack slot.
485 SDOperand Store = DAG.getStore(DAG.getEntryNode(), Op, FIPtr, NULL, 0);
486 // Result is a load from the stack slot.
487 return DAG.getLoad(DestVT, Store, FIPtr, NULL, 0);
490 /// JoinIntegers - Build an integer with low bits Lo and high bits Hi.
491 SDOperand DAGTypeLegalizer::JoinIntegers(SDOperand Lo, SDOperand Hi) {
492 MVT::ValueType LVT = Lo.getValueType();
493 MVT::ValueType HVT = Hi.getValueType();
494 MVT::ValueType NVT = MVT::getIntegerType(MVT::getSizeInBits(LVT) +
495 MVT::getSizeInBits(HVT));
497 Lo = DAG.getNode(ISD::ZERO_EXTEND, NVT, Lo);
498 Hi = DAG.getNode(ISD::ANY_EXTEND, NVT, Hi);
499 Hi = DAG.getNode(ISD::SHL, NVT, Hi, DAG.getConstant(MVT::getSizeInBits(LVT),
500 TLI.getShiftAmountTy()));
501 return DAG.getNode(ISD::OR, NVT, Lo, Hi);
504 /// SplitInteger - Return the lower LoVT bits of Op in Lo and the upper HiVT
506 void DAGTypeLegalizer::SplitInteger(SDOperand Op,
507 MVT::ValueType LoVT, MVT::ValueType HiVT,
508 SDOperand &Lo, SDOperand &Hi) {
509 assert(MVT::getSizeInBits(LoVT) + MVT::getSizeInBits(HiVT) ==
510 MVT::getSizeInBits(Op.getValueType()) && "Invalid integer splitting!");
511 Lo = DAG.getNode(ISD::TRUNCATE, LoVT, Op);
512 Hi = DAG.getNode(ISD::SRL, Op.getValueType(), Op,
513 DAG.getConstant(MVT::getSizeInBits(LoVT),
514 TLI.getShiftAmountTy()));
515 Hi = DAG.getNode(ISD::TRUNCATE, HiVT, Hi);
518 /// SplitInteger - Return the lower and upper halves of Op's bits in a value type
519 /// half the size of Op's.
520 void DAGTypeLegalizer::SplitInteger(SDOperand Op,
521 SDOperand &Lo, SDOperand &Hi) {
522 MVT::ValueType HalfVT =
523 MVT::getIntegerType(MVT::getSizeInBits(Op.getValueType())/2);
524 SplitInteger(Op, HalfVT, HalfVT, Lo, Hi);
527 //===----------------------------------------------------------------------===//
529 //===----------------------------------------------------------------------===//
531 /// LegalizeTypes - This transforms the SelectionDAG into a SelectionDAG that
532 /// only uses types natively supported by the target.
534 /// Note that this is an involved process that may invalidate pointers into
536 void SelectionDAG::LegalizeTypes() {
537 if (ViewLegalizeTypesDAGs) viewGraph();
539 DAGTypeLegalizer(*this).run();