bca5e756d457a3a267752336cd0b36f42fafab3c
[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 is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This implements the SelectionDAG class.
11 //
12 //===----------------------------------------------------------------------===//
13 #include "llvm/CodeGen/SelectionDAG.h"
14 #include "llvm/Constants.h"
15 #include "llvm/GlobalAlias.h"
16 #include "llvm/GlobalVariable.h"
17 #include "llvm/Intrinsics.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Assembly/Writer.h"
20 #include "llvm/CallingConv.h"
21 #include "llvm/CodeGen/MachineBasicBlock.h"
22 #include "llvm/CodeGen/MachineConstantPool.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineModuleInfo.h"
25 #include "llvm/CodeGen/PseudoSourceValue.h"
26 #include "llvm/Support/MathExtras.h"
27 #include "llvm/Target/TargetRegisterInfo.h"
28 #include "llvm/Target/TargetData.h"
29 #include "llvm/Target/TargetLowering.h"
30 #include "llvm/Target/TargetInstrInfo.h"
31 #include "llvm/Target/TargetMachine.h"
32 #include "llvm/ADT/SetVector.h"
33 #include "llvm/ADT/SmallPtrSet.h"
34 #include "llvm/ADT/SmallSet.h"
35 #include "llvm/ADT/SmallVector.h"
36 #include "llvm/ADT/StringExtras.h"
37 #include <algorithm>
38 #include <cmath>
39 using namespace llvm;
40
41 /// makeVTList - Return an instance of the SDVTList struct initialized with the
42 /// specified members.
43 static SDVTList makeVTList(const MVT *VTs, unsigned NumVTs) {
44   SDVTList Res = {VTs, NumVTs};
45   return Res;
46 }
47
48 static const fltSemantics *MVTToAPFloatSemantics(MVT VT) {
49   switch (VT.getSimpleVT()) {
50   default: assert(0 && "Unknown FP format");
51   case MVT::f32:     return &APFloat::IEEEsingle;
52   case MVT::f64:     return &APFloat::IEEEdouble;
53   case MVT::f80:     return &APFloat::x87DoubleExtended;
54   case MVT::f128:    return &APFloat::IEEEquad;
55   case MVT::ppcf128: return &APFloat::PPCDoubleDouble;
56   }
57 }
58
59 SelectionDAG::DAGUpdateListener::~DAGUpdateListener() {}
60
61 //===----------------------------------------------------------------------===//
62 //                              ConstantFPSDNode Class
63 //===----------------------------------------------------------------------===//
64
65 /// isExactlyValue - We don't rely on operator== working on double values, as
66 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
67 /// As such, this method can be used to do an exact bit-for-bit comparison of
68 /// two floating point values.
69 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
70   return Value.bitwiseIsEqual(V);
71 }
72
73 bool ConstantFPSDNode::isValueValidForType(MVT VT,
74                                            const APFloat& Val) {
75   assert(VT.isFloatingPoint() && "Can only convert between FP types");
76   
77   // PPC long double cannot be converted to any other type.
78   if (VT == MVT::ppcf128 ||
79       &Val.getSemantics() == &APFloat::PPCDoubleDouble)
80     return false;
81   
82   // convert modifies in place, so make a copy.
83   APFloat Val2 = APFloat(Val);
84   return Val2.convert(*MVTToAPFloatSemantics(VT),
85                       APFloat::rmNearestTiesToEven) == APFloat::opOK;
86 }
87
88 //===----------------------------------------------------------------------===//
89 //                              ISD Namespace
90 //===----------------------------------------------------------------------===//
91
92 /// isBuildVectorAllOnes - Return true if the specified node is a
93 /// BUILD_VECTOR where all of the elements are ~0 or undef.
94 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
95   // Look through a bit convert.
96   if (N->getOpcode() == ISD::BIT_CONVERT)
97     N = N->getOperand(0).Val;
98   
99   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
100   
101   unsigned i = 0, e = N->getNumOperands();
102   
103   // Skip over all of the undef values.
104   while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
105     ++i;
106   
107   // Do not accept an all-undef vector.
108   if (i == e) return false;
109   
110   // Do not accept build_vectors that aren't all constants or which have non-~0
111   // elements.
112   SDOperand NotZero = N->getOperand(i);
113   if (isa<ConstantSDNode>(NotZero)) {
114     if (!cast<ConstantSDNode>(NotZero)->isAllOnesValue())
115       return false;
116   } else if (isa<ConstantFPSDNode>(NotZero)) {
117     if (!cast<ConstantFPSDNode>(NotZero)->getValueAPF().
118                 convertToAPInt().isAllOnesValue())
119       return false;
120   } else
121     return false;
122   
123   // Okay, we have at least one ~0 value, check to see if the rest match or are
124   // undefs.
125   for (++i; i != e; ++i)
126     if (N->getOperand(i) != NotZero &&
127         N->getOperand(i).getOpcode() != ISD::UNDEF)
128       return false;
129   return true;
130 }
131
132
133 /// isBuildVectorAllZeros - Return true if the specified node is a
134 /// BUILD_VECTOR where all of the elements are 0 or undef.
135 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
136   // Look through a bit convert.
137   if (N->getOpcode() == ISD::BIT_CONVERT)
138     N = N->getOperand(0).Val;
139   
140   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
141   
142   unsigned i = 0, e = N->getNumOperands();
143   
144   // Skip over all of the undef values.
145   while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
146     ++i;
147   
148   // Do not accept an all-undef vector.
149   if (i == e) return false;
150   
151   // Do not accept build_vectors that aren't all constants or which have non-~0
152   // elements.
153   SDOperand Zero = N->getOperand(i);
154   if (isa<ConstantSDNode>(Zero)) {
155     if (!cast<ConstantSDNode>(Zero)->isNullValue())
156       return false;
157   } else if (isa<ConstantFPSDNode>(Zero)) {
158     if (!cast<ConstantFPSDNode>(Zero)->getValueAPF().isPosZero())
159       return false;
160   } else
161     return false;
162   
163   // Okay, we have at least one ~0 value, check to see if the rest match or are
164   // undefs.
165   for (++i; i != e; ++i)
166     if (N->getOperand(i) != Zero &&
167         N->getOperand(i).getOpcode() != ISD::UNDEF)
168       return false;
169   return true;
170 }
171
172 /// isScalarToVector - Return true if the specified node is a
173 /// ISD::SCALAR_TO_VECTOR node or a BUILD_VECTOR node where only the low
174 /// element is not an undef.
175 bool ISD::isScalarToVector(const SDNode *N) {
176   if (N->getOpcode() == ISD::SCALAR_TO_VECTOR)
177     return true;
178
179   if (N->getOpcode() != ISD::BUILD_VECTOR)
180     return false;
181   if (N->getOperand(0).getOpcode() == ISD::UNDEF)
182     return false;
183   unsigned NumElems = N->getNumOperands();
184   for (unsigned i = 1; i < NumElems; ++i) {
185     SDOperand V = N->getOperand(i);
186     if (V.getOpcode() != ISD::UNDEF)
187       return false;
188   }
189   return true;
190 }
191
192
193 /// isDebugLabel - Return true if the specified node represents a debug
194 /// label (i.e. ISD::LABEL or TargetInstrInfo::LABEL node and third operand
195 /// is 0).
196 bool ISD::isDebugLabel(const SDNode *N) {
197   SDOperand Zero;
198   if (N->getOpcode() == ISD::LABEL)
199     Zero = N->getOperand(2);
200   else if (N->isTargetOpcode() &&
201            N->getTargetOpcode() == TargetInstrInfo::LABEL)
202     // Chain moved to last operand.
203     Zero = N->getOperand(1);
204   else
205     return false;
206   return isa<ConstantSDNode>(Zero) && cast<ConstantSDNode>(Zero)->isNullValue();
207 }
208
209 /// getSetCCSwappedOperands - Return the operation corresponding to (Y op X)
210 /// when given the operation for (X op Y).
211 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
212   // To perform this operation, we just need to swap the L and G bits of the
213   // operation.
214   unsigned OldL = (Operation >> 2) & 1;
215   unsigned OldG = (Operation >> 1) & 1;
216   return ISD::CondCode((Operation & ~6) |  // Keep the N, U, E bits
217                        (OldL << 1) |       // New G bit
218                        (OldG << 2));        // New L bit.
219 }
220
221 /// getSetCCInverse - Return the operation corresponding to !(X op Y), where
222 /// 'op' is a valid SetCC operation.
223 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) {
224   unsigned Operation = Op;
225   if (isInteger)
226     Operation ^= 7;   // Flip L, G, E bits, but not U.
227   else
228     Operation ^= 15;  // Flip all of the condition bits.
229   if (Operation > ISD::SETTRUE2)
230     Operation &= ~8;     // Don't let N and U bits get set.
231   return ISD::CondCode(Operation);
232 }
233
234
235 /// isSignedOp - For an integer comparison, return 1 if the comparison is a
236 /// signed operation and 2 if the result is an unsigned comparison.  Return zero
237 /// if the operation does not depend on the sign of the input (setne and seteq).
238 static int isSignedOp(ISD::CondCode Opcode) {
239   switch (Opcode) {
240   default: assert(0 && "Illegal integer setcc operation!");
241   case ISD::SETEQ:
242   case ISD::SETNE: return 0;
243   case ISD::SETLT:
244   case ISD::SETLE:
245   case ISD::SETGT:
246   case ISD::SETGE: return 1;
247   case ISD::SETULT:
248   case ISD::SETULE:
249   case ISD::SETUGT:
250   case ISD::SETUGE: return 2;
251   }
252 }
253
254 /// getSetCCOrOperation - Return the result of a logical OR between different
255 /// comparisons of identical values: ((X op1 Y) | (X op2 Y)).  This function
256 /// returns SETCC_INVALID if it is not possible to represent the resultant
257 /// comparison.
258 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
259                                        bool isInteger) {
260   if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
261     // Cannot fold a signed integer setcc with an unsigned integer setcc.
262     return ISD::SETCC_INVALID;
263
264   unsigned Op = Op1 | Op2;  // Combine all of the condition bits.
265
266   // If the N and U bits get set then the resultant comparison DOES suddenly
267   // care about orderedness, and is true when ordered.
268   if (Op > ISD::SETTRUE2)
269     Op &= ~16;     // Clear the U bit if the N bit is set.
270   
271   // Canonicalize illegal integer setcc's.
272   if (isInteger && Op == ISD::SETUNE)  // e.g. SETUGT | SETULT
273     Op = ISD::SETNE;
274   
275   return ISD::CondCode(Op);
276 }
277
278 /// getSetCCAndOperation - Return the result of a logical AND between different
279 /// comparisons of identical values: ((X op1 Y) & (X op2 Y)).  This
280 /// function returns zero if it is not possible to represent the resultant
281 /// comparison.
282 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
283                                         bool isInteger) {
284   if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
285     // Cannot fold a signed setcc with an unsigned setcc.
286     return ISD::SETCC_INVALID;
287
288   // Combine all of the condition bits.
289   ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
290   
291   // Canonicalize illegal integer setcc's.
292   if (isInteger) {
293     switch (Result) {
294     default: break;
295     case ISD::SETUO : Result = ISD::SETFALSE; break;  // SETUGT & SETULT
296     case ISD::SETOEQ:                                 // SETEQ  & SETU[LG]E
297     case ISD::SETUEQ: Result = ISD::SETEQ   ; break;  // SETUGE & SETULE
298     case ISD::SETOLT: Result = ISD::SETULT  ; break;  // SETULT & SETNE
299     case ISD::SETOGT: Result = ISD::SETUGT  ; break;  // SETUGT & SETNE
300     }
301   }
302   
303   return Result;
304 }
305
306 const TargetMachine &SelectionDAG::getTarget() const {
307   return TLI.getTargetMachine();
308 }
309
310 //===----------------------------------------------------------------------===//
311 //                           SDNode Profile Support
312 //===----------------------------------------------------------------------===//
313
314 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
315 ///
316 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC)  {
317   ID.AddInteger(OpC);
318 }
319
320 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
321 /// solely with their pointer.
322 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
323   ID.AddPointer(VTList.VTs);  
324 }
325
326 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
327 ///
328 static void AddNodeIDOperands(FoldingSetNodeID &ID,
329                               SDOperandPtr Ops, unsigned NumOps) {
330   for (; NumOps; --NumOps, ++Ops) {
331     ID.AddPointer(Ops->Val);
332     ID.AddInteger(Ops->ResNo);
333   }
334 }
335
336 static void AddNodeIDNode(FoldingSetNodeID &ID,
337                           unsigned short OpC, SDVTList VTList, 
338                           SDOperandPtr OpList, unsigned N) {
339   AddNodeIDOpcode(ID, OpC);
340   AddNodeIDValueTypes(ID, VTList);
341   AddNodeIDOperands(ID, OpList, N);
342 }
343
344
345 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
346 /// data.
347 static void AddNodeIDNode(FoldingSetNodeID &ID, SDNode *N) {
348   AddNodeIDOpcode(ID, N->getOpcode());
349   // Add the return value info.
350   AddNodeIDValueTypes(ID, N->getVTList());
351   // Add the operand info.
352   AddNodeIDOperands(ID, N->op_begin(), N->getNumOperands());
353
354   // Handle SDNode leafs with special info.
355   switch (N->getOpcode()) {
356   default: break;  // Normal nodes don't need extra info.
357   case ISD::ARG_FLAGS:
358     ID.AddInteger(cast<ARG_FLAGSSDNode>(N)->getArgFlags().getRawBits());
359     break;
360   case ISD::TargetConstant:
361   case ISD::Constant:
362     ID.Add(cast<ConstantSDNode>(N)->getAPIntValue());
363     break;
364   case ISD::TargetConstantFP:
365   case ISD::ConstantFP: {
366     ID.Add(cast<ConstantFPSDNode>(N)->getValueAPF());
367     break;
368   }
369   case ISD::TargetGlobalAddress:
370   case ISD::GlobalAddress:
371   case ISD::TargetGlobalTLSAddress:
372   case ISD::GlobalTLSAddress: {
373     GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
374     ID.AddPointer(GA->getGlobal());
375     ID.AddInteger(GA->getOffset());
376     break;
377   }
378   case ISD::BasicBlock:
379     ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
380     break;
381   case ISD::Register:
382     ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
383     break;
384   case ISD::SRCVALUE:
385     ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
386     break;
387   case ISD::MEMOPERAND: {
388     const MachineMemOperand &MO = cast<MemOperandSDNode>(N)->MO;
389     ID.AddPointer(MO.getValue());
390     ID.AddInteger(MO.getFlags());
391     ID.AddInteger(MO.getOffset());
392     ID.AddInteger(MO.getSize());
393     ID.AddInteger(MO.getAlignment());
394     break;
395   }
396   case ISD::FrameIndex:
397   case ISD::TargetFrameIndex:
398     ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
399     break;
400   case ISD::JumpTable:
401   case ISD::TargetJumpTable:
402     ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
403     break;
404   case ISD::ConstantPool:
405   case ISD::TargetConstantPool: {
406     ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
407     ID.AddInteger(CP->getAlignment());
408     ID.AddInteger(CP->getOffset());
409     if (CP->isMachineConstantPoolEntry())
410       CP->getMachineCPVal()->AddSelectionDAGCSEId(ID);
411     else
412       ID.AddPointer(CP->getConstVal());
413     break;
414   }
415   case ISD::LOAD: {
416     LoadSDNode *LD = cast<LoadSDNode>(N);
417     ID.AddInteger(LD->getAddressingMode());
418     ID.AddInteger(LD->getExtensionType());
419     ID.AddInteger(LD->getMemoryVT().getRawBits());
420     ID.AddInteger(LD->getAlignment());
421     ID.AddInteger(LD->isVolatile());
422     break;
423   }
424   case ISD::STORE: {
425     StoreSDNode *ST = cast<StoreSDNode>(N);
426     ID.AddInteger(ST->getAddressingMode());
427     ID.AddInteger(ST->isTruncatingStore());
428     ID.AddInteger(ST->getMemoryVT().getRawBits());
429     ID.AddInteger(ST->getAlignment());
430     ID.AddInteger(ST->isVolatile());
431     break;
432   }
433   }
434 }
435
436 //===----------------------------------------------------------------------===//
437 //                              SelectionDAG Class
438 //===----------------------------------------------------------------------===//
439
440 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
441 /// SelectionDAG.
442 void SelectionDAG::RemoveDeadNodes() {
443   // Create a dummy node (which is not added to allnodes), that adds a reference
444   // to the root node, preventing it from being deleted.
445   HandleSDNode Dummy(getRoot());
446
447   SmallVector<SDNode*, 128> DeadNodes;
448   
449   // Add all obviously-dead nodes to the DeadNodes worklist.
450   for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I)
451     if (I->use_empty())
452       DeadNodes.push_back(I);
453
454   // Process the worklist, deleting the nodes and adding their uses to the
455   // worklist.
456   while (!DeadNodes.empty()) {
457     SDNode *N = DeadNodes.back();
458     DeadNodes.pop_back();
459     
460     // Take the node out of the appropriate CSE map.
461     RemoveNodeFromCSEMaps(N);
462
463     // Next, brutally remove the operand list.  This is safe to do, as there are
464     // no cycles in the graph.
465     for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
466       SDNode *Operand = I->getVal();
467       Operand->removeUser(std::distance(N->op_begin(), I), N);
468       
469       // Now that we removed this operand, see if there are no uses of it left.
470       if (Operand->use_empty())
471         DeadNodes.push_back(Operand);
472     }
473     if (N->OperandsNeedDelete) {
474       delete[] N->OperandList;
475     }
476     N->OperandList = 0;
477     N->NumOperands = 0;
478     
479     // Finally, remove N itself.
480     AllNodes.erase(N);
481   }
482   
483   // If the root changed (e.g. it was a dead load, update the root).
484   setRoot(Dummy.getValue());
485 }
486
487 void SelectionDAG::RemoveDeadNode(SDNode *N, DAGUpdateListener *UpdateListener){
488   SmallVector<SDNode*, 16> DeadNodes;
489   DeadNodes.push_back(N);
490
491   // Process the worklist, deleting the nodes and adding their uses to the
492   // worklist.
493   while (!DeadNodes.empty()) {
494     SDNode *N = DeadNodes.back();
495     DeadNodes.pop_back();
496     
497     if (UpdateListener)
498       UpdateListener->NodeDeleted(N, 0);
499     
500     // Take the node out of the appropriate CSE map.
501     RemoveNodeFromCSEMaps(N);
502
503     // Next, brutally remove the operand list.  This is safe to do, as there are
504     // no cycles in the graph.
505     for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
506       SDNode *Operand = I->getVal();
507       Operand->removeUser(std::distance(N->op_begin(), I), N);
508       
509       // Now that we removed this operand, see if there are no uses of it left.
510       if (Operand->use_empty())
511         DeadNodes.push_back(Operand);
512     }
513     if (N->OperandsNeedDelete) {
514       delete[] N->OperandList;
515     }
516     N->OperandList = 0;
517     N->NumOperands = 0;
518     
519     // Finally, remove N itself.
520     AllNodes.erase(N);
521   }
522 }
523
524 void SelectionDAG::DeleteNode(SDNode *N) {
525   assert(N->use_empty() && "Cannot delete a node that is not dead!");
526
527   // First take this out of the appropriate CSE map.
528   RemoveNodeFromCSEMaps(N);
529
530   // Finally, remove uses due to operands of this node, remove from the 
531   // AllNodes list, and delete the node.
532   DeleteNodeNotInCSEMaps(N);
533 }
534
535 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
536
537   // Remove it from the AllNodes list.
538   AllNodes.remove(N);
539     
540   // Drop all of the operands and decrement used nodes use counts.
541   for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I)
542     I->getVal()->removeUser(std::distance(N->op_begin(), I), N);
543   if (N->OperandsNeedDelete) {
544     delete[] N->OperandList;
545   }
546   N->OperandList = 0;
547   N->NumOperands = 0;
548   
549   delete N;
550 }
551
552 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
553 /// correspond to it.  This is useful when we're about to delete or repurpose
554 /// the node.  We don't want future request for structurally identical nodes
555 /// to return N anymore.
556 void SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
557   bool Erased = false;
558   switch (N->getOpcode()) {
559   case ISD::HANDLENODE: return;  // noop.
560   case ISD::STRING:
561     Erased = StringNodes.erase(cast<StringSDNode>(N)->getValue());
562     break;
563   case ISD::CONDCODE:
564     assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
565            "Cond code doesn't exist!");
566     Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != 0;
567     CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = 0;
568     break;
569   case ISD::ExternalSymbol:
570     Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
571     break;
572   case ISD::TargetExternalSymbol:
573     Erased =
574       TargetExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
575     break;
576   case ISD::VALUETYPE: {
577     MVT VT = cast<VTSDNode>(N)->getVT();
578     if (VT.isExtended()) {
579       Erased = ExtendedValueTypeNodes.erase(VT);
580     } else {
581       Erased = ValueTypeNodes[VT.getSimpleVT()] != 0;
582       ValueTypeNodes[VT.getSimpleVT()] = 0;
583     }
584     break;
585   }
586   default:
587     // Remove it from the CSE Map.
588     Erased = CSEMap.RemoveNode(N);
589     break;
590   }
591 #ifndef NDEBUG
592   // Verify that the node was actually in one of the CSE maps, unless it has a 
593   // flag result (which cannot be CSE'd) or is one of the special cases that are
594   // not subject to CSE.
595   if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Flag &&
596       !N->isTargetOpcode()) {
597     N->dump(this);
598     cerr << "\n";
599     assert(0 && "Node is not in map!");
600   }
601 #endif
602 }
603
604 /// AddNonLeafNodeToCSEMaps - Add the specified node back to the CSE maps.  It
605 /// has been taken out and modified in some way.  If the specified node already
606 /// exists in the CSE maps, do not modify the maps, but return the existing node
607 /// instead.  If it doesn't exist, add it and return null.
608 ///
609 SDNode *SelectionDAG::AddNonLeafNodeToCSEMaps(SDNode *N) {
610   assert(N->getNumOperands() && "This is a leaf node!");
611   if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
612     return 0;    // Never add these nodes.
613   
614   // Check that remaining values produced are not flags.
615   for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
616     if (N->getValueType(i) == MVT::Flag)
617       return 0;   // Never CSE anything that produces a flag.
618   
619   SDNode *New = CSEMap.GetOrInsertNode(N);
620   if (New != N) return New;  // Node already existed.
621   return 0;
622 }
623
624 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
625 /// were replaced with those specified.  If this node is never memoized, 
626 /// return null, otherwise return a pointer to the slot it would take.  If a
627 /// node already exists with these operands, the slot will be non-null.
628 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDOperand Op,
629                                            void *&InsertPos) {
630   if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
631     return 0;    // Never add these nodes.
632   
633   // Check that remaining values produced are not flags.
634   for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
635     if (N->getValueType(i) == MVT::Flag)
636       return 0;   // Never CSE anything that produces a flag.
637   
638   SDOperand Ops[] = { Op };
639   FoldingSetNodeID ID;
640   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 1);
641   return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
642 }
643
644 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
645 /// were replaced with those specified.  If this node is never memoized, 
646 /// return null, otherwise return a pointer to the slot it would take.  If a
647 /// node already exists with these operands, the slot will be non-null.
648 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, 
649                                            SDOperand Op1, SDOperand Op2,
650                                            void *&InsertPos) {
651   if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
652     return 0;    // Never add these nodes.
653   
654   // Check that remaining values produced are not flags.
655   for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
656     if (N->getValueType(i) == MVT::Flag)
657       return 0;   // Never CSE anything that produces a flag.
658                                               
659   SDOperand Ops[] = { Op1, Op2 };
660   FoldingSetNodeID ID;
661   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 2);
662   return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
663 }
664
665
666 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
667 /// were replaced with those specified.  If this node is never memoized, 
668 /// return null, otherwise return a pointer to the slot it would take.  If a
669 /// node already exists with these operands, the slot will be non-null.
670 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, 
671                                            SDOperandPtr Ops,unsigned NumOps,
672                                            void *&InsertPos) {
673   if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
674     return 0;    // Never add these nodes.
675   
676   // Check that remaining values produced are not flags.
677   for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
678     if (N->getValueType(i) == MVT::Flag)
679       return 0;   // Never CSE anything that produces a flag.
680   
681   FoldingSetNodeID ID;
682   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, NumOps);
683   
684   if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
685     ID.AddInteger(LD->getAddressingMode());
686     ID.AddInteger(LD->getExtensionType());
687     ID.AddInteger(LD->getMemoryVT().getRawBits());
688     ID.AddInteger(LD->getAlignment());
689     ID.AddInteger(LD->isVolatile());
690   } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
691     ID.AddInteger(ST->getAddressingMode());
692     ID.AddInteger(ST->isTruncatingStore());
693     ID.AddInteger(ST->getMemoryVT().getRawBits());
694     ID.AddInteger(ST->getAlignment());
695     ID.AddInteger(ST->isVolatile());
696   }
697   
698   return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
699 }
700
701
702 SelectionDAG::~SelectionDAG() {
703   while (!AllNodes.empty()) {
704     SDNode *N = AllNodes.begin();
705     N->SetNextInBucket(0);
706     if (N->OperandsNeedDelete) {
707       delete [] N->OperandList;
708     }
709     N->OperandList = 0;
710     N->NumOperands = 0;
711     AllNodes.pop_front();
712   }
713 }
714
715 SDOperand SelectionDAG::getZeroExtendInReg(SDOperand Op, MVT VT) {
716   if (Op.getValueType() == VT) return Op;
717   APInt Imm = APInt::getLowBitsSet(Op.getValueSizeInBits(),
718                                    VT.getSizeInBits());
719   return getNode(ISD::AND, Op.getValueType(), Op,
720                  getConstant(Imm, Op.getValueType()));
721 }
722
723 SDOperand SelectionDAG::getString(const std::string &Val) {
724   StringSDNode *&N = StringNodes[Val];
725   if (!N) {
726     N = new StringSDNode(Val);
727     AllNodes.push_back(N);
728   }
729   return SDOperand(N, 0);
730 }
731
732 SDOperand SelectionDAG::getConstant(uint64_t Val, MVT VT, bool isT) {
733   MVT EltVT =
734     VT.isVector() ? VT.getVectorElementType() : VT;
735
736   return getConstant(APInt(EltVT.getSizeInBits(), Val), VT, isT);
737 }
738
739 SDOperand SelectionDAG::getConstant(const APInt &Val, MVT VT, bool isT) {
740   assert(VT.isInteger() && "Cannot create FP integer constant!");
741
742   MVT EltVT =
743     VT.isVector() ? VT.getVectorElementType() : VT;
744   
745   assert(Val.getBitWidth() == EltVT.getSizeInBits() &&
746          "APInt size does not match type size!");
747
748   unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
749   FoldingSetNodeID ID;
750   AddNodeIDNode(ID, Opc, getVTList(EltVT), (SDOperand*)0, 0);
751   ID.Add(Val);
752   void *IP = 0;
753   SDNode *N = NULL;
754   if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
755     if (!VT.isVector())
756       return SDOperand(N, 0);
757   if (!N) {
758     N = new ConstantSDNode(isT, Val, EltVT);
759     CSEMap.InsertNode(N, IP);
760     AllNodes.push_back(N);
761   }
762
763   SDOperand Result(N, 0);
764   if (VT.isVector()) {
765     SmallVector<SDOperand, 8> Ops;
766     Ops.assign(VT.getVectorNumElements(), Result);
767     Result = getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
768   }
769   return Result;
770 }
771
772 SDOperand SelectionDAG::getIntPtrConstant(uint64_t Val, bool isTarget) {
773   return getConstant(Val, TLI.getPointerTy(), isTarget);
774 }
775
776
777 SDOperand SelectionDAG::getConstantFP(const APFloat& V, MVT VT, bool isTarget) {
778   assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
779                                 
780   MVT EltVT =
781     VT.isVector() ? VT.getVectorElementType() : VT;
782
783   // Do the map lookup using the actual bit pattern for the floating point
784   // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
785   // we don't have issues with SNANs.
786   unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
787   FoldingSetNodeID ID;
788   AddNodeIDNode(ID, Opc, getVTList(EltVT), (SDOperand*)0, 0);
789   ID.Add(V);
790   void *IP = 0;
791   SDNode *N = NULL;
792   if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
793     if (!VT.isVector())
794       return SDOperand(N, 0);
795   if (!N) {
796     N = new ConstantFPSDNode(isTarget, V, EltVT);
797     CSEMap.InsertNode(N, IP);
798     AllNodes.push_back(N);
799   }
800
801   SDOperand Result(N, 0);
802   if (VT.isVector()) {
803     SmallVector<SDOperand, 8> Ops;
804     Ops.assign(VT.getVectorNumElements(), Result);
805     Result = getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
806   }
807   return Result;
808 }
809
810 SDOperand SelectionDAG::getConstantFP(double Val, MVT VT, bool isTarget) {
811   MVT EltVT =
812     VT.isVector() ? VT.getVectorElementType() : VT;
813   if (EltVT==MVT::f32)
814     return getConstantFP(APFloat((float)Val), VT, isTarget);
815   else
816     return getConstantFP(APFloat(Val), VT, isTarget);
817 }
818
819 SDOperand SelectionDAG::getGlobalAddress(const GlobalValue *GV,
820                                          MVT VT, int Offset,
821                                          bool isTargetGA) {
822   unsigned Opc;
823
824   const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
825   if (!GVar) {
826     // If GV is an alias then use the aliasee for determining thread-localness.
827     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
828       GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal());
829   }
830
831   if (GVar && GVar->isThreadLocal())
832     Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
833   else
834     Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
835
836   FoldingSetNodeID ID;
837   AddNodeIDNode(ID, Opc, getVTList(VT), (SDOperand*)0, 0);
838   ID.AddPointer(GV);
839   ID.AddInteger(Offset);
840   void *IP = 0;
841   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
842    return SDOperand(E, 0);
843   SDNode *N = new GlobalAddressSDNode(isTargetGA, GV, VT, Offset);
844   CSEMap.InsertNode(N, IP);
845   AllNodes.push_back(N);
846   return SDOperand(N, 0);
847 }
848
849 SDOperand SelectionDAG::getFrameIndex(int FI, MVT VT, bool isTarget) {
850   unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
851   FoldingSetNodeID ID;
852   AddNodeIDNode(ID, Opc, getVTList(VT), (SDOperand*)0, 0);
853   ID.AddInteger(FI);
854   void *IP = 0;
855   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
856     return SDOperand(E, 0);
857   SDNode *N = new FrameIndexSDNode(FI, VT, isTarget);
858   CSEMap.InsertNode(N, IP);
859   AllNodes.push_back(N);
860   return SDOperand(N, 0);
861 }
862
863 SDOperand SelectionDAG::getJumpTable(int JTI, MVT VT, bool isTarget){
864   unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
865   FoldingSetNodeID ID;
866   AddNodeIDNode(ID, Opc, getVTList(VT), (SDOperand*)0, 0);
867   ID.AddInteger(JTI);
868   void *IP = 0;
869   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
870     return SDOperand(E, 0);
871   SDNode *N = new JumpTableSDNode(JTI, VT, isTarget);
872   CSEMap.InsertNode(N, IP);
873   AllNodes.push_back(N);
874   return SDOperand(N, 0);
875 }
876
877 SDOperand SelectionDAG::getConstantPool(Constant *C, MVT VT,
878                                         unsigned Alignment, int Offset,
879                                         bool isTarget) {
880   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
881   FoldingSetNodeID ID;
882   AddNodeIDNode(ID, Opc, getVTList(VT), (SDOperand*)0, 0);
883   ID.AddInteger(Alignment);
884   ID.AddInteger(Offset);
885   ID.AddPointer(C);
886   void *IP = 0;
887   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
888     return SDOperand(E, 0);
889   SDNode *N = new ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment);
890   CSEMap.InsertNode(N, IP);
891   AllNodes.push_back(N);
892   return SDOperand(N, 0);
893 }
894
895
896 SDOperand SelectionDAG::getConstantPool(MachineConstantPoolValue *C, MVT VT,
897                                         unsigned Alignment, int Offset,
898                                         bool isTarget) {
899   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
900   FoldingSetNodeID ID;
901   AddNodeIDNode(ID, Opc, getVTList(VT), (SDOperand*)0, 0);
902   ID.AddInteger(Alignment);
903   ID.AddInteger(Offset);
904   C->AddSelectionDAGCSEId(ID);
905   void *IP = 0;
906   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
907     return SDOperand(E, 0);
908   SDNode *N = new ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment);
909   CSEMap.InsertNode(N, IP);
910   AllNodes.push_back(N);
911   return SDOperand(N, 0);
912 }
913
914
915 SDOperand SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
916   FoldingSetNodeID ID;
917   AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), (SDOperand*)0, 0);
918   ID.AddPointer(MBB);
919   void *IP = 0;
920   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
921     return SDOperand(E, 0);
922   SDNode *N = new BasicBlockSDNode(MBB);
923   CSEMap.InsertNode(N, IP);
924   AllNodes.push_back(N);
925   return SDOperand(N, 0);
926 }
927
928 SDOperand SelectionDAG::getArgFlags(ISD::ArgFlagsTy Flags) {
929   FoldingSetNodeID ID;
930   AddNodeIDNode(ID, ISD::ARG_FLAGS, getVTList(MVT::Other), (SDOperand*)0, 0);
931   ID.AddInteger(Flags.getRawBits());
932   void *IP = 0;
933   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
934     return SDOperand(E, 0);
935   SDNode *N = new ARG_FLAGSSDNode(Flags);
936   CSEMap.InsertNode(N, IP);
937   AllNodes.push_back(N);
938   return SDOperand(N, 0);
939 }
940
941 SDOperand SelectionDAG::getValueType(MVT VT) {
942   if (VT.isSimple() && (unsigned)VT.getSimpleVT() >= ValueTypeNodes.size())
943     ValueTypeNodes.resize(VT.getSimpleVT()+1);
944
945   SDNode *&N = VT.isExtended() ?
946     ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT()];
947
948   if (N) return SDOperand(N, 0);
949   N = new VTSDNode(VT);
950   AllNodes.push_back(N);
951   return SDOperand(N, 0);
952 }
953
954 SDOperand SelectionDAG::getExternalSymbol(const char *Sym, MVT VT) {
955   SDNode *&N = ExternalSymbols[Sym];
956   if (N) return SDOperand(N, 0);
957   N = new ExternalSymbolSDNode(false, Sym, VT);
958   AllNodes.push_back(N);
959   return SDOperand(N, 0);
960 }
961
962 SDOperand SelectionDAG::getTargetExternalSymbol(const char *Sym, MVT VT) {
963   SDNode *&N = TargetExternalSymbols[Sym];
964   if (N) return SDOperand(N, 0);
965   N = new ExternalSymbolSDNode(true, Sym, VT);
966   AllNodes.push_back(N);
967   return SDOperand(N, 0);
968 }
969
970 SDOperand SelectionDAG::getCondCode(ISD::CondCode Cond) {
971   if ((unsigned)Cond >= CondCodeNodes.size())
972     CondCodeNodes.resize(Cond+1);
973
974   if (CondCodeNodes[Cond] == 0) {
975     CondCodeNodes[Cond] = new CondCodeSDNode(Cond);
976     AllNodes.push_back(CondCodeNodes[Cond]);
977   }
978   return SDOperand(CondCodeNodes[Cond], 0);
979 }
980
981 SDOperand SelectionDAG::getRegister(unsigned RegNo, MVT VT) {
982   FoldingSetNodeID ID;
983   AddNodeIDNode(ID, ISD::Register, getVTList(VT), (SDOperand*)0, 0);
984   ID.AddInteger(RegNo);
985   void *IP = 0;
986   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
987     return SDOperand(E, 0);
988   SDNode *N = new RegisterSDNode(RegNo, VT);
989   CSEMap.InsertNode(N, IP);
990   AllNodes.push_back(N);
991   return SDOperand(N, 0);
992 }
993
994 SDOperand SelectionDAG::getSrcValue(const Value *V) {
995   assert((!V || isa<PointerType>(V->getType())) &&
996          "SrcValue is not a pointer?");
997
998   FoldingSetNodeID ID;
999   AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), (SDOperand*)0, 0);
1000   ID.AddPointer(V);
1001
1002   void *IP = 0;
1003   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1004     return SDOperand(E, 0);
1005
1006   SDNode *N = new SrcValueSDNode(V);
1007   CSEMap.InsertNode(N, IP);
1008   AllNodes.push_back(N);
1009   return SDOperand(N, 0);
1010 }
1011
1012 SDOperand SelectionDAG::getMemOperand(const MachineMemOperand &MO) {
1013   const Value *v = MO.getValue();
1014   assert((!v || isa<PointerType>(v->getType())) &&
1015          "SrcValue is not a pointer?");
1016
1017   FoldingSetNodeID ID;
1018   AddNodeIDNode(ID, ISD::MEMOPERAND, getVTList(MVT::Other), (SDOperand*)0, 0);
1019   ID.AddPointer(v);
1020   ID.AddInteger(MO.getFlags());
1021   ID.AddInteger(MO.getOffset());
1022   ID.AddInteger(MO.getSize());
1023   ID.AddInteger(MO.getAlignment());
1024
1025   void *IP = 0;
1026   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1027     return SDOperand(E, 0);
1028
1029   SDNode *N = new MemOperandSDNode(MO);
1030   CSEMap.InsertNode(N, IP);
1031   AllNodes.push_back(N);
1032   return SDOperand(N, 0);
1033 }
1034
1035 /// CreateStackTemporary - Create a stack temporary, suitable for holding the
1036 /// specified value type.
1037 SDOperand SelectionDAG::CreateStackTemporary(MVT VT) {
1038   MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo();
1039   unsigned ByteSize = VT.getSizeInBits()/8;
1040   const Type *Ty = VT.getTypeForMVT();
1041   unsigned StackAlign = (unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty);
1042   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign);
1043   return getFrameIndex(FrameIdx, TLI.getPointerTy());
1044 }
1045
1046
1047 SDOperand SelectionDAG::FoldSetCC(MVT VT, SDOperand N1,
1048                                   SDOperand N2, ISD::CondCode Cond) {
1049   // These setcc operations always fold.
1050   switch (Cond) {
1051   default: break;
1052   case ISD::SETFALSE:
1053   case ISD::SETFALSE2: return getConstant(0, VT);
1054   case ISD::SETTRUE:
1055   case ISD::SETTRUE2:  return getConstant(1, VT);
1056     
1057   case ISD::SETOEQ:
1058   case ISD::SETOGT:
1059   case ISD::SETOGE:
1060   case ISD::SETOLT:
1061   case ISD::SETOLE:
1062   case ISD::SETONE:
1063   case ISD::SETO:
1064   case ISD::SETUO:
1065   case ISD::SETUEQ:
1066   case ISD::SETUNE:
1067     assert(!N1.getValueType().isInteger() && "Illegal setcc for integer!");
1068     break;
1069   }
1070   
1071   if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val)) {
1072     const APInt &C2 = N2C->getAPIntValue();
1073     if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val)) {
1074       const APInt &C1 = N1C->getAPIntValue();
1075       
1076       switch (Cond) {
1077       default: assert(0 && "Unknown integer setcc!");
1078       case ISD::SETEQ:  return getConstant(C1 == C2, VT);
1079       case ISD::SETNE:  return getConstant(C1 != C2, VT);
1080       case ISD::SETULT: return getConstant(C1.ult(C2), VT);
1081       case ISD::SETUGT: return getConstant(C1.ugt(C2), VT);
1082       case ISD::SETULE: return getConstant(C1.ule(C2), VT);
1083       case ISD::SETUGE: return getConstant(C1.uge(C2), VT);
1084       case ISD::SETLT:  return getConstant(C1.slt(C2), VT);
1085       case ISD::SETGT:  return getConstant(C1.sgt(C2), VT);
1086       case ISD::SETLE:  return getConstant(C1.sle(C2), VT);
1087       case ISD::SETGE:  return getConstant(C1.sge(C2), VT);
1088       }
1089     }
1090   }
1091   if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1.Val)) {
1092     if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2.Val)) {
1093       // No compile time operations on this type yet.
1094       if (N1C->getValueType(0) == MVT::ppcf128)
1095         return SDOperand();
1096
1097       APFloat::cmpResult R = N1C->getValueAPF().compare(N2C->getValueAPF());
1098       switch (Cond) {
1099       default: break;
1100       case ISD::SETEQ:  if (R==APFloat::cmpUnordered) 
1101                           return getNode(ISD::UNDEF, VT);
1102                         // fall through
1103       case ISD::SETOEQ: return getConstant(R==APFloat::cmpEqual, VT);
1104       case ISD::SETNE:  if (R==APFloat::cmpUnordered) 
1105                           return getNode(ISD::UNDEF, VT);
1106                         // fall through
1107       case ISD::SETONE: return getConstant(R==APFloat::cmpGreaterThan ||
1108                                            R==APFloat::cmpLessThan, VT);
1109       case ISD::SETLT:  if (R==APFloat::cmpUnordered) 
1110                           return getNode(ISD::UNDEF, VT);
1111                         // fall through
1112       case ISD::SETOLT: return getConstant(R==APFloat::cmpLessThan, VT);
1113       case ISD::SETGT:  if (R==APFloat::cmpUnordered) 
1114                           return getNode(ISD::UNDEF, VT);
1115                         // fall through
1116       case ISD::SETOGT: return getConstant(R==APFloat::cmpGreaterThan, VT);
1117       case ISD::SETLE:  if (R==APFloat::cmpUnordered) 
1118                           return getNode(ISD::UNDEF, VT);
1119                         // fall through
1120       case ISD::SETOLE: return getConstant(R==APFloat::cmpLessThan ||
1121                                            R==APFloat::cmpEqual, VT);
1122       case ISD::SETGE:  if (R==APFloat::cmpUnordered) 
1123                           return getNode(ISD::UNDEF, VT);
1124                         // fall through
1125       case ISD::SETOGE: return getConstant(R==APFloat::cmpGreaterThan ||
1126                                            R==APFloat::cmpEqual, VT);
1127       case ISD::SETO:   return getConstant(R!=APFloat::cmpUnordered, VT);
1128       case ISD::SETUO:  return getConstant(R==APFloat::cmpUnordered, VT);
1129       case ISD::SETUEQ: return getConstant(R==APFloat::cmpUnordered ||
1130                                            R==APFloat::cmpEqual, VT);
1131       case ISD::SETUNE: return getConstant(R!=APFloat::cmpEqual, VT);
1132       case ISD::SETULT: return getConstant(R==APFloat::cmpUnordered ||
1133                                            R==APFloat::cmpLessThan, VT);
1134       case ISD::SETUGT: return getConstant(R==APFloat::cmpGreaterThan ||
1135                                            R==APFloat::cmpUnordered, VT);
1136       case ISD::SETULE: return getConstant(R!=APFloat::cmpGreaterThan, VT);
1137       case ISD::SETUGE: return getConstant(R!=APFloat::cmpLessThan, VT);
1138       }
1139     } else {
1140       // Ensure that the constant occurs on the RHS.
1141       return getSetCC(VT, N2, N1, ISD::getSetCCSwappedOperands(Cond));
1142     }
1143   }
1144
1145   // Could not fold it.
1146   return SDOperand();
1147 }
1148
1149 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero.  We
1150 /// use this predicate to simplify operations downstream.
1151 bool SelectionDAG::SignBitIsZero(SDOperand Op, unsigned Depth) const {
1152   unsigned BitWidth = Op.getValueSizeInBits();
1153   return MaskedValueIsZero(Op, APInt::getSignBit(BitWidth), Depth);
1154 }
1155
1156 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
1157 /// this predicate to simplify operations downstream.  Mask is known to be zero
1158 /// for bits that V cannot have.
1159 bool SelectionDAG::MaskedValueIsZero(SDOperand Op, const APInt &Mask, 
1160                                      unsigned Depth) const {
1161   APInt KnownZero, KnownOne;
1162   ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
1163   assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1164   return (KnownZero & Mask) == Mask;
1165 }
1166
1167 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
1168 /// known to be either zero or one and return them in the KnownZero/KnownOne
1169 /// bitsets.  This code only analyzes bits in Mask, in order to short-circuit
1170 /// processing.
1171 void SelectionDAG::ComputeMaskedBits(SDOperand Op, const APInt &Mask, 
1172                                      APInt &KnownZero, APInt &KnownOne,
1173                                      unsigned Depth) const {
1174   unsigned BitWidth = Mask.getBitWidth();
1175   assert(BitWidth == Op.getValueType().getSizeInBits() &&
1176          "Mask size mismatches value type size!");
1177
1178   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
1179   if (Depth == 6 || Mask == 0)
1180     return;  // Limit search depth.
1181   
1182   APInt KnownZero2, KnownOne2;
1183
1184   switch (Op.getOpcode()) {
1185   case ISD::Constant:
1186     // We know all of the bits for a constant!
1187     KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue() & Mask;
1188     KnownZero = ~KnownOne & Mask;
1189     return;
1190   case ISD::AND:
1191     // If either the LHS or the RHS are Zero, the result is zero.
1192     ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1193     ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownZero,
1194                       KnownZero2, KnownOne2, Depth+1);
1195     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1196     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
1197
1198     // Output known-1 bits are only known if set in both the LHS & RHS.
1199     KnownOne &= KnownOne2;
1200     // Output known-0 are known to be clear if zero in either the LHS | RHS.
1201     KnownZero |= KnownZero2;
1202     return;
1203   case ISD::OR:
1204     ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1205     ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownOne,
1206                       KnownZero2, KnownOne2, Depth+1);
1207     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1208     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
1209     
1210     // Output known-0 bits are only known if clear in both the LHS & RHS.
1211     KnownZero &= KnownZero2;
1212     // Output known-1 are known to be set if set in either the LHS | RHS.
1213     KnownOne |= KnownOne2;
1214     return;
1215   case ISD::XOR: {
1216     ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1217     ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
1218     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1219     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
1220     
1221     // Output known-0 bits are known if clear or set in both the LHS & RHS.
1222     APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
1223     // Output known-1 are known to be set if set in only one of the LHS, RHS.
1224     KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
1225     KnownZero = KnownZeroOut;
1226     return;
1227   }
1228   case ISD::MUL: {
1229     APInt Mask2 = APInt::getAllOnesValue(BitWidth);
1230     ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero, KnownOne, Depth+1);
1231     ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
1232     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1233     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1234
1235     // If low bits are zero in either operand, output low known-0 bits.
1236     // Also compute a conserative estimate for high known-0 bits.
1237     // More trickiness is possible, but this is sufficient for the
1238     // interesting case of alignment computation.
1239     KnownOne.clear();
1240     unsigned TrailZ = KnownZero.countTrailingOnes() +
1241                       KnownZero2.countTrailingOnes();
1242     unsigned LeadZ =  std::max(KnownZero.countLeadingOnes() +
1243                                KnownZero2.countLeadingOnes(),
1244                                BitWidth) - BitWidth;
1245
1246     TrailZ = std::min(TrailZ, BitWidth);
1247     LeadZ = std::min(LeadZ, BitWidth);
1248     KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
1249                 APInt::getHighBitsSet(BitWidth, LeadZ);
1250     KnownZero &= Mask;
1251     return;
1252   }
1253   case ISD::UDIV: {
1254     // For the purposes of computing leading zeros we can conservatively
1255     // treat a udiv as a logical right shift by the power of 2 known to
1256     // be less than the denominator.
1257     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1258     ComputeMaskedBits(Op.getOperand(0),
1259                       AllOnes, KnownZero2, KnownOne2, Depth+1);
1260     unsigned LeadZ = KnownZero2.countLeadingOnes();
1261
1262     KnownOne2.clear();
1263     KnownZero2.clear();
1264     ComputeMaskedBits(Op.getOperand(1),
1265                       AllOnes, KnownZero2, KnownOne2, Depth+1);
1266     unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
1267     if (RHSUnknownLeadingOnes != BitWidth)
1268       LeadZ = std::min(BitWidth,
1269                        LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
1270
1271     KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
1272     return;
1273   }
1274   case ISD::SELECT:
1275     ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
1276     ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
1277     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1278     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
1279     
1280     // Only known if known in both the LHS and RHS.
1281     KnownOne &= KnownOne2;
1282     KnownZero &= KnownZero2;
1283     return;
1284   case ISD::SELECT_CC:
1285     ComputeMaskedBits(Op.getOperand(3), Mask, KnownZero, KnownOne, Depth+1);
1286     ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero2, KnownOne2, Depth+1);
1287     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1288     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
1289     
1290     // Only known if known in both the LHS and RHS.
1291     KnownOne &= KnownOne2;
1292     KnownZero &= KnownZero2;
1293     return;
1294   case ISD::SETCC:
1295     // If we know the result of a setcc has the top bits zero, use this info.
1296     if (TLI.getSetCCResultContents() == TargetLowering::ZeroOrOneSetCCResult &&
1297         BitWidth > 1)
1298       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1299     return;
1300   case ISD::SHL:
1301     // (shl X, C1) & C2 == 0   iff   (X & C2 >>u C1) == 0
1302     if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1303       unsigned ShAmt = SA->getValue();
1304
1305       // If the shift count is an invalid immediate, don't do anything.
1306       if (ShAmt >= BitWidth)
1307         return;
1308
1309       ComputeMaskedBits(Op.getOperand(0), Mask.lshr(ShAmt),
1310                         KnownZero, KnownOne, Depth+1);
1311       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1312       KnownZero <<= ShAmt;
1313       KnownOne  <<= ShAmt;
1314       // low bits known zero.
1315       KnownZero |= APInt::getLowBitsSet(BitWidth, ShAmt);
1316     }
1317     return;
1318   case ISD::SRL:
1319     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
1320     if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1321       unsigned ShAmt = SA->getValue();
1322
1323       // If the shift count is an invalid immediate, don't do anything.
1324       if (ShAmt >= BitWidth)
1325         return;
1326
1327       ComputeMaskedBits(Op.getOperand(0), (Mask << ShAmt),
1328                         KnownZero, KnownOne, Depth+1);
1329       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1330       KnownZero = KnownZero.lshr(ShAmt);
1331       KnownOne  = KnownOne.lshr(ShAmt);
1332
1333       APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
1334       KnownZero |= HighBits;  // High bits known zero.
1335     }
1336     return;
1337   case ISD::SRA:
1338     if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1339       unsigned ShAmt = SA->getValue();
1340
1341       // If the shift count is an invalid immediate, don't do anything.
1342       if (ShAmt >= BitWidth)
1343         return;
1344
1345       APInt InDemandedMask = (Mask << ShAmt);
1346       // If any of the demanded bits are produced by the sign extension, we also
1347       // demand the input sign bit.
1348       APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
1349       if (HighBits.getBoolValue())
1350         InDemandedMask |= APInt::getSignBit(BitWidth);
1351       
1352       ComputeMaskedBits(Op.getOperand(0), InDemandedMask, KnownZero, KnownOne,
1353                         Depth+1);
1354       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1355       KnownZero = KnownZero.lshr(ShAmt);
1356       KnownOne  = KnownOne.lshr(ShAmt);
1357       
1358       // Handle the sign bits.
1359       APInt SignBit = APInt::getSignBit(BitWidth);
1360       SignBit = SignBit.lshr(ShAmt);  // Adjust to where it is now in the mask.
1361       
1362       if (KnownZero.intersects(SignBit)) {
1363         KnownZero |= HighBits;  // New bits are known zero.
1364       } else if (KnownOne.intersects(SignBit)) {
1365         KnownOne  |= HighBits;  // New bits are known one.
1366       }
1367     }
1368     return;
1369   case ISD::SIGN_EXTEND_INREG: {
1370     MVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1371     unsigned EBits = EVT.getSizeInBits();
1372     
1373     // Sign extension.  Compute the demanded bits in the result that are not 
1374     // present in the input.
1375     APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - EBits) & Mask;
1376
1377     APInt InSignBit = APInt::getSignBit(EBits);
1378     APInt InputDemandedBits = Mask & APInt::getLowBitsSet(BitWidth, EBits);
1379     
1380     // If the sign extended bits are demanded, we know that the sign
1381     // bit is demanded.
1382     InSignBit.zext(BitWidth);
1383     if (NewBits.getBoolValue())
1384       InputDemandedBits |= InSignBit;
1385     
1386     ComputeMaskedBits(Op.getOperand(0), InputDemandedBits,
1387                       KnownZero, KnownOne, Depth+1);
1388     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1389     
1390     // If the sign bit of the input is known set or clear, then we know the
1391     // top bits of the result.
1392     if (KnownZero.intersects(InSignBit)) {         // Input sign bit known clear
1393       KnownZero |= NewBits;
1394       KnownOne  &= ~NewBits;
1395     } else if (KnownOne.intersects(InSignBit)) {   // Input sign bit known set
1396       KnownOne  |= NewBits;
1397       KnownZero &= ~NewBits;
1398     } else {                              // Input sign bit unknown
1399       KnownZero &= ~NewBits;
1400       KnownOne  &= ~NewBits;
1401     }
1402     return;
1403   }
1404   case ISD::CTTZ:
1405   case ISD::CTLZ:
1406   case ISD::CTPOP: {
1407     unsigned LowBits = Log2_32(BitWidth)+1;
1408     KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1409     KnownOne  = APInt(BitWidth, 0);
1410     return;
1411   }
1412   case ISD::LOAD: {
1413     if (ISD::isZEXTLoad(Op.Val)) {
1414       LoadSDNode *LD = cast<LoadSDNode>(Op);
1415       MVT VT = LD->getMemoryVT();
1416       unsigned MemBits = VT.getSizeInBits();
1417       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits) & Mask;
1418     }
1419     return;
1420   }
1421   case ISD::ZERO_EXTEND: {
1422     MVT InVT = Op.getOperand(0).getValueType();
1423     unsigned InBits = InVT.getSizeInBits();
1424     APInt NewBits   = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
1425     APInt InMask    = Mask;
1426     InMask.trunc(InBits);
1427     KnownZero.trunc(InBits);
1428     KnownOne.trunc(InBits);
1429     ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1430     KnownZero.zext(BitWidth);
1431     KnownOne.zext(BitWidth);
1432     KnownZero |= NewBits;
1433     return;
1434   }
1435   case ISD::SIGN_EXTEND: {
1436     MVT InVT = Op.getOperand(0).getValueType();
1437     unsigned InBits = InVT.getSizeInBits();
1438     APInt InSignBit = APInt::getSignBit(InBits);
1439     APInt NewBits   = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
1440     APInt InMask = Mask;
1441     InMask.trunc(InBits);
1442
1443     // If any of the sign extended bits are demanded, we know that the sign
1444     // bit is demanded. Temporarily set this bit in the mask for our callee.
1445     if (NewBits.getBoolValue())
1446       InMask |= InSignBit;
1447
1448     KnownZero.trunc(InBits);
1449     KnownOne.trunc(InBits);
1450     ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1451
1452     // Note if the sign bit is known to be zero or one.
1453     bool SignBitKnownZero = KnownZero.isNegative();
1454     bool SignBitKnownOne  = KnownOne.isNegative();
1455     assert(!(SignBitKnownZero && SignBitKnownOne) &&
1456            "Sign bit can't be known to be both zero and one!");
1457
1458     // If the sign bit wasn't actually demanded by our caller, we don't
1459     // want it set in the KnownZero and KnownOne result values. Reset the
1460     // mask and reapply it to the result values.
1461     InMask = Mask;
1462     InMask.trunc(InBits);
1463     KnownZero &= InMask;
1464     KnownOne  &= InMask;
1465
1466     KnownZero.zext(BitWidth);
1467     KnownOne.zext(BitWidth);
1468
1469     // If the sign bit is known zero or one, the top bits match.
1470     if (SignBitKnownZero)
1471       KnownZero |= NewBits;
1472     else if (SignBitKnownOne)
1473       KnownOne  |= NewBits;
1474     return;
1475   }
1476   case ISD::ANY_EXTEND: {
1477     MVT InVT = Op.getOperand(0).getValueType();
1478     unsigned InBits = InVT.getSizeInBits();
1479     APInt InMask = Mask;
1480     InMask.trunc(InBits);
1481     KnownZero.trunc(InBits);
1482     KnownOne.trunc(InBits);
1483     ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1484     KnownZero.zext(BitWidth);
1485     KnownOne.zext(BitWidth);
1486     return;
1487   }
1488   case ISD::TRUNCATE: {
1489     MVT InVT = Op.getOperand(0).getValueType();
1490     unsigned InBits = InVT.getSizeInBits();
1491     APInt InMask = Mask;
1492     InMask.zext(InBits);
1493     KnownZero.zext(InBits);
1494     KnownOne.zext(InBits);
1495     ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
1496     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1497     KnownZero.trunc(BitWidth);
1498     KnownOne.trunc(BitWidth);
1499     break;
1500   }
1501   case ISD::AssertZext: {
1502     MVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1503     APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
1504     ComputeMaskedBits(Op.getOperand(0), Mask & InMask, KnownZero, 
1505                       KnownOne, Depth+1);
1506     KnownZero |= (~InMask) & Mask;
1507     return;
1508   }
1509   case ISD::FGETSIGN:
1510     // All bits are zero except the low bit.
1511     KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - 1);
1512     return;
1513   
1514   case ISD::SUB: {
1515     if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0))) {
1516       // We know that the top bits of C-X are clear if X contains less bits
1517       // than C (i.e. no wrap-around can happen).  For example, 20-X is
1518       // positive if we can prove that X is >= 0 and < 16.
1519       if (CLHS->getAPIntValue().isNonNegative()) {
1520         unsigned NLZ = (CLHS->getAPIntValue()+1).countLeadingZeros();
1521         // NLZ can't be BitWidth with no sign bit
1522         APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
1523         ComputeMaskedBits(Op.getOperand(1), MaskV, KnownZero2, KnownOne2,
1524                           Depth+1);
1525
1526         // If all of the MaskV bits are known to be zero, then we know the
1527         // output top bits are zero, because we now know that the output is
1528         // from [0-C].
1529         if ((KnownZero2 & MaskV) == MaskV) {
1530           unsigned NLZ2 = CLHS->getAPIntValue().countLeadingZeros();
1531           // Top bits known zero.
1532           KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
1533         }
1534       }
1535     }
1536   }
1537   // fall through
1538   case ISD::ADD: {
1539     // Output known-0 bits are known if clear or set in both the low clear bits
1540     // common to both LHS & RHS.  For example, 8+(X<<3) is known to have the
1541     // low 3 bits clear.
1542     APInt Mask2 = APInt::getLowBitsSet(BitWidth, Mask.countTrailingOnes());
1543     ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
1544     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
1545     unsigned KnownZeroOut = KnownZero2.countTrailingOnes();
1546
1547     ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero2, KnownOne2, Depth+1);
1548     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
1549     KnownZeroOut = std::min(KnownZeroOut,
1550                             KnownZero2.countTrailingOnes());
1551
1552     KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut);
1553     return;
1554   }
1555   case ISD::SREM:
1556     if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1557       APInt RA = Rem->getAPIntValue();
1558       if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
1559         APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
1560         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1561         ComputeMaskedBits(Op.getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
1562
1563         // The sign of a remainder is equal to the sign of the first
1564         // operand (zero being positive).
1565         if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
1566           KnownZero2 |= ~LowBits;
1567         else if (KnownOne2[BitWidth-1])
1568           KnownOne2 |= ~LowBits;
1569
1570         KnownZero |= KnownZero2 & Mask;
1571         KnownOne |= KnownOne2 & Mask;
1572
1573         assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1574       }
1575     }
1576     return;
1577   case ISD::UREM: {
1578     if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1579       APInt RA = Rem->getAPIntValue();
1580       if (RA.isPowerOf2()) {
1581         APInt LowBits = (RA - 1);
1582         APInt Mask2 = LowBits & Mask;
1583         KnownZero |= ~LowBits & Mask;
1584         ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
1585         assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1586         break;
1587       }
1588     }
1589
1590     // Since the result is less than or equal to either operand, any leading
1591     // zero bits in either operand must also exist in the result.
1592     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1593     ComputeMaskedBits(Op.getOperand(0), AllOnes, KnownZero, KnownOne,
1594                       Depth+1);
1595     ComputeMaskedBits(Op.getOperand(1), AllOnes, KnownZero2, KnownOne2,
1596                       Depth+1);
1597
1598     uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
1599                                 KnownZero2.countLeadingOnes());
1600     KnownOne.clear();
1601     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
1602     return;
1603   }
1604   default:
1605     // Allow the target to implement this method for its nodes.
1606     if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
1607   case ISD::INTRINSIC_WO_CHAIN:
1608   case ISD::INTRINSIC_W_CHAIN:
1609   case ISD::INTRINSIC_VOID:
1610       TLI.computeMaskedBitsForTargetNode(Op, Mask, KnownZero, KnownOne, *this);
1611     }
1612     return;
1613   }
1614 }
1615
1616 /// ComputeNumSignBits - Return the number of times the sign bit of the
1617 /// register is replicated into the other bits.  We know that at least 1 bit
1618 /// is always equal to the sign bit (itself), but other cases can give us
1619 /// information.  For example, immediately after an "SRA X, 2", we know that
1620 /// the top 3 bits are all equal to each other, so we return 3.
1621 unsigned SelectionDAG::ComputeNumSignBits(SDOperand Op, unsigned Depth) const{
1622   MVT VT = Op.getValueType();
1623   assert(VT.isInteger() && "Invalid VT!");
1624   unsigned VTBits = VT.getSizeInBits();
1625   unsigned Tmp, Tmp2;
1626   unsigned FirstAnswer = 1;
1627   
1628   if (Depth == 6)
1629     return 1;  // Limit search depth.
1630
1631   switch (Op.getOpcode()) {
1632   default: break;
1633   case ISD::AssertSext:
1634     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
1635     return VTBits-Tmp+1;
1636   case ISD::AssertZext:
1637     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
1638     return VTBits-Tmp;
1639     
1640   case ISD::Constant: {
1641     const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue();
1642     // If negative, return # leading ones.
1643     if (Val.isNegative())
1644       return Val.countLeadingOnes();
1645     
1646     // Return # leading zeros.
1647     return Val.countLeadingZeros();
1648   }
1649     
1650   case ISD::SIGN_EXTEND:
1651     Tmp = VTBits-Op.getOperand(0).getValueType().getSizeInBits();
1652     return ComputeNumSignBits(Op.getOperand(0), Depth+1) + Tmp;
1653     
1654   case ISD::SIGN_EXTEND_INREG:
1655     // Max of the input and what this extends.
1656     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
1657     Tmp = VTBits-Tmp+1;
1658     
1659     Tmp2 = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1660     return std::max(Tmp, Tmp2);
1661
1662   case ISD::SRA:
1663     Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1664     // SRA X, C   -> adds C sign bits.
1665     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1666       Tmp += C->getValue();
1667       if (Tmp > VTBits) Tmp = VTBits;
1668     }
1669     return Tmp;
1670   case ISD::SHL:
1671     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1672       // shl destroys sign bits.
1673       Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1674       if (C->getValue() >= VTBits ||      // Bad shift.
1675           C->getValue() >= Tmp) break;    // Shifted all sign bits out.
1676       return Tmp - C->getValue();
1677     }
1678     break;
1679   case ISD::AND:
1680   case ISD::OR:
1681   case ISD::XOR:    // NOT is handled here.
1682     // Logical binary ops preserve the number of sign bits at the worst.
1683     Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1684     if (Tmp != 1) {
1685       Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1686       FirstAnswer = std::min(Tmp, Tmp2);
1687       // We computed what we know about the sign bits as our first
1688       // answer. Now proceed to the generic code that uses
1689       // ComputeMaskedBits, and pick whichever answer is better.
1690     }
1691     break;
1692
1693   case ISD::SELECT:
1694     Tmp = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1695     if (Tmp == 1) return 1;  // Early out.
1696     Tmp2 = ComputeNumSignBits(Op.getOperand(2), Depth+1);
1697     return std::min(Tmp, Tmp2);
1698     
1699   case ISD::SETCC:
1700     // If setcc returns 0/-1, all bits are sign bits.
1701     if (TLI.getSetCCResultContents() ==
1702         TargetLowering::ZeroOrNegativeOneSetCCResult)
1703       return VTBits;
1704     break;
1705   case ISD::ROTL:
1706   case ISD::ROTR:
1707     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1708       unsigned RotAmt = C->getValue() & (VTBits-1);
1709       
1710       // Handle rotate right by N like a rotate left by 32-N.
1711       if (Op.getOpcode() == ISD::ROTR)
1712         RotAmt = (VTBits-RotAmt) & (VTBits-1);
1713
1714       // If we aren't rotating out all of the known-in sign bits, return the
1715       // number that are left.  This handles rotl(sext(x), 1) for example.
1716       Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1717       if (Tmp > RotAmt+1) return Tmp-RotAmt;
1718     }
1719     break;
1720   case ISD::ADD:
1721     // Add can have at most one carry bit.  Thus we know that the output
1722     // is, at worst, one more bit than the inputs.
1723     Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1724     if (Tmp == 1) return 1;  // Early out.
1725       
1726     // Special case decrementing a value (ADD X, -1):
1727     if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
1728       if (CRHS->isAllOnesValue()) {
1729         APInt KnownZero, KnownOne;
1730         APInt Mask = APInt::getAllOnesValue(VTBits);
1731         ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
1732         
1733         // If the input is known to be 0 or 1, the output is 0/-1, which is all
1734         // sign bits set.
1735         if ((KnownZero | APInt(VTBits, 1)) == Mask)
1736           return VTBits;
1737         
1738         // If we are subtracting one from a positive number, there is no carry
1739         // out of the result.
1740         if (KnownZero.isNegative())
1741           return Tmp;
1742       }
1743       
1744     Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1745     if (Tmp2 == 1) return 1;
1746       return std::min(Tmp, Tmp2)-1;
1747     break;
1748     
1749   case ISD::SUB:
1750     Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1751     if (Tmp2 == 1) return 1;
1752       
1753     // Handle NEG.
1754     if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
1755       if (CLHS->isNullValue()) {
1756         APInt KnownZero, KnownOne;
1757         APInt Mask = APInt::getAllOnesValue(VTBits);
1758         ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1759         // If the input is known to be 0 or 1, the output is 0/-1, which is all
1760         // sign bits set.
1761         if ((KnownZero | APInt(VTBits, 1)) == Mask)
1762           return VTBits;
1763         
1764         // If the input is known to be positive (the sign bit is known clear),
1765         // the output of the NEG has the same number of sign bits as the input.
1766         if (KnownZero.isNegative())
1767           return Tmp2;
1768         
1769         // Otherwise, we treat this like a SUB.
1770       }
1771     
1772     // Sub can have at most one carry bit.  Thus we know that the output
1773     // is, at worst, one more bit than the inputs.
1774     Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1775     if (Tmp == 1) return 1;  // Early out.
1776       return std::min(Tmp, Tmp2)-1;
1777     break;
1778   case ISD::TRUNCATE:
1779     // FIXME: it's tricky to do anything useful for this, but it is an important
1780     // case for targets like X86.
1781     break;
1782   }
1783   
1784   // Handle LOADX separately here. EXTLOAD case will fallthrough.
1785   if (Op.getOpcode() == ISD::LOAD) {
1786     LoadSDNode *LD = cast<LoadSDNode>(Op);
1787     unsigned ExtType = LD->getExtensionType();
1788     switch (ExtType) {
1789     default: break;
1790     case ISD::SEXTLOAD:    // '17' bits known
1791       Tmp = LD->getMemoryVT().getSizeInBits();
1792       return VTBits-Tmp+1;
1793     case ISD::ZEXTLOAD:    // '16' bits known
1794       Tmp = LD->getMemoryVT().getSizeInBits();
1795       return VTBits-Tmp;
1796     }
1797   }
1798
1799   // Allow the target to implement this method for its nodes.
1800   if (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1801       Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 
1802       Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1803       Op.getOpcode() == ISD::INTRINSIC_VOID) {
1804     unsigned NumBits = TLI.ComputeNumSignBitsForTargetNode(Op, Depth);
1805     if (NumBits > 1) FirstAnswer = std::max(FirstAnswer, NumBits);
1806   }
1807   
1808   // Finally, if we can prove that the top bits of the result are 0's or 1's,
1809   // use this information.
1810   APInt KnownZero, KnownOne;
1811   APInt Mask = APInt::getAllOnesValue(VTBits);
1812   ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
1813   
1814   if (KnownZero.isNegative()) {        // sign bit is 0
1815     Mask = KnownZero;
1816   } else if (KnownOne.isNegative()) {  // sign bit is 1;
1817     Mask = KnownOne;
1818   } else {
1819     // Nothing known.
1820     return FirstAnswer;
1821   }
1822   
1823   // Okay, we know that the sign bit in Mask is set.  Use CLZ to determine
1824   // the number of identical bits in the top of the input value.
1825   Mask = ~Mask;
1826   Mask <<= Mask.getBitWidth()-VTBits;
1827   // Return # leading zeros.  We use 'min' here in case Val was zero before
1828   // shifting.  We don't want to return '64' as for an i32 "0".
1829   return std::max(FirstAnswer, std::min(VTBits, Mask.countLeadingZeros()));
1830 }
1831
1832
1833 bool SelectionDAG::isVerifiedDebugInfoDesc(SDOperand Op) const {
1834   GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
1835   if (!GA) return false;
1836   GlobalVariable *GV = dyn_cast<GlobalVariable>(GA->getGlobal());
1837   if (!GV) return false;
1838   MachineModuleInfo *MMI = getMachineModuleInfo();
1839   return MMI && MMI->hasDebugInfo() && MMI->isVerified(GV);
1840 }
1841
1842
1843 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
1844 /// element of the result of the vector shuffle.
1845 SDOperand SelectionDAG::getShuffleScalarElt(const SDNode *N, unsigned Idx) {
1846   MVT VT = N->getValueType(0);
1847   SDOperand PermMask = N->getOperand(2);
1848   unsigned NumElems = PermMask.getNumOperands();
1849   SDOperand V = (Idx < NumElems) ? N->getOperand(0) : N->getOperand(1);
1850   Idx %= NumElems;
1851
1852   if (V.getOpcode() == ISD::BIT_CONVERT) {
1853     V = V.getOperand(0);
1854     if (V.getValueType().getVectorNumElements() != NumElems)
1855       return SDOperand();
1856   }
1857   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
1858     return (Idx == 0) ? V.getOperand(0)
1859                       : getNode(ISD::UNDEF, VT.getVectorElementType());
1860   if (V.getOpcode() == ISD::BUILD_VECTOR)
1861     return V.getOperand(Idx);
1862   if (V.getOpcode() == ISD::VECTOR_SHUFFLE) {
1863     SDOperand Elt = PermMask.getOperand(Idx);
1864     if (Elt.getOpcode() == ISD::UNDEF)
1865       return getNode(ISD::UNDEF, VT.getVectorElementType());
1866     return getShuffleScalarElt(V.Val,cast<ConstantSDNode>(Elt)->getValue());
1867   }
1868   return SDOperand();
1869 }
1870
1871
1872 /// getNode - Gets or creates the specified node.
1873 ///
1874 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT) {
1875   FoldingSetNodeID ID;
1876   AddNodeIDNode(ID, Opcode, getVTList(VT), (SDOperand*)0, 0);
1877   void *IP = 0;
1878   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1879     return SDOperand(E, 0);
1880   SDNode *N = new SDNode(Opcode, SDNode::getSDVTList(VT));
1881   CSEMap.InsertNode(N, IP);
1882   
1883   AllNodes.push_back(N);
1884   return SDOperand(N, 0);
1885 }
1886
1887 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT, SDOperand Operand) {
1888   // Constant fold unary operations with an integer constant operand.
1889   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand.Val)) {
1890     const APInt &Val = C->getAPIntValue();
1891     unsigned BitWidth = VT.getSizeInBits();
1892     switch (Opcode) {
1893     default: break;
1894     case ISD::SIGN_EXTEND:
1895       return getConstant(APInt(Val).sextOrTrunc(BitWidth), VT);
1896     case ISD::ANY_EXTEND:
1897     case ISD::ZERO_EXTEND:
1898     case ISD::TRUNCATE:
1899       return getConstant(APInt(Val).zextOrTrunc(BitWidth), VT);
1900     case ISD::UINT_TO_FP:
1901     case ISD::SINT_TO_FP: {
1902       const uint64_t zero[] = {0, 0};
1903       // No compile time operations on this type.
1904       if (VT==MVT::ppcf128)
1905         break;
1906       APFloat apf = APFloat(APInt(BitWidth, 2, zero));
1907       (void)apf.convertFromAPInt(Val, 
1908                                  Opcode==ISD::SINT_TO_FP,
1909                                  APFloat::rmNearestTiesToEven);
1910       return getConstantFP(apf, VT);
1911     }
1912     case ISD::BIT_CONVERT:
1913       if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
1914         return getConstantFP(Val.bitsToFloat(), VT);
1915       else if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
1916         return getConstantFP(Val.bitsToDouble(), VT);
1917       break;
1918     case ISD::BSWAP:
1919       return getConstant(Val.byteSwap(), VT);
1920     case ISD::CTPOP:
1921       return getConstant(Val.countPopulation(), VT);
1922     case ISD::CTLZ:
1923       return getConstant(Val.countLeadingZeros(), VT);
1924     case ISD::CTTZ:
1925       return getConstant(Val.countTrailingZeros(), VT);
1926     }
1927   }
1928
1929   // Constant fold unary operations with a floating point constant operand.
1930   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand.Val)) {
1931     APFloat V = C->getValueAPF();    // make copy
1932     if (VT != MVT::ppcf128 && Operand.getValueType() != MVT::ppcf128) {
1933       switch (Opcode) {
1934       case ISD::FNEG:
1935         V.changeSign();
1936         return getConstantFP(V, VT);
1937       case ISD::FABS:
1938         V.clearSign();
1939         return getConstantFP(V, VT);
1940       case ISD::FP_ROUND:
1941       case ISD::FP_EXTEND:
1942         // This can return overflow, underflow, or inexact; we don't care.
1943         // FIXME need to be more flexible about rounding mode.
1944         (void)V.convert(*MVTToAPFloatSemantics(VT),
1945                         APFloat::rmNearestTiesToEven);
1946         return getConstantFP(V, VT);
1947       case ISD::FP_TO_SINT:
1948       case ISD::FP_TO_UINT: {
1949         integerPart x;
1950         assert(integerPartWidth >= 64);
1951         // FIXME need to be more flexible about rounding mode.
1952         APFloat::opStatus s = V.convertToInteger(&x, 64U,
1953                               Opcode==ISD::FP_TO_SINT,
1954                               APFloat::rmTowardZero);
1955         if (s==APFloat::opInvalidOp)     // inexact is OK, in fact usual
1956           break;
1957         return getConstant(x, VT);
1958       }
1959       case ISD::BIT_CONVERT:
1960         if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
1961           return getConstant((uint32_t)V.convertToAPInt().getZExtValue(), VT);
1962         else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
1963           return getConstant(V.convertToAPInt().getZExtValue(), VT);
1964         break;
1965       }
1966     }
1967   }
1968
1969   unsigned OpOpcode = Operand.Val->getOpcode();
1970   switch (Opcode) {
1971   case ISD::TokenFactor:
1972   case ISD::MERGE_VALUES:
1973     return Operand;         // Factor or merge of one node?  No need.
1974   case ISD::FP_ROUND: assert(0 && "Invalid method to make FP_ROUND node");
1975   case ISD::FP_EXTEND:
1976     assert(VT.isFloatingPoint() &&
1977            Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
1978     if (Operand.getValueType() == VT) return Operand;  // noop conversion.
1979     if (Operand.getOpcode() == ISD::UNDEF)
1980       return getNode(ISD::UNDEF, VT);
1981     break;
1982   case ISD::SIGN_EXTEND:
1983     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
1984            "Invalid SIGN_EXTEND!");
1985     if (Operand.getValueType() == VT) return Operand;   // noop extension
1986     assert(Operand.getValueType().bitsLT(VT)
1987            && "Invalid sext node, dst < src!");
1988     if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
1989       return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
1990     break;
1991   case ISD::ZERO_EXTEND:
1992     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
1993            "Invalid ZERO_EXTEND!");
1994     if (Operand.getValueType() == VT) return Operand;   // noop extension
1995     assert(Operand.getValueType().bitsLT(VT)
1996            && "Invalid zext node, dst < src!");
1997     if (OpOpcode == ISD::ZERO_EXTEND)   // (zext (zext x)) -> (zext x)
1998       return getNode(ISD::ZERO_EXTEND, VT, Operand.Val->getOperand(0));
1999     break;
2000   case ISD::ANY_EXTEND:
2001     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2002            "Invalid ANY_EXTEND!");
2003     if (Operand.getValueType() == VT) return Operand;   // noop extension
2004     assert(Operand.getValueType().bitsLT(VT)
2005            && "Invalid anyext node, dst < src!");
2006     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND)
2007       // (ext (zext x)) -> (zext x)  and  (ext (sext x)) -> (sext x)
2008       return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
2009     break;
2010   case ISD::TRUNCATE:
2011     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2012            "Invalid TRUNCATE!");
2013     if (Operand.getValueType() == VT) return Operand;   // noop truncate
2014     assert(Operand.getValueType().bitsGT(VT)
2015            && "Invalid truncate node, src < dst!");
2016     if (OpOpcode == ISD::TRUNCATE)
2017       return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
2018     else if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
2019              OpOpcode == ISD::ANY_EXTEND) {
2020       // If the source is smaller than the dest, we still need an extend.
2021       if (Operand.Val->getOperand(0).getValueType().bitsLT(VT))
2022         return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
2023       else if (Operand.Val->getOperand(0).getValueType().bitsGT(VT))
2024         return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
2025       else
2026         return Operand.Val->getOperand(0);
2027     }
2028     break;
2029   case ISD::BIT_CONVERT:
2030     // Basic sanity checking.
2031     assert(VT.getSizeInBits() == Operand.getValueType().getSizeInBits()
2032            && "Cannot BIT_CONVERT between types of different sizes!");
2033     if (VT == Operand.getValueType()) return Operand;  // noop conversion.
2034     if (OpOpcode == ISD::BIT_CONVERT)  // bitconv(bitconv(x)) -> bitconv(x)
2035       return getNode(ISD::BIT_CONVERT, VT, Operand.getOperand(0));
2036     if (OpOpcode == ISD::UNDEF)
2037       return getNode(ISD::UNDEF, VT);
2038     break;
2039   case ISD::SCALAR_TO_VECTOR:
2040     assert(VT.isVector() && !Operand.getValueType().isVector() &&
2041            VT.getVectorElementType() == Operand.getValueType() &&
2042            "Illegal SCALAR_TO_VECTOR node!");
2043     if (OpOpcode == ISD::UNDEF)
2044       return getNode(ISD::UNDEF, VT);
2045     // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
2046     if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
2047         isa<ConstantSDNode>(Operand.getOperand(1)) &&
2048         Operand.getConstantOperandVal(1) == 0 &&
2049         Operand.getOperand(0).getValueType() == VT)
2050       return Operand.getOperand(0);
2051     break;
2052   case ISD::FNEG:
2053     if (OpOpcode == ISD::FSUB)   // -(X-Y) -> (Y-X)
2054       return getNode(ISD::FSUB, VT, Operand.Val->getOperand(1),
2055                      Operand.Val->getOperand(0));
2056     if (OpOpcode == ISD::FNEG)  // --X -> X
2057       return Operand.Val->getOperand(0);
2058     break;
2059   case ISD::FABS:
2060     if (OpOpcode == ISD::FNEG)  // abs(-X) -> abs(X)
2061       return getNode(ISD::FABS, VT, Operand.Val->getOperand(0));
2062     break;
2063   }
2064
2065   SDNode *N;
2066   SDVTList VTs = getVTList(VT);
2067   if (VT != MVT::Flag) { // Don't CSE flag producing nodes
2068     FoldingSetNodeID ID;
2069     SDOperand Ops[1] = { Operand };
2070     AddNodeIDNode(ID, Opcode, VTs, Ops, 1);
2071     void *IP = 0;
2072     if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2073       return SDOperand(E, 0);
2074     N = new UnarySDNode(Opcode, VTs, Operand);
2075     CSEMap.InsertNode(N, IP);
2076   } else {
2077     N = new UnarySDNode(Opcode, VTs, Operand);
2078   }
2079   AllNodes.push_back(N);
2080   return SDOperand(N, 0);
2081 }
2082
2083
2084
2085 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
2086                                 SDOperand N1, SDOperand N2) {
2087   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
2088   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
2089   switch (Opcode) {
2090   default: break;
2091   case ISD::TokenFactor:
2092     assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
2093            N2.getValueType() == MVT::Other && "Invalid token factor!");
2094     // Fold trivial token factors.
2095     if (N1.getOpcode() == ISD::EntryToken) return N2;
2096     if (N2.getOpcode() == ISD::EntryToken) return N1;
2097     break;
2098   case ISD::AND:
2099     assert(VT.isInteger() && N1.getValueType() == N2.getValueType() &&
2100            N1.getValueType() == VT && "Binary operator types must match!");
2101     // (X & 0) -> 0.  This commonly occurs when legalizing i64 values, so it's
2102     // worth handling here.
2103     if (N2C && N2C->isNullValue())
2104       return N2;
2105     if (N2C && N2C->isAllOnesValue())  // X & -1 -> X
2106       return N1;
2107     break;
2108   case ISD::OR:
2109   case ISD::XOR:
2110   case ISD::ADD:
2111   case ISD::SUB:
2112     assert(VT.isInteger() && N1.getValueType() == N2.getValueType() &&
2113            N1.getValueType() == VT && "Binary operator types must match!");
2114     // (X ^|+- 0) -> X.  This commonly occurs when legalizing i64 values, so
2115     // it's worth handling here.
2116     if (N2C && N2C->isNullValue())
2117       return N1;
2118     break;
2119   case ISD::UDIV:
2120   case ISD::UREM:
2121   case ISD::MULHU:
2122   case ISD::MULHS:
2123     assert(VT.isInteger() && "This operator does not apply to FP types!");
2124     // fall through
2125   case ISD::MUL:
2126   case ISD::SDIV:
2127   case ISD::SREM:
2128   case ISD::FADD:
2129   case ISD::FSUB:
2130   case ISD::FMUL:
2131   case ISD::FDIV:
2132   case ISD::FREM:
2133     assert(N1.getValueType() == N2.getValueType() &&
2134            N1.getValueType() == VT && "Binary operator types must match!");
2135     break;
2136   case ISD::FCOPYSIGN:   // N1 and result must match.  N1/N2 need not match.
2137     assert(N1.getValueType() == VT &&
2138            N1.getValueType().isFloatingPoint() &&
2139            N2.getValueType().isFloatingPoint() &&
2140            "Invalid FCOPYSIGN!");
2141     break;
2142   case ISD::SHL:
2143   case ISD::SRA:
2144   case ISD::SRL:
2145   case ISD::ROTL:
2146   case ISD::ROTR:
2147     assert(VT == N1.getValueType() &&
2148            "Shift operators return type must be the same as their first arg");
2149     assert(VT.isInteger() && N2.getValueType().isInteger() &&
2150            VT != MVT::i1 && "Shifts only work on integers");
2151     break;
2152   case ISD::FP_ROUND_INREG: {
2153     MVT EVT = cast<VTSDNode>(N2)->getVT();
2154     assert(VT == N1.getValueType() && "Not an inreg round!");
2155     assert(VT.isFloatingPoint() && EVT.isFloatingPoint() &&
2156            "Cannot FP_ROUND_INREG integer types");
2157     assert(EVT.bitsLE(VT) && "Not rounding down!");
2158     if (cast<VTSDNode>(N2)->getVT() == VT) return N1;  // Not actually rounding.
2159     break;
2160   }
2161   case ISD::FP_ROUND:
2162     assert(VT.isFloatingPoint() &&
2163            N1.getValueType().isFloatingPoint() &&
2164            VT.bitsLE(N1.getValueType()) &&
2165            isa<ConstantSDNode>(N2) && "Invalid FP_ROUND!");
2166     if (N1.getValueType() == VT) return N1;  // noop conversion.
2167     break;
2168   case ISD::AssertSext:
2169   case ISD::AssertZext: {
2170     MVT EVT = cast<VTSDNode>(N2)->getVT();
2171     assert(VT == N1.getValueType() && "Not an inreg extend!");
2172     assert(VT.isInteger() && EVT.isInteger() &&
2173            "Cannot *_EXTEND_INREG FP types");
2174     assert(EVT.bitsLE(VT) && "Not extending!");
2175     if (VT == EVT) return N1; // noop assertion.
2176     break;
2177   }
2178   case ISD::SIGN_EXTEND_INREG: {
2179     MVT EVT = cast<VTSDNode>(N2)->getVT();
2180     assert(VT == N1.getValueType() && "Not an inreg extend!");
2181     assert(VT.isInteger() && EVT.isInteger() &&
2182            "Cannot *_EXTEND_INREG FP types");
2183     assert(EVT.bitsLE(VT) && "Not extending!");
2184     if (EVT == VT) return N1;  // Not actually extending
2185
2186     if (N1C) {
2187       APInt Val = N1C->getAPIntValue();
2188       unsigned FromBits = cast<VTSDNode>(N2)->getVT().getSizeInBits();
2189       Val <<= Val.getBitWidth()-FromBits;
2190       Val = Val.ashr(Val.getBitWidth()-FromBits);
2191       return getConstant(Val, VT);
2192     }
2193     break;
2194   }
2195   case ISD::EXTRACT_VECTOR_ELT:
2196     assert(N2C && "Bad EXTRACT_VECTOR_ELT!");
2197
2198     // EXTRACT_VECTOR_ELT of an UNDEF is an UNDEF.
2199     if (N1.getOpcode() == ISD::UNDEF)
2200       return getNode(ISD::UNDEF, VT);
2201       
2202     // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
2203     // expanding copies of large vectors from registers.
2204     if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
2205         N1.getNumOperands() > 0) {
2206       unsigned Factor =
2207         N1.getOperand(0).getValueType().getVectorNumElements();
2208       return getNode(ISD::EXTRACT_VECTOR_ELT, VT,
2209                      N1.getOperand(N2C->getValue() / Factor),
2210                      getConstant(N2C->getValue() % Factor, N2.getValueType()));
2211     }
2212
2213     // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is
2214     // expanding large vector constants.
2215     if (N1.getOpcode() == ISD::BUILD_VECTOR)
2216       return N1.getOperand(N2C->getValue());
2217       
2218     // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
2219     // operations are lowered to scalars.
2220     if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT)
2221       if (ConstantSDNode *IEC = dyn_cast<ConstantSDNode>(N1.getOperand(2))) {
2222         if (IEC == N2C)
2223           return N1.getOperand(1);
2224         else
2225           return getNode(ISD::EXTRACT_VECTOR_ELT, VT, N1.getOperand(0), N2);
2226       }
2227     break;
2228   case ISD::EXTRACT_ELEMENT:
2229     assert(N2C && (unsigned)N2C->getValue() < 2 && "Bad EXTRACT_ELEMENT!");
2230     assert(!N1.getValueType().isVector() &&
2231            N1.getValueType().isInteger() &&
2232            !VT.isVector() && VT.isInteger() &&
2233            "EXTRACT_ELEMENT only applies to integers!");
2234
2235     // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
2236     // 64-bit integers into 32-bit parts.  Instead of building the extract of
2237     // the BUILD_PAIR, only to have legalize rip it apart, just do it now. 
2238     if (N1.getOpcode() == ISD::BUILD_PAIR)
2239       return N1.getOperand(N2C->getValue());
2240
2241     // EXTRACT_ELEMENT of a constant int is also very common.
2242     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2243       unsigned ElementSize = VT.getSizeInBits();
2244       unsigned Shift = ElementSize * N2C->getValue();
2245       APInt ShiftedVal = C->getAPIntValue().lshr(Shift);
2246       return getConstant(ShiftedVal.trunc(ElementSize), VT);
2247     }
2248     break;
2249   case ISD::EXTRACT_SUBVECTOR:
2250     if (N1.getValueType() == VT) // Trivial extraction.
2251       return N1;
2252     break;
2253   }
2254
2255   if (N1C) {
2256     if (N2C) {
2257       APInt C1 = N1C->getAPIntValue(), C2 = N2C->getAPIntValue();
2258       switch (Opcode) {
2259       case ISD::ADD: return getConstant(C1 + C2, VT);
2260       case ISD::SUB: return getConstant(C1 - C2, VT);
2261       case ISD::MUL: return getConstant(C1 * C2, VT);
2262       case ISD::UDIV:
2263         if (C2.getBoolValue()) return getConstant(C1.udiv(C2), VT);
2264         break;
2265       case ISD::UREM :
2266         if (C2.getBoolValue()) return getConstant(C1.urem(C2), VT);
2267         break;
2268       case ISD::SDIV :
2269         if (C2.getBoolValue()) return getConstant(C1.sdiv(C2), VT);
2270         break;
2271       case ISD::SREM :
2272         if (C2.getBoolValue()) return getConstant(C1.srem(C2), VT);
2273         break;
2274       case ISD::AND  : return getConstant(C1 & C2, VT);
2275       case ISD::OR   : return getConstant(C1 | C2, VT);
2276       case ISD::XOR  : return getConstant(C1 ^ C2, VT);
2277       case ISD::SHL  : return getConstant(C1 << C2, VT);
2278       case ISD::SRL  : return getConstant(C1.lshr(C2), VT);
2279       case ISD::SRA  : return getConstant(C1.ashr(C2), VT);
2280       case ISD::ROTL : return getConstant(C1.rotl(C2), VT);
2281       case ISD::ROTR : return getConstant(C1.rotr(C2), VT);
2282       default: break;
2283       }
2284     } else {      // Cannonicalize constant to RHS if commutative
2285       if (isCommutativeBinOp(Opcode)) {
2286         std::swap(N1C, N2C);
2287         std::swap(N1, N2);
2288       }
2289     }
2290   }
2291
2292   // Constant fold FP operations.
2293   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1.Val);
2294   ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2.Val);
2295   if (N1CFP) {
2296     if (!N2CFP && isCommutativeBinOp(Opcode)) {
2297       // Cannonicalize constant to RHS if commutative
2298       std::swap(N1CFP, N2CFP);
2299       std::swap(N1, N2);
2300     } else if (N2CFP && VT != MVT::ppcf128) {
2301       APFloat V1 = N1CFP->getValueAPF(), V2 = N2CFP->getValueAPF();
2302       APFloat::opStatus s;
2303       switch (Opcode) {
2304       case ISD::FADD: 
2305         s = V1.add(V2, APFloat::rmNearestTiesToEven);
2306         if (s != APFloat::opInvalidOp)
2307           return getConstantFP(V1, VT);
2308         break;
2309       case ISD::FSUB: 
2310         s = V1.subtract(V2, APFloat::rmNearestTiesToEven);
2311         if (s!=APFloat::opInvalidOp)
2312           return getConstantFP(V1, VT);
2313         break;
2314       case ISD::FMUL:
2315         s = V1.multiply(V2, APFloat::rmNearestTiesToEven);
2316         if (s!=APFloat::opInvalidOp)
2317           return getConstantFP(V1, VT);
2318         break;
2319       case ISD::FDIV:
2320         s = V1.divide(V2, APFloat::rmNearestTiesToEven);
2321         if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2322           return getConstantFP(V1, VT);
2323         break;
2324       case ISD::FREM :
2325         s = V1.mod(V2, APFloat::rmNearestTiesToEven);
2326         if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2327           return getConstantFP(V1, VT);
2328         break;
2329       case ISD::FCOPYSIGN:
2330         V1.copySign(V2);
2331         return getConstantFP(V1, VT);
2332       default: break;
2333       }
2334     }
2335   }
2336   
2337   // Canonicalize an UNDEF to the RHS, even over a constant.
2338   if (N1.getOpcode() == ISD::UNDEF) {
2339     if (isCommutativeBinOp(Opcode)) {
2340       std::swap(N1, N2);
2341     } else {
2342       switch (Opcode) {
2343       case ISD::FP_ROUND_INREG:
2344       case ISD::SIGN_EXTEND_INREG:
2345       case ISD::SUB:
2346       case ISD::FSUB:
2347       case ISD::FDIV:
2348       case ISD::FREM:
2349       case ISD::SRA:
2350         return N1;     // fold op(undef, arg2) -> undef
2351       case ISD::UDIV:
2352       case ISD::SDIV:
2353       case ISD::UREM:
2354       case ISD::SREM:
2355       case ISD::SRL:
2356       case ISD::SHL:
2357         if (!VT.isVector())
2358           return getConstant(0, VT);    // fold op(undef, arg2) -> 0
2359         // For vectors, we can't easily build an all zero vector, just return
2360         // the LHS.
2361         return N2;
2362       }
2363     }
2364   }
2365   
2366   // Fold a bunch of operators when the RHS is undef. 
2367   if (N2.getOpcode() == ISD::UNDEF) {
2368     switch (Opcode) {
2369     case ISD::XOR:
2370       if (N1.getOpcode() == ISD::UNDEF)
2371         // Handle undef ^ undef -> 0 special case. This is a common
2372         // idiom (misuse).
2373         return getConstant(0, VT);
2374       // fallthrough
2375     case ISD::ADD:
2376     case ISD::ADDC:
2377     case ISD::ADDE:
2378     case ISD::SUB:
2379     case ISD::FADD:
2380     case ISD::FSUB:
2381     case ISD::FMUL:
2382     case ISD::FDIV:
2383     case ISD::FREM:
2384     case ISD::UDIV:
2385     case ISD::SDIV:
2386     case ISD::UREM:
2387     case ISD::SREM:
2388       return N2;       // fold op(arg1, undef) -> undef
2389     case ISD::MUL: 
2390     case ISD::AND:
2391     case ISD::SRL:
2392     case ISD::SHL:
2393       if (!VT.isVector())
2394         return getConstant(0, VT);  // fold op(arg1, undef) -> 0
2395       // For vectors, we can't easily build an all zero vector, just return
2396       // the LHS.
2397       return N1;
2398     case ISD::OR:
2399       if (!VT.isVector())
2400         return getConstant(VT.getIntegerVTBitMask(), VT);
2401       // For vectors, we can't easily build an all one vector, just return
2402       // the LHS.
2403       return N1;
2404     case ISD::SRA:
2405       return N1;
2406     }
2407   }
2408
2409   // Memoize this node if possible.
2410   SDNode *N;
2411   SDVTList VTs = getVTList(VT);
2412   if (VT != MVT::Flag) {
2413     SDOperand Ops[] = { N1, N2 };
2414     FoldingSetNodeID ID;
2415     AddNodeIDNode(ID, Opcode, VTs, Ops, 2);
2416     void *IP = 0;
2417     if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2418       return SDOperand(E, 0);
2419     N = new BinarySDNode(Opcode, VTs, N1, N2);
2420     CSEMap.InsertNode(N, IP);
2421   } else {
2422     N = new BinarySDNode(Opcode, VTs, N1, N2);
2423   }
2424
2425   AllNodes.push_back(N);
2426   return SDOperand(N, 0);
2427 }
2428
2429 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
2430                                 SDOperand N1, SDOperand N2, SDOperand N3) {
2431   // Perform various simplifications.
2432   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
2433   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
2434   switch (Opcode) {
2435   case ISD::SETCC: {
2436     // Use FoldSetCC to simplify SETCC's.
2437     SDOperand Simp = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get());
2438     if (Simp.Val) return Simp;
2439     break;
2440   }
2441   case ISD::SELECT:
2442     if (N1C) {
2443      if (N1C->getValue())
2444         return N2;             // select true, X, Y -> X
2445       else
2446         return N3;             // select false, X, Y -> Y
2447     }
2448
2449     if (N2 == N3) return N2;   // select C, X, X -> X
2450     break;
2451   case ISD::BRCOND:
2452     if (N2C) {
2453       if (N2C->getValue()) // Unconditional branch
2454         return getNode(ISD::BR, MVT::Other, N1, N3);
2455       else
2456         return N1;         // Never-taken branch
2457     }
2458     break;
2459   case ISD::VECTOR_SHUFFLE:
2460     assert(VT == N1.getValueType() && VT == N2.getValueType() &&
2461            VT.isVector() && N3.getValueType().isVector() &&
2462            N3.getOpcode() == ISD::BUILD_VECTOR &&
2463            VT.getVectorNumElements() == N3.getNumOperands() &&
2464            "Illegal VECTOR_SHUFFLE node!");
2465     break;
2466   case ISD::BIT_CONVERT:
2467     // Fold bit_convert nodes from a type to themselves.
2468     if (N1.getValueType() == VT)
2469       return N1;
2470     break;
2471   }
2472
2473   // Memoize node if it doesn't produce a flag.
2474   SDNode *N;
2475   SDVTList VTs = getVTList(VT);
2476   if (VT != MVT::Flag) {
2477     SDOperand Ops[] = { N1, N2, N3 };
2478     FoldingSetNodeID ID;
2479     AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
2480     void *IP = 0;
2481     if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2482       return SDOperand(E, 0);
2483     N = new TernarySDNode(Opcode, VTs, N1, N2, N3);
2484     CSEMap.InsertNode(N, IP);
2485   } else {
2486     N = new TernarySDNode(Opcode, VTs, N1, N2, N3);
2487   }
2488   AllNodes.push_back(N);
2489   return SDOperand(N, 0);
2490 }
2491
2492 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
2493                                 SDOperand N1, SDOperand N2, SDOperand N3,
2494                                 SDOperand N4) {
2495   SDOperand Ops[] = { N1, N2, N3, N4 };
2496   return getNode(Opcode, VT, Ops, 4);
2497 }
2498
2499 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
2500                                 SDOperand N1, SDOperand N2, SDOperand N3,
2501                                 SDOperand N4, SDOperand N5) {
2502   SDOperand Ops[] = { N1, N2, N3, N4, N5 };
2503   return getNode(Opcode, VT, Ops, 5);
2504 }
2505
2506 /// getMemsetValue - Vectorized representation of the memset value
2507 /// operand.
2508 static SDOperand getMemsetValue(SDOperand Value, MVT VT, SelectionDAG &DAG) {
2509   unsigned NumBits = VT.isVector() ?
2510     VT.getVectorElementType().getSizeInBits() : VT.getSizeInBits();
2511   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
2512     APInt Val = APInt(NumBits, C->getValue() & 255);
2513     unsigned Shift = 8;
2514     for (unsigned i = NumBits; i > 8; i >>= 1) {
2515       Val = (Val << Shift) | Val;
2516       Shift <<= 1;
2517     }
2518     if (VT.isInteger())
2519       return DAG.getConstant(Val, VT);
2520     return DAG.getConstantFP(APFloat(Val), VT);
2521   }
2522
2523   Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
2524   unsigned Shift = 8;
2525   for (unsigned i = NumBits; i > 8; i >>= 1) {
2526     Value = DAG.getNode(ISD::OR, VT,
2527                         DAG.getNode(ISD::SHL, VT, Value,
2528                                     DAG.getConstant(Shift, MVT::i8)), Value);
2529     Shift <<= 1;
2530   }
2531
2532   return Value;
2533 }
2534
2535 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
2536 /// used when a memcpy is turned into a memset when the source is a constant
2537 /// string ptr.
2538 static SDOperand getMemsetStringVal(MVT VT, SelectionDAG &DAG,
2539                                     const TargetLowering &TLI,
2540                                     std::string &Str, unsigned Offset) {
2541   assert(!VT.isVector() && "Can't handle vector type here!");
2542   unsigned NumBits = VT.getSizeInBits();
2543   unsigned MSB = NumBits / 8;
2544   uint64_t Val = 0;
2545   if (TLI.isLittleEndian())
2546     Offset = Offset + MSB - 1;
2547   for (unsigned i = 0; i != MSB; ++i) {
2548     Val = (Val << 8) | (unsigned char)Str[Offset];
2549     Offset += TLI.isLittleEndian() ? -1 : 1;
2550   }
2551   return DAG.getConstant(Val, VT);
2552 }
2553
2554 /// getMemBasePlusOffset - Returns base and offset node for the 
2555 ///
2556 static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
2557                                       SelectionDAG &DAG) {
2558   MVT VT = Base.getValueType();
2559   return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
2560 }
2561
2562 /// isMemSrcFromString - Returns true if memcpy source is a string constant.
2563 ///
2564 static bool isMemSrcFromString(SDOperand Src, std::string &Str,
2565                                uint64_t &SrcOff) {
2566   unsigned SrcDelta = 0;
2567   GlobalAddressSDNode *G = NULL;
2568   if (Src.getOpcode() == ISD::GlobalAddress)
2569     G = cast<GlobalAddressSDNode>(Src);
2570   else if (Src.getOpcode() == ISD::ADD &&
2571            Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
2572            Src.getOperand(1).getOpcode() == ISD::Constant) {
2573     G = cast<GlobalAddressSDNode>(Src.getOperand(0));
2574     SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getValue();
2575   }
2576   if (!G)
2577     return false;
2578
2579   GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
2580   if (GV && GV->isConstant()) {
2581     Str = GV->getStringValue(false);
2582     if (!Str.empty()) {
2583       SrcOff += SrcDelta;
2584       return true;
2585     }
2586   }
2587
2588   return false;
2589 }
2590
2591 /// MeetsMaxMemopRequirement - Determines if the number of memory ops required
2592 /// to replace the memset / memcpy is below the threshold. It also returns the
2593 /// types of the sequence of memory ops to perform memset / memcpy.
2594 static
2595 bool MeetsMaxMemopRequirement(std::vector<MVT> &MemOps,
2596                               SDOperand Dst, SDOperand Src,
2597                               unsigned Limit, uint64_t Size, unsigned &Align,
2598                               SelectionDAG &DAG,
2599                               const TargetLowering &TLI) {
2600   bool AllowUnalign = TLI.allowsUnalignedMemoryAccesses();
2601
2602   std::string Str;
2603   uint64_t SrcOff = 0;
2604   bool isSrcStr = isMemSrcFromString(Src, Str, SrcOff);
2605   bool isSrcConst = isa<ConstantSDNode>(Src);
2606   MVT VT= TLI.getOptimalMemOpType(Size, Align, isSrcConst, isSrcStr);
2607   if (VT != MVT::iAny) {
2608     unsigned NewAlign = (unsigned)
2609       TLI.getTargetData()->getABITypeAlignment(VT.getTypeForMVT());
2610     // If source is a string constant, this will require an unaligned load.
2611     if (NewAlign > Align && (isSrcConst || AllowUnalign)) {
2612       if (Dst.getOpcode() != ISD::FrameIndex) {
2613         // Can't change destination alignment. It requires a unaligned store.
2614         if (AllowUnalign)
2615           VT = MVT::iAny;
2616       } else {
2617         int FI = cast<FrameIndexSDNode>(Dst)->getIndex();
2618         MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2619         if (MFI->isFixedObjectIndex(FI)) {
2620           // Can't change destination alignment. It requires a unaligned store.
2621           if (AllowUnalign)
2622             VT = MVT::iAny;
2623         } else {
2624           // Give the stack frame object a larger alignment if needed.
2625           if (MFI->getObjectAlignment(FI) < NewAlign)
2626             MFI->setObjectAlignment(FI, NewAlign);
2627           Align = NewAlign;
2628         }
2629       }
2630     }
2631   }
2632
2633   if (VT == MVT::iAny) {
2634     if (AllowUnalign) {
2635       VT = MVT::i64;
2636     } else {
2637       switch (Align & 7) {
2638       case 0:  VT = MVT::i64; break;
2639       case 4:  VT = MVT::i32; break;
2640       case 2:  VT = MVT::i16; break;
2641       default: VT = MVT::i8;  break;
2642       }
2643     }
2644
2645     MVT LVT = MVT::i64;
2646     while (!TLI.isTypeLegal(LVT))
2647       LVT = (MVT::SimpleValueType)(LVT.getSimpleVT() - 1);
2648     assert(LVT.isInteger());
2649
2650     if (VT.bitsGT(LVT))
2651       VT = LVT;
2652   }
2653
2654   unsigned NumMemOps = 0;
2655   while (Size != 0) {
2656     unsigned VTSize = VT.getSizeInBits() / 8;
2657     while (VTSize > Size) {
2658       // For now, only use non-vector load / store's for the left-over pieces.
2659       if (VT.isVector()) {
2660         VT = MVT::i64;
2661         while (!TLI.isTypeLegal(VT))
2662           VT = (MVT::SimpleValueType)(VT.getSimpleVT() - 1);
2663         VTSize = VT.getSizeInBits() / 8;
2664       } else {
2665         VT = (MVT::SimpleValueType)(VT.getSimpleVT() - 1);
2666         VTSize >>= 1;
2667       }
2668     }
2669
2670     if (++NumMemOps > Limit)
2671       return false;
2672     MemOps.push_back(VT);
2673     Size -= VTSize;
2674   }
2675
2676   return true;
2677 }
2678
2679 static SDOperand getMemcpyLoadsAndStores(SelectionDAG &DAG,
2680                                          SDOperand Chain, SDOperand Dst,
2681                                          SDOperand Src, uint64_t Size,
2682                                          unsigned Align, bool AlwaysInline,
2683                                          const Value *DstSV, uint64_t DstSVOff,
2684                                          const Value *SrcSV, uint64_t SrcSVOff){
2685   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2686
2687   // Expand memcpy to a series of load and store ops if the size operand falls
2688   // below a certain threshold.
2689   std::vector<MVT> MemOps;
2690   uint64_t Limit = -1;
2691   if (!AlwaysInline)
2692     Limit = TLI.getMaxStoresPerMemcpy();
2693   unsigned DstAlign = Align;  // Destination alignment can change.
2694   if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, Limit, Size, DstAlign,
2695                                 DAG, TLI))
2696     return SDOperand();
2697
2698   std::string Str;
2699   uint64_t SrcOff = 0, DstOff = 0;
2700   bool CopyFromStr = isMemSrcFromString(Src, Str, SrcOff);
2701
2702   SmallVector<SDOperand, 8> OutChains;
2703   unsigned NumMemOps = MemOps.size();
2704   for (unsigned i = 0; i < NumMemOps; i++) {
2705     MVT VT = MemOps[i];
2706     unsigned VTSize = VT.getSizeInBits() / 8;
2707     SDOperand Value, Store;
2708
2709     if (CopyFromStr && !VT.isVector()) {
2710       // It's unlikely a store of a vector immediate can be done in a single
2711       // instruction. It would require a load from a constantpool first.
2712       // FIXME: Handle cases where store of vector immediate is done in a
2713       // single instruction.
2714       Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
2715       Store = DAG.getStore(Chain, Value,
2716                            getMemBasePlusOffset(Dst, DstOff, DAG),
2717                            DstSV, DstSVOff + DstOff);
2718     } else {
2719       Value = DAG.getLoad(VT, Chain,
2720                           getMemBasePlusOffset(Src, SrcOff, DAG),
2721                           SrcSV, SrcSVOff + SrcOff, false, Align);
2722       Store = DAG.getStore(Chain, Value,
2723                            getMemBasePlusOffset(Dst, DstOff, DAG),
2724                            DstSV, DstSVOff + DstOff, false, DstAlign);
2725     }
2726     OutChains.push_back(Store);
2727     SrcOff += VTSize;
2728     DstOff += VTSize;
2729   }
2730
2731   return DAG.getNode(ISD::TokenFactor, MVT::Other,
2732                      &OutChains[0], OutChains.size());
2733 }
2734
2735 static SDOperand getMemmoveLoadsAndStores(SelectionDAG &DAG,
2736                                           SDOperand Chain, SDOperand Dst,
2737                                           SDOperand Src, uint64_t Size,
2738                                           unsigned Align, bool AlwaysInline,
2739                                           const Value *DstSV, uint64_t DstSVOff,
2740                                           const Value *SrcSV, uint64_t SrcSVOff){
2741   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2742
2743   // Expand memmove to a series of load and store ops if the size operand falls
2744   // below a certain threshold.
2745   std::vector<MVT> MemOps;
2746   uint64_t Limit = -1;
2747   if (!AlwaysInline)
2748     Limit = TLI.getMaxStoresPerMemmove();
2749   unsigned DstAlign = Align;  // Destination alignment can change.
2750   if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, Limit, Size, DstAlign,
2751                                 DAG, TLI))
2752     return SDOperand();
2753
2754   uint64_t SrcOff = 0, DstOff = 0;
2755
2756   SmallVector<SDOperand, 8> LoadValues;
2757   SmallVector<SDOperand, 8> LoadChains;
2758   SmallVector<SDOperand, 8> OutChains;
2759   unsigned NumMemOps = MemOps.size();
2760   for (unsigned i = 0; i < NumMemOps; i++) {
2761     MVT VT = MemOps[i];
2762     unsigned VTSize = VT.getSizeInBits() / 8;
2763     SDOperand Value, Store;
2764
2765     Value = DAG.getLoad(VT, Chain,
2766                         getMemBasePlusOffset(Src, SrcOff, DAG),
2767                         SrcSV, SrcSVOff + SrcOff, false, Align);
2768     LoadValues.push_back(Value);
2769     LoadChains.push_back(Value.getValue(1));
2770     SrcOff += VTSize;
2771   }
2772   Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2773                       &LoadChains[0], LoadChains.size());
2774   OutChains.clear();
2775   for (unsigned i = 0; i < NumMemOps; i++) {
2776     MVT VT = MemOps[i];
2777     unsigned VTSize = VT.getSizeInBits() / 8;
2778     SDOperand Value, Store;
2779
2780     Store = DAG.getStore(Chain, LoadValues[i],
2781                          getMemBasePlusOffset(Dst, DstOff, DAG),
2782                          DstSV, DstSVOff + DstOff, false, DstAlign);
2783     OutChains.push_back(Store);
2784     DstOff += VTSize;
2785   }
2786
2787   return DAG.getNode(ISD::TokenFactor, MVT::Other,
2788                      &OutChains[0], OutChains.size());
2789 }
2790
2791 static SDOperand getMemsetStores(SelectionDAG &DAG,
2792                                  SDOperand Chain, SDOperand Dst,
2793                                  SDOperand Src, uint64_t Size,
2794                                  unsigned Align,
2795                                  const Value *DstSV, uint64_t DstSVOff) {
2796   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2797
2798   // Expand memset to a series of load/store ops if the size operand
2799   // falls below a certain threshold.
2800   std::vector<MVT> MemOps;
2801   if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, TLI.getMaxStoresPerMemset(),
2802                                 Size, Align, DAG, TLI))
2803     return SDOperand();
2804
2805   SmallVector<SDOperand, 8> OutChains;
2806   uint64_t DstOff = 0;
2807
2808   unsigned NumMemOps = MemOps.size();
2809   for (unsigned i = 0; i < NumMemOps; i++) {
2810     MVT VT = MemOps[i];
2811     unsigned VTSize = VT.getSizeInBits() / 8;
2812     SDOperand Value = getMemsetValue(Src, VT, DAG);
2813     SDOperand Store = DAG.getStore(Chain, Value,
2814                                    getMemBasePlusOffset(Dst, DstOff, DAG),
2815                                    DstSV, DstSVOff + DstOff);
2816     OutChains.push_back(Store);
2817     DstOff += VTSize;
2818   }
2819
2820   return DAG.getNode(ISD::TokenFactor, MVT::Other,
2821                      &OutChains[0], OutChains.size());
2822 }
2823
2824 SDOperand SelectionDAG::getMemcpy(SDOperand Chain, SDOperand Dst,
2825                                   SDOperand Src, SDOperand Size,
2826                                   unsigned Align, bool AlwaysInline,
2827                                   const Value *DstSV, uint64_t DstSVOff,
2828                                   const Value *SrcSV, uint64_t SrcSVOff) {
2829
2830   // Check to see if we should lower the memcpy to loads and stores first.
2831   // For cases within the target-specified limits, this is the best choice.
2832   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
2833   if (ConstantSize) {
2834     // Memcpy with size zero? Just return the original chain.
2835     if (ConstantSize->isNullValue())
2836       return Chain;
2837
2838     SDOperand Result =
2839       getMemcpyLoadsAndStores(*this, Chain, Dst, Src, ConstantSize->getValue(),
2840                               Align, false, DstSV, DstSVOff, SrcSV, SrcSVOff);
2841     if (Result.Val)
2842       return Result;
2843   }
2844
2845   // Then check to see if we should lower the memcpy with target-specific
2846   // code. If the target chooses to do this, this is the next best.
2847   SDOperand Result =
2848     TLI.EmitTargetCodeForMemcpy(*this, Chain, Dst, Src, Size, Align,
2849                                 AlwaysInline,
2850                                 DstSV, DstSVOff, SrcSV, SrcSVOff);
2851   if (Result.Val)
2852     return Result;
2853
2854   // If we really need inline code and the target declined to provide it,
2855   // use a (potentially long) sequence of loads and stores.
2856   if (AlwaysInline) {
2857     assert(ConstantSize && "AlwaysInline requires a constant size!");
2858     return getMemcpyLoadsAndStores(*this, Chain, Dst, Src,
2859                                    ConstantSize->getValue(), Align, true,
2860                                    DstSV, DstSVOff, SrcSV, SrcSVOff);
2861   }
2862
2863   // Emit a library call.
2864   TargetLowering::ArgListTy Args;
2865   TargetLowering::ArgListEntry Entry;
2866   Entry.Ty = TLI.getTargetData()->getIntPtrType();
2867   Entry.Node = Dst; Args.push_back(Entry);
2868   Entry.Node = Src; Args.push_back(Entry);
2869   Entry.Node = Size; Args.push_back(Entry);
2870   std::pair<SDOperand,SDOperand> CallResult =
2871     TLI.LowerCallTo(Chain, Type::VoidTy,
2872                     false, false, false, CallingConv::C, false,
2873                     getExternalSymbol("memcpy", TLI.getPointerTy()),
2874                     Args, *this);
2875   return CallResult.second;
2876 }
2877
2878 SDOperand SelectionDAG::getMemmove(SDOperand Chain, SDOperand Dst,
2879                                    SDOperand Src, SDOperand Size,
2880                                    unsigned Align,
2881                                    const Value *DstSV, uint64_t DstSVOff,
2882                                    const Value *SrcSV, uint64_t SrcSVOff) {
2883
2884   // Check to see if we should lower the memmove to loads and stores first.
2885   // For cases within the target-specified limits, this is the best choice.
2886   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
2887   if (ConstantSize) {
2888     // Memmove with size zero? Just return the original chain.
2889     if (ConstantSize->isNullValue())
2890       return Chain;
2891
2892     SDOperand Result =
2893       getMemmoveLoadsAndStores(*this, Chain, Dst, Src, ConstantSize->getValue(),
2894                                Align, false, DstSV, DstSVOff, SrcSV, SrcSVOff);
2895     if (Result.Val)
2896       return Result;
2897   }
2898
2899   // Then check to see if we should lower the memmove with target-specific
2900   // code. If the target chooses to do this, this is the next best.
2901   SDOperand Result =
2902     TLI.EmitTargetCodeForMemmove(*this, Chain, Dst, Src, Size, Align,
2903                                  DstSV, DstSVOff, SrcSV, SrcSVOff);
2904   if (Result.Val)
2905     return Result;
2906
2907   // Emit a library call.
2908   TargetLowering::ArgListTy Args;
2909   TargetLowering::ArgListEntry Entry;
2910   Entry.Ty = TLI.getTargetData()->getIntPtrType();
2911   Entry.Node = Dst; Args.push_back(Entry);
2912   Entry.Node = Src; Args.push_back(Entry);
2913   Entry.Node = Size; Args.push_back(Entry);
2914   std::pair<SDOperand,SDOperand> CallResult =
2915     TLI.LowerCallTo(Chain, Type::VoidTy,
2916                     false, false, false, CallingConv::C, false,
2917                     getExternalSymbol("memmove", TLI.getPointerTy()),
2918                     Args, *this);
2919   return CallResult.second;
2920 }
2921
2922 SDOperand SelectionDAG::getMemset(SDOperand Chain, SDOperand Dst,
2923                                   SDOperand Src, SDOperand Size,
2924                                   unsigned Align,
2925                                   const Value *DstSV, uint64_t DstSVOff) {
2926
2927   // Check to see if we should lower the memset to stores first.
2928   // For cases within the target-specified limits, this is the best choice.
2929   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
2930   if (ConstantSize) {
2931     // Memset with size zero? Just return the original chain.
2932     if (ConstantSize->isNullValue())
2933       return Chain;
2934
2935     SDOperand Result =
2936       getMemsetStores(*this, Chain, Dst, Src, ConstantSize->getValue(), Align,
2937                       DstSV, DstSVOff);
2938     if (Result.Val)
2939       return Result;
2940   }
2941
2942   // Then check to see if we should lower the memset with target-specific
2943   // code. If the target chooses to do this, this is the next best.
2944   SDOperand Result =
2945     TLI.EmitTargetCodeForMemset(*this, Chain, Dst, Src, Size, Align,
2946                                 DstSV, DstSVOff);
2947   if (Result.Val)
2948     return Result;
2949
2950   // Emit a library call.
2951   const Type *IntPtrTy = TLI.getTargetData()->getIntPtrType();
2952   TargetLowering::ArgListTy Args;
2953   TargetLowering::ArgListEntry Entry;
2954   Entry.Node = Dst; Entry.Ty = IntPtrTy;
2955   Args.push_back(Entry);
2956   // Extend or truncate the argument to be an i32 value for the call.
2957   if (Src.getValueType().bitsGT(MVT::i32))
2958     Src = getNode(ISD::TRUNCATE, MVT::i32, Src);
2959   else
2960     Src = getNode(ISD::ZERO_EXTEND, MVT::i32, Src);
2961   Entry.Node = Src; Entry.Ty = Type::Int32Ty; Entry.isSExt = true;
2962   Args.push_back(Entry);
2963   Entry.Node = Size; Entry.Ty = IntPtrTy; Entry.isSExt = false;
2964   Args.push_back(Entry);
2965   std::pair<SDOperand,SDOperand> CallResult =
2966     TLI.LowerCallTo(Chain, Type::VoidTy,
2967                     false, false, false, CallingConv::C, false,
2968                     getExternalSymbol("memset", TLI.getPointerTy()),
2969                     Args, *this);
2970   return CallResult.second;
2971 }
2972
2973 SDOperand SelectionDAG::getAtomic(unsigned Opcode, SDOperand Chain, 
2974                                   SDOperand Ptr, SDOperand Cmp, 
2975                                   SDOperand Swp, MVT VT) {
2976   assert(Opcode == ISD::ATOMIC_LCS && "Invalid Atomic Op");
2977   assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
2978   SDVTList VTs = getVTList(Cmp.getValueType(), MVT::Other);
2979   FoldingSetNodeID ID;
2980   SDOperand Ops[] = {Chain, Ptr, Cmp, Swp};
2981   AddNodeIDNode(ID, Opcode, VTs, Ops, 4);
2982   ID.AddInteger(VT.getRawBits());
2983   void* IP = 0;
2984   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2985     return SDOperand(E, 0);
2986   SDNode* N = new AtomicSDNode(Opcode, VTs, Chain, Ptr, Cmp, Swp, VT);
2987   CSEMap.InsertNode(N, IP);
2988   AllNodes.push_back(N);
2989   return SDOperand(N, 0);
2990 }
2991
2992 SDOperand SelectionDAG::getAtomic(unsigned Opcode, SDOperand Chain, 
2993                                   SDOperand Ptr, SDOperand Val, 
2994                                   MVT VT) {
2995   assert((   Opcode == ISD::ATOMIC_LAS || Opcode == ISD::ATOMIC_LSS
2996           || Opcode == ISD::ATOMIC_SWAP || Opcode == ISD::ATOMIC_LOAD_AND
2997           || Opcode == ISD::ATOMIC_LOAD_OR || Opcode == ISD::ATOMIC_LOAD_XOR
2998           || Opcode == ISD::ATOMIC_LOAD_NAND 
2999           || Opcode == ISD::ATOMIC_LOAD_MIN || Opcode == ISD::ATOMIC_LOAD_MAX
3000           || Opcode == ISD::ATOMIC_LOAD_UMIN || Opcode == ISD::ATOMIC_LOAD_UMAX) 
3001          && "Invalid Atomic Op");
3002   SDVTList VTs = getVTList(Val.getValueType(), MVT::Other);
3003   FoldingSetNodeID ID;
3004   SDOperand Ops[] = {Chain, Ptr, Val};
3005   AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
3006   ID.AddInteger(VT.getRawBits());
3007   void* IP = 0;
3008   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3009     return SDOperand(E, 0);
3010   SDNode* N = new AtomicSDNode(Opcode, VTs, Chain, Ptr, Val, VT);
3011   CSEMap.InsertNode(N, IP);
3012   AllNodes.push_back(N);
3013   return SDOperand(N, 0);
3014 }
3015
3016 SDOperand
3017 SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
3018                       MVT VT, SDOperand Chain,
3019                       SDOperand Ptr, SDOperand Offset,
3020                       const Value *SV, int SVOffset, MVT EVT,
3021                       bool isVolatile, unsigned Alignment) {
3022   if (Alignment == 0) { // Ensure that codegen never sees alignment 0
3023     const Type *Ty = 0;
3024     if (VT != MVT::iPTR) {
3025       Ty = VT.getTypeForMVT();
3026     } else if (SV) {
3027       const PointerType *PT = dyn_cast<PointerType>(SV->getType());
3028       assert(PT && "Value for load must be a pointer");
3029       Ty = PT->getElementType();
3030     }
3031     assert(Ty && "Could not get type information for load");
3032     Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
3033   }
3034
3035   if (VT == EVT) {
3036     ExtType = ISD::NON_EXTLOAD;
3037   } else if (ExtType == ISD::NON_EXTLOAD) {
3038     assert(VT == EVT && "Non-extending load from different memory type!");
3039   } else {
3040     // Extending load.
3041     if (VT.isVector())
3042       assert(EVT == VT.getVectorElementType() && "Invalid vector extload!");
3043     else
3044       assert(EVT.bitsLT(VT) &&
3045              "Should only be an extending load, not truncating!");
3046     assert((ExtType == ISD::EXTLOAD || VT.isInteger()) &&
3047            "Cannot sign/zero extend a FP/Vector load!");
3048     assert(VT.isInteger() == EVT.isInteger() &&
3049            "Cannot convert from FP to Int or Int -> FP!");
3050   }
3051
3052   bool Indexed = AM != ISD::UNINDEXED;
3053   assert((Indexed || Offset.getOpcode() == ISD::UNDEF) &&
3054          "Unindexed load with an offset!");
3055
3056   SDVTList VTs = Indexed ?
3057     getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
3058   SDOperand Ops[] = { Chain, Ptr, Offset };
3059   FoldingSetNodeID ID;
3060   AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
3061   ID.AddInteger(AM);
3062   ID.AddInteger(ExtType);
3063   ID.AddInteger(EVT.getRawBits());
3064   ID.AddInteger(Alignment);
3065   ID.AddInteger(isVolatile);
3066   void *IP = 0;
3067   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3068     return SDOperand(E, 0);
3069   SDNode *N = new LoadSDNode(Ops, VTs, AM, ExtType, EVT, SV, SVOffset,
3070                              Alignment, isVolatile);
3071   CSEMap.InsertNode(N, IP);
3072   AllNodes.push_back(N);
3073   return SDOperand(N, 0);
3074 }
3075
3076 SDOperand SelectionDAG::getLoad(MVT VT,
3077                                 SDOperand Chain, SDOperand Ptr,
3078                                 const Value *SV, int SVOffset,
3079                                 bool isVolatile, unsigned Alignment) {
3080   SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3081   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, Chain, Ptr, Undef,
3082                  SV, SVOffset, VT, isVolatile, Alignment);
3083 }
3084
3085 SDOperand SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, MVT VT,
3086                                    SDOperand Chain, SDOperand Ptr,
3087                                    const Value *SV,
3088                                    int SVOffset, MVT EVT,
3089                                    bool isVolatile, unsigned Alignment) {
3090   SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3091   return getLoad(ISD::UNINDEXED, ExtType, VT, Chain, Ptr, Undef,
3092                  SV, SVOffset, EVT, isVolatile, Alignment);
3093 }
3094
3095 SDOperand
3096 SelectionDAG::getIndexedLoad(SDOperand OrigLoad, SDOperand Base,
3097                              SDOperand Offset, ISD::MemIndexedMode AM) {
3098   LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
3099   assert(LD->getOffset().getOpcode() == ISD::UNDEF &&
3100          "Load is already a indexed load!");
3101   return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(),
3102                  LD->getChain(), Base, Offset, LD->getSrcValue(),
3103                  LD->getSrcValueOffset(), LD->getMemoryVT(),
3104                  LD->isVolatile(), LD->getAlignment());
3105 }
3106
3107 SDOperand SelectionDAG::getStore(SDOperand Chain, SDOperand Val,
3108                                  SDOperand Ptr, const Value *SV, int SVOffset,
3109                                  bool isVolatile, unsigned Alignment) {
3110   MVT VT = Val.getValueType();
3111
3112   if (Alignment == 0) { // Ensure that codegen never sees alignment 0
3113     const Type *Ty = 0;
3114     if (VT != MVT::iPTR) {
3115       Ty = VT.getTypeForMVT();
3116     } else if (SV) {
3117       const PointerType *PT = dyn_cast<PointerType>(SV->getType());
3118       assert(PT && "Value for store must be a pointer");
3119       Ty = PT->getElementType();
3120     }
3121     assert(Ty && "Could not get type information for store");
3122     Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
3123   }
3124   SDVTList VTs = getVTList(MVT::Other);
3125   SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3126   SDOperand Ops[] = { Chain, Val, Ptr, Undef };
3127   FoldingSetNodeID ID;
3128   AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3129   ID.AddInteger(ISD::UNINDEXED);
3130   ID.AddInteger(false);
3131   ID.AddInteger(VT.getRawBits());
3132   ID.AddInteger(Alignment);
3133   ID.AddInteger(isVolatile);
3134   void *IP = 0;
3135   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3136     return SDOperand(E, 0);
3137   SDNode *N = new StoreSDNode(Ops, VTs, ISD::UNINDEXED, false,
3138                               VT, SV, SVOffset, Alignment, isVolatile);
3139   CSEMap.InsertNode(N, IP);
3140   AllNodes.push_back(N);
3141   return SDOperand(N, 0);
3142 }
3143
3144 SDOperand SelectionDAG::getTruncStore(SDOperand Chain, SDOperand Val,
3145                                       SDOperand Ptr, const Value *SV,
3146                                       int SVOffset, MVT SVT,
3147                                       bool isVolatile, unsigned Alignment) {
3148   MVT VT = Val.getValueType();
3149
3150   if (VT == SVT)
3151     return getStore(Chain, Val, Ptr, SV, SVOffset, isVolatile, Alignment);
3152
3153   assert(VT.bitsGT(SVT) && "Not a truncation?");
3154   assert(VT.isInteger() == SVT.isInteger() &&
3155          "Can't do FP-INT conversion!");
3156
3157   if (Alignment == 0) { // Ensure that codegen never sees alignment 0
3158     const Type *Ty = 0;
3159     if (VT != MVT::iPTR) {
3160       Ty = VT.getTypeForMVT();
3161     } else if (SV) {
3162       const PointerType *PT = dyn_cast<PointerType>(SV->getType());
3163       assert(PT && "Value for store must be a pointer");
3164       Ty = PT->getElementType();
3165     }
3166     assert(Ty && "Could not get type information for store");
3167     Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
3168   }
3169   SDVTList VTs = getVTList(MVT::Other);
3170   SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
3171   SDOperand Ops[] = { Chain, Val, Ptr, Undef };
3172   FoldingSetNodeID ID;
3173   AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3174   ID.AddInteger(ISD::UNINDEXED);
3175   ID.AddInteger(1);
3176   ID.AddInteger(SVT.getRawBits());
3177   ID.AddInteger(Alignment);
3178   ID.AddInteger(isVolatile);
3179   void *IP = 0;
3180   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3181     return SDOperand(E, 0);
3182   SDNode *N = new StoreSDNode(Ops, VTs, ISD::UNINDEXED, true,
3183                               SVT, SV, SVOffset, Alignment, isVolatile);
3184   CSEMap.InsertNode(N, IP);
3185   AllNodes.push_back(N);
3186   return SDOperand(N, 0);
3187 }
3188
3189 SDOperand
3190 SelectionDAG::getIndexedStore(SDOperand OrigStore, SDOperand Base,
3191                               SDOperand Offset, ISD::MemIndexedMode AM) {
3192   StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
3193   assert(ST->getOffset().getOpcode() == ISD::UNDEF &&
3194          "Store is already a indexed store!");
3195   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
3196   SDOperand Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
3197   FoldingSetNodeID ID;
3198   AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
3199   ID.AddInteger(AM);
3200   ID.AddInteger(ST->isTruncatingStore());
3201   ID.AddInteger(ST->getMemoryVT().getRawBits());
3202   ID.AddInteger(ST->getAlignment());
3203   ID.AddInteger(ST->isVolatile());
3204   void *IP = 0;
3205   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3206     return SDOperand(E, 0);
3207   SDNode *N = new StoreSDNode(Ops, VTs, AM,
3208                               ST->isTruncatingStore(), ST->getMemoryVT(),
3209                               ST->getSrcValue(), ST->getSrcValueOffset(),
3210                               ST->getAlignment(), ST->isVolatile());
3211   CSEMap.InsertNode(N, IP);
3212   AllNodes.push_back(N);
3213   return SDOperand(N, 0);
3214 }
3215
3216 SDOperand SelectionDAG::getVAArg(MVT VT,
3217                                  SDOperand Chain, SDOperand Ptr,
3218                                  SDOperand SV) {
3219   SDOperand Ops[] = { Chain, Ptr, SV };
3220   return getNode(ISD::VAARG, getVTList(VT, MVT::Other), Ops, 3);
3221 }
3222
3223 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT VT,
3224                                 SDOperandPtr Ops, unsigned NumOps) {
3225   switch (NumOps) {
3226   case 0: return getNode(Opcode, VT);
3227   case 1: return getNode(Opcode, VT, Ops[0]);
3228   case 2: return getNode(Opcode, VT, Ops[0], Ops[1]);
3229   case 3: return getNode(Opcode, VT, Ops[0], Ops[1], Ops[2]);
3230   default: break;
3231   }
3232   
3233   switch (Opcode) {
3234   default: break;
3235   case ISD::SELECT_CC: {
3236     assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
3237     assert(Ops[0].getValueType() == Ops[1].getValueType() &&
3238            "LHS and RHS of condition must have same type!");
3239     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
3240            "True and False arms of SelectCC must have same type!");
3241     assert(Ops[2].getValueType() == VT &&
3242            "select_cc node must be of same type as true and false value!");
3243     break;
3244   }
3245   case ISD::BR_CC: {
3246     assert(NumOps == 5 && "BR_CC takes 5 operands!");
3247     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
3248            "LHS/RHS of comparison should match types!");
3249     break;
3250   }
3251   }
3252
3253   // Memoize nodes.
3254   SDNode *N;
3255   SDVTList VTs = getVTList(VT);
3256   if (VT != MVT::Flag) {
3257     FoldingSetNodeID ID;
3258     AddNodeIDNode(ID, Opcode, VTs, Ops, NumOps);
3259     void *IP = 0;
3260     if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3261       return SDOperand(E, 0);
3262     N = new SDNode(Opcode, VTs, Ops, NumOps);
3263     CSEMap.InsertNode(N, IP);
3264   } else {
3265     N = new SDNode(Opcode, VTs, Ops, NumOps);
3266   }
3267   AllNodes.push_back(N);
3268   return SDOperand(N, 0);
3269 }
3270
3271 SDOperand SelectionDAG::getNode(unsigned Opcode,
3272                                 std::vector<MVT> &ResultTys,
3273                                 SDOperandPtr Ops, unsigned NumOps) {
3274   return getNode(Opcode, getNodeValueTypes(ResultTys), ResultTys.size(),
3275                  Ops, NumOps);
3276 }
3277
3278 SDOperand SelectionDAG::getNode(unsigned Opcode,
3279                                 const MVT *VTs, unsigned NumVTs,
3280                                 SDOperandPtr Ops, unsigned NumOps) {
3281   if (NumVTs == 1)
3282     return getNode(Opcode, VTs[0], Ops, NumOps);
3283   return getNode(Opcode, makeVTList(VTs, NumVTs), Ops, NumOps);
3284 }  
3285   
3286 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3287                                 SDOperandPtr Ops, unsigned NumOps) {
3288   if (VTList.NumVTs == 1)
3289     return getNode(Opcode, VTList.VTs[0], Ops, NumOps);
3290
3291   switch (Opcode) {
3292   // FIXME: figure out how to safely handle things like
3293   // int foo(int x) { return 1 << (x & 255); }
3294   // int bar() { return foo(256); }
3295 #if 0
3296   case ISD::SRA_PARTS:
3297   case ISD::SRL_PARTS:
3298   case ISD::SHL_PARTS:
3299     if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
3300         cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
3301       return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
3302     else if (N3.getOpcode() == ISD::AND)
3303       if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
3304         // If the and is only masking out bits that cannot effect the shift,
3305         // eliminate the and.
3306         unsigned NumBits = VT.getSizeInBits()*2;
3307         if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
3308           return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
3309       }
3310     break;
3311 #endif
3312   }
3313
3314   // Memoize the node unless it returns a flag.
3315   SDNode *N;
3316   if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
3317     FoldingSetNodeID ID;
3318     AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
3319     void *IP = 0;
3320     if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3321       return SDOperand(E, 0);
3322     if (NumOps == 1)
3323       N = new UnarySDNode(Opcode, VTList, Ops[0]);
3324     else if (NumOps == 2)
3325       N = new BinarySDNode(Opcode, VTList, Ops[0], Ops[1]);
3326     else if (NumOps == 3)
3327       N = new TernarySDNode(Opcode, VTList, Ops[0], Ops[1], Ops[2]);
3328     else
3329       N = new SDNode(Opcode, VTList, Ops, NumOps);
3330     CSEMap.InsertNode(N, IP);
3331   } else {
3332     if (NumOps == 1)
3333       N = new UnarySDNode(Opcode, VTList, Ops[0]);
3334     else if (NumOps == 2)
3335       N = new BinarySDNode(Opcode, VTList, Ops[0], Ops[1]);
3336     else if (NumOps == 3)
3337       N = new TernarySDNode(Opcode, VTList, Ops[0], Ops[1], Ops[2]);
3338     else
3339       N = new SDNode(Opcode, VTList, Ops, NumOps);
3340   }
3341   AllNodes.push_back(N);
3342   return SDOperand(N, 0);
3343 }
3344
3345 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList) {
3346   return getNode(Opcode, VTList, (SDOperand*)0, 0);
3347 }
3348
3349 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3350                                 SDOperand N1) {
3351   SDOperand Ops[] = { N1 };
3352   return getNode(Opcode, VTList, Ops, 1);
3353 }
3354
3355 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3356                                 SDOperand N1, SDOperand N2) {
3357   SDOperand Ops[] = { N1, N2 };
3358   return getNode(Opcode, VTList, Ops, 2);
3359 }
3360
3361 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3362                                 SDOperand N1, SDOperand N2, SDOperand N3) {
3363   SDOperand Ops[] = { N1, N2, N3 };
3364   return getNode(Opcode, VTList, Ops, 3);
3365 }
3366
3367 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3368                                 SDOperand N1, SDOperand N2, SDOperand N3,
3369                                 SDOperand N4) {
3370   SDOperand Ops[] = { N1, N2, N3, N4 };
3371   return getNode(Opcode, VTList, Ops, 4);
3372 }
3373
3374 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
3375                                 SDOperand N1, SDOperand N2, SDOperand N3,
3376                                 SDOperand N4, SDOperand N5) {
3377   SDOperand Ops[] = { N1, N2, N3, N4, N5 };
3378   return getNode(Opcode, VTList, Ops, 5);
3379 }
3380
3381 SDVTList SelectionDAG::getVTList(MVT VT) {
3382   return makeVTList(SDNode::getValueTypeList(VT), 1);
3383 }
3384
3385 SDVTList SelectionDAG::getVTList(MVT VT1, MVT VT2) {
3386   for (std::list<std::vector<MVT> >::iterator I = VTList.begin(),
3387        E = VTList.end(); I != E; ++I) {
3388     if (I->size() == 2 && (*I)[0] == VT1 && (*I)[1] == VT2)
3389       return makeVTList(&(*I)[0], 2);
3390   }
3391   std::vector<MVT> V;
3392   V.push_back(VT1);
3393   V.push_back(VT2);
3394   VTList.push_front(V);
3395   return makeVTList(&(*VTList.begin())[0], 2);
3396 }
3397 SDVTList SelectionDAG::getVTList(MVT VT1, MVT VT2,
3398                                  MVT VT3) {
3399   for (std::list<std::vector<MVT> >::iterator I = VTList.begin(),
3400        E = VTList.end(); I != E; ++I) {
3401     if (I->size() == 3 && (*I)[0] == VT1 && (*I)[1] == VT2 &&
3402         (*I)[2] == VT3)
3403       return makeVTList(&(*I)[0], 3);
3404   }
3405   std::vector<MVT> V;
3406   V.push_back(VT1);
3407   V.push_back(VT2);
3408   V.push_back(VT3);
3409   VTList.push_front(V);
3410   return makeVTList(&(*VTList.begin())[0], 3);
3411 }
3412
3413 SDVTList SelectionDAG::getVTList(const MVT *VTs, unsigned NumVTs) {
3414   switch (NumVTs) {
3415     case 0: assert(0 && "Cannot have nodes without results!");
3416     case 1: return getVTList(VTs[0]);
3417     case 2: return getVTList(VTs[0], VTs[1]);
3418     case 3: return getVTList(VTs[0], VTs[1], VTs[2]);
3419     default: break;
3420   }
3421
3422   for (std::list<std::vector<MVT> >::iterator I = VTList.begin(),
3423        E = VTList.end(); I != E; ++I) {
3424     if (I->size() != NumVTs || VTs[0] != (*I)[0] || VTs[1] != (*I)[1]) continue;
3425    
3426     bool NoMatch = false;
3427     for (unsigned i = 2; i != NumVTs; ++i)
3428       if (VTs[i] != (*I)[i]) {
3429         NoMatch = true;
3430         break;
3431       }
3432     if (!NoMatch)
3433       return makeVTList(&*I->begin(), NumVTs);
3434   }
3435   
3436   VTList.push_front(std::vector<MVT>(VTs, VTs+NumVTs));
3437   return makeVTList(&*VTList.begin()->begin(), NumVTs);
3438 }
3439
3440
3441 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
3442 /// specified operands.  If the resultant node already exists in the DAG,
3443 /// this does not modify the specified node, instead it returns the node that
3444 /// already exists.  If the resultant node does not exist in the DAG, the
3445 /// input node is returned.  As a degenerate case, if you specify the same
3446 /// input operands as the node already has, the input node is returned.
3447 SDOperand SelectionDAG::
3448 UpdateNodeOperands(SDOperand InN, SDOperand Op) {
3449   SDNode *N = InN.Val;
3450   assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
3451   
3452   // Check to see if there is no change.
3453   if (Op == N->getOperand(0)) return InN;
3454   
3455   // See if the modified node already exists.
3456   void *InsertPos = 0;
3457   if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
3458     return SDOperand(Existing, InN.ResNo);
3459   
3460   // Nope it doesn't.  Remove the node from it's current place in the maps.
3461   if (InsertPos)
3462     RemoveNodeFromCSEMaps(N);
3463   
3464   // Now we update the operands.
3465   N->OperandList[0].getVal()->removeUser(0, N);
3466   N->OperandList[0] = Op;
3467   N->OperandList[0].setUser(N);
3468   Op.Val->addUser(0, N);
3469   
3470   // If this gets put into a CSE map, add it.
3471   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
3472   return InN;
3473 }
3474
3475 SDOperand SelectionDAG::
3476 UpdateNodeOperands(SDOperand InN, SDOperand Op1, SDOperand Op2) {
3477   SDNode *N = InN.Val;
3478   assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
3479   
3480   // Check to see if there is no change.
3481   if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
3482     return InN;   // No operands changed, just return the input node.
3483   
3484   // See if the modified node already exists.
3485   void *InsertPos = 0;
3486   if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
3487     return SDOperand(Existing, InN.ResNo);
3488   
3489   // Nope it doesn't.  Remove the node from it's current place in the maps.
3490   if (InsertPos)
3491     RemoveNodeFromCSEMaps(N);
3492   
3493   // Now we update the operands.
3494   if (N->OperandList[0] != Op1) {
3495     N->OperandList[0].getVal()->removeUser(0, N);
3496     N->OperandList[0] = Op1;
3497     N->OperandList[0].setUser(N);
3498     Op1.Val->addUser(0, N);
3499   }
3500   if (N->OperandList[1] != Op2) {
3501     N->OperandList[1].getVal()->removeUser(1, N);
3502     N->OperandList[1] = Op2;
3503     N->OperandList[1].setUser(N);
3504     Op2.Val->addUser(1, N);
3505   }
3506   
3507   // If this gets put into a CSE map, add it.
3508   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
3509   return InN;
3510 }
3511
3512 SDOperand SelectionDAG::
3513 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2, SDOperand Op3) {
3514   SDOperand Ops[] = { Op1, Op2, Op3 };
3515   return UpdateNodeOperands(N, Ops, 3);
3516 }
3517
3518 SDOperand SelectionDAG::
3519 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2, 
3520                    SDOperand Op3, SDOperand Op4) {
3521   SDOperand Ops[] = { Op1, Op2, Op3, Op4 };
3522   return UpdateNodeOperands(N, Ops, 4);
3523 }
3524
3525 SDOperand SelectionDAG::
3526 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2,
3527                    SDOperand Op3, SDOperand Op4, SDOperand Op5) {
3528   SDOperand Ops[] = { Op1, Op2, Op3, Op4, Op5 };
3529   return UpdateNodeOperands(N, Ops, 5);
3530 }
3531
3532 SDOperand SelectionDAG::
3533 UpdateNodeOperands(SDOperand InN, SDOperandPtr Ops, unsigned NumOps) {
3534   SDNode *N = InN.Val;
3535   assert(N->getNumOperands() == NumOps &&
3536          "Update with wrong number of operands");
3537   
3538   // Check to see if there is no change.
3539   bool AnyChange = false;
3540   for (unsigned i = 0; i != NumOps; ++i) {
3541     if (Ops[i] != N->getOperand(i)) {
3542       AnyChange = true;
3543       break;
3544     }
3545   }
3546   
3547   // No operands changed, just return the input node.
3548   if (!AnyChange) return InN;
3549   
3550   // See if the modified node already exists.
3551   void *InsertPos = 0;
3552   if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, NumOps, InsertPos))
3553     return SDOperand(Existing, InN.ResNo);
3554   
3555   // Nope it doesn't.  Remove the node from its current place in the maps.
3556   if (InsertPos)
3557     RemoveNodeFromCSEMaps(N);
3558   
3559   // Now we update the operands.
3560   for (unsigned i = 0; i != NumOps; ++i) {
3561     if (N->OperandList[i] != Ops[i]) {
3562       N->OperandList[i].getVal()->removeUser(i, N);
3563       N->OperandList[i] = Ops[i];
3564       N->OperandList[i].setUser(N);
3565       Ops[i].Val->addUser(i, N);
3566     }
3567   }
3568
3569   // If this gets put into a CSE map, add it.
3570   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
3571   return InN;
3572 }
3573
3574 /// MorphNodeTo - This frees the operands of the current node, resets the
3575 /// opcode, types, and operands to the specified value.  This should only be
3576 /// used by the SelectionDAG class.
3577 void SDNode::MorphNodeTo(unsigned Opc, SDVTList L,
3578                          SDOperandPtr Ops, unsigned NumOps) {
3579   NodeType = Opc;
3580   ValueList = L.VTs;
3581   NumValues = L.NumVTs;
3582   
3583   // Clear the operands list, updating used nodes to remove this from their
3584   // use list.
3585   for (op_iterator I = op_begin(), E = op_end(); I != E; ++I)
3586     I->getVal()->removeUser(std::distance(op_begin(), I), this);
3587   
3588   // If NumOps is larger than the # of operands we currently have, reallocate
3589   // the operand list.
3590   if (NumOps > NumOperands) {
3591     if (OperandsNeedDelete) {
3592       delete [] OperandList;
3593     }
3594     OperandList = new SDUse[NumOps];
3595     OperandsNeedDelete = true;
3596   }
3597   
3598   // Assign the new operands.
3599   NumOperands = NumOps;
3600   
3601   for (unsigned i = 0, e = NumOps; i != e; ++i) {
3602     OperandList[i] = Ops[i];
3603     OperandList[i].setUser(this);
3604     SDNode *N = OperandList[i].getVal();
3605     N->addUser(i, this);
3606     ++N->UsesSize;
3607   }
3608 }
3609
3610 /// SelectNodeTo - These are used for target selectors to *mutate* the
3611 /// specified node to have the specified return type, Target opcode, and
3612 /// operands.  Note that target opcodes are stored as
3613 /// ISD::BUILTIN_OP_END+TargetOpcode in the node opcode field.
3614 ///
3615 /// Note that SelectNodeTo returns the resultant node.  If there is already a
3616 /// node of the specified opcode and operands, it returns that node instead of
3617 /// the current one.
3618 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3619                                    MVT VT) {
3620   SDVTList VTs = getVTList(VT);
3621   FoldingSetNodeID ID;
3622   AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, (SDOperand*)0, 0);
3623   void *IP = 0;
3624   if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3625     return ON;
3626    
3627   RemoveNodeFromCSEMaps(N);
3628   
3629   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, SDOperandPtr(), 0);
3630
3631   CSEMap.InsertNode(N, IP);
3632   return N;
3633 }
3634
3635 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3636                                    MVT VT, SDOperand Op1) {
3637   // If an identical node already exists, use it.
3638   SDVTList VTs = getVTList(VT);
3639   SDOperand Ops[] = { Op1 };
3640   
3641   FoldingSetNodeID ID;
3642   AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 1);
3643   void *IP = 0;
3644   if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3645     return ON;
3646                                        
3647   RemoveNodeFromCSEMaps(N);
3648   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 1);
3649   CSEMap.InsertNode(N, IP);
3650   return N;
3651 }
3652
3653 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3654                                    MVT VT, SDOperand Op1,
3655                                    SDOperand Op2) {
3656   // If an identical node already exists, use it.
3657   SDVTList VTs = getVTList(VT);
3658   SDOperand Ops[] = { Op1, Op2 };
3659   
3660   FoldingSetNodeID ID;
3661   AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 2);
3662   void *IP = 0;
3663   if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3664     return ON;
3665                                        
3666   RemoveNodeFromCSEMaps(N);
3667   
3668   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 2);
3669   
3670   CSEMap.InsertNode(N, IP);   // Memoize the new node.
3671   return N;
3672 }
3673
3674 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3675                                    MVT VT, SDOperand Op1,
3676                                    SDOperand Op2, SDOperand Op3) {
3677   // If an identical node already exists, use it.
3678   SDVTList VTs = getVTList(VT);
3679   SDOperand Ops[] = { Op1, Op2, Op3 };
3680   FoldingSetNodeID ID;
3681   AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 3);
3682   void *IP = 0;
3683   if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3684     return ON;
3685                                        
3686   RemoveNodeFromCSEMaps(N);
3687   
3688   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 3);
3689
3690   CSEMap.InsertNode(N, IP);   // Memoize the new node.
3691   return N;
3692 }
3693
3694 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3695                                    MVT VT, SDOperandPtr Ops,
3696                                    unsigned NumOps) {
3697   // If an identical node already exists, use it.
3698   SDVTList VTs = getVTList(VT);
3699   FoldingSetNodeID ID;
3700   AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, NumOps);
3701   void *IP = 0;
3702   if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3703     return ON;
3704                                        
3705   RemoveNodeFromCSEMaps(N);
3706   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, NumOps);
3707   
3708   CSEMap.InsertNode(N, IP);   // Memoize the new node.
3709   return N;
3710 }
3711
3712 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc, 
3713                                    MVT VT1, MVT VT2,
3714                                    SDOperand Op1, SDOperand Op2) {
3715   SDVTList VTs = getVTList(VT1, VT2);
3716   FoldingSetNodeID ID;
3717   SDOperand Ops[] = { Op1, Op2 };
3718   AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 2);
3719   void *IP = 0;
3720   if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3721     return ON;
3722
3723   RemoveNodeFromCSEMaps(N);
3724   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 2);
3725   CSEMap.InsertNode(N, IP);   // Memoize the new node.
3726   return N;
3727 }
3728
3729 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
3730                                    MVT VT1, MVT VT2,
3731                                    SDOperand Op1, SDOperand Op2, 
3732                                    SDOperand Op3) {
3733   // If an identical node already exists, use it.
3734   SDVTList VTs = getVTList(VT1, VT2);
3735   SDOperand Ops[] = { Op1, Op2, Op3 };
3736   FoldingSetNodeID ID;
3737   AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 3);
3738   void *IP = 0;
3739   if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
3740     return ON;
3741
3742   RemoveNodeFromCSEMaps(N);
3743
3744   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 3);
3745   CSEMap.InsertNode(N, IP);   // Memoize the new node.
3746   return N;
3747 }
3748
3749
3750 /// getTargetNode - These are used for target selectors to create a new node
3751 /// with specified return type(s), target opcode, and operands.
3752 ///
3753 /// Note that getTargetNode returns the resultant node.  If there is already a
3754 /// node of the specified opcode and operands, it returns that node instead of
3755 /// the current one.
3756 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT) {
3757   return getNode(ISD::BUILTIN_OP_END+Opcode, VT).Val;
3758 }
3759 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT, SDOperand Op1) {
3760   return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1).Val;
3761 }
3762 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT,
3763                                     SDOperand Op1, SDOperand Op2) {
3764   return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1, Op2).Val;
3765 }
3766 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT,
3767                                     SDOperand Op1, SDOperand Op2,
3768                                     SDOperand Op3) {
3769   return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1, Op2, Op3).Val;
3770 }
3771 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT,
3772                                     SDOperandPtr Ops, unsigned NumOps) {
3773   return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Ops, NumOps).Val;
3774 }
3775 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2) {
3776   const MVT *VTs = getNodeValueTypes(VT1, VT2);
3777   SDOperand Op;
3778   return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, &Op, 0).Val;
3779 }
3780 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
3781                                     MVT VT2, SDOperand Op1) {
3782   const MVT *VTs = getNodeValueTypes(VT1, VT2);
3783   return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, &Op1, 1).Val;
3784 }
3785 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
3786                                     MVT VT2, SDOperand Op1,
3787                                     SDOperand Op2) {
3788   const MVT *VTs = getNodeValueTypes(VT1, VT2);
3789   SDOperand Ops[] = { Op1, Op2 };
3790   return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, Ops, 2).Val;
3791 }
3792 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
3793                                     MVT VT2, SDOperand Op1,
3794                                     SDOperand Op2, SDOperand Op3) {
3795   const MVT *VTs = getNodeValueTypes(VT1, VT2);
3796   SDOperand Ops[] = { Op1, Op2, Op3 };
3797   return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, Ops, 3).Val;
3798 }
3799 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2,
3800                                     SDOperandPtr Ops, unsigned NumOps) {
3801   const MVT *VTs = getNodeValueTypes(VT1, VT2);
3802   return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, Ops, NumOps).Val;
3803 }
3804 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3,
3805                                     SDOperand Op1, SDOperand Op2) {
3806   const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
3807   SDOperand Ops[] = { Op1, Op2 };
3808   return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 3, Ops, 2).Val;
3809 }
3810 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3,
3811                                     SDOperand Op1, SDOperand Op2,
3812                                     SDOperand Op3) {
3813   const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
3814   SDOperand Ops[] = { Op1, Op2, Op3 };
3815   return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 3, Ops, 3).Val;
3816 }
3817 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3,
3818                                     SDOperandPtr Ops, unsigned NumOps) {
3819   const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
3820   return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 3, Ops, NumOps).Val;
3821 }
3822 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
3823                                     MVT VT2, MVT VT3, MVT VT4,
3824                                     SDOperandPtr Ops, unsigned NumOps) {
3825   std::vector<MVT> VTList;
3826   VTList.push_back(VT1);
3827   VTList.push_back(VT2);
3828   VTList.push_back(VT3);
3829   VTList.push_back(VT4);
3830   const MVT *VTs = getNodeValueTypes(VTList);
3831   return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 4, Ops, NumOps).Val;
3832 }
3833 SDNode *SelectionDAG::getTargetNode(unsigned Opcode,
3834                                     std::vector<MVT> &ResultTys,
3835                                     SDOperandPtr Ops, unsigned NumOps) {
3836   const MVT *VTs = getNodeValueTypes(ResultTys);
3837   return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, ResultTys.size(),
3838                  Ops, NumOps).Val;
3839 }
3840
3841 /// getNodeIfExists - Get the specified node if it's already available, or
3842 /// else return NULL.
3843 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
3844                                       SDOperandPtr Ops, unsigned NumOps) {
3845   if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
3846     FoldingSetNodeID ID;
3847     AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
3848     void *IP = 0;
3849     if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3850       return E;
3851   }
3852   return NULL;
3853 }
3854
3855
3856 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
3857 /// This can cause recursive merging of nodes in the DAG.
3858 ///
3859 /// This version assumes From has a single result value.
3860 ///
3861 void SelectionDAG::ReplaceAllUsesWith(SDOperand FromN, SDOperand To,
3862                                       DAGUpdateListener *UpdateListener) {
3863   SDNode *From = FromN.Val;
3864   assert(From->getNumValues() == 1 && FromN.ResNo == 0 && 
3865          "Cannot replace with this method!");
3866   assert(From != To.Val && "Cannot replace uses of with self");
3867
3868   while (!From->use_empty()) {
3869     SDNode::use_iterator UI = From->use_begin();
3870     SDNode *U = UI->getUser();
3871
3872     // This node is about to morph, remove its old self from the CSE maps.
3873     RemoveNodeFromCSEMaps(U);
3874     int operandNum = 0;
3875     for (SDNode::op_iterator I = U->op_begin(), E = U->op_end();
3876          I != E; ++I, ++operandNum)
3877       if (I->getVal() == From) {
3878         From->removeUser(operandNum, U);
3879         *I = To;
3880         I->setUser(U);
3881         To.Val->addUser(operandNum, U);
3882       }    
3883
3884     // Now that we have modified U, add it back to the CSE maps.  If it already
3885     // exists there, recursively merge the results together.
3886     if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
3887       ReplaceAllUsesWith(U, Existing, UpdateListener);
3888       // U is now dead.  Inform the listener if it exists and delete it.
3889       if (UpdateListener) 
3890         UpdateListener->NodeDeleted(U, Existing);
3891       DeleteNodeNotInCSEMaps(U);
3892     } else {
3893       // If the node doesn't already exist, we updated it.  Inform a listener if
3894       // it exists.
3895       if (UpdateListener) 
3896         UpdateListener->NodeUpdated(U);
3897     }
3898   }
3899 }
3900
3901 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
3902 /// This can cause recursive merging of nodes in the DAG.
3903 ///
3904 /// This version assumes From/To have matching types and numbers of result
3905 /// values.
3906 ///
3907 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To,
3908                                       DAGUpdateListener *UpdateListener) {
3909   assert(From != To && "Cannot replace uses of with self");
3910   assert(From->getNumValues() == To->getNumValues() &&
3911          "Cannot use this version of ReplaceAllUsesWith!");
3912   if (From->getNumValues() == 1)   // If possible, use the faster version.
3913     return ReplaceAllUsesWith(SDOperand(From, 0), SDOperand(To, 0),
3914                               UpdateListener);
3915   
3916   while (!From->use_empty()) {
3917     SDNode::use_iterator UI = From->use_begin();
3918     SDNode *U = UI->getUser();
3919
3920     // This node is about to morph, remove its old self from the CSE maps.
3921     RemoveNodeFromCSEMaps(U);
3922     int operandNum = 0;
3923     for (SDNode::op_iterator I = U->op_begin(), E = U->op_end();
3924          I != E; ++I, ++operandNum)
3925       if (I->getVal() == From) {
3926         From->removeUser(operandNum, U);
3927         I->getVal() = To;
3928         To->addUser(operandNum, U);
3929       }
3930
3931     // Now that we have modified U, add it back to the CSE maps.  If it already
3932     // exists there, recursively merge the results together.
3933     if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
3934       ReplaceAllUsesWith(U, Existing, UpdateListener);
3935       // U is now dead.  Inform the listener if it exists and delete it.
3936       if (UpdateListener) 
3937         UpdateListener->NodeDeleted(U, Existing);
3938       DeleteNodeNotInCSEMaps(U);
3939     } else {
3940       // If the node doesn't already exist, we updated it.  Inform a listener if
3941       // it exists.
3942       if (UpdateListener) 
3943         UpdateListener->NodeUpdated(U);
3944     }
3945   }
3946 }
3947
3948 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
3949 /// This can cause recursive merging of nodes in the DAG.
3950 ///
3951 /// This version can replace From with any result values.  To must match the
3952 /// number and types of values returned by From.
3953 void SelectionDAG::ReplaceAllUsesWith(SDNode *From,
3954                                       SDOperandPtr To,
3955                                       DAGUpdateListener *UpdateListener) {
3956   if (From->getNumValues() == 1)  // Handle the simple case efficiently.
3957     return ReplaceAllUsesWith(SDOperand(From, 0), To[0], UpdateListener);
3958
3959   while (!From->use_empty()) {
3960     SDNode::use_iterator UI = From->use_begin();
3961     SDNode *U = UI->getUser();
3962
3963     // This node is about to morph, remove its old self from the CSE maps.
3964     RemoveNodeFromCSEMaps(U);
3965     int operandNum = 0;
3966     for (SDNode::op_iterator I = U->op_begin(), E = U->op_end();
3967          I != E; ++I, ++operandNum)
3968       if (I->getVal() == From) {
3969         const SDOperand &ToOp = To[I->getSDOperand().ResNo];
3970         From->removeUser(operandNum, U);
3971         *I = ToOp;
3972         I->setUser(U);
3973         ToOp.Val->addUser(operandNum, U);
3974       }
3975
3976     // Now that we have modified U, add it back to the CSE maps.  If it already
3977     // exists there, recursively merge the results together.
3978     if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
3979       ReplaceAllUsesWith(U, Existing, UpdateListener);
3980       // U is now dead.  Inform the listener if it exists and delete it.
3981       if (UpdateListener) 
3982         UpdateListener->NodeDeleted(U, Existing);
3983       DeleteNodeNotInCSEMaps(U);
3984     } else {
3985       // If the node doesn't already exist, we updated it.  Inform a listener if
3986       // it exists.
3987       if (UpdateListener) 
3988         UpdateListener->NodeUpdated(U);
3989     }
3990   }
3991 }
3992
3993 namespace {
3994   /// ChainedSetUpdaterListener - This class is a DAGUpdateListener that removes
3995   /// any deleted nodes from the set passed into its constructor and recursively
3996   /// notifies another update listener if specified.
3997   class ChainedSetUpdaterListener : 
3998   public SelectionDAG::DAGUpdateListener {
3999     SmallSetVector<SDNode*, 16> &Set;
4000     SelectionDAG::DAGUpdateListener *Chain;
4001   public:
4002     ChainedSetUpdaterListener(SmallSetVector<SDNode*, 16> &set,
4003                               SelectionDAG::DAGUpdateListener *chain)
4004       : Set(set), Chain(chain) {}
4005  
4006     virtual void NodeDeleted(SDNode *N, SDNode *E) {
4007       Set.remove(N);
4008       if (Chain) Chain->NodeDeleted(N, E);
4009     }
4010     virtual void NodeUpdated(SDNode *N) {
4011       if (Chain) Chain->NodeUpdated(N);
4012     }
4013   };
4014 }
4015
4016 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
4017 /// uses of other values produced by From.Val alone.  The Deleted vector is
4018 /// handled the same way as for ReplaceAllUsesWith.
4019 void SelectionDAG::ReplaceAllUsesOfValueWith(SDOperand From, SDOperand To,
4020                                              DAGUpdateListener *UpdateListener){
4021   assert(From != To && "Cannot replace a value with itself");
4022   
4023   // Handle the simple, trivial, case efficiently.
4024   if (From.Val->getNumValues() == 1) {
4025     ReplaceAllUsesWith(From, To, UpdateListener);
4026     return;
4027   }
4028
4029   if (From.use_empty()) return;
4030
4031   // Get all of the users of From.Val.  We want these in a nice,
4032   // deterministically ordered and uniqued set, so we use a SmallSetVector.
4033   SmallSetVector<SDNode*, 16> Users;
4034   for (SDNode::use_iterator UI = From.Val->use_begin(), 
4035       E = From.Val->use_end(); UI != E; ++UI) {
4036     SDNode *User = UI->getUser();
4037     if (!Users.count(User))
4038       Users.insert(User);
4039   }
4040
4041   // When one of the recursive merges deletes nodes from the graph, we need to
4042   // make sure that UpdateListener is notified *and* that the node is removed
4043   // from Users if present.  CSUL does this.
4044   ChainedSetUpdaterListener CSUL(Users, UpdateListener);
4045   
4046   while (!Users.empty()) {
4047     // We know that this user uses some value of From.  If it is the right
4048     // value, update it.
4049     SDNode *User = Users.back();
4050     Users.pop_back();
4051     
4052     // Scan for an operand that matches From.
4053     SDNode::op_iterator Op = User->op_begin(), E = User->op_end();
4054     for (; Op != E; ++Op)
4055       if (*Op == From) break;
4056     
4057     // If there are no matches, the user must use some other result of From.
4058     if (Op == E) continue;
4059       
4060     // Okay, we know this user needs to be updated.  Remove its old self
4061     // from the CSE maps.
4062     RemoveNodeFromCSEMaps(User);
4063     
4064     // Update all operands that match "From" in case there are multiple uses.
4065     for (; Op != E; ++Op) {
4066       if (*Op == From) {
4067         From.Val->removeUser(Op-User->op_begin(), User);
4068         *Op = To;
4069         Op->setUser(User);
4070         To.Val->addUser(Op-User->op_begin(), User);
4071       }
4072     }
4073                
4074     // Now that we have modified User, add it back to the CSE maps.  If it
4075     // already exists there, recursively merge the results together.
4076     SDNode *Existing = AddNonLeafNodeToCSEMaps(User);
4077     if (!Existing) {
4078       if (UpdateListener) UpdateListener->NodeUpdated(User);
4079       continue;  // Continue on to next user.
4080     }
4081     
4082     // If there was already an existing matching node, use ReplaceAllUsesWith
4083     // to replace the dead one with the existing one.  This can cause
4084     // recursive merging of other unrelated nodes down the line.  The merging
4085     // can cause deletion of nodes that used the old value.  To handle this, we
4086     // use CSUL to remove them from the Users set.
4087     ReplaceAllUsesWith(User, Existing, &CSUL);
4088     
4089     // User is now dead.  Notify a listener if present.
4090     if (UpdateListener) UpdateListener->NodeDeleted(User, Existing);
4091     DeleteNodeNotInCSEMaps(User);
4092   }
4093 }
4094
4095 /// AssignNodeIds - Assign a unique node id for each node in the DAG based on
4096 /// their allnodes order. It returns the maximum id.
4097 unsigned SelectionDAG::AssignNodeIds() {
4098   unsigned Id = 0;
4099   for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I){
4100     SDNode *N = I;
4101     N->setNodeId(Id++);
4102   }
4103   return Id;
4104 }
4105
4106 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
4107 /// based on their topological order. It returns the maximum id and a vector
4108 /// of the SDNodes* in assigned order by reference.
4109 unsigned SelectionDAG::AssignTopologicalOrder(std::vector<SDNode*> &TopOrder) {
4110   unsigned DAGSize = AllNodes.size();
4111   std::vector<unsigned> InDegree(DAGSize);
4112   std::vector<SDNode*> Sources;
4113
4114   // Use a two pass approach to avoid using a std::map which is slow.
4115   unsigned Id = 0;
4116   for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ++I){
4117     SDNode *N = I;
4118     N->setNodeId(Id++);
4119     unsigned Degree = N->use_size();
4120     InDegree[N->getNodeId()] = Degree;
4121     if (Degree == 0)
4122       Sources.push_back(N);
4123   }
4124
4125   TopOrder.clear();
4126   while (!Sources.empty()) {
4127     SDNode *N = Sources.back();
4128     Sources.pop_back();
4129     TopOrder.push_back(N);
4130     for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
4131       SDNode *P = I->getVal();
4132       unsigned Degree = --InDegree[P->getNodeId()];
4133       if (Degree == 0)
4134         Sources.push_back(P);
4135     }
4136   }
4137
4138   // Second pass, assign the actual topological order as node ids.
4139   Id = 0;
4140   for (std::vector<SDNode*>::iterator TI = TopOrder.begin(),TE = TopOrder.end();
4141        TI != TE; ++TI)
4142     (*TI)->setNodeId(Id++);
4143
4144   return Id;
4145 }
4146
4147
4148
4149 //===----------------------------------------------------------------------===//
4150 //                              SDNode Class
4151 //===----------------------------------------------------------------------===//
4152
4153 // Out-of-line virtual method to give class a home.
4154 void SDNode::ANCHOR() {}
4155 void UnarySDNode::ANCHOR() {}
4156 void BinarySDNode::ANCHOR() {}
4157 void TernarySDNode::ANCHOR() {}
4158 void HandleSDNode::ANCHOR() {}
4159 void StringSDNode::ANCHOR() {}
4160 void ConstantSDNode::ANCHOR() {}
4161 void ConstantFPSDNode::ANCHOR() {}
4162 void GlobalAddressSDNode::ANCHOR() {}
4163 void FrameIndexSDNode::ANCHOR() {}
4164 void JumpTableSDNode::ANCHOR() {}
4165 void ConstantPoolSDNode::ANCHOR() {}
4166 void BasicBlockSDNode::ANCHOR() {}
4167 void SrcValueSDNode::ANCHOR() {}
4168 void MemOperandSDNode::ANCHOR() {}
4169 void RegisterSDNode::ANCHOR() {}
4170 void ExternalSymbolSDNode::ANCHOR() {}
4171 void CondCodeSDNode::ANCHOR() {}
4172 void ARG_FLAGSSDNode::ANCHOR() {}
4173 void VTSDNode::ANCHOR() {}
4174 void LoadSDNode::ANCHOR() {}
4175 void StoreSDNode::ANCHOR() {}
4176 void AtomicSDNode::ANCHOR() {}
4177
4178 HandleSDNode::~HandleSDNode() {
4179   SDVTList VTs = { 0, 0 };
4180   MorphNodeTo(ISD::HANDLENODE, VTs, SDOperandPtr(), 0);  // Drops operand uses.
4181 }
4182
4183 GlobalAddressSDNode::GlobalAddressSDNode(bool isTarget, const GlobalValue *GA,
4184                                          MVT VT, int o)
4185   : SDNode(isa<GlobalVariable>(GA) &&
4186            cast<GlobalVariable>(GA)->isThreadLocal() ?
4187            // Thread Local
4188            (isTarget ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress) :
4189            // Non Thread Local
4190            (isTarget ? ISD::TargetGlobalAddress : ISD::GlobalAddress),
4191            getSDVTList(VT)), Offset(o) {
4192   TheGlobal = const_cast<GlobalValue*>(GA);
4193 }
4194
4195 /// getMemOperand - Return a MachineMemOperand object describing the memory
4196 /// reference performed by this load or store.
4197 MachineMemOperand LSBaseSDNode::getMemOperand() const {
4198   int Size = (getMemoryVT().getSizeInBits() + 7) >> 3;
4199   int Flags =
4200     getOpcode() == ISD::LOAD ? MachineMemOperand::MOLoad :
4201                                MachineMemOperand::MOStore;
4202   if (IsVolatile) Flags |= MachineMemOperand::MOVolatile;
4203
4204   // Check if the load references a frame index, and does not have
4205   // an SV attached.
4206   const FrameIndexSDNode *FI =
4207     dyn_cast<const FrameIndexSDNode>(getBasePtr().Val);
4208   if (!getSrcValue() && FI)
4209     return MachineMemOperand(PseudoSourceValue::getFixedStack(), Flags,
4210                              FI->getIndex(), Size, Alignment);
4211   else
4212     return MachineMemOperand(getSrcValue(), Flags,
4213                              getSrcValueOffset(), Size, Alignment);
4214 }
4215
4216 /// Profile - Gather unique data for the node.
4217 ///
4218 void SDNode::Profile(FoldingSetNodeID &ID) {
4219   AddNodeIDNode(ID, this);
4220 }
4221
4222 /// getValueTypeList - Return a pointer to the specified value type.
4223 ///
4224 const MVT *SDNode::getValueTypeList(MVT VT) {
4225   if (VT.isExtended()) {
4226     static std::set<MVT, MVT::compareRawBits> EVTs;
4227     return &(*EVTs.insert(VT).first);
4228   } else {
4229     static MVT VTs[MVT::LAST_VALUETYPE];
4230     VTs[VT.getSimpleVT()] = VT;
4231     return &VTs[VT.getSimpleVT()];
4232   }
4233 }
4234
4235 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
4236 /// indicated value.  This method ignores uses of other values defined by this
4237 /// operation.
4238 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
4239   assert(Value < getNumValues() && "Bad value!");
4240
4241   // If there is only one value, this is easy.
4242   if (getNumValues() == 1)
4243     return use_size() == NUses;
4244   if (use_size() < NUses) return false;
4245
4246   SDOperand TheValue(const_cast<SDNode *>(this), Value);
4247
4248   SmallPtrSet<SDNode*, 32> UsersHandled;
4249
4250   // TODO: Only iterate over uses of a given value of the node
4251   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
4252     if (*UI == TheValue) {
4253       if (NUses == 0)
4254         return false;
4255       --NUses;
4256     }
4257   }
4258
4259   // Found exactly the right number of uses?
4260   return NUses == 0;
4261 }
4262
4263
4264 /// hasAnyUseOfValue - Return true if there are any use of the indicated
4265 /// value. This method ignores uses of other values defined by this operation.
4266 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
4267   assert(Value < getNumValues() && "Bad value!");
4268
4269   if (use_empty()) return false;
4270
4271   SDOperand TheValue(const_cast<SDNode *>(this), Value);
4272
4273   SmallPtrSet<SDNode*, 32> UsersHandled;
4274
4275   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
4276     SDNode *User = UI->getUser();
4277     if (User->getNumOperands() == 1 ||
4278         UsersHandled.insert(User))     // First time we've seen this?
4279       for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
4280         if (User->getOperand(i) == TheValue) {
4281           return true;
4282         }
4283   }
4284
4285   return false;
4286 }
4287
4288
4289 /// isOnlyUseOf - Return true if this node is the only use of N.
4290 ///
4291 bool SDNode::isOnlyUseOf(SDNode *N) const {
4292   bool Seen = false;
4293   for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
4294     SDNode *User = I->getUser();
4295     if (User == this)
4296       Seen = true;
4297     else
4298       return false;
4299   }
4300
4301   return Seen;
4302 }
4303
4304 /// isOperand - Return true if this node is an operand of N.
4305 ///
4306 bool SDOperand::isOperandOf(SDNode *N) const {
4307   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4308     if (*this == N->getOperand(i))
4309       return true;
4310   return false;
4311 }
4312
4313 bool SDNode::isOperandOf(SDNode *N) const {
4314   for (unsigned i = 0, e = N->NumOperands; i != e; ++i)
4315     if (this == N->OperandList[i].getVal())
4316       return true;
4317   return false;
4318 }
4319
4320 /// reachesChainWithoutSideEffects - Return true if this operand (which must
4321 /// be a chain) reaches the specified operand without crossing any 
4322 /// side-effecting instructions.  In practice, this looks through token
4323 /// factors and non-volatile loads.  In order to remain efficient, this only
4324 /// looks a couple of nodes in, it does not do an exhaustive search.
4325 bool SDOperand::reachesChainWithoutSideEffects(SDOperand Dest, 
4326                                                unsigned Depth) const {
4327   if (*this == Dest) return true;
4328   
4329   // Don't search too deeply, we just want to be able to see through
4330   // TokenFactor's etc.
4331   if (Depth == 0) return false;
4332   
4333   // If this is a token factor, all inputs to the TF happen in parallel.  If any
4334   // of the operands of the TF reach dest, then we can do the xform.
4335   if (getOpcode() == ISD::TokenFactor) {
4336     for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
4337       if (getOperand(i).reachesChainWithoutSideEffects(Dest, Depth-1))
4338         return true;
4339     return false;
4340   }
4341   
4342   // Loads don't have side effects, look through them.
4343   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
4344     if (!Ld->isVolatile())
4345       return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
4346   }
4347   return false;
4348 }
4349
4350
4351 static void findPredecessor(SDNode *N, const SDNode *P, bool &found,
4352                             SmallPtrSet<SDNode *, 32> &Visited) {
4353   if (found || !Visited.insert(N))
4354     return;
4355
4356   for (unsigned i = 0, e = N->getNumOperands(); !found && i != e; ++i) {
4357     SDNode *Op = N->getOperand(i).Val;
4358     if (Op == P) {
4359       found = true;
4360       return;
4361     }
4362     findPredecessor(Op, P, found, Visited);
4363   }
4364 }
4365
4366 /// isPredecessorOf - Return true if this node is a predecessor of N. This node
4367 /// is either an operand of N or it can be reached by recursively traversing
4368 /// up the operands.
4369 /// NOTE: this is an expensive method. Use it carefully.
4370 bool SDNode::isPredecessorOf(SDNode *N) const {
4371   SmallPtrSet<SDNode *, 32> Visited;
4372   bool found = false;
4373   findPredecessor(N, this, found, Visited);
4374   return found;
4375 }
4376
4377 uint64_t SDNode::getConstantOperandVal(unsigned Num) const {
4378   assert(Num < NumOperands && "Invalid child # of SDNode!");
4379   return cast<ConstantSDNode>(OperandList[Num])->getValue();
4380 }
4381
4382 std::string SDNode::getOperationName(const SelectionDAG *G) const {
4383   switch (getOpcode()) {
4384   default:
4385     if (getOpcode() < ISD::BUILTIN_OP_END)
4386       return "<<Unknown DAG Node>>";
4387     else {
4388       if (G) {
4389         if (const TargetInstrInfo *TII = G->getTarget().getInstrInfo())
4390           if (getOpcode()-ISD::BUILTIN_OP_END < TII->getNumOpcodes())
4391             return TII->get(getOpcode()-ISD::BUILTIN_OP_END).getName();
4392
4393         TargetLowering &TLI = G->getTargetLoweringInfo();
4394         const char *Name =
4395           TLI.getTargetNodeName(getOpcode());
4396         if (Name) return Name;
4397       }
4398
4399       return "<<Unknown Target Node>>";
4400     }
4401    
4402   case ISD::PREFETCH:      return "Prefetch";
4403   case ISD::MEMBARRIER:    return "MemBarrier";
4404   case ISD::ATOMIC_LCS:    return "AtomicLCS";
4405   case ISD::ATOMIC_LAS:    return "AtomicLAS";
4406   case ISD::ATOMIC_LSS:    return "AtomicLSS";
4407   case ISD::ATOMIC_LOAD_AND:  return "AtomicLoadAnd";
4408   case ISD::ATOMIC_LOAD_OR:   return "AtomicLoadOr";
4409   case ISD::ATOMIC_LOAD_XOR:  return "AtomicLoadXor";
4410   case ISD::ATOMIC_LOAD_NAND: return "AtomicLoadNand";
4411   case ISD::ATOMIC_LOAD_MIN:  return "AtomicLoadMin";
4412   case ISD::ATOMIC_LOAD_MAX:  return "AtomicLoadMax";
4413   case ISD::ATOMIC_LOAD_UMIN: return "AtomicLoadUMin";
4414   case ISD::ATOMIC_LOAD_UMAX: return "AtomicLoadUMax";
4415   case ISD::ATOMIC_SWAP:   return "AtomicSWAP";
4416   case ISD::PCMARKER:      return "PCMarker";
4417   case ISD::READCYCLECOUNTER: return "ReadCycleCounter";
4418   case ISD::SRCVALUE:      return "SrcValue";
4419   case ISD::MEMOPERAND:    return "MemOperand";
4420   case ISD::EntryToken:    return "EntryToken";
4421   case ISD::TokenFactor:   return "TokenFactor";
4422   case ISD::AssertSext:    return "AssertSext";
4423   case ISD::AssertZext:    return "AssertZext";
4424
4425   case ISD::STRING:        return "String";
4426   case ISD::BasicBlock:    return "BasicBlock";
4427   case ISD::ARG_FLAGS:     return "ArgFlags";
4428   case ISD::VALUETYPE:     return "ValueType";
4429   case ISD::Register:      return "Register";
4430
4431   case ISD::Constant:      return "Constant";
4432   case ISD::ConstantFP:    return "ConstantFP";
4433   case ISD::GlobalAddress: return "GlobalAddress";
4434   case ISD::GlobalTLSAddress: return "GlobalTLSAddress";
4435   case ISD::FrameIndex:    return "FrameIndex";
4436   case ISD::JumpTable:     return "JumpTable";
4437   case ISD::GLOBAL_OFFSET_TABLE: return "GLOBAL_OFFSET_TABLE";
4438   case ISD::RETURNADDR: return "RETURNADDR";
4439   case ISD::FRAMEADDR: return "FRAMEADDR";
4440   case ISD::FRAME_TO_ARGS_OFFSET: return "FRAME_TO_ARGS_OFFSET";
4441   case ISD::EXCEPTIONADDR: return "EXCEPTIONADDR";
4442   case ISD::EHSELECTION: return "EHSELECTION";
4443   case ISD::EH_RETURN: return "EH_RETURN";
4444   case ISD::ConstantPool:  return "ConstantPool";
4445   case ISD::ExternalSymbol: return "ExternalSymbol";
4446   case ISD::INTRINSIC_WO_CHAIN: {
4447     unsigned IID = cast<ConstantSDNode>(getOperand(0))->getValue();
4448     return Intrinsic::getName((Intrinsic::ID)IID);
4449   }
4450   case ISD::INTRINSIC_VOID:
4451   case ISD::INTRINSIC_W_CHAIN: {
4452     unsigned IID = cast<ConstantSDNode>(getOperand(1))->getValue();
4453     return Intrinsic::getName((Intrinsic::ID)IID);
4454   }
4455
4456   case ISD::BUILD_VECTOR:   return "BUILD_VECTOR";
4457   case ISD::TargetConstant: return "TargetConstant";
4458   case ISD::TargetConstantFP:return "TargetConstantFP";
4459   case ISD::TargetGlobalAddress: return "TargetGlobalAddress";
4460   case ISD::TargetGlobalTLSAddress: return "TargetGlobalTLSAddress";
4461   case ISD::TargetFrameIndex: return "TargetFrameIndex";
4462   case ISD::TargetJumpTable:  return "TargetJumpTable";
4463   case ISD::TargetConstantPool:  return "TargetConstantPool";
4464   case ISD::TargetExternalSymbol: return "TargetExternalSymbol";
4465
4466   case ISD::CopyToReg:     return "CopyToReg";
4467   case ISD::CopyFromReg:   return "CopyFromReg";
4468   case ISD::UNDEF:         return "undef";
4469   case ISD::MERGE_VALUES:  return "merge_values";
4470   case ISD::INLINEASM:     return "inlineasm";
4471   case ISD::LABEL:         return "label";
4472   case ISD::DECLARE:       return "declare";
4473   case ISD::HANDLENODE:    return "handlenode";
4474   case ISD::FORMAL_ARGUMENTS: return "formal_arguments";
4475   case ISD::CALL:          return "call";
4476     
4477   // Unary operators
4478   case ISD::FABS:   return "fabs";
4479   case ISD::FNEG:   return "fneg";
4480   case ISD::FSQRT:  return "fsqrt";
4481   case ISD::FSIN:   return "fsin";
4482   case ISD::FCOS:   return "fcos";
4483   case ISD::FPOWI:  return "fpowi";
4484   case ISD::FPOW:   return "fpow";
4485
4486   // Binary operators
4487   case ISD::ADD:    return "add";
4488   case ISD::SUB:    return "sub";
4489   case ISD::MUL:    return "mul";
4490   case ISD::MULHU:  return "mulhu";
4491   case ISD::MULHS:  return "mulhs";
4492   case ISD::SDIV:   return "sdiv";
4493   case ISD::UDIV:   return "udiv";
4494   case ISD::SREM:   return "srem";
4495   case ISD::UREM:   return "urem";
4496   case ISD::SMUL_LOHI:  return "smul_lohi";
4497   case ISD::UMUL_LOHI:  return "umul_lohi";
4498   case ISD::SDIVREM:    return "sdivrem";
4499   case ISD::UDIVREM:    return "divrem";
4500   case ISD::AND:    return "and";
4501   case ISD::OR:     return "or";
4502   case ISD::XOR:    return "xor";
4503   case ISD::SHL:    return "shl";
4504   case ISD::SRA:    return "sra";
4505   case ISD::SRL:    return "srl";
4506   case ISD::ROTL:   return "rotl";
4507   case ISD::ROTR:   return "rotr";
4508   case ISD::FADD:   return "fadd";
4509   case ISD::FSUB:   return "fsub";
4510   case ISD::FMUL:   return "fmul";
4511   case ISD::FDIV:   return "fdiv";
4512   case ISD::FREM:   return "frem";
4513   case ISD::FCOPYSIGN: return "fcopysign";
4514   case ISD::FGETSIGN:  return "fgetsign";
4515
4516   case ISD::SETCC:       return "setcc";
4517   case ISD::VSETCC:      return "vsetcc";
4518   case ISD::SELECT:      return "select";
4519   case ISD::SELECT_CC:   return "select_cc";
4520   case ISD::INSERT_VECTOR_ELT:   return "insert_vector_elt";
4521   case ISD::EXTRACT_VECTOR_ELT:  return "extract_vector_elt";
4522   case ISD::CONCAT_VECTORS:      return "concat_vectors";
4523   case ISD::EXTRACT_SUBVECTOR:   return "extract_subvector";
4524   case ISD::SCALAR_TO_VECTOR:    return "scalar_to_vector";
4525   case ISD::VECTOR_SHUFFLE:      return "vector_shuffle";
4526   case ISD::CARRY_FALSE:         return "carry_false";
4527   case ISD::ADDC:        return "addc";
4528   case ISD::ADDE:        return "adde";
4529   case ISD::SUBC:        return "subc";
4530   case ISD::SUBE:        return "sube";
4531   case ISD::SHL_PARTS:   return "shl_parts";
4532   case ISD::SRA_PARTS:   return "sra_parts";
4533   case ISD::SRL_PARTS:   return "srl_parts";
4534   
4535   case ISD::EXTRACT_SUBREG:     return "extract_subreg";
4536   case ISD::INSERT_SUBREG:      return "insert_subreg";
4537   
4538   // Conversion operators.
4539   case ISD::SIGN_EXTEND: return "sign_extend";
4540   case ISD::ZERO_EXTEND: return "zero_extend";
4541   case ISD::ANY_EXTEND:  return "any_extend";
4542   case ISD::SIGN_EXTEND_INREG: return "sign_extend_inreg";
4543   case ISD::TRUNCATE:    return "truncate";
4544   case ISD::FP_ROUND:    return "fp_round";
4545   case ISD::FLT_ROUNDS_: return "flt_rounds";
4546   case ISD::FP_ROUND_INREG: return "fp_round_inreg";
4547   case ISD::FP_EXTEND:   return "fp_extend";
4548
4549   case ISD::SINT_TO_FP:  return "sint_to_fp";
4550   case ISD::UINT_TO_FP:  return "uint_to_fp";
4551   case ISD::FP_TO_SINT:  return "fp_to_sint";
4552   case ISD::FP_TO_UINT:  return "fp_to_uint";
4553   case ISD::BIT_CONVERT: return "bit_convert";
4554
4555     // Control flow instructions
4556   case ISD::BR:      return "br";
4557   case ISD::BRIND:   return "brind";
4558   case ISD::BR_JT:   return "br_jt";
4559   case ISD::BRCOND:  return "brcond";
4560   case ISD::BR_CC:   return "br_cc";
4561   case ISD::RET:     return "ret";
4562   case ISD::CALLSEQ_START:  return "callseq_start";
4563   case ISD::CALLSEQ_END:    return "callseq_end";
4564
4565     // Other operators
4566   case ISD::LOAD:               return "load";
4567   case ISD::STORE:              return "store";
4568   case ISD::VAARG:              return "vaarg";
4569   case ISD::VACOPY:             return "vacopy";
4570   case ISD::VAEND:              return "vaend";
4571   case ISD::VASTART:            return "vastart";
4572   case ISD::DYNAMIC_STACKALLOC: return "dynamic_stackalloc";
4573   case ISD::EXTRACT_ELEMENT:    return "extract_element";
4574   case ISD::BUILD_PAIR:         return "build_pair";
4575   case ISD::STACKSAVE:          return "stacksave";
4576   case ISD::STACKRESTORE:       return "stackrestore";
4577   case ISD::TRAP:               return "trap";
4578
4579   // Bit manipulation
4580   case ISD::BSWAP:   return "bswap";
4581   case ISD::CTPOP:   return "ctpop";
4582   case ISD::CTTZ:    return "cttz";
4583   case ISD::CTLZ:    return "ctlz";
4584
4585   // Debug info
4586   case ISD::LOCATION: return "location";
4587   case ISD::DEBUG_LOC: return "debug_loc";
4588
4589   // Trampolines
4590   case ISD::TRAMPOLINE: return "trampoline";
4591
4592   case ISD::CONDCODE:
4593     switch (cast<CondCodeSDNode>(this)->get()) {
4594     default: assert(0 && "Unknown setcc condition!");
4595     case ISD::SETOEQ:  return "setoeq";
4596     case ISD::SETOGT:  return "setogt";
4597     case ISD::SETOGE:  return "setoge";
4598     case ISD::SETOLT:  return "setolt";
4599     case ISD::SETOLE:  return "setole";
4600     case ISD::SETONE:  return "setone";
4601
4602     case ISD::SETO:    return "seto";
4603     case ISD::SETUO:   return "setuo";
4604     case ISD::SETUEQ:  return "setue";
4605     case ISD::SETUGT:  return "setugt";
4606     case ISD::SETUGE:  return "setuge";
4607     case ISD::SETULT:  return "setult";
4608     case ISD::SETULE:  return "setule";
4609     case ISD::SETUNE:  return "setune";
4610
4611     case ISD::SETEQ:   return "seteq";
4612     case ISD::SETGT:   return "setgt";
4613     case ISD::SETGE:   return "setge";
4614     case ISD::SETLT:   return "setlt";
4615     case ISD::SETLE:   return "setle";
4616     case ISD::SETNE:   return "setne";
4617     }
4618   }
4619 }
4620
4621 const char *SDNode::getIndexedModeName(ISD::MemIndexedMode AM) {
4622   switch (AM) {
4623   default:
4624     return "";
4625   case ISD::PRE_INC:
4626     return "<pre-inc>";
4627   case ISD::PRE_DEC:
4628     return "<pre-dec>";
4629   case ISD::POST_INC:
4630     return "<post-inc>";
4631   case ISD::POST_DEC:
4632     return "<post-dec>";
4633   }
4634 }
4635
4636 std::string ISD::ArgFlagsTy::getArgFlagsString() {
4637   std::string S = "< ";
4638
4639   if (isZExt())
4640     S += "zext ";
4641   if (isSExt())
4642     S += "sext ";
4643   if (isInReg())
4644     S += "inreg ";
4645   if (isSRet())
4646     S += "sret ";
4647   if (isByVal())
4648     S += "byval ";
4649   if (isNest())
4650     S += "nest ";
4651   if (getByValAlign())
4652     S += "byval-align:" + utostr(getByValAlign()) + " ";
4653   if (getOrigAlign())
4654     S += "orig-align:" + utostr(getOrigAlign()) + " ";
4655   if (getByValSize())
4656     S += "byval-size:" + utostr(getByValSize()) + " ";
4657   return S + ">";
4658 }
4659
4660 void SDNode::dump() const { dump(0); }
4661 void SDNode::dump(const SelectionDAG *G) const {
4662   cerr << (void*)this << ": ";
4663
4664   for (unsigned i = 0, e = getNumValues(); i != e; ++i) {
4665     if (i) cerr << ",";
4666     if (getValueType(i) == MVT::Other)
4667       cerr << "ch";
4668     else
4669       cerr << getValueType(i).getMVTString();
4670   }
4671   cerr << " = " << getOperationName(G);
4672
4673   cerr << " ";
4674   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
4675     if (i) cerr << ", ";
4676     cerr << (void*)getOperand(i).Val;
4677     if (unsigned RN = getOperand(i).ResNo)
4678       cerr << ":" << RN;
4679   }
4680
4681   if (!isTargetOpcode() && getOpcode() == ISD::VECTOR_SHUFFLE) {
4682     SDNode *Mask = getOperand(2).Val;
4683     cerr << "<";
4684     for (unsigned i = 0, e = Mask->getNumOperands(); i != e; ++i) {
4685       if (i) cerr << ",";
4686       if (Mask->getOperand(i).getOpcode() == ISD::UNDEF)
4687         cerr << "u";
4688       else
4689         cerr << cast<ConstantSDNode>(Mask->getOperand(i))->getValue();
4690     }
4691     cerr << ">";
4692   }
4693
4694   if (const ConstantSDNode *CSDN = dyn_cast<ConstantSDNode>(this)) {
4695     cerr << "<" << CSDN->getValue() << ">";
4696   } else if (const ConstantFPSDNode *CSDN = dyn_cast<ConstantFPSDNode>(this)) {
4697     if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEsingle)
4698       cerr << "<" << CSDN->getValueAPF().convertToFloat() << ">";
4699     else if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEdouble)
4700       cerr << "<" << CSDN->getValueAPF().convertToDouble() << ">";
4701     else {
4702       cerr << "<APFloat(";
4703       CSDN->getValueAPF().convertToAPInt().dump();
4704       cerr << ")>";
4705     }
4706   } else if (const GlobalAddressSDNode *GADN =
4707              dyn_cast<GlobalAddressSDNode>(this)) {
4708     int offset = GADN->getOffset();
4709     cerr << "<";
4710     WriteAsOperand(*cerr.stream(), GADN->getGlobal()) << ">";
4711     if (offset > 0)
4712       cerr << " + " << offset;
4713     else
4714       cerr << " " << offset;
4715   } else if (const FrameIndexSDNode *FIDN = dyn_cast<FrameIndexSDNode>(this)) {
4716     cerr << "<" << FIDN->getIndex() << ">";
4717   } else if (const JumpTableSDNode *JTDN = dyn_cast<JumpTableSDNode>(this)) {
4718     cerr << "<" << JTDN->getIndex() << ">";
4719   } else if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(this)){
4720     int offset = CP->getOffset();
4721     if (CP->isMachineConstantPoolEntry())
4722       cerr << "<" << *CP->getMachineCPVal() << ">";
4723     else
4724       cerr << "<" << *CP->getConstVal() << ">";
4725     if (offset > 0)
4726       cerr << " + " << offset;
4727     else
4728       cerr << " " << offset;
4729   } else if (const BasicBlockSDNode *BBDN = dyn_cast<BasicBlockSDNode>(this)) {
4730     cerr << "<";
4731     const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock();
4732     if (LBB)
4733       cerr << LBB->getName() << " ";
4734     cerr << (const void*)BBDN->getBasicBlock() << ">";
4735   } else if (const RegisterSDNode *R = dyn_cast<RegisterSDNode>(this)) {
4736     if (G && R->getReg() &&
4737         TargetRegisterInfo::isPhysicalRegister(R->getReg())) {
4738       cerr << " " << G->getTarget().getRegisterInfo()->getName(R->getReg());
4739     } else {
4740       cerr << " #" << R->getReg();
4741     }
4742   } else if (const ExternalSymbolSDNode *ES =
4743              dyn_cast<ExternalSymbolSDNode>(this)) {
4744     cerr << "'" << ES->getSymbol() << "'";
4745   } else if (const SrcValueSDNode *M = dyn_cast<SrcValueSDNode>(this)) {
4746     if (M->getValue())
4747       cerr << "<" << M->getValue() << ">";
4748     else
4749       cerr << "<null>";
4750   } else if (const MemOperandSDNode *M = dyn_cast<MemOperandSDNode>(this)) {
4751     if (M->MO.getValue())
4752       cerr << "<" << M->MO.getValue() << ":" << M->MO.getOffset() << ">";
4753     else
4754       cerr << "<null:" << M->MO.getOffset() << ">";
4755   } else if (const ARG_FLAGSSDNode *N = dyn_cast<ARG_FLAGSSDNode>(this)) {
4756     cerr << N->getArgFlags().getArgFlagsString();
4757   } else if (const VTSDNode *N = dyn_cast<VTSDNode>(this)) {
4758     cerr << ":" << N->getVT().getMVTString();
4759   } else if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(this)) {
4760     const Value *SrcValue = LD->getSrcValue();
4761     int SrcOffset = LD->getSrcValueOffset();
4762     cerr << " <";
4763     if (SrcValue)
4764       cerr << SrcValue;
4765     else
4766       cerr << "null";
4767     cerr << ":" << SrcOffset << ">";
4768
4769     bool doExt = true;
4770     switch (LD->getExtensionType()) {
4771     default: doExt = false; break;
4772     case ISD::EXTLOAD:
4773       cerr << " <anyext ";
4774       break;
4775     case ISD::SEXTLOAD:
4776       cerr << " <sext ";
4777       break;
4778     case ISD::ZEXTLOAD:
4779       cerr << " <zext ";
4780       break;
4781     }
4782     if (doExt)
4783       cerr << LD->getMemoryVT().getMVTString() << ">";
4784
4785     const char *AM = getIndexedModeName(LD->getAddressingMode());
4786     if (*AM)
4787       cerr << " " << AM;
4788     if (LD->isVolatile())
4789       cerr << " <volatile>";
4790     cerr << " alignment=" << LD->getAlignment();
4791   } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(this)) {
4792     const Value *SrcValue = ST->getSrcValue();
4793     int SrcOffset = ST->getSrcValueOffset();
4794     cerr << " <";
4795     if (SrcValue)
4796       cerr << SrcValue;
4797     else
4798       cerr << "null";
4799     cerr << ":" << SrcOffset << ">";
4800
4801     if (ST->isTruncatingStore())
4802       cerr << " <trunc "
4803            << ST->getMemoryVT().getMVTString() << ">";
4804
4805     const char *AM = getIndexedModeName(ST->getAddressingMode());
4806     if (*AM)
4807       cerr << " " << AM;
4808     if (ST->isVolatile())
4809       cerr << " <volatile>";
4810     cerr << " alignment=" << ST->getAlignment();
4811   }
4812 }
4813
4814 static void DumpNodes(const SDNode *N, unsigned indent, const SelectionDAG *G) {
4815   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4816     if (N->getOperand(i).Val->hasOneUse())
4817       DumpNodes(N->getOperand(i).Val, indent+2, G);
4818     else
4819       cerr << "\n" << std::string(indent+2, ' ')
4820            << (void*)N->getOperand(i).Val << ": <multiple use>";
4821
4822
4823   cerr << "\n" << std::string(indent, ' ');
4824   N->dump(G);
4825 }
4826
4827 void SelectionDAG::dump() const {
4828   cerr << "SelectionDAG has " << AllNodes.size() << " nodes:";
4829   std::vector<const SDNode*> Nodes;
4830   for (allnodes_const_iterator I = allnodes_begin(), E = allnodes_end();
4831        I != E; ++I)
4832     Nodes.push_back(I);
4833   
4834   std::sort(Nodes.begin(), Nodes.end());
4835
4836   for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
4837     if (!Nodes[i]->hasOneUse() && Nodes[i] != getRoot().Val)
4838       DumpNodes(Nodes[i], 2, this);
4839   }
4840
4841   if (getRoot().Val) DumpNodes(getRoot().Val, 2, this);
4842
4843   cerr << "\n\n";
4844 }
4845
4846 const Type *ConstantPoolSDNode::getType() const {
4847   if (isMachineConstantPoolEntry())
4848     return Val.MachineCPVal->getType();
4849   return Val.ConstVal->getType();
4850 }