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 case ISD::ImplicitDef:
211 Tmp1 = LegalizeOp(Node->getOperand(0));
212 if (Tmp1 != Node->getOperand(0))
213 Result = DAG.getImplicitDef(Tmp1, cast<RegSDNode>(Node)->getReg());
216 // We know we don't need to expand constants here, constants only have one
217 // value and we check that it is fine above.
219 // FIXME: Maybe we should handle things like targets that don't support full
220 // 32-bit immediates?
222 case ISD::ConstantFP: {
223 // Spill FP immediates to the constant pool if the target cannot directly
224 // codegen them. Targets often have some immediate values that can be
225 // efficiently generated into an FP register without a load. We explicitly
226 // leave these constants as ConstantFP nodes for the target to deal with.
228 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Node);
230 // Check to see if this FP immediate is already legal.
231 bool isLegal = false;
232 for (TargetLowering::legal_fpimm_iterator I = TLI.legal_fpimm_begin(),
233 E = TLI.legal_fpimm_end(); I != E; ++I)
234 if (CFP->isExactlyValue(*I)) {
240 // Otherwise we need to spill the constant to memory.
241 MachineConstantPool *CP = DAG.getMachineFunction().getConstantPool();
245 // If a FP immediate is precise when represented as a float, we put it
246 // into the constant pool as a float, even if it's is statically typed
248 MVT::ValueType VT = CFP->getValueType(0);
249 bool isDouble = VT == MVT::f64;
250 ConstantFP *LLVMC = ConstantFP::get(isDouble ? Type::DoubleTy :
251 Type::FloatTy, CFP->getValue());
252 if (isDouble && CFP->isExactlyValue((float)CFP->getValue())) {
253 LLVMC = cast<ConstantFP>(ConstantExpr::getCast(LLVMC, Type::FloatTy));
258 SDOperand CPIdx = DAG.getConstantPool(CP->getConstantPoolIndex(LLVMC),
261 Result = DAG.getNode(ISD::EXTLOAD, MVT::f64, DAG.getEntryNode(), CPIdx,
264 Result = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx);
269 case ISD::TokenFactor: {
270 std::vector<SDOperand> Ops;
271 bool Changed = false;
272 for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
273 SDOperand Op = Node->getOperand(i);
274 // Fold single-use TokenFactor nodes into this token factor as we go.
275 if (Op.getOpcode() == ISD::TokenFactor && Op.hasOneUse()) {
277 for (unsigned j = 0, e = Op.getNumOperands(); j != e; ++j)
278 Ops.push_back(LegalizeOp(Op.getOperand(j)));
280 Ops.push_back(LegalizeOp(Op)); // Legalize the operands
281 Changed |= Ops[i] != Op;
285 Result = DAG.getNode(ISD::TokenFactor, MVT::Other, Ops);
289 case ISD::ADJCALLSTACKDOWN:
290 case ISD::ADJCALLSTACKUP:
291 Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the chain.
292 // There is no need to legalize the size argument (Operand #1)
293 if (Tmp1 != Node->getOperand(0))
294 Result = DAG.getNode(Node->getOpcode(), MVT::Other, Tmp1,
295 Node->getOperand(1));
297 case ISD::DYNAMIC_STACKALLOC:
298 Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the chain.
299 Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the size.
300 Tmp3 = LegalizeOp(Node->getOperand(2)); // Legalize the alignment.
301 if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
302 Tmp3 != Node->getOperand(2))
303 Result = DAG.getNode(ISD::DYNAMIC_STACKALLOC, Node->getValueType(0),
306 Result = Op.getValue(0);
308 // Since this op produces two values, make sure to remember that we
309 // legalized both of them.
310 AddLegalizedOperand(SDOperand(Node, 0), Result);
311 AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
312 return Result.getValue(Op.ResNo);
315 Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the chain.
316 Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the callee.
318 bool Changed = false;
319 std::vector<SDOperand> Ops;
320 for (unsigned i = 2, e = Node->getNumOperands(); i != e; ++i) {
321 Ops.push_back(LegalizeOp(Node->getOperand(i)));
322 Changed |= Ops.back() != Node->getOperand(i);
325 if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) || Changed) {
326 std::vector<MVT::ValueType> RetTyVTs;
327 RetTyVTs.reserve(Node->getNumValues());
328 for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
329 RetTyVTs.push_back(Node->getValueType(i));
330 Result = SDOperand(DAG.getCall(RetTyVTs, Tmp1, Tmp2, Ops), 0);
332 Result = Result.getValue(0);
334 // Since calls produce multiple values, make sure to remember that we
335 // legalized all of them.
336 for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
337 AddLegalizedOperand(SDOperand(Node, i), Result.getValue(i));
338 return Result.getValue(Op.ResNo);
341 Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the chain.
342 if (Tmp1 != Node->getOperand(0))
343 Result = DAG.getNode(ISD::BR, MVT::Other, Tmp1, Node->getOperand(1));
347 Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the chain.
349 switch (getTypeAction(Node->getOperand(1).getValueType())) {
350 case Expand: assert(0 && "It's impossible to expand bools");
352 Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the condition.
355 Tmp2 = PromoteOp(Node->getOperand(1)); // Promote the condition.
358 // Basic block destination (Op#2) is always legal.
359 if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
360 Result = DAG.getNode(ISD::BRCOND, MVT::Other, Tmp1, Tmp2,
361 Node->getOperand(2));
365 Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the chain.
366 Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the pointer.
367 if (Tmp1 != Node->getOperand(0) ||
368 Tmp2 != Node->getOperand(1))
369 Result = DAG.getLoad(Node->getValueType(0), Tmp1, Tmp2);
371 Result = SDOperand(Node, 0);
373 // Since loads produce two values, make sure to remember that we legalized
375 AddLegalizedOperand(SDOperand(Node, 0), Result);
376 AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
377 return Result.getValue(Op.ResNo);
382 Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the chain.
383 Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the pointer.
384 if (Tmp1 != Node->getOperand(0) ||
385 Tmp2 != Node->getOperand(1))
386 Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1, Tmp2,
387 cast<MVTSDNode>(Node)->getExtraValueType());
389 Result = SDOperand(Node, 0);
391 // Since loads produce two values, make sure to remember that we legalized
393 AddLegalizedOperand(SDOperand(Node, 0), Result);
394 AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
395 return Result.getValue(Op.ResNo);
397 case ISD::EXTRACT_ELEMENT:
398 // Get both the low and high parts.
399 ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
400 if (cast<ConstantSDNode>(Node->getOperand(1))->getValue())
401 Result = Tmp2; // 1 -> Hi
403 Result = Tmp1; // 0 -> Lo
407 Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the chain.
409 switch (getTypeAction(Node->getOperand(1).getValueType())) {
411 // Legalize the incoming value (must be legal).
412 Tmp2 = LegalizeOp(Node->getOperand(1));
413 if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
414 Result = DAG.getCopyToReg(Tmp1, Tmp2, cast<RegSDNode>(Node)->getReg());
417 Tmp2 = PromoteOp(Node->getOperand(1));
418 Result = DAG.getCopyToReg(Tmp1, Tmp2, cast<RegSDNode>(Node)->getReg());
422 ExpandOp(Node->getOperand(1), Lo, Hi);
423 unsigned Reg = cast<RegSDNode>(Node)->getReg();
424 Lo = DAG.getCopyToReg(Tmp1, Lo, Reg);
425 Hi = DAG.getCopyToReg(Tmp1, Hi, Reg+1);
426 // Note that the copytoreg nodes are independent of each other.
427 Result = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo, Hi);
428 assert(isTypeLegal(Result.getValueType()) &&
429 "Cannot expand multiple times yet (i64 -> i16)");
435 Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the chain.
436 switch (Node->getNumOperands()) {
438 switch (getTypeAction(Node->getOperand(1).getValueType())) {
440 Tmp2 = LegalizeOp(Node->getOperand(1));
441 if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
442 Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Tmp2);
446 ExpandOp(Node->getOperand(1), Lo, Hi);
447 Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Lo, Hi);
451 Tmp2 = PromoteOp(Node->getOperand(1));
452 Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Tmp2);
457 if (Tmp1 != Node->getOperand(0))
458 Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1);
460 default: { // ret <values>
461 std::vector<SDOperand> NewValues;
462 NewValues.push_back(Tmp1);
463 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
464 switch (getTypeAction(Node->getOperand(i).getValueType())) {
466 NewValues.push_back(LegalizeOp(Node->getOperand(i)));
470 ExpandOp(Node->getOperand(i), Lo, Hi);
471 NewValues.push_back(Lo);
472 NewValues.push_back(Hi);
476 assert(0 && "Can't promote multiple return value yet!");
478 Result = DAG.getNode(ISD::RET, MVT::Other, NewValues);
484 Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the chain.
485 Tmp2 = LegalizeOp(Node->getOperand(2)); // Legalize the pointer.
487 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
488 if (ConstantFPSDNode *CFP =dyn_cast<ConstantFPSDNode>(Node->getOperand(1))){
489 if (CFP->getValueType(0) == MVT::f32) {
494 V.F = CFP->getValue();
495 Result = DAG.getNode(ISD::STORE, MVT::Other, Tmp1,
496 DAG.getConstant(V.I, MVT::i32), Tmp2);
498 assert(CFP->getValueType(0) == MVT::f64 && "Unknown FP type!");
503 V.F = CFP->getValue();
504 Result = DAG.getNode(ISD::STORE, MVT::Other, Tmp1,
505 DAG.getConstant(V.I, MVT::i64), Tmp2);
511 switch (getTypeAction(Node->getOperand(1).getValueType())) {
513 SDOperand Val = LegalizeOp(Node->getOperand(1));
514 if (Val != Node->getOperand(1) || Tmp1 != Node->getOperand(0) ||
515 Tmp2 != Node->getOperand(2))
516 Result = DAG.getNode(ISD::STORE, MVT::Other, Tmp1, Val, Tmp2);
520 // Truncate the value and store the result.
521 Tmp3 = PromoteOp(Node->getOperand(1));
522 Result = DAG.getNode(ISD::TRUNCSTORE, MVT::Other, Tmp1, Tmp3, Tmp2,
523 Node->getOperand(1).getValueType());
528 ExpandOp(Node->getOperand(1), Lo, Hi);
530 if (!TLI.isLittleEndian())
533 Lo = DAG.getNode(ISD::STORE, MVT::Other, Tmp1, Lo, Tmp2);
535 unsigned IncrementSize = MVT::getSizeInBits(Hi.getValueType())/8;
536 Tmp2 = DAG.getNode(ISD::ADD, Tmp2.getValueType(), Tmp2,
537 getIntPtrConstant(IncrementSize));
538 assert(isTypeLegal(Tmp2.getValueType()) &&
539 "Pointers must be legal!");
540 Hi = DAG.getNode(ISD::STORE, MVT::Other, Tmp1, Hi, Tmp2);
541 Result = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo, Hi);
545 case ISD::TRUNCSTORE:
546 Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the chain.
547 Tmp3 = LegalizeOp(Node->getOperand(2)); // Legalize the pointer.
549 switch (getTypeAction(Node->getOperand(1).getValueType())) {
551 Tmp2 = LegalizeOp(Node->getOperand(1));
552 if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
553 Tmp3 != Node->getOperand(2))
554 Result = DAG.getNode(ISD::TRUNCSTORE, MVT::Other, Tmp1, Tmp2, Tmp3,
555 cast<MVTSDNode>(Node)->getExtraValueType());
559 assert(0 && "Cannot handle illegal TRUNCSTORE yet!");
563 switch (getTypeAction(Node->getOperand(0).getValueType())) {
564 case Expand: assert(0 && "It's impossible to expand bools");
566 Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the condition.
569 Tmp1 = PromoteOp(Node->getOperand(0)); // Promote the condition.
572 Tmp2 = LegalizeOp(Node->getOperand(1)); // TrueVal
573 Tmp3 = LegalizeOp(Node->getOperand(2)); // FalseVal
575 switch (TLI.getOperationAction(Node->getOpcode(), Tmp2.getValueType())) {
576 default: assert(0 && "This action is not supported yet!");
577 case TargetLowering::Legal:
578 if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
579 Tmp3 != Node->getOperand(2))
580 Result = DAG.getNode(ISD::SELECT, Node->getValueType(0),
583 case TargetLowering::Promote: {
585 TLI.getTypeToPromoteTo(ISD::SELECT, Tmp2.getValueType());
586 unsigned ExtOp, TruncOp;
587 if (MVT::isInteger(Tmp2.getValueType())) {
588 ExtOp = ISD::ZERO_EXTEND;
589 TruncOp = ISD::TRUNCATE;
591 ExtOp = ISD::FP_EXTEND;
592 TruncOp = ISD::FP_ROUND;
594 // Promote each of the values to the new type.
595 Tmp2 = DAG.getNode(ExtOp, NVT, Tmp2);
596 Tmp3 = DAG.getNode(ExtOp, NVT, Tmp3);
597 // Perform the larger operation, then round down.
598 Result = DAG.getNode(ISD::SELECT, NVT, Tmp1, Tmp2,Tmp3);
599 Result = DAG.getNode(TruncOp, Node->getValueType(0), Result);
605 switch (getTypeAction(Node->getOperand(0).getValueType())) {
607 Tmp1 = LegalizeOp(Node->getOperand(0)); // LHS
608 Tmp2 = LegalizeOp(Node->getOperand(1)); // RHS
609 if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
610 Result = DAG.getSetCC(cast<SetCCSDNode>(Node)->getCondition(),
611 Node->getValueType(0), Tmp1, Tmp2);
614 Tmp1 = PromoteOp(Node->getOperand(0)); // LHS
615 Tmp2 = PromoteOp(Node->getOperand(1)); // RHS
617 // If this is an FP compare, the operands have already been extended.
618 if (MVT::isInteger(Node->getOperand(0).getValueType())) {
619 MVT::ValueType VT = Node->getOperand(0).getValueType();
620 MVT::ValueType NVT = TLI.getTypeToTransformTo(VT);
622 // Otherwise, we have to insert explicit sign or zero extends. Note
623 // that we could insert sign extends for ALL conditions, but zero extend
624 // is cheaper on many machines (an AND instead of two shifts), so prefer
626 switch (cast<SetCCSDNode>(Node)->getCondition()) {
627 default: assert(0 && "Unknown integer comparison!");
634 // ALL of these operations will work if we either sign or zero extend
635 // the operands (including the unsigned comparisons!). Zero extend is
636 // usually a simpler/cheaper operation, so prefer it.
637 Tmp1 = DAG.getNode(ISD::ZERO_EXTEND_INREG, NVT, Tmp1, VT);
638 Tmp2 = DAG.getNode(ISD::ZERO_EXTEND_INREG, NVT, Tmp2, VT);
644 Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1, VT);
645 Tmp2 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp2, VT);
650 Result = DAG.getSetCC(cast<SetCCSDNode>(Node)->getCondition(),
651 Node->getValueType(0), Tmp1, Tmp2);
654 SDOperand LHSLo, LHSHi, RHSLo, RHSHi;
655 ExpandOp(Node->getOperand(0), LHSLo, LHSHi);
656 ExpandOp(Node->getOperand(1), RHSLo, RHSHi);
657 switch (cast<SetCCSDNode>(Node)->getCondition()) {
660 Tmp1 = DAG.getNode(ISD::XOR, LHSLo.getValueType(), LHSLo, RHSLo);
661 Tmp2 = DAG.getNode(ISD::XOR, LHSLo.getValueType(), LHSHi, RHSHi);
662 Tmp1 = DAG.getNode(ISD::OR, Tmp1.getValueType(), Tmp1, Tmp2);
663 Result = DAG.getSetCC(cast<SetCCSDNode>(Node)->getCondition(),
664 Node->getValueType(0), Tmp1,
665 DAG.getConstant(0, Tmp1.getValueType()));
668 // FIXME: This generated code sucks.
670 switch (cast<SetCCSDNode>(Node)->getCondition()) {
671 default: assert(0 && "Unknown integer setcc!");
673 case ISD::SETULT: LowCC = ISD::SETULT; break;
675 case ISD::SETUGT: LowCC = ISD::SETUGT; break;
677 case ISD::SETULE: LowCC = ISD::SETULE; break;
679 case ISD::SETUGE: LowCC = ISD::SETUGE; break;
682 // Tmp1 = lo(op1) < lo(op2) // Always unsigned comparison
683 // Tmp2 = hi(op1) < hi(op2) // Signedness depends on operands
684 // dest = hi(op1) == hi(op2) ? Tmp1 : Tmp2;
686 // NOTE: on targets without efficient SELECT of bools, we can always use
687 // this identity: (B1 ? B2 : B3) --> (B1 & B2)|(!B1&B3)
688 Tmp1 = DAG.getSetCC(LowCC, Node->getValueType(0), LHSLo, RHSLo);
689 Tmp2 = DAG.getSetCC(cast<SetCCSDNode>(Node)->getCondition(),
690 Node->getValueType(0), LHSHi, RHSHi);
691 Result = DAG.getSetCC(ISD::SETEQ, Node->getValueType(0), LHSHi, RHSHi);
692 Result = DAG.getNode(ISD::SELECT, Tmp1.getValueType(),
702 Tmp1 = LegalizeOp(Node->getOperand(0));
703 Tmp2 = LegalizeOp(Node->getOperand(1));
704 Tmp3 = LegalizeOp(Node->getOperand(2));
705 SDOperand Tmp4 = LegalizeOp(Node->getOperand(3));
706 SDOperand Tmp5 = LegalizeOp(Node->getOperand(4));
708 switch (TLI.getOperationAction(Node->getOpcode(), MVT::Other)) {
709 default: assert(0 && "This action not implemented for this operation!");
710 case TargetLowering::Legal:
711 if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
712 Tmp3 != Node->getOperand(2) || Tmp4 != Node->getOperand(3) ||
713 Tmp5 != Node->getOperand(4)) {
714 std::vector<SDOperand> Ops;
715 Ops.push_back(Tmp1); Ops.push_back(Tmp2); Ops.push_back(Tmp3);
716 Ops.push_back(Tmp4); Ops.push_back(Tmp5);
717 Result = DAG.getNode(Node->getOpcode(), MVT::Other, Ops);
720 case TargetLowering::Expand: {
721 // Otherwise, the target does not support this operation. Lower the
722 // operation to an explicit libcall as appropriate.
723 MVT::ValueType IntPtr = TLI.getPointerTy();
724 const Type *IntPtrTy = TLI.getTargetData().getIntPtrType();
725 std::vector<std::pair<SDOperand, const Type*> > Args;
727 const char *FnName = 0;
728 if (Node->getOpcode() == ISD::MEMSET) {
729 Args.push_back(std::make_pair(Tmp2, IntPtrTy));
730 // Extend the ubyte argument to be an int value for the call.
731 Tmp3 = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Tmp3);
732 Args.push_back(std::make_pair(Tmp3, Type::IntTy));
733 Args.push_back(std::make_pair(Tmp4, IntPtrTy));
736 } else if (Node->getOpcode() == ISD::MEMCPY ||
737 Node->getOpcode() == ISD::MEMMOVE) {
738 Args.push_back(std::make_pair(Tmp2, IntPtrTy));
739 Args.push_back(std::make_pair(Tmp3, IntPtrTy));
740 Args.push_back(std::make_pair(Tmp4, IntPtrTy));
741 FnName = Node->getOpcode() == ISD::MEMMOVE ? "memmove" : "memcpy";
743 assert(0 && "Unknown op!");
745 std::pair<SDOperand,SDOperand> CallResult =
746 TLI.LowerCallTo(Tmp1, Type::VoidTy,
747 DAG.getExternalSymbol(FnName, IntPtr), Args, DAG);
748 Result = LegalizeOp(CallResult.second);
751 case TargetLowering::Custom:
752 std::vector<SDOperand> Ops;
753 Ops.push_back(Tmp1); Ops.push_back(Tmp2); Ops.push_back(Tmp3);
754 Ops.push_back(Tmp4); Ops.push_back(Tmp5);
755 Result = DAG.getNode(Node->getOpcode(), MVT::Other, Ops);
756 Result = TLI.LowerOperation(Result);
757 Result = LegalizeOp(Result);
763 case ISD::SUB_PARTS: {
764 std::vector<SDOperand> Ops;
765 bool Changed = false;
766 for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
767 Ops.push_back(LegalizeOp(Node->getOperand(i)));
768 Changed |= Ops.back() != Node->getOperand(i);
771 Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Ops);
787 Tmp1 = LegalizeOp(Node->getOperand(0)); // LHS
788 Tmp2 = LegalizeOp(Node->getOperand(1)); // RHS
789 if (Tmp1 != Node->getOperand(0) ||
790 Tmp2 != Node->getOperand(1))
791 Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1,Tmp2);
793 case ISD::ZERO_EXTEND:
794 case ISD::SIGN_EXTEND:
798 case ISD::FP_TO_SINT:
799 case ISD::FP_TO_UINT:
800 case ISD::SINT_TO_FP:
801 case ISD::UINT_TO_FP:
802 switch (getTypeAction(Node->getOperand(0).getValueType())) {
804 Tmp1 = LegalizeOp(Node->getOperand(0));
805 if (Tmp1 != Node->getOperand(0))
806 Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1);
809 if (Node->getOpcode() == ISD::SINT_TO_FP ||
810 Node->getOpcode() == ISD::UINT_TO_FP) {
811 Result = ExpandIntToFP(Node->getOpcode() == ISD::SINT_TO_FP,
812 Node->getValueType(0), Node->getOperand(0));
813 Result = LegalizeOp(Result);
816 // In the expand case, we must be dealing with a truncate, because
817 // otherwise the result would be larger than the source.
818 assert(Node->getOpcode() == ISD::TRUNCATE &&
819 "Shouldn't need to expand other operators here!");
820 ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
822 // Since the result is legal, we should just be able to truncate the low
823 // part of the source.
824 Result = DAG.getNode(ISD::TRUNCATE, Node->getValueType(0), Tmp1);
828 switch (Node->getOpcode()) {
829 case ISD::ZERO_EXTEND:
830 Result = PromoteOp(Node->getOperand(0));
831 // NOTE: Any extend would work here...
832 Result = DAG.getNode(ISD::ZERO_EXTEND, Op.getValueType(), Result);
833 Result = DAG.getNode(ISD::ZERO_EXTEND_INREG, Op.getValueType(),
834 Result, Node->getOperand(0).getValueType());
836 case ISD::SIGN_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::SIGN_EXTEND_INREG, Result.getValueType(),
841 Result, Node->getOperand(0).getValueType());
844 Result = PromoteOp(Node->getOperand(0));
845 Result = DAG.getNode(ISD::TRUNCATE, Op.getValueType(), Result);
848 Result = PromoteOp(Node->getOperand(0));
849 if (Result.getValueType() != Op.getValueType())
850 // Dynamically dead while we have only 2 FP types.
851 Result = DAG.getNode(ISD::FP_EXTEND, Op.getValueType(), Result);
854 case ISD::FP_TO_SINT:
855 case ISD::FP_TO_UINT:
856 Result = PromoteOp(Node->getOperand(0));
857 Result = DAG.getNode(Node->getOpcode(), Op.getValueType(), Result);
859 case ISD::SINT_TO_FP:
860 Result = PromoteOp(Node->getOperand(0));
861 Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
862 Result, Node->getOperand(0).getValueType());
863 Result = DAG.getNode(ISD::SINT_TO_FP, Op.getValueType(), Result);
865 case ISD::UINT_TO_FP:
866 Result = PromoteOp(Node->getOperand(0));
867 Result = DAG.getNode(ISD::ZERO_EXTEND_INREG, Result.getValueType(),
868 Result, Node->getOperand(0).getValueType());
869 Result = DAG.getNode(ISD::UINT_TO_FP, Op.getValueType(), Result);
874 case ISD::FP_ROUND_INREG:
875 case ISD::SIGN_EXTEND_INREG:
876 case ISD::ZERO_EXTEND_INREG: {
877 Tmp1 = LegalizeOp(Node->getOperand(0));
878 MVT::ValueType ExtraVT = cast<MVTSDNode>(Node)->getExtraValueType();
880 // If this operation is not supported, convert it to a shl/shr or load/store
882 switch (TLI.getOperationAction(Node->getOpcode(), ExtraVT)) {
883 default: assert(0 && "This action not supported for this op yet!");
884 case TargetLowering::Legal:
885 if (Tmp1 != Node->getOperand(0))
886 Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1,
889 case TargetLowering::Expand:
890 // If this is an integer extend and shifts are supported, do that.
891 if (Node->getOpcode() == ISD::ZERO_EXTEND_INREG) {
892 // NOTE: we could fall back on load/store here too for targets without
893 // AND. However, it is doubtful that any exist.
894 // AND out the appropriate bits.
896 DAG.getConstant((1ULL << MVT::getSizeInBits(ExtraVT))-1,
897 Node->getValueType(0));
898 Result = DAG.getNode(ISD::AND, Node->getValueType(0),
899 Node->getOperand(0), Mask);
900 } else if (Node->getOpcode() == ISD::SIGN_EXTEND_INREG) {
901 // NOTE: we could fall back on load/store here too for targets without
902 // SAR. However, it is doubtful that any exist.
903 unsigned BitsDiff = MVT::getSizeInBits(Node->getValueType(0)) -
904 MVT::getSizeInBits(ExtraVT);
905 SDOperand ShiftCst = DAG.getConstant(BitsDiff, TLI.getShiftAmountTy());
906 Result = DAG.getNode(ISD::SHL, Node->getValueType(0),
907 Node->getOperand(0), ShiftCst);
908 Result = DAG.getNode(ISD::SRA, Node->getValueType(0),
910 } else if (Node->getOpcode() == ISD::FP_ROUND_INREG) {
911 // The only way we can lower this is to turn it into a STORETRUNC,
912 // EXTLOAD pair, targetting a temporary location (a stack slot).
914 // NOTE: there is a choice here between constantly creating new stack
915 // slots and always reusing the same one. We currently always create
916 // new ones, as reuse may inhibit scheduling.
917 const Type *Ty = MVT::getTypeForValueType(ExtraVT);
918 unsigned TySize = (unsigned)TLI.getTargetData().getTypeSize(Ty);
919 unsigned Align = TLI.getTargetData().getTypeAlignment(Ty);
920 MachineFunction &MF = DAG.getMachineFunction();
922 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
923 SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
924 Result = DAG.getNode(ISD::TRUNCSTORE, MVT::Other, DAG.getEntryNode(),
925 Node->getOperand(0), StackSlot, ExtraVT);
926 Result = DAG.getNode(ISD::EXTLOAD, Node->getValueType(0),
927 Result, StackSlot, ExtraVT);
929 assert(0 && "Unknown op");
931 Result = LegalizeOp(Result);
938 if (!Op.Val->hasOneUse())
939 AddLegalizedOperand(Op, Result);
944 /// PromoteOp - Given an operation that produces a value in an invalid type,
945 /// promote it to compute the value into a larger type. The produced value will
946 /// have the correct bits for the low portion of the register, but no guarantee
947 /// is made about the top bits: it may be zero, sign-extended, or garbage.
948 SDOperand SelectionDAGLegalize::PromoteOp(SDOperand Op) {
949 MVT::ValueType VT = Op.getValueType();
950 MVT::ValueType NVT = TLI.getTypeToTransformTo(VT);
951 assert(getTypeAction(VT) == Promote &&
952 "Caller should expand or legalize operands that are not promotable!");
953 assert(NVT > VT && MVT::isInteger(NVT) == MVT::isInteger(VT) &&
954 "Cannot promote to smaller type!");
956 std::map<SDOperand, SDOperand>::iterator I = PromotedNodes.find(Op);
957 if (I != PromotedNodes.end()) return I->second;
959 SDOperand Tmp1, Tmp2, Tmp3;
962 SDNode *Node = Op.Val;
964 // Promotion needs an optimization step to clean up after it, and is not
965 // careful to avoid operations the target does not support. Make sure that
966 // all generated operations are legalized in the next iteration.
967 NeedsAnotherIteration = true;
969 switch (Node->getOpcode()) {
971 std::cerr << "NODE: "; Node->dump(); std::cerr << "\n";
972 assert(0 && "Do not know how to promote this operator!");
975 Result = DAG.getNode(ISD::ZERO_EXTEND, NVT, Op);
976 assert(isa<ConstantSDNode>(Result) && "Didn't constant fold zext?");
978 case ISD::ConstantFP:
979 Result = DAG.getNode(ISD::FP_EXTEND, NVT, Op);
980 assert(isa<ConstantFPSDNode>(Result) && "Didn't constant fold fp_extend?");
982 case ISD::CopyFromReg:
983 Result = DAG.getCopyFromReg(cast<RegSDNode>(Node)->getReg(), NVT,
984 Node->getOperand(0));
985 // Remember that we legalized the chain.
986 AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
990 assert(getTypeAction(TLI.getSetCCResultTy()) == Legal &&
991 "SetCC type is not legal??");
992 Result = DAG.getSetCC(cast<SetCCSDNode>(Node)->getCondition(),
993 TLI.getSetCCResultTy(), Node->getOperand(0),
994 Node->getOperand(1));
995 Result = LegalizeOp(Result);
999 switch (getTypeAction(Node->getOperand(0).getValueType())) {
1001 Result = LegalizeOp(Node->getOperand(0));
1002 assert(Result.getValueType() >= NVT &&
1003 "This truncation doesn't make sense!");
1004 if (Result.getValueType() > NVT) // Truncate to NVT instead of VT
1005 Result = DAG.getNode(ISD::TRUNCATE, NVT, Result);
1008 assert(0 && "Cannot handle expand yet");
1010 assert(0 && "Cannot handle promote-promote yet");
1013 case ISD::SIGN_EXTEND:
1014 case ISD::ZERO_EXTEND:
1015 switch (getTypeAction(Node->getOperand(0).getValueType())) {
1016 case Expand: assert(0 && "BUG: Smaller reg should have been promoted!");
1018 // Input is legal? Just do extend all the way to the larger type.
1019 Result = LegalizeOp(Node->getOperand(0));
1020 Result = DAG.getNode(Node->getOpcode(), NVT, Result);
1023 // Promote the reg if it's smaller.
1024 Result = PromoteOp(Node->getOperand(0));
1025 // The high bits are not guaranteed to be anything. Insert an extend.
1026 if (Node->getOpcode() == ISD::SIGN_EXTEND)
1027 Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Result, VT);
1029 Result = DAG.getNode(ISD::ZERO_EXTEND_INREG, NVT, Result, VT);
1034 case ISD::FP_EXTEND:
1035 assert(0 && "Case not implemented. Dynamically dead with 2 FP types!");
1037 switch (getTypeAction(Node->getOperand(0).getValueType())) {
1038 case Expand: assert(0 && "BUG: Cannot expand FP regs!");
1039 case Promote: assert(0 && "Unreachable with 2 FP types!");
1041 // Input is legal? Do an FP_ROUND_INREG.
1042 Result = LegalizeOp(Node->getOperand(0));
1043 Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result, VT);
1048 case ISD::SINT_TO_FP:
1049 case ISD::UINT_TO_FP:
1050 switch (getTypeAction(Node->getOperand(0).getValueType())) {
1052 Result = LegalizeOp(Node->getOperand(0));
1053 // No extra round required here.
1054 Result = DAG.getNode(Node->getOpcode(), NVT, Result);
1058 Result = PromoteOp(Node->getOperand(0));
1059 if (Node->getOpcode() == ISD::SINT_TO_FP)
1060 Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
1061 Result, Node->getOperand(0).getValueType());
1063 Result = DAG.getNode(ISD::ZERO_EXTEND_INREG, Result.getValueType(),
1064 Result, Node->getOperand(0).getValueType());
1065 // No extra round required here.
1066 Result = DAG.getNode(Node->getOpcode(), NVT, Result);
1069 Result = ExpandIntToFP(Node->getOpcode() == ISD::SINT_TO_FP, NVT,
1070 Node->getOperand(0));
1071 Result = LegalizeOp(Result);
1073 // Round if we cannot tolerate excess precision.
1074 if (NoExcessFPPrecision)
1075 Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result, VT);
1080 case ISD::FP_TO_SINT:
1081 case ISD::FP_TO_UINT:
1082 switch (getTypeAction(Node->getOperand(0).getValueType())) {
1084 Tmp1 = LegalizeOp(Node->getOperand(0));
1087 // The input result is prerounded, so we don't have to do anything
1089 Tmp1 = PromoteOp(Node->getOperand(0));
1092 assert(0 && "not implemented");
1094 Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
1103 // The input may have strange things in the top bits of the registers, but
1104 // these operations don't care. They may have wierd bits going out, but
1105 // that too is okay if they are integer operations.
1106 Tmp1 = PromoteOp(Node->getOperand(0));
1107 Tmp2 = PromoteOp(Node->getOperand(1));
1108 assert(Tmp1.getValueType() == NVT && Tmp2.getValueType() == NVT);
1109 Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
1111 // However, if this is a floating point operation, they will give excess
1112 // precision that we may not be able to tolerate. If we DO allow excess
1113 // precision, just leave it, otherwise excise it.
1114 // FIXME: Why would we need to round FP ops more than integer ones?
1115 // Is Round(Add(Add(A,B),C)) != Round(Add(Round(Add(A,B)), C))
1116 if (MVT::isFloatingPoint(NVT) && NoExcessFPPrecision)
1117 Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result, VT);
1122 // These operators require that their input be sign extended.
1123 Tmp1 = PromoteOp(Node->getOperand(0));
1124 Tmp2 = PromoteOp(Node->getOperand(1));
1125 if (MVT::isInteger(NVT)) {
1126 Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1, VT);
1127 Tmp2 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp2, VT);
1129 Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
1131 // Perform FP_ROUND: this is probably overly pessimistic.
1132 if (MVT::isFloatingPoint(NVT) && NoExcessFPPrecision)
1133 Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result, VT);
1138 // These operators require that their input be zero extended.
1139 Tmp1 = PromoteOp(Node->getOperand(0));
1140 Tmp2 = PromoteOp(Node->getOperand(1));
1141 assert(MVT::isInteger(NVT) && "Operators don't apply to FP!");
1142 Tmp1 = DAG.getNode(ISD::ZERO_EXTEND_INREG, NVT, Tmp1, VT);
1143 Tmp2 = DAG.getNode(ISD::ZERO_EXTEND_INREG, NVT, Tmp2, VT);
1144 Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
1148 Tmp1 = PromoteOp(Node->getOperand(0));
1149 Tmp2 = LegalizeOp(Node->getOperand(1));
1150 Result = DAG.getNode(ISD::SHL, NVT, Tmp1, Tmp2);
1153 // The input value must be properly sign extended.
1154 Tmp1 = PromoteOp(Node->getOperand(0));
1155 Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1, VT);
1156 Tmp2 = LegalizeOp(Node->getOperand(1));
1157 Result = DAG.getNode(ISD::SRA, NVT, Tmp1, Tmp2);
1160 // The input value must be properly zero extended.
1161 Tmp1 = PromoteOp(Node->getOperand(0));
1162 Tmp1 = DAG.getNode(ISD::ZERO_EXTEND_INREG, NVT, Tmp1, VT);
1163 Tmp2 = LegalizeOp(Node->getOperand(1));
1164 Result = DAG.getNode(ISD::SRL, NVT, Tmp1, Tmp2);
1167 Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the chain.
1168 Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the pointer.
1169 Result = DAG.getNode(ISD::EXTLOAD, NVT, Tmp1, Tmp2, VT);
1171 // Remember that we legalized the chain.
1172 AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
1175 switch (getTypeAction(Node->getOperand(0).getValueType())) {
1176 case Expand: assert(0 && "It's impossible to expand bools");
1178 Tmp1 = LegalizeOp(Node->getOperand(0));// Legalize the condition.
1181 Tmp1 = PromoteOp(Node->getOperand(0)); // Promote the condition.
1184 Tmp2 = PromoteOp(Node->getOperand(1)); // Legalize the op0
1185 Tmp3 = PromoteOp(Node->getOperand(2)); // Legalize the op1
1186 Result = DAG.getNode(ISD::SELECT, NVT, Tmp1, Tmp2, Tmp3);
1189 Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the chain.
1190 Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the callee.
1192 std::vector<SDOperand> Ops;
1193 for (unsigned i = 2, e = Node->getNumOperands(); i != e; ++i)
1194 Ops.push_back(LegalizeOp(Node->getOperand(i)));
1196 assert(Node->getNumValues() == 2 && Op.ResNo == 0 &&
1197 "Can only promote single result calls");
1198 std::vector<MVT::ValueType> RetTyVTs;
1199 RetTyVTs.reserve(2);
1200 RetTyVTs.push_back(NVT);
1201 RetTyVTs.push_back(MVT::Other);
1202 SDNode *NC = DAG.getCall(RetTyVTs, Tmp1, Tmp2, Ops);
1203 Result = SDOperand(NC, 0);
1205 // Insert the new chain mapping.
1206 AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
1211 assert(Result.Val && "Didn't set a result!");
1212 AddPromotedOperand(Op, Result);
1216 /// ExpandAddSub - Find a clever way to expand this add operation into
1218 void SelectionDAGLegalize::ExpandAddSub(bool isAdd, SDOperand LHS,SDOperand RHS,
1219 SDOperand &Lo, SDOperand &Hi) {
1220 // Expand the subcomponents.
1221 SDOperand LHSL, LHSH, RHSL, RHSH;
1222 ExpandOp(LHS, LHSL, LHSH);
1223 ExpandOp(RHS, RHSL, RHSH);
1225 // Convert this add to the appropriate ADDC pair. The low part has no carry
1227 unsigned Opc = isAdd ? ISD::ADD_PARTS : ISD::SUB_PARTS;
1228 std::vector<SDOperand> Ops;
1229 Ops.push_back(LHSL);
1230 Ops.push_back(LHSH);
1231 Ops.push_back(RHSL);
1232 Ops.push_back(RHSH);
1233 Lo = DAG.getNode(Opc, LHSL.getValueType(), Ops);
1234 Hi = Lo.getValue(1);
1237 /// ExpandShift - Try to find a clever way to expand this shift operation out to
1238 /// smaller elements. If we can't find a way that is more efficient than a
1239 /// libcall on this target, return false. Otherwise, return true with the
1240 /// low-parts expanded into Lo and Hi.
1241 bool SelectionDAGLegalize::ExpandShift(unsigned Opc, SDOperand Op,SDOperand Amt,
1242 SDOperand &Lo, SDOperand &Hi) {
1243 assert((Opc == ISD::SHL || Opc == ISD::SRA || Opc == ISD::SRL) &&
1244 "This is not a shift!");
1245 MVT::ValueType NVT = TLI.getTypeToTransformTo(Op.getValueType());
1247 // If we have an efficient select operation (or if the selects will all fold
1248 // away), lower to some complex code, otherwise just emit the libcall.
1249 if (TLI.getOperationAction(ISD::SELECT, NVT) != TargetLowering::Legal &&
1250 !isa<ConstantSDNode>(Amt))
1254 ExpandOp(Op, InL, InH);
1255 SDOperand ShAmt = LegalizeOp(Amt);
1256 MVT::ValueType ShTy = ShAmt.getValueType();
1258 unsigned NVTBits = MVT::getSizeInBits(NVT);
1259 SDOperand NAmt = DAG.getNode(ISD::SUB, ShTy, // NAmt = 32-ShAmt
1260 DAG.getConstant(NVTBits, ShTy), ShAmt);
1262 // Compare the unmasked shift amount against 32.
1263 SDOperand Cond = DAG.getSetCC(ISD::SETGE, TLI.getSetCCResultTy(), ShAmt,
1264 DAG.getConstant(NVTBits, ShTy));
1266 if (TLI.getShiftAmountFlavor() != TargetLowering::Mask) {
1267 ShAmt = DAG.getNode(ISD::AND, ShTy, ShAmt, // ShAmt &= 31
1268 DAG.getConstant(NVTBits-1, ShTy));
1269 NAmt = DAG.getNode(ISD::AND, ShTy, NAmt, // NAmt &= 31
1270 DAG.getConstant(NVTBits-1, ShTy));
1273 if (Opc == ISD::SHL) {
1274 SDOperand T1 = DAG.getNode(ISD::OR, NVT,// T1 = (Hi << Amt) | (Lo >> NAmt)
1275 DAG.getNode(ISD::SHL, NVT, InH, ShAmt),
1276 DAG.getNode(ISD::SRL, NVT, InL, NAmt));
1277 SDOperand T2 = DAG.getNode(ISD::SHL, NVT, InL, ShAmt); // T2 = Lo << Amt&31
1279 Hi = DAG.getNode(ISD::SELECT, NVT, Cond, T2, T1);
1280 Lo = DAG.getNode(ISD::SELECT, NVT, Cond, DAG.getConstant(0, NVT), T2);
1282 SDOperand HiLoPart = DAG.getNode(ISD::SELECT, NVT,
1283 DAG.getSetCC(ISD::SETEQ,
1284 TLI.getSetCCResultTy(), NAmt,
1285 DAG.getConstant(32, ShTy)),
1286 DAG.getConstant(0, NVT),
1287 DAG.getNode(ISD::SHL, NVT, InH, NAmt));
1288 SDOperand T1 = DAG.getNode(ISD::OR, NVT,// T1 = (Hi << NAmt) | (Lo >> Amt)
1290 DAG.getNode(ISD::SRL, NVT, InL, ShAmt));
1291 SDOperand T2 = DAG.getNode(Opc, NVT, InH, ShAmt); // T2 = InH >> ShAmt&31
1294 if (Opc == ISD::SRA)
1295 HiPart = DAG.getNode(ISD::SRA, NVT, InH,
1296 DAG.getConstant(NVTBits-1, ShTy));
1298 HiPart = DAG.getConstant(0, NVT);
1299 Lo = DAG.getNode(ISD::SELECT, NVT, Cond, T2, T1);
1300 Hi = DAG.getNode(ISD::SELECT, NVT, Cond, HiPart, T2);
1305 /// FindLatestAdjCallStackDown - Scan up the dag to find the latest (highest
1306 /// NodeDepth) node that is an AdjCallStackDown operation and occurs later than
1308 static void FindLatestAdjCallStackDown(SDNode *Node, SDNode *&Found) {
1309 if (Node->getNodeDepth() <= Found->getNodeDepth()) return;
1311 // If we found an ADJCALLSTACKDOWN, we already know this node occurs later
1312 // than the Found node. Just remember this node and return.
1313 if (Node->getOpcode() == ISD::ADJCALLSTACKDOWN) {
1318 // Otherwise, scan the operands of Node to see if any of them is a call.
1319 assert(Node->getNumOperands() != 0 &&
1320 "All leaves should have depth equal to the entry node!");
1321 for (unsigned i = 0, e = Node->getNumOperands()-1; i != e; ++i)
1322 FindLatestAdjCallStackDown(Node->getOperand(i).Val, Found);
1324 // Tail recurse for the last iteration.
1325 FindLatestAdjCallStackDown(Node->getOperand(Node->getNumOperands()-1).Val,
1330 /// FindEarliestAdjCallStackUp - Scan down the dag to find the earliest (lowest
1331 /// NodeDepth) node that is an AdjCallStackUp operation and occurs more recent
1333 static void FindEarliestAdjCallStackUp(SDNode *Node, SDNode *&Found) {
1334 if (Found && Node->getNodeDepth() >= Found->getNodeDepth()) return;
1336 // If we found an ADJCALLSTACKUP, we already know this node occurs earlier
1337 // than the Found node. Just remember this node and return.
1338 if (Node->getOpcode() == ISD::ADJCALLSTACKUP) {
1343 // Otherwise, scan the operands of Node to see if any of them is a call.
1344 SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
1345 if (UI == E) return;
1346 for (--E; UI != E; ++UI)
1347 FindEarliestAdjCallStackUp(*UI, Found);
1349 // Tail recurse for the last iteration.
1350 FindEarliestAdjCallStackUp(*UI, Found);
1353 /// FindAdjCallStackUp - Given a chained node that is part of a call sequence,
1354 /// find the ADJCALLSTACKUP node that terminates the call sequence.
1355 static SDNode *FindAdjCallStackUp(SDNode *Node) {
1356 if (Node->getOpcode() == ISD::ADJCALLSTACKUP)
1358 assert(!Node->use_empty() && "Could not find ADJCALLSTACKUP!");
1360 if (Node->hasOneUse()) // Simple case, only has one user to check.
1361 return FindAdjCallStackUp(*Node->use_begin());
1363 SDOperand TheChain(Node, Node->getNumValues()-1);
1364 assert(TheChain.getValueType() == MVT::Other && "Is not a token chain!");
1366 for (SDNode::use_iterator UI = Node->use_begin(),
1367 E = Node->use_end(); ; ++UI) {
1368 assert(UI != E && "Didn't find a user of the tokchain, no ADJCALLSTACKUP!");
1370 // Make sure to only follow users of our token chain.
1372 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
1373 if (User->getOperand(i) == TheChain)
1374 return FindAdjCallStackUp(User);
1376 assert(0 && "Unreachable");
1380 /// FindInputOutputChains - If we are replacing an operation with a call we need
1381 /// to find the call that occurs before and the call that occurs after it to
1382 /// properly serialize the calls in the block.
1383 static SDOperand FindInputOutputChains(SDNode *OpNode, SDNode *&OutChain,
1385 SDNode *LatestAdjCallStackDown = Entry.Val;
1386 FindLatestAdjCallStackDown(OpNode, LatestAdjCallStackDown);
1387 //std::cerr << "Found node: "; LatestAdjCallStackDown->dump(); std::cerr <<"\n";
1389 SDNode *LatestAdjCallStackUp = FindAdjCallStackUp(LatestAdjCallStackDown);
1392 SDNode *EarliestAdjCallStackUp = 0;
1393 FindEarliestAdjCallStackUp(OpNode, EarliestAdjCallStackUp);
1395 if (EarliestAdjCallStackUp) {
1396 //std::cerr << "Found node: ";
1397 //EarliestAdjCallStackUp->dump(); std::cerr <<"\n";
1400 return SDOperand(LatestAdjCallStackUp, 0);
1405 // ExpandLibCall - Expand a node into a call to a libcall. If the result value
1406 // does not fit into a register, return the lo part and set the hi part to the
1407 // by-reg argument. If it does fit into a single register, return the result
1408 // and leave the Hi part unset.
1409 SDOperand SelectionDAGLegalize::ExpandLibCall(const char *Name, SDNode *Node,
1412 SDOperand InChain = FindInputOutputChains(Node, OutChain,
1413 DAG.getEntryNode());
1414 // TODO. Link in chains.
1416 TargetLowering::ArgListTy Args;
1417 for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
1418 MVT::ValueType ArgVT = Node->getOperand(i).getValueType();
1419 const Type *ArgTy = MVT::getTypeForValueType(ArgVT);
1420 Args.push_back(std::make_pair(Node->getOperand(i), ArgTy));
1422 SDOperand Callee = DAG.getExternalSymbol(Name, TLI.getPointerTy());
1424 // We don't care about token chains for libcalls. We just use the entry
1425 // node as our input and ignore the output chain. This allows us to place
1426 // calls wherever we need them to satisfy data dependences.
1427 const Type *RetTy = MVT::getTypeForValueType(Node->getValueType(0));
1428 SDOperand Result = TLI.LowerCallTo(InChain, RetTy, Callee,
1430 switch (getTypeAction(Result.getValueType())) {
1431 default: assert(0 && "Unknown thing");
1435 assert(0 && "Cannot promote this yet!");
1438 ExpandOp(Result, Lo, Hi);
1444 /// ExpandIntToFP - Expand a [US]INT_TO_FP operation, assuming that the
1445 /// destination type is legal.
1446 SDOperand SelectionDAGLegalize::
1447 ExpandIntToFP(bool isSigned, MVT::ValueType DestTy, SDOperand Source) {
1448 assert(getTypeAction(DestTy) == Legal && "Destination type is not legal!");
1449 assert(getTypeAction(Source.getValueType()) == Expand &&
1450 "This is not an expansion!");
1451 assert(Source.getValueType() == MVT::i64 && "Only handle expand from i64!");
1454 SDOperand InChain = FindInputOutputChains(Source.Val, OutChain,
1455 DAG.getEntryNode());
1457 const char *FnName = 0;
1459 if (DestTy == MVT::f32)
1460 FnName = "__floatdisf";
1462 assert(DestTy == MVT::f64 && "Unknown fp value type!");
1463 FnName = "__floatdidf";
1466 // If this is unsigned, and not supported, first perform the conversion to
1467 // signed, then adjust the result if the sign bit is set.
1468 SDOperand SignedConv = ExpandIntToFP(false, DestTy, Source);
1470 assert(0 && "Unsigned casts not supported yet!");
1472 SDOperand Callee = DAG.getExternalSymbol(FnName, TLI.getPointerTy());
1474 TargetLowering::ArgListTy Args;
1475 const Type *ArgTy = MVT::getTypeForValueType(Source.getValueType());
1476 Args.push_back(std::make_pair(Source, ArgTy));
1478 // We don't care about token chains for libcalls. We just use the entry
1479 // node as our input and ignore the output chain. This allows us to place
1480 // calls wherever we need them to satisfy data dependences.
1481 const Type *RetTy = MVT::getTypeForValueType(DestTy);
1482 return TLI.LowerCallTo(InChain, RetTy, Callee, Args, DAG).first;
1488 /// ExpandOp - Expand the specified SDOperand into its two component pieces
1489 /// Lo&Hi. Note that the Op MUST be an expanded type. As a result of this, the
1490 /// LegalizeNodes map is filled in for any results that are not expanded, the
1491 /// ExpandedNodes map is filled in for any results that are expanded, and the
1492 /// Lo/Hi values are returned.
1493 void SelectionDAGLegalize::ExpandOp(SDOperand Op, SDOperand &Lo, SDOperand &Hi){
1494 MVT::ValueType VT = Op.getValueType();
1495 MVT::ValueType NVT = TLI.getTypeToTransformTo(VT);
1496 SDNode *Node = Op.Val;
1497 assert(getTypeAction(VT) == Expand && "Not an expanded type!");
1498 assert(MVT::isInteger(VT) && "Cannot expand FP values!");
1499 assert(MVT::isInteger(NVT) && NVT < VT &&
1500 "Cannot expand to FP value or to larger int value!");
1502 // If there is more than one use of this, see if we already expanded it.
1503 // There is no use remembering values that only have a single use, as the map
1504 // entries will never be reused.
1505 if (!Node->hasOneUse()) {
1506 std::map<SDOperand, std::pair<SDOperand, SDOperand> >::iterator I
1507 = ExpandedNodes.find(Op);
1508 if (I != ExpandedNodes.end()) {
1509 Lo = I->second.first;
1510 Hi = I->second.second;
1515 // Expanding to multiple registers needs to perform an optimization step, and
1516 // is not careful to avoid operations the target does not support. Make sure
1517 // that all generated operations are legalized in the next iteration.
1518 NeedsAnotherIteration = true;
1520 switch (Node->getOpcode()) {
1522 std::cerr << "NODE: "; Node->dump(); std::cerr << "\n";
1523 assert(0 && "Do not know how to expand this operator!");
1525 case ISD::Constant: {
1526 uint64_t Cst = cast<ConstantSDNode>(Node)->getValue();
1527 Lo = DAG.getConstant(Cst, NVT);
1528 Hi = DAG.getConstant(Cst >> MVT::getSizeInBits(NVT), NVT);
1532 case ISD::CopyFromReg: {
1533 unsigned Reg = cast<RegSDNode>(Node)->getReg();
1534 // Aggregate register values are always in consequtive pairs.
1535 Lo = DAG.getCopyFromReg(Reg, NVT, Node->getOperand(0));
1536 Hi = DAG.getCopyFromReg(Reg+1, NVT, Lo.getValue(1));
1538 // Remember that we legalized the chain.
1539 AddLegalizedOperand(Op.getValue(1), Hi.getValue(1));
1541 assert(isTypeLegal(NVT) && "Cannot expand this multiple times yet!");
1546 SDOperand Ch = LegalizeOp(Node->getOperand(0)); // Legalize the chain.
1547 SDOperand Ptr = LegalizeOp(Node->getOperand(1)); // Legalize the pointer.
1548 Lo = DAG.getLoad(NVT, Ch, Ptr);
1550 // Increment the pointer to the other half.
1551 unsigned IncrementSize = MVT::getSizeInBits(Lo.getValueType())/8;
1552 Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
1553 getIntPtrConstant(IncrementSize));
1554 Hi = DAG.getLoad(NVT, Ch, Ptr);
1556 // Build a factor node to remember that this load is independent of the
1558 SDOperand TF = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo.getValue(1),
1561 // Remember that we legalized the chain.
1562 AddLegalizedOperand(Op.getValue(1), TF);
1563 if (!TLI.isLittleEndian())
1568 SDOperand Chain = LegalizeOp(Node->getOperand(0)); // Legalize the chain.
1569 SDOperand Callee = LegalizeOp(Node->getOperand(1)); // Legalize the callee.
1571 bool Changed = false;
1572 std::vector<SDOperand> Ops;
1573 for (unsigned i = 2, e = Node->getNumOperands(); i != e; ++i) {
1574 Ops.push_back(LegalizeOp(Node->getOperand(i)));
1575 Changed |= Ops.back() != Node->getOperand(i);
1578 assert(Node->getNumValues() == 2 && Op.ResNo == 0 &&
1579 "Can only expand a call once so far, not i64 -> i16!");
1581 std::vector<MVT::ValueType> RetTyVTs;
1582 RetTyVTs.reserve(3);
1583 RetTyVTs.push_back(NVT);
1584 RetTyVTs.push_back(NVT);
1585 RetTyVTs.push_back(MVT::Other);
1586 SDNode *NC = DAG.getCall(RetTyVTs, Chain, Callee, Ops);
1587 Lo = SDOperand(NC, 0);
1588 Hi = SDOperand(NC, 1);
1590 // Insert the new chain mapping.
1591 AddLegalizedOperand(Op.getValue(1), Hi.getValue(2));
1596 case ISD::XOR: { // Simple logical operators -> two trivial pieces.
1597 SDOperand LL, LH, RL, RH;
1598 ExpandOp(Node->getOperand(0), LL, LH);
1599 ExpandOp(Node->getOperand(1), RL, RH);
1600 Lo = DAG.getNode(Node->getOpcode(), NVT, LL, RL);
1601 Hi = DAG.getNode(Node->getOpcode(), NVT, LH, RH);
1605 SDOperand C, LL, LH, RL, RH;
1607 switch (getTypeAction(Node->getOperand(0).getValueType())) {
1608 case Expand: assert(0 && "It's impossible to expand bools");
1610 C = LegalizeOp(Node->getOperand(0)); // Legalize the condition.
1613 C = PromoteOp(Node->getOperand(0)); // Promote the condition.
1616 ExpandOp(Node->getOperand(1), LL, LH);
1617 ExpandOp(Node->getOperand(2), RL, RH);
1618 Lo = DAG.getNode(ISD::SELECT, NVT, C, LL, RL);
1619 Hi = DAG.getNode(ISD::SELECT, NVT, C, LH, RH);
1622 case ISD::SIGN_EXTEND: {
1623 // The low part is just a sign extension of the input (which degenerates to
1625 Lo = DAG.getNode(ISD::SIGN_EXTEND, NVT, LegalizeOp(Node->getOperand(0)));
1627 // The high part is obtained by SRA'ing all but one of the bits of the lo
1629 unsigned LoSize = MVT::getSizeInBits(Lo.getValueType());
1630 Hi = DAG.getNode(ISD::SRA, NVT, Lo, DAG.getConstant(LoSize-1,
1631 TLI.getShiftAmountTy()));
1634 case ISD::ZERO_EXTEND:
1635 // The low part is just a zero extension of the input (which degenerates to
1637 Lo = DAG.getNode(ISD::ZERO_EXTEND, NVT, LegalizeOp(Node->getOperand(0)));
1639 // The high part is just a zero.
1640 Hi = DAG.getConstant(0, NVT);
1643 // These operators cannot be expanded directly, emit them as calls to
1644 // library functions.
1645 case ISD::FP_TO_SINT:
1646 if (Node->getOperand(0).getValueType() == MVT::f32)
1647 Lo = ExpandLibCall("__fixsfdi", Node, Hi);
1649 Lo = ExpandLibCall("__fixdfdi", Node, Hi);
1651 case ISD::FP_TO_UINT:
1652 if (Node->getOperand(0).getValueType() == MVT::f32)
1653 Lo = ExpandLibCall("__fixunssfdi", Node, Hi);
1655 Lo = ExpandLibCall("__fixunsdfdi", Node, Hi);
1659 // If we can emit an efficient shift operation, do so now.
1660 if (ExpandShift(ISD::SHL, Node->getOperand(0), Node->getOperand(1), Lo, Hi))
1662 // Otherwise, emit a libcall.
1663 Lo = ExpandLibCall("__ashldi3", Node, Hi);
1667 // If we can emit an efficient shift operation, do so now.
1668 if (ExpandShift(ISD::SRA, Node->getOperand(0), Node->getOperand(1), Lo, Hi))
1670 // Otherwise, emit a libcall.
1671 Lo = ExpandLibCall("__ashrdi3", Node, Hi);
1674 // If we can emit an efficient shift operation, do so now.
1675 if (ExpandShift(ISD::SRL, Node->getOperand(0), Node->getOperand(1), Lo, Hi))
1677 // Otherwise, emit a libcall.
1678 Lo = ExpandLibCall("__lshrdi3", Node, Hi);
1682 ExpandAddSub(true, Node->getOperand(0), Node->getOperand(1), Lo, Hi);
1685 ExpandAddSub(false, Node->getOperand(0), Node->getOperand(1), Lo, Hi);
1687 case ISD::MUL: Lo = ExpandLibCall("__muldi3" , Node, Hi); break;
1688 case ISD::SDIV: Lo = ExpandLibCall("__divdi3" , Node, Hi); break;
1689 case ISD::UDIV: Lo = ExpandLibCall("__udivdi3", Node, Hi); break;
1690 case ISD::SREM: Lo = ExpandLibCall("__moddi3" , Node, Hi); break;
1691 case ISD::UREM: Lo = ExpandLibCall("__umoddi3", Node, Hi); break;
1694 // Remember in a map if the values will be reused later.
1695 if (!Node->hasOneUse()) {
1696 bool isNew = ExpandedNodes.insert(std::make_pair(Op,
1697 std::make_pair(Lo, Hi))).second;
1698 assert(isNew && "Value already expanded?!?");
1703 // SelectionDAG::Legalize - This is the entry point for the file.
1705 void SelectionDAG::Legalize() {
1706 /// run - This is the main entry point to this class.
1708 SelectionDAGLegalize(*this).Run();