1 //===-- LegalizeTypes.cpp - Common code for DAG type legalizer ------------===//
3 // The LLVM Compiler Infrastructure
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.
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/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Support/MathExtras.h"
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());
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());
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
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);
43 I->setNodeId(NewNode);
47 // Now that we have a set of nodes to process, handle them all.
48 while (!Worklist.empty()) {
49 SDNode *N = Worklist.back();
51 assert(N->getNodeId() == ReadyToProcess &&
52 "Node should be ready if on worklist!");
54 // Scan the values produced by the node, checking to see if any result
57 unsigned NumResults = N->getNumValues();
59 MVT::ValueType ResultVT = N->getValueType(i);
60 LegalizeAction Action = getTypeAction(ResultVT);
61 if (Action == Promote) {
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))
69 else if (MVT::getVectorNumElements(ResultVT) == 1)
70 ScalarizeResult(N, i); // Scalarize the single-element vector.
72 SplitResult(N, i); // Split the vector in half.
75 assert(Action == Legal && "Unknown action!");
77 } while (++i < NumResults);
79 // Scan the operand list for the node, handling any nodes with operands that
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);
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);
99 NeedsRevisit = SplitOperand(N, i); // Split the vector in half.
103 assert(Action == Legal && "Unknown action!");
107 // If the node needs revisiting, don't add all users to the worklist etc.
111 if (i == NumOperands)
112 DEBUG(cerr << "Legally typed node: "; N->dump(&DAG); cerr << "\n");
116 // If we reach here, the node was processed, potentially creating new nodes.
117 // Mark it as processed and add its users to the worklist as appropriate.
118 N->setNodeId(Processed);
120 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
123 int NodeID = User->getNodeId();
124 assert(NodeID != ReadyToProcess && NodeID != Processed &&
125 "Invalid node id for user of unprocessed node!");
127 // This node has two options: it can either be a new node or its Node ID
128 // may be a count of the number of operands it has that are not ready.
130 User->setNodeId(NodeID-1);
132 // If this was the last use it was waiting on, add it to the ready list.
133 if (NodeID-1 == ReadyToProcess)
134 Worklist.push_back(User);
138 // Otherwise, this node is new: this is the first operand of it that
139 // became ready. Its new NodeID is the number of operands it has minus 1
140 // (as this node is now processed).
141 assert(NodeID == NewNode && "Unknown node ID!");
142 User->setNodeId(User->getNumOperands()-1);
144 // If the node only has a single operand, it is now ready.
145 if (User->getNumOperands() == 1)
146 Worklist.push_back(User);
150 // If the root changed (e.g. it was a dead load, update the root).
151 DAG.setRoot(Dummy.getValue());
155 // Remove dead nodes. This is important to do for cleanliness but also before
156 // the checking loop below. Implicit folding by the DAG.getNode operators can
157 // cause unreachable nodes to be around with their flags set to new.
158 DAG.RemoveDeadNodes();
160 // In a debug build, scan all the nodes to make sure we found them all. This
161 // ensures that there are no cycles and that everything got processed.
163 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
164 E = DAG.allnodes_end(); I != E; ++I) {
165 if (I->getNodeId() == Processed)
167 cerr << "Unprocessed node: ";
168 I->dump(&DAG); cerr << "\n";
170 if (I->getNodeId() == NewNode)
171 cerr << "New node not 'noticed'?\n";
172 else if (I->getNodeId() > 0)
173 cerr << "Operand not processed?\n";
174 else if (I->getNodeId() == ReadyToProcess)
175 cerr << "Not added to worklist?\n";
181 /// MarkNewNodes - The specified node is the root of a subtree of potentially
182 /// new nodes. Add the correct NodeId to mark it.
183 void DAGTypeLegalizer::MarkNewNodes(SDNode *N) {
184 // If this was an existing node that is already done, we're done.
185 if (N->getNodeId() != NewNode)
188 // Okay, we know that this node is new. Recursively walk all of its operands
189 // to see if they are new also. The depth of this walk is bounded by the size
190 // of the new tree that was constructed (usually 2-3 nodes), so we don't worry
191 // about revisiting of nodes.
193 // As we walk the operands, keep track of the number of nodes that are
194 // processed. If non-zero, this will become the new nodeid of this node.
195 unsigned NumProcessed = 0;
196 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
197 int OpId = N->getOperand(i).Val->getNodeId();
199 MarkNewNodes(N->getOperand(i).Val);
200 else if (OpId == Processed)
204 N->setNodeId(N->getNumOperands()-NumProcessed);
205 if (N->getNodeId() == ReadyToProcess)
206 Worklist.push_back(N);
209 /// ReplaceValueWith - The specified value was legalized to the specified other
210 /// value. If they are different, update the DAG and NodeIDs replacing any uses
211 /// of From to use To instead.
212 void DAGTypeLegalizer::ReplaceValueWith(SDOperand From, SDOperand To) {
213 if (From == To) return;
215 // If expansion produced new nodes, make sure they are properly marked.
216 if (To.Val->getNodeId() == NewNode)
217 MarkNewNodes(To.Val);
219 // Anything that used the old node should now use the new one. Note that this
220 // can potentially cause recursive merging.
221 DAG.ReplaceAllUsesOfValueWith(From, To);
223 // The old node may still be present in ExpandedNodes or PromotedNodes.
224 // Inform them about the replacement.
225 ReplacedNodes[From] = To;
227 // Since we just made an unstructured update to the DAG, which could wreak
228 // general havoc on anything that once used From and now uses To, walk all
229 // users of the result, updating their flags.
230 for (SDNode::use_iterator I = To.Val->use_begin(), E = To.Val->use_end();
233 // If the node isn't already processed or in the worklist, mark it as new,
234 // then use MarkNewNodes to recompute its ID.
235 int NodeId = User->getNodeId();
236 if (NodeId != ReadyToProcess && NodeId != Processed) {
237 User->setNodeId(NewNode);
243 /// ReplaceNodeWith - Replace uses of the 'from' node's results with the 'to'
244 /// node's results. The from and to node must define identical result types.
245 void DAGTypeLegalizer::ReplaceNodeWith(SDNode *From, SDNode *To) {
246 if (From == To) return;
247 assert(From->getNumValues() == To->getNumValues() &&
248 "Node results don't match");
250 // If expansion produced new nodes, make sure they are properly marked.
251 if (To->getNodeId() == NewNode)
254 // Anything that used the old node should now use the new one. Note that this
255 // can potentially cause recursive merging.
256 DAG.ReplaceAllUsesWith(From, To);
258 // The old node may still be present in ExpandedNodes or PromotedNodes.
259 // Inform them about the replacement.
260 for (unsigned i = 0, e = From->getNumValues(); i != e; ++i) {
261 assert(From->getValueType(i) == To->getValueType(i) &&
262 "Node results don't match");
263 ReplacedNodes[SDOperand(From, i)] = SDOperand(To, i);
266 // Since we just made an unstructured update to the DAG, which could wreak
267 // general havoc on anything that once used From and now uses To, walk all
268 // users of the result, updating their flags.
269 for (SDNode::use_iterator I = To->use_begin(), E = To->use_end();I != E; ++I){
271 // If the node isn't already processed or in the worklist, mark it as new,
272 // then use MarkNewNodes to recompute its ID.
273 int NodeId = User->getNodeId();
274 if (NodeId != ReadyToProcess && NodeId != Processed) {
275 User->setNodeId(NewNode);
282 /// RemapNode - If the specified value was already legalized to another value,
283 /// replace it by that value.
284 void DAGTypeLegalizer::RemapNode(SDOperand &N) {
285 DenseMap<SDOperand, SDOperand>::iterator I = ReplacedNodes.find(N);
286 if (I != ReplacedNodes.end()) {
287 // Use path compression to speed up future lookups if values get multiply
288 // replaced with other values.
289 RemapNode(I->second);
294 void DAGTypeLegalizer::SetPromotedOp(SDOperand Op, SDOperand Result) {
295 if (Result.Val->getNodeId() == NewNode)
296 MarkNewNodes(Result.Val);
298 SDOperand &OpEntry = PromotedNodes[Op];
299 assert(OpEntry.Val == 0 && "Node is already promoted!");
303 void DAGTypeLegalizer::SetScalarizedOp(SDOperand Op, SDOperand Result) {
304 if (Result.Val->getNodeId() == NewNode)
305 MarkNewNodes(Result.Val);
307 SDOperand &OpEntry = ScalarizedNodes[Op];
308 assert(OpEntry.Val == 0 && "Node is already scalarized!");
313 void DAGTypeLegalizer::GetExpandedOp(SDOperand Op, SDOperand &Lo,
315 std::pair<SDOperand, SDOperand> &Entry = ExpandedNodes[Op];
316 RemapNode(Entry.first);
317 RemapNode(Entry.second);
318 assert(Entry.first.Val && "Operand isn't expanded");
323 void DAGTypeLegalizer::SetExpandedOp(SDOperand Op, SDOperand Lo,
325 // Remember that this is the result of the node.
326 std::pair<SDOperand, SDOperand> &Entry = ExpandedNodes[Op];
327 assert(Entry.first.Val == 0 && "Node already expanded");
331 // Lo/Hi may have been newly allocated, if so, add nodeid's as relevant.
332 if (Lo.Val->getNodeId() == NewNode)
333 MarkNewNodes(Lo.Val);
334 if (Hi.Val->getNodeId() == NewNode)
335 MarkNewNodes(Hi.Val);
338 SDOperand DAGTypeLegalizer::CreateStackStoreLoad(SDOperand Op,
339 MVT::ValueType DestVT) {
340 // Create the stack frame object.
341 SDOperand FIPtr = DAG.CreateStackTemporary(DestVT);
343 // Emit a store to the stack slot.
344 SDOperand Store = DAG.getStore(DAG.getEntryNode(), Op, FIPtr, NULL, 0);
345 // Result is a load from the stack slot.
346 return DAG.getLoad(DestVT, Store, FIPtr, NULL, 0);
349 /// HandleMemIntrinsic - This handles memcpy/memset/memmove with invalid
350 /// operands. This promotes or expands the operands as required.
351 SDOperand DAGTypeLegalizer::HandleMemIntrinsic(SDNode *N) {
352 // The chain and pointer [operands #0 and #1] are always valid types.
353 SDOperand Chain = N->getOperand(0);
354 SDOperand Ptr = N->getOperand(1);
355 SDOperand Op2 = N->getOperand(2);
357 // Op #2 is either a value (memset) or a pointer. Promote it if required.
358 switch (getTypeAction(Op2.getValueType())) {
359 default: assert(0 && "Unknown action for pointer/value operand");
361 case Promote: Op2 = GetPromotedOp(Op2); break;
364 // The length could have any action required.
365 SDOperand Length = N->getOperand(3);
366 switch (getTypeAction(Length.getValueType())) {
367 default: assert(0 && "Unknown action for memop operand");
369 case Promote: Length = GetPromotedZExtOp(Length); break;
371 SDOperand Dummy; // discard the high part.
372 GetExpandedOp(Length, Length, Dummy);
376 SDOperand Align = N->getOperand(4);
377 switch (getTypeAction(Align.getValueType())) {
378 default: assert(0 && "Unknown action for memop operand");
380 case Promote: Align = GetPromotedZExtOp(Align); break;
383 SDOperand AlwaysInline = N->getOperand(5);
384 switch (getTypeAction(AlwaysInline.getValueType())) {
385 default: assert(0 && "Unknown action for memop operand");
387 case Promote: AlwaysInline = GetPromotedZExtOp(AlwaysInline); break;
390 SDOperand Ops[] = { Chain, Ptr, Op2, Length, Align, AlwaysInline };
391 return DAG.UpdateNodeOperands(SDOperand(N, 0), Ops, 6);
394 /// SplitOp - Return the lower and upper halves of Op's bits in a value type
395 /// half the size of Op's.
396 void DAGTypeLegalizer::SplitOp(SDOperand Op, SDOperand &Lo, SDOperand &Hi) {
397 unsigned NVTBits = MVT::getSizeInBits(Op.getValueType())/2;
398 assert(MVT::getSizeInBits(Op.getValueType()) == 2*NVTBits &&
399 "Cannot split odd sized integer type");
400 MVT::ValueType NVT = MVT::getIntegerType(NVTBits);
401 Lo = DAG.getNode(ISD::TRUNCATE, NVT, Op);
402 Hi = DAG.getNode(ISD::SRL, Op.getValueType(), Op,
403 DAG.getConstant(NVTBits, TLI.getShiftAmountTy()));
404 Hi = DAG.getNode(ISD::TRUNCATE, NVT, Hi);
408 //===----------------------------------------------------------------------===//
410 //===----------------------------------------------------------------------===//
412 /// LegalizeTypes - This transforms the SelectionDAG into a SelectionDAG that
413 /// only uses types natively supported by the target.
415 /// Note that this is an involved process that may invalidate pointers into
417 void SelectionDAG::LegalizeTypes() {
418 DAGTypeLegalizer(*this).run();