34f99da49fa7f074542d77d93da6af391b45ad57
[oota-llvm.git] / lib / CodeGen / SelectionDAG / LegalizeTypes.cpp
1 //===-- LegalizeTypes.cpp - Common code for DAG type legalizer ------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // 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.
13 //
14 //===----------------------------------------------------------------------===//
15
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"
21 using namespace llvm;
22
23 #ifndef NDEBUG
24 static cl::opt<bool>
25 ViewLegalizeTypesDAGs("view-legalize-types-dags", cl::Hidden,
26                 cl::desc("Pop up a window to show dags before legalize types"));
27 #else
28 static const bool ViewLegalizeTypesDAGs = 0;
29 #endif
30
31
32
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());
40
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());
44   
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
47   // non-leaves.
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);
53     } else {
54       I->setNodeId(NewNode);
55     }
56   }
57   
58   // Now that we have a set of nodes to process, handle them all.
59   while (!Worklist.empty()) {
60     SDNode *N = Worklist.back();
61     Worklist.pop_back();
62     assert(N->getNodeId() == ReadyToProcess &&
63            "Node should be ready if on worklist!");
64     
65     // Scan the values produced by the node, checking to see if any result
66     // types are illegal.
67     unsigned i = 0;
68     unsigned NumResults = N->getNumValues();
69     do {
70       MVT::ValueType ResultVT = N->getValueType(i);
71       switch (getTypeAction(ResultVT)) {
72       default:
73         assert(false && "Unknown action!");
74       case Legal:
75         break;
76       case Promote:
77         PromoteResult(N, i);
78         goto NodeDone;
79       case Expand:
80         ExpandResult(N, i);
81         goto NodeDone;
82       case FloatToInt:
83         FloatToIntResult(N, i);
84         goto NodeDone;
85       case Scalarize:
86         ScalarizeResult(N, i);
87         goto NodeDone;
88       case Split:
89         SplitResult(N, i);
90         goto NodeDone;
91       }
92     } while (++i < NumResults);
93
94     // Scan the operand list for the node, handling any nodes with operands that
95     // are illegal.
96     {
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)) {
102       default:
103         assert(false && "Unknown action!");
104       case Legal:
105         continue;
106       case Promote:
107         NeedsRevisit = PromoteOperand(N, i);
108         break;
109       case Expand:
110         NeedsRevisit = ExpandOperand(N, i);
111         break;
112       case FloatToInt:
113         NeedsRevisit = FloatToIntOperand(N, i);
114         break;
115       case Scalarize:
116         NeedsRevisit = ScalarizeOperand(N, i);
117         break;
118       case Split:
119         NeedsRevisit = SplitOperand(N, i);
120         break;
121       }
122       break;
123     }
124
125     // If the node needs revisiting, don't add all users to the worklist etc.
126     if (NeedsRevisit)
127       continue;
128     
129     if (i == NumOperands)
130       DEBUG(cerr << "Legally typed node: "; N->dump(&DAG); cerr << "\n");
131     }
132 NodeDone:
133
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);
137     
138     for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
139          UI != E; ++UI) {
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!");
144       
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.
147       if (NodeID > 0) {
148         User->setNodeId(NodeID-1);
149         
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);
153         continue;
154       }
155       
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);
161       
162       // If the node only has a single operand, it is now ready.
163       if (User->getNumOperands() == 1)
164         Worklist.push_back(User);
165     }
166   }
167   
168   // If the root changed (e.g. it was a dead load, update the root).
169   DAG.setRoot(Dummy.getValue());
170
171   //DAG.viewGraph();
172
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();
177
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.
180 #ifndef NDEBUG
181   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
182        E = DAG.allnodes_end(); I != E; ++I) {
183     bool Failed = false;
184
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";
189         Failed = true;
190       }
191
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";
196         Failed = true;
197       }
198
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";
206        Failed = true;
207     }
208
209     if (Failed) {
210       I->dump(&DAG); cerr << "\n";
211       abort();
212     }
213   }
214 #endif
215 }
216
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)
223     return;
224
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.
229   //
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.
235
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;
241
242     if (Op.Val->getNodeId() == Processed)
243       RemapNode(Op);
244
245     if (Op.Val->getNodeId() == NewNode)
246       AnalyzeNewNode(Op.Val);
247     else if (Op.Val->getNodeId() == Processed)
248       ++NumProcessed;
249
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);
258     }
259   }
260
261   // Some operands changed - update the node.
262   if (!NewOps.empty())
263     N = DAG.UpdateNodeOperands(SDOperand(N, 0), &NewOps[0], NewOps.size()).Val;
264
265   N->setNodeId(N->getNumOperands()-NumProcessed);
266   if (N->getNodeId() == ReadyToProcess)
267     Worklist.push_back(N);
268 }
269
270 void DAGTypeLegalizer::SanityCheck(SDNode *N) {
271   for (SmallVector<SDNode*, 128>::iterator I = Worklist.begin(),
272        E = Worklist.end(); I != E; ++I)
273     assert(*I != N);
274
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);
279   }
280
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);
285   }
286
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);
292   }
293
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);
298   }
299
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);
305   }
306
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);
312   }
313 }
314
315 namespace {
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;
321   public:
322     NodeUpdateListener(DAGTypeLegalizer &dtl) : DTL(dtl) {}
323
324     virtual void NodeDeleted(SDNode *N) {
325       // Ignore deletes.
326       assert(N->getNodeId() != DAGTypeLegalizer::Processed &&
327              N->getNodeId() != DAGTypeLegalizer::ReadyToProcess &&
328              "RAUW deleted processed node!");
329 #ifndef NDEBUG
330       DTL.SanityCheck(N);
331 #endif
332     }
333
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);
342     }
343   };
344 }
345
346
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;
352
353   // If expansion produced new nodes, make sure they are properly marked.
354   AnalyzeNewNode(To.Val);
355
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);
360
361   // The old node may still be present in ExpandedNodes or PromotedNodes.
362   // Inform them about the replacement.
363   ReplacedNodes[From] = To;
364 }
365
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;
370
371   // If expansion produced new nodes, make sure they are properly marked.
372   AnalyzeNewNode(To);
373
374   assert(From->getNumValues() == To->getNumValues() &&
375          "Node results don't match");
376
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);
381   
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);
388   }
389 }
390
391
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);
400     N = I->second;
401   }
402 }
403
404 void DAGTypeLegalizer::SetPromotedOp(SDOperand Op, SDOperand Result) {
405   AnalyzeNewNode(Result.Val);
406
407   SDOperand &OpEntry = PromotedNodes[Op];
408   assert(OpEntry.Val == 0 && "Node is already promoted!");
409   OpEntry = Result;
410 }
411
412 void DAGTypeLegalizer::SetIntegerOp(SDOperand Op, SDOperand Result) {
413   AnalyzeNewNode(Result.Val);
414
415   SDOperand &OpEntry = FloatToIntedNodes[Op];
416   assert(OpEntry.Val == 0 && "Node is already converted to integer!");
417   OpEntry = Result;
418 }
419
420 void DAGTypeLegalizer::SetScalarizedOp(SDOperand Op, SDOperand Result) {
421   AnalyzeNewNode(Result.Val);
422
423   SDOperand &OpEntry = ScalarizedNodes[Op];
424   assert(OpEntry.Val == 0 && "Node is already scalarized!");
425   OpEntry = Result;
426 }
427
428 void DAGTypeLegalizer::GetExpandedOp(SDOperand Op, SDOperand &Lo, 
429                                      SDOperand &Hi) {
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");
434   Lo = Entry.first;
435   Hi = Entry.second;
436 }
437
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);
442
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");
446   Entry.first = Lo;
447   Entry.second = Hi;
448 }
449
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");
455   Lo = Entry.first;
456   Hi = Entry.second;
457 }
458
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);
463
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");
467   Entry.first = Lo;
468   Entry.second = Hi;
469 }
470
471
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())),
476                      Op);
477 }
478
479 SDOperand DAGTypeLegalizer::CreateStackStoreLoad(SDOperand Op, 
480                                                  MVT::ValueType DestVT) {
481   // Create the stack frame object.
482   SDOperand FIPtr = DAG.CreateStackTemporary(DestVT);
483   
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);
488 }
489
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));
496
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);
502 }
503
504 /// SplitInteger - Return the lower LoVT bits of Op in Lo and the upper HiVT
505 /// bits in Hi.
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);
516 }
517
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);
525 }
526
527 //===----------------------------------------------------------------------===//
528 //  Entry Point
529 //===----------------------------------------------------------------------===//
530
531 /// LegalizeTypes - This transforms the SelectionDAG into a SelectionDAG that
532 /// only uses types natively supported by the target.
533 ///
534 /// Note that this is an involved process that may invalidate pointers into
535 /// the graph.
536 void SelectionDAG::LegalizeTypes() {
537   if (ViewLegalizeTypesDAGs) viewGraph();
538   
539   DAGTypeLegalizer(*this).run();
540 }