split scalarization out to its own file.
[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 was developed by Chris Lattner and is distributed under
6 // the University of Illinois Open Source 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/MathExtras.h"
20 using namespace llvm;
21
22 /// run - This is the main entry point for the type legalizer.  This does a
23 /// top-down traversal of the dag, legalizing types as it goes.
24 void DAGTypeLegalizer::run() {
25   // Create a dummy node (which is not added to allnodes), that adds a reference
26   // to the root node, preventing it from being deleted, and tracking any
27   // changes of the root.
28   HandleSDNode Dummy(DAG.getRoot());
29
30   // The root of the dag may dangle to deleted nodes until the type legalizer is
31   // done.  Set it to null to avoid confusion.
32   DAG.setRoot(SDOperand());
33   
34   // Walk all nodes in the graph, assigning them a NodeID of 'ReadyToProcess'
35   // (and remembering them) if they are leaves and assigning 'NewNode' if
36   // non-leaves.
37   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
38        E = DAG.allnodes_end(); I != E; ++I) {
39     if (I->getNumOperands() == 0) {
40       I->setNodeId(ReadyToProcess);
41       Worklist.push_back(I);
42     } else {
43       I->setNodeId(NewNode);
44     }
45   }
46   
47   // Now that we have a set of nodes to process, handle them all.
48   while (!Worklist.empty()) {
49     SDNode *N = Worklist.back();
50     Worklist.pop_back();
51     assert(N->getNodeId() == ReadyToProcess &&
52            "Node should be ready if on worklist!");
53     
54     // Scan the values produced by the node, checking to see if any result
55     // types are illegal.
56     unsigned i = 0;
57     unsigned NumResults = N->getNumValues();
58     do {
59       MVT::ValueType ResultVT = N->getValueType(i);
60       LegalizeAction Action = getTypeAction(ResultVT);
61       if (Action == Promote) {
62         PromoteResult(N, i);
63         goto NodeDone;
64       } else if (Action == Expand) {
65         // Expand can mean 1) split integer in half 2) scalarize single-element
66         // vector 3) split vector in half.
67         if (!MVT::isVector(ResultVT))
68           ExpandResult(N, i);
69         else if (MVT::getVectorNumElements(ResultVT) == 1)
70           ScalarizeResult(N, i);     // Scalarize the single-element vector.
71         else         // Split the vector in half.
72           assert(0 && "Vector splitting not implemented");
73         goto NodeDone;
74       } else {
75         assert(Action == Legal && "Unknown action!");
76       }
77     } while (++i < NumResults);
78     
79     // Scan the operand list for the node, handling any nodes with operands that
80     // are illegal.
81     {
82     unsigned NumOperands = N->getNumOperands();
83     bool NeedsRevisit = false;
84     for (i = 0; i != NumOperands; ++i) {
85       MVT::ValueType OpVT = N->getOperand(i).getValueType();
86       LegalizeAction Action = getTypeAction(OpVT);
87       if (Action == Promote) {
88         NeedsRevisit = PromoteOperand(N, i);
89         break;
90       } else if (Action == Expand) {
91         // Expand can mean 1) split integer in half 2) scalarize single-element
92         // vector 3) split vector in half.
93         if (!MVT::isVector(OpVT)) {
94           NeedsRevisit = ExpandOperand(N, i);
95         } else if (MVT::getVectorNumElements(OpVT) == 1) {
96           // Scalarize the single-element vector.
97           NeedsRevisit = ScalarizeOperand(N, i);
98         } else {
99           // Split the vector in half.
100           assert(0 && "Vector splitting not implemented");
101         }
102         break;
103       } else {
104         assert(Action == Legal && "Unknown action!");
105       }
106     }
107
108     // If the node needs revisiting, don't add all users to the worklist etc.
109     if (NeedsRevisit)
110       continue;
111     
112     if (i == NumOperands)
113       DEBUG(cerr << "Legally typed node: "; N->dump(&DAG); cerr << "\n");
114     }
115 NodeDone:
116
117     // If we reach here, the node was processed, potentially creating new nodes.
118     // Mark it as processed and add its users to the worklist as appropriate.
119     N->setNodeId(Processed);
120     
121     for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
122          UI != E; ++UI) {
123       SDNode *User = *UI;
124       int NodeID = User->getNodeId();
125       assert(NodeID != ReadyToProcess && NodeID != Processed &&
126              "Invalid node id for user of unprocessed node!");
127       
128       // This node has two options: it can either be a new node or its Node ID
129       // may be a count of the number of operands it has that are not ready.
130       if (NodeID > 0) {
131         User->setNodeId(NodeID-1);
132         
133         // If this was the last use it was waiting on, add it to the ready list.
134         if (NodeID-1 == ReadyToProcess)
135           Worklist.push_back(User);
136         continue;
137       }
138       
139       // Otherwise, this node is new: this is the first operand of it that
140       // became ready.  Its new NodeID is the number of operands it has minus 1
141       // (as this node is now processed).
142       assert(NodeID == NewNode && "Unknown node ID!");
143       User->setNodeId(User->getNumOperands()-1);
144       
145       // If the node only has a single operand, it is now ready.
146       if (User->getNumOperands() == 1)
147         Worklist.push_back(User);
148     }
149   }
150   
151   // If the root changed (e.g. it was a dead load, update the root).
152   DAG.setRoot(Dummy.getValue());
153
154   //DAG.viewGraph();
155
156   // Remove dead nodes.  This is important to do for cleanliness but also before
157   // the checking loop below.  Implicit folding by the DAG.getNode operators can
158   // cause unreachable nodes to be around with their flags set to new.
159   DAG.RemoveDeadNodes();
160
161   // In a debug build, scan all the nodes to make sure we found them all.  This
162   // ensures that there are no cycles and that everything got processed.
163 #ifndef NDEBUG
164   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
165        E = DAG.allnodes_end(); I != E; ++I) {
166     if (I->getNodeId() == Processed)
167       continue;
168     cerr << "Unprocessed node: ";
169     I->dump(&DAG); cerr << "\n";
170
171     if (I->getNodeId() == NewNode)
172       cerr << "New node not 'noticed'?\n";
173     else if (I->getNodeId() > 0)
174       cerr << "Operand not processed?\n";
175     else if (I->getNodeId() == ReadyToProcess)
176       cerr << "Not added to worklist?\n";
177     abort();
178   }
179 #endif
180 }
181
182 /// MarkNewNodes - The specified node is the root of a subtree of potentially
183 /// new nodes.  Add the correct NodeId to mark it.
184 void DAGTypeLegalizer::MarkNewNodes(SDNode *N) {
185   // If this was an existing node that is already done, we're done.
186   if (N->getNodeId() != NewNode)
187     return;
188
189   // Okay, we know that this node is new.  Recursively walk all of its operands
190   // to see if they are new also.  The depth of this walk is bounded by the size
191   // of the new tree that was constructed (usually 2-3 nodes), so we don't worry
192   // about revisiting of nodes.
193   //
194   // As we walk the operands, keep track of the number of nodes that are
195   // processed.  If non-zero, this will become the new nodeid of this node.
196   unsigned NumProcessed = 0;
197   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
198     int OpId = N->getOperand(i).Val->getNodeId();
199     if (OpId == NewNode)
200       MarkNewNodes(N->getOperand(i).Val);
201     else if (OpId == Processed)
202       ++NumProcessed;
203   }
204   
205   N->setNodeId(N->getNumOperands()-NumProcessed);
206   if (N->getNodeId() == ReadyToProcess)
207     Worklist.push_back(N);
208 }
209
210 /// ReplaceValueWith - The specified value was legalized to the specified other
211 /// value.  If they are different, update the DAG and NodeIDs replacing any uses
212 /// of From to use To instead.
213 void DAGTypeLegalizer::ReplaceValueWith(SDOperand From, SDOperand To) {
214   if (From == To) return;
215   
216   // If expansion produced new nodes, make sure they are properly marked.
217   if (To.Val->getNodeId() == NewNode)
218     MarkNewNodes(To.Val);
219   
220   // Anything that used the old node should now use the new one.  Note that this
221   // can potentially cause recursive merging.
222   DAG.ReplaceAllUsesOfValueWith(From, To);
223
224   // The old node may still be present in ExpandedNodes or PromotedNodes.
225   // Inform them about the replacement.
226   ReplacedNodes[From] = To;
227
228   // Since we just made an unstructured update to the DAG, which could wreak
229   // general havoc on anything that once used From and now uses To, walk all
230   // users of the result, updating their flags.
231   for (SDNode::use_iterator I = To.Val->use_begin(), E = To.Val->use_end();
232        I != E; ++I) {
233     SDNode *User = *I;
234     // If the node isn't already processed or in the worklist, mark it as new,
235     // then use MarkNewNodes to recompute its ID.
236     int NodeId = User->getNodeId();
237     if (NodeId != ReadyToProcess && NodeId != Processed) {
238       User->setNodeId(NewNode);
239       MarkNewNodes(User);
240     }
241   }
242 }
243
244 /// ReplaceNodeWith - Replace uses of the 'from' node's results with the 'to'
245 /// node's results.  The from and to node must define identical result types.
246 void DAGTypeLegalizer::ReplaceNodeWith(SDNode *From, SDNode *To) {
247   if (From == To) return;
248   assert(From->getNumValues() == To->getNumValues() &&
249          "Node results don't match");
250   
251   // If expansion produced new nodes, make sure they are properly marked.
252   if (To->getNodeId() == NewNode)
253     MarkNewNodes(To);
254   
255   // Anything that used the old node should now use the new one.  Note that this
256   // can potentially cause recursive merging.
257   DAG.ReplaceAllUsesWith(From, To);
258   
259   // The old node may still be present in ExpandedNodes or PromotedNodes.
260   // Inform them about the replacement.
261   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) {
262     assert(From->getValueType(i) == To->getValueType(i) &&
263            "Node results don't match");
264     ReplacedNodes[SDOperand(From, i)] = SDOperand(To, i);
265   }
266   
267   // Since we just made an unstructured update to the DAG, which could wreak
268   // general havoc on anything that once used From and now uses To, walk all
269   // users of the result, updating their flags.
270   for (SDNode::use_iterator I = To->use_begin(), E = To->use_end();I != E; ++I){
271     SDNode *User = *I;
272     // If the node isn't already processed or in the worklist, mark it as new,
273     // then use MarkNewNodes to recompute its ID.
274     int NodeId = User->getNodeId();
275     if (NodeId != ReadyToProcess && NodeId != Processed) {
276       User->setNodeId(NewNode);
277       MarkNewNodes(User);
278     }
279   }
280 }
281
282
283 /// RemapNode - If the specified value was already legalized to another value,
284 /// replace it by that value.
285 void DAGTypeLegalizer::RemapNode(SDOperand &N) {
286   DenseMap<SDOperand, SDOperand>::iterator I = ReplacedNodes.find(N);
287   if (I != ReplacedNodes.end()) {
288     // Use path compression to speed up future lookups if values get multiply
289     // replaced with other values.
290     RemapNode(I->second);
291     N = I->second;
292   }
293 }
294
295 void DAGTypeLegalizer::SetPromotedOp(SDOperand Op, SDOperand Result) {
296   if (Result.Val->getNodeId() == NewNode) 
297     MarkNewNodes(Result.Val);
298
299   SDOperand &OpEntry = PromotedNodes[Op];
300   assert(OpEntry.Val == 0 && "Node is already promoted!");
301   OpEntry = Result;
302 }
303
304 void DAGTypeLegalizer::SetScalarizedOp(SDOperand Op, SDOperand Result) {
305   if (Result.Val->getNodeId() == NewNode) 
306     MarkNewNodes(Result.Val);
307   
308   SDOperand &OpEntry = ScalarizedNodes[Op];
309   assert(OpEntry.Val == 0 && "Node is already scalarized!");
310   OpEntry = Result;
311 }
312
313
314 void DAGTypeLegalizer::GetExpandedOp(SDOperand Op, SDOperand &Lo, 
315                                      SDOperand &Hi) {
316   std::pair<SDOperand, SDOperand> &Entry = ExpandedNodes[Op];
317   RemapNode(Entry.first);
318   RemapNode(Entry.second);
319   assert(Entry.first.Val && "Operand isn't expanded");
320   Lo = Entry.first;
321   Hi = Entry.second;
322 }
323
324 void DAGTypeLegalizer::SetExpandedOp(SDOperand Op, SDOperand Lo, 
325                                      SDOperand Hi) {
326   // Remember that this is the result of the node.
327   std::pair<SDOperand, SDOperand> &Entry = ExpandedNodes[Op];
328   assert(Entry.first.Val == 0 && "Node already expanded");
329   Entry.first = Lo;
330   Entry.second = Hi;
331   
332   // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
333   if (Lo.Val->getNodeId() == NewNode) 
334     MarkNewNodes(Lo.Val);
335   if (Hi.Val->getNodeId() == NewNode) 
336     MarkNewNodes(Hi.Val);
337 }
338
339 SDOperand DAGTypeLegalizer::CreateStackStoreLoad(SDOperand Op, 
340                                                  MVT::ValueType DestVT) {
341   // Create the stack frame object.
342   SDOperand FIPtr = DAG.CreateStackTemporary(DestVT);
343   
344   // Emit a store to the stack slot.
345   SDOperand Store = DAG.getStore(DAG.getEntryNode(), Op, FIPtr, NULL, 0);
346   // Result is a load from the stack slot.
347   return DAG.getLoad(DestVT, Store, FIPtr, NULL, 0);
348 }
349
350 /// HandleMemIntrinsic - This handles memcpy/memset/memmove with invalid
351 /// operands.  This promotes or expands the operands as required.
352 SDOperand DAGTypeLegalizer::HandleMemIntrinsic(SDNode *N) {
353   // The chain and pointer [operands #0 and #1] are always valid types.
354   SDOperand Chain = N->getOperand(0);
355   SDOperand Ptr   = N->getOperand(1);
356   SDOperand Op2   = N->getOperand(2);
357   
358   // Op #2 is either a value (memset) or a pointer.  Promote it if required.
359   switch (getTypeAction(Op2.getValueType())) {
360   default: assert(0 && "Unknown action for pointer/value operand");
361   case Legal: break;
362   case Promote: Op2 = GetPromotedOp(Op2); break;
363   }
364   
365   // The length could have any action required.
366   SDOperand Length = N->getOperand(3);
367   switch (getTypeAction(Length.getValueType())) {
368   default: assert(0 && "Unknown action for memop operand");
369   case Legal: break;
370   case Promote: Length = GetPromotedZExtOp(Length); break;
371   case Expand:
372     SDOperand Dummy;  // discard the high part.
373     GetExpandedOp(Length, Length, Dummy);
374     break;
375   }
376   
377   SDOperand Align = N->getOperand(4);
378   switch (getTypeAction(Align.getValueType())) {
379   default: assert(0 && "Unknown action for memop operand");
380   case Legal: break;
381   case Promote: Align = GetPromotedZExtOp(Align); break;
382   }
383   
384   SDOperand AlwaysInline = N->getOperand(5);
385   switch (getTypeAction(AlwaysInline.getValueType())) {
386   default: assert(0 && "Unknown action for memop operand");
387   case Legal: break;
388   case Promote: AlwaysInline = GetPromotedZExtOp(AlwaysInline); break;
389   }
390   
391   SDOperand Ops[] = { Chain, Ptr, Op2, Length, Align, AlwaysInline };
392   return DAG.UpdateNodeOperands(SDOperand(N, 0), Ops, 6);
393 }
394
395 /// SplitOp - Return the lower and upper halves of Op's bits in a value type
396 /// half the size of Op's.
397 void DAGTypeLegalizer::SplitOp(SDOperand Op, SDOperand &Lo, SDOperand &Hi) {
398   unsigned NVTBits = MVT::getSizeInBits(Op.getValueType())/2;
399   assert(MVT::getSizeInBits(Op.getValueType()) == 2*NVTBits &&
400          "Cannot split odd sized integer type");
401   MVT::ValueType NVT = MVT::getIntegerType(NVTBits);
402   Lo = DAG.getNode(ISD::TRUNCATE, NVT, Op);
403   Hi = DAG.getNode(ISD::SRL, Op.getValueType(), Op,
404                    DAG.getConstant(NVTBits, TLI.getShiftAmountTy()));
405   Hi = DAG.getNode(ISD::TRUNCATE, NVT, Hi);
406 }
407
408
409 //===----------------------------------------------------------------------===//
410 //  Entry Point
411 //===----------------------------------------------------------------------===//
412
413 /// LegalizeTypes - This transforms the SelectionDAG into a SelectionDAG that
414 /// only uses types natively supported by the target.
415 ///
416 /// Note that this is an involved process that may invalidate pointers into
417 /// the graph.
418 void SelectionDAG::LegalizeTypes() {
419   DAGTypeLegalizer(*this).run();
420 }