Initial libcall support for LegalizeTypes. This is
[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/CallingConv.h"
18 #include "llvm/Constants.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Support/CommandLine.h"
21 #include "llvm/Support/MathExtras.h"
22 using namespace llvm;
23
24 #ifndef NDEBUG
25 static cl::opt<bool>
26 ViewLegalizeTypesDAGs("view-legalize-types-dags", cl::Hidden,
27                 cl::desc("Pop up a window to show dags before legalize types"));
28 #else
29 static const bool ViewLegalizeTypesDAGs = 0;
30 #endif
31
32
33
34 /// run - This is the main entry point for the type legalizer.  This does a
35 /// top-down traversal of the dag, legalizing types as it goes.
36 void DAGTypeLegalizer::run() {
37   // Create a dummy node (which is not added to allnodes), that adds a reference
38   // to the root node, preventing it from being deleted, and tracking any
39   // changes of the root.
40   HandleSDNode Dummy(DAG.getRoot());
41
42   // The root of the dag may dangle to deleted nodes until the type legalizer is
43   // done.  Set it to null to avoid confusion.
44   DAG.setRoot(SDOperand());
45   
46   // Walk all nodes in the graph, assigning them a NodeID of 'ReadyToProcess'
47   // (and remembering them) if they are leaves and assigning 'NewNode' if
48   // non-leaves.
49   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
50        E = DAG.allnodes_end(); I != E; ++I) {
51     if (I->getNumOperands() == 0) {
52       I->setNodeId(ReadyToProcess);
53       Worklist.push_back(I);
54     } else {
55       I->setNodeId(NewNode);
56     }
57   }
58   
59   // Now that we have a set of nodes to process, handle them all.
60   while (!Worklist.empty()) {
61     SDNode *N = Worklist.back();
62     Worklist.pop_back();
63     assert(N->getNodeId() == ReadyToProcess &&
64            "Node should be ready if on worklist!");
65     
66     // Scan the values produced by the node, checking to see if any result
67     // types are illegal.
68     unsigned i = 0;
69     unsigned NumResults = N->getNumValues();
70     do {
71       MVT::ValueType ResultVT = N->getValueType(i);
72       switch (getTypeAction(ResultVT)) {
73       default:
74         assert(false && "Unknown action!");
75       case Legal:
76         break;
77       case Promote:
78         PromoteResult(N, i);
79         goto NodeDone;
80       case Expand:
81         ExpandResult(N, i);
82         goto NodeDone;
83       case FloatToInt:
84         FloatToIntResult(N, i);
85         goto NodeDone;
86       case Scalarize:
87         ScalarizeResult(N, i);
88         goto NodeDone;
89       case Split:
90         SplitResult(N, i);
91         goto NodeDone;
92       }
93     } while (++i < NumResults);
94
95     // Scan the operand list for the node, handling any nodes with operands that
96     // are illegal.
97     {
98     unsigned NumOperands = N->getNumOperands();
99     bool NeedsRevisit = false;
100     for (i = 0; i != NumOperands; ++i) {
101       MVT::ValueType OpVT = N->getOperand(i).getValueType();
102       switch (getTypeAction(OpVT)) {
103       default:
104         assert(false && "Unknown action!");
105       case Legal:
106         continue;
107       case Promote:
108         NeedsRevisit = PromoteOperand(N, i);
109         break;
110       case Expand:
111         NeedsRevisit = ExpandOperand(N, i);
112         break;
113       case FloatToInt:
114         NeedsRevisit = FloatToIntOperand(N, i);
115         break;
116       case Scalarize:
117         NeedsRevisit = ScalarizeOperand(N, i);
118         break;
119       case Split:
120         NeedsRevisit = SplitOperand(N, i);
121         break;
122       }
123       break;
124     }
125
126     // If the node needs revisiting, don't add all users to the worklist etc.
127     if (NeedsRevisit)
128       continue;
129     
130     if (i == NumOperands)
131       DEBUG(cerr << "Legally typed node: "; N->dump(&DAG); cerr << "\n");
132     }
133 NodeDone:
134
135     // If we reach here, the node was processed, potentially creating new nodes.
136     // Mark it as processed and add its users to the worklist as appropriate.
137     N->setNodeId(Processed);
138     
139     for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
140          UI != E; ++UI) {
141       SDNode *User = UI->getUser();
142       int NodeID = User->getNodeId();
143       assert(NodeID != ReadyToProcess && NodeID != Processed &&
144              "Invalid node id for user of unprocessed node!");
145       
146       // This node has two options: it can either be a new node or its Node ID
147       // may be a count of the number of operands it has that are not ready.
148       if (NodeID > 0) {
149         User->setNodeId(NodeID-1);
150         
151         // If this was the last use it was waiting on, add it to the ready list.
152         if (NodeID-1 == ReadyToProcess)
153           Worklist.push_back(User);
154         continue;
155       }
156       
157       // Otherwise, this node is new: this is the first operand of it that
158       // became ready.  Its new NodeID is the number of operands it has minus 1
159       // (as this node is now processed).
160       assert(NodeID == NewNode && "Unknown node ID!");
161       User->setNodeId(User->getNumOperands()-1);
162       
163       // If the node only has a single operand, it is now ready.
164       if (User->getNumOperands() == 1)
165         Worklist.push_back(User);
166     }
167   }
168   
169   // If the root changed (e.g. it was a dead load, update the root).
170   DAG.setRoot(Dummy.getValue());
171
172   //DAG.viewGraph();
173
174   // Remove dead nodes.  This is important to do for cleanliness but also before
175   // the checking loop below.  Implicit folding by the DAG.getNode operators can
176   // cause unreachable nodes to be around with their flags set to new.
177   DAG.RemoveDeadNodes();
178
179   // In a debug build, scan all the nodes to make sure we found them all.  This
180   // ensures that there are no cycles and that everything got processed.
181 #ifndef NDEBUG
182   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
183        E = DAG.allnodes_end(); I != E; ++I) {
184     bool Failed = false;
185
186     // Check that all result types are legal.
187     for (unsigned i = 0, NumVals = I->getNumValues(); i < NumVals; ++i)
188       if (!isTypeLegal(I->getValueType(i))) {
189         cerr << "Result type " << i << " illegal!\n";
190         Failed = true;
191       }
192
193     // Check that all operand types are legal.
194     for (unsigned i = 0, NumOps = I->getNumOperands(); i < NumOps; ++i)
195       if (!isTypeLegal(I->getOperand(i).getValueType())) {
196         cerr << "Operand type " << i << " illegal!\n";
197         Failed = true;
198       }
199
200     if (I->getNodeId() != Processed) {
201        if (I->getNodeId() == NewNode)
202          cerr << "New node not 'noticed'?\n";
203        else if (I->getNodeId() > 0)
204          cerr << "Operand not processed?\n";
205        else if (I->getNodeId() == ReadyToProcess)
206          cerr << "Not added to worklist?\n";
207        Failed = true;
208     }
209
210     if (Failed) {
211       I->dump(&DAG); cerr << "\n";
212       abort();
213     }
214   }
215 #endif
216 }
217
218 /// AnalyzeNewNode - The specified node is the root of a subtree of potentially
219 /// new nodes.  Correct any processed operands (this may change the node) and
220 /// calculate the NodeId.
221 void DAGTypeLegalizer::AnalyzeNewNode(SDNode *&N) {
222   // If this was an existing node that is already done, we're done.
223   if (N->getNodeId() != NewNode)
224     return;
225
226   // Okay, we know that this node is new.  Recursively walk all of its operands
227   // to see if they are new also.  The depth of this walk is bounded by the size
228   // of the new tree that was constructed (usually 2-3 nodes), so we don't worry
229   // about revisiting of nodes.
230   //
231   // As we walk the operands, keep track of the number of nodes that are
232   // processed.  If non-zero, this will become the new nodeid of this node.
233   // Already processed operands may need to be remapped to the node that
234   // replaced them, which can result in our node changing.  Since remapping
235   // is rare, the code tries to minimize overhead in the non-remapping case.
236
237   SmallVector<SDOperand, 8> NewOps;
238   unsigned NumProcessed = 0;
239   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
240     SDOperand OrigOp = N->getOperand(i);
241     SDOperand Op = OrigOp;
242
243     if (Op.Val->getNodeId() == Processed)
244       RemapNode(Op);
245
246     if (Op.Val->getNodeId() == NewNode)
247       AnalyzeNewNode(Op.Val);
248     else if (Op.Val->getNodeId() == Processed)
249       ++NumProcessed;
250
251     if (!NewOps.empty()) {
252       // Some previous operand changed.  Add this one to the list.
253       NewOps.push_back(Op);
254     } else if (Op != OrigOp) {
255       // This is the first operand to change - add all operands so far.
256       for (unsigned j = 0; j < i; ++j)
257         NewOps.push_back(N->getOperand(j));
258       NewOps.push_back(Op);
259     }
260   }
261
262   // Some operands changed - update the node.
263   if (!NewOps.empty())
264     N = DAG.UpdateNodeOperands(SDOperand(N, 0), &NewOps[0], NewOps.size()).Val;
265
266   N->setNodeId(N->getNumOperands()-NumProcessed);
267   if (N->getNodeId() == ReadyToProcess)
268     Worklist.push_back(N);
269 }
270
271 void DAGTypeLegalizer::SanityCheck(SDNode *N) {
272   for (SmallVector<SDNode*, 128>::iterator I = Worklist.begin(),
273        E = Worklist.end(); I != E; ++I)
274     assert(*I != N);
275
276   for (DenseMap<SDOperandImpl, SDOperand>::iterator I = ReplacedNodes.begin(),
277        E = ReplacedNodes.end(); I != E; ++I) {
278     assert(I->first.Val != N);
279     assert(I->second.Val != N);
280   }
281
282   for (DenseMap<SDOperandImpl, SDOperand>::iterator I = PromotedNodes.begin(),
283        E = PromotedNodes.end(); I != E; ++I) {
284     assert(I->first.Val != N);
285     assert(I->second.Val != N);
286   }
287
288   for (DenseMap<SDOperandImpl, SDOperand>::iterator
289        I = FloatToIntedNodes.begin(),
290        E = FloatToIntedNodes.end(); I != E; ++I) {
291     assert(I->first.Val != N);
292     assert(I->second.Val != N);
293   }
294
295   for (DenseMap<SDOperandImpl, SDOperand>::iterator I = ScalarizedNodes.begin(),
296        E = ScalarizedNodes.end(); I != E; ++I) {
297     assert(I->first.Val != N);
298     assert(I->second.Val != N);
299   }
300
301   for (DenseMap<SDOperandImpl, std::pair<SDOperand, SDOperand> >::iterator
302        I = ExpandedNodes.begin(), E = ExpandedNodes.end(); I != E; ++I) {
303     assert(I->first.Val != N);
304     assert(I->second.first.Val != N);
305     assert(I->second.second.Val != N);
306   }
307
308   for (DenseMap<SDOperandImpl, std::pair<SDOperand, SDOperand> >::iterator
309        I = SplitNodes.begin(), E = SplitNodes.end(); I != E; ++I) {
310     assert(I->first.Val != N);
311     assert(I->second.first.Val != N);
312     assert(I->second.second.Val != N);
313   }
314 }
315
316 namespace {
317   /// NodeUpdateListener - This class is a DAGUpdateListener that listens for
318   /// updates to nodes and recomputes their ready state.
319   class VISIBILITY_HIDDEN NodeUpdateListener :
320     public SelectionDAG::DAGUpdateListener {
321     DAGTypeLegalizer &DTL;
322   public:
323     NodeUpdateListener(DAGTypeLegalizer &dtl) : DTL(dtl) {}
324
325     virtual void NodeDeleted(SDNode *N) {
326       // Ignore deletes.
327       assert(N->getNodeId() != DAGTypeLegalizer::Processed &&
328              N->getNodeId() != DAGTypeLegalizer::ReadyToProcess &&
329              "RAUW deleted processed node!");
330 #ifndef NDEBUG
331       DTL.SanityCheck(N);
332 #endif
333     }
334
335     virtual void NodeUpdated(SDNode *N) {
336       // Node updates can mean pretty much anything.  It is possible that an
337       // operand was set to something already processed (f.e.) in which case
338       // this node could become ready.  Recompute its flags.
339       assert(N->getNodeId() != DAGTypeLegalizer::Processed &&
340              N->getNodeId() != DAGTypeLegalizer::ReadyToProcess &&
341              "RAUW updated processed node!");
342       DTL.ReanalyzeNode(N);
343     }
344   };
345 }
346
347
348 /// ReplaceValueWith - The specified value was legalized to the specified other
349 /// value.  If they are different, update the DAG and NodeIDs replacing any uses
350 /// of From to use To instead.
351 void DAGTypeLegalizer::ReplaceValueWith(SDOperand From, SDOperand To) {
352   if (From == To) return;
353
354   // If expansion produced new nodes, make sure they are properly marked.
355   AnalyzeNewNode(To.Val);
356
357   // Anything that used the old node should now use the new one.  Note that this
358   // can potentially cause recursive merging.
359   NodeUpdateListener NUL(*this);
360   DAG.ReplaceAllUsesOfValueWith(From, To, &NUL);
361
362   // The old node may still be present in ExpandedNodes or PromotedNodes.
363   // Inform them about the replacement.
364   ReplacedNodes[From] = To;
365 }
366
367 /// ReplaceNodeWith - Replace uses of the 'from' node's results with the 'to'
368 /// node's results.  The from and to node must define identical result types.
369 void DAGTypeLegalizer::ReplaceNodeWith(SDNode *From, SDNode *To) {
370   if (From == To) return;
371
372   // If expansion produced new nodes, make sure they are properly marked.
373   AnalyzeNewNode(To);
374
375   assert(From->getNumValues() == To->getNumValues() &&
376          "Node results don't match");
377
378   // Anything that used the old node should now use the new one.  Note that this
379   // can potentially cause recursive merging.
380   NodeUpdateListener NUL(*this);
381   DAG.ReplaceAllUsesWith(From, To, &NUL);
382   
383   // The old node may still be present in ExpandedNodes or PromotedNodes.
384   // Inform them about the replacement.
385   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) {
386     assert(From->getValueType(i) == To->getValueType(i) &&
387            "Node results don't match");
388     ReplacedNodes[SDOperand(From, i)] = SDOperand(To, i);
389   }
390 }
391
392
393 /// RemapNode - If the specified value was already legalized to another value,
394 /// replace it by that value.
395 void DAGTypeLegalizer::RemapNode(SDOperand &N) {
396   DenseMap<SDOperandImpl, SDOperand>::iterator I = ReplacedNodes.find(N);
397   if (I != ReplacedNodes.end()) {
398     // Use path compression to speed up future lookups if values get multiply
399     // replaced with other values.
400     RemapNode(I->second);
401     N = I->second;
402   }
403 }
404
405 void DAGTypeLegalizer::SetPromotedOp(SDOperand Op, SDOperand Result) {
406   AnalyzeNewNode(Result.Val);
407
408   SDOperand &OpEntry = PromotedNodes[Op];
409   assert(OpEntry.Val == 0 && "Node is already promoted!");
410   OpEntry = Result;
411 }
412
413 void DAGTypeLegalizer::SetIntegerOp(SDOperand Op, SDOperand Result) {
414   AnalyzeNewNode(Result.Val);
415
416   SDOperand &OpEntry = FloatToIntedNodes[Op];
417   assert(OpEntry.Val == 0 && "Node is already converted to integer!");
418   OpEntry = Result;
419 }
420
421 void DAGTypeLegalizer::SetScalarizedOp(SDOperand Op, SDOperand Result) {
422   AnalyzeNewNode(Result.Val);
423
424   SDOperand &OpEntry = ScalarizedNodes[Op];
425   assert(OpEntry.Val == 0 && "Node is already scalarized!");
426   OpEntry = Result;
427 }
428
429 void DAGTypeLegalizer::GetExpandedOp(SDOperand Op, SDOperand &Lo, 
430                                      SDOperand &Hi) {
431   std::pair<SDOperand, SDOperand> &Entry = ExpandedNodes[Op];
432   RemapNode(Entry.first);
433   RemapNode(Entry.second);
434   assert(Entry.first.Val && "Operand isn't expanded");
435   Lo = Entry.first;
436   Hi = Entry.second;
437 }
438
439 void DAGTypeLegalizer::SetExpandedOp(SDOperand Op, SDOperand Lo, SDOperand Hi) {
440   // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
441   AnalyzeNewNode(Lo.Val);
442   AnalyzeNewNode(Hi.Val);
443
444   // Remember that this is the result of the node.
445   std::pair<SDOperand, SDOperand> &Entry = ExpandedNodes[Op];
446   assert(Entry.first.Val == 0 && "Node already expanded");
447   Entry.first = Lo;
448   Entry.second = Hi;
449 }
450
451 void DAGTypeLegalizer::GetSplitOp(SDOperand Op, SDOperand &Lo, SDOperand &Hi) {
452   std::pair<SDOperand, SDOperand> &Entry = SplitNodes[Op];
453   RemapNode(Entry.first);
454   RemapNode(Entry.second);
455   assert(Entry.first.Val && "Operand isn't split");
456   Lo = Entry.first;
457   Hi = Entry.second;
458 }
459
460 void DAGTypeLegalizer::SetSplitOp(SDOperand Op, SDOperand Lo, SDOperand Hi) {
461   // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
462   AnalyzeNewNode(Lo.Val);
463   AnalyzeNewNode(Hi.Val);
464
465   // Remember that this is the result of the node.
466   std::pair<SDOperand, SDOperand> &Entry = SplitNodes[Op];
467   assert(Entry.first.Val == 0 && "Node already split");
468   Entry.first = Lo;
469   Entry.second = Hi;
470 }
471
472
473 /// BitConvertToInteger - Convert to an integer of the same size.
474 SDOperand DAGTypeLegalizer::BitConvertToInteger(SDOperand Op) {
475   return DAG.getNode(ISD::BIT_CONVERT,
476                      MVT::getIntegerType(MVT::getSizeInBits(Op.getValueType())),
477                      Op);
478 }
479
480 SDOperand DAGTypeLegalizer::CreateStackStoreLoad(SDOperand Op, 
481                                                  MVT::ValueType DestVT) {
482   // Create the stack frame object.
483   SDOperand FIPtr = DAG.CreateStackTemporary(DestVT);
484   
485   // Emit a store to the stack slot.
486   SDOperand Store = DAG.getStore(DAG.getEntryNode(), Op, FIPtr, NULL, 0);
487   // Result is a load from the stack slot.
488   return DAG.getLoad(DestVT, Store, FIPtr, NULL, 0);
489 }
490
491 /// JoinIntegers - Build an integer with low bits Lo and high bits Hi.
492 SDOperand DAGTypeLegalizer::JoinIntegers(SDOperand Lo, SDOperand Hi) {
493   MVT::ValueType LVT = Lo.getValueType();
494   MVT::ValueType HVT = Hi.getValueType();
495   MVT::ValueType NVT = MVT::getIntegerType(MVT::getSizeInBits(LVT) +
496                                            MVT::getSizeInBits(HVT));
497
498   Lo = DAG.getNode(ISD::ZERO_EXTEND, NVT, Lo);
499   Hi = DAG.getNode(ISD::ANY_EXTEND, NVT, Hi);
500   Hi = DAG.getNode(ISD::SHL, NVT, Hi, DAG.getConstant(MVT::getSizeInBits(LVT),
501                                                       TLI.getShiftAmountTy()));
502   return DAG.getNode(ISD::OR, NVT, Lo, Hi);
503 }
504
505 /// SplitInteger - Return the lower LoVT bits of Op in Lo and the upper HiVT
506 /// bits in Hi.
507 void DAGTypeLegalizer::SplitInteger(SDOperand Op,
508                                     MVT::ValueType LoVT, MVT::ValueType HiVT,
509                                     SDOperand &Lo, SDOperand &Hi) {
510   assert(MVT::getSizeInBits(LoVT) + MVT::getSizeInBits(HiVT) ==
511          MVT::getSizeInBits(Op.getValueType()) && "Invalid integer splitting!");
512   Lo = DAG.getNode(ISD::TRUNCATE, LoVT, Op);
513   Hi = DAG.getNode(ISD::SRL, Op.getValueType(), Op,
514                    DAG.getConstant(MVT::getSizeInBits(LoVT),
515                                    TLI.getShiftAmountTy()));
516   Hi = DAG.getNode(ISD::TRUNCATE, HiVT, Hi);
517 }
518
519 /// SplitInteger - Return the lower and upper halves of Op's bits in a value type
520 /// half the size of Op's.
521 void DAGTypeLegalizer::SplitInteger(SDOperand Op,
522                                     SDOperand &Lo, SDOperand &Hi) {
523   MVT::ValueType HalfVT =
524     MVT::getIntegerType(MVT::getSizeInBits(Op.getValueType())/2);
525   SplitInteger(Op, HalfVT, HalfVT, Lo, Hi);
526 }
527
528 /// MakeLibCall - Expand a node into a libcall and return the result.
529 SDOperand DAGTypeLegalizer::MakeLibCall(RTLIB::Libcall LC, SDNode *N,
530                                         bool isSigned) {
531   TargetLowering::ArgListTy Args;
532   TargetLowering::ArgListEntry Entry;
533   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
534     MVT::ValueType ArgVT = N->getOperand(i).getValueType();
535     Entry.Node = N->getOperand(i);
536     Entry.Ty = MVT::getTypeForValueType(ArgVT);
537     Entry.isSExt = isSigned;
538     Entry.isZExt = !isSigned;
539     Args.push_back(Entry);
540   }
541   SDOperand Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
542                                            TLI.getPointerTy());
543
544   const Type *RetTy = MVT::getTypeForValueType(N->getValueType(0));
545   std::pair<SDOperand,SDOperand> CallInfo =
546     TLI.LowerCallTo(DAG.getEntryNode(), RetTy, isSigned, !isSigned, false,
547                     CallingConv::C, false, Callee, Args, DAG);
548   return CallInfo.first;
549 }
550
551 //===----------------------------------------------------------------------===//
552 //  Entry Point
553 //===----------------------------------------------------------------------===//
554
555 /// LegalizeTypes - This transforms the SelectionDAG into a SelectionDAG that
556 /// only uses types natively supported by the target.
557 ///
558 /// Note that this is an involved process that may invalidate pointers into
559 /// the graph.
560 void SelectionDAG::LegalizeTypes() {
561   if (ViewLegalizeTypesDAGs) viewGraph();
562   
563   DAGTypeLegalizer(*this).run();
564 }