1 //===-- LegalizeTypes.cpp - Common code for DAG type legalizer ------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
14 //===----------------------------------------------------------------------===//
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"
26 ViewLegalizeTypesDAGs("view-legalize-types-dags", cl::Hidden,
27 cl::desc("Pop up a window to show dags before legalize types"));
29 static const bool ViewLegalizeTypesDAGs = 0;
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());
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());
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
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);
55 I->setNodeId(NewNode);
59 // Now that we have a set of nodes to process, handle them all.
60 while (!Worklist.empty()) {
61 SDNode *N = Worklist.back();
63 assert(N->getNodeId() == ReadyToProcess &&
64 "Node should be ready if on worklist!");
66 // Scan the values produced by the node, checking to see if any result
69 unsigned NumResults = N->getNumValues();
71 MVT ResultVT = N->getValueType(i);
72 switch (getTypeAction(ResultVT)) {
74 assert(false && "Unknown action!");
84 FloatToIntResult(N, i);
87 ScalarizeResult(N, i);
93 } while (++i < NumResults);
95 // Scan the operand list for the node, handling any nodes with operands that
98 unsigned NumOperands = N->getNumOperands();
99 bool NeedsRevisit = false;
100 for (i = 0; i != NumOperands; ++i) {
101 MVT OpVT = N->getOperand(i).getValueType();
102 switch (getTypeAction(OpVT)) {
104 assert(false && "Unknown action!");
108 NeedsRevisit = PromoteOperand(N, i);
111 NeedsRevisit = ExpandOperand(N, i);
114 NeedsRevisit = FloatToIntOperand(N, i);
117 NeedsRevisit = ScalarizeOperand(N, i);
120 NeedsRevisit = SplitOperand(N, i);
126 // If the node needs revisiting, don't add all users to the worklist etc.
130 if (i == NumOperands)
131 DEBUG(cerr << "Legally typed node: "; N->dump(&DAG); cerr << "\n");
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);
139 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
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!");
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.
149 User->setNodeId(NodeID-1);
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);
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);
163 // If the node only has a single operand, it is now ready.
164 if (User->getNumOperands() == 1)
165 Worklist.push_back(User);
169 // If the root changed (e.g. it was a dead load, update the root).
170 DAG.setRoot(Dummy.getValue());
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();
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.
182 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
183 E = DAG.allnodes_end(); I != E; ++I) {
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";
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";
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";
211 I->dump(&DAG); cerr << "\n";
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)
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.
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.
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;
243 if (Op.Val->getNodeId() == Processed)
246 if (Op.Val->getNodeId() == NewNode)
247 AnalyzeNewNode(Op.Val);
248 else if (Op.Val->getNodeId() == Processed)
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);
262 // Some operands changed - update the node.
264 N = DAG.UpdateNodeOperands(SDOperand(N, 0), &NewOps[0], NewOps.size()).Val;
266 N->setNodeId(N->getNumOperands()-NumProcessed);
267 if (N->getNodeId() == ReadyToProcess)
268 Worklist.push_back(N);
271 void DAGTypeLegalizer::SanityCheck(SDNode *N) {
272 for (SmallVector<SDNode*, 128>::iterator I = Worklist.begin(),
273 E = Worklist.end(); I != E; ++I)
276 for (DenseMap<SDOperand, SDOperand>::iterator I = ReplacedNodes.begin(),
277 E = ReplacedNodes.end(); I != E; ++I) {
278 assert(I->first.Val != N);
279 assert(I->second.Val != N);
282 for (DenseMap<SDOperand, SDOperand>::iterator I = PromotedNodes.begin(),
283 E = PromotedNodes.end(); I != E; ++I) {
284 assert(I->first.Val != N);
285 assert(I->second.Val != N);
288 for (DenseMap<SDOperand, 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);
295 for (DenseMap<SDOperand, SDOperand>::iterator I = ScalarizedNodes.begin(),
296 E = ScalarizedNodes.end(); I != E; ++I) {
297 assert(I->first.Val != N);
298 assert(I->second.Val != N);
301 for (DenseMap<SDOperand, 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);
308 for (DenseMap<SDOperand, 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);
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;
323 NodeUpdateListener(DAGTypeLegalizer &dtl) : DTL(dtl) {}
325 virtual void NodeDeleted(SDNode *N) {
327 assert(N->getNodeId() != DAGTypeLegalizer::Processed &&
328 N->getNodeId() != DAGTypeLegalizer::ReadyToProcess &&
329 "RAUW deleted processed node!");
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);
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;
354 // If expansion produced new nodes, make sure they are properly marked.
355 AnalyzeNewNode(To.Val);
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);
362 // The old node may still be present in ExpandedNodes or PromotedNodes.
363 // Inform them about the replacement.
364 ReplacedNodes[From] = To;
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;
372 // If expansion produced new nodes, make sure they are properly marked.
375 assert(From->getNumValues() == To->getNumValues() &&
376 "Node results don't match");
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);
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);
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<SDOperand, 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);
405 void DAGTypeLegalizer::SetPromotedOp(SDOperand Op, SDOperand Result) {
406 AnalyzeNewNode(Result.Val);
408 SDOperand &OpEntry = PromotedNodes[Op];
409 assert(OpEntry.Val == 0 && "Node is already promoted!");
413 void DAGTypeLegalizer::SetIntegerOp(SDOperand Op, SDOperand Result) {
414 AnalyzeNewNode(Result.Val);
416 SDOperand &OpEntry = FloatToIntedNodes[Op];
417 assert(OpEntry.Val == 0 && "Node is already converted to integer!");
421 void DAGTypeLegalizer::SetScalarizedOp(SDOperand Op, SDOperand Result) {
422 AnalyzeNewNode(Result.Val);
424 SDOperand &OpEntry = ScalarizedNodes[Op];
425 assert(OpEntry.Val == 0 && "Node is already scalarized!");
429 void DAGTypeLegalizer::GetExpandedOp(SDOperand Op, SDOperand &Lo,
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");
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);
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");
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");
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);
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");
473 /// BitConvertToInteger - Convert to an integer of the same size.
474 SDOperand DAGTypeLegalizer::BitConvertToInteger(SDOperand Op) {
475 unsigned BitWidth = Op.getValueType().getSizeInBits();
476 return DAG.getNode(ISD::BIT_CONVERT, MVT::getIntegerVT(BitWidth), Op);
479 SDOperand DAGTypeLegalizer::CreateStackStoreLoad(SDOperand Op,
481 // Create the stack frame object.
482 SDOperand FIPtr = DAG.CreateStackTemporary(DestVT);
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);
490 /// JoinIntegers - Build an integer with low bits Lo and high bits Hi.
491 SDOperand DAGTypeLegalizer::JoinIntegers(SDOperand Lo, SDOperand Hi) {
492 MVT LVT = Lo.getValueType();
493 MVT HVT = Hi.getValueType();
494 MVT NVT = MVT::getIntegerVT(LVT.getSizeInBits() + HVT.getSizeInBits());
496 Lo = DAG.getNode(ISD::ZERO_EXTEND, NVT, Lo);
497 Hi = DAG.getNode(ISD::ANY_EXTEND, NVT, Hi);
498 Hi = DAG.getNode(ISD::SHL, NVT, Hi, DAG.getConstant(LVT.getSizeInBits(),
499 TLI.getShiftAmountTy()));
500 return DAG.getNode(ISD::OR, NVT, Lo, Hi);
503 /// SplitInteger - Return the lower LoVT bits of Op in Lo and the upper HiVT
505 void DAGTypeLegalizer::SplitInteger(SDOperand Op,
507 SDOperand &Lo, SDOperand &Hi) {
508 assert(LoVT.getSizeInBits() + HiVT.getSizeInBits() ==
509 Op.getValueType().getSizeInBits() && "Invalid integer splitting!");
510 Lo = DAG.getNode(ISD::TRUNCATE, LoVT, Op);
511 Hi = DAG.getNode(ISD::SRL, Op.getValueType(), Op,
512 DAG.getConstant(LoVT.getSizeInBits(),
513 TLI.getShiftAmountTy()));
514 Hi = DAG.getNode(ISD::TRUNCATE, HiVT, Hi);
517 /// SplitInteger - Return the lower and upper halves of Op's bits in a value type
518 /// half the size of Op's.
519 void DAGTypeLegalizer::SplitInteger(SDOperand Op,
520 SDOperand &Lo, SDOperand &Hi) {
521 MVT HalfVT = MVT::getIntegerVT(Op.getValueType().getSizeInBits()/2);
522 SplitInteger(Op, HalfVT, HalfVT, Lo, Hi);
525 /// MakeLibCall - Generate a libcall taking the given operands as arguments and
526 /// returning a result of type RetVT.
527 SDOperand DAGTypeLegalizer::MakeLibCall(RTLIB::Libcall LC, MVT RetVT,
528 const SDOperand *Ops, unsigned NumOps,
530 TargetLowering::ArgListTy Args;
531 Args.reserve(NumOps);
533 TargetLowering::ArgListEntry Entry;
534 for (unsigned i = 0; i != NumOps; ++i) {
536 Entry.Ty = Entry.Node.getValueType().getTypeForMVT();
537 Entry.isSExt = isSigned;
538 Entry.isZExt = !isSigned;
539 Args.push_back(Entry);
541 SDOperand Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
544 const Type *RetTy = RetVT.getTypeForMVT();
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;
551 //===----------------------------------------------------------------------===//
553 //===----------------------------------------------------------------------===//
555 /// LegalizeTypes - This transforms the SelectionDAG into a SelectionDAG that
556 /// only uses types natively supported by the target.
558 /// Note that this is an involved process that may invalidate pointers into
560 void SelectionDAG::LegalizeTypes() {
561 if (ViewLegalizeTypesDAGs) viewGraph();
563 DAGTypeLegalizer(*this).run();