Some LegalizeTypes code factorization and minor
[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 Scalarize:
83         ScalarizeResult(N, i);
84         goto NodeDone;
85       case Split:
86         SplitResult(N, i);
87         goto NodeDone;
88       }
89     } while (++i < NumResults);
90
91     // Scan the operand list for the node, handling any nodes with operands that
92     // are illegal.
93     {
94     unsigned NumOperands = N->getNumOperands();
95     bool NeedsRevisit = false;
96     for (i = 0; i != NumOperands; ++i) {
97       MVT::ValueType OpVT = N->getOperand(i).getValueType();
98       switch (getTypeAction(OpVT)) {
99       default:
100         assert(false && "Unknown action!");
101       case Legal:
102         continue;
103       case Promote:
104         NeedsRevisit = PromoteOperand(N, i);
105         break;
106       case Expand:
107         NeedsRevisit = ExpandOperand(N, i);
108         break;
109       case Scalarize:
110         NeedsRevisit = ScalarizeOperand(N, i);
111         break;
112       case Split:
113         NeedsRevisit = SplitOperand(N, i);
114         break;
115       }
116       break;
117     }
118
119     // If the node needs revisiting, don't add all users to the worklist etc.
120     if (NeedsRevisit)
121       continue;
122     
123     if (i == NumOperands)
124       DEBUG(cerr << "Legally typed node: "; N->dump(&DAG); cerr << "\n");
125     }
126 NodeDone:
127
128     // If we reach here, the node was processed, potentially creating new nodes.
129     // Mark it as processed and add its users to the worklist as appropriate.
130     N->setNodeId(Processed);
131     
132     for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
133          UI != E; ++UI) {
134       SDNode *User = *UI;
135       int NodeID = User->getNodeId();
136       assert(NodeID != ReadyToProcess && NodeID != Processed &&
137              "Invalid node id for user of unprocessed node!");
138       
139       // This node has two options: it can either be a new node or its Node ID
140       // may be a count of the number of operands it has that are not ready.
141       if (NodeID > 0) {
142         User->setNodeId(NodeID-1);
143         
144         // If this was the last use it was waiting on, add it to the ready list.
145         if (NodeID-1 == ReadyToProcess)
146           Worklist.push_back(User);
147         continue;
148       }
149       
150       // Otherwise, this node is new: this is the first operand of it that
151       // became ready.  Its new NodeID is the number of operands it has minus 1
152       // (as this node is now processed).
153       assert(NodeID == NewNode && "Unknown node ID!");
154       User->setNodeId(User->getNumOperands()-1);
155       
156       // If the node only has a single operand, it is now ready.
157       if (User->getNumOperands() == 1)
158         Worklist.push_back(User);
159     }
160   }
161   
162   // If the root changed (e.g. it was a dead load, update the root).
163   DAG.setRoot(Dummy.getValue());
164
165   //DAG.viewGraph();
166
167   // Remove dead nodes.  This is important to do for cleanliness but also before
168   // the checking loop below.  Implicit folding by the DAG.getNode operators can
169   // cause unreachable nodes to be around with their flags set to new.
170   DAG.RemoveDeadNodes();
171
172   // In a debug build, scan all the nodes to make sure we found them all.  This
173   // ensures that there are no cycles and that everything got processed.
174 #ifndef NDEBUG
175   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
176        E = DAG.allnodes_end(); I != E; ++I) {
177     bool Failed = false;
178
179     // Check that all result types are legal.
180     for (unsigned i = 0, NumVals = I->getNumValues(); i < NumVals; ++i)
181       if (!isTypeLegal(I->getValueType(i))) {
182         cerr << "Result type " << i << " illegal!\n";
183         Failed = true;
184       }
185
186     // Check that all operand types are legal.
187     for (unsigned i = 0, NumOps = I->getNumOperands(); i < NumOps; ++i)
188       if (!isTypeLegal(I->getOperand(i).getValueType())) {
189         cerr << "Operand type " << i << " illegal!\n";
190         Failed = true;
191       }
192
193     if (I->getNodeId() != Processed) {
194        if (I->getNodeId() == NewNode)
195          cerr << "New node not 'noticed'?\n";
196        else if (I->getNodeId() > 0)
197          cerr << "Operand not processed?\n";
198        else if (I->getNodeId() == ReadyToProcess)
199          cerr << "Not added to worklist?\n";
200        Failed = true;
201     }
202
203     if (Failed) {
204       I->dump(&DAG); cerr << "\n";
205       abort();
206     }
207   }
208 #endif
209 }
210
211 /// AnalyzeNewNode - The specified node is the root of a subtree of potentially
212 /// new nodes.  Correct any processed operands (this may change the node) and
213 /// calculate the NodeId.
214 void DAGTypeLegalizer::AnalyzeNewNode(SDNode *&N) {
215   // If this was an existing node that is already done, we're done.
216   if (N->getNodeId() != NewNode)
217     return;
218
219   // Okay, we know that this node is new.  Recursively walk all of its operands
220   // to see if they are new also.  The depth of this walk is bounded by the size
221   // of the new tree that was constructed (usually 2-3 nodes), so we don't worry
222   // about revisiting of nodes.
223   //
224   // As we walk the operands, keep track of the number of nodes that are
225   // processed.  If non-zero, this will become the new nodeid of this node.
226   // Already processed operands may need to be remapped to the node that
227   // replaced them, which can result in our node changing.  Since remapping
228   // is rare, the code tries to minimize overhead in the non-remapping case.
229
230   SmallVector<SDOperand, 8> NewOps;
231   unsigned NumProcessed = 0;
232   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
233     SDOperand OrigOp = N->getOperand(i);
234     SDOperand Op = OrigOp;
235
236     if (Op.Val->getNodeId() == Processed)
237       RemapNode(Op);
238
239     if (Op.Val->getNodeId() == NewNode)
240       AnalyzeNewNode(Op.Val);
241     else if (Op.Val->getNodeId() == Processed)
242       ++NumProcessed;
243
244     if (!NewOps.empty()) {
245       // Some previous operand changed.  Add this one to the list.
246       NewOps.push_back(Op);
247     } else if (Op != OrigOp) {
248       // This is the first operand to change - add all operands so far.
249       for (unsigned j = 0; j < i; ++j)
250         NewOps.push_back(N->getOperand(j));
251       NewOps.push_back(Op);
252     }
253   }
254
255   // Some operands changed - update the node.
256   if (!NewOps.empty())
257     N = DAG.UpdateNodeOperands(SDOperand(N, 0), &NewOps[0], NewOps.size()).Val;
258
259   N->setNodeId(N->getNumOperands()-NumProcessed);
260   if (N->getNodeId() == ReadyToProcess)
261     Worklist.push_back(N);
262 }
263
264 namespace {
265   /// NodeUpdateListener - This class is a DAGUpdateListener that listens for
266   /// updates to nodes and recomputes their ready state.
267   class VISIBILITY_HIDDEN NodeUpdateListener :
268     public SelectionDAG::DAGUpdateListener {
269     DAGTypeLegalizer &DTL;
270   public:
271     NodeUpdateListener(DAGTypeLegalizer &dtl) : DTL(dtl) {}
272
273     virtual void NodeDeleted(SDNode *N) {
274       // Ignore deletes.
275       assert(N->getNodeId() != DAGTypeLegalizer::Processed &&
276              N->getNodeId() != DAGTypeLegalizer::ReadyToProcess &&
277              "RAUW deleted processed node!");
278     }
279
280     virtual void NodeUpdated(SDNode *N) {
281       // Node updates can mean pretty much anything.  It is possible that an
282       // operand was set to something already processed (f.e.) in which case
283       // this node could become ready.  Recompute its flags.
284       assert(N->getNodeId() != DAGTypeLegalizer::Processed &&
285              N->getNodeId() != DAGTypeLegalizer::ReadyToProcess &&
286              "RAUW updated processed node!");
287       DTL.ReanalyzeNode(N);
288     }
289   };
290 }
291
292
293 /// ReplaceValueWith - The specified value was legalized to the specified other
294 /// value.  If they are different, update the DAG and NodeIDs replacing any uses
295 /// of From to use To instead.
296 void DAGTypeLegalizer::ReplaceValueWith(SDOperand From, SDOperand To) {
297   if (From == To) return;
298
299   // If expansion produced new nodes, make sure they are properly marked.
300   AnalyzeNewNode(To.Val);
301
302   // Anything that used the old node should now use the new one.  Note that this
303   // can potentially cause recursive merging.
304   NodeUpdateListener NUL(*this);
305   DAG.ReplaceAllUsesOfValueWith(From, To, &NUL);
306
307   // The old node may still be present in ExpandedNodes or PromotedNodes.
308   // Inform them about the replacement.
309   ReplacedNodes[From] = To;
310 }
311
312 /// ReplaceNodeWith - Replace uses of the 'from' node's results with the 'to'
313 /// node's results.  The from and to node must define identical result types.
314 void DAGTypeLegalizer::ReplaceNodeWith(SDNode *From, SDNode *To) {
315   if (From == To) return;
316
317   // If expansion produced new nodes, make sure they are properly marked.
318   AnalyzeNewNode(To);
319
320   assert(From->getNumValues() == To->getNumValues() &&
321          "Node results don't match");
322
323   // Anything that used the old node should now use the new one.  Note that this
324   // can potentially cause recursive merging.
325   NodeUpdateListener NUL(*this);
326   DAG.ReplaceAllUsesWith(From, To, &NUL);
327   
328   // The old node may still be present in ExpandedNodes or PromotedNodes.
329   // Inform them about the replacement.
330   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) {
331     assert(From->getValueType(i) == To->getValueType(i) &&
332            "Node results don't match");
333     ReplacedNodes[SDOperand(From, i)] = SDOperand(To, i);
334   }
335 }
336
337
338 /// RemapNode - If the specified value was already legalized to another value,
339 /// replace it by that value.
340 void DAGTypeLegalizer::RemapNode(SDOperand &N) {
341   DenseMap<SDOperand, SDOperand>::iterator I = ReplacedNodes.find(N);
342   if (I != ReplacedNodes.end()) {
343     // Use path compression to speed up future lookups if values get multiply
344     // replaced with other values.
345     RemapNode(I->second);
346     N = I->second;
347   }
348 }
349
350 void DAGTypeLegalizer::SetPromotedOp(SDOperand Op, SDOperand Result) {
351   AnalyzeNewNode(Result.Val);
352
353   SDOperand &OpEntry = PromotedNodes[Op];
354   assert(OpEntry.Val == 0 && "Node is already promoted!");
355   OpEntry = Result;
356 }
357
358 void DAGTypeLegalizer::SetScalarizedOp(SDOperand Op, SDOperand Result) {
359   AnalyzeNewNode(Result.Val);
360
361   SDOperand &OpEntry = ScalarizedNodes[Op];
362   assert(OpEntry.Val == 0 && "Node is already scalarized!");
363   OpEntry = Result;
364 }
365
366
367 void DAGTypeLegalizer::GetExpandedOp(SDOperand Op, SDOperand &Lo, 
368                                      SDOperand &Hi) {
369   std::pair<SDOperand, SDOperand> &Entry = ExpandedNodes[Op];
370   RemapNode(Entry.first);
371   RemapNode(Entry.second);
372   assert(Entry.first.Val && "Operand isn't expanded");
373   Lo = Entry.first;
374   Hi = Entry.second;
375 }
376
377 void DAGTypeLegalizer::SetExpandedOp(SDOperand Op, SDOperand Lo, SDOperand Hi) {
378   // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
379   AnalyzeNewNode(Lo.Val);
380   AnalyzeNewNode(Hi.Val);
381
382   // Remember that this is the result of the node.
383   std::pair<SDOperand, SDOperand> &Entry = ExpandedNodes[Op];
384   assert(Entry.first.Val == 0 && "Node already expanded");
385   Entry.first = Lo;
386   Entry.second = Hi;
387 }
388
389 void DAGTypeLegalizer::GetSplitOp(SDOperand Op, SDOperand &Lo, SDOperand &Hi) {
390   std::pair<SDOperand, SDOperand> &Entry = SplitNodes[Op];
391   RemapNode(Entry.first);
392   RemapNode(Entry.second);
393   assert(Entry.first.Val && "Operand isn't split");
394   Lo = Entry.first;
395   Hi = Entry.second;
396 }
397
398 void DAGTypeLegalizer::SetSplitOp(SDOperand Op, SDOperand Lo, SDOperand Hi) {
399   // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
400   AnalyzeNewNode(Lo.Val);
401   AnalyzeNewNode(Hi.Val);
402
403   // Remember that this is the result of the node.
404   std::pair<SDOperand, SDOperand> &Entry = SplitNodes[Op];
405   assert(Entry.first.Val == 0 && "Node already split");
406   Entry.first = Lo;
407   Entry.second = Hi;
408 }
409
410
411 SDOperand DAGTypeLegalizer::CreateStackStoreLoad(SDOperand Op, 
412                                                  MVT::ValueType DestVT) {
413   // Create the stack frame object.
414   SDOperand FIPtr = DAG.CreateStackTemporary(DestVT);
415   
416   // Emit a store to the stack slot.
417   SDOperand Store = DAG.getStore(DAG.getEntryNode(), Op, FIPtr, NULL, 0);
418   // Result is a load from the stack slot.
419   return DAG.getLoad(DestVT, Store, FIPtr, NULL, 0);
420 }
421
422 /// HandleMemIntrinsic - This handles memcpy/memset/memmove with invalid
423 /// operands.  This promotes or expands the operands as required.
424 SDOperand DAGTypeLegalizer::HandleMemIntrinsic(SDNode *N) {
425   // The chain and pointer [operands #0 and #1] are always valid types.
426   SDOperand Chain = N->getOperand(0);
427   SDOperand Ptr   = N->getOperand(1);
428   SDOperand Op2   = N->getOperand(2);
429   
430   // Op #2 is either a value (memset) or a pointer.  Promote it if required.
431   switch (getTypeAction(Op2.getValueType())) {
432   default: assert(0 && "Unknown action for pointer/value operand");
433   case Legal: break;
434   case Promote: Op2 = GetPromotedOp(Op2); break;
435   }
436
437   // The length could have any action required.
438   SDOperand Length = N->getOperand(3);
439   switch (getTypeAction(Length.getValueType())) {
440   default: assert(0 && "Unknown action for memop operand");
441   case Legal: break;
442   case Promote: Length = GetPromotedZExtOp(Length); break;
443   case Expand:
444     SDOperand Dummy;  // discard the high part.
445     GetExpandedOp(Length, Length, Dummy);
446     break;
447   }
448
449   SDOperand Align = N->getOperand(4);
450   switch (getTypeAction(Align.getValueType())) {
451   default: assert(0 && "Unknown action for memop operand");
452   case Legal: break;
453   case Promote: Align = GetPromotedZExtOp(Align); break;
454   }
455
456   SDOperand AlwaysInline = N->getOperand(5);
457   switch (getTypeAction(AlwaysInline.getValueType())) {
458   default: assert(0 && "Unknown action for memop operand");
459   case Legal: break;
460   case Promote: AlwaysInline = GetPromotedZExtOp(AlwaysInline); break;
461   }
462
463   SDOperand Ops[] = { Chain, Ptr, Op2, Length, Align, AlwaysInline };
464   return DAG.UpdateNodeOperands(SDOperand(N, 0), Ops, 6);
465 }
466
467 /// JoinIntegers - Build an integer with low bits Lo and high bits Hi.
468 SDOperand DAGTypeLegalizer::JoinIntegers(SDOperand Lo, SDOperand Hi) {
469   MVT::ValueType LVT = Lo.getValueType();
470   MVT::ValueType HVT = Hi.getValueType();
471   MVT::ValueType NVT = MVT::getIntegerType(MVT::getSizeInBits(LVT) +
472                                            MVT::getSizeInBits(HVT));
473
474   Lo = DAG.getNode(ISD::ZERO_EXTEND, NVT, Lo);
475   Hi = DAG.getNode(ISD::ANY_EXTEND, NVT, Hi);
476   Hi = DAG.getNode(ISD::SHL, NVT, Hi, DAG.getConstant(MVT::getSizeInBits(LVT),
477                                                       TLI.getShiftAmountTy()));
478   return DAG.getNode(ISD::OR, NVT, Lo, Hi);
479 }
480
481 /// SplitInteger - Return the lower LoVT bits of Op in Lo and the upper HiVT
482 /// bits in Hi.
483 void DAGTypeLegalizer::SplitInteger(SDOperand Op,
484                                     MVT::ValueType LoVT, MVT::ValueType HiVT,
485                                     SDOperand &Lo, SDOperand &Hi) {
486   assert(MVT::getSizeInBits(LoVT) + MVT::getSizeInBits(HiVT) ==
487          MVT::getSizeInBits(Op.getValueType()) && "Invalid integer splitting!");
488   Lo = DAG.getNode(ISD::TRUNCATE, LoVT, Op);
489   Hi = DAG.getNode(ISD::SRL, Op.getValueType(), Op,
490                    DAG.getConstant(MVT::getSizeInBits(LoVT),
491                                    TLI.getShiftAmountTy()));
492   Hi = DAG.getNode(ISD::TRUNCATE, HiVT, Hi);
493 }
494
495 /// SplitInteger - Return the lower and upper halves of Op's bits in a value type
496 /// half the size of Op's.
497 void DAGTypeLegalizer::SplitInteger(SDOperand Op,
498                                     SDOperand &Lo, SDOperand &Hi) {
499   MVT::ValueType HalfVT =
500     MVT::getIntegerType(MVT::getSizeInBits(Op.getValueType())/2);
501   SplitInteger(Op, HalfVT, HalfVT, Lo, Hi);
502 }
503
504 //===----------------------------------------------------------------------===//
505 //  Entry Point
506 //===----------------------------------------------------------------------===//
507
508 /// LegalizeTypes - This transforms the SelectionDAG into a SelectionDAG that
509 /// only uses types natively supported by the target.
510 ///
511 /// Note that this is an involved process that may invalidate pointers into
512 /// the graph.
513 void SelectionDAG::LegalizeTypes() {
514   if (ViewLegalizeTypesDAGs) viewGraph();
515   
516   DAGTypeLegalizer(*this).run();
517 }