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