91fbf98ab5d187fb673234d6e58dfae4a21a3dcf
[oota-llvm.git] / lib / CodeGen / SelectionDAG / SelectionDAG.cpp
1 //===-- SelectionDAG.cpp - Implement the SelectionDAG data structures -----===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
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.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This implements the SelectionDAG class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/CodeGen/SelectionDAG.h"
15 #include "llvm/Constants.h"
16 #include "llvm/GlobalValue.h"
17 #include "llvm/Assembly/Writer.h"
18 #include "llvm/CodeGen/MachineBasicBlock.h"
19 #include "llvm/Target/TargetLowering.h"
20 #include <iostream>
21 #include <set>
22 #include <cmath>
23 #include <algorithm>
24 using namespace llvm;
25
26 static bool isCommutativeBinOp(unsigned Opcode) {
27   switch (Opcode) {
28   case ISD::ADD:
29   case ISD::MUL:
30   case ISD::AND:
31   case ISD::OR:
32   case ISD::XOR: return true;
33   default: return false; // FIXME: Need commutative info for user ops!
34   }
35 }
36
37 static bool isAssociativeBinOp(unsigned Opcode) {
38   switch (Opcode) {
39   case ISD::ADD:
40   case ISD::MUL:
41   case ISD::AND:
42   case ISD::OR:
43   case ISD::XOR: return true;
44   default: return false; // FIXME: Need associative info for user ops!
45   }
46 }
47
48 static unsigned ExactLog2(uint64_t Val) {
49   unsigned Count = 0;
50   while (Val != 1) {
51     Val >>= 1;
52     ++Count;
53   }
54   return Count;
55 }
56
57 // isInvertibleForFree - Return true if there is no cost to emitting the logical
58 // inverse of this node.
59 static bool isInvertibleForFree(SDOperand N) {
60   if (isa<ConstantSDNode>(N.Val)) return true;
61   if (isa<SetCCSDNode>(N.Val) && N.Val->hasOneUse())
62     return true;
63   return false;
64 }
65
66
67 /// getSetCCSwappedOperands - Return the operation corresponding to (Y op X)
68 /// when given the operation for (X op Y).
69 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
70   // To perform this operation, we just need to swap the L and G bits of the
71   // operation.
72   unsigned OldL = (Operation >> 2) & 1;
73   unsigned OldG = (Operation >> 1) & 1;
74   return ISD::CondCode((Operation & ~6) |  // Keep the N, U, E bits
75                        (OldL << 1) |       // New G bit
76                        (OldG << 2));        // New L bit.
77 }
78
79 /// getSetCCInverse - Return the operation corresponding to !(X op Y), where
80 /// 'op' is a valid SetCC operation.
81 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) {
82   unsigned Operation = Op;
83   if (isInteger)
84     Operation ^= 7;   // Flip L, G, E bits, but not U.
85   else
86     Operation ^= 15;  // Flip all of the condition bits.
87   if (Operation > ISD::SETTRUE2)
88     Operation &= ~8;     // Don't let N and U bits get set.
89   return ISD::CondCode(Operation);
90 }
91
92
93 /// isSignedOp - For an integer comparison, return 1 if the comparison is a
94 /// signed operation and 2 if the result is an unsigned comparison.  Return zero
95 /// if the operation does not depend on the sign of the input (setne and seteq).
96 static int isSignedOp(ISD::CondCode Opcode) {
97   switch (Opcode) {
98   default: assert(0 && "Illegal integer setcc operation!");
99   case ISD::SETEQ:
100   case ISD::SETNE: return 0;
101   case ISD::SETLT:
102   case ISD::SETLE:
103   case ISD::SETGT:
104   case ISD::SETGE: return 1;
105   case ISD::SETULT:
106   case ISD::SETULE:
107   case ISD::SETUGT:
108   case ISD::SETUGE: return 2;
109   }
110 }
111
112 /// getSetCCOrOperation - Return the result of a logical OR between different
113 /// comparisons of identical values: ((X op1 Y) | (X op2 Y)).  This function
114 /// returns SETCC_INVALID if it is not possible to represent the resultant
115 /// comparison.
116 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
117                                        bool isInteger) {
118   if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
119     // Cannot fold a signed integer setcc with an unsigned integer setcc.
120     return ISD::SETCC_INVALID;
121
122   unsigned Op = Op1 | Op2;  // Combine all of the condition bits.
123
124   // If the N and U bits get set then the resultant comparison DOES suddenly
125   // care about orderedness, and is true when ordered.
126   if (Op > ISD::SETTRUE2)
127     Op &= ~16;     // Clear the N bit.
128   return ISD::CondCode(Op);
129 }
130
131 /// getSetCCAndOperation - Return the result of a logical AND between different
132 /// comparisons of identical values: ((X op1 Y) & (X op2 Y)).  This
133 /// function returns zero if it is not possible to represent the resultant
134 /// comparison.
135 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
136                                         bool isInteger) {
137   if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
138     // Cannot fold a signed setcc with an unsigned setcc.
139     return ISD::SETCC_INVALID;
140
141   // Combine all of the condition bits.
142   return ISD::CondCode(Op1 & Op2);
143 }
144
145 const TargetMachine &SelectionDAG::getTarget() const {
146   return TLI.getTargetMachine();
147 }
148
149
150 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
151 /// SelectionDAG, including nodes (like loads) that have uses of their token
152 /// chain but no other uses and no side effect.  If a node is passed in as an
153 /// argument, it is used as the seed for node deletion.
154 void SelectionDAG::RemoveDeadNodes(SDNode *N) {
155   std::set<SDNode*> AllNodeSet(AllNodes.begin(), AllNodes.end());
156
157   // Create a dummy node (which is not added to allnodes), that adds a reference
158   // to the root node, preventing it from being deleted.
159   SDNode *DummyNode = new SDNode(ISD::EntryToken, getRoot());
160
161   DeleteNodeIfDead(N, &AllNodeSet);
162
163  Restart:
164   unsigned NumNodes = AllNodeSet.size();
165   for (std::set<SDNode*>::iterator I = AllNodeSet.begin(), E = AllNodeSet.end();
166        I != E; ++I) {
167     // Try to delete this node.
168     DeleteNodeIfDead(*I, &AllNodeSet);
169
170     // If we actually deleted any nodes, do not use invalid iterators in
171     // AllNodeSet.
172     if (AllNodeSet.size() != NumNodes)
173       goto Restart;
174   }
175
176   // Restore AllNodes.
177   if (AllNodes.size() != NumNodes)
178     AllNodes.assign(AllNodeSet.begin(), AllNodeSet.end());
179
180   // If the root changed (e.g. it was a dead load, update the root).
181   setRoot(DummyNode->getOperand(0));
182
183   // Now that we are done with the dummy node, delete it.
184   DummyNode->getOperand(0).Val->removeUser(DummyNode);
185   delete DummyNode;
186 }
187
188 void SelectionDAG::DeleteNodeIfDead(SDNode *N, void *NodeSet) {
189   if (!N->use_empty())
190     return;
191
192   // Okay, we really are going to delete this node.  First take this out of the
193   // appropriate CSE map.
194   switch (N->getOpcode()) {
195   case ISD::Constant:
196     Constants.erase(std::make_pair(cast<ConstantSDNode>(N)->getValue(),
197                                    N->getValueType(0)));
198     break;
199   case ISD::ConstantFP: {
200     union {
201       double DV;
202       uint64_t IV;
203     };
204     DV = cast<ConstantFPSDNode>(N)->getValue();
205     ConstantFPs.erase(std::make_pair(IV, N->getValueType(0)));
206     break;
207   }
208   case ISD::GlobalAddress:
209     GlobalValues.erase(cast<GlobalAddressSDNode>(N)->getGlobal());
210     break;
211   case ISD::FrameIndex:
212     FrameIndices.erase(cast<FrameIndexSDNode>(N)->getIndex());
213     break;
214   case ISD::ConstantPool:
215     ConstantPoolIndices.erase(cast<ConstantPoolSDNode>(N)->getIndex());
216     break;
217   case ISD::BasicBlock:
218     BBNodes.erase(cast<BasicBlockSDNode>(N)->getBasicBlock());
219     break;
220   case ISD::ExternalSymbol:
221     ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
222     break;
223   case ISD::VALUETYPE:
224     ValueTypeNodes[cast<VTSDNode>(N)->getVT()] = 0;
225     break;
226   case ISD::LOAD:
227     Loads.erase(std::make_pair(N->getOperand(1),
228                                std::make_pair(N->getOperand(0),
229                                               N->getValueType(0))));
230     break;
231   case ISD::SETCC:
232     SetCCs.erase(std::make_pair(std::make_pair(N->getOperand(0),
233                                                N->getOperand(1)),
234                                 std::make_pair(
235                                      cast<SetCCSDNode>(N)->getCondition(),
236                                      N->getValueType(0))));
237     break;
238   default:
239     if (N->getNumOperands() == 1)
240       UnaryOps.erase(std::make_pair(N->getOpcode(),
241                                     std::make_pair(N->getOperand(0),
242                                                    N->getValueType(0))));
243     else if (N->getNumOperands() == 2)
244       BinaryOps.erase(std::make_pair(N->getOpcode(),
245                                      std::make_pair(N->getOperand(0),
246                                                     N->getOperand(1))));
247     else if (N->getNumValues() == 1) {
248       std::vector<SDOperand> Ops(N->op_begin(), N->op_end());
249       OneResultNodes.erase(std::make_pair(N->getOpcode(),
250                                           std::make_pair(N->getValueType(0),
251                                                          Ops)));
252     } else {
253       // Remove the node from the ArbitraryNodes map.
254       std::vector<MVT::ValueType> RV(N->value_begin(), N->value_end());
255       std::vector<SDOperand>     Ops(N->op_begin(), N->op_end());
256       ArbitraryNodes.erase(std::make_pair(N->getOpcode(),
257                                           std::make_pair(RV, Ops)));
258     }
259     break;
260   }
261
262   // Next, brutally remove the operand list.
263   while (!N->Operands.empty()) {
264     SDNode *O = N->Operands.back().Val;
265     N->Operands.pop_back();
266     O->removeUser(N);
267
268     // Now that we removed this operand, see if there are no uses of it left.
269     DeleteNodeIfDead(O, NodeSet);
270   }
271
272   // Remove the node from the nodes set and delete it.
273   std::set<SDNode*> &AllNodeSet = *(std::set<SDNode*>*)NodeSet;
274   AllNodeSet.erase(N);
275
276   // Now that the node is gone, check to see if any of the operands of this node
277   // are dead now.
278   delete N;
279 }
280
281
282 SelectionDAG::~SelectionDAG() {
283   for (unsigned i = 0, e = AllNodes.size(); i != e; ++i)
284     delete AllNodes[i];
285 }
286
287 SDOperand SelectionDAG::getZeroExtendInReg(SDOperand Op, MVT::ValueType VT) {
288   if (Op.getValueType() == VT) return Op;
289   int64_t Imm = ~0ULL >> (64-MVT::getSizeInBits(VT));
290   return getNode(ISD::AND, Op.getValueType(), Op,
291                  getConstant(Imm, Op.getValueType()));
292 }
293
294 SDOperand SelectionDAG::getConstant(uint64_t Val, MVT::ValueType VT) {
295   assert(MVT::isInteger(VT) && "Cannot create FP integer constant!");
296   // Mask out any bits that are not valid for this constant.
297   if (VT != MVT::i64)
298     Val &= ((uint64_t)1 << MVT::getSizeInBits(VT)) - 1;
299
300   SDNode *&N = Constants[std::make_pair(Val, VT)];
301   if (N) return SDOperand(N, 0);
302   N = new ConstantSDNode(Val, VT);
303   AllNodes.push_back(N);
304   return SDOperand(N, 0);
305 }
306
307 SDOperand SelectionDAG::getConstantFP(double Val, MVT::ValueType VT) {
308   assert(MVT::isFloatingPoint(VT) && "Cannot create integer FP constant!");
309   if (VT == MVT::f32)
310     Val = (float)Val;  // Mask out extra precision.
311
312   // Do the map lookup using the actual bit pattern for the floating point
313   // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
314   // we don't have issues with SNANs.
315   union {
316     double DV;
317     uint64_t IV;
318   };
319
320   DV = Val;
321
322   SDNode *&N = ConstantFPs[std::make_pair(IV, VT)];
323   if (N) return SDOperand(N, 0);
324   N = new ConstantFPSDNode(Val, VT);
325   AllNodes.push_back(N);
326   return SDOperand(N, 0);
327 }
328
329
330
331 SDOperand SelectionDAG::getGlobalAddress(const GlobalValue *GV,
332                                          MVT::ValueType VT) {
333   SDNode *&N = GlobalValues[GV];
334   if (N) return SDOperand(N, 0);
335   N = new GlobalAddressSDNode(GV,VT);
336   AllNodes.push_back(N);
337   return SDOperand(N, 0);
338 }
339
340 SDOperand SelectionDAG::getFrameIndex(int FI, MVT::ValueType VT) {
341   SDNode *&N = FrameIndices[FI];
342   if (N) return SDOperand(N, 0);
343   N = new FrameIndexSDNode(FI, VT);
344   AllNodes.push_back(N);
345   return SDOperand(N, 0);
346 }
347
348 SDOperand SelectionDAG::getConstantPool(unsigned CPIdx, MVT::ValueType VT) {
349   SDNode *N = ConstantPoolIndices[CPIdx];
350   if (N) return SDOperand(N, 0);
351   N = new ConstantPoolSDNode(CPIdx, VT);
352   AllNodes.push_back(N);
353   return SDOperand(N, 0);
354 }
355
356 SDOperand SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
357   SDNode *&N = BBNodes[MBB];
358   if (N) return SDOperand(N, 0);
359   N = new BasicBlockSDNode(MBB);
360   AllNodes.push_back(N);
361   return SDOperand(N, 0);
362 }
363
364 SDOperand SelectionDAG::getValueType(MVT::ValueType VT) {
365   if ((unsigned)VT >= ValueTypeNodes.size())
366     ValueTypeNodes.resize(VT+1);
367   if (ValueTypeNodes[VT] == 0) {
368     ValueTypeNodes[VT] = new VTSDNode(VT);
369     AllNodes.push_back(ValueTypeNodes[VT]);
370   }
371
372   return SDOperand(ValueTypeNodes[VT], 0);
373 }
374
375 SDOperand SelectionDAG::getExternalSymbol(const char *Sym, MVT::ValueType VT) {
376   SDNode *&N = ExternalSymbols[Sym];
377   if (N) return SDOperand(N, 0);
378   N = new ExternalSymbolSDNode(Sym, VT);
379   AllNodes.push_back(N);
380   return SDOperand(N, 0);
381 }
382
383 SDOperand SelectionDAG::getSetCC(ISD::CondCode Cond, MVT::ValueType VT,
384                                  SDOperand N1, SDOperand N2) {
385   // These setcc operations always fold.
386   switch (Cond) {
387   default: break;
388   case ISD::SETFALSE:
389   case ISD::SETFALSE2: return getConstant(0, VT);
390   case ISD::SETTRUE:
391   case ISD::SETTRUE2:  return getConstant(1, VT);
392   }
393
394   if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val)) {
395     uint64_t C2 = N2C->getValue();
396     if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val)) {
397       uint64_t C1 = N1C->getValue();
398
399       // Sign extend the operands if required
400       if (ISD::isSignedIntSetCC(Cond)) {
401         C1 = N1C->getSignExtended();
402         C2 = N2C->getSignExtended();
403       }
404
405       switch (Cond) {
406       default: assert(0 && "Unknown integer setcc!");
407       case ISD::SETEQ:  return getConstant(C1 == C2, VT);
408       case ISD::SETNE:  return getConstant(C1 != C2, VT);
409       case ISD::SETULT: return getConstant(C1 <  C2, VT);
410       case ISD::SETUGT: return getConstant(C1 >  C2, VT);
411       case ISD::SETULE: return getConstant(C1 <= C2, VT);
412       case ISD::SETUGE: return getConstant(C1 >= C2, VT);
413       case ISD::SETLT:  return getConstant((int64_t)C1 <  (int64_t)C2, VT);
414       case ISD::SETGT:  return getConstant((int64_t)C1 >  (int64_t)C2, VT);
415       case ISD::SETLE:  return getConstant((int64_t)C1 <= (int64_t)C2, VT);
416       case ISD::SETGE:  return getConstant((int64_t)C1 >= (int64_t)C2, VT);
417       }
418     } else {
419       // If the LHS is a ZERO_EXTEND and if this is an ==/!= comparison, perform
420       // the comparison on the input.
421       if (N1.getOpcode() == ISD::ZERO_EXTEND) {
422         unsigned InSize = MVT::getSizeInBits(N1.getOperand(0).getValueType());
423
424         // If the comparison constant has bits in the upper part, the
425         // zero-extended value could never match.
426         if (C2 & (~0ULL << InSize)) {
427           unsigned VSize = MVT::getSizeInBits(N1.getValueType());
428           switch (Cond) {
429           case ISD::SETUGT:
430           case ISD::SETUGE:
431           case ISD::SETEQ: return getConstant(0, VT);
432           case ISD::SETULT:
433           case ISD::SETULE:
434           case ISD::SETNE: return getConstant(1, VT);
435           case ISD::SETGT:
436           case ISD::SETGE:
437             // True if the sign bit of C2 is set.
438             return getConstant((C2 & (1ULL << VSize)) != 0, VT);
439           case ISD::SETLT:
440           case ISD::SETLE:
441             // True if the sign bit of C2 isn't set.
442             return getConstant((C2 & (1ULL << VSize)) == 0, VT);
443           default:
444             break;
445           }
446         }
447
448         // Otherwise, we can perform the comparison with the low bits.
449         switch (Cond) {
450         case ISD::SETEQ:
451         case ISD::SETNE:
452         case ISD::SETUGT:
453         case ISD::SETUGE:
454         case ISD::SETULT:
455         case ISD::SETULE:
456           return getSetCC(Cond, VT, N1.getOperand(0),
457                           getConstant(C2, N1.getOperand(0).getValueType()));
458         default:
459           break;   // todo, be more careful with signed comparisons
460         }
461       }
462
463
464       uint64_t MinVal, MaxVal;
465       unsigned OperandBitSize = MVT::getSizeInBits(N2C->getValueType(0));
466       if (ISD::isSignedIntSetCC(Cond)) {
467         MinVal = 1ULL << (OperandBitSize-1);
468         if (OperandBitSize != 1)   // Avoid X >> 64, which is undefined.
469           MaxVal = ~0ULL >> (65-OperandBitSize);
470         else
471           MaxVal = 0;
472       } else {
473         MinVal = 0;
474         MaxVal = ~0ULL >> (64-OperandBitSize);
475       }
476
477       // Canonicalize GE/LE comparisons to use GT/LT comparisons.
478       if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
479         if (C2 == MinVal) return getConstant(1, VT);   // X >= MIN --> true
480         --C2;                                          // X >= C1 --> X > (C1-1)
481         Cond = (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT;
482         N2 = getConstant(C2, N2.getValueType());
483         N2C = cast<ConstantSDNode>(N2.Val);
484       }
485
486       if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
487         if (C2 == MaxVal) return getConstant(1, VT);   // X <= MAX --> true
488         ++C2;                                          // X <= C1 --> X < (C1+1)
489         Cond = (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT;
490         N2 = getConstant(C2, N2.getValueType());
491         N2C = cast<ConstantSDNode>(N2.Val);
492       }
493
494       if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C2 == MinVal)
495         return getConstant(0, VT);      // X < MIN --> false
496
497       // Canonicalize setgt X, Min --> setne X, Min
498       if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C2 == MinVal)
499         return getSetCC(ISD::SETNE, VT, N1, N2);
500
501       // If we have setult X, 1, turn it into seteq X, 0
502       if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C2 == MinVal+1)
503         return getSetCC(ISD::SETEQ, VT, N1,
504                         getConstant(MinVal, N1.getValueType()));
505       // If we have setugt X, Max-1, turn it into seteq X, Max
506       else if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C2 == MaxVal-1)
507         return getSetCC(ISD::SETEQ, VT, N1,
508                         getConstant(MaxVal, N1.getValueType()));
509
510       // If we have "setcc X, C1", check to see if we can shrink the immediate
511       // by changing cc.
512
513       // SETUGT X, SINTMAX  -> SETLT X, 0
514       if (Cond == ISD::SETUGT && OperandBitSize != 1 &&
515           C2 == (~0ULL >> (65-OperandBitSize)))
516         return getSetCC(ISD::SETLT, VT, N1, getConstant(0, N2.getValueType()));
517
518       // FIXME: Implement the rest of these.
519
520
521       // Fold bit comparisons when we can.
522       if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
523           VT == N1.getValueType() && N1.getOpcode() == ISD::AND)
524         if (ConstantSDNode *AndRHS =
525                     dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
526           if (Cond == ISD::SETNE && C2 == 0) {// (X & 8) != 0  -->  (X & 8) >> 3
527             // Perform the xform if the AND RHS is a single bit.
528             if ((AndRHS->getValue() & (AndRHS->getValue()-1)) == 0) {
529               return getNode(ISD::SRL, VT, N1,
530                              getConstant(ExactLog2(AndRHS->getValue()),
531                                                    TLI.getShiftAmountTy()));
532             }
533           } else if (Cond == ISD::SETEQ && C2 == AndRHS->getValue()) {
534             // (X & 8) == 8  -->  (X & 8) >> 3
535             // Perform the xform if C2 is a single bit.
536             if ((C2 & (C2-1)) == 0) {
537               return getNode(ISD::SRL, VT, N1,
538                              getConstant(ExactLog2(C2),TLI.getShiftAmountTy()));
539             }
540           }
541         }
542     }
543   } else if (isa<ConstantSDNode>(N1.Val)) {
544       // Ensure that the constant occurs on the RHS.
545     return getSetCC(ISD::getSetCCSwappedOperands(Cond), VT, N2, N1);
546   }
547
548   if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1.Val))
549     if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2.Val)) {
550       double C1 = N1C->getValue(), C2 = N2C->getValue();
551
552       switch (Cond) {
553       default: break; // FIXME: Implement the rest of these!
554       case ISD::SETEQ:  return getConstant(C1 == C2, VT);
555       case ISD::SETNE:  return getConstant(C1 != C2, VT);
556       case ISD::SETLT:  return getConstant(C1 < C2, VT);
557       case ISD::SETGT:  return getConstant(C1 > C2, VT);
558       case ISD::SETLE:  return getConstant(C1 <= C2, VT);
559       case ISD::SETGE:  return getConstant(C1 >= C2, VT);
560       }
561     } else {
562       // Ensure that the constant occurs on the RHS.
563       Cond = ISD::getSetCCSwappedOperands(Cond);
564       std::swap(N1, N2);
565     }
566
567   if (N1 == N2) {
568     // We can always fold X == Y for integer setcc's.
569     if (MVT::isInteger(N1.getValueType()))
570       return getConstant(ISD::isTrueWhenEqual(Cond), VT);
571     unsigned UOF = ISD::getUnorderedFlavor(Cond);
572     if (UOF == 2)   // FP operators that are undefined on NaNs.
573       return getConstant(ISD::isTrueWhenEqual(Cond), VT);
574     if (UOF == unsigned(ISD::isTrueWhenEqual(Cond)))
575       return getConstant(UOF, VT);
576     // Otherwise, we can't fold it.  However, we can simplify it to SETUO/SETO
577     // if it is not already.
578     Cond = UOF == 0 ? ISD::SETUO : ISD::SETO;
579   }
580
581   if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
582       MVT::isInteger(N1.getValueType())) {
583     if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB ||
584         N1.getOpcode() == ISD::XOR) {
585       // Simplify (X+Y) == (X+Z) -->  Y == Z
586       if (N1.getOpcode() == N2.getOpcode()) {
587         if (N1.getOperand(0) == N2.getOperand(0))
588           return getSetCC(Cond, VT, N1.getOperand(1), N2.getOperand(1));
589         if (N1.getOperand(1) == N2.getOperand(1))
590           return getSetCC(Cond, VT, N1.getOperand(0), N2.getOperand(0));
591         if (isCommutativeBinOp(N1.getOpcode())) {
592           // If X op Y == Y op X, try other combinations.
593           if (N1.getOperand(0) == N2.getOperand(1))
594             return getSetCC(Cond, VT, N1.getOperand(1), N2.getOperand(0));
595           if (N1.getOperand(1) == N2.getOperand(0))
596             return getSetCC(Cond, VT, N1.getOperand(1), N2.getOperand(1));
597         }
598       }
599
600       // FIXME: move this stuff to the DAG Combiner when it exists!
601
602       // Simplify (X+Z) == X -->  Z == 0
603       if (N1.getOperand(0) == N2)
604         return getSetCC(Cond, VT, N1.getOperand(1),
605                         getConstant(0, N1.getValueType()));
606       if (N1.getOperand(1) == N2) {
607         if (isCommutativeBinOp(N1.getOpcode()))
608           return getSetCC(Cond, VT, N1.getOperand(0),
609                           getConstant(0, N1.getValueType()));
610         else {
611           assert(N1.getOpcode() == ISD::SUB && "Unexpected operation!");
612           // (Z-X) == X  --> Z == X<<1
613           return getSetCC(Cond, VT, N1.getOperand(0),
614                           getNode(ISD::SHL, N2.getValueType(),
615                                   N2, getConstant(1, TLI.getShiftAmountTy())));
616         }
617       }
618     }
619
620     if (N2.getOpcode() == ISD::ADD || N2.getOpcode() == ISD::SUB ||
621         N2.getOpcode() == ISD::XOR) {
622       // Simplify  X == (X+Z) -->  Z == 0
623       if (N2.getOperand(0) == N1)
624         return getSetCC(Cond, VT, N2.getOperand(1),
625                         getConstant(0, N2.getValueType()));
626       else if (N2.getOperand(1) == N1)
627         return getSetCC(Cond, VT, N2.getOperand(0),
628                         getConstant(0, N2.getValueType()));
629     }
630   }
631
632   // Fold away ALL boolean setcc's.
633   if (N1.getValueType() == MVT::i1) {
634     switch (Cond) {
635     default: assert(0 && "Unknown integer setcc!");
636     case ISD::SETEQ:  // X == Y  -> (X^Y)^1
637       N1 = getNode(ISD::XOR, MVT::i1,
638                    getNode(ISD::XOR, MVT::i1, N1, N2),
639                    getConstant(1, MVT::i1));
640       break;
641     case ISD::SETNE:  // X != Y   -->  (X^Y)
642       N1 = getNode(ISD::XOR, MVT::i1, N1, N2);
643       break;
644     case ISD::SETGT:  // X >s Y   -->  X == 0 & Y == 1  -->  X^1 & Y
645     case ISD::SETULT: // X <u Y   -->  X == 0 & Y == 1  -->  X^1 & Y
646       N1 = getNode(ISD::AND, MVT::i1, N2,
647                    getNode(ISD::XOR, MVT::i1, N1, getConstant(1, MVT::i1)));
648       break;
649     case ISD::SETLT:  // X <s Y   --> X == 1 & Y == 0  -->  Y^1 & X
650     case ISD::SETUGT: // X >u Y   --> X == 1 & Y == 0  -->  Y^1 & X
651       N1 = getNode(ISD::AND, MVT::i1, N1,
652                    getNode(ISD::XOR, MVT::i1, N2, getConstant(1, MVT::i1)));
653       break;
654     case ISD::SETULE: // X <=u Y  --> X == 0 | Y == 1  -->  X^1 | Y
655     case ISD::SETGE:  // X >=s Y  --> X == 0 | Y == 1  -->  X^1 | Y
656       N1 = getNode(ISD::OR, MVT::i1, N2,
657                    getNode(ISD::XOR, MVT::i1, N1, getConstant(1, MVT::i1)));
658       break;
659     case ISD::SETUGE: // X >=u Y  --> X == 1 | Y == 0  -->  Y^1 | X
660     case ISD::SETLE:  // X <=s Y  --> X == 1 | Y == 0  -->  Y^1 | X
661       N1 = getNode(ISD::OR, MVT::i1, N1,
662                    getNode(ISD::XOR, MVT::i1, N2, getConstant(1, MVT::i1)));
663       break;
664     }
665     if (VT != MVT::i1)
666       N1 = getNode(ISD::ZERO_EXTEND, VT, N1);
667     return N1;
668   }
669
670
671   SetCCSDNode *&N = SetCCs[std::make_pair(std::make_pair(N1, N2),
672                                           std::make_pair(Cond, VT))];
673   if (N) return SDOperand(N, 0);
674   N = new SetCCSDNode(Cond, N1, N2);
675   N->setValueTypes(VT);
676   AllNodes.push_back(N);
677   return SDOperand(N, 0);
678 }
679
680
681
682 /// getNode - Gets or creates the specified node.
683 ///
684 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT) {
685   SDNode *N = new SDNode(Opcode, VT);
686   AllNodes.push_back(N);
687   return SDOperand(N, 0);
688 }
689
690 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
691                                 SDOperand Operand) {
692   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand.Val)) {
693     uint64_t Val = C->getValue();
694     switch (Opcode) {
695     default: break;
696     case ISD::SIGN_EXTEND: return getConstant(C->getSignExtended(), VT);
697     case ISD::ZERO_EXTEND: return getConstant(Val, VT);
698     case ISD::TRUNCATE:    return getConstant(Val, VT);
699     case ISD::SINT_TO_FP:  return getConstantFP(C->getSignExtended(), VT);
700     case ISD::UINT_TO_FP:  return getConstantFP(C->getValue(), VT);
701     }
702   }
703
704   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand.Val))
705     switch (Opcode) {
706     case ISD::FNEG:
707       return getConstantFP(-C->getValue(), VT);
708     case ISD::FP_ROUND:
709     case ISD::FP_EXTEND:
710       return getConstantFP(C->getValue(), VT);
711     case ISD::FP_TO_SINT:
712       return getConstant((int64_t)C->getValue(), VT);
713     case ISD::FP_TO_UINT:
714       return getConstant((uint64_t)C->getValue(), VT);
715     }
716
717   unsigned OpOpcode = Operand.Val->getOpcode();
718   switch (Opcode) {
719   case ISD::TokenFactor:
720     return Operand;         // Factor of one node?  No factor.
721   case ISD::SIGN_EXTEND:
722     if (Operand.getValueType() == VT) return Operand;   // noop extension
723     if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
724       return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
725     break;
726   case ISD::ZERO_EXTEND:
727     if (Operand.getValueType() == VT) return Operand;   // noop extension
728     if (OpOpcode == ISD::ZERO_EXTEND)   // (zext (zext x)) -> (zext x)
729       return getNode(ISD::ZERO_EXTEND, VT, Operand.Val->getOperand(0));
730     break;
731   case ISD::TRUNCATE:
732     if (Operand.getValueType() == VT) return Operand;   // noop truncate
733     if (OpOpcode == ISD::TRUNCATE)
734       return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
735     else if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND) {
736       // If the source is smaller than the dest, we still need an extend.
737       if (Operand.Val->getOperand(0).getValueType() < VT)
738         return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
739       else if (Operand.Val->getOperand(0).getValueType() > VT)
740         return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
741       else
742         return Operand.Val->getOperand(0);
743     }
744     break;
745   case ISD::FNEG:
746     if (OpOpcode == ISD::SUB)   // -(X-Y) -> (Y-X)
747       return getNode(ISD::SUB, VT, Operand.Val->getOperand(1),
748                      Operand.Val->getOperand(0));
749     if (OpOpcode == ISD::FNEG)  // --X -> X
750       return Operand.Val->getOperand(0);
751     break;
752   case ISD::FABS:
753     if (OpOpcode == ISD::FNEG)  // abs(-X) -> abs(X)
754       return getNode(ISD::FABS, VT, Operand.Val->getOperand(0));
755     break;
756   }
757
758   SDNode *&N = UnaryOps[std::make_pair(Opcode, std::make_pair(Operand, VT))];
759   if (N) return SDOperand(N, 0);
760   N = new SDNode(Opcode, Operand);
761   N->setValueTypes(VT);
762   AllNodes.push_back(N);
763   return SDOperand(N, 0);
764 }
765
766 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
767 /// this predicate to simplify operations downstream.  V and Mask are known to
768 /// be the same type.
769 static bool MaskedValueIsZero(const SDOperand &Op, uint64_t Mask,
770                               const TargetLowering &TLI) {
771   unsigned SrcBits;
772   if (Mask == 0) return true;
773
774   // If we know the result of a setcc has the top bits zero, use this info.
775   switch (Op.getOpcode()) {
776   case ISD::UNDEF:
777     return true;
778   case ISD::Constant:
779     return (cast<ConstantSDNode>(Op)->getValue() & Mask) == 0;
780
781   case ISD::SETCC:
782     return ((Mask & 1) == 0) &&
783            TLI.getSetCCResultContents() == TargetLowering::ZeroOrOneSetCCResult;
784
785   case ISD::ZEXTLOAD:
786     SrcBits = MVT::getSizeInBits(cast<VTSDNode>(Op.getOperand(3))->getVT());
787     return (Mask & ((1ULL << SrcBits)-1)) == 0; // Returning only the zext bits.
788   case ISD::ZERO_EXTEND:
789     SrcBits = MVT::getSizeInBits(Op.getOperand(0).getValueType());
790     return MaskedValueIsZero(Op.getOperand(0),Mask & ((1ULL << SrcBits)-1),TLI);
791
792   case ISD::AND:
793     // (X & C1) & C2 == 0   iff   C1 & C2 == 0.
794     if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
795       return MaskedValueIsZero(Op.getOperand(0),AndRHS->getValue() & Mask, TLI);
796
797     // FALL THROUGH
798   case ISD::OR:
799   case ISD::XOR:
800     return MaskedValueIsZero(Op.getOperand(0), Mask, TLI) &&
801            MaskedValueIsZero(Op.getOperand(1), Mask, TLI);
802   case ISD::SELECT:
803     return MaskedValueIsZero(Op.getOperand(1), Mask, TLI) &&
804            MaskedValueIsZero(Op.getOperand(2), Mask, TLI);
805
806   case ISD::SRL:
807     // (ushr X, C1) & C2 == 0   iff  X & (C2 << C1) == 0
808     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
809       uint64_t NewVal = Mask << ShAmt->getValue();
810       SrcBits = MVT::getSizeInBits(Op.getValueType());
811       if (SrcBits != 64) NewVal &= (1ULL << SrcBits)-1;
812       return MaskedValueIsZero(Op.getOperand(0), NewVal, TLI);
813     }
814     return false;
815   case ISD::SHL:
816     // (ushl X, C1) & C2 == 0   iff  X & (C2 >> C1) == 0
817     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
818       uint64_t NewVal = Mask >> ShAmt->getValue();
819       return MaskedValueIsZero(Op.getOperand(0), NewVal, TLI);
820     }
821     return false;
822     // TODO we could handle some SRA cases here.
823   default: break;
824   }
825
826   return false;
827 }
828
829
830
831 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
832                                 SDOperand N1, SDOperand N2) {
833 #ifndef NDEBUG
834   switch (Opcode) {
835   case ISD::TokenFactor:
836     assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
837            N2.getValueType() == MVT::Other && "Invalid token factor!");
838     break;
839   case ISD::AND:
840   case ISD::OR:
841   case ISD::XOR:
842   case ISD::UDIV:
843   case ISD::UREM:
844   case ISD::MULHU:
845   case ISD::MULHS:
846     assert(MVT::isInteger(VT) && "This operator does not apply to FP types!");
847     // fall through
848   case ISD::ADD:
849   case ISD::SUB:
850   case ISD::MUL:
851   case ISD::SDIV:
852   case ISD::SREM:
853     assert(N1.getValueType() == N2.getValueType() &&
854            N1.getValueType() == VT && "Binary operator types must match!");
855     break;
856
857   case ISD::SHL:
858   case ISD::SRA:
859   case ISD::SRL:
860     assert(VT == N1.getValueType() &&
861            "Shift operators return type must be the same as their first arg");
862     assert(MVT::isInteger(VT) && MVT::isInteger(N2.getValueType()) &&
863            VT != MVT::i1 && "Shifts only work on integers");
864     break;
865   case ISD::FP_ROUND_INREG: {
866     MVT::ValueType EVT = cast<VTSDNode>(N2)->getVT();
867     assert(VT == N1.getValueType() && "Not an inreg round!");
868     assert(MVT::isFloatingPoint(VT) && MVT::isFloatingPoint(EVT) &&
869            "Cannot FP_ROUND_INREG integer types");
870     assert(EVT <= VT && "Not rounding down!");
871     break;
872   }
873   case ISD::SIGN_EXTEND_INREG: {
874     MVT::ValueType EVT = cast<VTSDNode>(N2)->getVT();
875     assert(VT == N1.getValueType() && "Not an inreg extend!");
876     assert(MVT::isInteger(VT) && MVT::isInteger(EVT) &&
877            "Cannot *_EXTEND_INREG FP types");
878     assert(EVT <= VT && "Not extending!");
879   }
880
881   default: break;
882   }
883 #endif
884
885   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
886   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
887   if (N1C) {
888     if (N2C) {
889       uint64_t C1 = N1C->getValue(), C2 = N2C->getValue();
890       switch (Opcode) {
891       case ISD::ADD: return getConstant(C1 + C2, VT);
892       case ISD::SUB: return getConstant(C1 - C2, VT);
893       case ISD::MUL: return getConstant(C1 * C2, VT);
894       case ISD::UDIV:
895         if (C2) return getConstant(C1 / C2, VT);
896         break;
897       case ISD::UREM :
898         if (C2) return getConstant(C1 % C2, VT);
899         break;
900       case ISD::SDIV :
901         if (C2) return getConstant(N1C->getSignExtended() /
902                                    N2C->getSignExtended(), VT);
903         break;
904       case ISD::SREM :
905         if (C2) return getConstant(N1C->getSignExtended() %
906                                    N2C->getSignExtended(), VT);
907         break;
908       case ISD::AND  : return getConstant(C1 & C2, VT);
909       case ISD::OR   : return getConstant(C1 | C2, VT);
910       case ISD::XOR  : return getConstant(C1 ^ C2, VT);
911       case ISD::SHL  : return getConstant(C1 << (int)C2, VT);
912       case ISD::SRL  : return getConstant(C1 >> (unsigned)C2, VT);
913       case ISD::SRA  : return getConstant(N1C->getSignExtended() >>(int)C2, VT);
914       default: break;
915       }
916
917     } else {      // Cannonicalize constant to RHS if commutative
918       if (isCommutativeBinOp(Opcode)) {
919         std::swap(N1C, N2C);
920         std::swap(N1, N2);
921       }
922     }
923
924     switch (Opcode) {
925     default: break;
926     case ISD::SHL:    // shl  0, X -> 0
927       if (N1C->isNullValue()) return N1;
928       break;
929     case ISD::SRL:    // srl  0, X -> 0
930       if (N1C->isNullValue()) return N1;
931       break;
932     case ISD::SRA:    // sra -1, X -> -1
933       if (N1C->isAllOnesValue()) return N1;
934       break;
935     case ISD::SIGN_EXTEND_INREG:  // SIGN_EXTEND_INREG N1C, EVT
936       // Extending a constant?  Just return the extended constant.
937       SDOperand Tmp = getNode(ISD::TRUNCATE, cast<VTSDNode>(N2)->getVT(), N1);
938       return getNode(ISD::SIGN_EXTEND, VT, Tmp);
939     }
940   }
941
942   if (N2C) {
943     uint64_t C2 = N2C->getValue();
944
945     switch (Opcode) {
946     case ISD::ADD:
947       if (!C2) return N1;         // add X, 0 -> X
948       break;
949     case ISD::SUB:
950       if (!C2) return N1;         // sub X, 0 -> X
951       return getNode(ISD::ADD, VT, N1, getConstant(-C2, VT));
952     case ISD::MUL:
953       if (!C2) return N2;         // mul X, 0 -> 0
954       if (N2C->isAllOnesValue()) // mul X, -1 -> 0-X
955         return getNode(ISD::SUB, VT, getConstant(0, VT), N1);
956
957       // FIXME: Move this to the DAG combiner when it exists.
958       if ((C2 & C2-1) == 0) {
959         SDOperand ShAmt = getConstant(ExactLog2(C2), TLI.getShiftAmountTy());
960         return getNode(ISD::SHL, VT, N1, ShAmt);
961       }
962       break;
963
964     case ISD::MULHU:
965     case ISD::MULHS:
966       if (!C2) return N2;         // mul X, 0 -> 0
967
968       if (C2 == 1)                // 0X*01 -> 0X  hi(0X) == 0
969         return getConstant(0, VT);
970
971       // Many others could be handled here, including -1, powers of 2, etc.
972       break;
973
974     case ISD::UDIV:
975       // FIXME: Move this to the DAG combiner when it exists.
976       if ((C2 & C2-1) == 0 && C2) {
977         SDOperand ShAmt = getConstant(ExactLog2(C2), TLI.getShiftAmountTy());
978         return getNode(ISD::SRL, VT, N1, ShAmt);
979       }
980       break;
981
982     case ISD::SHL:
983     case ISD::SRL:
984     case ISD::SRA:
985       // If the shift amount is bigger than the size of the data, then all the
986       // bits are shifted out.  Simplify to undef.
987       if (C2 >= MVT::getSizeInBits(N1.getValueType())) {
988         return getNode(ISD::UNDEF, N1.getValueType());
989       }
990       if (C2 == 0) return N1;
991
992       if (Opcode == ISD::SHL && N1.getNumOperands() == 2)
993         if (ConstantSDNode *OpSA = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
994           unsigned OpSAC = OpSA->getValue();
995           if (N1.getOpcode() == ISD::SHL) {
996             if (C2+OpSAC >= MVT::getSizeInBits(N1.getValueType()))
997               return getConstant(0, N1.getValueType());
998             return getNode(ISD::SHL, N1.getValueType(), N1.getOperand(0),
999                            getConstant(C2+OpSAC, N2.getValueType()));
1000           } else if (N1.getOpcode() == ISD::SRL) {
1001             // (X >> C1) << C2:  if C2 > C1, ((X & ~0<<C1) << C2-C1)
1002             SDOperand Mask = getNode(ISD::AND, VT, N1.getOperand(0),
1003                                      getConstant(~0ULL << OpSAC, VT));
1004             if (C2 > OpSAC) {
1005               return getNode(ISD::SHL, VT, Mask,
1006                              getConstant(C2-OpSAC, N2.getValueType()));
1007             } else {
1008               // (X >> C1) << C2:  if C2 <= C1, ((X & ~0<<C1) >> C1-C2)
1009               return getNode(ISD::SRL, VT, Mask,
1010                              getConstant(OpSAC-C2, N2.getValueType()));
1011             }
1012           } else if (N1.getOpcode() == ISD::SRA) {
1013             // if C1 == C2, just mask out low bits.
1014             if (C2 == OpSAC)
1015               return getNode(ISD::AND, VT, N1.getOperand(0),
1016                              getConstant(~0ULL << C2, VT));
1017           }
1018         }
1019       break;
1020
1021     case ISD::AND:
1022       if (!C2) return N2;         // X and 0 -> 0
1023       if (N2C->isAllOnesValue())
1024         return N1;                // X and -1 -> X
1025
1026       if (MaskedValueIsZero(N1, C2, TLI))  // X and 0 -> 0
1027         return getConstant(0, VT);
1028
1029       {
1030         uint64_t NotC2 = ~C2;
1031         if (VT != MVT::i64)
1032           NotC2 &= (1ULL << MVT::getSizeInBits(VT))-1;
1033
1034         if (MaskedValueIsZero(N1, NotC2, TLI))
1035           return N1;                // if (X & ~C2) -> 0, the and is redundant
1036       }
1037
1038       // FIXME: Should add a corresponding version of this for
1039       // ZERO_EXTEND/SIGN_EXTEND by converting them to an ANY_EXTEND node which
1040       // we don't have yet.
1041
1042       // and (sign_extend_inreg x:16:32), 1 -> and x, 1
1043       if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1044         // If we are masking out the part of our input that was extended, just
1045         // mask the input to the extension directly.
1046         unsigned ExtendBits =
1047           MVT::getSizeInBits(cast<VTSDNode>(N1.getOperand(1))->getVT());
1048         if ((C2 & (~0ULL << ExtendBits)) == 0)
1049           return getNode(ISD::AND, VT, N1.getOperand(0), N2);
1050       }
1051       break;
1052     case ISD::OR:
1053       if (!C2)return N1;          // X or 0 -> X
1054       if (N2C->isAllOnesValue())
1055         return N2;                // X or -1 -> -1
1056       break;
1057     case ISD::XOR:
1058       if (!C2) return N1;        // X xor 0 -> X
1059       if (N2C->isAllOnesValue()) {
1060         if (SetCCSDNode *SetCC = dyn_cast<SetCCSDNode>(N1.Val)){
1061           // !(X op Y) -> (X !op Y)
1062           bool isInteger = MVT::isInteger(SetCC->getOperand(0).getValueType());
1063           return getSetCC(ISD::getSetCCInverse(SetCC->getCondition(),isInteger),
1064                           SetCC->getValueType(0),
1065                           SetCC->getOperand(0), SetCC->getOperand(1));
1066         } else if (N1.getOpcode() == ISD::AND || N1.getOpcode() == ISD::OR) {
1067           SDNode *Op = N1.Val;
1068           // !(X or Y) -> (!X and !Y) iff X or Y are freely invertible
1069           // !(X and Y) -> (!X or !Y) iff X or Y are freely invertible
1070           SDOperand LHS = Op->getOperand(0), RHS = Op->getOperand(1);
1071           if (isInvertibleForFree(RHS) || isInvertibleForFree(LHS)) {
1072             LHS = getNode(ISD::XOR, VT, LHS, N2);  // RHS = ~LHS
1073             RHS = getNode(ISD::XOR, VT, RHS, N2);  // RHS = ~RHS
1074             if (Op->getOpcode() == ISD::AND)
1075               return getNode(ISD::OR, VT, LHS, RHS);
1076             return getNode(ISD::AND, VT, LHS, RHS);
1077           }
1078         }
1079         // X xor -1 -> not(x)  ?
1080       }
1081       break;
1082     }
1083
1084     // Reassociate ((X op C1) op C2) if possible.
1085     if (N1.getOpcode() == Opcode && isAssociativeBinOp(Opcode))
1086       if (ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N1.Val->getOperand(1)))
1087         return getNode(Opcode, VT, N1.Val->getOperand(0),
1088                        getNode(Opcode, VT, N2, N1.Val->getOperand(1)));
1089   }
1090
1091   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1.Val);
1092   ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2.Val);
1093   if (N1CFP) {
1094     if (N2CFP) {
1095       double C1 = N1CFP->getValue(), C2 = N2CFP->getValue();
1096       switch (Opcode) {
1097       case ISD::ADD: return getConstantFP(C1 + C2, VT);
1098       case ISD::SUB: return getConstantFP(C1 - C2, VT);
1099       case ISD::MUL: return getConstantFP(C1 * C2, VT);
1100       case ISD::SDIV:
1101         if (C2) return getConstantFP(C1 / C2, VT);
1102         break;
1103       case ISD::SREM :
1104         if (C2) return getConstantFP(fmod(C1, C2), VT);
1105         break;
1106       default: break;
1107       }
1108
1109     } else {      // Cannonicalize constant to RHS if commutative
1110       if (isCommutativeBinOp(Opcode)) {
1111         std::swap(N1CFP, N2CFP);
1112         std::swap(N1, N2);
1113       }
1114     }
1115
1116     if (Opcode == ISD::FP_ROUND_INREG)
1117       return getNode(ISD::FP_EXTEND, VT,
1118                      getNode(ISD::FP_ROUND, cast<VTSDNode>(N2)->getVT(), N1));
1119   }
1120
1121   // Finally, fold operations that do not require constants.
1122   switch (Opcode) {
1123   case ISD::TokenFactor:
1124     if (N1.getOpcode() == ISD::EntryToken)
1125       return N2;
1126     if (N2.getOpcode() == ISD::EntryToken)
1127       return N1;
1128     break;
1129
1130   case ISD::AND:
1131   case ISD::OR:
1132     if (SetCCSDNode *LHS = dyn_cast<SetCCSDNode>(N1.Val))
1133       if (SetCCSDNode *RHS = dyn_cast<SetCCSDNode>(N2.Val)) {
1134         SDOperand LL = LHS->getOperand(0), RL = RHS->getOperand(0);
1135         SDOperand LR = LHS->getOperand(1), RR = RHS->getOperand(1);
1136         ISD::CondCode Op2 = RHS->getCondition();
1137
1138         if (LR == RR && isa<ConstantSDNode>(LR) &&
1139             Op2 == LHS->getCondition() && MVT::isInteger(LL.getValueType())) {
1140           // (X != 0) | (Y != 0) -> (X|Y != 0)
1141           // (X == 0) & (Y == 0) -> (X|Y == 0)
1142           // (X <  0) | (Y <  0) -> (X|Y < 0)
1143           if (cast<ConstantSDNode>(LR)->getValue() == 0 &&
1144               ((Op2 == ISD::SETEQ && Opcode == ISD::AND) ||
1145                (Op2 == ISD::SETNE && Opcode == ISD::OR) ||
1146                (Op2 == ISD::SETLT && Opcode == ISD::OR)))
1147             return getSetCC(Op2, VT,
1148                             getNode(ISD::OR, LR.getValueType(), LL, RL), LR);
1149
1150           if (cast<ConstantSDNode>(LR)->isAllOnesValue()) {
1151             // (X == -1) & (Y == -1) -> (X&Y == -1)
1152             // (X != -1) | (Y != -1) -> (X&Y != -1)
1153             // (X >  -1) | (Y >  -1) -> (X&Y >  -1)
1154             if ((Opcode == ISD::AND && Op2 == ISD::SETEQ) ||
1155                 (Opcode == ISD::OR  && Op2 == ISD::SETNE) ||
1156                 (Opcode == ISD::OR  && Op2 == ISD::SETGT))
1157               return getSetCC(Op2, VT,
1158                             getNode(ISD::AND, LR.getValueType(), LL, RL), LR);
1159             // (X >  -1) & (Y >  -1) -> (X|Y > -1)
1160             if (Opcode == ISD::AND && Op2 == ISD::SETGT)
1161               return getSetCC(Op2, VT,
1162                             getNode(ISD::OR, LR.getValueType(), LL, RL), LR);
1163           }
1164         }
1165
1166         // (X op1 Y) | (Y op2 X) -> (X op1 Y) | (X swapop2 Y)
1167         if (LL == RR && LR == RL) {
1168           Op2 = ISD::getSetCCSwappedOperands(Op2);
1169           goto MatchedBackwards;
1170         }
1171
1172         if (LL == RL && LR == RR) {
1173         MatchedBackwards:
1174           ISD::CondCode Result;
1175           bool isInteger = MVT::isInteger(LL.getValueType());
1176           if (Opcode == ISD::OR)
1177             Result = ISD::getSetCCOrOperation(LHS->getCondition(), Op2,
1178                                               isInteger);
1179           else
1180             Result = ISD::getSetCCAndOperation(LHS->getCondition(), Op2,
1181                                                isInteger);
1182           if (Result != ISD::SETCC_INVALID)
1183             return getSetCC(Result, LHS->getValueType(0), LL, LR);
1184         }
1185       }
1186
1187     // and/or zext(a), zext(b) -> zext(and/or a, b)
1188     if (N1.getOpcode() == ISD::ZERO_EXTEND &&
1189         N2.getOpcode() == ISD::ZERO_EXTEND &&
1190         N1.getOperand(0).getValueType() == N2.getOperand(0).getValueType())
1191       return getNode(ISD::ZERO_EXTEND, VT,
1192                      getNode(Opcode, N1.getOperand(0).getValueType(),
1193                              N1.getOperand(0), N2.getOperand(0)));
1194     break;
1195   case ISD::XOR:
1196     if (N1 == N2) return getConstant(0, VT);  // xor X, Y -> 0
1197     break;
1198   case ISD::ADD:
1199     if (N2.getOpcode() == ISD::FNEG)          // (A+ (-B) -> A-B
1200       return getNode(ISD::SUB, VT, N1, N2.getOperand(0));
1201     if (N1.getOpcode() == ISD::FNEG)          // ((-A)+B) -> B-A
1202       return getNode(ISD::SUB, VT, N2, N1.getOperand(0));
1203     if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1204         cast<ConstantSDNode>(N1.getOperand(0))->getValue() == 0)
1205       return getNode(ISD::SUB, VT, N2, N1.getOperand(1)); // (0-A)+B -> B-A
1206     if (N2.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N2.getOperand(0)) &&
1207         cast<ConstantSDNode>(N2.getOperand(0))->getValue() == 0)
1208       return getNode(ISD::SUB, VT, N1, N2.getOperand(1)); // A+(0-B) -> A-B
1209     if (N2.getOpcode() == ISD::SUB && N1 == N2.Val->getOperand(1) &&
1210         !MVT::isFloatingPoint(N2.getValueType()))
1211       return N2.Val->getOperand(0); // A+(B-A) -> B
1212     break;
1213   case ISD::SUB:
1214     if (N1.getOpcode() == ISD::ADD) {
1215       if (N1.Val->getOperand(0) == N2 && 
1216           !MVT::isFloatingPoint(N2.getValueType()))
1217         return N1.Val->getOperand(1);         // (A+B)-A == B
1218       if (N1.Val->getOperand(1) == N2 &&
1219           !MVT::isFloatingPoint(N2.getValueType()))
1220         return N1.Val->getOperand(0);         // (A+B)-B == A
1221     }
1222     if (N2.getOpcode() == ISD::FNEG)          // (A- (-B) -> A+B
1223       return getNode(ISD::ADD, VT, N1, N2.getOperand(0));
1224     break;
1225   case ISD::FP_ROUND_INREG:
1226     if (cast<VTSDNode>(N2)->getVT() == VT) return N1;  // Not actually rounding.
1227     break;
1228   case ISD::SIGN_EXTEND_INREG: {
1229     MVT::ValueType EVT = cast<VTSDNode>(N2)->getVT();
1230     if (EVT == VT) return N1;  // Not actually extending
1231
1232     // If we are sign extending an extension, use the original source.
1233     if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG)
1234       if (cast<VTSDNode>(N1.getOperand(1))->getVT() <= EVT)
1235         return N1;
1236     
1237     // If we are sign extending a sextload, return just the load.
1238     if (N1.getOpcode() == ISD::SEXTLOAD)
1239       if (cast<VTSDNode>(N1.getOperand(3))->getVT() <= EVT)
1240         return N1;
1241
1242     // If we are extending the result of a setcc, and we already know the
1243     // contents of the top bits, eliminate the extension.
1244     if (N1.getOpcode() == ISD::SETCC &&
1245         TLI.getSetCCResultContents() ==
1246                         TargetLowering::ZeroOrNegativeOneSetCCResult)
1247       return N1;
1248
1249     // If we are sign extending the result of an (and X, C) operation, and we
1250     // know the extended bits are zeros already, don't do the extend.
1251     if (N1.getOpcode() == ISD::AND)
1252       if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
1253         uint64_t Mask = N1C->getValue();
1254         unsigned NumBits = MVT::getSizeInBits(EVT);
1255         if ((Mask & (~0ULL << (NumBits-1))) == 0)
1256           return N1;
1257       }
1258     break;
1259   }
1260
1261   // FIXME: figure out how to safely handle things like
1262   // int foo(int x) { return 1 << (x & 255); }
1263   // int bar() { return foo(256); }
1264 #if 0
1265   case ISD::SHL:
1266   case ISD::SRL:
1267   case ISD::SRA:
1268     if (N2.getOpcode() == ISD::SIGN_EXTEND_INREG &&
1269         cast<VTSDNode>(N2.getOperand(1))->getVT() != MVT::i1)
1270       return getNode(Opcode, VT, N1, N2.getOperand(0));
1271     else if (N2.getOpcode() == ISD::AND)
1272       if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N2.getOperand(1))) {
1273         // If the and is only masking out bits that cannot effect the shift,
1274         // eliminate the and.
1275         unsigned NumBits = MVT::getSizeInBits(VT);
1276         if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
1277           return getNode(Opcode, VT, N1, N2.getOperand(0));
1278       }
1279     break;
1280 #endif
1281   }
1282
1283   // Memoize this node if possible.
1284   SDNode *N;
1285   if (Opcode != ISD::CALLSEQ_START && Opcode != ISD::CALLSEQ_END) {
1286     SDNode *&BON = BinaryOps[std::make_pair(Opcode, std::make_pair(N1, N2))];
1287     if (BON) return SDOperand(BON, 0);
1288
1289     BON = N = new SDNode(Opcode, N1, N2);
1290   } else {
1291     N = new SDNode(Opcode, N1, N2);
1292   }
1293
1294   N->setValueTypes(VT);
1295   AllNodes.push_back(N);
1296   return SDOperand(N, 0);
1297 }
1298
1299 // setAdjCallChain - This method changes the token chain of an
1300 // CALLSEQ_START/END node to be the specified operand.
1301 void SDNode::setAdjCallChain(SDOperand N) {
1302   assert(N.getValueType() == MVT::Other);
1303   assert((getOpcode() == ISD::CALLSEQ_START ||
1304           getOpcode() == ISD::CALLSEQ_END) && "Cannot adjust this node!");
1305
1306   Operands[0].Val->removeUser(this);
1307   Operands[0] = N;
1308   N.Val->Uses.push_back(this);
1309 }
1310
1311
1312
1313 SDOperand SelectionDAG::getLoad(MVT::ValueType VT,
1314                                 SDOperand Chain, SDOperand Ptr, 
1315                                 SDOperand SV) {
1316   SDNode *&N = Loads[std::make_pair(Ptr, std::make_pair(Chain, VT))];
1317   if (N) return SDOperand(N, 0);
1318   N = new SDNode(ISD::LOAD, Chain, Ptr, SV);
1319
1320   // Loads have a token chain.
1321   N->setValueTypes(VT, MVT::Other);
1322   AllNodes.push_back(N);
1323   return SDOperand(N, 0);
1324 }
1325
1326
1327 SDOperand SelectionDAG::getExtLoad(unsigned Opcode, MVT::ValueType VT,
1328                                    SDOperand Chain, SDOperand Ptr, SDOperand SV,
1329                                    MVT::ValueType EVT) {
1330   std::vector<SDOperand> Ops;
1331   Ops.reserve(4);
1332   Ops.push_back(Chain);
1333   Ops.push_back(Ptr);
1334   Ops.push_back(SV);
1335   Ops.push_back(getValueType(EVT));
1336   std::vector<MVT::ValueType> VTs;
1337   VTs.reserve(2);
1338   VTs.push_back(VT); VTs.push_back(MVT::Other);  // Add token chain.
1339   return getNode(Opcode, VTs, Ops);
1340 }
1341
1342 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
1343                                 SDOperand N1, SDOperand N2, SDOperand N3) {
1344   // Perform various simplifications.
1345   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1346   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
1347   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.Val);
1348   switch (Opcode) {
1349   case ISD::SELECT:
1350     if (N1C)
1351       if (N1C->getValue())
1352         return N2;             // select true, X, Y -> X
1353       else
1354         return N3;             // select false, X, Y -> Y
1355
1356     if (N2 == N3) return N2;   // select C, X, X -> X
1357
1358     if (VT == MVT::i1) {  // Boolean SELECT
1359       if (N2C) {
1360         if (N2C->getValue())   // select C, 1, X -> C | X
1361           return getNode(ISD::OR, VT, N1, N3);
1362         else                   // select C, 0, X -> ~C & X
1363           return getNode(ISD::AND, VT,
1364                          getNode(ISD::XOR, N1.getValueType(), N1,
1365                                  getConstant(1, N1.getValueType())), N3);
1366       } else if (N3C) {
1367         if (N3C->getValue())   // select C, X, 1 -> ~C | X
1368           return getNode(ISD::OR, VT,
1369                          getNode(ISD::XOR, N1.getValueType(), N1,
1370                                  getConstant(1, N1.getValueType())), N2);
1371         else                   // select C, X, 0 -> C & X
1372           return getNode(ISD::AND, VT, N1, N2);
1373       }
1374
1375       if (N1 == N2)   // X ? X : Y --> X ? 1 : Y --> X | Y
1376         return getNode(ISD::OR, VT, N1, N3);
1377       if (N1 == N3)   // X ? Y : X --> X ? Y : 0 --> X & Y
1378         return getNode(ISD::AND, VT, N1, N2);
1379     }
1380
1381     // If this is a selectcc, check to see if we can simplify the result.
1382     if (SetCCSDNode *SetCC = dyn_cast<SetCCSDNode>(N1)) {
1383       if (ConstantFPSDNode *CFP =
1384           dyn_cast<ConstantFPSDNode>(SetCC->getOperand(1)))
1385         if (CFP->getValue() == 0.0) {   // Allow either -0.0 or 0.0
1386           // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
1387           if ((SetCC->getCondition() == ISD::SETGE ||
1388                SetCC->getCondition() == ISD::SETGT) &&
1389               N2 == SetCC->getOperand(0) && N3.getOpcode() == ISD::FNEG &&
1390               N3.getOperand(0) == N2)
1391             return getNode(ISD::FABS, VT, N2);
1392
1393           // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
1394           if ((SetCC->getCondition() == ISD::SETLT ||
1395                SetCC->getCondition() == ISD::SETLE) &&
1396               N3 == SetCC->getOperand(0) && N2.getOpcode() == ISD::FNEG &&
1397               N2.getOperand(0) == N3)
1398             return getNode(ISD::FABS, VT, N3);
1399         }
1400       // select (setlt X, 0), A, 0 -> and (sra X, size(X)-1), A
1401       if (ConstantSDNode *CN =
1402           dyn_cast<ConstantSDNode>(SetCC->getOperand(1)))
1403         if (CN->getValue() == 0 && N3C && N3C->getValue() == 0)
1404           if (SetCC->getCondition() == ISD::SETLT) {
1405             MVT::ValueType XType = SetCC->getOperand(0).getValueType();
1406             MVT::ValueType AType = N2.getValueType();
1407             if (XType >= AType) {
1408               // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
1409               // single-bit constant.  FIXME: remove once the dag combiner
1410               // exists.
1411               if (ConstantSDNode *AC = dyn_cast<ConstantSDNode>(N2))
1412                 if ((AC->getValue() & (AC->getValue()-1)) == 0) {
1413                   unsigned ShCtV = ExactLog2(AC->getValue());
1414                   ShCtV = MVT::getSizeInBits(XType)-ShCtV-1;
1415                   SDOperand ShCt = getConstant(ShCtV, TLI.getShiftAmountTy());
1416                   SDOperand Shift = getNode(ISD::SRL, XType,
1417                                             SetCC->getOperand(0), ShCt);
1418                   if (XType > AType)
1419                     Shift = getNode(ISD::TRUNCATE, AType, Shift);
1420                   return getNode(ISD::AND, AType, Shift, N2);
1421                 }
1422
1423
1424               SDOperand Shift = getNode(ISD::SRA, XType, SetCC->getOperand(0),
1425                 getConstant(MVT::getSizeInBits(XType)-1,
1426                             TLI.getShiftAmountTy()));
1427               if (XType > AType)
1428                 Shift = getNode(ISD::TRUNCATE, AType, Shift);
1429               return getNode(ISD::AND, AType, Shift, N2);
1430             }
1431           }
1432     }
1433     break;
1434   case ISD::BRCOND:
1435     if (N2C)
1436       if (N2C->getValue()) // Unconditional branch
1437         return getNode(ISD::BR, MVT::Other, N1, N3);
1438       else
1439         return N1;         // Never-taken branch
1440     break;
1441   }
1442
1443   std::vector<SDOperand> Ops;
1444   Ops.reserve(3);
1445   Ops.push_back(N1);
1446   Ops.push_back(N2);
1447   Ops.push_back(N3);
1448
1449   // Memoize nodes.
1450   SDNode *&N = OneResultNodes[std::make_pair(Opcode, std::make_pair(VT, Ops))];
1451   if (N) return SDOperand(N, 0);
1452
1453   N = new SDNode(Opcode, N1, N2, N3);
1454   N->setValueTypes(VT);
1455   AllNodes.push_back(N);
1456   return SDOperand(N, 0);
1457 }
1458
1459 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
1460                                 SDOperand N1, SDOperand N2, SDOperand N3, 
1461                                 SDOperand N4) {
1462   std::vector<SDOperand> Ops;
1463   Ops.reserve(4);
1464   Ops.push_back(N1);
1465   Ops.push_back(N2);
1466   Ops.push_back(N3);
1467   Ops.push_back(N4);
1468   return getNode(Opcode, VT, Ops);
1469 }
1470
1471 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
1472                                 SDOperand N1, SDOperand N2, SDOperand N3,
1473                                 SDOperand N4, SDOperand N5) {
1474   std::vector<SDOperand> Ops;
1475   Ops.reserve(5);
1476   Ops.push_back(N1);
1477   Ops.push_back(N2);
1478   Ops.push_back(N3);
1479   Ops.push_back(N4);
1480   Ops.push_back(N5);
1481   return getNode(Opcode, VT, Ops);
1482 }
1483
1484
1485 SDOperand SelectionDAG::getSrcValue(const Value *V, int Offset) {
1486   assert((!V || isa<PointerType>(V->getType())) &&
1487          "SrcValue is not a pointer?");
1488   SDNode *&N = ValueNodes[std::make_pair(V, Offset)];
1489   if (N) return SDOperand(N, 0);
1490
1491   N = new SrcValueSDNode(V, Offset);
1492   AllNodes.push_back(N);
1493   return SDOperand(N, 0);
1494 }
1495
1496 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
1497                                 std::vector<SDOperand> &Ops) {
1498   switch (Ops.size()) {
1499   case 0: return getNode(Opcode, VT);
1500   case 1: return getNode(Opcode, VT, Ops[0]);
1501   case 2: return getNode(Opcode, VT, Ops[0], Ops[1]);
1502   case 3: return getNode(Opcode, VT, Ops[0], Ops[1], Ops[2]);
1503   default: break;
1504   }
1505
1506   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Ops[1].Val);
1507   switch (Opcode) {
1508   default: break;
1509   case ISD::BRCONDTWOWAY:
1510     if (N1C)
1511       if (N1C->getValue()) // Unconditional branch to true dest.
1512         return getNode(ISD::BR, MVT::Other, Ops[0], Ops[2]);
1513       else                 // Unconditional branch to false dest.
1514         return getNode(ISD::BR, MVT::Other, Ops[0], Ops[3]);
1515     break;
1516
1517   case ISD::TRUNCSTORE: {
1518     assert(Ops.size() == 5 && "TRUNCSTORE takes 5 operands!");
1519     MVT::ValueType EVT = cast<VTSDNode>(Ops[4])->getVT();
1520 #if 0 // FIXME: If the target supports EVT natively, convert to a truncate/store
1521     // If this is a truncating store of a constant, convert to the desired type
1522     // and store it instead.
1523     if (isa<Constant>(Ops[0])) {
1524       SDOperand Op = getNode(ISD::TRUNCATE, EVT, N1);
1525       if (isa<Constant>(Op))
1526         N1 = Op;
1527     }
1528     // Also for ConstantFP?
1529 #endif
1530     if (Ops[0].getValueType() == EVT)       // Normal store?
1531       return getNode(ISD::STORE, VT, Ops[0], Ops[1], Ops[2], Ops[3]);
1532     assert(Ops[1].getValueType() > EVT && "Not a truncation?");
1533     assert(MVT::isInteger(Ops[1].getValueType()) == MVT::isInteger(EVT) &&
1534            "Can't do FP-INT conversion!");
1535     break;
1536   }
1537   }
1538
1539   // Memoize nodes.
1540   SDNode *&N = OneResultNodes[std::make_pair(Opcode, std::make_pair(VT, Ops))];
1541   if (N) return SDOperand(N, 0);
1542   N = new SDNode(Opcode, Ops);
1543   N->setValueTypes(VT);
1544   AllNodes.push_back(N);
1545   return SDOperand(N, 0);
1546 }
1547
1548 SDOperand SelectionDAG::getNode(unsigned Opcode,
1549                                 std::vector<MVT::ValueType> &ResultTys,
1550                                 std::vector<SDOperand> &Ops) {
1551   if (ResultTys.size() == 1)
1552     return getNode(Opcode, ResultTys[0], Ops);
1553
1554   switch (Opcode) {
1555   case ISD::EXTLOAD:
1556   case ISD::SEXTLOAD:
1557   case ISD::ZEXTLOAD: {
1558     MVT::ValueType EVT = cast<VTSDNode>(Ops[3])->getVT();
1559     assert(Ops.size() == 4 && ResultTys.size() == 2 && "Bad *EXTLOAD!");
1560     // If they are asking for an extending load from/to the same thing, return a
1561     // normal load.
1562     if (ResultTys[0] == EVT)
1563       return getLoad(ResultTys[0], Ops[0], Ops[1], Ops[2]);
1564     assert(EVT < ResultTys[0] &&
1565            "Should only be an extending load, not truncating!");
1566     assert((Opcode == ISD::EXTLOAD || MVT::isInteger(ResultTys[0])) &&
1567            "Cannot sign/zero extend a FP load!");
1568     assert(MVT::isInteger(ResultTys[0]) == MVT::isInteger(EVT) &&
1569            "Cannot convert from FP to Int or Int -> FP!");
1570     break;
1571   }
1572
1573   // FIXME: figure out how to safely handle things like
1574   // int foo(int x) { return 1 << (x & 255); }
1575   // int bar() { return foo(256); }
1576 #if 0
1577   case ISD::SRA_PARTS:
1578   case ISD::SRL_PARTS:
1579   case ISD::SHL_PARTS:
1580     if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
1581         cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
1582       return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
1583     else if (N3.getOpcode() == ISD::AND)
1584       if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
1585         // If the and is only masking out bits that cannot effect the shift,
1586         // eliminate the and.
1587         unsigned NumBits = MVT::getSizeInBits(VT)*2;
1588         if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
1589           return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
1590       }
1591     break;
1592 #endif
1593   }
1594
1595   // Memoize the node.
1596   SDNode *&N = ArbitraryNodes[std::make_pair(Opcode, std::make_pair(ResultTys,
1597                                                                     Ops))];
1598   if (N) return SDOperand(N, 0);
1599   N = new SDNode(Opcode, Ops);
1600   N->setValueTypes(ResultTys);
1601   AllNodes.push_back(N);
1602   return SDOperand(N, 0);
1603 }
1604
1605 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
1606 /// indicated value.  This method ignores uses of other values defined by this
1607 /// operation.
1608 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) {
1609   assert(Value < getNumValues() && "Bad value!");
1610
1611   // If there is only one value, this is easy.
1612   if (getNumValues() == 1)
1613     return use_size() == NUses;
1614   if (Uses.size() < NUses) return false;
1615
1616   SDOperand TheValue(this, Value);
1617
1618   std::set<SDNode*> UsersHandled;
1619
1620   for (std::vector<SDNode*>::iterator UI = Uses.begin(), E = Uses.end();
1621        UI != E; ++UI) {
1622     SDNode *User = *UI;
1623     if (User->getNumOperands() == 1 ||
1624         UsersHandled.insert(User).second)     // First time we've seen this?
1625       for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
1626         if (User->getOperand(i) == TheValue) {
1627           if (NUses == 0)
1628             return false;   // too many uses
1629           --NUses;
1630         }
1631   }
1632
1633   // Found exactly the right number of uses?
1634   return NUses == 0;
1635 }
1636
1637
1638 const char *SDNode::getOperationName() const {
1639   switch (getOpcode()) {
1640   default: return "<<Unknown>>";
1641   case ISD::PCMARKER:      return "PCMarker";
1642   case ISD::SRCVALUE:      return "SrcValue";
1643   case ISD::EntryToken:    return "EntryToken";
1644   case ISD::TokenFactor:   return "TokenFactor";
1645   case ISD::Constant:      return "Constant";
1646   case ISD::ConstantFP:    return "ConstantFP";
1647   case ISD::GlobalAddress: return "GlobalAddress";
1648   case ISD::FrameIndex:    return "FrameIndex";
1649   case ISD::BasicBlock:    return "BasicBlock";
1650   case ISD::ExternalSymbol: return "ExternalSymbol";
1651   case ISD::ConstantPool:  return "ConstantPoolIndex";
1652   case ISD::CopyToReg:     return "CopyToReg";
1653   case ISD::CopyFromReg:   return "CopyFromReg";
1654   case ISD::ImplicitDef:   return "ImplicitDef";
1655   case ISD::UNDEF:         return "undef";
1656
1657   // Unary operators
1658   case ISD::FABS:   return "fabs";
1659   case ISD::FNEG:   return "fneg";
1660   case ISD::FSQRT:  return "fsqrt";
1661   case ISD::FSIN:   return "fsin";
1662   case ISD::FCOS:   return "fcos";
1663
1664   // Binary operators
1665   case ISD::ADD:    return "add";
1666   case ISD::SUB:    return "sub";
1667   case ISD::MUL:    return "mul";
1668   case ISD::MULHU:  return "mulhu";
1669   case ISD::MULHS:  return "mulhs";
1670   case ISD::SDIV:   return "sdiv";
1671   case ISD::UDIV:   return "udiv";
1672   case ISD::SREM:   return "srem";
1673   case ISD::UREM:   return "urem";
1674   case ISD::AND:    return "and";
1675   case ISD::OR:     return "or";
1676   case ISD::XOR:    return "xor";
1677   case ISD::SHL:    return "shl";
1678   case ISD::SRA:    return "sra";
1679   case ISD::SRL:    return "srl";
1680
1681   case ISD::SELECT: return "select";
1682   case ISD::ADD_PARTS:   return "add_parts";
1683   case ISD::SUB_PARTS:   return "sub_parts";
1684   case ISD::SHL_PARTS:   return "shl_parts";
1685   case ISD::SRA_PARTS:   return "sra_parts";
1686   case ISD::SRL_PARTS:   return "srl_parts";
1687
1688   // Conversion operators.
1689   case ISD::SIGN_EXTEND: return "sign_extend";
1690   case ISD::ZERO_EXTEND: return "zero_extend";
1691   case ISD::SIGN_EXTEND_INREG: return "sign_extend_inreg";
1692   case ISD::TRUNCATE:    return "truncate";
1693   case ISD::FP_ROUND:    return "fp_round";
1694   case ISD::FP_ROUND_INREG: return "fp_round_inreg";
1695   case ISD::FP_EXTEND:   return "fp_extend";
1696
1697   case ISD::SINT_TO_FP:  return "sint_to_fp";
1698   case ISD::UINT_TO_FP:  return "uint_to_fp";
1699   case ISD::FP_TO_SINT:  return "fp_to_sint";
1700   case ISD::FP_TO_UINT:  return "fp_to_uint";
1701
1702     // Control flow instructions
1703   case ISD::BR:      return "br";
1704   case ISD::BRCOND:  return "brcond";
1705   case ISD::BRCONDTWOWAY:  return "brcondtwoway";
1706   case ISD::RET:     return "ret";
1707   case ISD::CALL:    return "call";
1708   case ISD::TAILCALL:return "tailcall";
1709   case ISD::CALLSEQ_START:  return "callseq_start";
1710   case ISD::CALLSEQ_END:    return "callseq_end";
1711
1712     // Other operators
1713   case ISD::LOAD:    return "load";
1714   case ISD::STORE:   return "store";
1715   case ISD::EXTLOAD:    return "extload";
1716   case ISD::SEXTLOAD:   return "sextload";
1717   case ISD::ZEXTLOAD:   return "zextload";
1718   case ISD::TRUNCSTORE: return "truncstore";
1719
1720   case ISD::DYNAMIC_STACKALLOC: return "dynamic_stackalloc";
1721   case ISD::EXTRACT_ELEMENT: return "extract_element";
1722   case ISD::BUILD_PAIR: return "build_pair";
1723   case ISD::MEMSET:  return "memset";
1724   case ISD::MEMCPY:  return "memcpy";
1725   case ISD::MEMMOVE: return "memmove";
1726
1727   // Bit counting
1728   case ISD::CTPOP:   return "ctpop";
1729   case ISD::CTTZ:    return "cttz";
1730   case ISD::CTLZ:    return "ctlz";
1731
1732   // IO Intrinsics
1733   case ISD::READPORT: return "readport";
1734   case ISD::WRITEPORT: return "writeport";
1735   case ISD::READIO: return "readio";
1736   case ISD::WRITEIO: return "writeio";
1737
1738   case ISD::SETCC:
1739     const SetCCSDNode *SetCC = cast<SetCCSDNode>(this);
1740     switch (SetCC->getCondition()) {
1741     default: assert(0 && "Unknown setcc condition!");
1742     case ISD::SETOEQ:  return "setcc:setoeq";
1743     case ISD::SETOGT:  return "setcc:setogt";
1744     case ISD::SETOGE:  return "setcc:setoge";
1745     case ISD::SETOLT:  return "setcc:setolt";
1746     case ISD::SETOLE:  return "setcc:setole";
1747     case ISD::SETONE:  return "setcc:setone";
1748
1749     case ISD::SETO:    return "setcc:seto";
1750     case ISD::SETUO:   return "setcc:setuo";
1751     case ISD::SETUEQ:  return "setcc:setue";
1752     case ISD::SETUGT:  return "setcc:setugt";
1753     case ISD::SETUGE:  return "setcc:setuge";
1754     case ISD::SETULT:  return "setcc:setult";
1755     case ISD::SETULE:  return "setcc:setule";
1756     case ISD::SETUNE:  return "setcc:setune";
1757
1758     case ISD::SETEQ:   return "setcc:seteq";
1759     case ISD::SETGT:   return "setcc:setgt";
1760     case ISD::SETGE:   return "setcc:setge";
1761     case ISD::SETLT:   return "setcc:setlt";
1762     case ISD::SETLE:   return "setcc:setle";
1763     case ISD::SETNE:   return "setcc:setne";
1764     }
1765   }
1766 }
1767
1768 void SDNode::dump() const {
1769   std::cerr << (void*)this << ": ";
1770
1771   for (unsigned i = 0, e = getNumValues(); i != e; ++i) {
1772     if (i) std::cerr << ",";
1773     if (getValueType(i) == MVT::Other)
1774       std::cerr << "ch";
1775     else
1776       std::cerr << MVT::getValueTypeString(getValueType(i));
1777   }
1778   std::cerr << " = " << getOperationName();
1779
1780   std::cerr << " ";
1781   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1782     if (i) std::cerr << ", ";
1783     std::cerr << (void*)getOperand(i).Val;
1784     if (unsigned RN = getOperand(i).ResNo)
1785       std::cerr << ":" << RN;
1786   }
1787
1788   if (const ConstantSDNode *CSDN = dyn_cast<ConstantSDNode>(this)) {
1789     std::cerr << "<" << CSDN->getValue() << ">";
1790   } else if (const ConstantFPSDNode *CSDN = dyn_cast<ConstantFPSDNode>(this)) {
1791     std::cerr << "<" << CSDN->getValue() << ">";
1792   } else if (const GlobalAddressSDNode *GADN =
1793              dyn_cast<GlobalAddressSDNode>(this)) {
1794     std::cerr << "<";
1795     WriteAsOperand(std::cerr, GADN->getGlobal()) << ">";
1796   } else if (const FrameIndexSDNode *FIDN = dyn_cast<FrameIndexSDNode>(this)) {
1797     std::cerr << "<" << FIDN->getIndex() << ">";
1798   } else if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(this)){
1799     std::cerr << "<" << CP->getIndex() << ">";
1800   } else if (const BasicBlockSDNode *BBDN = dyn_cast<BasicBlockSDNode>(this)) {
1801     std::cerr << "<";
1802     const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock();
1803     if (LBB)
1804       std::cerr << LBB->getName() << " ";
1805     std::cerr << (const void*)BBDN->getBasicBlock() << ">";
1806   } else if (const RegSDNode *C2V = dyn_cast<RegSDNode>(this)) {
1807     std::cerr << "<reg #" << C2V->getReg() << ">";
1808   } else if (const ExternalSymbolSDNode *ES =
1809              dyn_cast<ExternalSymbolSDNode>(this)) {
1810     std::cerr << "'" << ES->getSymbol() << "'";
1811   } else if (const SrcValueSDNode *M = dyn_cast<SrcValueSDNode>(this)) {
1812     if (M->getValue())
1813       std::cerr << "<" << M->getValue() << ":" << M->getOffset() << ">";
1814     else
1815       std::cerr << "<null:" << M->getOffset() << ">";
1816   }
1817 }
1818
1819 static void DumpNodes(SDNode *N, unsigned indent) {
1820   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1821     if (N->getOperand(i).Val->hasOneUse())
1822       DumpNodes(N->getOperand(i).Val, indent+2);
1823     else
1824       std::cerr << "\n" << std::string(indent+2, ' ')
1825                 << (void*)N->getOperand(i).Val << ": <multiple use>";
1826
1827
1828   std::cerr << "\n" << std::string(indent, ' ');
1829   N->dump();
1830 }
1831
1832 void SelectionDAG::dump() const {
1833   std::cerr << "SelectionDAG has " << AllNodes.size() << " nodes:";
1834   std::vector<SDNode*> Nodes(AllNodes);
1835   std::sort(Nodes.begin(), Nodes.end());
1836
1837   for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
1838     if (!Nodes[i]->hasOneUse() && Nodes[i] != getRoot().Val)
1839       DumpNodes(Nodes[i], 2);
1840   }
1841
1842   DumpNodes(getRoot().Val, 2);
1843
1844   std::cerr << "\n\n";
1845 }
1846