1 //===-- LegalizeDAG.cpp - Implement SelectionDAG::Legalize ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the SelectionDAG::Legalize method.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/CodeGen/SelectionDAG.h"
15 #include "llvm/CodeGen/MachineConstantPool.h"
16 #include "llvm/CodeGen/MachineFunction.h"
17 #include "llvm/CodeGen/MachineFrameInfo.h"
18 #include "llvm/Target/TargetLowering.h"
19 #include "llvm/Target/TargetData.h"
20 #include "llvm/Target/TargetOptions.h"
21 #include "llvm/Constants.h"
25 //===----------------------------------------------------------------------===//
26 /// SelectionDAGLegalize - This takes an arbitrary SelectionDAG as input and
27 /// hacks on it until the target machine can handle it. This involves
28 /// eliminating value sizes the machine cannot handle (promoting small sizes to
29 /// large sizes or splitting up large values into small values) as well as
30 /// eliminating operations the machine cannot handle.
32 /// This code also does a small amount of optimization and recognition of idioms
33 /// as part of its processing. For example, if a target does not support a
34 /// 'setcc' instruction efficiently, but does support 'brcc' instruction, this
35 /// will attempt merge setcc and brc instructions into brcc's.
38 class SelectionDAGLegalize {
42 /// LegalizeAction - This enum indicates what action we should take for each
43 /// value type the can occur in the program.
45 Legal, // The target natively supports this value type.
46 Promote, // This should be promoted to the next larger type.
47 Expand, // This integer type should be broken into smaller pieces.
50 /// ValueTypeActions - This is a bitvector that contains two bits for each
51 /// value type, where the two bits correspond to the LegalizeAction enum.
52 /// This can be queried with "getTypeAction(VT)".
53 unsigned ValueTypeActions;
55 /// NeedsAnotherIteration - This is set when we expand a large integer
56 /// operation into smaller integer operations, but the smaller operations are
57 /// not set. This occurs only rarely in practice, for targets that don't have
58 /// 32-bit or larger integer registers.
59 bool NeedsAnotherIteration;
61 /// LegalizedNodes - For nodes that are of legal width, and that have more
62 /// than one use, this map indicates what regularized operand to use. This
63 /// allows us to avoid legalizing the same thing more than once.
64 std::map<SDOperand, SDOperand> LegalizedNodes;
66 /// PromotedNodes - For nodes that are below legal width, and that have more
67 /// than one use, this map indicates what promoted value to use. This allows
68 /// us to avoid promoting the same thing more than once.
69 std::map<SDOperand, SDOperand> PromotedNodes;
71 /// ExpandedNodes - For nodes that need to be expanded, and which have more
72 /// than one use, this map indicates which which operands are the expanded
73 /// version of the input. This allows us to avoid expanding the same node
75 std::map<SDOperand, std::pair<SDOperand, SDOperand> > ExpandedNodes;
77 void AddLegalizedOperand(SDOperand From, SDOperand To) {
78 bool isNew = LegalizedNodes.insert(std::make_pair(From, To)).second;
79 assert(isNew && "Got into the map somehow?");
81 void AddPromotedOperand(SDOperand From, SDOperand To) {
82 bool isNew = PromotedNodes.insert(std::make_pair(From, To)).second;
83 assert(isNew && "Got into the map somehow?");
88 SelectionDAGLegalize(SelectionDAG &DAG);
90 /// Run - While there is still lowering to do, perform a pass over the DAG.
91 /// Most regularization can be done in a single pass, but targets that require
92 /// large values to be split into registers multiple times (e.g. i64 -> 4x
93 /// i16) require iteration for these values (the first iteration will demote
94 /// to i32, the second will demote to i16).
97 NeedsAnotherIteration = false;
99 } while (NeedsAnotherIteration);
102 /// getTypeAction - Return how we should legalize values of this type, either
103 /// it is already legal or we need to expand it into multiple registers of
104 /// smaller integer type, or we need to promote it to a larger type.
105 LegalizeAction getTypeAction(MVT::ValueType VT) const {
106 return (LegalizeAction)((ValueTypeActions >> (2*VT)) & 3);
109 /// isTypeLegal - Return true if this type is legal on this target.
111 bool isTypeLegal(MVT::ValueType VT) const {
112 return getTypeAction(VT) == Legal;
118 SDOperand LegalizeOp(SDOperand O);
119 void ExpandOp(SDOperand O, SDOperand &Lo, SDOperand &Hi);
120 SDOperand PromoteOp(SDOperand O);
122 SDOperand ExpandLibCall(const char *Name, SDNode *Node,
124 SDOperand ExpandIntToFP(bool isSigned, MVT::ValueType DestTy,
126 bool ExpandShift(unsigned Opc, SDOperand Op, SDOperand Amt,
127 SDOperand &Lo, SDOperand &Hi);
128 void ExpandAddSub(bool isAdd, SDOperand Op, SDOperand Amt,
129 SDOperand &Lo, SDOperand &Hi);
131 SDOperand getIntPtrConstant(uint64_t Val) {
132 return DAG.getConstant(Val, TLI.getPointerTy());
138 SelectionDAGLegalize::SelectionDAGLegalize(SelectionDAG &dag)
139 : TLI(dag.getTargetLoweringInfo()), DAG(dag),
140 ValueTypeActions(TLI.getValueTypeActions()) {
141 assert(MVT::LAST_VALUETYPE <= 16 &&
142 "Too many value types for ValueTypeActions to hold!");
145 void SelectionDAGLegalize::LegalizeDAG() {
146 SDOperand OldRoot = DAG.getRoot();
147 SDOperand NewRoot = LegalizeOp(OldRoot);
148 DAG.setRoot(NewRoot);
150 ExpandedNodes.clear();
151 LegalizedNodes.clear();
152 PromotedNodes.clear();
154 // Remove dead nodes now.
155 DAG.RemoveDeadNodes(OldRoot.Val);
158 SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
159 assert(getTypeAction(Op.getValueType()) == Legal &&
160 "Caller should expand or promote operands that are not legal!");
162 // If this operation defines any values that cannot be represented in a
163 // register on this target, make sure to expand or promote them.
164 if (Op.Val->getNumValues() > 1) {
165 for (unsigned i = 0, e = Op.Val->getNumValues(); i != e; ++i)
166 switch (getTypeAction(Op.Val->getValueType(i))) {
167 case Legal: break; // Nothing to do.
170 ExpandOp(Op.getValue(i), T1, T2);
171 assert(LegalizedNodes.count(Op) &&
172 "Expansion didn't add legal operands!");
173 return LegalizedNodes[Op];
176 PromoteOp(Op.getValue(i));
177 assert(LegalizedNodes.count(Op) &&
178 "Expansion didn't add legal operands!");
179 return LegalizedNodes[Op];
183 std::map<SDOperand, SDOperand>::iterator I = LegalizedNodes.find(Op);
184 if (I != LegalizedNodes.end()) return I->second;
186 SDOperand Tmp1, Tmp2, Tmp3;
188 SDOperand Result = Op;
189 SDNode *Node = Op.Val;
191 switch (Node->getOpcode()) {
193 std::cerr << "NODE: "; Node->dump(); std::cerr << "\n";
194 assert(0 && "Do not know how to legalize this operator!");
196 case ISD::EntryToken:
197 case ISD::FrameIndex:
198 case ISD::GlobalAddress:
199 case ISD::ExternalSymbol:
200 case ISD::ConstantPool: // Nothing to do.
201 assert(getTypeAction(Node->getValueType(0)) == Legal &&
202 "This must be legal!");
204 case ISD::CopyFromReg:
205 Tmp1 = LegalizeOp(Node->getOperand(0));
206 if (Tmp1 != Node->getOperand(0))
207 Result = DAG.getCopyFromReg(cast<RegSDNode>(Node)->getReg(),
208 Node->getValueType(0), Tmp1);
210 Result = Op.getValue(0);
212 // Since CopyFromReg produces two values, make sure to remember that we
213 // legalized both of them.
214 AddLegalizedOperand(Op.getValue(0), Result);
215 AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
216 return Result.getValue(Op.ResNo);
217 case ISD::ImplicitDef:
218 Tmp1 = LegalizeOp(Node->getOperand(0));
219 if (Tmp1 != Node->getOperand(0))
220 Result = DAG.getImplicitDef(Tmp1, cast<RegSDNode>(Node)->getReg());
223 // We know we don't need to expand constants here, constants only have one
224 // value and we check that it is fine above.
226 // FIXME: Maybe we should handle things like targets that don't support full
227 // 32-bit immediates?
229 case ISD::ConstantFP: {
230 // Spill FP immediates to the constant pool if the target cannot directly
231 // codegen them. Targets often have some immediate values that can be
232 // efficiently generated into an FP register without a load. We explicitly
233 // leave these constants as ConstantFP nodes for the target to deal with.
235 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Node);
237 // Check to see if this FP immediate is already legal.
238 bool isLegal = false;
239 for (TargetLowering::legal_fpimm_iterator I = TLI.legal_fpimm_begin(),
240 E = TLI.legal_fpimm_end(); I != E; ++I)
241 if (CFP->isExactlyValue(*I)) {
247 // Otherwise we need to spill the constant to memory.
248 MachineConstantPool *CP = DAG.getMachineFunction().getConstantPool();
252 // If a FP immediate is precise when represented as a float, we put it
253 // into the constant pool as a float, even if it's is statically typed
255 MVT::ValueType VT = CFP->getValueType(0);
256 bool isDouble = VT == MVT::f64;
257 ConstantFP *LLVMC = ConstantFP::get(isDouble ? Type::DoubleTy :
258 Type::FloatTy, CFP->getValue());
259 if (isDouble && CFP->isExactlyValue((float)CFP->getValue())) {
260 LLVMC = cast<ConstantFP>(ConstantExpr::getCast(LLVMC, Type::FloatTy));
265 SDOperand CPIdx = DAG.getConstantPool(CP->getConstantPoolIndex(LLVMC),
268 Result = DAG.getNode(ISD::EXTLOAD, MVT::f64, DAG.getEntryNode(), CPIdx,
271 Result = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx);
276 case ISD::TokenFactor: {
277 std::vector<SDOperand> Ops;
278 bool Changed = false;
279 for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
280 SDOperand Op = Node->getOperand(i);
281 // Fold single-use TokenFactor nodes into this token factor as we go.
282 if (Op.getOpcode() == ISD::TokenFactor && Op.hasOneUse()) {
284 for (unsigned j = 0, e = Op.getNumOperands(); j != e; ++j)
285 Ops.push_back(LegalizeOp(Op.getOperand(j)));
287 Ops.push_back(LegalizeOp(Op)); // Legalize the operands
288 Changed |= Ops[i] != Op;
292 Result = DAG.getNode(ISD::TokenFactor, MVT::Other, Ops);
296 case ISD::ADJCALLSTACKDOWN:
297 case ISD::ADJCALLSTACKUP:
298 Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the chain.
299 // There is no need to legalize the size argument (Operand #1)
300 if (Tmp1 != Node->getOperand(0))
301 Result = DAG.getNode(Node->getOpcode(), MVT::Other, Tmp1,
302 Node->getOperand(1));
304 case ISD::DYNAMIC_STACKALLOC:
305 Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the chain.
306 Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the size.
307 Tmp3 = LegalizeOp(Node->getOperand(2)); // Legalize the alignment.
308 if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
309 Tmp3 != Node->getOperand(2))
310 Result = DAG.getNode(ISD::DYNAMIC_STACKALLOC, Node->getValueType(0),
313 Result = Op.getValue(0);
315 // Since this op produces two values, make sure to remember that we
316 // legalized both of them.
317 AddLegalizedOperand(SDOperand(Node, 0), Result);
318 AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
319 return Result.getValue(Op.ResNo);
322 Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the chain.
323 Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the callee.
325 bool Changed = false;
326 std::vector<SDOperand> Ops;
327 for (unsigned i = 2, e = Node->getNumOperands(); i != e; ++i) {
328 Ops.push_back(LegalizeOp(Node->getOperand(i)));
329 Changed |= Ops.back() != Node->getOperand(i);
332 if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) || Changed) {
333 std::vector<MVT::ValueType> RetTyVTs;
334 RetTyVTs.reserve(Node->getNumValues());
335 for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
336 RetTyVTs.push_back(Node->getValueType(i));
337 Result = SDOperand(DAG.getCall(RetTyVTs, Tmp1, Tmp2, Ops), 0);
339 Result = Result.getValue(0);
341 // Since calls produce multiple values, make sure to remember that we
342 // legalized all of them.
343 for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
344 AddLegalizedOperand(SDOperand(Node, i), Result.getValue(i));
345 return Result.getValue(Op.ResNo);
348 Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the chain.
349 if (Tmp1 != Node->getOperand(0))
350 Result = DAG.getNode(ISD::BR, MVT::Other, Tmp1, Node->getOperand(1));
354 Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the chain.
356 switch (getTypeAction(Node->getOperand(1).getValueType())) {
357 case Expand: assert(0 && "It's impossible to expand bools");
359 Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the condition.
362 Tmp2 = PromoteOp(Node->getOperand(1)); // Promote the condition.
365 // Basic block destination (Op#2) is always legal.
366 if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
367 Result = DAG.getNode(ISD::BRCOND, MVT::Other, Tmp1, Tmp2,
368 Node->getOperand(2));
372 Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the chain.
373 Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the pointer.
374 if (Tmp1 != Node->getOperand(0) ||
375 Tmp2 != Node->getOperand(1))
376 Result = DAG.getLoad(Node->getValueType(0), Tmp1, Tmp2);
378 Result = SDOperand(Node, 0);
380 // Since loads produce two values, make sure to remember that we legalized
382 AddLegalizedOperand(SDOperand(Node, 0), Result);
383 AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
384 return Result.getValue(Op.ResNo);
389 Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the chain.
390 Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the pointer.
391 if (Tmp1 != Node->getOperand(0) ||
392 Tmp2 != Node->getOperand(1))
393 Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1, Tmp2,
394 cast<MVTSDNode>(Node)->getExtraValueType());
396 Result = SDOperand(Node, 0);
398 // Since loads produce two values, make sure to remember that we legalized
400 AddLegalizedOperand(SDOperand(Node, 0), Result);
401 AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
402 return Result.getValue(Op.ResNo);
404 case ISD::EXTRACT_ELEMENT:
405 // Get both the low and high parts.
406 ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
407 if (cast<ConstantSDNode>(Node->getOperand(1))->getValue())
408 Result = Tmp2; // 1 -> Hi
410 Result = Tmp1; // 0 -> Lo
414 Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the chain.
416 switch (getTypeAction(Node->getOperand(1).getValueType())) {
418 // Legalize the incoming value (must be legal).
419 Tmp2 = LegalizeOp(Node->getOperand(1));
420 if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
421 Result = DAG.getCopyToReg(Tmp1, Tmp2, cast<RegSDNode>(Node)->getReg());
424 Tmp2 = PromoteOp(Node->getOperand(1));
425 Result = DAG.getCopyToReg(Tmp1, Tmp2, cast<RegSDNode>(Node)->getReg());
429 ExpandOp(Node->getOperand(1), Lo, Hi);
430 unsigned Reg = cast<RegSDNode>(Node)->getReg();
431 Lo = DAG.getCopyToReg(Tmp1, Lo, Reg);
432 Hi = DAG.getCopyToReg(Tmp1, Hi, Reg+1);
433 // Note that the copytoreg nodes are independent of each other.
434 Result = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo, Hi);
435 assert(isTypeLegal(Result.getValueType()) &&
436 "Cannot expand multiple times yet (i64 -> i16)");
442 Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the chain.
443 switch (Node->getNumOperands()) {
445 switch (getTypeAction(Node->getOperand(1).getValueType())) {
447 Tmp2 = LegalizeOp(Node->getOperand(1));
448 if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
449 Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Tmp2);
453 ExpandOp(Node->getOperand(1), Lo, Hi);
454 Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Lo, Hi);
458 Tmp2 = PromoteOp(Node->getOperand(1));
459 Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Tmp2);
464 if (Tmp1 != Node->getOperand(0))
465 Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1);
467 default: { // ret <values>
468 std::vector<SDOperand> NewValues;
469 NewValues.push_back(Tmp1);
470 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
471 switch (getTypeAction(Node->getOperand(i).getValueType())) {
473 NewValues.push_back(LegalizeOp(Node->getOperand(i)));
477 ExpandOp(Node->getOperand(i), Lo, Hi);
478 NewValues.push_back(Lo);
479 NewValues.push_back(Hi);
483 assert(0 && "Can't promote multiple return value yet!");
485 Result = DAG.getNode(ISD::RET, MVT::Other, NewValues);
491 Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the chain.
492 Tmp2 = LegalizeOp(Node->getOperand(2)); // Legalize the pointer.
494 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
495 if (ConstantFPSDNode *CFP =dyn_cast<ConstantFPSDNode>(Node->getOperand(1))){
496 if (CFP->getValueType(0) == MVT::f32) {
501 V.F = CFP->getValue();
502 Result = DAG.getNode(ISD::STORE, MVT::Other, Tmp1,
503 DAG.getConstant(V.I, MVT::i32), Tmp2);
505 assert(CFP->getValueType(0) == MVT::f64 && "Unknown FP type!");
510 V.F = CFP->getValue();
511 Result = DAG.getNode(ISD::STORE, MVT::Other, Tmp1,
512 DAG.getConstant(V.I, MVT::i64), Tmp2);
518 switch (getTypeAction(Node->getOperand(1).getValueType())) {
520 SDOperand Val = LegalizeOp(Node->getOperand(1));
521 if (Val != Node->getOperand(1) || Tmp1 != Node->getOperand(0) ||
522 Tmp2 != Node->getOperand(2))
523 Result = DAG.getNode(ISD::STORE, MVT::Other, Tmp1, Val, Tmp2);
527 // Truncate the value and store the result.
528 Tmp3 = PromoteOp(Node->getOperand(1));
529 Result = DAG.getNode(ISD::TRUNCSTORE, MVT::Other, Tmp1, Tmp3, Tmp2,
530 Node->getOperand(1).getValueType());
535 ExpandOp(Node->getOperand(1), Lo, Hi);
537 if (!TLI.isLittleEndian())
540 Lo = DAG.getNode(ISD::STORE, MVT::Other, Tmp1, Lo, Tmp2);
542 unsigned IncrementSize = MVT::getSizeInBits(Hi.getValueType())/8;
543 Tmp2 = DAG.getNode(ISD::ADD, Tmp2.getValueType(), Tmp2,
544 getIntPtrConstant(IncrementSize));
545 assert(isTypeLegal(Tmp2.getValueType()) &&
546 "Pointers must be legal!");
547 Hi = DAG.getNode(ISD::STORE, MVT::Other, Tmp1, Hi, Tmp2);
548 Result = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo, Hi);
552 case ISD::TRUNCSTORE:
553 Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the chain.
554 Tmp3 = LegalizeOp(Node->getOperand(2)); // Legalize the pointer.
556 switch (getTypeAction(Node->getOperand(1).getValueType())) {
558 Tmp2 = LegalizeOp(Node->getOperand(1));
559 if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
560 Tmp3 != Node->getOperand(2))
561 Result = DAG.getNode(ISD::TRUNCSTORE, MVT::Other, Tmp1, Tmp2, Tmp3,
562 cast<MVTSDNode>(Node)->getExtraValueType());
566 assert(0 && "Cannot handle illegal TRUNCSTORE yet!");
570 switch (getTypeAction(Node->getOperand(0).getValueType())) {
571 case Expand: assert(0 && "It's impossible to expand bools");
573 Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the condition.
576 Tmp1 = PromoteOp(Node->getOperand(0)); // Promote the condition.
579 Tmp2 = LegalizeOp(Node->getOperand(1)); // TrueVal
580 Tmp3 = LegalizeOp(Node->getOperand(2)); // FalseVal
582 switch (TLI.getOperationAction(Node->getOpcode(), Tmp2.getValueType())) {
583 default: assert(0 && "This action is not supported yet!");
584 case TargetLowering::Legal:
585 if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
586 Tmp3 != Node->getOperand(2))
587 Result = DAG.getNode(ISD::SELECT, Node->getValueType(0),
590 case TargetLowering::Promote: {
592 TLI.getTypeToPromoteTo(ISD::SELECT, Tmp2.getValueType());
593 unsigned ExtOp, TruncOp;
594 if (MVT::isInteger(Tmp2.getValueType())) {
595 ExtOp = ISD::ZERO_EXTEND;
596 TruncOp = ISD::TRUNCATE;
598 ExtOp = ISD::FP_EXTEND;
599 TruncOp = ISD::FP_ROUND;
601 // Promote each of the values to the new type.
602 Tmp2 = DAG.getNode(ExtOp, NVT, Tmp2);
603 Tmp3 = DAG.getNode(ExtOp, NVT, Tmp3);
604 // Perform the larger operation, then round down.
605 Result = DAG.getNode(ISD::SELECT, NVT, Tmp1, Tmp2,Tmp3);
606 Result = DAG.getNode(TruncOp, Node->getValueType(0), Result);
612 switch (getTypeAction(Node->getOperand(0).getValueType())) {
614 Tmp1 = LegalizeOp(Node->getOperand(0)); // LHS
615 Tmp2 = LegalizeOp(Node->getOperand(1)); // RHS
616 if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
617 Result = DAG.getSetCC(cast<SetCCSDNode>(Node)->getCondition(),
618 Node->getValueType(0), Tmp1, Tmp2);
621 Tmp1 = PromoteOp(Node->getOperand(0)); // LHS
622 Tmp2 = PromoteOp(Node->getOperand(1)); // RHS
624 // If this is an FP compare, the operands have already been extended.
625 if (MVT::isInteger(Node->getOperand(0).getValueType())) {
626 MVT::ValueType VT = Node->getOperand(0).getValueType();
627 MVT::ValueType NVT = TLI.getTypeToTransformTo(VT);
629 // Otherwise, we have to insert explicit sign or zero extends. Note
630 // that we could insert sign extends for ALL conditions, but zero extend
631 // is cheaper on many machines (an AND instead of two shifts), so prefer
633 switch (cast<SetCCSDNode>(Node)->getCondition()) {
634 default: assert(0 && "Unknown integer comparison!");
641 // ALL of these operations will work if we either sign or zero extend
642 // the operands (including the unsigned comparisons!). Zero extend is
643 // usually a simpler/cheaper operation, so prefer it.
644 Tmp1 = DAG.getNode(ISD::ZERO_EXTEND_INREG, NVT, Tmp1, VT);
645 Tmp2 = DAG.getNode(ISD::ZERO_EXTEND_INREG, NVT, Tmp2, VT);
651 Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1, VT);
652 Tmp2 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp2, VT);
657 Result = DAG.getSetCC(cast<SetCCSDNode>(Node)->getCondition(),
658 Node->getValueType(0), Tmp1, Tmp2);
661 SDOperand LHSLo, LHSHi, RHSLo, RHSHi;
662 ExpandOp(Node->getOperand(0), LHSLo, LHSHi);
663 ExpandOp(Node->getOperand(1), RHSLo, RHSHi);
664 switch (cast<SetCCSDNode>(Node)->getCondition()) {
667 Tmp1 = DAG.getNode(ISD::XOR, LHSLo.getValueType(), LHSLo, RHSLo);
668 Tmp2 = DAG.getNode(ISD::XOR, LHSLo.getValueType(), LHSHi, RHSHi);
669 Tmp1 = DAG.getNode(ISD::OR, Tmp1.getValueType(), Tmp1, Tmp2);
670 Result = DAG.getSetCC(cast<SetCCSDNode>(Node)->getCondition(),
671 Node->getValueType(0), Tmp1,
672 DAG.getConstant(0, Tmp1.getValueType()));
675 // FIXME: This generated code sucks.
677 switch (cast<SetCCSDNode>(Node)->getCondition()) {
678 default: assert(0 && "Unknown integer setcc!");
680 case ISD::SETULT: LowCC = ISD::SETULT; break;
682 case ISD::SETUGT: LowCC = ISD::SETUGT; break;
684 case ISD::SETULE: LowCC = ISD::SETULE; break;
686 case ISD::SETUGE: LowCC = ISD::SETUGE; break;
689 // Tmp1 = lo(op1) < lo(op2) // Always unsigned comparison
690 // Tmp2 = hi(op1) < hi(op2) // Signedness depends on operands
691 // dest = hi(op1) == hi(op2) ? Tmp1 : Tmp2;
693 // NOTE: on targets without efficient SELECT of bools, we can always use
694 // this identity: (B1 ? B2 : B3) --> (B1 & B2)|(!B1&B3)
695 Tmp1 = DAG.getSetCC(LowCC, Node->getValueType(0), LHSLo, RHSLo);
696 Tmp2 = DAG.getSetCC(cast<SetCCSDNode>(Node)->getCondition(),
697 Node->getValueType(0), LHSHi, RHSHi);
698 Result = DAG.getSetCC(ISD::SETEQ, Node->getValueType(0), LHSHi, RHSHi);
699 Result = DAG.getNode(ISD::SELECT, Tmp1.getValueType(),
709 Tmp1 = LegalizeOp(Node->getOperand(0));
710 Tmp2 = LegalizeOp(Node->getOperand(1));
711 Tmp3 = LegalizeOp(Node->getOperand(2));
712 SDOperand Tmp4 = LegalizeOp(Node->getOperand(3));
713 SDOperand Tmp5 = LegalizeOp(Node->getOperand(4));
715 switch (TLI.getOperationAction(Node->getOpcode(), MVT::Other)) {
716 default: assert(0 && "This action not implemented for this operation!");
717 case TargetLowering::Legal:
718 if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
719 Tmp3 != Node->getOperand(2) || Tmp4 != Node->getOperand(3) ||
720 Tmp5 != Node->getOperand(4)) {
721 std::vector<SDOperand> Ops;
722 Ops.push_back(Tmp1); Ops.push_back(Tmp2); Ops.push_back(Tmp3);
723 Ops.push_back(Tmp4); Ops.push_back(Tmp5);
724 Result = DAG.getNode(Node->getOpcode(), MVT::Other, Ops);
727 case TargetLowering::Expand: {
728 // Otherwise, the target does not support this operation. Lower the
729 // operation to an explicit libcall as appropriate.
730 MVT::ValueType IntPtr = TLI.getPointerTy();
731 const Type *IntPtrTy = TLI.getTargetData().getIntPtrType();
732 std::vector<std::pair<SDOperand, const Type*> > Args;
734 const char *FnName = 0;
735 if (Node->getOpcode() == ISD::MEMSET) {
736 Args.push_back(std::make_pair(Tmp2, IntPtrTy));
737 // Extend the ubyte argument to be an int value for the call.
738 Tmp3 = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Tmp3);
739 Args.push_back(std::make_pair(Tmp3, Type::IntTy));
740 Args.push_back(std::make_pair(Tmp4, IntPtrTy));
743 } else if (Node->getOpcode() == ISD::MEMCPY ||
744 Node->getOpcode() == ISD::MEMMOVE) {
745 Args.push_back(std::make_pair(Tmp2, IntPtrTy));
746 Args.push_back(std::make_pair(Tmp3, IntPtrTy));
747 Args.push_back(std::make_pair(Tmp4, IntPtrTy));
748 FnName = Node->getOpcode() == ISD::MEMMOVE ? "memmove" : "memcpy";
750 assert(0 && "Unknown op!");
752 std::pair<SDOperand,SDOperand> CallResult =
753 TLI.LowerCallTo(Tmp1, Type::VoidTy,
754 DAG.getExternalSymbol(FnName, IntPtr), Args, DAG);
755 Result = LegalizeOp(CallResult.second);
758 case TargetLowering::Custom:
759 std::vector<SDOperand> Ops;
760 Ops.push_back(Tmp1); Ops.push_back(Tmp2); Ops.push_back(Tmp3);
761 Ops.push_back(Tmp4); Ops.push_back(Tmp5);
762 Result = DAG.getNode(Node->getOpcode(), MVT::Other, Ops);
763 Result = TLI.LowerOperation(Result);
764 Result = LegalizeOp(Result);
770 case ISD::SUB_PARTS: {
771 std::vector<SDOperand> Ops;
772 bool Changed = false;
773 for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
774 Ops.push_back(LegalizeOp(Node->getOperand(i)));
775 Changed |= Ops.back() != Node->getOperand(i);
778 Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Ops);
794 Tmp1 = LegalizeOp(Node->getOperand(0)); // LHS
795 Tmp2 = LegalizeOp(Node->getOperand(1)); // RHS
796 if (Tmp1 != Node->getOperand(0) ||
797 Tmp2 != Node->getOperand(1))
798 Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1,Tmp2);
800 case ISD::ZERO_EXTEND:
801 case ISD::SIGN_EXTEND:
805 case ISD::FP_TO_SINT:
806 case ISD::FP_TO_UINT:
807 case ISD::SINT_TO_FP:
808 case ISD::UINT_TO_FP:
809 switch (getTypeAction(Node->getOperand(0).getValueType())) {
811 Tmp1 = LegalizeOp(Node->getOperand(0));
812 if (Tmp1 != Node->getOperand(0))
813 Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1);
816 if (Node->getOpcode() == ISD::SINT_TO_FP ||
817 Node->getOpcode() == ISD::UINT_TO_FP) {
818 Result = ExpandIntToFP(Node->getOpcode() == ISD::SINT_TO_FP,
819 Node->getValueType(0), Node->getOperand(0));
820 Result = LegalizeOp(Result);
823 // In the expand case, we must be dealing with a truncate, because
824 // otherwise the result would be larger than the source.
825 assert(Node->getOpcode() == ISD::TRUNCATE &&
826 "Shouldn't need to expand other operators here!");
827 ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
829 // Since the result is legal, we should just be able to truncate the low
830 // part of the source.
831 Result = DAG.getNode(ISD::TRUNCATE, Node->getValueType(0), Tmp1);
835 switch (Node->getOpcode()) {
836 case ISD::ZERO_EXTEND:
837 Result = PromoteOp(Node->getOperand(0));
838 // NOTE: Any extend would work here...
839 Result = DAG.getNode(ISD::ZERO_EXTEND, Op.getValueType(), Result);
840 Result = DAG.getNode(ISD::ZERO_EXTEND_INREG, Op.getValueType(),
841 Result, Node->getOperand(0).getValueType());
843 case ISD::SIGN_EXTEND:
844 Result = PromoteOp(Node->getOperand(0));
845 // NOTE: Any extend would work here...
846 Result = DAG.getNode(ISD::ZERO_EXTEND, Op.getValueType(), Result);
847 Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
848 Result, Node->getOperand(0).getValueType());
851 Result = PromoteOp(Node->getOperand(0));
852 Result = DAG.getNode(ISD::TRUNCATE, Op.getValueType(), Result);
855 Result = PromoteOp(Node->getOperand(0));
856 if (Result.getValueType() != Op.getValueType())
857 // Dynamically dead while we have only 2 FP types.
858 Result = DAG.getNode(ISD::FP_EXTEND, Op.getValueType(), Result);
861 case ISD::FP_TO_SINT:
862 case ISD::FP_TO_UINT:
863 Result = PromoteOp(Node->getOperand(0));
864 Result = DAG.getNode(Node->getOpcode(), Op.getValueType(), Result);
866 case ISD::SINT_TO_FP:
867 Result = PromoteOp(Node->getOperand(0));
868 Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
869 Result, Node->getOperand(0).getValueType());
870 Result = DAG.getNode(ISD::SINT_TO_FP, Op.getValueType(), Result);
872 case ISD::UINT_TO_FP:
873 Result = PromoteOp(Node->getOperand(0));
874 Result = DAG.getNode(ISD::ZERO_EXTEND_INREG, Result.getValueType(),
875 Result, Node->getOperand(0).getValueType());
876 Result = DAG.getNode(ISD::UINT_TO_FP, Op.getValueType(), Result);
881 case ISD::FP_ROUND_INREG:
882 case ISD::SIGN_EXTEND_INREG:
883 case ISD::ZERO_EXTEND_INREG: {
884 Tmp1 = LegalizeOp(Node->getOperand(0));
885 MVT::ValueType ExtraVT = cast<MVTSDNode>(Node)->getExtraValueType();
887 // If this operation is not supported, convert it to a shl/shr or load/store
889 switch (TLI.getOperationAction(Node->getOpcode(), ExtraVT)) {
890 default: assert(0 && "This action not supported for this op yet!");
891 case TargetLowering::Legal:
892 if (Tmp1 != Node->getOperand(0))
893 Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1,
896 case TargetLowering::Expand:
897 // If this is an integer extend and shifts are supported, do that.
898 if (Node->getOpcode() == ISD::ZERO_EXTEND_INREG) {
899 // NOTE: we could fall back on load/store here too for targets without
900 // AND. However, it is doubtful that any exist.
901 // AND out the appropriate bits.
903 DAG.getConstant((1ULL << MVT::getSizeInBits(ExtraVT))-1,
904 Node->getValueType(0));
905 Result = DAG.getNode(ISD::AND, Node->getValueType(0),
906 Node->getOperand(0), Mask);
907 } else if (Node->getOpcode() == ISD::SIGN_EXTEND_INREG) {
908 // NOTE: we could fall back on load/store here too for targets without
909 // SAR. However, it is doubtful that any exist.
910 unsigned BitsDiff = MVT::getSizeInBits(Node->getValueType(0)) -
911 MVT::getSizeInBits(ExtraVT);
912 SDOperand ShiftCst = DAG.getConstant(BitsDiff, TLI.getShiftAmountTy());
913 Result = DAG.getNode(ISD::SHL, Node->getValueType(0),
914 Node->getOperand(0), ShiftCst);
915 Result = DAG.getNode(ISD::SRA, Node->getValueType(0),
917 } else if (Node->getOpcode() == ISD::FP_ROUND_INREG) {
918 // The only way we can lower this is to turn it into a STORETRUNC,
919 // EXTLOAD pair, targetting a temporary location (a stack slot).
921 // NOTE: there is a choice here between constantly creating new stack
922 // slots and always reusing the same one. We currently always create
923 // new ones, as reuse may inhibit scheduling.
924 const Type *Ty = MVT::getTypeForValueType(ExtraVT);
925 unsigned TySize = (unsigned)TLI.getTargetData().getTypeSize(Ty);
926 unsigned Align = TLI.getTargetData().getTypeAlignment(Ty);
927 MachineFunction &MF = DAG.getMachineFunction();
929 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
930 SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
931 Result = DAG.getNode(ISD::TRUNCSTORE, MVT::Other, DAG.getEntryNode(),
932 Node->getOperand(0), StackSlot, ExtraVT);
933 Result = DAG.getNode(ISD::EXTLOAD, Node->getValueType(0),
934 Result, StackSlot, ExtraVT);
936 assert(0 && "Unknown op");
938 Result = LegalizeOp(Result);
945 if (!Op.Val->hasOneUse())
946 AddLegalizedOperand(Op, Result);
951 /// PromoteOp - Given an operation that produces a value in an invalid type,
952 /// promote it to compute the value into a larger type. The produced value will
953 /// have the correct bits for the low portion of the register, but no guarantee
954 /// is made about the top bits: it may be zero, sign-extended, or garbage.
955 SDOperand SelectionDAGLegalize::PromoteOp(SDOperand Op) {
956 MVT::ValueType VT = Op.getValueType();
957 MVT::ValueType NVT = TLI.getTypeToTransformTo(VT);
958 assert(getTypeAction(VT) == Promote &&
959 "Caller should expand or legalize operands that are not promotable!");
960 assert(NVT > VT && MVT::isInteger(NVT) == MVT::isInteger(VT) &&
961 "Cannot promote to smaller type!");
963 std::map<SDOperand, SDOperand>::iterator I = PromotedNodes.find(Op);
964 if (I != PromotedNodes.end()) return I->second;
966 SDOperand Tmp1, Tmp2, Tmp3;
969 SDNode *Node = Op.Val;
971 // Promotion needs an optimization step to clean up after it, and is not
972 // careful to avoid operations the target does not support. Make sure that
973 // all generated operations are legalized in the next iteration.
974 NeedsAnotherIteration = true;
976 switch (Node->getOpcode()) {
978 std::cerr << "NODE: "; Node->dump(); std::cerr << "\n";
979 assert(0 && "Do not know how to promote this operator!");
982 Result = DAG.getNode(ISD::ZERO_EXTEND, NVT, Op);
983 assert(isa<ConstantSDNode>(Result) && "Didn't constant fold zext?");
985 case ISD::ConstantFP:
986 Result = DAG.getNode(ISD::FP_EXTEND, NVT, Op);
987 assert(isa<ConstantFPSDNode>(Result) && "Didn't constant fold fp_extend?");
989 case ISD::CopyFromReg:
990 Result = DAG.getCopyFromReg(cast<RegSDNode>(Node)->getReg(), NVT,
991 Node->getOperand(0));
992 // Remember that we legalized the chain.
993 AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
997 assert(getTypeAction(TLI.getSetCCResultTy()) == Legal &&
998 "SetCC type is not legal??");
999 Result = DAG.getSetCC(cast<SetCCSDNode>(Node)->getCondition(),
1000 TLI.getSetCCResultTy(), Node->getOperand(0),
1001 Node->getOperand(1));
1002 Result = LegalizeOp(Result);
1006 switch (getTypeAction(Node->getOperand(0).getValueType())) {
1008 Result = LegalizeOp(Node->getOperand(0));
1009 assert(Result.getValueType() >= NVT &&
1010 "This truncation doesn't make sense!");
1011 if (Result.getValueType() > NVT) // Truncate to NVT instead of VT
1012 Result = DAG.getNode(ISD::TRUNCATE, NVT, Result);
1015 assert(0 && "Cannot handle expand yet");
1017 assert(0 && "Cannot handle promote-promote yet");
1020 case ISD::SIGN_EXTEND:
1021 case ISD::ZERO_EXTEND:
1022 switch (getTypeAction(Node->getOperand(0).getValueType())) {
1023 case Expand: assert(0 && "BUG: Smaller reg should have been promoted!");
1025 // Input is legal? Just do extend all the way to the larger type.
1026 Result = LegalizeOp(Node->getOperand(0));
1027 Result = DAG.getNode(Node->getOpcode(), NVT, Result);
1030 // Promote the reg if it's smaller.
1031 Result = PromoteOp(Node->getOperand(0));
1032 // The high bits are not guaranteed to be anything. Insert an extend.
1033 if (Node->getOpcode() == ISD::SIGN_EXTEND)
1034 Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Result, VT);
1036 Result = DAG.getNode(ISD::ZERO_EXTEND_INREG, NVT, Result, VT);
1041 case ISD::FP_EXTEND:
1042 assert(0 && "Case not implemented. Dynamically dead with 2 FP types!");
1044 switch (getTypeAction(Node->getOperand(0).getValueType())) {
1045 case Expand: assert(0 && "BUG: Cannot expand FP regs!");
1046 case Promote: assert(0 && "Unreachable with 2 FP types!");
1048 // Input is legal? Do an FP_ROUND_INREG.
1049 Result = LegalizeOp(Node->getOperand(0));
1050 Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result, VT);
1055 case ISD::SINT_TO_FP:
1056 case ISD::UINT_TO_FP:
1057 switch (getTypeAction(Node->getOperand(0).getValueType())) {
1059 Result = LegalizeOp(Node->getOperand(0));
1060 // No extra round required here.
1061 Result = DAG.getNode(Node->getOpcode(), NVT, Result);
1065 Result = PromoteOp(Node->getOperand(0));
1066 if (Node->getOpcode() == ISD::SINT_TO_FP)
1067 Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
1068 Result, Node->getOperand(0).getValueType());
1070 Result = DAG.getNode(ISD::ZERO_EXTEND_INREG, Result.getValueType(),
1071 Result, Node->getOperand(0).getValueType());
1072 // No extra round required here.
1073 Result = DAG.getNode(Node->getOpcode(), NVT, Result);
1076 Result = ExpandIntToFP(Node->getOpcode() == ISD::SINT_TO_FP, NVT,
1077 Node->getOperand(0));
1078 Result = LegalizeOp(Result);
1080 // Round if we cannot tolerate excess precision.
1081 if (NoExcessFPPrecision)
1082 Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result, VT);
1087 case ISD::FP_TO_SINT:
1088 case ISD::FP_TO_UINT:
1089 switch (getTypeAction(Node->getOperand(0).getValueType())) {
1091 Tmp1 = LegalizeOp(Node->getOperand(0));
1094 // The input result is prerounded, so we don't have to do anything
1096 Tmp1 = PromoteOp(Node->getOperand(0));
1099 assert(0 && "not implemented");
1101 Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
1110 // The input may have strange things in the top bits of the registers, but
1111 // these operations don't care. They may have wierd bits going out, but
1112 // that too is okay if they are integer operations.
1113 Tmp1 = PromoteOp(Node->getOperand(0));
1114 Tmp2 = PromoteOp(Node->getOperand(1));
1115 assert(Tmp1.getValueType() == NVT && Tmp2.getValueType() == NVT);
1116 Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
1118 // However, if this is a floating point operation, they will give excess
1119 // precision that we may not be able to tolerate. If we DO allow excess
1120 // precision, just leave it, otherwise excise it.
1121 // FIXME: Why would we need to round FP ops more than integer ones?
1122 // Is Round(Add(Add(A,B),C)) != Round(Add(Round(Add(A,B)), C))
1123 if (MVT::isFloatingPoint(NVT) && NoExcessFPPrecision)
1124 Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result, VT);
1129 // These operators require that their input be sign extended.
1130 Tmp1 = PromoteOp(Node->getOperand(0));
1131 Tmp2 = PromoteOp(Node->getOperand(1));
1132 if (MVT::isInteger(NVT)) {
1133 Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1, VT);
1134 Tmp2 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp2, VT);
1136 Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
1138 // Perform FP_ROUND: this is probably overly pessimistic.
1139 if (MVT::isFloatingPoint(NVT) && NoExcessFPPrecision)
1140 Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result, VT);
1145 // These operators require that their input be zero extended.
1146 Tmp1 = PromoteOp(Node->getOperand(0));
1147 Tmp2 = PromoteOp(Node->getOperand(1));
1148 assert(MVT::isInteger(NVT) && "Operators don't apply to FP!");
1149 Tmp1 = DAG.getNode(ISD::ZERO_EXTEND_INREG, NVT, Tmp1, VT);
1150 Tmp2 = DAG.getNode(ISD::ZERO_EXTEND_INREG, NVT, Tmp2, VT);
1151 Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
1155 Tmp1 = PromoteOp(Node->getOperand(0));
1156 Tmp2 = LegalizeOp(Node->getOperand(1));
1157 Result = DAG.getNode(ISD::SHL, NVT, Tmp1, Tmp2);
1160 // The input value must be properly sign extended.
1161 Tmp1 = PromoteOp(Node->getOperand(0));
1162 Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1, VT);
1163 Tmp2 = LegalizeOp(Node->getOperand(1));
1164 Result = DAG.getNode(ISD::SRA, NVT, Tmp1, Tmp2);
1167 // The input value must be properly zero extended.
1168 Tmp1 = PromoteOp(Node->getOperand(0));
1169 Tmp1 = DAG.getNode(ISD::ZERO_EXTEND_INREG, NVT, Tmp1, VT);
1170 Tmp2 = LegalizeOp(Node->getOperand(1));
1171 Result = DAG.getNode(ISD::SRL, NVT, Tmp1, Tmp2);
1174 Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the chain.
1175 Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the pointer.
1176 Result = DAG.getNode(ISD::EXTLOAD, NVT, Tmp1, Tmp2, VT);
1178 // Remember that we legalized the chain.
1179 AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
1182 switch (getTypeAction(Node->getOperand(0).getValueType())) {
1183 case Expand: assert(0 && "It's impossible to expand bools");
1185 Tmp1 = LegalizeOp(Node->getOperand(0));// Legalize the condition.
1188 Tmp1 = PromoteOp(Node->getOperand(0)); // Promote the condition.
1191 Tmp2 = PromoteOp(Node->getOperand(1)); // Legalize the op0
1192 Tmp3 = PromoteOp(Node->getOperand(2)); // Legalize the op1
1193 Result = DAG.getNode(ISD::SELECT, NVT, Tmp1, Tmp2, Tmp3);
1196 Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the chain.
1197 Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the callee.
1199 std::vector<SDOperand> Ops;
1200 for (unsigned i = 2, e = Node->getNumOperands(); i != e; ++i)
1201 Ops.push_back(LegalizeOp(Node->getOperand(i)));
1203 assert(Node->getNumValues() == 2 && Op.ResNo == 0 &&
1204 "Can only promote single result calls");
1205 std::vector<MVT::ValueType> RetTyVTs;
1206 RetTyVTs.reserve(2);
1207 RetTyVTs.push_back(NVT);
1208 RetTyVTs.push_back(MVT::Other);
1209 SDNode *NC = DAG.getCall(RetTyVTs, Tmp1, Tmp2, Ops);
1210 Result = SDOperand(NC, 0);
1212 // Insert the new chain mapping.
1213 AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
1218 assert(Result.Val && "Didn't set a result!");
1219 AddPromotedOperand(Op, Result);
1223 /// ExpandAddSub - Find a clever way to expand this add operation into
1225 void SelectionDAGLegalize::ExpandAddSub(bool isAdd, SDOperand LHS,SDOperand RHS,
1226 SDOperand &Lo, SDOperand &Hi) {
1227 // Expand the subcomponents.
1228 SDOperand LHSL, LHSH, RHSL, RHSH;
1229 ExpandOp(LHS, LHSL, LHSH);
1230 ExpandOp(RHS, RHSL, RHSH);
1232 // Convert this add to the appropriate ADDC pair. The low part has no carry
1234 unsigned Opc = isAdd ? ISD::ADD_PARTS : ISD::SUB_PARTS;
1235 std::vector<SDOperand> Ops;
1236 Ops.push_back(LHSL);
1237 Ops.push_back(LHSH);
1238 Ops.push_back(RHSL);
1239 Ops.push_back(RHSH);
1240 Lo = DAG.getNode(Opc, LHSL.getValueType(), Ops);
1241 Hi = Lo.getValue(1);
1244 /// ExpandShift - Try to find a clever way to expand this shift operation out to
1245 /// smaller elements. If we can't find a way that is more efficient than a
1246 /// libcall on this target, return false. Otherwise, return true with the
1247 /// low-parts expanded into Lo and Hi.
1248 bool SelectionDAGLegalize::ExpandShift(unsigned Opc, SDOperand Op,SDOperand Amt,
1249 SDOperand &Lo, SDOperand &Hi) {
1250 assert((Opc == ISD::SHL || Opc == ISD::SRA || Opc == ISD::SRL) &&
1251 "This is not a shift!");
1252 MVT::ValueType NVT = TLI.getTypeToTransformTo(Op.getValueType());
1254 // If we have an efficient select operation (or if the selects will all fold
1255 // away), lower to some complex code, otherwise just emit the libcall.
1256 if (TLI.getOperationAction(ISD::SELECT, NVT) != TargetLowering::Legal &&
1257 !isa<ConstantSDNode>(Amt))
1261 ExpandOp(Op, InL, InH);
1262 SDOperand ShAmt = LegalizeOp(Amt);
1263 MVT::ValueType ShTy = ShAmt.getValueType();
1265 unsigned NVTBits = MVT::getSizeInBits(NVT);
1266 SDOperand NAmt = DAG.getNode(ISD::SUB, ShTy, // NAmt = 32-ShAmt
1267 DAG.getConstant(NVTBits, ShTy), ShAmt);
1269 // Compare the unmasked shift amount against 32.
1270 SDOperand Cond = DAG.getSetCC(ISD::SETGE, TLI.getSetCCResultTy(), ShAmt,
1271 DAG.getConstant(NVTBits, ShTy));
1273 if (TLI.getShiftAmountFlavor() != TargetLowering::Mask) {
1274 ShAmt = DAG.getNode(ISD::AND, ShTy, ShAmt, // ShAmt &= 31
1275 DAG.getConstant(NVTBits-1, ShTy));
1276 NAmt = DAG.getNode(ISD::AND, ShTy, NAmt, // NAmt &= 31
1277 DAG.getConstant(NVTBits-1, ShTy));
1280 if (Opc == ISD::SHL) {
1281 SDOperand T1 = DAG.getNode(ISD::OR, NVT,// T1 = (Hi << Amt) | (Lo >> NAmt)
1282 DAG.getNode(ISD::SHL, NVT, InH, ShAmt),
1283 DAG.getNode(ISD::SRL, NVT, InL, NAmt));
1284 SDOperand T2 = DAG.getNode(ISD::SHL, NVT, InL, ShAmt); // T2 = Lo << Amt&31
1286 Hi = DAG.getNode(ISD::SELECT, NVT, Cond, T2, T1);
1287 Lo = DAG.getNode(ISD::SELECT, NVT, Cond, DAG.getConstant(0, NVT), T2);
1289 SDOperand HiLoPart = DAG.getNode(ISD::SELECT, NVT,
1290 DAG.getSetCC(ISD::SETEQ,
1291 TLI.getSetCCResultTy(), NAmt,
1292 DAG.getConstant(32, ShTy)),
1293 DAG.getConstant(0, NVT),
1294 DAG.getNode(ISD::SHL, NVT, InH, NAmt));
1295 SDOperand T1 = DAG.getNode(ISD::OR, NVT,// T1 = (Hi << NAmt) | (Lo >> Amt)
1297 DAG.getNode(ISD::SRL, NVT, InL, ShAmt));
1298 SDOperand T2 = DAG.getNode(Opc, NVT, InH, ShAmt); // T2 = InH >> ShAmt&31
1301 if (Opc == ISD::SRA)
1302 HiPart = DAG.getNode(ISD::SRA, NVT, InH,
1303 DAG.getConstant(NVTBits-1, ShTy));
1305 HiPart = DAG.getConstant(0, NVT);
1306 Lo = DAG.getNode(ISD::SELECT, NVT, Cond, T2, T1);
1307 Hi = DAG.getNode(ISD::SELECT, NVT, Cond, HiPart, T2);
1312 /// FindLatestAdjCallStackDown - Scan up the dag to find the latest (highest
1313 /// NodeDepth) node that is an AdjCallStackDown operation and occurs later than
1315 static void FindLatestAdjCallStackDown(SDNode *Node, SDNode *&Found) {
1316 if (Node->getNodeDepth() <= Found->getNodeDepth()) return;
1318 // If we found an ADJCALLSTACKDOWN, we already know this node occurs later
1319 // than the Found node. Just remember this node and return.
1320 if (Node->getOpcode() == ISD::ADJCALLSTACKDOWN) {
1325 // Otherwise, scan the operands of Node to see if any of them is a call.
1326 assert(Node->getNumOperands() != 0 &&
1327 "All leaves should have depth equal to the entry node!");
1328 for (unsigned i = 0, e = Node->getNumOperands()-1; i != e; ++i)
1329 FindLatestAdjCallStackDown(Node->getOperand(i).Val, Found);
1331 // Tail recurse for the last iteration.
1332 FindLatestAdjCallStackDown(Node->getOperand(Node->getNumOperands()-1).Val,
1337 /// FindEarliestAdjCallStackUp - Scan down the dag to find the earliest (lowest
1338 /// NodeDepth) node that is an AdjCallStackUp operation and occurs more recent
1340 static void FindEarliestAdjCallStackUp(SDNode *Node, SDNode *&Found) {
1341 if (Found && Node->getNodeDepth() >= Found->getNodeDepth()) return;
1343 // If we found an ADJCALLSTACKUP, we already know this node occurs earlier
1344 // than the Found node. Just remember this node and return.
1345 if (Node->getOpcode() == ISD::ADJCALLSTACKUP) {
1350 // Otherwise, scan the operands of Node to see if any of them is a call.
1351 SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
1352 if (UI == E) return;
1353 for (--E; UI != E; ++UI)
1354 FindEarliestAdjCallStackUp(*UI, Found);
1356 // Tail recurse for the last iteration.
1357 FindEarliestAdjCallStackUp(*UI, Found);
1360 /// FindAdjCallStackUp - Given a chained node that is part of a call sequence,
1361 /// find the ADJCALLSTACKUP node that terminates the call sequence.
1362 static SDNode *FindAdjCallStackUp(SDNode *Node) {
1363 if (Node->getOpcode() == ISD::ADJCALLSTACKUP)
1365 assert(!Node->use_empty() && "Could not find ADJCALLSTACKUP!");
1367 if (Node->hasOneUse()) // Simple case, only has one user to check.
1368 return FindAdjCallStackUp(*Node->use_begin());
1370 SDOperand TheChain(Node, Node->getNumValues()-1);
1371 assert(TheChain.getValueType() == MVT::Other && "Is not a token chain!");
1373 for (SDNode::use_iterator UI = Node->use_begin(),
1374 E = Node->use_end(); ; ++UI) {
1375 assert(UI != E && "Didn't find a user of the tokchain, no ADJCALLSTACKUP!");
1377 // Make sure to only follow users of our token chain.
1379 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
1380 if (User->getOperand(i) == TheChain)
1381 return FindAdjCallStackUp(User);
1383 assert(0 && "Unreachable");
1387 /// FindInputOutputChains - If we are replacing an operation with a call we need
1388 /// to find the call that occurs before and the call that occurs after it to
1389 /// properly serialize the calls in the block.
1390 static SDOperand FindInputOutputChains(SDNode *OpNode, SDNode *&OutChain,
1392 SDNode *LatestAdjCallStackDown = Entry.Val;
1393 FindLatestAdjCallStackDown(OpNode, LatestAdjCallStackDown);
1394 //std::cerr << "Found node: "; LatestAdjCallStackDown->dump(); std::cerr <<"\n";
1396 SDNode *LatestAdjCallStackUp = FindAdjCallStackUp(LatestAdjCallStackDown);
1399 SDNode *EarliestAdjCallStackUp = 0;
1400 FindEarliestAdjCallStackUp(OpNode, EarliestAdjCallStackUp);
1402 if (EarliestAdjCallStackUp) {
1403 //std::cerr << "Found node: ";
1404 //EarliestAdjCallStackUp->dump(); std::cerr <<"\n";
1407 return SDOperand(LatestAdjCallStackUp, 0);
1412 // ExpandLibCall - Expand a node into a call to a libcall. If the result value
1413 // does not fit into a register, return the lo part and set the hi part to the
1414 // by-reg argument. If it does fit into a single register, return the result
1415 // and leave the Hi part unset.
1416 SDOperand SelectionDAGLegalize::ExpandLibCall(const char *Name, SDNode *Node,
1419 SDOperand InChain = FindInputOutputChains(Node, OutChain,
1420 DAG.getEntryNode());
1421 // TODO. Link in chains.
1423 TargetLowering::ArgListTy Args;
1424 for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
1425 MVT::ValueType ArgVT = Node->getOperand(i).getValueType();
1426 const Type *ArgTy = MVT::getTypeForValueType(ArgVT);
1427 Args.push_back(std::make_pair(Node->getOperand(i), ArgTy));
1429 SDOperand Callee = DAG.getExternalSymbol(Name, TLI.getPointerTy());
1431 // We don't care about token chains for libcalls. We just use the entry
1432 // node as our input and ignore the output chain. This allows us to place
1433 // calls wherever we need them to satisfy data dependences.
1434 const Type *RetTy = MVT::getTypeForValueType(Node->getValueType(0));
1435 SDOperand Result = TLI.LowerCallTo(InChain, RetTy, Callee,
1437 switch (getTypeAction(Result.getValueType())) {
1438 default: assert(0 && "Unknown thing");
1442 assert(0 && "Cannot promote this yet!");
1445 ExpandOp(Result, Lo, Hi);
1451 /// ExpandIntToFP - Expand a [US]INT_TO_FP operation, assuming that the
1452 /// destination type is legal.
1453 SDOperand SelectionDAGLegalize::
1454 ExpandIntToFP(bool isSigned, MVT::ValueType DestTy, SDOperand Source) {
1455 assert(getTypeAction(DestTy) == Legal && "Destination type is not legal!");
1456 assert(getTypeAction(Source.getValueType()) == Expand &&
1457 "This is not an expansion!");
1458 assert(Source.getValueType() == MVT::i64 && "Only handle expand from i64!");
1461 SDOperand InChain = FindInputOutputChains(Source.Val, OutChain,
1462 DAG.getEntryNode());
1464 const char *FnName = 0;
1466 if (DestTy == MVT::f32)
1467 FnName = "__floatdisf";
1469 assert(DestTy == MVT::f64 && "Unknown fp value type!");
1470 FnName = "__floatdidf";
1473 // If this is unsigned, and not supported, first perform the conversion to
1474 // signed, then adjust the result if the sign bit is set.
1475 SDOperand SignedConv = ExpandIntToFP(false, DestTy, Source);
1477 assert(0 && "Unsigned casts not supported yet!");
1479 SDOperand Callee = DAG.getExternalSymbol(FnName, TLI.getPointerTy());
1481 TargetLowering::ArgListTy Args;
1482 const Type *ArgTy = MVT::getTypeForValueType(Source.getValueType());
1483 Args.push_back(std::make_pair(Source, ArgTy));
1485 // We don't care about token chains for libcalls. We just use the entry
1486 // node as our input and ignore the output chain. This allows us to place
1487 // calls wherever we need them to satisfy data dependences.
1488 const Type *RetTy = MVT::getTypeForValueType(DestTy);
1489 return TLI.LowerCallTo(InChain, RetTy, Callee, Args, DAG).first;
1495 /// ExpandOp - Expand the specified SDOperand into its two component pieces
1496 /// Lo&Hi. Note that the Op MUST be an expanded type. As a result of this, the
1497 /// LegalizeNodes map is filled in for any results that are not expanded, the
1498 /// ExpandedNodes map is filled in for any results that are expanded, and the
1499 /// Lo/Hi values are returned.
1500 void SelectionDAGLegalize::ExpandOp(SDOperand Op, SDOperand &Lo, SDOperand &Hi){
1501 MVT::ValueType VT = Op.getValueType();
1502 MVT::ValueType NVT = TLI.getTypeToTransformTo(VT);
1503 SDNode *Node = Op.Val;
1504 assert(getTypeAction(VT) == Expand && "Not an expanded type!");
1505 assert(MVT::isInteger(VT) && "Cannot expand FP values!");
1506 assert(MVT::isInteger(NVT) && NVT < VT &&
1507 "Cannot expand to FP value or to larger int value!");
1509 // If there is more than one use of this, see if we already expanded it.
1510 // There is no use remembering values that only have a single use, as the map
1511 // entries will never be reused.
1512 if (!Node->hasOneUse()) {
1513 std::map<SDOperand, std::pair<SDOperand, SDOperand> >::iterator I
1514 = ExpandedNodes.find(Op);
1515 if (I != ExpandedNodes.end()) {
1516 Lo = I->second.first;
1517 Hi = I->second.second;
1522 // Expanding to multiple registers needs to perform an optimization step, and
1523 // is not careful to avoid operations the target does not support. Make sure
1524 // that all generated operations are legalized in the next iteration.
1525 NeedsAnotherIteration = true;
1527 switch (Node->getOpcode()) {
1529 std::cerr << "NODE: "; Node->dump(); std::cerr << "\n";
1530 assert(0 && "Do not know how to expand this operator!");
1532 case ISD::Constant: {
1533 uint64_t Cst = cast<ConstantSDNode>(Node)->getValue();
1534 Lo = DAG.getConstant(Cst, NVT);
1535 Hi = DAG.getConstant(Cst >> MVT::getSizeInBits(NVT), NVT);
1539 case ISD::CopyFromReg: {
1540 unsigned Reg = cast<RegSDNode>(Node)->getReg();
1541 // Aggregate register values are always in consequtive pairs.
1542 Lo = DAG.getCopyFromReg(Reg, NVT, Node->getOperand(0));
1543 Hi = DAG.getCopyFromReg(Reg+1, NVT, Lo.getValue(1));
1545 // Remember that we legalized the chain.
1546 AddLegalizedOperand(Op.getValue(1), Hi.getValue(1));
1548 assert(isTypeLegal(NVT) && "Cannot expand this multiple times yet!");
1553 SDOperand Ch = LegalizeOp(Node->getOperand(0)); // Legalize the chain.
1554 SDOperand Ptr = LegalizeOp(Node->getOperand(1)); // Legalize the pointer.
1555 Lo = DAG.getLoad(NVT, Ch, Ptr);
1557 // Increment the pointer to the other half.
1558 unsigned IncrementSize = MVT::getSizeInBits(Lo.getValueType())/8;
1559 Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
1560 getIntPtrConstant(IncrementSize));
1561 Hi = DAG.getLoad(NVT, Ch, Ptr);
1563 // Build a factor node to remember that this load is independent of the
1565 SDOperand TF = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo.getValue(1),
1568 // Remember that we legalized the chain.
1569 AddLegalizedOperand(Op.getValue(1), TF);
1570 if (!TLI.isLittleEndian())
1575 SDOperand Chain = LegalizeOp(Node->getOperand(0)); // Legalize the chain.
1576 SDOperand Callee = LegalizeOp(Node->getOperand(1)); // Legalize the callee.
1578 bool Changed = false;
1579 std::vector<SDOperand> Ops;
1580 for (unsigned i = 2, e = Node->getNumOperands(); i != e; ++i) {
1581 Ops.push_back(LegalizeOp(Node->getOperand(i)));
1582 Changed |= Ops.back() != Node->getOperand(i);
1585 assert(Node->getNumValues() == 2 && Op.ResNo == 0 &&
1586 "Can only expand a call once so far, not i64 -> i16!");
1588 std::vector<MVT::ValueType> RetTyVTs;
1589 RetTyVTs.reserve(3);
1590 RetTyVTs.push_back(NVT);
1591 RetTyVTs.push_back(NVT);
1592 RetTyVTs.push_back(MVT::Other);
1593 SDNode *NC = DAG.getCall(RetTyVTs, Chain, Callee, Ops);
1594 Lo = SDOperand(NC, 0);
1595 Hi = SDOperand(NC, 1);
1597 // Insert the new chain mapping.
1598 AddLegalizedOperand(Op.getValue(1), Hi.getValue(2));
1603 case ISD::XOR: { // Simple logical operators -> two trivial pieces.
1604 SDOperand LL, LH, RL, RH;
1605 ExpandOp(Node->getOperand(0), LL, LH);
1606 ExpandOp(Node->getOperand(1), RL, RH);
1607 Lo = DAG.getNode(Node->getOpcode(), NVT, LL, RL);
1608 Hi = DAG.getNode(Node->getOpcode(), NVT, LH, RH);
1612 SDOperand C, LL, LH, RL, RH;
1614 switch (getTypeAction(Node->getOperand(0).getValueType())) {
1615 case Expand: assert(0 && "It's impossible to expand bools");
1617 C = LegalizeOp(Node->getOperand(0)); // Legalize the condition.
1620 C = PromoteOp(Node->getOperand(0)); // Promote the condition.
1623 ExpandOp(Node->getOperand(1), LL, LH);
1624 ExpandOp(Node->getOperand(2), RL, RH);
1625 Lo = DAG.getNode(ISD::SELECT, NVT, C, LL, RL);
1626 Hi = DAG.getNode(ISD::SELECT, NVT, C, LH, RH);
1629 case ISD::SIGN_EXTEND: {
1630 // The low part is just a sign extension of the input (which degenerates to
1632 Lo = DAG.getNode(ISD::SIGN_EXTEND, NVT, LegalizeOp(Node->getOperand(0)));
1634 // The high part is obtained by SRA'ing all but one of the bits of the lo
1636 unsigned LoSize = MVT::getSizeInBits(Lo.getValueType());
1637 Hi = DAG.getNode(ISD::SRA, NVT, Lo, DAG.getConstant(LoSize-1,
1638 TLI.getShiftAmountTy()));
1641 case ISD::ZERO_EXTEND:
1642 // The low part is just a zero extension of the input (which degenerates to
1644 Lo = DAG.getNode(ISD::ZERO_EXTEND, NVT, LegalizeOp(Node->getOperand(0)));
1646 // The high part is just a zero.
1647 Hi = DAG.getConstant(0, NVT);
1650 // These operators cannot be expanded directly, emit them as calls to
1651 // library functions.
1652 case ISD::FP_TO_SINT:
1653 if (Node->getOperand(0).getValueType() == MVT::f32)
1654 Lo = ExpandLibCall("__fixsfdi", Node, Hi);
1656 Lo = ExpandLibCall("__fixdfdi", Node, Hi);
1658 case ISD::FP_TO_UINT:
1659 if (Node->getOperand(0).getValueType() == MVT::f32)
1660 Lo = ExpandLibCall("__fixunssfdi", Node, Hi);
1662 Lo = ExpandLibCall("__fixunsdfdi", Node, Hi);
1666 // If we can emit an efficient shift operation, do so now.
1667 if (ExpandShift(ISD::SHL, Node->getOperand(0), Node->getOperand(1), Lo, Hi))
1669 // Otherwise, emit a libcall.
1670 Lo = ExpandLibCall("__ashldi3", Node, Hi);
1674 // If we can emit an efficient shift operation, do so now.
1675 if (ExpandShift(ISD::SRA, Node->getOperand(0), Node->getOperand(1), Lo, Hi))
1677 // Otherwise, emit a libcall.
1678 Lo = ExpandLibCall("__ashrdi3", Node, Hi);
1681 // If we can emit an efficient shift operation, do so now.
1682 if (ExpandShift(ISD::SRL, Node->getOperand(0), Node->getOperand(1), Lo, Hi))
1684 // Otherwise, emit a libcall.
1685 Lo = ExpandLibCall("__lshrdi3", Node, Hi);
1689 ExpandAddSub(true, Node->getOperand(0), Node->getOperand(1), Lo, Hi);
1692 ExpandAddSub(false, Node->getOperand(0), Node->getOperand(1), Lo, Hi);
1694 case ISD::MUL: Lo = ExpandLibCall("__muldi3" , Node, Hi); break;
1695 case ISD::SDIV: Lo = ExpandLibCall("__divdi3" , Node, Hi); break;
1696 case ISD::UDIV: Lo = ExpandLibCall("__udivdi3", Node, Hi); break;
1697 case ISD::SREM: Lo = ExpandLibCall("__moddi3" , Node, Hi); break;
1698 case ISD::UREM: Lo = ExpandLibCall("__umoddi3", Node, Hi); break;
1701 // Remember in a map if the values will be reused later.
1702 if (!Node->hasOneUse()) {
1703 bool isNew = ExpandedNodes.insert(std::make_pair(Op,
1704 std::make_pair(Lo, Hi))).second;
1705 assert(isNew && "Value already expanded?!?");
1710 // SelectionDAG::Legalize - This is the entry point for the file.
1712 void SelectionDAG::Legalize() {
1713 /// run - This is the main entry point to this class.
1715 SelectionDAGLegalize(*this).Run();