Remove custom expansion from LegalizeTypes when doing
[oota-llvm.git] / lib / CodeGen / SelectionDAG / LegalizeDAG.cpp
1 //===-- LegalizeDAG.cpp - Implement SelectionDAG::Legalize ----------------===//
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 file implements the SelectionDAG::Legalize method.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/CodeGen/SelectionDAG.h"
15 #include "llvm/CodeGen/MachineFunction.h"
16 #include "llvm/CodeGen/MachineFrameInfo.h"
17 #include "llvm/CodeGen/MachineJumpTableInfo.h"
18 #include "llvm/CodeGen/MachineModuleInfo.h"
19 #include "llvm/CodeGen/PseudoSourceValue.h"
20 #include "llvm/Target/TargetFrameInfo.h"
21 #include "llvm/Target/TargetLowering.h"
22 #include "llvm/Target/TargetData.h"
23 #include "llvm/Target/TargetMachine.h"
24 #include "llvm/Target/TargetOptions.h"
25 #include "llvm/Target/TargetSubtarget.h"
26 #include "llvm/CallingConv.h"
27 #include "llvm/Constants.h"
28 #include "llvm/DerivedTypes.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Compiler.h"
31 #include "llvm/Support/MathExtras.h"
32 #include "llvm/ADT/DenseMap.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/SmallPtrSet.h"
35 #include <map>
36 using namespace llvm;
37
38 #ifndef NDEBUG
39 static cl::opt<bool>
40 ViewLegalizeDAGs("view-legalize-dags", cl::Hidden,
41                  cl::desc("Pop up a window to show dags before legalize"));
42 #else
43 static const bool ViewLegalizeDAGs = 0;
44 #endif
45
46 //===----------------------------------------------------------------------===//
47 /// SelectionDAGLegalize - This takes an arbitrary SelectionDAG as input and
48 /// hacks on it until the target machine can handle it.  This involves
49 /// eliminating value sizes the machine cannot handle (promoting small sizes to
50 /// large sizes or splitting up large values into small values) as well as
51 /// eliminating operations the machine cannot handle.
52 ///
53 /// This code also does a small amount of optimization and recognition of idioms
54 /// as part of its processing.  For example, if a target does not support a
55 /// 'setcc' instruction efficiently, but does support 'brcc' instruction, this
56 /// will attempt merge setcc and brc instructions into brcc's.
57 ///
58 namespace {
59 class VISIBILITY_HIDDEN SelectionDAGLegalize {
60   TargetLowering &TLI;
61   SelectionDAG &DAG;
62
63   // Libcall insertion helpers.
64   
65   /// LastCALLSEQ_END - This keeps track of the CALLSEQ_END node that has been
66   /// legalized.  We use this to ensure that calls are properly serialized
67   /// against each other, including inserted libcalls.
68   SDOperand LastCALLSEQ_END;
69   
70   /// IsLegalizingCall - This member is used *only* for purposes of providing
71   /// helpful assertions that a libcall isn't created while another call is 
72   /// being legalized (which could lead to non-serialized call sequences).
73   bool IsLegalizingCall;
74   
75   enum LegalizeAction {
76     Legal,      // The target natively supports this operation.
77     Promote,    // This operation should be executed in a larger type.
78     Expand      // Try to expand this to other ops, otherwise use a libcall.
79   };
80   
81   /// ValueTypeActions - This is a bitvector that contains two bits for each
82   /// value type, where the two bits correspond to the LegalizeAction enum.
83   /// This can be queried with "getTypeAction(VT)".
84   TargetLowering::ValueTypeActionImpl ValueTypeActions;
85
86   /// LegalizedNodes - For nodes that are of legal width, and that have more
87   /// than one use, this map indicates what regularized operand to use.  This
88   /// allows us to avoid legalizing the same thing more than once.
89   DenseMap<SDOperand, SDOperand> LegalizedNodes;
90
91   /// PromotedNodes - For nodes that are below legal width, and that have more
92   /// than one use, this map indicates what promoted value to use.  This allows
93   /// us to avoid promoting the same thing more than once.
94   DenseMap<SDOperand, SDOperand> PromotedNodes;
95
96   /// ExpandedNodes - For nodes that need to be expanded this map indicates
97   /// which which operands are the expanded version of the input.  This allows
98   /// us to avoid expanding the same node more than once.
99   DenseMap<SDOperand, std::pair<SDOperand, SDOperand> > ExpandedNodes;
100
101   /// SplitNodes - For vector nodes that need to be split, this map indicates
102   /// which which operands are the split version of the input.  This allows us
103   /// to avoid splitting the same node more than once.
104   std::map<SDOperand, std::pair<SDOperand, SDOperand> > SplitNodes;
105   
106   /// ScalarizedNodes - For nodes that need to be converted from vector types to
107   /// scalar types, this contains the mapping of ones we have already
108   /// processed to the result.
109   std::map<SDOperand, SDOperand> ScalarizedNodes;
110   
111   void AddLegalizedOperand(SDOperand From, SDOperand To) {
112     LegalizedNodes.insert(std::make_pair(From, To));
113     // If someone requests legalization of the new node, return itself.
114     if (From != To)
115       LegalizedNodes.insert(std::make_pair(To, To));
116   }
117   void AddPromotedOperand(SDOperand From, SDOperand To) {
118     bool isNew = PromotedNodes.insert(std::make_pair(From, To)).second;
119     assert(isNew && "Got into the map somehow?");
120     // If someone requests legalization of the new node, return itself.
121     LegalizedNodes.insert(std::make_pair(To, To));
122   }
123
124 public:
125   explicit SelectionDAGLegalize(SelectionDAG &DAG);
126
127   /// getTypeAction - Return how we should legalize values of this type, either
128   /// it is already legal or we need to expand it into multiple registers of
129   /// smaller integer type, or we need to promote it to a larger type.
130   LegalizeAction getTypeAction(MVT VT) const {
131     return (LegalizeAction)ValueTypeActions.getTypeAction(VT);
132   }
133
134   /// isTypeLegal - Return true if this type is legal on this target.
135   ///
136   bool isTypeLegal(MVT VT) const {
137     return getTypeAction(VT) == Legal;
138   }
139
140   void LegalizeDAG();
141
142 private:
143   /// HandleOp - Legalize, Promote, or Expand the specified operand as
144   /// appropriate for its type.
145   void HandleOp(SDOperand Op);
146     
147   /// LegalizeOp - We know that the specified value has a legal type.
148   /// Recursively ensure that the operands have legal types, then return the
149   /// result.
150   SDOperand LegalizeOp(SDOperand O);
151   
152   /// UnrollVectorOp - We know that the given vector has a legal type, however
153   /// the operation it performs is not legal and is an operation that we have
154   /// no way of lowering.  "Unroll" the vector, splitting out the scalars and
155   /// operating on each element individually.
156   SDOperand UnrollVectorOp(SDOperand O);
157   
158   /// PerformInsertVectorEltInMemory - Some target cannot handle a variable
159   /// insertion index for the INSERT_VECTOR_ELT instruction.  In this case, it
160   /// is necessary to spill the vector being inserted into to memory, perform
161   /// the insert there, and then read the result back.
162   SDOperand PerformInsertVectorEltInMemory(SDOperand Vec, SDOperand Val,
163                                            SDOperand Idx);
164
165   /// PromoteOp - Given an operation that produces a value in an invalid type,
166   /// promote it to compute the value into a larger type.  The produced value
167   /// will have the correct bits for the low portion of the register, but no
168   /// guarantee is made about the top bits: it may be zero, sign-extended, or
169   /// garbage.
170   SDOperand PromoteOp(SDOperand O);
171
172   /// ExpandOp - Expand the specified SDOperand into its two component pieces
173   /// Lo&Hi.  Note that the Op MUST be an expanded type.  As a result of this,
174   /// the LegalizeNodes map is filled in for any results that are not expanded,
175   /// the ExpandedNodes map is filled in for any results that are expanded, and
176   /// the Lo/Hi values are returned.   This applies to integer types and Vector
177   /// types.
178   void ExpandOp(SDOperand O, SDOperand &Lo, SDOperand &Hi);
179
180   /// SplitVectorOp - Given an operand of vector type, break it down into
181   /// two smaller values.
182   void SplitVectorOp(SDOperand O, SDOperand &Lo, SDOperand &Hi);
183   
184   /// ScalarizeVectorOp - Given an operand of single-element vector type
185   /// (e.g. v1f32), convert it into the equivalent operation that returns a
186   /// scalar (e.g. f32) value.
187   SDOperand ScalarizeVectorOp(SDOperand O);
188   
189   /// isShuffleLegal - Return true if a vector shuffle is legal with the
190   /// specified mask and type.  Targets can specify exactly which masks they
191   /// support and the code generator is tasked with not creating illegal masks.
192   ///
193   /// Note that this will also return true for shuffles that are promoted to a
194   /// different type.
195   ///
196   /// If this is a legal shuffle, this method returns the (possibly promoted)
197   /// build_vector Mask.  If it's not a legal shuffle, it returns null.
198   SDNode *isShuffleLegal(MVT VT, SDOperand Mask) const;
199   
200   bool LegalizeAllNodesNotLeadingTo(SDNode *N, SDNode *Dest,
201                                     SmallPtrSet<SDNode*, 32> &NodesLeadingTo);
202
203   void LegalizeSetCCOperands(SDOperand &LHS, SDOperand &RHS, SDOperand &CC);
204     
205   SDOperand ExpandLibCall(RTLIB::Libcall LC, SDNode *Node, bool isSigned,
206                           SDOperand &Hi);
207   SDOperand ExpandIntToFP(bool isSigned, MVT DestTy, SDOperand Source);
208
209   SDOperand EmitStackConvert(SDOperand SrcOp, MVT SlotVT, MVT DestVT);
210   SDOperand ExpandBUILD_VECTOR(SDNode *Node);
211   SDOperand ExpandSCALAR_TO_VECTOR(SDNode *Node);
212   SDOperand ExpandLegalINT_TO_FP(bool isSigned, SDOperand LegalOp, MVT DestVT);
213   SDOperand PromoteLegalINT_TO_FP(SDOperand LegalOp, MVT DestVT, bool isSigned);
214   SDOperand PromoteLegalFP_TO_INT(SDOperand LegalOp, MVT DestVT, bool isSigned);
215
216   SDOperand ExpandBSWAP(SDOperand Op);
217   SDOperand ExpandBitCount(unsigned Opc, SDOperand Op);
218   bool ExpandShift(unsigned Opc, SDOperand Op, SDOperand Amt,
219                    SDOperand &Lo, SDOperand &Hi);
220   void ExpandShiftParts(unsigned NodeOp, SDOperand Op, SDOperand Amt,
221                         SDOperand &Lo, SDOperand &Hi);
222
223   SDOperand ExpandEXTRACT_SUBVECTOR(SDOperand Op);
224   SDOperand ExpandEXTRACT_VECTOR_ELT(SDOperand Op);
225 };
226 }
227
228 /// isVectorShuffleLegal - Return true if a vector shuffle is legal with the
229 /// specified mask and type.  Targets can specify exactly which masks they
230 /// support and the code generator is tasked with not creating illegal masks.
231 ///
232 /// Note that this will also return true for shuffles that are promoted to a
233 /// different type.
234 SDNode *SelectionDAGLegalize::isShuffleLegal(MVT VT, SDOperand Mask) const {
235   switch (TLI.getOperationAction(ISD::VECTOR_SHUFFLE, VT)) {
236   default: return 0;
237   case TargetLowering::Legal:
238   case TargetLowering::Custom:
239     break;
240   case TargetLowering::Promote: {
241     // If this is promoted to a different type, convert the shuffle mask and
242     // ask if it is legal in the promoted type!
243     MVT NVT = TLI.getTypeToPromoteTo(ISD::VECTOR_SHUFFLE, VT);
244
245     // If we changed # elements, change the shuffle mask.
246     unsigned NumEltsGrowth =
247       NVT.getVectorNumElements() / VT.getVectorNumElements();
248     assert(NumEltsGrowth && "Cannot promote to vector type with fewer elts!");
249     if (NumEltsGrowth > 1) {
250       // Renumber the elements.
251       SmallVector<SDOperand, 8> Ops;
252       for (unsigned i = 0, e = Mask.getNumOperands(); i != e; ++i) {
253         SDOperand InOp = Mask.getOperand(i);
254         for (unsigned j = 0; j != NumEltsGrowth; ++j) {
255           if (InOp.getOpcode() == ISD::UNDEF)
256             Ops.push_back(DAG.getNode(ISD::UNDEF, MVT::i32));
257           else {
258             unsigned InEltNo = cast<ConstantSDNode>(InOp)->getValue();
259             Ops.push_back(DAG.getConstant(InEltNo*NumEltsGrowth+j, MVT::i32));
260           }
261         }
262       }
263       Mask = DAG.getNode(ISD::BUILD_VECTOR, NVT, &Ops[0], Ops.size());
264     }
265     VT = NVT;
266     break;
267   }
268   }
269   return TLI.isShuffleMaskLegal(Mask, VT) ? Mask.Val : 0;
270 }
271
272 SelectionDAGLegalize::SelectionDAGLegalize(SelectionDAG &dag)
273   : TLI(dag.getTargetLoweringInfo()), DAG(dag),
274     ValueTypeActions(TLI.getValueTypeActions()) {
275   assert(MVT::LAST_VALUETYPE <= 32 &&
276          "Too many value types for ValueTypeActions to hold!");
277 }
278
279 /// ComputeTopDownOrdering - Compute a top-down ordering of the dag, where Order
280 /// contains all of a nodes operands before it contains the node.
281 static void ComputeTopDownOrdering(SelectionDAG &DAG,
282                                    SmallVector<SDNode*, 64> &Order) {
283
284   DenseMap<SDNode*, unsigned> Visited;
285   std::vector<SDNode*> Worklist;
286   Worklist.reserve(128);
287   
288   // Compute ordering from all of the leaves in the graphs, those (like the
289   // entry node) that have no operands.
290   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
291        E = DAG.allnodes_end(); I != E; ++I) {
292     if (I->getNumOperands() == 0) {
293       Visited[I] = 0 - 1U;
294       Worklist.push_back(I);
295     }
296   }
297   
298   while (!Worklist.empty()) {
299     SDNode *N = Worklist.back();
300     Worklist.pop_back();
301     
302     if (++Visited[N] != N->getNumOperands())
303       continue;  // Haven't visited all operands yet
304     
305     Order.push_back(N);
306
307     // Now that we have N in, add anything that uses it if all of their operands
308     // are now done.
309     for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
310          UI != E; ++UI)
311       Worklist.push_back(UI->getUser());
312   }
313
314   assert(Order.size() == Visited.size() &&
315          Order.size() == DAG.allnodes_size() &&
316          "Error: DAG is cyclic!");
317 }
318
319
320 void SelectionDAGLegalize::LegalizeDAG() {
321   LastCALLSEQ_END = DAG.getEntryNode();
322   IsLegalizingCall = false;
323   
324   // The legalize process is inherently a bottom-up recursive process (users
325   // legalize their uses before themselves).  Given infinite stack space, we
326   // could just start legalizing on the root and traverse the whole graph.  In
327   // practice however, this causes us to run out of stack space on large basic
328   // blocks.  To avoid this problem, compute an ordering of the nodes where each
329   // node is only legalized after all of its operands are legalized.
330   SmallVector<SDNode*, 64> Order;
331   ComputeTopDownOrdering(DAG, Order);
332   
333   for (unsigned i = 0, e = Order.size(); i != e; ++i)
334     HandleOp(SDOperand(Order[i], 0));
335
336   // Finally, it's possible the root changed.  Get the new root.
337   SDOperand OldRoot = DAG.getRoot();
338   assert(LegalizedNodes.count(OldRoot) && "Root didn't get legalized?");
339   DAG.setRoot(LegalizedNodes[OldRoot]);
340
341   ExpandedNodes.clear();
342   LegalizedNodes.clear();
343   PromotedNodes.clear();
344   SplitNodes.clear();
345   ScalarizedNodes.clear();
346
347   // Remove dead nodes now.
348   DAG.RemoveDeadNodes();
349 }
350
351
352 /// FindCallEndFromCallStart - Given a chained node that is part of a call
353 /// sequence, find the CALLSEQ_END node that terminates the call sequence.
354 static SDNode *FindCallEndFromCallStart(SDNode *Node) {
355   if (Node->getOpcode() == ISD::CALLSEQ_END)
356     return Node;
357   if (Node->use_empty())
358     return 0;   // No CallSeqEnd
359   
360   // The chain is usually at the end.
361   SDOperand TheChain(Node, Node->getNumValues()-1);
362   if (TheChain.getValueType() != MVT::Other) {
363     // Sometimes it's at the beginning.
364     TheChain = SDOperand(Node, 0);
365     if (TheChain.getValueType() != MVT::Other) {
366       // Otherwise, hunt for it.
367       for (unsigned i = 1, e = Node->getNumValues(); i != e; ++i)
368         if (Node->getValueType(i) == MVT::Other) {
369           TheChain = SDOperand(Node, i);
370           break;
371         }
372           
373       // Otherwise, we walked into a node without a chain.  
374       if (TheChain.getValueType() != MVT::Other)
375         return 0;
376     }
377   }
378   
379   for (SDNode::use_iterator UI = Node->use_begin(),
380        E = Node->use_end(); UI != E; ++UI) {
381     
382     // Make sure to only follow users of our token chain.
383     SDNode *User = UI->getUser();
384     for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
385       if (User->getOperand(i) == TheChain)
386         if (SDNode *Result = FindCallEndFromCallStart(User))
387           return Result;
388   }
389   return 0;
390 }
391
392 /// FindCallStartFromCallEnd - Given a chained node that is part of a call 
393 /// sequence, find the CALLSEQ_START node that initiates the call sequence.
394 static SDNode *FindCallStartFromCallEnd(SDNode *Node) {
395   assert(Node && "Didn't find callseq_start for a call??");
396   if (Node->getOpcode() == ISD::CALLSEQ_START) return Node;
397   
398   assert(Node->getOperand(0).getValueType() == MVT::Other &&
399          "Node doesn't have a token chain argument!");
400   return FindCallStartFromCallEnd(Node->getOperand(0).Val);
401 }
402
403 /// LegalizeAllNodesNotLeadingTo - Recursively walk the uses of N, looking to
404 /// see if any uses can reach Dest.  If no dest operands can get to dest, 
405 /// legalize them, legalize ourself, and return false, otherwise, return true.
406 ///
407 /// Keep track of the nodes we fine that actually do lead to Dest in
408 /// NodesLeadingTo.  This avoids retraversing them exponential number of times.
409 ///
410 bool SelectionDAGLegalize::LegalizeAllNodesNotLeadingTo(SDNode *N, SDNode *Dest,
411                                      SmallPtrSet<SDNode*, 32> &NodesLeadingTo) {
412   if (N == Dest) return true;  // N certainly leads to Dest :)
413   
414   // If we've already processed this node and it does lead to Dest, there is no
415   // need to reprocess it.
416   if (NodesLeadingTo.count(N)) return true;
417   
418   // If the first result of this node has been already legalized, then it cannot
419   // reach N.
420   switch (getTypeAction(N->getValueType(0))) {
421   case Legal: 
422     if (LegalizedNodes.count(SDOperand(N, 0))) return false;
423     break;
424   case Promote:
425     if (PromotedNodes.count(SDOperand(N, 0))) return false;
426     break;
427   case Expand:
428     if (ExpandedNodes.count(SDOperand(N, 0))) return false;
429     break;
430   }
431   
432   // Okay, this node has not already been legalized.  Check and legalize all
433   // operands.  If none lead to Dest, then we can legalize this node.
434   bool OperandsLeadToDest = false;
435   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
436     OperandsLeadToDest |=     // If an operand leads to Dest, so do we.
437       LegalizeAllNodesNotLeadingTo(N->getOperand(i).Val, Dest, NodesLeadingTo);
438
439   if (OperandsLeadToDest) {
440     NodesLeadingTo.insert(N);
441     return true;
442   }
443
444   // Okay, this node looks safe, legalize it and return false.
445   HandleOp(SDOperand(N, 0));
446   return false;
447 }
448
449 /// HandleOp - Legalize, Promote, or Expand the specified operand as
450 /// appropriate for its type.
451 void SelectionDAGLegalize::HandleOp(SDOperand Op) {
452   MVT VT = Op.getValueType();
453   switch (getTypeAction(VT)) {
454   default: assert(0 && "Bad type action!");
455   case Legal:   (void)LegalizeOp(Op); break;
456   case Promote: (void)PromoteOp(Op); break;
457   case Expand:
458     if (!VT.isVector()) {
459       // If this is an illegal scalar, expand it into its two component
460       // pieces.
461       SDOperand X, Y;
462       if (Op.getOpcode() == ISD::TargetConstant)
463         break;  // Allow illegal target nodes.
464       ExpandOp(Op, X, Y);
465     } else if (VT.getVectorNumElements() == 1) {
466       // If this is an illegal single element vector, convert it to a
467       // scalar operation.
468       (void)ScalarizeVectorOp(Op);
469     } else {
470       // Otherwise, this is an illegal multiple element vector.
471       // Split it in half and legalize both parts.
472       SDOperand X, Y;
473       SplitVectorOp(Op, X, Y);
474     }
475     break;
476   }
477 }
478
479 /// ExpandConstantFP - Expands the ConstantFP node to an integer constant or
480 /// a load from the constant pool.
481 static SDOperand ExpandConstantFP(ConstantFPSDNode *CFP, bool UseCP,
482                                   SelectionDAG &DAG, TargetLowering &TLI) {
483   bool Extend = false;
484
485   // If a FP immediate is precise when represented as a float and if the
486   // target can do an extending load from float to double, we put it into
487   // the constant pool as a float, even if it's is statically typed as a
488   // double.  This shrinks FP constants and canonicalizes them for targets where
489   // an FP extending load is the same cost as a normal load (such as on the x87
490   // fp stack or PPC FP unit).
491   MVT VT = CFP->getValueType(0);
492   ConstantFP *LLVMC = ConstantFP::get(CFP->getValueAPF());
493   if (!UseCP) {
494     if (VT!=MVT::f64 && VT!=MVT::f32)
495       assert(0 && "Invalid type expansion");
496     return DAG.getConstant(LLVMC->getValueAPF().convertToAPInt(),
497                            (VT == MVT::f64) ? MVT::i64 : MVT::i32);
498   }
499
500   MVT OrigVT = VT;
501   MVT SVT = VT;
502   while (SVT != MVT::f32) {
503     SVT = (MVT::SimpleValueType)(SVT.getSimpleVT() - 1);
504     if (CFP->isValueValidForType(SVT, CFP->getValueAPF()) &&
505         // Only do this if the target has a native EXTLOAD instruction from
506         // smaller type.
507         TLI.isLoadXLegal(ISD::EXTLOAD, SVT) &&
508         TLI.ShouldShrinkFPConstant(OrigVT)) {
509       const Type *SType = SVT.getTypeForMVT();
510       LLVMC = cast<ConstantFP>(ConstantExpr::getFPTrunc(LLVMC, SType));
511       VT = SVT;
512       Extend = true;
513     }
514   }
515
516   SDOperand CPIdx = DAG.getConstantPool(LLVMC, TLI.getPointerTy());
517   if (Extend)
518     return DAG.getExtLoad(ISD::EXTLOAD, OrigVT, DAG.getEntryNode(),
519                           CPIdx, PseudoSourceValue::getConstantPool(),
520                           0, VT);
521   return DAG.getLoad(OrigVT, DAG.getEntryNode(), CPIdx,
522                      PseudoSourceValue::getConstantPool(), 0);
523 }
524
525
526 /// ExpandFCOPYSIGNToBitwiseOps - Expands fcopysign to a series of bitwise
527 /// operations.
528 static
529 SDOperand ExpandFCOPYSIGNToBitwiseOps(SDNode *Node, MVT NVT,
530                                       SelectionDAG &DAG, TargetLowering &TLI) {
531   MVT VT = Node->getValueType(0);
532   MVT SrcVT = Node->getOperand(1).getValueType();
533   assert((SrcVT == MVT::f32 || SrcVT == MVT::f64) &&
534          "fcopysign expansion only supported for f32 and f64");
535   MVT SrcNVT = (SrcVT == MVT::f64) ? MVT::i64 : MVT::i32;
536
537   // First get the sign bit of second operand.
538   SDOperand Mask1 = (SrcVT == MVT::f64)
539     ? DAG.getConstantFP(BitsToDouble(1ULL << 63), SrcVT)
540     : DAG.getConstantFP(BitsToFloat(1U << 31), SrcVT);
541   Mask1 = DAG.getNode(ISD::BIT_CONVERT, SrcNVT, Mask1);
542   SDOperand SignBit= DAG.getNode(ISD::BIT_CONVERT, SrcNVT, Node->getOperand(1));
543   SignBit = DAG.getNode(ISD::AND, SrcNVT, SignBit, Mask1);
544   // Shift right or sign-extend it if the two operands have different types.
545   int SizeDiff = SrcNVT.getSizeInBits() - NVT.getSizeInBits();
546   if (SizeDiff > 0) {
547     SignBit = DAG.getNode(ISD::SRL, SrcNVT, SignBit,
548                           DAG.getConstant(SizeDiff, TLI.getShiftAmountTy()));
549     SignBit = DAG.getNode(ISD::TRUNCATE, NVT, SignBit);
550   } else if (SizeDiff < 0)
551     SignBit = DAG.getNode(ISD::SIGN_EXTEND, NVT, SignBit);
552
553   // Clear the sign bit of first operand.
554   SDOperand Mask2 = (VT == MVT::f64)
555     ? DAG.getConstantFP(BitsToDouble(~(1ULL << 63)), VT)
556     : DAG.getConstantFP(BitsToFloat(~(1U << 31)), VT);
557   Mask2 = DAG.getNode(ISD::BIT_CONVERT, NVT, Mask2);
558   SDOperand Result = DAG.getNode(ISD::BIT_CONVERT, NVT, Node->getOperand(0));
559   Result = DAG.getNode(ISD::AND, NVT, Result, Mask2);
560
561   // Or the value with the sign bit.
562   Result = DAG.getNode(ISD::OR, NVT, Result, SignBit);
563   return Result;
564 }
565
566 /// ExpandUnalignedStore - Expands an unaligned store to 2 half-size stores.
567 static
568 SDOperand ExpandUnalignedStore(StoreSDNode *ST, SelectionDAG &DAG,
569                                TargetLowering &TLI) {
570   SDOperand Chain = ST->getChain();
571   SDOperand Ptr = ST->getBasePtr();
572   SDOperand Val = ST->getValue();
573   MVT VT = Val.getValueType();
574   int Alignment = ST->getAlignment();
575   int SVOffset = ST->getSrcValueOffset();
576   if (ST->getMemoryVT().isFloatingPoint() ||
577       ST->getMemoryVT().isVector()) {
578     // Expand to a bitconvert of the value to the integer type of the 
579     // same size, then a (misaligned) int store.
580     MVT intVT;
581     if (VT.is128BitVector() || VT == MVT::ppcf128 || VT == MVT::f128)
582       intVT = MVT::i128;
583     else if (VT.is64BitVector() || VT==MVT::f64)
584       intVT = MVT::i64;
585     else if (VT==MVT::f32)
586       intVT = MVT::i32;
587     else
588       assert(0 && "Unaligned store of unsupported type");
589
590     SDOperand Result = DAG.getNode(ISD::BIT_CONVERT, intVT, Val);
591     return DAG.getStore(Chain, Result, Ptr, ST->getSrcValue(),
592                         SVOffset, ST->isVolatile(), Alignment);
593   }
594   assert(ST->getMemoryVT().isInteger() &&
595          !ST->getMemoryVT().isVector() &&
596          "Unaligned store of unknown type.");
597   // Get the half-size VT
598   MVT NewStoredVT =
599     (MVT::SimpleValueType)(ST->getMemoryVT().getSimpleVT() - 1);
600   int NumBits = NewStoredVT.getSizeInBits();
601   int IncrementSize = NumBits / 8;
602
603   // Divide the stored value in two parts.
604   SDOperand ShiftAmount = DAG.getConstant(NumBits, TLI.getShiftAmountTy());
605   SDOperand Lo = Val;
606   SDOperand Hi = DAG.getNode(ISD::SRL, VT, Val, ShiftAmount);
607
608   // Store the two parts
609   SDOperand Store1, Store2;
610   Store1 = DAG.getTruncStore(Chain, TLI.isLittleEndian()?Lo:Hi, Ptr,
611                              ST->getSrcValue(), SVOffset, NewStoredVT,
612                              ST->isVolatile(), Alignment);
613   Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
614                     DAG.getConstant(IncrementSize, TLI.getPointerTy()));
615   Alignment = MinAlign(Alignment, IncrementSize);
616   Store2 = DAG.getTruncStore(Chain, TLI.isLittleEndian()?Hi:Lo, Ptr,
617                              ST->getSrcValue(), SVOffset + IncrementSize,
618                              NewStoredVT, ST->isVolatile(), Alignment);
619
620   return DAG.getNode(ISD::TokenFactor, MVT::Other, Store1, Store2);
621 }
622
623 /// ExpandUnalignedLoad - Expands an unaligned load to 2 half-size loads.
624 static
625 SDOperand ExpandUnalignedLoad(LoadSDNode *LD, SelectionDAG &DAG,
626                               TargetLowering &TLI) {
627   int SVOffset = LD->getSrcValueOffset();
628   SDOperand Chain = LD->getChain();
629   SDOperand Ptr = LD->getBasePtr();
630   MVT VT = LD->getValueType(0);
631   MVT LoadedVT = LD->getMemoryVT();
632   if (VT.isFloatingPoint() || VT.isVector()) {
633     // Expand to a (misaligned) integer load of the same size,
634     // then bitconvert to floating point or vector.
635     MVT intVT;
636     if (LoadedVT.is128BitVector() ||
637          LoadedVT == MVT::ppcf128 || LoadedVT == MVT::f128)
638       intVT = MVT::i128;
639     else if (LoadedVT.is64BitVector() || LoadedVT == MVT::f64)
640       intVT = MVT::i64;
641     else if (LoadedVT == MVT::f32)
642       intVT = MVT::i32;
643     else
644       assert(0 && "Unaligned load of unsupported type");
645
646     SDOperand newLoad = DAG.getLoad(intVT, Chain, Ptr, LD->getSrcValue(),
647                                     SVOffset, LD->isVolatile(), 
648                                     LD->getAlignment());
649     SDOperand Result = DAG.getNode(ISD::BIT_CONVERT, LoadedVT, newLoad);
650     if (VT.isFloatingPoint() && LoadedVT != VT)
651       Result = DAG.getNode(ISD::FP_EXTEND, VT, Result);
652
653     SDOperand Ops[] = { Result, Chain };
654     return DAG.getMergeValues(Ops, 2);
655   }
656   assert(LoadedVT.isInteger() && !LoadedVT.isVector() &&
657          "Unaligned load of unsupported type.");
658
659   // Compute the new VT that is half the size of the old one.  This is an
660   // integer MVT.
661   unsigned NumBits = LoadedVT.getSizeInBits();
662   MVT NewLoadedVT;
663   NewLoadedVT = MVT::getIntegerVT(NumBits/2);
664   NumBits >>= 1;
665   
666   unsigned Alignment = LD->getAlignment();
667   unsigned IncrementSize = NumBits / 8;
668   ISD::LoadExtType HiExtType = LD->getExtensionType();
669
670   // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD.
671   if (HiExtType == ISD::NON_EXTLOAD)
672     HiExtType = ISD::ZEXTLOAD;
673
674   // Load the value in two parts
675   SDOperand Lo, Hi;
676   if (TLI.isLittleEndian()) {
677     Lo = DAG.getExtLoad(ISD::ZEXTLOAD, VT, Chain, Ptr, LD->getSrcValue(),
678                         SVOffset, NewLoadedVT, LD->isVolatile(), Alignment);
679     Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
680                       DAG.getConstant(IncrementSize, TLI.getPointerTy()));
681     Hi = DAG.getExtLoad(HiExtType, VT, Chain, Ptr, LD->getSrcValue(),
682                         SVOffset + IncrementSize, NewLoadedVT, LD->isVolatile(),
683                         MinAlign(Alignment, IncrementSize));
684   } else {
685     Hi = DAG.getExtLoad(HiExtType, VT, Chain, Ptr, LD->getSrcValue(), SVOffset,
686                         NewLoadedVT,LD->isVolatile(), Alignment);
687     Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
688                       DAG.getConstant(IncrementSize, TLI.getPointerTy()));
689     Lo = DAG.getExtLoad(ISD::ZEXTLOAD, VT, Chain, Ptr, LD->getSrcValue(),
690                         SVOffset + IncrementSize, NewLoadedVT, LD->isVolatile(),
691                         MinAlign(Alignment, IncrementSize));
692   }
693
694   // aggregate the two parts
695   SDOperand ShiftAmount = DAG.getConstant(NumBits, TLI.getShiftAmountTy());
696   SDOperand Result = DAG.getNode(ISD::SHL, VT, Hi, ShiftAmount);
697   Result = DAG.getNode(ISD::OR, VT, Result, Lo);
698
699   SDOperand TF = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo.getValue(1),
700                              Hi.getValue(1));
701
702   SDOperand Ops[] = { Result, TF };
703   return DAG.getMergeValues(Ops, 2);
704 }
705
706 /// UnrollVectorOp - We know that the given vector has a legal type, however
707 /// the operation it performs is not legal and is an operation that we have
708 /// no way of lowering.  "Unroll" the vector, splitting out the scalars and
709 /// operating on each element individually.
710 SDOperand SelectionDAGLegalize::UnrollVectorOp(SDOperand Op) {
711   MVT VT = Op.getValueType();
712   assert(isTypeLegal(VT) &&
713          "Caller should expand or promote operands that are not legal!");
714   assert(Op.Val->getNumValues() == 1 &&
715          "Can't unroll a vector with multiple results!");
716   unsigned NE = VT.getVectorNumElements();
717   MVT EltVT = VT.getVectorElementType();
718
719   SmallVector<SDOperand, 8> Scalars;
720   SmallVector<SDOperand, 4> Operands(Op.getNumOperands());
721   for (unsigned i = 0; i != NE; ++i) {
722     for (unsigned j = 0; j != Op.getNumOperands(); ++j) {
723       SDOperand Operand = Op.getOperand(j);
724       MVT OperandVT = Operand.getValueType();
725       if (OperandVT.isVector()) {
726         // A vector operand; extract a single element.
727         MVT OperandEltVT = OperandVT.getVectorElementType();
728         Operands[j] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
729                                   OperandEltVT,
730                                   Operand,
731                                   DAG.getConstant(i, MVT::i32));
732       } else {
733         // A scalar operand; just use it as is.
734         Operands[j] = Operand;
735       }
736     }
737     Scalars.push_back(DAG.getNode(Op.getOpcode(), EltVT,
738                                   &Operands[0], Operands.size()));
739   }
740
741   return DAG.getNode(ISD::BUILD_VECTOR, VT, &Scalars[0], Scalars.size());
742 }
743
744 /// GetFPLibCall - Return the right libcall for the given floating point type.
745 static RTLIB::Libcall GetFPLibCall(MVT VT,
746                                    RTLIB::Libcall Call_F32,
747                                    RTLIB::Libcall Call_F64,
748                                    RTLIB::Libcall Call_F80,
749                                    RTLIB::Libcall Call_PPCF128) {
750   return
751     VT == MVT::f32 ? Call_F32 :
752     VT == MVT::f64 ? Call_F64 :
753     VT == MVT::f80 ? Call_F80 :
754     VT == MVT::ppcf128 ? Call_PPCF128 :
755     RTLIB::UNKNOWN_LIBCALL;
756 }
757
758 /// PerformInsertVectorEltInMemory - Some target cannot handle a variable
759 /// insertion index for the INSERT_VECTOR_ELT instruction.  In this case, it
760 /// is necessary to spill the vector being inserted into to memory, perform
761 /// the insert there, and then read the result back.
762 SDOperand SelectionDAGLegalize::
763 PerformInsertVectorEltInMemory(SDOperand Vec, SDOperand Val, SDOperand Idx) {
764   SDOperand Tmp1 = Vec;
765   SDOperand Tmp2 = Val;
766   SDOperand Tmp3 = Idx;
767   
768   // If the target doesn't support this, we have to spill the input vector
769   // to a temporary stack slot, update the element, then reload it.  This is
770   // badness.  We could also load the value into a vector register (either
771   // with a "move to register" or "extload into register" instruction, then
772   // permute it into place, if the idx is a constant and if the idx is
773   // supported by the target.
774   MVT VT    = Tmp1.getValueType();
775   MVT EltVT = VT.getVectorElementType();
776   MVT IdxVT = Tmp3.getValueType();
777   MVT PtrVT = TLI.getPointerTy();
778   SDOperand StackPtr = DAG.CreateStackTemporary(VT);
779
780   FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(StackPtr.Val);
781   int SPFI = StackPtrFI->getIndex();
782
783   // Store the vector.
784   SDOperand Ch = DAG.getStore(DAG.getEntryNode(), Tmp1, StackPtr,
785                               PseudoSourceValue::getFixedStack(),
786                               SPFI);
787
788   // Truncate or zero extend offset to target pointer type.
789   unsigned CastOpc = IdxVT.bitsGT(PtrVT) ? ISD::TRUNCATE : ISD::ZERO_EXTEND;
790   Tmp3 = DAG.getNode(CastOpc, PtrVT, Tmp3);
791   // Add the offset to the index.
792   unsigned EltSize = EltVT.getSizeInBits()/8;
793   Tmp3 = DAG.getNode(ISD::MUL, IdxVT, Tmp3,DAG.getConstant(EltSize, IdxVT));
794   SDOperand StackPtr2 = DAG.getNode(ISD::ADD, IdxVT, Tmp3, StackPtr);
795   // Store the scalar value.
796   Ch = DAG.getTruncStore(Ch, Tmp2, StackPtr2,
797                          PseudoSourceValue::getFixedStack(), SPFI, EltVT);
798   // Load the updated vector.
799   return DAG.getLoad(VT, Ch, StackPtr, PseudoSourceValue::getFixedStack(),SPFI);
800 }
801
802 /// LegalizeOp - We know that the specified value has a legal type, and
803 /// that its operands are legal.  Now ensure that the operation itself
804 /// is legal, recursively ensuring that the operands' operations remain
805 /// legal.
806 SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
807   if (Op.getOpcode() == ISD::TargetConstant) // Allow illegal target nodes.
808     return Op;
809   
810   assert(isTypeLegal(Op.getValueType()) &&
811          "Caller should expand or promote operands that are not legal!");
812   SDNode *Node = Op.Val;
813
814   // If this operation defines any values that cannot be represented in a
815   // register on this target, make sure to expand or promote them.
816   if (Node->getNumValues() > 1) {
817     for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
818       if (getTypeAction(Node->getValueType(i)) != Legal) {
819         HandleOp(Op.getValue(i));
820         assert(LegalizedNodes.count(Op) &&
821                "Handling didn't add legal operands!");
822         return LegalizedNodes[Op];
823       }
824   }
825
826   // Note that LegalizeOp may be reentered even from single-use nodes, which
827   // means that we always must cache transformed nodes.
828   DenseMap<SDOperand, SDOperand>::iterator I = LegalizedNodes.find(Op);
829   if (I != LegalizedNodes.end()) return I->second;
830
831   SDOperand Tmp1, Tmp2, Tmp3, Tmp4;
832   SDOperand Result = Op;
833   bool isCustom = false;
834   
835   switch (Node->getOpcode()) {
836   case ISD::FrameIndex:
837   case ISD::EntryToken:
838   case ISD::Register:
839   case ISD::BasicBlock:
840   case ISD::TargetFrameIndex:
841   case ISD::TargetJumpTable:
842   case ISD::TargetConstant:
843   case ISD::TargetConstantFP:
844   case ISD::TargetConstantPool:
845   case ISD::TargetGlobalAddress:
846   case ISD::TargetGlobalTLSAddress:
847   case ISD::TargetExternalSymbol:
848   case ISD::VALUETYPE:
849   case ISD::SRCVALUE:
850   case ISD::MEMOPERAND:
851   case ISD::CONDCODE:
852   case ISD::ARG_FLAGS:
853     // Primitives must all be legal.
854     assert(TLI.isOperationLegal(Node->getOpcode(), Node->getValueType(0)) &&
855            "This must be legal!");
856     break;
857   default:
858     if (Node->getOpcode() >= ISD::BUILTIN_OP_END) {
859       // If this is a target node, legalize it by legalizing the operands then
860       // passing it through.
861       SmallVector<SDOperand, 8> Ops;
862       for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
863         Ops.push_back(LegalizeOp(Node->getOperand(i)));
864
865       Result = DAG.UpdateNodeOperands(Result.getValue(0), &Ops[0], Ops.size());
866
867       for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
868         AddLegalizedOperand(Op.getValue(i), Result.getValue(i));
869       return Result.getValue(Op.ResNo);
870     }
871     // Otherwise this is an unhandled builtin node.  splat.
872 #ifndef NDEBUG
873     cerr << "NODE: "; Node->dump(&DAG); cerr << "\n";
874 #endif
875     assert(0 && "Do not know how to legalize this operator!");
876     abort();
877   case ISD::GLOBAL_OFFSET_TABLE:
878   case ISD::GlobalAddress:
879   case ISD::GlobalTLSAddress:
880   case ISD::ExternalSymbol:
881   case ISD::ConstantPool:
882   case ISD::JumpTable: // Nothing to do.
883     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
884     default: assert(0 && "This action is not supported yet!");
885     case TargetLowering::Custom:
886       Tmp1 = TLI.LowerOperation(Op, DAG);
887       if (Tmp1.Val) Result = Tmp1;
888       // FALLTHROUGH if the target doesn't want to lower this op after all.
889     case TargetLowering::Legal:
890       break;
891     }
892     break;
893   case ISD::FRAMEADDR:
894   case ISD::RETURNADDR:
895     // The only option for these nodes is to custom lower them.  If the target
896     // does not custom lower them, then return zero.
897     Tmp1 = TLI.LowerOperation(Op, DAG);
898     if (Tmp1.Val) 
899       Result = Tmp1;
900     else
901       Result = DAG.getConstant(0, TLI.getPointerTy());
902     break;
903   case ISD::FRAME_TO_ARGS_OFFSET: {
904     MVT VT = Node->getValueType(0);
905     switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
906     default: assert(0 && "This action is not supported yet!");
907     case TargetLowering::Custom:
908       Result = TLI.LowerOperation(Op, DAG);
909       if (Result.Val) break;
910       // Fall Thru
911     case TargetLowering::Legal:
912       Result = DAG.getConstant(0, VT);
913       break;
914     }
915     }
916     break;
917   case ISD::EXCEPTIONADDR: {
918     Tmp1 = LegalizeOp(Node->getOperand(0));
919     MVT VT = Node->getValueType(0);
920     switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
921     default: assert(0 && "This action is not supported yet!");
922     case TargetLowering::Expand: {
923         unsigned Reg = TLI.getExceptionAddressRegister();
924         Result = DAG.getCopyFromReg(Tmp1, Reg, VT);
925       }
926       break;
927     case TargetLowering::Custom:
928       Result = TLI.LowerOperation(Op, DAG);
929       if (Result.Val) break;
930       // Fall Thru
931     case TargetLowering::Legal: {
932       SDOperand Ops[] = { DAG.getConstant(0, VT), Tmp1 };
933       Result = DAG.getMergeValues(Ops, 2);
934       break;
935     }
936     }
937     }
938     if (Result.Val->getNumValues() == 1) break;
939
940     assert(Result.Val->getNumValues() == 2 &&
941            "Cannot return more than two values!");
942
943     // Since we produced two values, make sure to remember that we
944     // legalized both of them.
945     Tmp1 = LegalizeOp(Result);
946     Tmp2 = LegalizeOp(Result.getValue(1));
947     AddLegalizedOperand(Op.getValue(0), Tmp1);
948     AddLegalizedOperand(Op.getValue(1), Tmp2);
949     return Op.ResNo ? Tmp2 : Tmp1;
950   case ISD::EHSELECTION: {
951     Tmp1 = LegalizeOp(Node->getOperand(0));
952     Tmp2 = LegalizeOp(Node->getOperand(1));
953     MVT VT = Node->getValueType(0);
954     switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
955     default: assert(0 && "This action is not supported yet!");
956     case TargetLowering::Expand: {
957         unsigned Reg = TLI.getExceptionSelectorRegister();
958         Result = DAG.getCopyFromReg(Tmp2, Reg, VT);
959       }
960       break;
961     case TargetLowering::Custom:
962       Result = TLI.LowerOperation(Op, DAG);
963       if (Result.Val) break;
964       // Fall Thru
965     case TargetLowering::Legal: {
966       SDOperand Ops[] = { DAG.getConstant(0, VT), Tmp2 };
967       Result = DAG.getMergeValues(Ops, 2);
968       break;
969     }
970     }
971     }
972     if (Result.Val->getNumValues() == 1) break;
973
974     assert(Result.Val->getNumValues() == 2 &&
975            "Cannot return more than two values!");
976
977     // Since we produced two values, make sure to remember that we
978     // legalized both of them.
979     Tmp1 = LegalizeOp(Result);
980     Tmp2 = LegalizeOp(Result.getValue(1));
981     AddLegalizedOperand(Op.getValue(0), Tmp1);
982     AddLegalizedOperand(Op.getValue(1), Tmp2);
983     return Op.ResNo ? Tmp2 : Tmp1;
984   case ISD::EH_RETURN: {
985     MVT VT = Node->getValueType(0);
986     // The only "good" option for this node is to custom lower it.
987     switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
988     default: assert(0 && "This action is not supported at all!");
989     case TargetLowering::Custom:
990       Result = TLI.LowerOperation(Op, DAG);
991       if (Result.Val) break;
992       // Fall Thru
993     case TargetLowering::Legal:
994       // Target does not know, how to lower this, lower to noop
995       Result = LegalizeOp(Node->getOperand(0));
996       break;
997     }
998     }
999     break;
1000   case ISD::AssertSext:
1001   case ISD::AssertZext:
1002     Tmp1 = LegalizeOp(Node->getOperand(0));
1003     Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
1004     break;
1005   case ISD::MERGE_VALUES:
1006     // Legalize eliminates MERGE_VALUES nodes.
1007     Result = Node->getOperand(Op.ResNo);
1008     break;
1009   case ISD::CopyFromReg:
1010     Tmp1 = LegalizeOp(Node->getOperand(0));
1011     Result = Op.getValue(0);
1012     if (Node->getNumValues() == 2) {
1013       Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
1014     } else {
1015       assert(Node->getNumValues() == 3 && "Invalid copyfromreg!");
1016       if (Node->getNumOperands() == 3) {
1017         Tmp2 = LegalizeOp(Node->getOperand(2));
1018         Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1),Tmp2);
1019       } else {
1020         Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
1021       }
1022       AddLegalizedOperand(Op.getValue(2), Result.getValue(2));
1023     }
1024     // Since CopyFromReg produces two values, make sure to remember that we
1025     // legalized both of them.
1026     AddLegalizedOperand(Op.getValue(0), Result);
1027     AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
1028     return Result.getValue(Op.ResNo);
1029   case ISD::UNDEF: {
1030     MVT VT = Op.getValueType();
1031     switch (TLI.getOperationAction(ISD::UNDEF, VT)) {
1032     default: assert(0 && "This action is not supported yet!");
1033     case TargetLowering::Expand:
1034       if (VT.isInteger())
1035         Result = DAG.getConstant(0, VT);
1036       else if (VT.isFloatingPoint())
1037         Result = DAG.getConstantFP(APFloat(APInt(VT.getSizeInBits(), 0)),
1038                                    VT);
1039       else
1040         assert(0 && "Unknown value type!");
1041       break;
1042     case TargetLowering::Legal:
1043       break;
1044     }
1045     break;
1046   }
1047     
1048   case ISD::INTRINSIC_W_CHAIN:
1049   case ISD::INTRINSIC_WO_CHAIN:
1050   case ISD::INTRINSIC_VOID: {
1051     SmallVector<SDOperand, 8> Ops;
1052     for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
1053       Ops.push_back(LegalizeOp(Node->getOperand(i)));
1054     Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
1055     
1056     // Allow the target to custom lower its intrinsics if it wants to.
1057     if (TLI.getOperationAction(Node->getOpcode(), MVT::Other) == 
1058         TargetLowering::Custom) {
1059       Tmp3 = TLI.LowerOperation(Result, DAG);
1060       if (Tmp3.Val) Result = Tmp3;
1061     }
1062
1063     if (Result.Val->getNumValues() == 1) break;
1064
1065     // Must have return value and chain result.
1066     assert(Result.Val->getNumValues() == 2 &&
1067            "Cannot return more than two values!");
1068
1069     // Since loads produce two values, make sure to remember that we 
1070     // legalized both of them.
1071     AddLegalizedOperand(SDOperand(Node, 0), Result.getValue(0));
1072     AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
1073     return Result.getValue(Op.ResNo);
1074   }    
1075
1076   case ISD::DBG_STOPPOINT:
1077     assert(Node->getNumOperands() == 1 && "Invalid DBG_STOPPOINT node!");
1078     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the input chain.
1079     
1080     switch (TLI.getOperationAction(ISD::DBG_STOPPOINT, MVT::Other)) {
1081     case TargetLowering::Promote:
1082     default: assert(0 && "This action is not supported yet!");
1083     case TargetLowering::Expand: {
1084       MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
1085       bool useDEBUG_LOC = TLI.isOperationLegal(ISD::DEBUG_LOC, MVT::Other);
1086       bool useLABEL = TLI.isOperationLegal(ISD::DBG_LABEL, MVT::Other);
1087       
1088       const DbgStopPointSDNode *DSP = cast<DbgStopPointSDNode>(Node);
1089       if (MMI && (useDEBUG_LOC || useLABEL)) {
1090         const CompileUnitDesc *CompileUnit = DSP->getCompileUnit();
1091         unsigned SrcFile = MMI->RecordSource(CompileUnit);
1092
1093         unsigned Line = DSP->getLine();
1094         unsigned Col = DSP->getColumn();
1095         
1096         if (useDEBUG_LOC) {
1097           SmallVector<SDOperand, 8> Ops;
1098           Ops.push_back(Tmp1);  // chain
1099           Ops.push_back(DAG.getConstant(Line, MVT::i32));  // line #
1100           Ops.push_back(DAG.getConstant(Col, MVT::i32));   // col #
1101           Ops.push_back(DAG.getConstant(SrcFile, MVT::i32));  // source file id
1102           Result = DAG.getNode(ISD::DEBUG_LOC, MVT::Other, &Ops[0], Ops.size());
1103         } else {
1104           unsigned ID = MMI->RecordSourceLine(Line, Col, SrcFile);
1105           Result = DAG.getLabel(ISD::DBG_LABEL, Tmp1, ID);
1106         }
1107       } else {
1108         Result = Tmp1;  // chain
1109       }
1110       break;
1111     }
1112     case TargetLowering::Legal:
1113       if (Tmp1 != Node->getOperand(0) ||
1114           getTypeAction(Node->getOperand(1).getValueType()) == Promote) {
1115         SmallVector<SDOperand, 8> Ops;
1116         Ops.push_back(Tmp1);
1117         if (getTypeAction(Node->getOperand(1).getValueType()) == Legal) {
1118           Ops.push_back(Node->getOperand(1));  // line # must be legal.
1119           Ops.push_back(Node->getOperand(2));  // col # must be legal.
1120         } else {
1121           // Otherwise promote them.
1122           Ops.push_back(PromoteOp(Node->getOperand(1)));
1123           Ops.push_back(PromoteOp(Node->getOperand(2)));
1124         }
1125         Ops.push_back(Node->getOperand(3));  // filename must be legal.
1126         Ops.push_back(Node->getOperand(4));  // working dir # must be legal.
1127         Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
1128       }
1129       break;
1130     }
1131     break;
1132
1133   case ISD::DECLARE:
1134     assert(Node->getNumOperands() == 3 && "Invalid DECLARE node!");
1135     switch (TLI.getOperationAction(ISD::DECLARE, MVT::Other)) {
1136     default: assert(0 && "This action is not supported yet!");
1137     case TargetLowering::Legal:
1138       Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1139       Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the address.
1140       Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the variable.
1141       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
1142       break;
1143     case TargetLowering::Expand:
1144       Result = LegalizeOp(Node->getOperand(0));
1145       break;
1146     }
1147     break;    
1148     
1149   case ISD::DEBUG_LOC:
1150     assert(Node->getNumOperands() == 4 && "Invalid DEBUG_LOC node!");
1151     switch (TLI.getOperationAction(ISD::DEBUG_LOC, MVT::Other)) {
1152     default: assert(0 && "This action is not supported yet!");
1153     case TargetLowering::Legal:
1154       Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1155       Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the line #.
1156       Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the col #.
1157       Tmp4 = LegalizeOp(Node->getOperand(3));  // Legalize the source file id.
1158       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3, Tmp4);
1159       break;
1160     }
1161     break;    
1162
1163   case ISD::DBG_LABEL:
1164   case ISD::EH_LABEL:
1165     assert(Node->getNumOperands() == 1 && "Invalid LABEL node!");
1166     switch (TLI.getOperationAction(Node->getOpcode(), MVT::Other)) {
1167     default: assert(0 && "This action is not supported yet!");
1168     case TargetLowering::Legal:
1169       Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1170       Result = DAG.UpdateNodeOperands(Result, Tmp1);
1171       break;
1172     case TargetLowering::Expand:
1173       Result = LegalizeOp(Node->getOperand(0));
1174       break;
1175     }
1176     break;
1177
1178   case ISD::PREFETCH:
1179     assert(Node->getNumOperands() == 4 && "Invalid Prefetch node!");
1180     switch (TLI.getOperationAction(ISD::PREFETCH, MVT::Other)) {
1181     default: assert(0 && "This action is not supported yet!");
1182     case TargetLowering::Legal:
1183       Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1184       Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the address.
1185       Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the rw specifier.
1186       Tmp4 = LegalizeOp(Node->getOperand(3));  // Legalize locality specifier.
1187       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3, Tmp4);
1188       break;
1189     case TargetLowering::Expand:
1190       // It's a noop.
1191       Result = LegalizeOp(Node->getOperand(0));
1192       break;
1193     }
1194     break;
1195
1196   case ISD::MEMBARRIER: {
1197     assert(Node->getNumOperands() == 6 && "Invalid MemBarrier node!");
1198     switch (TLI.getOperationAction(ISD::MEMBARRIER, MVT::Other)) {
1199     default: assert(0 && "This action is not supported yet!");
1200     case TargetLowering::Legal: {
1201       SDOperand Ops[6];
1202       Ops[0] = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1203       for (int x = 1; x < 6; ++x) {
1204         Ops[x] = Node->getOperand(x);
1205         if (!isTypeLegal(Ops[x].getValueType()))
1206           Ops[x] = PromoteOp(Ops[x]);
1207       }
1208       Result = DAG.UpdateNodeOperands(Result, &Ops[0], 6);
1209       break;
1210     }
1211     case TargetLowering::Expand:
1212       //There is no libgcc call for this op
1213       Result = Node->getOperand(0);  // Noop
1214     break;
1215     }
1216     break;
1217   }
1218
1219   case ISD::ATOMIC_CMP_SWAP: {
1220     unsigned int num_operands = 4;
1221     assert(Node->getNumOperands() == num_operands && "Invalid Atomic node!");
1222     SDOperand Ops[4];
1223     for (unsigned int x = 0; x < num_operands; ++x)
1224       Ops[x] = LegalizeOp(Node->getOperand(x));
1225     Result = DAG.UpdateNodeOperands(Result, &Ops[0], num_operands);
1226     
1227     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
1228       default: assert(0 && "This action is not supported yet!");
1229       case TargetLowering::Custom:
1230         Result = TLI.LowerOperation(Result, DAG);
1231         break;
1232       case TargetLowering::Legal:
1233         break;
1234     }
1235     AddLegalizedOperand(SDOperand(Node, 0), Result.getValue(0));
1236     AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
1237     return Result.getValue(Op.ResNo);
1238   }
1239   case ISD::ATOMIC_LOAD_ADD:
1240   case ISD::ATOMIC_LOAD_SUB:
1241   case ISD::ATOMIC_LOAD_AND:
1242   case ISD::ATOMIC_LOAD_OR:
1243   case ISD::ATOMIC_LOAD_XOR:
1244   case ISD::ATOMIC_LOAD_NAND:
1245   case ISD::ATOMIC_LOAD_MIN:
1246   case ISD::ATOMIC_LOAD_MAX:
1247   case ISD::ATOMIC_LOAD_UMIN:
1248   case ISD::ATOMIC_LOAD_UMAX:
1249   case ISD::ATOMIC_SWAP: {
1250     unsigned int num_operands = 3;
1251     assert(Node->getNumOperands() == num_operands && "Invalid Atomic node!");
1252     SDOperand Ops[3];
1253     for (unsigned int x = 0; x < num_operands; ++x)
1254       Ops[x] = LegalizeOp(Node->getOperand(x));
1255     Result = DAG.UpdateNodeOperands(Result, &Ops[0], num_operands);
1256
1257     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
1258     default: assert(0 && "This action is not supported yet!");
1259     case TargetLowering::Custom:
1260       Result = TLI.LowerOperation(Result, DAG);
1261       break;
1262     case TargetLowering::Expand:
1263       Result = SDOperand(TLI.ReplaceNodeResults(Op.Val, DAG),0);
1264       break;
1265     case TargetLowering::Legal:
1266       break;
1267     }
1268     AddLegalizedOperand(SDOperand(Node, 0), Result.getValue(0));
1269     AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
1270     return Result.getValue(Op.ResNo);
1271   }
1272   case ISD::Constant: {
1273     ConstantSDNode *CN = cast<ConstantSDNode>(Node);
1274     unsigned opAction =
1275       TLI.getOperationAction(ISD::Constant, CN->getValueType(0));
1276
1277     // We know we don't need to expand constants here, constants only have one
1278     // value and we check that it is fine above.
1279
1280     if (opAction == TargetLowering::Custom) {
1281       Tmp1 = TLI.LowerOperation(Result, DAG);
1282       if (Tmp1.Val)
1283         Result = Tmp1;
1284     }
1285     break;
1286   }
1287   case ISD::ConstantFP: {
1288     // Spill FP immediates to the constant pool if the target cannot directly
1289     // codegen them.  Targets often have some immediate values that can be
1290     // efficiently generated into an FP register without a load.  We explicitly
1291     // leave these constants as ConstantFP nodes for the target to deal with.
1292     ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Node);
1293
1294     switch (TLI.getOperationAction(ISD::ConstantFP, CFP->getValueType(0))) {
1295     default: assert(0 && "This action is not supported yet!");
1296     case TargetLowering::Legal:
1297       break;
1298     case TargetLowering::Custom:
1299       Tmp3 = TLI.LowerOperation(Result, DAG);
1300       if (Tmp3.Val) {
1301         Result = Tmp3;
1302         break;
1303       }
1304       // FALLTHROUGH
1305     case TargetLowering::Expand: {
1306       // Check to see if this FP immediate is already legal.
1307       bool isLegal = false;
1308       for (TargetLowering::legal_fpimm_iterator I = TLI.legal_fpimm_begin(),
1309              E = TLI.legal_fpimm_end(); I != E; ++I) {
1310         if (CFP->isExactlyValue(*I)) {
1311           isLegal = true;
1312           break;
1313         }
1314       }
1315       // If this is a legal constant, turn it into a TargetConstantFP node.
1316       if (isLegal)
1317         break;
1318       Result = ExpandConstantFP(CFP, true, DAG, TLI);
1319     }
1320     }
1321     break;
1322   }
1323   case ISD::TokenFactor:
1324     if (Node->getNumOperands() == 2) {
1325       Tmp1 = LegalizeOp(Node->getOperand(0));
1326       Tmp2 = LegalizeOp(Node->getOperand(1));
1327       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
1328     } else if (Node->getNumOperands() == 3) {
1329       Tmp1 = LegalizeOp(Node->getOperand(0));
1330       Tmp2 = LegalizeOp(Node->getOperand(1));
1331       Tmp3 = LegalizeOp(Node->getOperand(2));
1332       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
1333     } else {
1334       SmallVector<SDOperand, 8> Ops;
1335       // Legalize the operands.
1336       for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
1337         Ops.push_back(LegalizeOp(Node->getOperand(i)));
1338       Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
1339     }
1340     break;
1341     
1342   case ISD::FORMAL_ARGUMENTS:
1343   case ISD::CALL:
1344     // The only option for this is to custom lower it.
1345     Tmp3 = TLI.LowerOperation(Result.getValue(0), DAG);
1346     assert(Tmp3.Val && "Target didn't custom lower this node!");
1347     // A call within a calling sequence must be legalized to something
1348     // other than the normal CALLSEQ_END.  Violating this gets Legalize
1349     // into an infinite loop.
1350     assert ((!IsLegalizingCall ||
1351              Node->getOpcode() != ISD::CALL ||
1352              Tmp3.Val->getOpcode() != ISD::CALLSEQ_END) &&
1353             "Nested CALLSEQ_START..CALLSEQ_END not supported.");
1354
1355     // The number of incoming and outgoing values should match; unless the final
1356     // outgoing value is a flag.
1357     assert((Tmp3.Val->getNumValues() == Result.Val->getNumValues() ||
1358             (Tmp3.Val->getNumValues() == Result.Val->getNumValues() + 1 &&
1359              Tmp3.Val->getValueType(Tmp3.Val->getNumValues() - 1) ==
1360                MVT::Flag)) &&
1361            "Lowering call/formal_arguments produced unexpected # results!");
1362     
1363     // Since CALL/FORMAL_ARGUMENTS nodes produce multiple values, make sure to
1364     // remember that we legalized all of them, so it doesn't get relegalized.
1365     for (unsigned i = 0, e = Tmp3.Val->getNumValues(); i != e; ++i) {
1366       if (Tmp3.Val->getValueType(i) == MVT::Flag)
1367         continue;
1368       Tmp1 = LegalizeOp(Tmp3.getValue(i));
1369       if (Op.ResNo == i)
1370         Tmp2 = Tmp1;
1371       AddLegalizedOperand(SDOperand(Node, i), Tmp1);
1372     }
1373     return Tmp2;
1374    case ISD::EXTRACT_SUBREG: {
1375       Tmp1 = LegalizeOp(Node->getOperand(0));
1376       ConstantSDNode *idx = dyn_cast<ConstantSDNode>(Node->getOperand(1));
1377       assert(idx && "Operand must be a constant");
1378       Tmp2 = DAG.getTargetConstant(idx->getValue(), idx->getValueType(0));
1379       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
1380     }
1381     break;
1382   case ISD::INSERT_SUBREG: {
1383       Tmp1 = LegalizeOp(Node->getOperand(0));
1384       Tmp2 = LegalizeOp(Node->getOperand(1));      
1385       ConstantSDNode *idx = dyn_cast<ConstantSDNode>(Node->getOperand(2));
1386       assert(idx && "Operand must be a constant");
1387       Tmp3 = DAG.getTargetConstant(idx->getValue(), idx->getValueType(0));
1388       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
1389     }
1390     break;      
1391   case ISD::BUILD_VECTOR:
1392     switch (TLI.getOperationAction(ISD::BUILD_VECTOR, Node->getValueType(0))) {
1393     default: assert(0 && "This action is not supported yet!");
1394     case TargetLowering::Custom:
1395       Tmp3 = TLI.LowerOperation(Result, DAG);
1396       if (Tmp3.Val) {
1397         Result = Tmp3;
1398         break;
1399       }
1400       // FALLTHROUGH
1401     case TargetLowering::Expand:
1402       Result = ExpandBUILD_VECTOR(Result.Val);
1403       break;
1404     }
1405     break;
1406   case ISD::INSERT_VECTOR_ELT:
1407     Tmp1 = LegalizeOp(Node->getOperand(0));  // InVec
1408     Tmp3 = LegalizeOp(Node->getOperand(2));  // InEltNo
1409
1410     // The type of the value to insert may not be legal, even though the vector
1411     // type is legal.  Legalize/Promote accordingly.  We do not handle Expand
1412     // here.
1413     switch (getTypeAction(Node->getOperand(1).getValueType())) {
1414     default: assert(0 && "Cannot expand insert element operand");
1415     case Legal:   Tmp2 = LegalizeOp(Node->getOperand(1)); break;
1416     case Promote: Tmp2 = PromoteOp(Node->getOperand(1));  break;
1417     }
1418     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
1419     
1420     switch (TLI.getOperationAction(ISD::INSERT_VECTOR_ELT,
1421                                    Node->getValueType(0))) {
1422     default: assert(0 && "This action is not supported yet!");
1423     case TargetLowering::Legal:
1424       break;
1425     case TargetLowering::Custom:
1426       Tmp4 = TLI.LowerOperation(Result, DAG);
1427       if (Tmp4.Val) {
1428         Result = Tmp4;
1429         break;
1430       }
1431       // FALLTHROUGH
1432     case TargetLowering::Expand: {
1433       // If the insert index is a constant, codegen this as a scalar_to_vector,
1434       // then a shuffle that inserts it into the right position in the vector.
1435       if (ConstantSDNode *InsertPos = dyn_cast<ConstantSDNode>(Tmp3)) {
1436         // SCALAR_TO_VECTOR requires that the type of the value being inserted
1437         // match the element type of the vector being created.
1438         if (Tmp2.getValueType() == 
1439             Op.getValueType().getVectorElementType()) {
1440           SDOperand ScVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, 
1441                                         Tmp1.getValueType(), Tmp2);
1442           
1443           unsigned NumElts = Tmp1.getValueType().getVectorNumElements();
1444           MVT ShufMaskVT =
1445             MVT::getIntVectorWithNumElements(NumElts);
1446           MVT ShufMaskEltVT = ShufMaskVT.getVectorElementType();
1447           
1448           // We generate a shuffle of InVec and ScVec, so the shuffle mask
1449           // should be 0,1,2,3,4,5... with the appropriate element replaced with
1450           // elt 0 of the RHS.
1451           SmallVector<SDOperand, 8> ShufOps;
1452           for (unsigned i = 0; i != NumElts; ++i) {
1453             if (i != InsertPos->getValue())
1454               ShufOps.push_back(DAG.getConstant(i, ShufMaskEltVT));
1455             else
1456               ShufOps.push_back(DAG.getConstant(NumElts, ShufMaskEltVT));
1457           }
1458           SDOperand ShufMask = DAG.getNode(ISD::BUILD_VECTOR, ShufMaskVT,
1459                                            &ShufOps[0], ShufOps.size());
1460           
1461           Result = DAG.getNode(ISD::VECTOR_SHUFFLE, Tmp1.getValueType(),
1462                                Tmp1, ScVec, ShufMask);
1463           Result = LegalizeOp(Result);
1464           break;
1465         }
1466       }
1467       Result = PerformInsertVectorEltInMemory(Tmp1, Tmp2, Tmp3);
1468       break;
1469     }
1470     }
1471     break;
1472   case ISD::SCALAR_TO_VECTOR:
1473     if (!TLI.isTypeLegal(Node->getOperand(0).getValueType())) {
1474       Result = LegalizeOp(ExpandSCALAR_TO_VECTOR(Node));
1475       break;
1476     }
1477     
1478     Tmp1 = LegalizeOp(Node->getOperand(0));  // InVal
1479     Result = DAG.UpdateNodeOperands(Result, Tmp1);
1480     switch (TLI.getOperationAction(ISD::SCALAR_TO_VECTOR,
1481                                    Node->getValueType(0))) {
1482     default: assert(0 && "This action is not supported yet!");
1483     case TargetLowering::Legal:
1484       break;
1485     case TargetLowering::Custom:
1486       Tmp3 = TLI.LowerOperation(Result, DAG);
1487       if (Tmp3.Val) {
1488         Result = Tmp3;
1489         break;
1490       }
1491       // FALLTHROUGH
1492     case TargetLowering::Expand:
1493       Result = LegalizeOp(ExpandSCALAR_TO_VECTOR(Node));
1494       break;
1495     }
1496     break;
1497   case ISD::VECTOR_SHUFFLE:
1498     Tmp1 = LegalizeOp(Node->getOperand(0));   // Legalize the input vectors,
1499     Tmp2 = LegalizeOp(Node->getOperand(1));   // but not the shuffle mask.
1500     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
1501
1502     // Allow targets to custom lower the SHUFFLEs they support.
1503     switch (TLI.getOperationAction(ISD::VECTOR_SHUFFLE,Result.getValueType())) {
1504     default: assert(0 && "Unknown operation action!");
1505     case TargetLowering::Legal:
1506       assert(isShuffleLegal(Result.getValueType(), Node->getOperand(2)) &&
1507              "vector shuffle should not be created if not legal!");
1508       break;
1509     case TargetLowering::Custom:
1510       Tmp3 = TLI.LowerOperation(Result, DAG);
1511       if (Tmp3.Val) {
1512         Result = Tmp3;
1513         break;
1514       }
1515       // FALLTHROUGH
1516     case TargetLowering::Expand: {
1517       MVT VT = Node->getValueType(0);
1518       MVT EltVT = VT.getVectorElementType();
1519       MVT PtrVT = TLI.getPointerTy();
1520       SDOperand Mask = Node->getOperand(2);
1521       unsigned NumElems = Mask.getNumOperands();
1522       SmallVector<SDOperand,8> Ops;
1523       for (unsigned i = 0; i != NumElems; ++i) {
1524         SDOperand Arg = Mask.getOperand(i);
1525         if (Arg.getOpcode() == ISD::UNDEF) {
1526           Ops.push_back(DAG.getNode(ISD::UNDEF, EltVT));
1527         } else {
1528           assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1529           unsigned Idx = cast<ConstantSDNode>(Arg)->getValue();
1530           if (Idx < NumElems)
1531             Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, EltVT, Tmp1,
1532                                       DAG.getConstant(Idx, PtrVT)));
1533           else
1534             Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, EltVT, Tmp2,
1535                                       DAG.getConstant(Idx - NumElems, PtrVT)));
1536         }
1537       }
1538       Result = DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
1539       break;
1540     }
1541     case TargetLowering::Promote: {
1542       // Change base type to a different vector type.
1543       MVT OVT = Node->getValueType(0);
1544       MVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
1545
1546       // Cast the two input vectors.
1547       Tmp1 = DAG.getNode(ISD::BIT_CONVERT, NVT, Tmp1);
1548       Tmp2 = DAG.getNode(ISD::BIT_CONVERT, NVT, Tmp2);
1549       
1550       // Convert the shuffle mask to the right # elements.
1551       Tmp3 = SDOperand(isShuffleLegal(OVT, Node->getOperand(2)), 0);
1552       assert(Tmp3.Val && "Shuffle not legal?");
1553       Result = DAG.getNode(ISD::VECTOR_SHUFFLE, NVT, Tmp1, Tmp2, Tmp3);
1554       Result = DAG.getNode(ISD::BIT_CONVERT, OVT, Result);
1555       break;
1556     }
1557     }
1558     break;
1559   
1560   case ISD::EXTRACT_VECTOR_ELT:
1561     Tmp1 = Node->getOperand(0);
1562     Tmp2 = LegalizeOp(Node->getOperand(1));
1563     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
1564     Result = ExpandEXTRACT_VECTOR_ELT(Result);
1565     break;
1566
1567   case ISD::EXTRACT_SUBVECTOR: 
1568     Tmp1 = Node->getOperand(0);
1569     Tmp2 = LegalizeOp(Node->getOperand(1));
1570     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
1571     Result = ExpandEXTRACT_SUBVECTOR(Result);
1572     break;
1573     
1574   case ISD::CALLSEQ_START: {
1575     SDNode *CallEnd = FindCallEndFromCallStart(Node);
1576     
1577     // Recursively Legalize all of the inputs of the call end that do not lead
1578     // to this call start.  This ensures that any libcalls that need be inserted
1579     // are inserted *before* the CALLSEQ_START.
1580     {SmallPtrSet<SDNode*, 32> NodesLeadingTo;
1581     for (unsigned i = 0, e = CallEnd->getNumOperands(); i != e; ++i)
1582       LegalizeAllNodesNotLeadingTo(CallEnd->getOperand(i).Val, Node,
1583                                    NodesLeadingTo);
1584     }
1585
1586     // Now that we legalized all of the inputs (which may have inserted
1587     // libcalls) create the new CALLSEQ_START node.
1588     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1589
1590     // Merge in the last call, to ensure that this call start after the last
1591     // call ended.
1592     if (LastCALLSEQ_END.getOpcode() != ISD::EntryToken) {
1593       Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
1594       Tmp1 = LegalizeOp(Tmp1);
1595     }
1596       
1597     // Do not try to legalize the target-specific arguments (#1+).
1598     if (Tmp1 != Node->getOperand(0)) {
1599       SmallVector<SDOperand, 8> Ops(Node->op_begin(), Node->op_end());
1600       Ops[0] = Tmp1;
1601       Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
1602     }
1603     
1604     // Remember that the CALLSEQ_START is legalized.
1605     AddLegalizedOperand(Op.getValue(0), Result);
1606     if (Node->getNumValues() == 2)    // If this has a flag result, remember it.
1607       AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
1608     
1609     // Now that the callseq_start and all of the non-call nodes above this call
1610     // sequence have been legalized, legalize the call itself.  During this 
1611     // process, no libcalls can/will be inserted, guaranteeing that no calls
1612     // can overlap.
1613     assert(!IsLegalizingCall && "Inconsistent sequentialization of calls!");
1614     // Note that we are selecting this call!
1615     LastCALLSEQ_END = SDOperand(CallEnd, 0);
1616     IsLegalizingCall = true;
1617     
1618     // Legalize the call, starting from the CALLSEQ_END.
1619     LegalizeOp(LastCALLSEQ_END);
1620     assert(!IsLegalizingCall && "CALLSEQ_END should have cleared this!");
1621     return Result;
1622   }
1623   case ISD::CALLSEQ_END:
1624     // If the CALLSEQ_START node hasn't been legalized first, legalize it.  This
1625     // will cause this node to be legalized as well as handling libcalls right.
1626     if (LastCALLSEQ_END.Val != Node) {
1627       LegalizeOp(SDOperand(FindCallStartFromCallEnd(Node), 0));
1628       DenseMap<SDOperand, SDOperand>::iterator I = LegalizedNodes.find(Op);
1629       assert(I != LegalizedNodes.end() &&
1630              "Legalizing the call start should have legalized this node!");
1631       return I->second;
1632     }
1633     
1634     // Otherwise, the call start has been legalized and everything is going 
1635     // according to plan.  Just legalize ourselves normally here.
1636     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1637     // Do not try to legalize the target-specific arguments (#1+), except for
1638     // an optional flag input.
1639     if (Node->getOperand(Node->getNumOperands()-1).getValueType() != MVT::Flag){
1640       if (Tmp1 != Node->getOperand(0)) {
1641         SmallVector<SDOperand, 8> Ops(Node->op_begin(), Node->op_end());
1642         Ops[0] = Tmp1;
1643         Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
1644       }
1645     } else {
1646       Tmp2 = LegalizeOp(Node->getOperand(Node->getNumOperands()-1));
1647       if (Tmp1 != Node->getOperand(0) ||
1648           Tmp2 != Node->getOperand(Node->getNumOperands()-1)) {
1649         SmallVector<SDOperand, 8> Ops(Node->op_begin(), Node->op_end());
1650         Ops[0] = Tmp1;
1651         Ops.back() = Tmp2;
1652         Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
1653       }
1654     }
1655     assert(IsLegalizingCall && "Call sequence imbalance between start/end?");
1656     // This finishes up call legalization.
1657     IsLegalizingCall = false;
1658     
1659     // If the CALLSEQ_END node has a flag, remember that we legalized it.
1660     AddLegalizedOperand(SDOperand(Node, 0), Result.getValue(0));
1661     if (Node->getNumValues() == 2)
1662       AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
1663     return Result.getValue(Op.ResNo);
1664   case ISD::DYNAMIC_STACKALLOC: {
1665     MVT VT = Node->getValueType(0);
1666     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1667     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the size.
1668     Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the alignment.
1669     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
1670
1671     Tmp1 = Result.getValue(0);
1672     Tmp2 = Result.getValue(1);
1673     switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
1674     default: assert(0 && "This action is not supported yet!");
1675     case TargetLowering::Expand: {
1676       unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
1677       assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
1678              " not tell us which reg is the stack pointer!");
1679       SDOperand Chain = Tmp1.getOperand(0);
1680
1681       // Chain the dynamic stack allocation so that it doesn't modify the stack
1682       // pointer when other instructions are using the stack.
1683       Chain = DAG.getCALLSEQ_START(Chain,
1684                                    DAG.getConstant(0, TLI.getPointerTy()));
1685
1686       SDOperand Size  = Tmp2.getOperand(1);
1687       SDOperand SP = DAG.getCopyFromReg(Chain, SPReg, VT);
1688       Chain = SP.getValue(1);
1689       unsigned Align = cast<ConstantSDNode>(Tmp3)->getValue();
1690       unsigned StackAlign =
1691         TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
1692       if (Align > StackAlign)
1693         SP = DAG.getNode(ISD::AND, VT, SP,
1694                          DAG.getConstant(-(uint64_t)Align, VT));
1695       Tmp1 = DAG.getNode(ISD::SUB, VT, SP, Size);       // Value
1696       Chain = DAG.getCopyToReg(Chain, SPReg, Tmp1);     // Output chain
1697
1698       Tmp2 =
1699         DAG.getCALLSEQ_END(Chain,
1700                            DAG.getConstant(0, TLI.getPointerTy()),
1701                            DAG.getConstant(0, TLI.getPointerTy()),
1702                            SDOperand());
1703
1704       Tmp1 = LegalizeOp(Tmp1);
1705       Tmp2 = LegalizeOp(Tmp2);
1706       break;
1707     }
1708     case TargetLowering::Custom:
1709       Tmp3 = TLI.LowerOperation(Tmp1, DAG);
1710       if (Tmp3.Val) {
1711         Tmp1 = LegalizeOp(Tmp3);
1712         Tmp2 = LegalizeOp(Tmp3.getValue(1));
1713       }
1714       break;
1715     case TargetLowering::Legal:
1716       break;
1717     }
1718     // Since this op produce two values, make sure to remember that we
1719     // legalized both of them.
1720     AddLegalizedOperand(SDOperand(Node, 0), Tmp1);
1721     AddLegalizedOperand(SDOperand(Node, 1), Tmp2);
1722     return Op.ResNo ? Tmp2 : Tmp1;
1723   }
1724   case ISD::INLINEASM: {
1725     SmallVector<SDOperand, 8> Ops(Node->op_begin(), Node->op_end());
1726     bool Changed = false;
1727     // Legalize all of the operands of the inline asm, in case they are nodes
1728     // that need to be expanded or something.  Note we skip the asm string and
1729     // all of the TargetConstant flags.
1730     SDOperand Op = LegalizeOp(Ops[0]);
1731     Changed = Op != Ops[0];
1732     Ops[0] = Op;
1733
1734     bool HasInFlag = Ops.back().getValueType() == MVT::Flag;
1735     for (unsigned i = 2, e = Ops.size()-HasInFlag; i < e; ) {
1736       unsigned NumVals = cast<ConstantSDNode>(Ops[i])->getValue() >> 3;
1737       for (++i; NumVals; ++i, --NumVals) {
1738         SDOperand Op = LegalizeOp(Ops[i]);
1739         if (Op != Ops[i]) {
1740           Changed = true;
1741           Ops[i] = Op;
1742         }
1743       }
1744     }
1745
1746     if (HasInFlag) {
1747       Op = LegalizeOp(Ops.back());
1748       Changed |= Op != Ops.back();
1749       Ops.back() = Op;
1750     }
1751     
1752     if (Changed)
1753       Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
1754       
1755     // INLINE asm returns a chain and flag, make sure to add both to the map.
1756     AddLegalizedOperand(SDOperand(Node, 0), Result.getValue(0));
1757     AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
1758     return Result.getValue(Op.ResNo);
1759   }
1760   case ISD::BR:
1761     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1762     // Ensure that libcalls are emitted before a branch.
1763     Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
1764     Tmp1 = LegalizeOp(Tmp1);
1765     LastCALLSEQ_END = DAG.getEntryNode();
1766     
1767     Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
1768     break;
1769   case ISD::BRIND:
1770     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1771     // Ensure that libcalls are emitted before a branch.
1772     Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
1773     Tmp1 = LegalizeOp(Tmp1);
1774     LastCALLSEQ_END = DAG.getEntryNode();
1775     
1776     switch (getTypeAction(Node->getOperand(1).getValueType())) {
1777     default: assert(0 && "Indirect target must be legal type (pointer)!");
1778     case Legal:
1779       Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the condition.
1780       break;
1781     }
1782     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
1783     break;
1784   case ISD::BR_JT:
1785     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1786     // Ensure that libcalls are emitted before a branch.
1787     Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
1788     Tmp1 = LegalizeOp(Tmp1);
1789     LastCALLSEQ_END = DAG.getEntryNode();
1790
1791     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the jumptable node.
1792     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
1793
1794     switch (TLI.getOperationAction(ISD::BR_JT, MVT::Other)) {  
1795     default: assert(0 && "This action is not supported yet!");
1796     case TargetLowering::Legal: break;
1797     case TargetLowering::Custom:
1798       Tmp1 = TLI.LowerOperation(Result, DAG);
1799       if (Tmp1.Val) Result = Tmp1;
1800       break;
1801     case TargetLowering::Expand: {
1802       SDOperand Chain = Result.getOperand(0);
1803       SDOperand Table = Result.getOperand(1);
1804       SDOperand Index = Result.getOperand(2);
1805
1806       MVT PTy = TLI.getPointerTy();
1807       MachineFunction &MF = DAG.getMachineFunction();
1808       unsigned EntrySize = MF.getJumpTableInfo()->getEntrySize();
1809       Index= DAG.getNode(ISD::MUL, PTy, Index, DAG.getConstant(EntrySize, PTy));
1810       SDOperand Addr = DAG.getNode(ISD::ADD, PTy, Index, Table);
1811       
1812       SDOperand LD;
1813       switch (EntrySize) {
1814       default: assert(0 && "Size of jump table not supported yet."); break;
1815       case 4: LD = DAG.getLoad(MVT::i32, Chain, Addr,
1816                                PseudoSourceValue::getJumpTable(), 0); break;
1817       case 8: LD = DAG.getLoad(MVT::i64, Chain, Addr,
1818                                PseudoSourceValue::getJumpTable(), 0); break;
1819       }
1820
1821       Addr = LD;
1822       if (TLI.getTargetMachine().getRelocationModel() == Reloc::PIC_) {
1823         // For PIC, the sequence is:
1824         // BRIND(load(Jumptable + index) + RelocBase)
1825         // RelocBase can be JumpTable, GOT or some sort of global base.
1826         if (PTy != MVT::i32)
1827           Addr = DAG.getNode(ISD::SIGN_EXTEND, PTy, Addr);
1828         Addr = DAG.getNode(ISD::ADD, PTy, Addr,
1829                            TLI.getPICJumpTableRelocBase(Table, DAG));
1830       }
1831       Result = DAG.getNode(ISD::BRIND, MVT::Other, LD.getValue(1), Addr);
1832     }
1833     }
1834     break;
1835   case ISD::BRCOND:
1836     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1837     // Ensure that libcalls are emitted before a return.
1838     Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
1839     Tmp1 = LegalizeOp(Tmp1);
1840     LastCALLSEQ_END = DAG.getEntryNode();
1841
1842     switch (getTypeAction(Node->getOperand(1).getValueType())) {
1843     case Expand: assert(0 && "It's impossible to expand bools");
1844     case Legal:
1845       Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the condition.
1846       break;
1847     case Promote: {
1848       Tmp2 = PromoteOp(Node->getOperand(1));  // Promote the condition.
1849       
1850       // The top bits of the promoted condition are not necessarily zero, ensure
1851       // that the value is properly zero extended.
1852       unsigned BitWidth = Tmp2.getValueSizeInBits();
1853       if (!DAG.MaskedValueIsZero(Tmp2, 
1854                                  APInt::getHighBitsSet(BitWidth, BitWidth-1)))
1855         Tmp2 = DAG.getZeroExtendInReg(Tmp2, MVT::i1);
1856       break;
1857     }
1858     }
1859
1860     // Basic block destination (Op#2) is always legal.
1861     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
1862       
1863     switch (TLI.getOperationAction(ISD::BRCOND, MVT::Other)) {  
1864     default: assert(0 && "This action is not supported yet!");
1865     case TargetLowering::Legal: break;
1866     case TargetLowering::Custom:
1867       Tmp1 = TLI.LowerOperation(Result, DAG);
1868       if (Tmp1.Val) Result = Tmp1;
1869       break;
1870     case TargetLowering::Expand:
1871       // Expand brcond's setcc into its constituent parts and create a BR_CC
1872       // Node.
1873       if (Tmp2.getOpcode() == ISD::SETCC) {
1874         Result = DAG.getNode(ISD::BR_CC, MVT::Other, Tmp1, Tmp2.getOperand(2),
1875                              Tmp2.getOperand(0), Tmp2.getOperand(1),
1876                              Node->getOperand(2));
1877       } else {
1878         Result = DAG.getNode(ISD::BR_CC, MVT::Other, Tmp1, 
1879                              DAG.getCondCode(ISD::SETNE), Tmp2,
1880                              DAG.getConstant(0, Tmp2.getValueType()),
1881                              Node->getOperand(2));
1882       }
1883       break;
1884     }
1885     break;
1886   case ISD::BR_CC:
1887     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1888     // Ensure that libcalls are emitted before a branch.
1889     Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
1890     Tmp1 = LegalizeOp(Tmp1);
1891     Tmp2 = Node->getOperand(2);              // LHS 
1892     Tmp3 = Node->getOperand(3);              // RHS
1893     Tmp4 = Node->getOperand(1);              // CC
1894
1895     LegalizeSetCCOperands(Tmp2, Tmp3, Tmp4);
1896     LastCALLSEQ_END = DAG.getEntryNode();
1897
1898     // If we didn't get both a LHS and RHS back from LegalizeSetCCOperands,
1899     // the LHS is a legal SETCC itself.  In this case, we need to compare
1900     // the result against zero to select between true and false values.
1901     if (Tmp3.Val == 0) {
1902       Tmp3 = DAG.getConstant(0, Tmp2.getValueType());
1903       Tmp4 = DAG.getCondCode(ISD::SETNE);
1904     }
1905     
1906     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp4, Tmp2, Tmp3, 
1907                                     Node->getOperand(4));
1908       
1909     switch (TLI.getOperationAction(ISD::BR_CC, Tmp3.getValueType())) {
1910     default: assert(0 && "Unexpected action for BR_CC!");
1911     case TargetLowering::Legal: break;
1912     case TargetLowering::Custom:
1913       Tmp4 = TLI.LowerOperation(Result, DAG);
1914       if (Tmp4.Val) Result = Tmp4;
1915       break;
1916     }
1917     break;
1918   case ISD::LOAD: {
1919     LoadSDNode *LD = cast<LoadSDNode>(Node);
1920     Tmp1 = LegalizeOp(LD->getChain());   // Legalize the chain.
1921     Tmp2 = LegalizeOp(LD->getBasePtr()); // Legalize the base pointer.
1922
1923     ISD::LoadExtType ExtType = LD->getExtensionType();
1924     if (ExtType == ISD::NON_EXTLOAD) {
1925       MVT VT = Node->getValueType(0);
1926       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, LD->getOffset());
1927       Tmp3 = Result.getValue(0);
1928       Tmp4 = Result.getValue(1);
1929     
1930       switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
1931       default: assert(0 && "This action is not supported yet!");
1932       case TargetLowering::Legal:
1933         // If this is an unaligned load and the target doesn't support it,
1934         // expand it.
1935         if (!TLI.allowsUnalignedMemoryAccesses()) {
1936           unsigned ABIAlignment = TLI.getTargetData()->
1937             getABITypeAlignment(LD->getMemoryVT().getTypeForMVT());
1938           if (LD->getAlignment() < ABIAlignment){
1939             Result = ExpandUnalignedLoad(cast<LoadSDNode>(Result.Val), DAG,
1940                                          TLI);
1941             Tmp3 = Result.getOperand(0);
1942             Tmp4 = Result.getOperand(1);
1943             Tmp3 = LegalizeOp(Tmp3);
1944             Tmp4 = LegalizeOp(Tmp4);
1945           }
1946         }
1947         break;
1948       case TargetLowering::Custom:
1949         Tmp1 = TLI.LowerOperation(Tmp3, DAG);
1950         if (Tmp1.Val) {
1951           Tmp3 = LegalizeOp(Tmp1);
1952           Tmp4 = LegalizeOp(Tmp1.getValue(1));
1953         }
1954         break;
1955       case TargetLowering::Promote: {
1956         // Only promote a load of vector type to another.
1957         assert(VT.isVector() && "Cannot promote this load!");
1958         // Change base type to a different vector type.
1959         MVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), VT);
1960
1961         Tmp1 = DAG.getLoad(NVT, Tmp1, Tmp2, LD->getSrcValue(),
1962                            LD->getSrcValueOffset(),
1963                            LD->isVolatile(), LD->getAlignment());
1964         Tmp3 = LegalizeOp(DAG.getNode(ISD::BIT_CONVERT, VT, Tmp1));
1965         Tmp4 = LegalizeOp(Tmp1.getValue(1));
1966         break;
1967       }
1968       }
1969       // Since loads produce two values, make sure to remember that we 
1970       // legalized both of them.
1971       AddLegalizedOperand(SDOperand(Node, 0), Tmp3);
1972       AddLegalizedOperand(SDOperand(Node, 1), Tmp4);
1973       return Op.ResNo ? Tmp4 : Tmp3;
1974     } else {
1975       MVT SrcVT = LD->getMemoryVT();
1976       unsigned SrcWidth = SrcVT.getSizeInBits();
1977       int SVOffset = LD->getSrcValueOffset();
1978       unsigned Alignment = LD->getAlignment();
1979       bool isVolatile = LD->isVolatile();
1980
1981       if (SrcWidth != SrcVT.getStoreSizeInBits() &&
1982           // Some targets pretend to have an i1 loading operation, and actually
1983           // load an i8.  This trick is correct for ZEXTLOAD because the top 7
1984           // bits are guaranteed to be zero; it helps the optimizers understand
1985           // that these bits are zero.  It is also useful for EXTLOAD, since it
1986           // tells the optimizers that those bits are undefined.  It would be
1987           // nice to have an effective generic way of getting these benefits...
1988           // Until such a way is found, don't insist on promoting i1 here.
1989           (SrcVT != MVT::i1 ||
1990            TLI.getLoadXAction(ExtType, MVT::i1) == TargetLowering::Promote)) {
1991         // Promote to a byte-sized load if not loading an integral number of
1992         // bytes.  For example, promote EXTLOAD:i20 -> EXTLOAD:i24.
1993         unsigned NewWidth = SrcVT.getStoreSizeInBits();
1994         MVT NVT = MVT::getIntegerVT(NewWidth);
1995         SDOperand Ch;
1996
1997         // The extra bits are guaranteed to be zero, since we stored them that
1998         // way.  A zext load from NVT thus automatically gives zext from SrcVT.
1999
2000         ISD::LoadExtType NewExtType =
2001           ExtType == ISD::ZEXTLOAD ? ISD::ZEXTLOAD : ISD::EXTLOAD;
2002
2003         Result = DAG.getExtLoad(NewExtType, Node->getValueType(0),
2004                                 Tmp1, Tmp2, LD->getSrcValue(), SVOffset,
2005                                 NVT, isVolatile, Alignment);
2006
2007         Ch = Result.getValue(1); // The chain.
2008
2009         if (ExtType == ISD::SEXTLOAD)
2010           // Having the top bits zero doesn't help when sign extending.
2011           Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
2012                                Result, DAG.getValueType(SrcVT));
2013         else if (ExtType == ISD::ZEXTLOAD || NVT == Result.getValueType())
2014           // All the top bits are guaranteed to be zero - inform the optimizers.
2015           Result = DAG.getNode(ISD::AssertZext, Result.getValueType(), Result,
2016                                DAG.getValueType(SrcVT));
2017
2018         Tmp1 = LegalizeOp(Result);
2019         Tmp2 = LegalizeOp(Ch);
2020       } else if (SrcWidth & (SrcWidth - 1)) {
2021         // If not loading a power-of-2 number of bits, expand as two loads.
2022         assert(SrcVT.isExtended() && !SrcVT.isVector() &&
2023                "Unsupported extload!");
2024         unsigned RoundWidth = 1 << Log2_32(SrcWidth);
2025         assert(RoundWidth < SrcWidth);
2026         unsigned ExtraWidth = SrcWidth - RoundWidth;
2027         assert(ExtraWidth < RoundWidth);
2028         assert(!(RoundWidth % 8) && !(ExtraWidth % 8) &&
2029                "Load size not an integral number of bytes!");
2030         MVT RoundVT = MVT::getIntegerVT(RoundWidth);
2031         MVT ExtraVT = MVT::getIntegerVT(ExtraWidth);
2032         SDOperand Lo, Hi, Ch;
2033         unsigned IncrementSize;
2034
2035         if (TLI.isLittleEndian()) {
2036           // EXTLOAD:i24 -> ZEXTLOAD:i16 | (shl EXTLOAD@+2:i8, 16)
2037           // Load the bottom RoundWidth bits.
2038           Lo = DAG.getExtLoad(ISD::ZEXTLOAD, Node->getValueType(0), Tmp1, Tmp2,
2039                               LD->getSrcValue(), SVOffset, RoundVT, isVolatile,
2040                               Alignment);
2041
2042           // Load the remaining ExtraWidth bits.
2043           IncrementSize = RoundWidth / 8;
2044           Tmp2 = DAG.getNode(ISD::ADD, Tmp2.getValueType(), Tmp2,
2045                              DAG.getIntPtrConstant(IncrementSize));
2046           Hi = DAG.getExtLoad(ExtType, Node->getValueType(0), Tmp1, Tmp2,
2047                               LD->getSrcValue(), SVOffset + IncrementSize,
2048                               ExtraVT, isVolatile,
2049                               MinAlign(Alignment, IncrementSize));
2050
2051           // Build a factor node to remember that this load is independent of the
2052           // other one.
2053           Ch = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo.getValue(1),
2054                            Hi.getValue(1));
2055
2056           // Move the top bits to the right place.
2057           Hi = DAG.getNode(ISD::SHL, Hi.getValueType(), Hi,
2058                            DAG.getConstant(RoundWidth, TLI.getShiftAmountTy()));
2059
2060           // Join the hi and lo parts.
2061           Result = DAG.getNode(ISD::OR, Node->getValueType(0), Lo, Hi);
2062         } else {
2063           // Big endian - avoid unaligned loads.
2064           // EXTLOAD:i24 -> (shl EXTLOAD:i16, 8) | ZEXTLOAD@+2:i8
2065           // Load the top RoundWidth bits.
2066           Hi = DAG.getExtLoad(ExtType, Node->getValueType(0), Tmp1, Tmp2,
2067                               LD->getSrcValue(), SVOffset, RoundVT, isVolatile,
2068                               Alignment);
2069
2070           // Load the remaining ExtraWidth bits.
2071           IncrementSize = RoundWidth / 8;
2072           Tmp2 = DAG.getNode(ISD::ADD, Tmp2.getValueType(), Tmp2,
2073                              DAG.getIntPtrConstant(IncrementSize));
2074           Lo = DAG.getExtLoad(ISD::ZEXTLOAD, Node->getValueType(0), Tmp1, Tmp2,
2075                               LD->getSrcValue(), SVOffset + IncrementSize,
2076                               ExtraVT, isVolatile,
2077                               MinAlign(Alignment, IncrementSize));
2078
2079           // Build a factor node to remember that this load is independent of the
2080           // other one.
2081           Ch = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo.getValue(1),
2082                            Hi.getValue(1));
2083
2084           // Move the top bits to the right place.
2085           Hi = DAG.getNode(ISD::SHL, Hi.getValueType(), Hi,
2086                            DAG.getConstant(ExtraWidth, TLI.getShiftAmountTy()));
2087
2088           // Join the hi and lo parts.
2089           Result = DAG.getNode(ISD::OR, Node->getValueType(0), Lo, Hi);
2090         }
2091
2092         Tmp1 = LegalizeOp(Result);
2093         Tmp2 = LegalizeOp(Ch);
2094       } else {
2095         switch (TLI.getLoadXAction(ExtType, SrcVT)) {
2096         default: assert(0 && "This action is not supported yet!");
2097         case TargetLowering::Custom:
2098           isCustom = true;
2099           // FALLTHROUGH
2100         case TargetLowering::Legal:
2101           Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, LD->getOffset());
2102           Tmp1 = Result.getValue(0);
2103           Tmp2 = Result.getValue(1);
2104
2105           if (isCustom) {
2106             Tmp3 = TLI.LowerOperation(Result, DAG);
2107             if (Tmp3.Val) {
2108               Tmp1 = LegalizeOp(Tmp3);
2109               Tmp2 = LegalizeOp(Tmp3.getValue(1));
2110             }
2111           } else {
2112             // If this is an unaligned load and the target doesn't support it,
2113             // expand it.
2114             if (!TLI.allowsUnalignedMemoryAccesses()) {
2115               unsigned ABIAlignment = TLI.getTargetData()->
2116                 getABITypeAlignment(LD->getMemoryVT().getTypeForMVT());
2117               if (LD->getAlignment() < ABIAlignment){
2118                 Result = ExpandUnalignedLoad(cast<LoadSDNode>(Result.Val), DAG,
2119                                              TLI);
2120                 Tmp1 = Result.getOperand(0);
2121                 Tmp2 = Result.getOperand(1);
2122                 Tmp1 = LegalizeOp(Tmp1);
2123                 Tmp2 = LegalizeOp(Tmp2);
2124               }
2125             }
2126           }
2127           break;
2128         case TargetLowering::Expand:
2129           // f64 = EXTLOAD f32 should expand to LOAD, FP_EXTEND
2130           if (SrcVT == MVT::f32 && Node->getValueType(0) == MVT::f64) {
2131             SDOperand Load = DAG.getLoad(SrcVT, Tmp1, Tmp2, LD->getSrcValue(),
2132                                          LD->getSrcValueOffset(),
2133                                          LD->isVolatile(), LD->getAlignment());
2134             Result = DAG.getNode(ISD::FP_EXTEND, Node->getValueType(0), Load);
2135             Tmp1 = LegalizeOp(Result);  // Relegalize new nodes.
2136             Tmp2 = LegalizeOp(Load.getValue(1));
2137             break;
2138           }
2139           assert(ExtType != ISD::EXTLOAD &&"EXTLOAD should always be supported!");
2140           // Turn the unsupported load into an EXTLOAD followed by an explicit
2141           // zero/sign extend inreg.
2142           Result = DAG.getExtLoad(ISD::EXTLOAD, Node->getValueType(0),
2143                                   Tmp1, Tmp2, LD->getSrcValue(),
2144                                   LD->getSrcValueOffset(), SrcVT,
2145                                   LD->isVolatile(), LD->getAlignment());
2146           SDOperand ValRes;
2147           if (ExtType == ISD::SEXTLOAD)
2148             ValRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
2149                                  Result, DAG.getValueType(SrcVT));
2150           else
2151             ValRes = DAG.getZeroExtendInReg(Result, SrcVT);
2152           Tmp1 = LegalizeOp(ValRes);  // Relegalize new nodes.
2153           Tmp2 = LegalizeOp(Result.getValue(1));  // Relegalize new nodes.
2154           break;
2155         }
2156       }
2157
2158       // Since loads produce two values, make sure to remember that we legalized
2159       // both of them.
2160       AddLegalizedOperand(SDOperand(Node, 0), Tmp1);
2161       AddLegalizedOperand(SDOperand(Node, 1), Tmp2);
2162       return Op.ResNo ? Tmp2 : Tmp1;
2163     }
2164   }
2165   case ISD::EXTRACT_ELEMENT: {
2166     MVT OpTy = Node->getOperand(0).getValueType();
2167     switch (getTypeAction(OpTy)) {
2168     default: assert(0 && "EXTRACT_ELEMENT action for type unimplemented!");
2169     case Legal:
2170       if (cast<ConstantSDNode>(Node->getOperand(1))->getValue()) {
2171         // 1 -> Hi
2172         Result = DAG.getNode(ISD::SRL, OpTy, Node->getOperand(0),
2173                              DAG.getConstant(OpTy.getSizeInBits()/2,
2174                                              TLI.getShiftAmountTy()));
2175         Result = DAG.getNode(ISD::TRUNCATE, Node->getValueType(0), Result);
2176       } else {
2177         // 0 -> Lo
2178         Result = DAG.getNode(ISD::TRUNCATE, Node->getValueType(0), 
2179                              Node->getOperand(0));
2180       }
2181       break;
2182     case Expand:
2183       // Get both the low and high parts.
2184       ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
2185       if (cast<ConstantSDNode>(Node->getOperand(1))->getValue())
2186         Result = Tmp2;  // 1 -> Hi
2187       else
2188         Result = Tmp1;  // 0 -> Lo
2189       break;
2190     }
2191     break;
2192   }
2193
2194   case ISD::CopyToReg:
2195     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2196
2197     assert(isTypeLegal(Node->getOperand(2).getValueType()) &&
2198            "Register type must be legal!");
2199     // Legalize the incoming value (must be a legal type).
2200     Tmp2 = LegalizeOp(Node->getOperand(2));
2201     if (Node->getNumValues() == 1) {
2202       Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1), Tmp2);
2203     } else {
2204       assert(Node->getNumValues() == 2 && "Unknown CopyToReg");
2205       if (Node->getNumOperands() == 4) {
2206         Tmp3 = LegalizeOp(Node->getOperand(3));
2207         Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1), Tmp2,
2208                                         Tmp3);
2209       } else {
2210         Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1),Tmp2);
2211       }
2212       
2213       // Since this produces two values, make sure to remember that we legalized
2214       // both of them.
2215       AddLegalizedOperand(SDOperand(Node, 0), Result.getValue(0));
2216       AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
2217       return Result;
2218     }
2219     break;
2220
2221   case ISD::RET:
2222     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2223
2224     // Ensure that libcalls are emitted before a return.
2225     Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
2226     Tmp1 = LegalizeOp(Tmp1);
2227     LastCALLSEQ_END = DAG.getEntryNode();
2228       
2229     switch (Node->getNumOperands()) {
2230     case 3:  // ret val
2231       Tmp2 = Node->getOperand(1);
2232       Tmp3 = Node->getOperand(2);  // Signness
2233       switch (getTypeAction(Tmp2.getValueType())) {
2234       case Legal:
2235         Result = DAG.UpdateNodeOperands(Result, Tmp1, LegalizeOp(Tmp2), Tmp3);
2236         break;
2237       case Expand:
2238         if (!Tmp2.getValueType().isVector()) {
2239           SDOperand Lo, Hi;
2240           ExpandOp(Tmp2, Lo, Hi);
2241
2242           // Big endian systems want the hi reg first.
2243           if (TLI.isBigEndian())
2244             std::swap(Lo, Hi);
2245           
2246           if (Hi.Val)
2247             Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Lo, Tmp3, Hi,Tmp3);
2248           else
2249             Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Lo, Tmp3);
2250           Result = LegalizeOp(Result);
2251         } else {
2252           SDNode *InVal = Tmp2.Val;
2253           int InIx = Tmp2.ResNo;
2254           unsigned NumElems = InVal->getValueType(InIx).getVectorNumElements();
2255           MVT EVT = InVal->getValueType(InIx).getVectorElementType();
2256           
2257           // Figure out if there is a simple type corresponding to this Vector
2258           // type.  If so, convert to the vector type.
2259           MVT TVT = MVT::getVectorVT(EVT, NumElems);
2260           if (TLI.isTypeLegal(TVT)) {
2261             // Turn this into a return of the vector type.
2262             Tmp2 = LegalizeOp(Tmp2);
2263             Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
2264           } else if (NumElems == 1) {
2265             // Turn this into a return of the scalar type.
2266             Tmp2 = ScalarizeVectorOp(Tmp2);
2267             Tmp2 = LegalizeOp(Tmp2);
2268             Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
2269             
2270             // FIXME: Returns of gcc generic vectors smaller than a legal type
2271             // should be returned in integer registers!
2272             
2273             // The scalarized value type may not be legal, e.g. it might require
2274             // promotion or expansion.  Relegalize the return.
2275             Result = LegalizeOp(Result);
2276           } else {
2277             // FIXME: Returns of gcc generic vectors larger than a legal vector
2278             // type should be returned by reference!
2279             SDOperand Lo, Hi;
2280             SplitVectorOp(Tmp2, Lo, Hi);
2281             Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Lo, Tmp3, Hi,Tmp3);
2282             Result = LegalizeOp(Result);
2283           }
2284         }
2285         break;
2286       case Promote:
2287         Tmp2 = PromoteOp(Node->getOperand(1));
2288         Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
2289         Result = LegalizeOp(Result);
2290         break;
2291       }
2292       break;
2293     case 1:  // ret void
2294       Result = DAG.UpdateNodeOperands(Result, Tmp1);
2295       break;
2296     default: { // ret <values>
2297       SmallVector<SDOperand, 8> NewValues;
2298       NewValues.push_back(Tmp1);
2299       for (unsigned i = 1, e = Node->getNumOperands(); i < e; i += 2)
2300         switch (getTypeAction(Node->getOperand(i).getValueType())) {
2301         case Legal:
2302           NewValues.push_back(LegalizeOp(Node->getOperand(i)));
2303           NewValues.push_back(Node->getOperand(i+1));
2304           break;
2305         case Expand: {
2306           SDOperand Lo, Hi;
2307           assert(!Node->getOperand(i).getValueType().isExtended() &&
2308                  "FIXME: TODO: implement returning non-legal vector types!");
2309           ExpandOp(Node->getOperand(i), Lo, Hi);
2310           NewValues.push_back(Lo);
2311           NewValues.push_back(Node->getOperand(i+1));
2312           if (Hi.Val) {
2313             NewValues.push_back(Hi);
2314             NewValues.push_back(Node->getOperand(i+1));
2315           }
2316           break;
2317         }
2318         case Promote:
2319           assert(0 && "Can't promote multiple return value yet!");
2320         }
2321           
2322       if (NewValues.size() == Node->getNumOperands())
2323         Result = DAG.UpdateNodeOperands(Result, &NewValues[0],NewValues.size());
2324       else
2325         Result = DAG.getNode(ISD::RET, MVT::Other,
2326                              &NewValues[0], NewValues.size());
2327       break;
2328     }
2329     }
2330
2331     if (Result.getOpcode() == ISD::RET) {
2332       switch (TLI.getOperationAction(Result.getOpcode(), MVT::Other)) {
2333       default: assert(0 && "This action is not supported yet!");
2334       case TargetLowering::Legal: break;
2335       case TargetLowering::Custom:
2336         Tmp1 = TLI.LowerOperation(Result, DAG);
2337         if (Tmp1.Val) Result = Tmp1;
2338         break;
2339       }
2340     }
2341     break;
2342   case ISD::STORE: {
2343     StoreSDNode *ST = cast<StoreSDNode>(Node);
2344     Tmp1 = LegalizeOp(ST->getChain());    // Legalize the chain.
2345     Tmp2 = LegalizeOp(ST->getBasePtr());  // Legalize the pointer.
2346     int SVOffset = ST->getSrcValueOffset();
2347     unsigned Alignment = ST->getAlignment();
2348     bool isVolatile = ST->isVolatile();
2349
2350     if (!ST->isTruncatingStore()) {
2351       // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
2352       // FIXME: We shouldn't do this for TargetConstantFP's.
2353       // FIXME: move this to the DAG Combiner!  Note that we can't regress due
2354       // to phase ordering between legalized code and the dag combiner.  This
2355       // probably means that we need to integrate dag combiner and legalizer
2356       // together.
2357       // We generally can't do this one for long doubles.
2358       if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(ST->getValue())) {
2359         if (CFP->getValueType(0) == MVT::f32 && 
2360             getTypeAction(MVT::i32) == Legal) {
2361           Tmp3 = DAG.getConstant(CFP->getValueAPF().
2362                                           convertToAPInt().zextOrTrunc(32),
2363                                   MVT::i32);
2364           Result = DAG.getStore(Tmp1, Tmp3, Tmp2, ST->getSrcValue(),
2365                                 SVOffset, isVolatile, Alignment);
2366           break;
2367         } else if (CFP->getValueType(0) == MVT::f64) {
2368           // If this target supports 64-bit registers, do a single 64-bit store.
2369           if (getTypeAction(MVT::i64) == Legal) {
2370             Tmp3 = DAG.getConstant(CFP->getValueAPF().convertToAPInt().
2371                                      zextOrTrunc(64), MVT::i64);
2372             Result = DAG.getStore(Tmp1, Tmp3, Tmp2, ST->getSrcValue(),
2373                                   SVOffset, isVolatile, Alignment);
2374             break;
2375           } else if (getTypeAction(MVT::i32) == Legal && !ST->isVolatile()) {
2376             // Otherwise, if the target supports 32-bit registers, use 2 32-bit
2377             // stores.  If the target supports neither 32- nor 64-bits, this
2378             // xform is certainly not worth it.
2379             const APInt &IntVal =CFP->getValueAPF().convertToAPInt();
2380             SDOperand Lo = DAG.getConstant(APInt(IntVal).trunc(32), MVT::i32);
2381             SDOperand Hi = DAG.getConstant(IntVal.lshr(32).trunc(32), MVT::i32);
2382             if (TLI.isBigEndian()) std::swap(Lo, Hi);
2383
2384             Lo = DAG.getStore(Tmp1, Lo, Tmp2, ST->getSrcValue(),
2385                               SVOffset, isVolatile, Alignment);
2386             Tmp2 = DAG.getNode(ISD::ADD, Tmp2.getValueType(), Tmp2,
2387                                DAG.getIntPtrConstant(4));
2388             Hi = DAG.getStore(Tmp1, Hi, Tmp2, ST->getSrcValue(), SVOffset+4,
2389                               isVolatile, MinAlign(Alignment, 4U));
2390
2391             Result = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo, Hi);
2392             break;
2393           }
2394         }
2395       }
2396       
2397       switch (getTypeAction(ST->getMemoryVT())) {
2398       case Legal: {
2399         Tmp3 = LegalizeOp(ST->getValue());
2400         Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp3, Tmp2, 
2401                                         ST->getOffset());
2402
2403         MVT VT = Tmp3.getValueType();
2404         switch (TLI.getOperationAction(ISD::STORE, VT)) {
2405         default: assert(0 && "This action is not supported yet!");
2406         case TargetLowering::Legal:
2407           // If this is an unaligned store and the target doesn't support it,
2408           // expand it.
2409           if (!TLI.allowsUnalignedMemoryAccesses()) {
2410             unsigned ABIAlignment = TLI.getTargetData()->
2411               getABITypeAlignment(ST->getMemoryVT().getTypeForMVT());
2412             if (ST->getAlignment() < ABIAlignment)
2413               Result = ExpandUnalignedStore(cast<StoreSDNode>(Result.Val), DAG,
2414                                             TLI);
2415           }
2416           break;
2417         case TargetLowering::Custom:
2418           Tmp1 = TLI.LowerOperation(Result, DAG);
2419           if (Tmp1.Val) Result = Tmp1;
2420           break;
2421         case TargetLowering::Promote:
2422           assert(VT.isVector() && "Unknown legal promote case!");
2423           Tmp3 = DAG.getNode(ISD::BIT_CONVERT, 
2424                              TLI.getTypeToPromoteTo(ISD::STORE, VT), Tmp3);
2425           Result = DAG.getStore(Tmp1, Tmp3, Tmp2,
2426                                 ST->getSrcValue(), SVOffset, isVolatile,
2427                                 Alignment);
2428           break;
2429         }
2430         break;
2431       }
2432       case Promote:
2433         // Truncate the value and store the result.
2434         Tmp3 = PromoteOp(ST->getValue());
2435         Result = DAG.getTruncStore(Tmp1, Tmp3, Tmp2, ST->getSrcValue(),
2436                                    SVOffset, ST->getMemoryVT(),
2437                                    isVolatile, Alignment);
2438         break;
2439
2440       case Expand:
2441         unsigned IncrementSize = 0;
2442         SDOperand Lo, Hi;
2443       
2444         // If this is a vector type, then we have to calculate the increment as
2445         // the product of the element size in bytes, and the number of elements
2446         // in the high half of the vector.
2447         if (ST->getValue().getValueType().isVector()) {
2448           SDNode *InVal = ST->getValue().Val;
2449           int InIx = ST->getValue().ResNo;
2450           MVT InVT = InVal->getValueType(InIx);
2451           unsigned NumElems = InVT.getVectorNumElements();
2452           MVT EVT = InVT.getVectorElementType();
2453
2454           // Figure out if there is a simple type corresponding to this Vector
2455           // type.  If so, convert to the vector type.
2456           MVT TVT = MVT::getVectorVT(EVT, NumElems);
2457           if (TLI.isTypeLegal(TVT)) {
2458             // Turn this into a normal store of the vector type.
2459             Tmp3 = LegalizeOp(ST->getValue());
2460             Result = DAG.getStore(Tmp1, Tmp3, Tmp2, ST->getSrcValue(),
2461                                   SVOffset, isVolatile, Alignment);
2462             Result = LegalizeOp(Result);
2463             break;
2464           } else if (NumElems == 1) {
2465             // Turn this into a normal store of the scalar type.
2466             Tmp3 = ScalarizeVectorOp(ST->getValue());
2467             Result = DAG.getStore(Tmp1, Tmp3, Tmp2, ST->getSrcValue(),
2468                                   SVOffset, isVolatile, Alignment);
2469             // The scalarized value type may not be legal, e.g. it might require
2470             // promotion or expansion.  Relegalize the scalar store.
2471             Result = LegalizeOp(Result);
2472             break;
2473           } else {
2474             SplitVectorOp(ST->getValue(), Lo, Hi);
2475             IncrementSize = Lo.Val->getValueType(0).getVectorNumElements() *
2476                             EVT.getSizeInBits()/8;
2477           }
2478         } else {
2479           ExpandOp(ST->getValue(), Lo, Hi);
2480           IncrementSize = Hi.Val ? Hi.getValueType().getSizeInBits()/8 : 0;
2481
2482           if (TLI.isBigEndian())
2483             std::swap(Lo, Hi);
2484         }
2485
2486         Lo = DAG.getStore(Tmp1, Lo, Tmp2, ST->getSrcValue(),
2487                           SVOffset, isVolatile, Alignment);
2488
2489         if (Hi.Val == NULL) {
2490           // Must be int <-> float one-to-one expansion.
2491           Result = Lo;
2492           break;
2493         }
2494
2495         Tmp2 = DAG.getNode(ISD::ADD, Tmp2.getValueType(), Tmp2,
2496                            DAG.getIntPtrConstant(IncrementSize));
2497         assert(isTypeLegal(Tmp2.getValueType()) &&
2498                "Pointers must be legal!");
2499         SVOffset += IncrementSize;
2500         Alignment = MinAlign(Alignment, IncrementSize);
2501         Hi = DAG.getStore(Tmp1, Hi, Tmp2, ST->getSrcValue(),
2502                           SVOffset, isVolatile, Alignment);
2503         Result = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo, Hi);
2504         break;
2505       }
2506     } else {
2507       switch (getTypeAction(ST->getValue().getValueType())) {
2508       case Legal:
2509         Tmp3 = LegalizeOp(ST->getValue());
2510         break;
2511       case Promote:
2512         // We can promote the value, the truncstore will still take care of it.
2513         Tmp3 = PromoteOp(ST->getValue());
2514         break;
2515       case Expand:
2516         // Just store the low part.  This may become a non-trunc store, so make
2517         // sure to use getTruncStore, not UpdateNodeOperands below.
2518         ExpandOp(ST->getValue(), Tmp3, Tmp4);
2519         return DAG.getTruncStore(Tmp1, Tmp3, Tmp2, ST->getSrcValue(),
2520                                  SVOffset, MVT::i8, isVolatile, Alignment);
2521       }
2522
2523       MVT StVT = ST->getMemoryVT();
2524       unsigned StWidth = StVT.getSizeInBits();
2525
2526       if (StWidth != StVT.getStoreSizeInBits()) {
2527         // Promote to a byte-sized store with upper bits zero if not
2528         // storing an integral number of bytes.  For example, promote
2529         // TRUNCSTORE:i1 X -> TRUNCSTORE:i8 (and X, 1)
2530         MVT NVT = MVT::getIntegerVT(StVT.getStoreSizeInBits());
2531         Tmp3 = DAG.getZeroExtendInReg(Tmp3, StVT);
2532         Result = DAG.getTruncStore(Tmp1, Tmp3, Tmp2, ST->getSrcValue(),
2533                                    SVOffset, NVT, isVolatile, Alignment);
2534       } else if (StWidth & (StWidth - 1)) {
2535         // If not storing a power-of-2 number of bits, expand as two stores.
2536         assert(StVT.isExtended() && !StVT.isVector() &&
2537                "Unsupported truncstore!");
2538         unsigned RoundWidth = 1 << Log2_32(StWidth);
2539         assert(RoundWidth < StWidth);
2540         unsigned ExtraWidth = StWidth - RoundWidth;
2541         assert(ExtraWidth < RoundWidth);
2542         assert(!(RoundWidth % 8) && !(ExtraWidth % 8) &&
2543                "Store size not an integral number of bytes!");
2544         MVT RoundVT = MVT::getIntegerVT(RoundWidth);
2545         MVT ExtraVT = MVT::getIntegerVT(ExtraWidth);
2546         SDOperand Lo, Hi;
2547         unsigned IncrementSize;
2548
2549         if (TLI.isLittleEndian()) {
2550           // TRUNCSTORE:i24 X -> TRUNCSTORE:i16 X, TRUNCSTORE@+2:i8 (srl X, 16)
2551           // Store the bottom RoundWidth bits.
2552           Lo = DAG.getTruncStore(Tmp1, Tmp3, Tmp2, ST->getSrcValue(),
2553                                  SVOffset, RoundVT,
2554                                  isVolatile, Alignment);
2555
2556           // Store the remaining ExtraWidth bits.
2557           IncrementSize = RoundWidth / 8;
2558           Tmp2 = DAG.getNode(ISD::ADD, Tmp2.getValueType(), Tmp2,
2559                              DAG.getIntPtrConstant(IncrementSize));
2560           Hi = DAG.getNode(ISD::SRL, Tmp3.getValueType(), Tmp3,
2561                            DAG.getConstant(RoundWidth, TLI.getShiftAmountTy()));
2562           Hi = DAG.getTruncStore(Tmp1, Hi, Tmp2, ST->getSrcValue(),
2563                                  SVOffset + IncrementSize, ExtraVT, isVolatile,
2564                                  MinAlign(Alignment, IncrementSize));
2565         } else {
2566           // Big endian - avoid unaligned stores.
2567           // TRUNCSTORE:i24 X -> TRUNCSTORE:i16 (srl X, 8), TRUNCSTORE@+2:i8 X
2568           // Store the top RoundWidth bits.
2569           Hi = DAG.getNode(ISD::SRL, Tmp3.getValueType(), Tmp3,
2570                            DAG.getConstant(ExtraWidth, TLI.getShiftAmountTy()));
2571           Hi = DAG.getTruncStore(Tmp1, Hi, Tmp2, ST->getSrcValue(), SVOffset,
2572                                  RoundVT, isVolatile, Alignment);
2573
2574           // Store the remaining ExtraWidth bits.
2575           IncrementSize = RoundWidth / 8;
2576           Tmp2 = DAG.getNode(ISD::ADD, Tmp2.getValueType(), Tmp2,
2577                              DAG.getIntPtrConstant(IncrementSize));
2578           Lo = DAG.getTruncStore(Tmp1, Tmp3, Tmp2, ST->getSrcValue(),
2579                                  SVOffset + IncrementSize, ExtraVT, isVolatile,
2580                                  MinAlign(Alignment, IncrementSize));
2581         }
2582
2583         // The order of the stores doesn't matter.
2584         Result = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo, Hi);
2585       } else {
2586         if (Tmp1 != ST->getChain() || Tmp3 != ST->getValue() ||
2587             Tmp2 != ST->getBasePtr())
2588           Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp3, Tmp2,
2589                                           ST->getOffset());
2590
2591         switch (TLI.getTruncStoreAction(ST->getValue().getValueType(), StVT)) {
2592         default: assert(0 && "This action is not supported yet!");
2593         case TargetLowering::Legal:
2594           // If this is an unaligned store and the target doesn't support it,
2595           // expand it.
2596           if (!TLI.allowsUnalignedMemoryAccesses()) {
2597             unsigned ABIAlignment = TLI.getTargetData()->
2598               getABITypeAlignment(ST->getMemoryVT().getTypeForMVT());
2599             if (ST->getAlignment() < ABIAlignment)
2600               Result = ExpandUnalignedStore(cast<StoreSDNode>(Result.Val), DAG,
2601                                             TLI);
2602           }
2603           break;
2604         case TargetLowering::Custom:
2605           Result = TLI.LowerOperation(Result, DAG);
2606           break;
2607         case Expand:
2608           // TRUNCSTORE:i16 i32 -> STORE i16
2609           assert(isTypeLegal(StVT) && "Do not know how to expand this store!");
2610           Tmp3 = DAG.getNode(ISD::TRUNCATE, StVT, Tmp3);
2611           Result = DAG.getStore(Tmp1, Tmp3, Tmp2, ST->getSrcValue(), SVOffset,
2612                                 isVolatile, Alignment);
2613           break;
2614         }
2615       }
2616     }
2617     break;
2618   }
2619   case ISD::PCMARKER:
2620     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2621     Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
2622     break;
2623   case ISD::STACKSAVE:
2624     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2625     Result = DAG.UpdateNodeOperands(Result, Tmp1);
2626     Tmp1 = Result.getValue(0);
2627     Tmp2 = Result.getValue(1);
2628     
2629     switch (TLI.getOperationAction(ISD::STACKSAVE, MVT::Other)) {
2630     default: assert(0 && "This action is not supported yet!");
2631     case TargetLowering::Legal: break;
2632     case TargetLowering::Custom:
2633       Tmp3 = TLI.LowerOperation(Result, DAG);
2634       if (Tmp3.Val) {
2635         Tmp1 = LegalizeOp(Tmp3);
2636         Tmp2 = LegalizeOp(Tmp3.getValue(1));
2637       }
2638       break;
2639     case TargetLowering::Expand:
2640       // Expand to CopyFromReg if the target set 
2641       // StackPointerRegisterToSaveRestore.
2642       if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) {
2643         Tmp1 = DAG.getCopyFromReg(Result.getOperand(0), SP,
2644                                   Node->getValueType(0));
2645         Tmp2 = Tmp1.getValue(1);
2646       } else {
2647         Tmp1 = DAG.getNode(ISD::UNDEF, Node->getValueType(0));
2648         Tmp2 = Node->getOperand(0);
2649       }
2650       break;
2651     }
2652
2653     // Since stacksave produce two values, make sure to remember that we
2654     // legalized both of them.
2655     AddLegalizedOperand(SDOperand(Node, 0), Tmp1);
2656     AddLegalizedOperand(SDOperand(Node, 1), Tmp2);
2657     return Op.ResNo ? Tmp2 : Tmp1;
2658
2659   case ISD::STACKRESTORE:
2660     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2661     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
2662     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
2663       
2664     switch (TLI.getOperationAction(ISD::STACKRESTORE, MVT::Other)) {
2665     default: assert(0 && "This action is not supported yet!");
2666     case TargetLowering::Legal: break;
2667     case TargetLowering::Custom:
2668       Tmp1 = TLI.LowerOperation(Result, DAG);
2669       if (Tmp1.Val) Result = Tmp1;
2670       break;
2671     case TargetLowering::Expand:
2672       // Expand to CopyToReg if the target set 
2673       // StackPointerRegisterToSaveRestore.
2674       if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) {
2675         Result = DAG.getCopyToReg(Tmp1, SP, Tmp2);
2676       } else {
2677         Result = Tmp1;
2678       }
2679       break;
2680     }
2681     break;
2682
2683   case ISD::READCYCLECOUNTER:
2684     Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the chain
2685     Result = DAG.UpdateNodeOperands(Result, Tmp1);
2686     switch (TLI.getOperationAction(ISD::READCYCLECOUNTER,
2687                                    Node->getValueType(0))) {
2688     default: assert(0 && "This action is not supported yet!");
2689     case TargetLowering::Legal:
2690       Tmp1 = Result.getValue(0);
2691       Tmp2 = Result.getValue(1);
2692       break;
2693     case TargetLowering::Custom:
2694       Result = TLI.LowerOperation(Result, DAG);
2695       Tmp1 = LegalizeOp(Result.getValue(0));
2696       Tmp2 = LegalizeOp(Result.getValue(1));
2697       break;
2698     }
2699
2700     // Since rdcc produce two values, make sure to remember that we legalized
2701     // both of them.
2702     AddLegalizedOperand(SDOperand(Node, 0), Tmp1);
2703     AddLegalizedOperand(SDOperand(Node, 1), Tmp2);
2704     return Result;
2705
2706   case ISD::SELECT:
2707     switch (getTypeAction(Node->getOperand(0).getValueType())) {
2708     case Expand: assert(0 && "It's impossible to expand bools");
2709     case Legal:
2710       Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the condition.
2711       break;
2712     case Promote: {
2713       Tmp1 = PromoteOp(Node->getOperand(0));  // Promote the condition.
2714       // Make sure the condition is either zero or one.
2715       unsigned BitWidth = Tmp1.getValueSizeInBits();
2716       if (!DAG.MaskedValueIsZero(Tmp1,
2717                                  APInt::getHighBitsSet(BitWidth, BitWidth-1)))
2718         Tmp1 = DAG.getZeroExtendInReg(Tmp1, MVT::i1);
2719       break;
2720     }
2721     }
2722     Tmp2 = LegalizeOp(Node->getOperand(1));   // TrueVal
2723     Tmp3 = LegalizeOp(Node->getOperand(2));   // FalseVal
2724
2725     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
2726       
2727     switch (TLI.getOperationAction(ISD::SELECT, Tmp2.getValueType())) {
2728     default: assert(0 && "This action is not supported yet!");
2729     case TargetLowering::Legal: break;
2730     case TargetLowering::Custom: {
2731       Tmp1 = TLI.LowerOperation(Result, DAG);
2732       if (Tmp1.Val) Result = Tmp1;
2733       break;
2734     }
2735     case TargetLowering::Expand:
2736       if (Tmp1.getOpcode() == ISD::SETCC) {
2737         Result = DAG.getSelectCC(Tmp1.getOperand(0), Tmp1.getOperand(1), 
2738                               Tmp2, Tmp3,
2739                               cast<CondCodeSDNode>(Tmp1.getOperand(2))->get());
2740       } else {
2741         Result = DAG.getSelectCC(Tmp1, 
2742                                  DAG.getConstant(0, Tmp1.getValueType()),
2743                                  Tmp2, Tmp3, ISD::SETNE);
2744       }
2745       break;
2746     case TargetLowering::Promote: {
2747       MVT NVT =
2748         TLI.getTypeToPromoteTo(ISD::SELECT, Tmp2.getValueType());
2749       unsigned ExtOp, TruncOp;
2750       if (Tmp2.getValueType().isVector()) {
2751         ExtOp   = ISD::BIT_CONVERT;
2752         TruncOp = ISD::BIT_CONVERT;
2753       } else if (Tmp2.getValueType().isInteger()) {
2754         ExtOp   = ISD::ANY_EXTEND;
2755         TruncOp = ISD::TRUNCATE;
2756       } else {
2757         ExtOp   = ISD::FP_EXTEND;
2758         TruncOp = ISD::FP_ROUND;
2759       }
2760       // Promote each of the values to the new type.
2761       Tmp2 = DAG.getNode(ExtOp, NVT, Tmp2);
2762       Tmp3 = DAG.getNode(ExtOp, NVT, Tmp3);
2763       // Perform the larger operation, then round down.
2764       Result = DAG.getNode(ISD::SELECT, NVT, Tmp1, Tmp2,Tmp3);
2765       if (TruncOp != ISD::FP_ROUND)
2766         Result = DAG.getNode(TruncOp, Node->getValueType(0), Result);
2767       else
2768         Result = DAG.getNode(TruncOp, Node->getValueType(0), Result,
2769                              DAG.getIntPtrConstant(0));
2770       break;
2771     }
2772     }
2773     break;
2774   case ISD::SELECT_CC: {
2775     Tmp1 = Node->getOperand(0);               // LHS
2776     Tmp2 = Node->getOperand(1);               // RHS
2777     Tmp3 = LegalizeOp(Node->getOperand(2));   // True
2778     Tmp4 = LegalizeOp(Node->getOperand(3));   // False
2779     SDOperand CC = Node->getOperand(4);
2780     
2781     LegalizeSetCCOperands(Tmp1, Tmp2, CC);
2782     
2783     // If we didn't get both a LHS and RHS back from LegalizeSetCCOperands,
2784     // the LHS is a legal SETCC itself.  In this case, we need to compare
2785     // the result against zero to select between true and false values.
2786     if (Tmp2.Val == 0) {
2787       Tmp2 = DAG.getConstant(0, Tmp1.getValueType());
2788       CC = DAG.getCondCode(ISD::SETNE);
2789     }
2790     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3, Tmp4, CC);
2791
2792     // Everything is legal, see if we should expand this op or something.
2793     switch (TLI.getOperationAction(ISD::SELECT_CC, Tmp3.getValueType())) {
2794     default: assert(0 && "This action is not supported yet!");
2795     case TargetLowering::Legal: break;
2796     case TargetLowering::Custom:
2797       Tmp1 = TLI.LowerOperation(Result, DAG);
2798       if (Tmp1.Val) Result = Tmp1;
2799       break;
2800     }
2801     break;
2802   }
2803   case ISD::SETCC:
2804     Tmp1 = Node->getOperand(0);
2805     Tmp2 = Node->getOperand(1);
2806     Tmp3 = Node->getOperand(2);
2807     LegalizeSetCCOperands(Tmp1, Tmp2, Tmp3);
2808     
2809     // If we had to Expand the SetCC operands into a SELECT node, then it may 
2810     // not always be possible to return a true LHS & RHS.  In this case, just 
2811     // return the value we legalized, returned in the LHS
2812     if (Tmp2.Val == 0) {
2813       Result = Tmp1;
2814       break;
2815     }
2816
2817     switch (TLI.getOperationAction(ISD::SETCC, Tmp1.getValueType())) {
2818     default: assert(0 && "Cannot handle this action for SETCC yet!");
2819     case TargetLowering::Custom:
2820       isCustom = true;
2821       // FALLTHROUGH.
2822     case TargetLowering::Legal:
2823       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
2824       if (isCustom) {
2825         Tmp4 = TLI.LowerOperation(Result, DAG);
2826         if (Tmp4.Val) Result = Tmp4;
2827       }
2828       break;
2829     case TargetLowering::Promote: {
2830       // First step, figure out the appropriate operation to use.
2831       // Allow SETCC to not be supported for all legal data types
2832       // Mostly this targets FP
2833       MVT NewInTy = Node->getOperand(0).getValueType();
2834       MVT OldVT = NewInTy; OldVT = OldVT;
2835
2836       // Scan for the appropriate larger type to use.
2837       while (1) {
2838         NewInTy = (MVT::SimpleValueType)(NewInTy.getSimpleVT()+1);
2839
2840         assert(NewInTy.isInteger() == OldVT.isInteger() &&
2841                "Fell off of the edge of the integer world");
2842         assert(NewInTy.isFloatingPoint() == OldVT.isFloatingPoint() &&
2843                "Fell off of the edge of the floating point world");
2844           
2845         // If the target supports SETCC of this type, use it.
2846         if (TLI.isOperationLegal(ISD::SETCC, NewInTy))
2847           break;
2848       }
2849       if (NewInTy.isInteger())
2850         assert(0 && "Cannot promote Legal Integer SETCC yet");
2851       else {
2852         Tmp1 = DAG.getNode(ISD::FP_EXTEND, NewInTy, Tmp1);
2853         Tmp2 = DAG.getNode(ISD::FP_EXTEND, NewInTy, Tmp2);
2854       }
2855       Tmp1 = LegalizeOp(Tmp1);
2856       Tmp2 = LegalizeOp(Tmp2);
2857       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
2858       Result = LegalizeOp(Result);
2859       break;
2860     }
2861     case TargetLowering::Expand:
2862       // Expand a setcc node into a select_cc of the same condition, lhs, and
2863       // rhs that selects between const 1 (true) and const 0 (false).
2864       MVT VT = Node->getValueType(0);
2865       Result = DAG.getNode(ISD::SELECT_CC, VT, Tmp1, Tmp2, 
2866                            DAG.getConstant(1, VT), DAG.getConstant(0, VT),
2867                            Tmp3);
2868       break;
2869     }
2870     break;
2871   case ISD::VSETCC: {
2872     Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
2873     Tmp2 = LegalizeOp(Node->getOperand(1));   // RHS
2874     SDOperand CC = Node->getOperand(2);
2875     
2876     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, CC);
2877
2878     // Everything is legal, see if we should expand this op or something.
2879     switch (TLI.getOperationAction(ISD::VSETCC, Tmp1.getValueType())) {
2880     default: assert(0 && "This action is not supported yet!");
2881     case TargetLowering::Legal: break;
2882     case TargetLowering::Custom:
2883       Tmp1 = TLI.LowerOperation(Result, DAG);
2884       if (Tmp1.Val) Result = Tmp1;
2885       break;
2886     }
2887     break;
2888   }
2889
2890   case ISD::SHL_PARTS:
2891   case ISD::SRA_PARTS:
2892   case ISD::SRL_PARTS: {
2893     SmallVector<SDOperand, 8> Ops;
2894     bool Changed = false;
2895     for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
2896       Ops.push_back(LegalizeOp(Node->getOperand(i)));
2897       Changed |= Ops.back() != Node->getOperand(i);
2898     }
2899     if (Changed)
2900       Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
2901
2902     switch (TLI.getOperationAction(Node->getOpcode(),
2903                                    Node->getValueType(0))) {
2904     default: assert(0 && "This action is not supported yet!");
2905     case TargetLowering::Legal: break;
2906     case TargetLowering::Custom:
2907       Tmp1 = TLI.LowerOperation(Result, DAG);
2908       if (Tmp1.Val) {
2909         SDOperand Tmp2, RetVal(0, 0);
2910         for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i) {
2911           Tmp2 = LegalizeOp(Tmp1.getValue(i));
2912           AddLegalizedOperand(SDOperand(Node, i), Tmp2);
2913           if (i == Op.ResNo)
2914             RetVal = Tmp2;
2915         }
2916         assert(RetVal.Val && "Illegal result number");
2917         return RetVal;
2918       }
2919       break;
2920     }
2921
2922     // Since these produce multiple values, make sure to remember that we
2923     // legalized all of them.
2924     for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
2925       AddLegalizedOperand(SDOperand(Node, i), Result.getValue(i));
2926     return Result.getValue(Op.ResNo);
2927   }
2928
2929     // Binary operators
2930   case ISD::ADD:
2931   case ISD::SUB:
2932   case ISD::MUL:
2933   case ISD::MULHS:
2934   case ISD::MULHU:
2935   case ISD::UDIV:
2936   case ISD::SDIV:
2937   case ISD::AND:
2938   case ISD::OR:
2939   case ISD::XOR:
2940   case ISD::SHL:
2941   case ISD::SRL:
2942   case ISD::SRA:
2943   case ISD::FADD:
2944   case ISD::FSUB:
2945   case ISD::FMUL:
2946   case ISD::FDIV:
2947   case ISD::FPOW:
2948     Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
2949     switch (getTypeAction(Node->getOperand(1).getValueType())) {
2950     case Expand: assert(0 && "Not possible");
2951     case Legal:
2952       Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the RHS.
2953       break;
2954     case Promote:
2955       Tmp2 = PromoteOp(Node->getOperand(1));  // Promote the RHS.
2956       break;
2957     }
2958     
2959     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
2960       
2961     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
2962     default: assert(0 && "BinOp legalize operation not supported");
2963     case TargetLowering::Legal: break;
2964     case TargetLowering::Custom:
2965       Tmp1 = TLI.LowerOperation(Result, DAG);
2966       if (Tmp1.Val) Result = Tmp1;
2967       break;
2968     case TargetLowering::Expand: {
2969       MVT VT = Op.getValueType();
2970  
2971       // See if multiply or divide can be lowered using two-result operations.
2972       SDVTList VTs = DAG.getVTList(VT, VT);
2973       if (Node->getOpcode() == ISD::MUL) {
2974         // We just need the low half of the multiply; try both the signed
2975         // and unsigned forms. If the target supports both SMUL_LOHI and
2976         // UMUL_LOHI, form a preference by checking which forms of plain
2977         // MULH it supports.
2978         bool HasSMUL_LOHI = TLI.isOperationLegal(ISD::SMUL_LOHI, VT);
2979         bool HasUMUL_LOHI = TLI.isOperationLegal(ISD::UMUL_LOHI, VT);
2980         bool HasMULHS = TLI.isOperationLegal(ISD::MULHS, VT);
2981         bool HasMULHU = TLI.isOperationLegal(ISD::MULHU, VT);
2982         unsigned OpToUse = 0;
2983         if (HasSMUL_LOHI && !HasMULHS) {
2984           OpToUse = ISD::SMUL_LOHI;
2985         } else if (HasUMUL_LOHI && !HasMULHU) {
2986           OpToUse = ISD::UMUL_LOHI;
2987         } else if (HasSMUL_LOHI) {
2988           OpToUse = ISD::SMUL_LOHI;
2989         } else if (HasUMUL_LOHI) {
2990           OpToUse = ISD::UMUL_LOHI;
2991         }
2992         if (OpToUse) {
2993           Result = SDOperand(DAG.getNode(OpToUse, VTs, Tmp1, Tmp2).Val, 0);
2994           break;
2995         }
2996       }
2997       if (Node->getOpcode() == ISD::MULHS &&
2998           TLI.isOperationLegal(ISD::SMUL_LOHI, VT)) {
2999         Result = SDOperand(DAG.getNode(ISD::SMUL_LOHI, VTs, Tmp1, Tmp2).Val, 1);
3000         break;
3001       }
3002       if (Node->getOpcode() == ISD::MULHU && 
3003           TLI.isOperationLegal(ISD::UMUL_LOHI, VT)) {
3004         Result = SDOperand(DAG.getNode(ISD::UMUL_LOHI, VTs, Tmp1, Tmp2).Val, 1);
3005         break;
3006       }
3007       if (Node->getOpcode() == ISD::SDIV &&
3008           TLI.isOperationLegal(ISD::SDIVREM, VT)) {
3009         Result = SDOperand(DAG.getNode(ISD::SDIVREM, VTs, Tmp1, Tmp2).Val, 0);
3010         break;
3011       }
3012       if (Node->getOpcode() == ISD::UDIV &&
3013           TLI.isOperationLegal(ISD::UDIVREM, VT)) {
3014         Result = SDOperand(DAG.getNode(ISD::UDIVREM, VTs, Tmp1, Tmp2).Val, 0);
3015         break;
3016       }
3017
3018       // Check to see if we have a libcall for this operator.
3019       RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
3020       bool isSigned = false;
3021       switch (Node->getOpcode()) {
3022       case ISD::UDIV:
3023       case ISD::SDIV:
3024         if (VT == MVT::i32) {
3025           LC = Node->getOpcode() == ISD::UDIV
3026             ? RTLIB::UDIV_I32 : RTLIB::SDIV_I32;
3027           isSigned = Node->getOpcode() == ISD::SDIV;
3028         }
3029         break;
3030       case ISD::FPOW:
3031         LC = GetFPLibCall(VT, RTLIB::POW_F32, RTLIB::POW_F64, RTLIB::POW_F80,
3032                           RTLIB::POW_PPCF128);
3033         break;
3034       default: break;
3035       }
3036       if (LC != RTLIB::UNKNOWN_LIBCALL) {
3037         SDOperand Dummy;
3038         Result = ExpandLibCall(LC, Node, isSigned, Dummy);
3039         break;
3040       }
3041
3042       assert(Node->getValueType(0).isVector() &&
3043              "Cannot expand this binary operator!");
3044       // Expand the operation into a bunch of nasty scalar code.
3045       Result = LegalizeOp(UnrollVectorOp(Op));
3046       break;
3047     }
3048     case TargetLowering::Promote: {
3049       switch (Node->getOpcode()) {
3050       default:  assert(0 && "Do not know how to promote this BinOp!");
3051       case ISD::AND:
3052       case ISD::OR:
3053       case ISD::XOR: {
3054         MVT OVT = Node->getValueType(0);
3055         MVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
3056         assert(OVT.isVector() && "Cannot promote this BinOp!");
3057         // Bit convert each of the values to the new type.
3058         Tmp1 = DAG.getNode(ISD::BIT_CONVERT, NVT, Tmp1);
3059         Tmp2 = DAG.getNode(ISD::BIT_CONVERT, NVT, Tmp2);
3060         Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
3061         // Bit convert the result back the original type.
3062         Result = DAG.getNode(ISD::BIT_CONVERT, OVT, Result);
3063         break;
3064       }
3065       }
3066     }
3067     }
3068     break;
3069     
3070   case ISD::SMUL_LOHI:
3071   case ISD::UMUL_LOHI:
3072   case ISD::SDIVREM:
3073   case ISD::UDIVREM:
3074     // These nodes will only be produced by target-specific lowering, so
3075     // they shouldn't be here if they aren't legal.
3076     assert(TLI.isOperationLegal(Node->getOpcode(), Node->getValueType(0)) &&
3077            "This must be legal!");
3078
3079     Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
3080     Tmp2 = LegalizeOp(Node->getOperand(1));   // RHS
3081     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
3082     break;
3083
3084   case ISD::FCOPYSIGN:  // FCOPYSIGN does not require LHS/RHS to match type!
3085     Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
3086     switch (getTypeAction(Node->getOperand(1).getValueType())) {
3087       case Expand: assert(0 && "Not possible");
3088       case Legal:
3089         Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the RHS.
3090         break;
3091       case Promote:
3092         Tmp2 = PromoteOp(Node->getOperand(1));  // Promote the RHS.
3093         break;
3094     }
3095       
3096     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
3097     
3098     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
3099     default: assert(0 && "Operation not supported");
3100     case TargetLowering::Custom:
3101       Tmp1 = TLI.LowerOperation(Result, DAG);
3102       if (Tmp1.Val) Result = Tmp1;
3103       break;
3104     case TargetLowering::Legal: break;
3105     case TargetLowering::Expand: {
3106       // If this target supports fabs/fneg natively and select is cheap,
3107       // do this efficiently.
3108       if (!TLI.isSelectExpensive() &&
3109           TLI.getOperationAction(ISD::FABS, Tmp1.getValueType()) ==
3110           TargetLowering::Legal &&
3111           TLI.getOperationAction(ISD::FNEG, Tmp1.getValueType()) ==
3112           TargetLowering::Legal) {
3113         // Get the sign bit of the RHS.
3114         MVT IVT =
3115           Tmp2.getValueType() == MVT::f32 ? MVT::i32 : MVT::i64;
3116         SDOperand SignBit = DAG.getNode(ISD::BIT_CONVERT, IVT, Tmp2);
3117         SignBit = DAG.getSetCC(TLI.getSetCCResultType(SignBit),
3118                                SignBit, DAG.getConstant(0, IVT), ISD::SETLT);
3119         // Get the absolute value of the result.
3120         SDOperand AbsVal = DAG.getNode(ISD::FABS, Tmp1.getValueType(), Tmp1);
3121         // Select between the nabs and abs value based on the sign bit of
3122         // the input.
3123         Result = DAG.getNode(ISD::SELECT, AbsVal.getValueType(), SignBit,
3124                              DAG.getNode(ISD::FNEG, AbsVal.getValueType(), 
3125                                          AbsVal),
3126                              AbsVal);
3127         Result = LegalizeOp(Result);
3128         break;
3129       }
3130       
3131       // Otherwise, do bitwise ops!
3132       MVT NVT =
3133         Node->getValueType(0) == MVT::f32 ? MVT::i32 : MVT::i64;
3134       Result = ExpandFCOPYSIGNToBitwiseOps(Node, NVT, DAG, TLI);
3135       Result = DAG.getNode(ISD::BIT_CONVERT, Node->getValueType(0), Result);
3136       Result = LegalizeOp(Result);
3137       break;
3138     }
3139     }
3140     break;
3141     
3142   case ISD::ADDC:
3143   case ISD::SUBC:
3144     Tmp1 = LegalizeOp(Node->getOperand(0));
3145     Tmp2 = LegalizeOp(Node->getOperand(1));
3146     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
3147     // Since this produces two values, make sure to remember that we legalized
3148     // both of them.
3149     AddLegalizedOperand(SDOperand(Node, 0), Result.getValue(0));
3150     AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
3151     return Result;
3152
3153   case ISD::ADDE:
3154   case ISD::SUBE:
3155     Tmp1 = LegalizeOp(Node->getOperand(0));
3156     Tmp2 = LegalizeOp(Node->getOperand(1));
3157     Tmp3 = LegalizeOp(Node->getOperand(2));
3158     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
3159     // Since this produces two values, make sure to remember that we legalized
3160     // both of them.
3161     AddLegalizedOperand(SDOperand(Node, 0), Result.getValue(0));
3162     AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
3163     return Result;
3164     
3165   case ISD::BUILD_PAIR: {
3166     MVT PairTy = Node->getValueType(0);
3167     // TODO: handle the case where the Lo and Hi operands are not of legal type
3168     Tmp1 = LegalizeOp(Node->getOperand(0));   // Lo
3169     Tmp2 = LegalizeOp(Node->getOperand(1));   // Hi
3170     switch (TLI.getOperationAction(ISD::BUILD_PAIR, PairTy)) {
3171     case TargetLowering::Promote:
3172     case TargetLowering::Custom:
3173       assert(0 && "Cannot promote/custom this yet!");
3174     case TargetLowering::Legal:
3175       if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
3176         Result = DAG.getNode(ISD::BUILD_PAIR, PairTy, Tmp1, Tmp2);
3177       break;
3178     case TargetLowering::Expand:
3179       Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, PairTy, Tmp1);
3180       Tmp2 = DAG.getNode(ISD::ANY_EXTEND, PairTy, Tmp2);
3181       Tmp2 = DAG.getNode(ISD::SHL, PairTy, Tmp2,
3182                          DAG.getConstant(PairTy.getSizeInBits()/2,
3183                                          TLI.getShiftAmountTy()));
3184       Result = DAG.getNode(ISD::OR, PairTy, Tmp1, Tmp2);
3185       break;
3186     }
3187     break;
3188   }
3189
3190   case ISD::UREM:
3191   case ISD::SREM:
3192   case ISD::FREM:
3193     Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
3194     Tmp2 = LegalizeOp(Node->getOperand(1));   // RHS
3195
3196     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
3197     case TargetLowering::Promote: assert(0 && "Cannot promote this yet!");
3198     case TargetLowering::Custom:
3199       isCustom = true;
3200       // FALLTHROUGH
3201     case TargetLowering::Legal:
3202       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
3203       if (isCustom) {
3204         Tmp1 = TLI.LowerOperation(Result, DAG);
3205         if (Tmp1.Val) Result = Tmp1;
3206       }
3207       break;
3208     case TargetLowering::Expand: {
3209       unsigned DivOpc= (Node->getOpcode() == ISD::UREM) ? ISD::UDIV : ISD::SDIV;
3210       bool isSigned = DivOpc == ISD::SDIV;
3211       MVT VT = Node->getValueType(0);
3212  
3213       // See if remainder can be lowered using two-result operations.
3214       SDVTList VTs = DAG.getVTList(VT, VT);
3215       if (Node->getOpcode() == ISD::SREM &&
3216           TLI.isOperationLegal(ISD::SDIVREM, VT)) {
3217         Result = SDOperand(DAG.getNode(ISD::SDIVREM, VTs, Tmp1, Tmp2).Val, 1);
3218         break;
3219       }
3220       if (Node->getOpcode() == ISD::UREM &&
3221           TLI.isOperationLegal(ISD::UDIVREM, VT)) {
3222         Result = SDOperand(DAG.getNode(ISD::UDIVREM, VTs, Tmp1, Tmp2).Val, 1);
3223         break;
3224       }
3225
3226       if (VT.isInteger()) {
3227         if (TLI.getOperationAction(DivOpc, VT) ==
3228             TargetLowering::Legal) {
3229           // X % Y -> X-X/Y*Y
3230           Result = DAG.getNode(DivOpc, VT, Tmp1, Tmp2);
3231           Result = DAG.getNode(ISD::MUL, VT, Result, Tmp2);
3232           Result = DAG.getNode(ISD::SUB, VT, Tmp1, Result);
3233         } else if (VT.isVector()) {
3234           Result = LegalizeOp(UnrollVectorOp(Op));
3235         } else {
3236           assert(VT == MVT::i32 &&
3237                  "Cannot expand this binary operator!");
3238           RTLIB::Libcall LC = Node->getOpcode() == ISD::UREM
3239             ? RTLIB::UREM_I32 : RTLIB::SREM_I32;
3240           SDOperand Dummy;
3241           Result = ExpandLibCall(LC, Node, isSigned, Dummy);
3242         }
3243       } else {
3244         assert(VT.isFloatingPoint() &&
3245                "remainder op must have integer or floating-point type");
3246         if (VT.isVector()) {
3247           Result = LegalizeOp(UnrollVectorOp(Op));
3248         } else {
3249           // Floating point mod -> fmod libcall.
3250           RTLIB::Libcall LC = GetFPLibCall(VT, RTLIB::REM_F32, RTLIB::REM_F64,
3251                                            RTLIB::REM_F80, RTLIB::REM_PPCF128);
3252           SDOperand Dummy;
3253           Result = ExpandLibCall(LC, Node, false/*sign irrelevant*/, Dummy);
3254         }
3255       }
3256       break;
3257     }
3258     }
3259     break;
3260   case ISD::VAARG: {
3261     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
3262     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
3263
3264     MVT VT = Node->getValueType(0);
3265     switch (TLI.getOperationAction(Node->getOpcode(), MVT::Other)) {
3266     default: assert(0 && "This action is not supported yet!");
3267     case TargetLowering::Custom:
3268       isCustom = true;
3269       // FALLTHROUGH
3270     case TargetLowering::Legal:
3271       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
3272       Result = Result.getValue(0);
3273       Tmp1 = Result.getValue(1);
3274
3275       if (isCustom) {
3276         Tmp2 = TLI.LowerOperation(Result, DAG);
3277         if (Tmp2.Val) {
3278           Result = LegalizeOp(Tmp2);
3279           Tmp1 = LegalizeOp(Tmp2.getValue(1));
3280         }
3281       }
3282       break;
3283     case TargetLowering::Expand: {
3284       const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
3285       SDOperand VAList = DAG.getLoad(TLI.getPointerTy(), Tmp1, Tmp2, V, 0);
3286       // Increment the pointer, VAList, to the next vaarg
3287       Tmp3 = DAG.getNode(ISD::ADD, TLI.getPointerTy(), VAList, 
3288                          DAG.getConstant(VT.getSizeInBits()/8,
3289                                          TLI.getPointerTy()));
3290       // Store the incremented VAList to the legalized pointer
3291       Tmp3 = DAG.getStore(VAList.getValue(1), Tmp3, Tmp2, V, 0);
3292       // Load the actual argument out of the pointer VAList
3293       Result = DAG.getLoad(VT, Tmp3, VAList, NULL, 0);
3294       Tmp1 = LegalizeOp(Result.getValue(1));
3295       Result = LegalizeOp(Result);
3296       break;
3297     }
3298     }
3299     // Since VAARG produces two values, make sure to remember that we 
3300     // legalized both of them.
3301     AddLegalizedOperand(SDOperand(Node, 0), Result);
3302     AddLegalizedOperand(SDOperand(Node, 1), Tmp1);
3303     return Op.ResNo ? Tmp1 : Result;
3304   }
3305     
3306   case ISD::VACOPY: 
3307     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
3308     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the dest pointer.
3309     Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the source pointer.
3310
3311     switch (TLI.getOperationAction(ISD::VACOPY, MVT::Other)) {
3312     default: assert(0 && "This action is not supported yet!");
3313     case TargetLowering::Custom:
3314       isCustom = true;
3315       // FALLTHROUGH
3316     case TargetLowering::Legal:
3317       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3,
3318                                       Node->getOperand(3), Node->getOperand(4));
3319       if (isCustom) {
3320         Tmp1 = TLI.LowerOperation(Result, DAG);
3321         if (Tmp1.Val) Result = Tmp1;
3322       }
3323       break;
3324     case TargetLowering::Expand:
3325       // This defaults to loading a pointer from the input and storing it to the
3326       // output, returning the chain.
3327       const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
3328       const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
3329       Tmp4 = DAG.getLoad(TLI.getPointerTy(), Tmp1, Tmp3, VS, 0);
3330       Result = DAG.getStore(Tmp4.getValue(1), Tmp4, Tmp2, VD, 0);
3331       break;
3332     }
3333     break;
3334
3335   case ISD::VAEND: 
3336     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
3337     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
3338
3339     switch (TLI.getOperationAction(ISD::VAEND, MVT::Other)) {
3340     default: assert(0 && "This action is not supported yet!");
3341     case TargetLowering::Custom:
3342       isCustom = true;
3343       // FALLTHROUGH
3344     case TargetLowering::Legal:
3345       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
3346       if (isCustom) {
3347         Tmp1 = TLI.LowerOperation(Tmp1, DAG);
3348         if (Tmp1.Val) Result = Tmp1;
3349       }
3350       break;
3351     case TargetLowering::Expand:
3352       Result = Tmp1; // Default to a no-op, return the chain
3353       break;
3354     }
3355     break;
3356     
3357   case ISD::VASTART: 
3358     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
3359     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
3360
3361     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
3362     
3363     switch (TLI.getOperationAction(ISD::VASTART, MVT::Other)) {
3364     default: assert(0 && "This action is not supported yet!");
3365     case TargetLowering::Legal: break;
3366     case TargetLowering::Custom:
3367       Tmp1 = TLI.LowerOperation(Result, DAG);
3368       if (Tmp1.Val) Result = Tmp1;
3369       break;
3370     }
3371     break;
3372     
3373   case ISD::ROTL:
3374   case ISD::ROTR:
3375     Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
3376     Tmp2 = LegalizeOp(Node->getOperand(1));   // RHS
3377     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
3378     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
3379     default:
3380       assert(0 && "ROTL/ROTR legalize operation not supported");
3381       break;
3382     case TargetLowering::Legal:
3383       break;
3384     case TargetLowering::Custom:
3385       Tmp1 = TLI.LowerOperation(Result, DAG);
3386       if (Tmp1.Val) Result = Tmp1;
3387       break;
3388     case TargetLowering::Promote:
3389       assert(0 && "Do not know how to promote ROTL/ROTR");
3390       break;
3391     case TargetLowering::Expand:
3392       assert(0 && "Do not know how to expand ROTL/ROTR");
3393       break;
3394     }
3395     break;
3396     
3397   case ISD::BSWAP:
3398     Tmp1 = LegalizeOp(Node->getOperand(0));   // Op
3399     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
3400     case TargetLowering::Custom:
3401       assert(0 && "Cannot custom legalize this yet!");
3402     case TargetLowering::Legal:
3403       Result = DAG.UpdateNodeOperands(Result, Tmp1);
3404       break;
3405     case TargetLowering::Promote: {
3406       MVT OVT = Tmp1.getValueType();
3407       MVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
3408       unsigned DiffBits = NVT.getSizeInBits() - OVT.getSizeInBits();
3409
3410       Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, NVT, Tmp1);
3411       Tmp1 = DAG.getNode(ISD::BSWAP, NVT, Tmp1);
3412       Result = DAG.getNode(ISD::SRL, NVT, Tmp1,
3413                            DAG.getConstant(DiffBits, TLI.getShiftAmountTy()));
3414       break;
3415     }
3416     case TargetLowering::Expand:
3417       Result = ExpandBSWAP(Tmp1);
3418       break;
3419     }
3420     break;
3421     
3422   case ISD::CTPOP:
3423   case ISD::CTTZ:
3424   case ISD::CTLZ:
3425     Tmp1 = LegalizeOp(Node->getOperand(0));   // Op
3426     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
3427     case TargetLowering::Custom:
3428     case TargetLowering::Legal:
3429       Result = DAG.UpdateNodeOperands(Result, Tmp1);
3430       if (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0)) ==
3431           TargetLowering::Custom) {
3432         Tmp1 = TLI.LowerOperation(Result, DAG);
3433         if (Tmp1.Val) {
3434           Result = Tmp1;
3435         }
3436       }
3437       break;
3438     case TargetLowering::Promote: {
3439       MVT OVT = Tmp1.getValueType();
3440       MVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
3441
3442       // Zero extend the argument.
3443       Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, NVT, Tmp1);
3444       // Perform the larger operation, then subtract if needed.
3445       Tmp1 = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1);
3446       switch (Node->getOpcode()) {
3447       case ISD::CTPOP:
3448         Result = Tmp1;
3449         break;
3450       case ISD::CTTZ:
3451         //if Tmp1 == sizeinbits(NVT) then Tmp1 = sizeinbits(Old VT)
3452         Tmp2 = DAG.getSetCC(TLI.getSetCCResultType(Tmp1), Tmp1,
3453                             DAG.getConstant(NVT.getSizeInBits(), NVT),
3454                             ISD::SETEQ);
3455         Result = DAG.getNode(ISD::SELECT, NVT, Tmp2,
3456                              DAG.getConstant(OVT.getSizeInBits(), NVT), Tmp1);
3457         break;
3458       case ISD::CTLZ:
3459         // Tmp1 = Tmp1 - (sizeinbits(NVT) - sizeinbits(Old VT))
3460         Result = DAG.getNode(ISD::SUB, NVT, Tmp1,
3461                              DAG.getConstant(NVT.getSizeInBits() -
3462                                              OVT.getSizeInBits(), NVT));
3463         break;
3464       }
3465       break;
3466     }
3467     case TargetLowering::Expand:
3468       Result = ExpandBitCount(Node->getOpcode(), Tmp1);
3469       break;
3470     }
3471     break;
3472
3473     // Unary operators
3474   case ISD::FABS:
3475   case ISD::FNEG:
3476   case ISD::FSQRT:
3477   case ISD::FSIN:
3478   case ISD::FCOS:
3479     Tmp1 = LegalizeOp(Node->getOperand(0));
3480     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
3481     case TargetLowering::Promote:
3482     case TargetLowering::Custom:
3483      isCustom = true;
3484      // FALLTHROUGH
3485     case TargetLowering::Legal:
3486       Result = DAG.UpdateNodeOperands(Result, Tmp1);
3487       if (isCustom) {
3488         Tmp1 = TLI.LowerOperation(Result, DAG);
3489         if (Tmp1.Val) Result = Tmp1;
3490       }
3491       break;
3492     case TargetLowering::Expand:
3493       switch (Node->getOpcode()) {
3494       default: assert(0 && "Unreachable!");
3495       case ISD::FNEG:
3496         // Expand Y = FNEG(X) ->  Y = SUB -0.0, X
3497         Tmp2 = DAG.getConstantFP(-0.0, Node->getValueType(0));
3498         Result = DAG.getNode(ISD::FSUB, Node->getValueType(0), Tmp2, Tmp1);
3499         break;
3500       case ISD::FABS: {
3501         // Expand Y = FABS(X) -> Y = (X >u 0.0) ? X : fneg(X).
3502         MVT VT = Node->getValueType(0);
3503         Tmp2 = DAG.getConstantFP(0.0, VT);
3504         Tmp2 = DAG.getSetCC(TLI.getSetCCResultType(Tmp1), Tmp1, Tmp2,
3505                             ISD::SETUGT);
3506         Tmp3 = DAG.getNode(ISD::FNEG, VT, Tmp1);
3507         Result = DAG.getNode(ISD::SELECT, VT, Tmp2, Tmp1, Tmp3);
3508         break;
3509       }
3510       case ISD::FSQRT:
3511       case ISD::FSIN:
3512       case ISD::FCOS: {
3513         MVT VT = Node->getValueType(0);
3514
3515         // Expand unsupported unary vector operators by unrolling them.
3516         if (VT.isVector()) {
3517           Result = LegalizeOp(UnrollVectorOp(Op));
3518           break;
3519         }
3520
3521         RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
3522         switch(Node->getOpcode()) {
3523         case ISD::FSQRT:
3524           LC = GetFPLibCall(VT, RTLIB::SQRT_F32, RTLIB::SQRT_F64,
3525                             RTLIB::SQRT_F80, RTLIB::SQRT_PPCF128);
3526           break;
3527         case ISD::FSIN:
3528           LC = GetFPLibCall(VT, RTLIB::SIN_F32, RTLIB::SIN_F64,
3529                             RTLIB::SIN_F80, RTLIB::SIN_PPCF128);
3530           break;
3531         case ISD::FCOS:
3532           LC = GetFPLibCall(VT, RTLIB::COS_F32, RTLIB::COS_F64,
3533                             RTLIB::COS_F80, RTLIB::COS_PPCF128);
3534           break;
3535         default: assert(0 && "Unreachable!");
3536         }
3537         SDOperand Dummy;
3538         Result = ExpandLibCall(LC, Node, false/*sign irrelevant*/, Dummy);
3539         break;
3540       }
3541       }
3542       break;
3543     }
3544     break;
3545   case ISD::FPOWI: {
3546     MVT VT = Node->getValueType(0);
3547
3548     // Expand unsupported unary vector operators by unrolling them.
3549     if (VT.isVector()) {
3550       Result = LegalizeOp(UnrollVectorOp(Op));
3551       break;
3552     }
3553
3554     // We always lower FPOWI into a libcall.  No target support for it yet.
3555     RTLIB::Libcall LC = GetFPLibCall(VT, RTLIB::POWI_F32, RTLIB::POWI_F64,
3556                                      RTLIB::POWI_F80, RTLIB::POWI_PPCF128);
3557     SDOperand Dummy;
3558     Result = ExpandLibCall(LC, Node, false/*sign irrelevant*/, Dummy);
3559     break;
3560   }
3561   case ISD::BIT_CONVERT:
3562     if (!isTypeLegal(Node->getOperand(0).getValueType())) {
3563       Result = EmitStackConvert(Node->getOperand(0), Node->getValueType(0),
3564                                 Node->getValueType(0));
3565     } else if (Op.getOperand(0).getValueType().isVector()) {
3566       // The input has to be a vector type, we have to either scalarize it, pack
3567       // it, or convert it based on whether the input vector type is legal.
3568       SDNode *InVal = Node->getOperand(0).Val;
3569       int InIx = Node->getOperand(0).ResNo;
3570       unsigned NumElems = InVal->getValueType(InIx).getVectorNumElements();
3571       MVT EVT = InVal->getValueType(InIx).getVectorElementType();
3572     
3573       // Figure out if there is a simple type corresponding to this Vector
3574       // type.  If so, convert to the vector type.
3575       MVT TVT = MVT::getVectorVT(EVT, NumElems);
3576       if (TLI.isTypeLegal(TVT)) {
3577         // Turn this into a bit convert of the vector input.
3578         Result = DAG.getNode(ISD::BIT_CONVERT, Node->getValueType(0), 
3579                              LegalizeOp(Node->getOperand(0)));
3580         break;
3581       } else if (NumElems == 1) {
3582         // Turn this into a bit convert of the scalar input.
3583         Result = DAG.getNode(ISD::BIT_CONVERT, Node->getValueType(0), 
3584                              ScalarizeVectorOp(Node->getOperand(0)));
3585         break;
3586       } else {
3587         // FIXME: UNIMP!  Store then reload
3588         assert(0 && "Cast from unsupported vector type not implemented yet!");
3589       }
3590     } else {
3591       switch (TLI.getOperationAction(ISD::BIT_CONVERT,
3592                                      Node->getOperand(0).getValueType())) {
3593       default: assert(0 && "Unknown operation action!");
3594       case TargetLowering::Expand:
3595         Result = EmitStackConvert(Node->getOperand(0), Node->getValueType(0),
3596                                   Node->getValueType(0));
3597         break;
3598       case TargetLowering::Legal:
3599         Tmp1 = LegalizeOp(Node->getOperand(0));
3600         Result = DAG.UpdateNodeOperands(Result, Tmp1);
3601         break;
3602       }
3603     }
3604     break;
3605       
3606     // Conversion operators.  The source and destination have different types.
3607   case ISD::SINT_TO_FP:
3608   case ISD::UINT_TO_FP: {
3609     bool isSigned = Node->getOpcode() == ISD::SINT_TO_FP;
3610     switch (getTypeAction(Node->getOperand(0).getValueType())) {
3611     case Legal:
3612       switch (TLI.getOperationAction(Node->getOpcode(),
3613                                      Node->getOperand(0).getValueType())) {
3614       default: assert(0 && "Unknown operation action!");
3615       case TargetLowering::Custom:
3616         isCustom = true;
3617         // FALLTHROUGH
3618       case TargetLowering::Legal:
3619         Tmp1 = LegalizeOp(Node->getOperand(0));
3620         Result = DAG.UpdateNodeOperands(Result, Tmp1);
3621         if (isCustom) {
3622           Tmp1 = TLI.LowerOperation(Result, DAG);
3623           if (Tmp1.Val) Result = Tmp1;
3624         }
3625         break;
3626       case TargetLowering::Expand:
3627         Result = ExpandLegalINT_TO_FP(isSigned,
3628                                       LegalizeOp(Node->getOperand(0)),
3629                                       Node->getValueType(0));
3630         break;
3631       case TargetLowering::Promote:
3632         Result = PromoteLegalINT_TO_FP(LegalizeOp(Node->getOperand(0)),
3633                                        Node->getValueType(0),
3634                                        isSigned);
3635         break;
3636       }
3637       break;
3638     case Expand:
3639       Result = ExpandIntToFP(Node->getOpcode() == ISD::SINT_TO_FP,
3640                              Node->getValueType(0), Node->getOperand(0));
3641       break;
3642     case Promote:
3643       Tmp1 = PromoteOp(Node->getOperand(0));
3644       if (isSigned) {
3645         Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, Tmp1.getValueType(),
3646                  Tmp1, DAG.getValueType(Node->getOperand(0).getValueType()));
3647       } else {
3648         Tmp1 = DAG.getZeroExtendInReg(Tmp1,
3649                                       Node->getOperand(0).getValueType());
3650       }
3651       Result = DAG.UpdateNodeOperands(Result, Tmp1);
3652       Result = LegalizeOp(Result);  // The 'op' is not necessarily legal!
3653       break;
3654     }
3655     break;
3656   }
3657   case ISD::TRUNCATE:
3658     switch (getTypeAction(Node->getOperand(0).getValueType())) {
3659     case Legal:
3660       Tmp1 = LegalizeOp(Node->getOperand(0));
3661       Result = DAG.UpdateNodeOperands(Result, Tmp1);
3662       break;
3663     case Expand:
3664       ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
3665
3666       // Since the result is legal, we should just be able to truncate the low
3667       // part of the source.
3668       Result = DAG.getNode(ISD::TRUNCATE, Node->getValueType(0), Tmp1);
3669       break;
3670     case Promote:
3671       Result = PromoteOp(Node->getOperand(0));
3672       Result = DAG.getNode(ISD::TRUNCATE, Op.getValueType(), Result);
3673       break;
3674     }
3675     break;
3676
3677   case ISD::FP_TO_SINT:
3678   case ISD::FP_TO_UINT:
3679     switch (getTypeAction(Node->getOperand(0).getValueType())) {
3680     case Legal:
3681       Tmp1 = LegalizeOp(Node->getOperand(0));
3682
3683       switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))){
3684       default: assert(0 && "Unknown operation action!");
3685       case TargetLowering::Custom:
3686         isCustom = true;
3687         // FALLTHROUGH
3688       case TargetLowering::Legal:
3689         Result = DAG.UpdateNodeOperands(Result, Tmp1);
3690         if (isCustom) {
3691           Tmp1 = TLI.LowerOperation(Result, DAG);
3692           if (Tmp1.Val) Result = Tmp1;
3693         }
3694         break;
3695       case TargetLowering::Promote:
3696         Result = PromoteLegalFP_TO_INT(Tmp1, Node->getValueType(0),
3697                                        Node->getOpcode() == ISD::FP_TO_SINT);
3698         break;
3699       case TargetLowering::Expand:
3700         if (Node->getOpcode() == ISD::FP_TO_UINT) {
3701           SDOperand True, False;
3702           MVT VT =  Node->getOperand(0).getValueType();
3703           MVT NVT = Node->getValueType(0);
3704           const uint64_t zero[] = {0, 0};
3705           APFloat apf = APFloat(APInt(VT.getSizeInBits(), 2, zero));
3706           APInt x = APInt::getSignBit(NVT.getSizeInBits());
3707           (void)apf.convertFromAPInt(x, false, APFloat::rmNearestTiesToEven);
3708           Tmp2 = DAG.getConstantFP(apf, VT);
3709           Tmp3 = DAG.getSetCC(TLI.getSetCCResultType(Node->getOperand(0)),
3710                             Node->getOperand(0), Tmp2, ISD::SETLT);
3711           True = DAG.getNode(ISD::FP_TO_SINT, NVT, Node->getOperand(0));
3712           False = DAG.getNode(ISD::FP_TO_SINT, NVT,
3713                               DAG.getNode(ISD::FSUB, VT, Node->getOperand(0),
3714                                           Tmp2));
3715           False = DAG.getNode(ISD::XOR, NVT, False, 
3716                               DAG.getConstant(x, NVT));
3717           Result = DAG.getNode(ISD::SELECT, NVT, Tmp3, True, False);
3718           break;
3719         } else {
3720           assert(0 && "Do not know how to expand FP_TO_SINT yet!");
3721         }
3722         break;
3723       }
3724       break;
3725     case Expand: {
3726       MVT VT = Op.getValueType();
3727       MVT OVT = Node->getOperand(0).getValueType();
3728       // Convert ppcf128 to i32
3729       if (OVT == MVT::ppcf128 && VT == MVT::i32) {
3730         if (Node->getOpcode() == ISD::FP_TO_SINT) {
3731           Result = DAG.getNode(ISD::FP_ROUND_INREG, MVT::ppcf128, 
3732                                Node->getOperand(0), DAG.getValueType(MVT::f64));
3733           Result = DAG.getNode(ISD::FP_ROUND, MVT::f64, Result, 
3734                                DAG.getIntPtrConstant(1));
3735           Result = DAG.getNode(ISD::FP_TO_SINT, VT, Result);
3736         } else {
3737           const uint64_t TwoE31[] = {0x41e0000000000000LL, 0};
3738           APFloat apf = APFloat(APInt(128, 2, TwoE31));
3739           Tmp2 = DAG.getConstantFP(apf, OVT);
3740           //  X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X
3741           // FIXME: generated code sucks.
3742           Result = DAG.getNode(ISD::SELECT_CC, VT, Node->getOperand(0), Tmp2,
3743                                DAG.getNode(ISD::ADD, MVT::i32,
3744                                  DAG.getNode(ISD::FP_TO_SINT, VT,
3745                                    DAG.getNode(ISD::FSUB, OVT,
3746                                                  Node->getOperand(0), Tmp2)),
3747                                  DAG.getConstant(0x80000000, MVT::i32)),
3748                                DAG.getNode(ISD::FP_TO_SINT, VT, 
3749                                            Node->getOperand(0)),
3750                                DAG.getCondCode(ISD::SETGE));
3751         }
3752         break;
3753       }
3754       // Convert f32 / f64 to i32 / i64 / i128.
3755       RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
3756       switch (Node->getOpcode()) {
3757       case ISD::FP_TO_SINT: {
3758         if (VT == MVT::i32) {
3759           if (OVT == MVT::f32)
3760             LC = RTLIB::FPTOSINT_F32_I32;
3761           else if (OVT == MVT::f64)
3762             LC = RTLIB::FPTOSINT_F64_I32;
3763           else
3764             assert(0 && "Unexpected i32-to-fp conversion!");
3765         } else if (VT == MVT::i64) {
3766           if (OVT == MVT::f32)
3767             LC = RTLIB::FPTOSINT_F32_I64;
3768           else if (OVT == MVT::f64)
3769             LC = RTLIB::FPTOSINT_F64_I64;
3770           else if (OVT == MVT::f80)
3771             LC = RTLIB::FPTOSINT_F80_I64;
3772           else if (OVT == MVT::ppcf128)
3773             LC = RTLIB::FPTOSINT_PPCF128_I64;
3774           else
3775             assert(0 && "Unexpected i64-to-fp conversion!");
3776         } else if (VT == MVT::i128) {
3777           if (OVT == MVT::f32)
3778             LC = RTLIB::FPTOSINT_F32_I128;
3779           else if (OVT == MVT::f64)
3780             LC = RTLIB::FPTOSINT_F64_I128;
3781           else if (OVT == MVT::f80)
3782             LC = RTLIB::FPTOSINT_F80_I128;
3783           else if (OVT == MVT::ppcf128)
3784             LC = RTLIB::FPTOSINT_PPCF128_I128;
3785           else
3786             assert(0 && "Unexpected i128-to-fp conversion!");
3787         } else {
3788           assert(0 && "Unexpectd int-to-fp conversion!");
3789         }
3790         break;
3791       }
3792       case ISD::FP_TO_UINT: {
3793         if (VT == MVT::i32) {
3794           if (OVT == MVT::f32)
3795             LC = RTLIB::FPTOUINT_F32_I32;
3796           else if (OVT == MVT::f64)
3797             LC = RTLIB::FPTOUINT_F64_I32;
3798           else if (OVT == MVT::f80)
3799             LC = RTLIB::FPTOUINT_F80_I32;
3800           else
3801             assert(0 && "Unexpected i32-to-fp conversion!");
3802         } else if (VT == MVT::i64) {
3803           if (OVT == MVT::f32)
3804             LC = RTLIB::FPTOUINT_F32_I64;
3805           else if (OVT == MVT::f64)
3806             LC = RTLIB::FPTOUINT_F64_I64;
3807           else if (OVT == MVT::f80)
3808             LC = RTLIB::FPTOUINT_F80_I64;
3809           else if (OVT == MVT::ppcf128)
3810             LC = RTLIB::FPTOUINT_PPCF128_I64;
3811           else
3812             assert(0 && "Unexpected i64-to-fp conversion!");
3813         } else if (VT == MVT::i128) {
3814           if (OVT == MVT::f32)
3815             LC = RTLIB::FPTOUINT_F32_I128;
3816           else if (OVT == MVT::f64)
3817             LC = RTLIB::FPTOUINT_F64_I128;
3818           else if (OVT == MVT::f80)
3819             LC = RTLIB::FPTOUINT_F80_I128;
3820           else if (OVT == MVT::ppcf128)
3821             LC = RTLIB::FPTOUINT_PPCF128_I128;
3822           else
3823             assert(0 && "Unexpected i128-to-fp conversion!");
3824         } else {
3825           assert(0 && "Unexpectd int-to-fp conversion!");
3826         }
3827         break;
3828       }
3829       default: assert(0 && "Unreachable!");
3830       }
3831       SDOperand Dummy;
3832       Result = ExpandLibCall(LC, Node, false/*sign irrelevant*/, Dummy);
3833       break;
3834     }
3835     case Promote:
3836       Tmp1 = PromoteOp(Node->getOperand(0));
3837       Result = DAG.UpdateNodeOperands(Result, LegalizeOp(Tmp1));
3838       Result = LegalizeOp(Result);
3839       break;
3840     }
3841     break;
3842
3843   case ISD::FP_EXTEND: {
3844     MVT DstVT = Op.getValueType();
3845     MVT SrcVT = Op.getOperand(0).getValueType();
3846     if (TLI.getConvertAction(SrcVT, DstVT) == TargetLowering::Expand) {
3847       // The only other way we can lower this is to turn it into a STORE,
3848       // LOAD pair, targetting a temporary location (a stack slot).
3849       Result = EmitStackConvert(Node->getOperand(0), SrcVT, DstVT);
3850       break;
3851     }
3852     switch (getTypeAction(Node->getOperand(0).getValueType())) {
3853     case Expand: assert(0 && "Shouldn't need to expand other operators here!");
3854     case Legal:
3855       Tmp1 = LegalizeOp(Node->getOperand(0));
3856       Result = DAG.UpdateNodeOperands(Result, Tmp1);
3857       break;
3858     case Promote:
3859       Tmp1 = PromoteOp(Node->getOperand(0));
3860       Result = DAG.getNode(ISD::FP_EXTEND, Op.getValueType(), Tmp1);
3861       break;
3862     }
3863     break;
3864   }
3865   case ISD::FP_ROUND: {
3866     MVT DstVT = Op.getValueType();
3867     MVT SrcVT = Op.getOperand(0).getValueType();
3868     if (TLI.getConvertAction(SrcVT, DstVT) == TargetLowering::Expand) {
3869       if (SrcVT == MVT::ppcf128) {
3870         SDOperand Lo;
3871         ExpandOp(Node->getOperand(0), Lo, Result);
3872         // Round it the rest of the way (e.g. to f32) if needed.
3873         if (DstVT!=MVT::f64)
3874           Result = DAG.getNode(ISD::FP_ROUND, DstVT, Result, Op.getOperand(1));
3875         break;
3876       }
3877       // The only other way we can lower this is to turn it into a STORE,
3878       // LOAD pair, targetting a temporary location (a stack slot).
3879       Result = EmitStackConvert(Node->getOperand(0), DstVT, DstVT);
3880       break;
3881     }
3882     switch (getTypeAction(Node->getOperand(0).getValueType())) {
3883     case Expand: assert(0 && "Shouldn't need to expand other operators here!");
3884     case Legal:
3885       Tmp1 = LegalizeOp(Node->getOperand(0));
3886       Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
3887       break;
3888     case Promote:
3889       Tmp1 = PromoteOp(Node->getOperand(0));
3890       Result = DAG.getNode(ISD::FP_ROUND, Op.getValueType(), Tmp1,
3891                            Node->getOperand(1));
3892       break;
3893     }
3894     break;
3895   }
3896   case ISD::ANY_EXTEND:
3897   case ISD::ZERO_EXTEND:
3898   case ISD::SIGN_EXTEND:
3899     switch (getTypeAction(Node->getOperand(0).getValueType())) {
3900     case Expand: assert(0 && "Shouldn't need to expand other operators here!");
3901     case Legal:
3902       Tmp1 = LegalizeOp(Node->getOperand(0));
3903       Result = DAG.UpdateNodeOperands(Result, Tmp1);
3904       if (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0)) ==
3905           TargetLowering::Custom) {
3906         Tmp1 = TLI.LowerOperation(Result, DAG);
3907         if (Tmp1.Val) Result = Tmp1;
3908       }
3909       break;
3910     case Promote:
3911       switch (Node->getOpcode()) {
3912       case ISD::ANY_EXTEND:
3913         Tmp1 = PromoteOp(Node->getOperand(0));
3914         Result = DAG.getNode(ISD::ANY_EXTEND, Op.getValueType(), Tmp1);
3915         break;
3916       case ISD::ZERO_EXTEND:
3917         Result = PromoteOp(Node->getOperand(0));
3918         Result = DAG.getNode(ISD::ANY_EXTEND, Op.getValueType(), Result);
3919         Result = DAG.getZeroExtendInReg(Result,
3920                                         Node->getOperand(0).getValueType());
3921         break;
3922       case ISD::SIGN_EXTEND:
3923         Result = PromoteOp(Node->getOperand(0));
3924         Result = DAG.getNode(ISD::ANY_EXTEND, Op.getValueType(), Result);
3925         Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
3926                              Result,
3927                           DAG.getValueType(Node->getOperand(0).getValueType()));
3928         break;
3929       }
3930     }
3931     break;
3932   case ISD::FP_ROUND_INREG:
3933   case ISD::SIGN_EXTEND_INREG: {
3934     Tmp1 = LegalizeOp(Node->getOperand(0));
3935     MVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
3936
3937     // If this operation is not supported, convert it to a shl/shr or load/store
3938     // pair.
3939     switch (TLI.getOperationAction(Node->getOpcode(), ExtraVT)) {
3940     default: assert(0 && "This action not supported for this op yet!");
3941     case TargetLowering::Legal:
3942       Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
3943       break;
3944     case TargetLowering::Expand:
3945       // If this is an integer extend and shifts are supported, do that.
3946       if (Node->getOpcode() == ISD::SIGN_EXTEND_INREG) {
3947         // NOTE: we could fall back on load/store here too for targets without
3948         // SAR.  However, it is doubtful that any exist.
3949         unsigned BitsDiff = Node->getValueType(0).getSizeInBits() -
3950                             ExtraVT.getSizeInBits();
3951         SDOperand ShiftCst = DAG.getConstant(BitsDiff, TLI.getShiftAmountTy());
3952         Result = DAG.getNode(ISD::SHL, Node->getValueType(0),
3953                              Node->getOperand(0), ShiftCst);
3954         Result = DAG.getNode(ISD::SRA, Node->getValueType(0),
3955                              Result, ShiftCst);
3956       } else if (Node->getOpcode() == ISD::FP_ROUND_INREG) {
3957         // The only way we can lower this is to turn it into a TRUNCSTORE,
3958         // EXTLOAD pair, targetting a temporary location (a stack slot).
3959
3960         // NOTE: there is a choice here between constantly creating new stack
3961         // slots and always reusing the same one.  We currently always create
3962         // new ones, as reuse may inhibit scheduling.
3963         Result = EmitStackConvert(Node->getOperand(0), ExtraVT, 
3964                                   Node->getValueType(0));
3965       } else {
3966         assert(0 && "Unknown op");
3967       }
3968       break;
3969     }
3970     break;
3971   }
3972   case ISD::TRAMPOLINE: {
3973     SDOperand Ops[6];
3974     for (unsigned i = 0; i != 6; ++i)
3975       Ops[i] = LegalizeOp(Node->getOperand(i));
3976     Result = DAG.UpdateNodeOperands(Result, Ops, 6);
3977     // The only option for this node is to custom lower it.
3978     Result = TLI.LowerOperation(Result, DAG);
3979     assert(Result.Val && "Should always custom lower!");
3980
3981     // Since trampoline produces two values, make sure to remember that we
3982     // legalized both of them.
3983     Tmp1 = LegalizeOp(Result.getValue(1));
3984     Result = LegalizeOp(Result);
3985     AddLegalizedOperand(SDOperand(Node, 0), Result);
3986     AddLegalizedOperand(SDOperand(Node, 1), Tmp1);
3987     return Op.ResNo ? Tmp1 : Result;
3988   }
3989   case ISD::FLT_ROUNDS_: {
3990     MVT VT = Node->getValueType(0);
3991     switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
3992     default: assert(0 && "This action not supported for this op yet!");
3993     case TargetLowering::Custom:
3994       Result = TLI.LowerOperation(Op, DAG);
3995       if (Result.Val) break;
3996       // Fall Thru
3997     case TargetLowering::Legal:
3998       // If this operation is not supported, lower it to constant 1
3999       Result = DAG.getConstant(1, VT);
4000       break;
4001     }
4002     break;
4003   }
4004   case ISD::TRAP: {
4005     MVT VT = Node->getValueType(0);
4006     switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
4007     default: assert(0 && "This action not supported for this op yet!");
4008     case TargetLowering::Legal:
4009       Tmp1 = LegalizeOp(Node->getOperand(0));
4010       Result = DAG.UpdateNodeOperands(Result, Tmp1);
4011       break;
4012     case TargetLowering::Custom:
4013       Result = TLI.LowerOperation(Op, DAG);
4014       if (Result.Val) break;
4015       // Fall Thru
4016     case TargetLowering::Expand:
4017       // If this operation is not supported, lower it to 'abort()' call
4018       Tmp1 = LegalizeOp(Node->getOperand(0));
4019       TargetLowering::ArgListTy Args;
4020       std::pair<SDOperand,SDOperand> CallResult =
4021         TLI.LowerCallTo(Tmp1, Type::VoidTy,
4022                         false, false, false, CallingConv::C, false,
4023                         DAG.getExternalSymbol("abort", TLI.getPointerTy()),
4024                         Args, DAG);
4025       Result = CallResult.second;
4026       break;
4027     }
4028     break;
4029   }
4030   }
4031   
4032   assert(Result.getValueType() == Op.getValueType() &&
4033          "Bad legalization!");
4034   
4035   // Make sure that the generated code is itself legal.
4036   if (Result != Op)
4037     Result = LegalizeOp(Result);
4038
4039   // Note that LegalizeOp may be reentered even from single-use nodes, which
4040   // means that we always must cache transformed nodes.
4041   AddLegalizedOperand(Op, Result);
4042   return Result;
4043 }
4044
4045 /// PromoteOp - Given an operation that produces a value in an invalid type,
4046 /// promote it to compute the value into a larger type.  The produced value will
4047 /// have the correct bits for the low portion of the register, but no guarantee
4048 /// is made about the top bits: it may be zero, sign-extended, or garbage.
4049 SDOperand SelectionDAGLegalize::PromoteOp(SDOperand Op) {
4050   MVT VT = Op.getValueType();
4051   MVT NVT = TLI.getTypeToTransformTo(VT);
4052   assert(getTypeAction(VT) == Promote &&
4053          "Caller should expand or legalize operands that are not promotable!");
4054   assert(NVT.bitsGT(VT) && NVT.isInteger() == VT.isInteger() &&
4055          "Cannot promote to smaller type!");
4056
4057   SDOperand Tmp1, Tmp2, Tmp3;
4058   SDOperand Result;
4059   SDNode *Node = Op.Val;
4060
4061   DenseMap<SDOperand, SDOperand>::iterator I = PromotedNodes.find(Op);
4062   if (I != PromotedNodes.end()) return I->second;
4063
4064   switch (Node->getOpcode()) {
4065   case ISD::CopyFromReg:
4066     assert(0 && "CopyFromReg must be legal!");
4067   default:
4068 #ifndef NDEBUG
4069     cerr << "NODE: "; Node->dump(&DAG); cerr << "\n";
4070 #endif
4071     assert(0 && "Do not know how to promote this operator!");
4072     abort();
4073   case ISD::UNDEF:
4074     Result = DAG.getNode(ISD::UNDEF, NVT);
4075     break;
4076   case ISD::Constant:
4077     if (VT != MVT::i1)
4078       Result = DAG.getNode(ISD::SIGN_EXTEND, NVT, Op);
4079     else
4080       Result = DAG.getNode(ISD::ZERO_EXTEND, NVT, Op);
4081     assert(isa<ConstantSDNode>(Result) && "Didn't constant fold zext?");
4082     break;
4083   case ISD::ConstantFP:
4084     Result = DAG.getNode(ISD::FP_EXTEND, NVT, Op);
4085     assert(isa<ConstantFPSDNode>(Result) && "Didn't constant fold fp_extend?");
4086     break;
4087
4088   case ISD::SETCC:
4089     assert(isTypeLegal(TLI.getSetCCResultType(Node->getOperand(0)))
4090            && "SetCC type is not legal??");
4091     Result = DAG.getNode(ISD::SETCC,
4092                          TLI.getSetCCResultType(Node->getOperand(0)),
4093                          Node->getOperand(0), Node->getOperand(1),
4094                          Node->getOperand(2));
4095     break;
4096     
4097   case ISD::TRUNCATE:
4098     switch (getTypeAction(Node->getOperand(0).getValueType())) {
4099     case Legal:
4100       Result = LegalizeOp(Node->getOperand(0));
4101       assert(Result.getValueType().bitsGE(NVT) &&
4102              "This truncation doesn't make sense!");
4103       if (Result.getValueType().bitsGT(NVT))    // Truncate to NVT instead of VT
4104         Result = DAG.getNode(ISD::TRUNCATE, NVT, Result);
4105       break;
4106     case Promote:
4107       // The truncation is not required, because we don't guarantee anything
4108       // about high bits anyway.
4109       Result = PromoteOp(Node->getOperand(0));
4110       break;
4111     case Expand:
4112       ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
4113       // Truncate the low part of the expanded value to the result type
4114       Result = DAG.getNode(ISD::TRUNCATE, NVT, Tmp1);
4115     }
4116     break;
4117   case ISD::SIGN_EXTEND:
4118   case ISD::ZERO_EXTEND:
4119   case ISD::ANY_EXTEND:
4120     switch (getTypeAction(Node->getOperand(0).getValueType())) {
4121     case Expand: assert(0 && "BUG: Smaller reg should have been promoted!");
4122     case Legal:
4123       // Input is legal?  Just do extend all the way to the larger type.
4124       Result = DAG.getNode(Node->getOpcode(), NVT, Node->getOperand(0));
4125       break;
4126     case Promote:
4127       // Promote the reg if it's smaller.
4128       Result = PromoteOp(Node->getOperand(0));
4129       // The high bits are not guaranteed to be anything.  Insert an extend.
4130       if (Node->getOpcode() == ISD::SIGN_EXTEND)
4131         Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Result,
4132                          DAG.getValueType(Node->getOperand(0).getValueType()));
4133       else if (Node->getOpcode() == ISD::ZERO_EXTEND)
4134         Result = DAG.getZeroExtendInReg(Result,
4135                                         Node->getOperand(0).getValueType());
4136       break;
4137     }
4138     break;
4139   case ISD::BIT_CONVERT:
4140     Result = EmitStackConvert(Node->getOperand(0), Node->getValueType(0),
4141                               Node->getValueType(0));
4142     Result = PromoteOp(Result);
4143     break;
4144     
4145   case ISD::FP_EXTEND:
4146     assert(0 && "Case not implemented.  Dynamically dead with 2 FP types!");
4147   case ISD::FP_ROUND:
4148     switch (getTypeAction(Node->getOperand(0).getValueType())) {
4149     case Expand: assert(0 && "BUG: Cannot expand FP regs!");
4150     case Promote:  assert(0 && "Unreachable with 2 FP types!");
4151     case Legal:
4152       if (Node->getConstantOperandVal(1) == 0) {
4153         // Input is legal?  Do an FP_ROUND_INREG.
4154         Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Node->getOperand(0),
4155                              DAG.getValueType(VT));
4156       } else {
4157         // Just remove the truncate, it isn't affecting the value.
4158         Result = DAG.getNode(ISD::FP_ROUND, NVT, Node->getOperand(0), 
4159                              Node->getOperand(1));
4160       }
4161       break;
4162     }
4163     break;
4164   case ISD::SINT_TO_FP:
4165   case ISD::UINT_TO_FP:
4166     switch (getTypeAction(Node->getOperand(0).getValueType())) {
4167     case Legal:
4168       // No extra round required here.
4169       Result = DAG.getNode(Node->getOpcode(), NVT, Node->getOperand(0));
4170       break;
4171
4172     case Promote:
4173       Result = PromoteOp(Node->getOperand(0));
4174       if (Node->getOpcode() == ISD::SINT_TO_FP)
4175         Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
4176                              Result,
4177                          DAG.getValueType(Node->getOperand(0).getValueType()));
4178       else
4179         Result = DAG.getZeroExtendInReg(Result,
4180                                         Node->getOperand(0).getValueType());
4181       // No extra round required here.
4182       Result = DAG.getNode(Node->getOpcode(), NVT, Result);
4183       break;
4184     case Expand:
4185       Result = ExpandIntToFP(Node->getOpcode() == ISD::SINT_TO_FP, NVT,
4186                              Node->getOperand(0));
4187       // Round if we cannot tolerate excess precision.
4188       if (NoExcessFPPrecision)
4189         Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
4190                              DAG.getValueType(VT));
4191       break;
4192     }
4193     break;
4194
4195   case ISD::SIGN_EXTEND_INREG:
4196     Result = PromoteOp(Node->getOperand(0));
4197     Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Result, 
4198                          Node->getOperand(1));
4199     break;
4200   case ISD::FP_TO_SINT:
4201   case ISD::FP_TO_UINT:
4202     switch (getTypeAction(Node->getOperand(0).getValueType())) {
4203     case Legal:
4204     case Expand:
4205       Tmp1 = Node->getOperand(0);
4206       break;
4207     case Promote:
4208       // The input result is prerounded, so we don't have to do anything
4209       // special.
4210       Tmp1 = PromoteOp(Node->getOperand(0));
4211       break;
4212     }
4213     // If we're promoting a UINT to a larger size, check to see if the new node
4214     // will be legal.  If it isn't, check to see if FP_TO_SINT is legal, since
4215     // we can use that instead.  This allows us to generate better code for
4216     // FP_TO_UINT for small destination sizes on targets where FP_TO_UINT is not
4217     // legal, such as PowerPC.
4218     if (Node->getOpcode() == ISD::FP_TO_UINT && 
4219         !TLI.isOperationLegal(ISD::FP_TO_UINT, NVT) &&
4220         (TLI.isOperationLegal(ISD::FP_TO_SINT, NVT) ||
4221          TLI.getOperationAction(ISD::FP_TO_SINT, NVT)==TargetLowering::Custom)){
4222       Result = DAG.getNode(ISD::FP_TO_SINT, NVT, Tmp1);
4223     } else {
4224       Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
4225     }
4226     break;
4227
4228   case ISD::FABS:
4229   case ISD::FNEG:
4230     Tmp1 = PromoteOp(Node->getOperand(0));
4231     assert(Tmp1.getValueType() == NVT);
4232     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
4233     // NOTE: we do not have to do any extra rounding here for
4234     // NoExcessFPPrecision, because we know the input will have the appropriate
4235     // precision, and these operations don't modify precision at all.
4236     break;
4237
4238   case ISD::FSQRT:
4239   case ISD::FSIN:
4240   case ISD::FCOS:
4241     Tmp1 = PromoteOp(Node->getOperand(0));
4242     assert(Tmp1.getValueType() == NVT);
4243     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
4244     if (NoExcessFPPrecision)
4245       Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
4246                            DAG.getValueType(VT));
4247     break;
4248
4249   case ISD::FPOWI: {
4250     // Promote f32 powi to f64 powi.  Note that this could insert a libcall
4251     // directly as well, which may be better.
4252     Tmp1 = PromoteOp(Node->getOperand(0));
4253     assert(Tmp1.getValueType() == NVT);
4254     Result = DAG.getNode(ISD::FPOWI, NVT, Tmp1, Node->getOperand(1));
4255     if (NoExcessFPPrecision)
4256       Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
4257                            DAG.getValueType(VT));
4258     break;
4259   }
4260     
4261   case ISD::ATOMIC_CMP_SWAP: {
4262     AtomicSDNode* AtomNode = cast<AtomicSDNode>(Node);
4263     Tmp2 = PromoteOp(Node->getOperand(2));
4264     Tmp3 = PromoteOp(Node->getOperand(3));
4265     Result = DAG.getAtomic(Node->getOpcode(), AtomNode->getChain(), 
4266                            AtomNode->getBasePtr(), Tmp2, Tmp3,
4267                            AtomNode->getSrcValue(),
4268                            AtomNode->getAlignment());
4269     // Remember that we legalized the chain.
4270     AddLegalizedOperand(Op.getValue(1), LegalizeOp(Result.getValue(1)));
4271     break;
4272   }
4273   case ISD::ATOMIC_LOAD_ADD:
4274   case ISD::ATOMIC_LOAD_SUB:
4275   case ISD::ATOMIC_LOAD_AND:
4276   case ISD::ATOMIC_LOAD_OR:
4277   case ISD::ATOMIC_LOAD_XOR:
4278   case ISD::ATOMIC_LOAD_NAND:
4279   case ISD::ATOMIC_LOAD_MIN:
4280   case ISD::ATOMIC_LOAD_MAX:
4281   case ISD::ATOMIC_LOAD_UMIN:
4282   case ISD::ATOMIC_LOAD_UMAX:
4283   case ISD::ATOMIC_SWAP: {
4284     AtomicSDNode* AtomNode = cast<AtomicSDNode>(Node);
4285     Tmp2 = PromoteOp(Node->getOperand(2));
4286     Result = DAG.getAtomic(Node->getOpcode(), AtomNode->getChain(), 
4287                            AtomNode->getBasePtr(), Tmp2,
4288                            AtomNode->getSrcValue(),
4289                            AtomNode->getAlignment());
4290     // Remember that we legalized the chain.
4291     AddLegalizedOperand(Op.getValue(1), LegalizeOp(Result.getValue(1)));
4292     break;
4293   }
4294
4295   case ISD::AND:
4296   case ISD::OR:
4297   case ISD::XOR:
4298   case ISD::ADD:
4299   case ISD::SUB:
4300   case ISD::MUL:
4301     // The input may have strange things in the top bits of the registers, but
4302     // these operations don't care.  They may have weird bits going out, but
4303     // that too is okay if they are integer operations.
4304     Tmp1 = PromoteOp(Node->getOperand(0));
4305     Tmp2 = PromoteOp(Node->getOperand(1));
4306     assert(Tmp1.getValueType() == NVT && Tmp2.getValueType() == NVT);
4307     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
4308     break;
4309   case ISD::FADD:
4310   case ISD::FSUB:
4311   case ISD::FMUL:
4312     Tmp1 = PromoteOp(Node->getOperand(0));
4313     Tmp2 = PromoteOp(Node->getOperand(1));
4314     assert(Tmp1.getValueType() == NVT && Tmp2.getValueType() == NVT);
4315     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
4316     
4317     // Floating point operations will give excess precision that we may not be
4318     // able to tolerate.  If we DO allow excess precision, just leave it,
4319     // otherwise excise it.
4320     // FIXME: Why would we need to round FP ops more than integer ones?
4321     //     Is Round(Add(Add(A,B),C)) != Round(Add(Round(Add(A,B)), C))
4322     if (NoExcessFPPrecision)
4323       Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
4324                            DAG.getValueType(VT));
4325     break;
4326
4327   case ISD::SDIV:
4328   case ISD::SREM:
4329     // These operators require that their input be sign extended.
4330     Tmp1 = PromoteOp(Node->getOperand(0));
4331     Tmp2 = PromoteOp(Node->getOperand(1));
4332     if (NVT.isInteger()) {
4333       Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1,
4334                          DAG.getValueType(VT));
4335       Tmp2 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp2,
4336                          DAG.getValueType(VT));
4337     }
4338     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
4339
4340     // Perform FP_ROUND: this is probably overly pessimistic.
4341     if (NVT.isFloatingPoint() && NoExcessFPPrecision)
4342       Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
4343                            DAG.getValueType(VT));
4344     break;
4345   case ISD::FDIV:
4346   case ISD::FREM:
4347   case ISD::FCOPYSIGN:
4348     // These operators require that their input be fp extended.
4349     switch (getTypeAction(Node->getOperand(0).getValueType())) {
4350     case Expand: assert(0 && "not implemented");
4351     case Legal:   Tmp1 = LegalizeOp(Node->getOperand(0)); break;
4352     case Promote: Tmp1 = PromoteOp(Node->getOperand(0));  break;
4353     }
4354     switch (getTypeAction(Node->getOperand(1).getValueType())) {
4355     case Expand: assert(0 && "not implemented");
4356     case Legal:   Tmp2 = LegalizeOp(Node->getOperand(1)); break;
4357     case Promote: Tmp2 = PromoteOp(Node->getOperand(1)); break;
4358     }
4359     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
4360     
4361     // Perform FP_ROUND: this is probably overly pessimistic.
4362     if (NoExcessFPPrecision && Node->getOpcode() != ISD::FCOPYSIGN)
4363       Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
4364                            DAG.getValueType(VT));
4365     break;
4366
4367   case ISD::UDIV:
4368   case ISD::UREM:
4369     // These operators require that their input be zero extended.
4370     Tmp1 = PromoteOp(Node->getOperand(0));
4371     Tmp2 = PromoteOp(Node->getOperand(1));
4372     assert(NVT.isInteger() && "Operators don't apply to FP!");
4373     Tmp1 = DAG.getZeroExtendInReg(Tmp1, VT);
4374     Tmp2 = DAG.getZeroExtendInReg(Tmp2, VT);
4375     Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
4376     break;
4377
4378   case ISD::SHL:
4379     Tmp1 = PromoteOp(Node->getOperand(0));
4380     Result = DAG.getNode(ISD::SHL, NVT, Tmp1, Node->getOperand(1));
4381     break;
4382   case ISD::SRA:
4383     // The input value must be properly sign extended.
4384     Tmp1 = PromoteOp(Node->getOperand(0));
4385     Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1,
4386                        DAG.getValueType(VT));
4387     Result = DAG.getNode(ISD::SRA, NVT, Tmp1, Node->getOperand(1));
4388     break;
4389   case ISD::SRL:
4390     // The input value must be properly zero extended.
4391     Tmp1 = PromoteOp(Node->getOperand(0));
4392     Tmp1 = DAG.getZeroExtendInReg(Tmp1, VT);
4393     Result = DAG.getNode(ISD::SRL, NVT, Tmp1, Node->getOperand(1));
4394     break;
4395
4396   case ISD::VAARG:
4397     Tmp1 = Node->getOperand(0);   // Get the chain.
4398     Tmp2 = Node->getOperand(1);   // Get the pointer.
4399     if (TLI.getOperationAction(ISD::VAARG, VT) == TargetLowering::Custom) {
4400       Tmp3 = DAG.getVAArg(VT, Tmp1, Tmp2, Node->getOperand(2));
4401       Result = TLI.LowerOperation(Tmp3, DAG);
4402     } else {
4403       const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
4404       SDOperand VAList = DAG.getLoad(TLI.getPointerTy(), Tmp1, Tmp2, V, 0);
4405       // Increment the pointer, VAList, to the next vaarg
4406       Tmp3 = DAG.getNode(ISD::ADD, TLI.getPointerTy(), VAList, 
4407                          DAG.getConstant(VT.getSizeInBits()/8,
4408                                          TLI.getPointerTy()));
4409       // Store the incremented VAList to the legalized pointer
4410       Tmp3 = DAG.getStore(VAList.getValue(1), Tmp3, Tmp2, V, 0);
4411       // Load the actual argument out of the pointer VAList
4412       Result = DAG.getExtLoad(ISD::EXTLOAD, NVT, Tmp3, VAList, NULL, 0, VT);
4413     }
4414     // Remember that we legalized the chain.
4415     AddLegalizedOperand(Op.getValue(1), LegalizeOp(Result.getValue(1)));
4416     break;
4417
4418   case ISD::LOAD: {
4419     LoadSDNode *LD = cast<LoadSDNode>(Node);
4420     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(Node)
4421       ? ISD::EXTLOAD : LD->getExtensionType();
4422     Result = DAG.getExtLoad(ExtType, NVT,
4423                             LD->getChain(), LD->getBasePtr(),
4424                             LD->getSrcValue(), LD->getSrcValueOffset(),
4425                             LD->getMemoryVT(),
4426                             LD->isVolatile(),
4427                             LD->getAlignment());
4428     // Remember that we legalized the chain.
4429     AddLegalizedOperand(Op.getValue(1), LegalizeOp(Result.getValue(1)));
4430     break;
4431   }
4432   case ISD::SELECT: {
4433     Tmp2 = PromoteOp(Node->getOperand(1));   // Legalize the op0
4434     Tmp3 = PromoteOp(Node->getOperand(2));   // Legalize the op1
4435
4436     MVT VT2 = Tmp2.getValueType();
4437     assert(VT2 == Tmp3.getValueType()
4438            && "PromoteOp SELECT: Operands 2 and 3 ValueTypes don't match");
4439     // Ensure that the resulting node is at least the same size as the operands'
4440     // value types, because we cannot assume that TLI.getSetCCValueType() is
4441     // constant.
4442     Result = DAG.getNode(ISD::SELECT, VT2, Node->getOperand(0), Tmp2, Tmp3);
4443     break;
4444   }
4445   case ISD::SELECT_CC:
4446     Tmp2 = PromoteOp(Node->getOperand(2));   // True
4447     Tmp3 = PromoteOp(Node->getOperand(3));   // False
4448     Result = DAG.getNode(ISD::SELECT_CC, NVT, Node->getOperand(0),
4449                          Node->getOperand(1), Tmp2, Tmp3, Node->getOperand(4));
4450     break;
4451   case ISD::BSWAP:
4452     Tmp1 = Node->getOperand(0);
4453     Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, NVT, Tmp1);
4454     Tmp1 = DAG.getNode(ISD::BSWAP, NVT, Tmp1);
4455     Result = DAG.getNode(ISD::SRL, NVT, Tmp1,
4456                          DAG.getConstant(NVT.getSizeInBits() -
4457                                          VT.getSizeInBits(),
4458                                          TLI.getShiftAmountTy()));
4459     break;
4460   case ISD::CTPOP:
4461   case ISD::CTTZ:
4462   case ISD::CTLZ:
4463     // Zero extend the argument
4464     Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, NVT, Node->getOperand(0));
4465     // Perform the larger operation, then subtract if needed.
4466     Tmp1 = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
4467     switch(Node->getOpcode()) {
4468     case ISD::CTPOP:
4469       Result = Tmp1;
4470       break;
4471     case ISD::CTTZ:
4472       // if Tmp1 == sizeinbits(NVT) then Tmp1 = sizeinbits(Old VT)
4473       Tmp2 = DAG.getSetCC(TLI.getSetCCResultType(Tmp1), Tmp1,
4474                           DAG.getConstant(NVT.getSizeInBits(), NVT),
4475                           ISD::SETEQ);
4476       Result = DAG.getNode(ISD::SELECT, NVT, Tmp2,
4477                            DAG.getConstant(VT.getSizeInBits(), NVT), Tmp1);
4478       break;
4479     case ISD::CTLZ:
4480       //Tmp1 = Tmp1 - (sizeinbits(NVT) - sizeinbits(Old VT))
4481       Result = DAG.getNode(ISD::SUB, NVT, Tmp1,
4482                            DAG.getConstant(NVT.getSizeInBits() -
4483                                            VT.getSizeInBits(), NVT));
4484       break;
4485     }
4486     break;
4487   case ISD::EXTRACT_SUBVECTOR:
4488     Result = PromoteOp(ExpandEXTRACT_SUBVECTOR(Op));
4489     break;
4490   case ISD::EXTRACT_VECTOR_ELT:
4491     Result = PromoteOp(ExpandEXTRACT_VECTOR_ELT(Op));
4492     break;
4493   }
4494
4495   assert(Result.Val && "Didn't set a result!");
4496
4497   // Make sure the result is itself legal.
4498   Result = LegalizeOp(Result);
4499   
4500   // Remember that we promoted this!
4501   AddPromotedOperand(Op, Result);
4502   return Result;
4503 }
4504
4505 /// ExpandEXTRACT_VECTOR_ELT - Expand an EXTRACT_VECTOR_ELT operation into
4506 /// a legal EXTRACT_VECTOR_ELT operation, scalar code, or memory traffic,
4507 /// based on the vector type. The return type of this matches the element type
4508 /// of the vector, which may not be legal for the target.
4509 SDOperand SelectionDAGLegalize::ExpandEXTRACT_VECTOR_ELT(SDOperand Op) {
4510   // We know that operand #0 is the Vec vector.  If the index is a constant
4511   // or if the invec is a supported hardware type, we can use it.  Otherwise,
4512   // lower to a store then an indexed load.
4513   SDOperand Vec = Op.getOperand(0);
4514   SDOperand Idx = Op.getOperand(1);
4515   
4516   MVT TVT = Vec.getValueType();
4517   unsigned NumElems = TVT.getVectorNumElements();
4518   
4519   switch (TLI.getOperationAction(ISD::EXTRACT_VECTOR_ELT, TVT)) {
4520   default: assert(0 && "This action is not supported yet!");
4521   case TargetLowering::Custom: {
4522     Vec = LegalizeOp(Vec);
4523     Op = DAG.UpdateNodeOperands(Op, Vec, Idx);
4524     SDOperand Tmp3 = TLI.LowerOperation(Op, DAG);
4525     if (Tmp3.Val)
4526       return Tmp3;
4527     break;
4528   }
4529   case TargetLowering::Legal:
4530     if (isTypeLegal(TVT)) {
4531       Vec = LegalizeOp(Vec);
4532       Op = DAG.UpdateNodeOperands(Op, Vec, Idx);
4533       return Op;
4534     }
4535     break;
4536   case TargetLowering::Expand:
4537     break;
4538   }
4539
4540   if (NumElems == 1) {
4541     // This must be an access of the only element.  Return it.
4542     Op = ScalarizeVectorOp(Vec);
4543   } else if (!TLI.isTypeLegal(TVT) && isa<ConstantSDNode>(Idx)) {
4544     unsigned NumLoElts =  1 << Log2_32(NumElems-1);
4545     ConstantSDNode *CIdx = cast<ConstantSDNode>(Idx);
4546     SDOperand Lo, Hi;
4547     SplitVectorOp(Vec, Lo, Hi);
4548     if (CIdx->getValue() < NumLoElts) {
4549       Vec = Lo;
4550     } else {
4551       Vec = Hi;
4552       Idx = DAG.getConstant(CIdx->getValue() - NumLoElts,
4553                             Idx.getValueType());
4554     }
4555   
4556     // It's now an extract from the appropriate high or low part.  Recurse.
4557     Op = DAG.UpdateNodeOperands(Op, Vec, Idx);
4558     Op = ExpandEXTRACT_VECTOR_ELT(Op);
4559   } else {
4560     // Store the value to a temporary stack slot, then LOAD the scalar
4561     // element back out.
4562     SDOperand StackPtr = DAG.CreateStackTemporary(Vec.getValueType());
4563     SDOperand Ch = DAG.getStore(DAG.getEntryNode(), Vec, StackPtr, NULL, 0);
4564
4565     // Add the offset to the index.
4566     unsigned EltSize = Op.getValueType().getSizeInBits()/8;
4567     Idx = DAG.getNode(ISD::MUL, Idx.getValueType(), Idx,
4568                       DAG.getConstant(EltSize, Idx.getValueType()));
4569
4570     if (Idx.getValueType().bitsGT(TLI.getPointerTy()))
4571       Idx = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), Idx);
4572     else
4573       Idx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), Idx);
4574
4575     StackPtr = DAG.getNode(ISD::ADD, Idx.getValueType(), Idx, StackPtr);
4576
4577     Op = DAG.getLoad(Op.getValueType(), Ch, StackPtr, NULL, 0);
4578   }
4579   return Op;
4580 }
4581
4582 /// ExpandEXTRACT_SUBVECTOR - Expand a EXTRACT_SUBVECTOR operation.  For now
4583 /// we assume the operation can be split if it is not already legal.
4584 SDOperand SelectionDAGLegalize::ExpandEXTRACT_SUBVECTOR(SDOperand Op) {
4585   // We know that operand #0 is the Vec vector.  For now we assume the index
4586   // is a constant and that the extracted result is a supported hardware type.
4587   SDOperand Vec = Op.getOperand(0);
4588   SDOperand Idx = LegalizeOp(Op.getOperand(1));
4589   
4590   unsigned NumElems = Vec.getValueType().getVectorNumElements();
4591   
4592   if (NumElems == Op.getValueType().getVectorNumElements()) {
4593     // This must be an access of the desired vector length.  Return it.
4594     return Vec;
4595   }
4596
4597   ConstantSDNode *CIdx = cast<ConstantSDNode>(Idx);
4598   SDOperand Lo, Hi;
4599   SplitVectorOp(Vec, Lo, Hi);
4600   if (CIdx->getValue() < NumElems/2) {
4601     Vec = Lo;
4602   } else {
4603     Vec = Hi;
4604     Idx = DAG.getConstant(CIdx->getValue() - NumElems/2, Idx.getValueType());
4605   }
4606   
4607   // It's now an extract from the appropriate high or low part.  Recurse.
4608   Op = DAG.UpdateNodeOperands(Op, Vec, Idx);
4609   return ExpandEXTRACT_SUBVECTOR(Op);
4610 }
4611
4612 /// LegalizeSetCCOperands - Attempts to create a legal LHS and RHS for a SETCC
4613 /// with condition CC on the current target.  This usually involves legalizing
4614 /// or promoting the arguments.  In the case where LHS and RHS must be expanded,
4615 /// there may be no choice but to create a new SetCC node to represent the
4616 /// legalized value of setcc lhs, rhs.  In this case, the value is returned in
4617 /// LHS, and the SDOperand returned in RHS has a nil SDNode value.
4618 void SelectionDAGLegalize::LegalizeSetCCOperands(SDOperand &LHS,
4619                                                  SDOperand &RHS,
4620                                                  SDOperand &CC) {
4621   SDOperand Tmp1, Tmp2, Tmp3, Result;    
4622   
4623   switch (getTypeAction(LHS.getValueType())) {
4624   case Legal:
4625     Tmp1 = LegalizeOp(LHS);   // LHS
4626     Tmp2 = LegalizeOp(RHS);   // RHS
4627     break;
4628   case Promote:
4629     Tmp1 = PromoteOp(LHS);   // LHS
4630     Tmp2 = PromoteOp(RHS);   // RHS
4631
4632     // If this is an FP compare, the operands have already been extended.
4633     if (LHS.getValueType().isInteger()) {
4634       MVT VT = LHS.getValueType();
4635       MVT NVT = TLI.getTypeToTransformTo(VT);
4636
4637       // Otherwise, we have to insert explicit sign or zero extends.  Note
4638       // that we could insert sign extends for ALL conditions, but zero extend
4639       // is cheaper on many machines (an AND instead of two shifts), so prefer
4640       // it.
4641       switch (cast<CondCodeSDNode>(CC)->get()) {
4642       default: assert(0 && "Unknown integer comparison!");
4643       case ISD::SETEQ:
4644       case ISD::SETNE:
4645       case ISD::SETUGE:
4646       case ISD::SETUGT:
4647       case ISD::SETULE:
4648       case ISD::SETULT:
4649         // ALL of these operations will work if we either sign or zero extend
4650         // the operands (including the unsigned comparisons!).  Zero extend is
4651         // usually a simpler/cheaper operation, so prefer it.
4652         Tmp1 = DAG.getZeroExtendInReg(Tmp1, VT);
4653         Tmp2 = DAG.getZeroExtendInReg(Tmp2, VT);
4654         break;
4655       case ISD::SETGE:
4656       case ISD::SETGT:
4657       case ISD::SETLT:
4658       case ISD::SETLE:
4659         Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1,
4660                            DAG.getValueType(VT));
4661         Tmp2 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp2,
4662                            DAG.getValueType(VT));
4663         break;
4664       }
4665     }
4666     break;
4667   case Expand: {
4668     MVT VT = LHS.getValueType();
4669     if (VT == MVT::f32 || VT == MVT::f64) {
4670       // Expand into one or more soft-fp libcall(s).
4671       RTLIB::Libcall LC1 = RTLIB::UNKNOWN_LIBCALL, LC2 = RTLIB::UNKNOWN_LIBCALL;
4672       switch (cast<CondCodeSDNode>(CC)->get()) {
4673       case ISD::SETEQ:
4674       case ISD::SETOEQ:
4675         LC1 = (VT == MVT::f32) ? RTLIB::OEQ_F32 : RTLIB::OEQ_F64;
4676         break;
4677       case ISD::SETNE:
4678       case ISD::SETUNE:
4679         LC1 = (VT == MVT::f32) ? RTLIB::UNE_F32 : RTLIB::UNE_F64;
4680         break;
4681       case ISD::SETGE:
4682       case ISD::SETOGE:
4683         LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 : RTLIB::OGE_F64;
4684         break;
4685       case ISD::SETLT:
4686       case ISD::SETOLT:
4687         LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 : RTLIB::OLT_F64;
4688         break;
4689       case ISD::SETLE:
4690       case ISD::SETOLE:
4691         LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 : RTLIB::OLE_F64;
4692         break;
4693       case ISD::SETGT:
4694       case ISD::SETOGT:
4695         LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 : RTLIB::OGT_F64;
4696         break;
4697       case ISD::SETUO:
4698         LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 : RTLIB::UO_F64;
4699         break;
4700       case ISD::SETO:
4701         LC1 = (VT == MVT::f32) ? RTLIB::O_F32 : RTLIB::O_F64;
4702         break;
4703       default:
4704         LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 : RTLIB::UO_F64;
4705         switch (cast<CondCodeSDNode>(CC)->get()) {
4706         case ISD::SETONE:
4707           // SETONE = SETOLT | SETOGT
4708           LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 : RTLIB::OLT_F64;
4709           // Fallthrough
4710         case ISD::SETUGT:
4711           LC2 = (VT == MVT::f32) ? RTLIB::OGT_F32 : RTLIB::OGT_F64;
4712           break;
4713         case ISD::SETUGE:
4714           LC2 = (VT == MVT::f32) ? RTLIB::OGE_F32 : RTLIB::OGE_F64;
4715           break;
4716         case ISD::SETULT:
4717           LC2 = (VT == MVT::f32) ? RTLIB::OLT_F32 : RTLIB::OLT_F64;
4718           break;
4719         case ISD::SETULE:
4720           LC2 = (VT == MVT::f32) ? RTLIB::OLE_F32 : RTLIB::OLE_F64;
4721           break;
4722         case ISD::SETUEQ:
4723           LC2 = (VT == MVT::f32) ? RTLIB::OEQ_F32 : RTLIB::OEQ_F64;
4724           break;
4725         default: assert(0 && "Unsupported FP setcc!");
4726         }
4727       }
4728
4729       SDOperand Dummy;
4730       SDOperand Ops[2] = { LHS, RHS };
4731       Tmp1 = ExpandLibCall(LC1, DAG.getMergeValues(Ops, 2).Val,
4732                            false /*sign irrelevant*/, Dummy);
4733       Tmp2 = DAG.getConstant(0, MVT::i32);
4734       CC = DAG.getCondCode(TLI.getCmpLibcallCC(LC1));
4735       if (LC2 != RTLIB::UNKNOWN_LIBCALL) {
4736         Tmp1 = DAG.getNode(ISD::SETCC, TLI.getSetCCResultType(Tmp1), Tmp1, Tmp2,
4737                            CC);
4738         LHS = ExpandLibCall(LC2, DAG.getMergeValues(Ops, 2).Val,
4739                             false /*sign irrelevant*/, Dummy);
4740         Tmp2 = DAG.getNode(ISD::SETCC, TLI.getSetCCResultType(LHS), LHS, Tmp2,
4741                            DAG.getCondCode(TLI.getCmpLibcallCC(LC2)));
4742         Tmp1 = DAG.getNode(ISD::OR, Tmp1.getValueType(), Tmp1, Tmp2);
4743         Tmp2 = SDOperand();
4744       }
4745       LHS = LegalizeOp(Tmp1);
4746       RHS = Tmp2;
4747       return;
4748     }
4749
4750     SDOperand LHSLo, LHSHi, RHSLo, RHSHi;
4751     ExpandOp(LHS, LHSLo, LHSHi);
4752     ExpandOp(RHS, RHSLo, RHSHi);
4753     ISD::CondCode CCCode = cast<CondCodeSDNode>(CC)->get();
4754
4755     if (VT==MVT::ppcf128) {
4756       // FIXME:  This generated code sucks.  We want to generate
4757       //         FCMP crN, hi1, hi2
4758       //         BNE crN, L:
4759       //         FCMP crN, lo1, lo2
4760       // The following can be improved, but not that much.
4761       Tmp1 = DAG.getSetCC(TLI.getSetCCResultType(LHSHi), LHSHi, RHSHi, ISD::SETEQ);
4762       Tmp2 = DAG.getSetCC(TLI.getSetCCResultType(LHSLo), LHSLo, RHSLo, CCCode);
4763       Tmp3 = DAG.getNode(ISD::AND, Tmp1.getValueType(), Tmp1, Tmp2);
4764       Tmp1 = DAG.getSetCC(TLI.getSetCCResultType(LHSHi), LHSHi, RHSHi, ISD::SETNE);
4765       Tmp2 = DAG.getSetCC(TLI.getSetCCResultType(LHSHi), LHSHi, RHSHi, CCCode);
4766       Tmp1 = DAG.getNode(ISD::AND, Tmp1.getValueType(), Tmp1, Tmp2);
4767       Tmp1 = DAG.getNode(ISD::OR, Tmp1.getValueType(), Tmp1, Tmp3);
4768       Tmp2 = SDOperand();
4769       break;
4770     }
4771
4772     switch (CCCode) {
4773     case ISD::SETEQ:
4774     case ISD::SETNE:
4775       if (RHSLo == RHSHi)
4776         if (ConstantSDNode *RHSCST = dyn_cast<ConstantSDNode>(RHSLo))
4777           if (RHSCST->isAllOnesValue()) {
4778             // Comparison to -1.
4779             Tmp1 = DAG.getNode(ISD::AND, LHSLo.getValueType(), LHSLo, LHSHi);
4780             Tmp2 = RHSLo;
4781             break;
4782           }
4783
4784       Tmp1 = DAG.getNode(ISD::XOR, LHSLo.getValueType(), LHSLo, RHSLo);
4785       Tmp2 = DAG.getNode(ISD::XOR, LHSLo.getValueType(), LHSHi, RHSHi);
4786       Tmp1 = DAG.getNode(ISD::OR, Tmp1.getValueType(), Tmp1, Tmp2);
4787       Tmp2 = DAG.getConstant(0, Tmp1.getValueType());
4788       break;
4789     default:
4790       // If this is a comparison of the sign bit, just look at the top part.
4791       // X > -1,  x < 0
4792       if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(RHS))
4793         if ((cast<CondCodeSDNode>(CC)->get() == ISD::SETLT && 
4794              CST->isNullValue()) ||               // X < 0
4795             (cast<CondCodeSDNode>(CC)->get() == ISD::SETGT &&
4796              CST->isAllOnesValue())) {            // X > -1
4797           Tmp1 = LHSHi;
4798           Tmp2 = RHSHi;
4799           break;
4800         }
4801
4802       // FIXME: This generated code sucks.
4803       ISD::CondCode LowCC;
4804       switch (CCCode) {
4805       default: assert(0 && "Unknown integer setcc!");
4806       case ISD::SETLT:
4807       case ISD::SETULT: LowCC = ISD::SETULT; break;
4808       case ISD::SETGT:
4809       case ISD::SETUGT: LowCC = ISD::SETUGT; break;
4810       case ISD::SETLE:
4811       case ISD::SETULE: LowCC = ISD::SETULE; break;
4812       case ISD::SETGE:
4813       case ISD::SETUGE: LowCC = ISD::SETUGE; break;
4814       }
4815
4816       // Tmp1 = lo(op1) < lo(op2)   // Always unsigned comparison
4817       // Tmp2 = hi(op1) < hi(op2)   // Signedness depends on operands
4818       // dest = hi(op1) == hi(op2) ? Tmp1 : Tmp2;
4819
4820       // NOTE: on targets without efficient SELECT of bools, we can always use
4821       // this identity: (B1 ? B2 : B3) --> (B1 & B2)|(!B1&B3)
4822       TargetLowering::DAGCombinerInfo DagCombineInfo(DAG, false, true, NULL);
4823       Tmp1 = TLI.SimplifySetCC(TLI.getSetCCResultType(LHSLo), LHSLo, RHSLo,
4824                                LowCC, false, DagCombineInfo);
4825       if (!Tmp1.Val)
4826         Tmp1 = DAG.getSetCC(TLI.getSetCCResultType(LHSLo), LHSLo, RHSLo, LowCC);
4827       Tmp2 = TLI.SimplifySetCC(TLI.getSetCCResultType(LHSHi), LHSHi, RHSHi,
4828                                CCCode, false, DagCombineInfo);
4829       if (!Tmp2.Val)
4830         Tmp2 = DAG.getNode(ISD::SETCC, TLI.getSetCCResultType(LHSHi), LHSHi,
4831                            RHSHi,CC);
4832       
4833       ConstantSDNode *Tmp1C = dyn_cast<ConstantSDNode>(Tmp1.Val);
4834       ConstantSDNode *Tmp2C = dyn_cast<ConstantSDNode>(Tmp2.Val);
4835       if ((Tmp1C && Tmp1C->isNullValue()) ||
4836           (Tmp2C && Tmp2C->isNullValue() &&
4837            (CCCode == ISD::SETLE || CCCode == ISD::SETGE ||
4838             CCCode == ISD::SETUGE || CCCode == ISD::SETULE)) ||
4839           (Tmp2C && Tmp2C->getAPIntValue() == 1 &&
4840            (CCCode == ISD::SETLT || CCCode == ISD::SETGT ||
4841             CCCode == ISD::SETUGT || CCCode == ISD::SETULT))) {
4842         // low part is known false, returns high part.
4843         // For LE / GE, if high part is known false, ignore the low part.
4844         // For LT / GT, if high part is known true, ignore the low part.
4845         Tmp1 = Tmp2;
4846         Tmp2 = SDOperand();
4847       } else {
4848         Result = TLI.SimplifySetCC(TLI.getSetCCResultType(LHSHi), LHSHi, RHSHi,
4849                                    ISD::SETEQ, false, DagCombineInfo);
4850         if (!Result.Val)
4851           Result=DAG.getSetCC(TLI.getSetCCResultType(LHSHi), LHSHi, RHSHi,
4852                               ISD::SETEQ);
4853         Result = LegalizeOp(DAG.getNode(ISD::SELECT, Tmp1.getValueType(),
4854                                         Result, Tmp1, Tmp2));
4855         Tmp1 = Result;
4856         Tmp2 = SDOperand();
4857       }
4858     }
4859   }
4860   }
4861   LHS = Tmp1;
4862   RHS = Tmp2;
4863 }
4864
4865 /// EmitStackConvert - Emit a store/load combination to the stack.  This stores
4866 /// SrcOp to a stack slot of type SlotVT, truncating it if needed.  It then does
4867 /// a load from the stack slot to DestVT, extending it if needed.
4868 /// The resultant code need not be legal.
4869 SDOperand SelectionDAGLegalize::EmitStackConvert(SDOperand SrcOp,
4870                                                  MVT SlotVT,
4871                                                  MVT DestVT) {
4872   // Create the stack frame object.
4873   unsigned SrcAlign = TLI.getTargetData()->getPrefTypeAlignment(
4874                                           SrcOp.getValueType().getTypeForMVT());
4875   SDOperand FIPtr = DAG.CreateStackTemporary(SlotVT, SrcAlign);
4876   
4877   FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(FIPtr);
4878   int SPFI = StackPtrFI->getIndex();
4879   
4880   unsigned SrcSize = SrcOp.getValueType().getSizeInBits();
4881   unsigned SlotSize = SlotVT.getSizeInBits();
4882   unsigned DestSize = DestVT.getSizeInBits();
4883   unsigned DestAlign = TLI.getTargetData()->getPrefTypeAlignment(
4884                                                         DestVT.getTypeForMVT());
4885   
4886   // Emit a store to the stack slot.  Use a truncstore if the input value is
4887   // later than DestVT.
4888   SDOperand Store;
4889   
4890   if (SrcSize > SlotSize)
4891     Store = DAG.getTruncStore(DAG.getEntryNode(), SrcOp, FIPtr,
4892                               PseudoSourceValue::getFixedStack(), SPFI, SlotVT, 
4893                               false, SrcAlign);
4894   else {
4895     assert(SrcSize == SlotSize && "Invalid store");
4896     Store = DAG.getStore(DAG.getEntryNode(), SrcOp, FIPtr,
4897                          PseudoSourceValue::getFixedStack(), SPFI,
4898                          false, SrcAlign);
4899   }
4900   
4901   // Result is a load from the stack slot.
4902   if (SlotSize == DestSize)
4903     return DAG.getLoad(DestVT, Store, FIPtr, NULL, 0, false, DestAlign);
4904   
4905   assert(SlotSize < DestSize && "Unknown extension!");
4906   return DAG.getExtLoad(ISD::EXTLOAD, DestVT, Store, FIPtr, NULL, 0, SlotVT,
4907                         false, DestAlign);
4908 }
4909
4910 SDOperand SelectionDAGLegalize::ExpandSCALAR_TO_VECTOR(SDNode *Node) {
4911   // Create a vector sized/aligned stack slot, store the value to element #0,
4912   // then load the whole vector back out.
4913   SDOperand StackPtr = DAG.CreateStackTemporary(Node->getValueType(0));
4914
4915   FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(StackPtr);
4916   int SPFI = StackPtrFI->getIndex();
4917
4918   SDOperand Ch = DAG.getStore(DAG.getEntryNode(), Node->getOperand(0), StackPtr,
4919                               PseudoSourceValue::getFixedStack(), SPFI);
4920   return DAG.getLoad(Node->getValueType(0), Ch, StackPtr,
4921                      PseudoSourceValue::getFixedStack(), SPFI);
4922 }
4923
4924
4925 /// ExpandBUILD_VECTOR - Expand a BUILD_VECTOR node on targets that don't
4926 /// support the operation, but do support the resultant vector type.
4927 SDOperand SelectionDAGLegalize::ExpandBUILD_VECTOR(SDNode *Node) {
4928   
4929   // If the only non-undef value is the low element, turn this into a 
4930   // SCALAR_TO_VECTOR node.  If this is { X, X, X, X }, determine X.
4931   unsigned NumElems = Node->getNumOperands();
4932   bool isOnlyLowElement = true;
4933   SDOperand SplatValue = Node->getOperand(0);
4934   
4935   // FIXME: it would be far nicer to change this into map<SDOperand,uint64_t>
4936   // and use a bitmask instead of a list of elements.
4937   std::map<SDOperand, std::vector<unsigned> > Values;
4938   Values[SplatValue].push_back(0);
4939   bool isConstant = true;
4940   if (!isa<ConstantFPSDNode>(SplatValue) && !isa<ConstantSDNode>(SplatValue) &&
4941       SplatValue.getOpcode() != ISD::UNDEF)
4942     isConstant = false;
4943   
4944   for (unsigned i = 1; i < NumElems; ++i) {
4945     SDOperand V = Node->getOperand(i);
4946     Values[V].push_back(i);
4947     if (V.getOpcode() != ISD::UNDEF)
4948       isOnlyLowElement = false;
4949     if (SplatValue != V)
4950       SplatValue = SDOperand(0,0);
4951
4952     // If this isn't a constant element or an undef, we can't use a constant
4953     // pool load.
4954     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V) &&
4955         V.getOpcode() != ISD::UNDEF)
4956       isConstant = false;
4957   }
4958   
4959   if (isOnlyLowElement) {
4960     // If the low element is an undef too, then this whole things is an undef.
4961     if (Node->getOperand(0).getOpcode() == ISD::UNDEF)
4962       return DAG.getNode(ISD::UNDEF, Node->getValueType(0));
4963     // Otherwise, turn this into a scalar_to_vector node.
4964     return DAG.getNode(ISD::SCALAR_TO_VECTOR, Node->getValueType(0),
4965                        Node->getOperand(0));
4966   }
4967   
4968   // If all elements are constants, create a load from the constant pool.
4969   if (isConstant) {
4970     MVT VT = Node->getValueType(0);
4971     std::vector<Constant*> CV;
4972     for (unsigned i = 0, e = NumElems; i != e; ++i) {
4973       if (ConstantFPSDNode *V = 
4974           dyn_cast<ConstantFPSDNode>(Node->getOperand(i))) {
4975         CV.push_back(ConstantFP::get(V->getValueAPF()));
4976       } else if (ConstantSDNode *V = 
4977                    dyn_cast<ConstantSDNode>(Node->getOperand(i))) {
4978         CV.push_back(ConstantInt::get(V->getAPIntValue()));
4979       } else {
4980         assert(Node->getOperand(i).getOpcode() == ISD::UNDEF);
4981         const Type *OpNTy = 
4982           Node->getOperand(0).getValueType().getTypeForMVT();
4983         CV.push_back(UndefValue::get(OpNTy));
4984       }
4985     }
4986     Constant *CP = ConstantVector::get(CV);
4987     SDOperand CPIdx = DAG.getConstantPool(CP, TLI.getPointerTy());
4988     return DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4989                        PseudoSourceValue::getConstantPool(), 0);
4990   }
4991   
4992   if (SplatValue.Val) {   // Splat of one value?
4993     // Build the shuffle constant vector: <0, 0, 0, 0>
4994     MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
4995     SDOperand Zero = DAG.getConstant(0, MaskVT.getVectorElementType());
4996     std::vector<SDOperand> ZeroVec(NumElems, Zero);
4997     SDOperand SplatMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
4998                                       &ZeroVec[0], ZeroVec.size());
4999
5000     // If the target supports VECTOR_SHUFFLE and this shuffle mask, use it.
5001     if (isShuffleLegal(Node->getValueType(0), SplatMask)) {
5002       // Get the splatted value into the low element of a vector register.
5003       SDOperand LowValVec = 
5004         DAG.getNode(ISD::SCALAR_TO_VECTOR, Node->getValueType(0), SplatValue);
5005     
5006       // Return shuffle(LowValVec, undef, <0,0,0,0>)
5007       return DAG.getNode(ISD::VECTOR_SHUFFLE, Node->getValueType(0), LowValVec,
5008                          DAG.getNode(ISD::UNDEF, Node->getValueType(0)),
5009                          SplatMask);
5010     }
5011   }
5012   
5013   // If there are only two unique elements, we may be able to turn this into a
5014   // vector shuffle.
5015   if (Values.size() == 2) {
5016     // Get the two values in deterministic order.
5017     SDOperand Val1 = Node->getOperand(1);
5018     SDOperand Val2;
5019     std::map<SDOperand, std::vector<unsigned> >::iterator MI = Values.begin();
5020     if (MI->first != Val1)
5021       Val2 = MI->first;
5022     else
5023       Val2 = (++MI)->first;
5024     
5025     // If Val1 is an undef, make sure end ends up as Val2, to ensure that our 
5026     // vector shuffle has the undef vector on the RHS.
5027     if (Val1.getOpcode() == ISD::UNDEF)
5028       std::swap(Val1, Val2);
5029     
5030     // Build the shuffle constant vector: e.g. <0, 4, 0, 4>
5031     MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
5032     MVT MaskEltVT = MaskVT.getVectorElementType();
5033     std::vector<SDOperand> MaskVec(NumElems);
5034
5035     // Set elements of the shuffle mask for Val1.
5036     std::vector<unsigned> &Val1Elts = Values[Val1];
5037     for (unsigned i = 0, e = Val1Elts.size(); i != e; ++i)
5038       MaskVec[Val1Elts[i]] = DAG.getConstant(0, MaskEltVT);
5039
5040     // Set elements of the shuffle mask for Val2.
5041     std::vector<unsigned> &Val2Elts = Values[Val2];
5042     for (unsigned i = 0, e = Val2Elts.size(); i != e; ++i)
5043       if (Val2.getOpcode() != ISD::UNDEF)
5044         MaskVec[Val2Elts[i]] = DAG.getConstant(NumElems, MaskEltVT);
5045       else
5046         MaskVec[Val2Elts[i]] = DAG.getNode(ISD::UNDEF, MaskEltVT);
5047     
5048     SDOperand ShuffleMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
5049                                         &MaskVec[0], MaskVec.size());
5050
5051     // If the target supports SCALAR_TO_VECTOR and this shuffle mask, use it.
5052     if (TLI.isOperationLegal(ISD::SCALAR_TO_VECTOR, Node->getValueType(0)) &&
5053         isShuffleLegal(Node->getValueType(0), ShuffleMask)) {
5054       Val1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, Node->getValueType(0), Val1);
5055       Val2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, Node->getValueType(0), Val2);
5056       SDOperand Ops[] = { Val1, Val2, ShuffleMask };
5057
5058       // Return shuffle(LoValVec, HiValVec, <0,1,0,1>)
5059       return DAG.getNode(ISD::VECTOR_SHUFFLE, Node->getValueType(0), Ops, 3);
5060     }
5061   }
5062   
5063   // Otherwise, we can't handle this case efficiently.  Allocate a sufficiently
5064   // aligned object on the stack, store each element into it, then load
5065   // the result as a vector.
5066   MVT VT = Node->getValueType(0);
5067   // Create the stack frame object.
5068   SDOperand FIPtr = DAG.CreateStackTemporary(VT);
5069   
5070   // Emit a store of each element to the stack slot.
5071   SmallVector<SDOperand, 8> Stores;
5072   unsigned TypeByteSize = Node->getOperand(0).getValueType().getSizeInBits()/8;
5073   // Store (in the right endianness) the elements to memory.
5074   for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
5075     // Ignore undef elements.
5076     if (Node->getOperand(i).getOpcode() == ISD::UNDEF) continue;
5077     
5078     unsigned Offset = TypeByteSize*i;
5079     
5080     SDOperand Idx = DAG.getConstant(Offset, FIPtr.getValueType());
5081     Idx = DAG.getNode(ISD::ADD, FIPtr.getValueType(), FIPtr, Idx);
5082     
5083     Stores.push_back(DAG.getStore(DAG.getEntryNode(), Node->getOperand(i), Idx, 
5084                                   NULL, 0));
5085   }
5086   
5087   SDOperand StoreChain;
5088   if (!Stores.empty())    // Not all undef elements?
5089     StoreChain = DAG.getNode(ISD::TokenFactor, MVT::Other,
5090                              &Stores[0], Stores.size());
5091   else
5092     StoreChain = DAG.getEntryNode();
5093   
5094   // Result is a load from the stack slot.
5095   return DAG.getLoad(VT, StoreChain, FIPtr, NULL, 0);
5096 }
5097
5098 void SelectionDAGLegalize::ExpandShiftParts(unsigned NodeOp,
5099                                             SDOperand Op, SDOperand Amt,
5100                                             SDOperand &Lo, SDOperand &Hi) {
5101   // Expand the subcomponents.
5102   SDOperand LHSL, LHSH;
5103   ExpandOp(Op, LHSL, LHSH);
5104
5105   SDOperand Ops[] = { LHSL, LHSH, Amt };
5106   MVT VT = LHSL.getValueType();
5107   Lo = DAG.getNode(NodeOp, DAG.getNodeValueTypes(VT, VT), 2, Ops, 3);
5108   Hi = Lo.getValue(1);
5109 }
5110
5111
5112 /// ExpandShift - Try to find a clever way to expand this shift operation out to
5113 /// smaller elements.  If we can't find a way that is more efficient than a
5114 /// libcall on this target, return false.  Otherwise, return true with the
5115 /// low-parts expanded into Lo and Hi.
5116 bool SelectionDAGLegalize::ExpandShift(unsigned Opc, SDOperand Op,SDOperand Amt,
5117                                        SDOperand &Lo, SDOperand &Hi) {
5118   assert((Opc == ISD::SHL || Opc == ISD::SRA || Opc == ISD::SRL) &&
5119          "This is not a shift!");
5120
5121   MVT NVT = TLI.getTypeToTransformTo(Op.getValueType());
5122   SDOperand ShAmt = LegalizeOp(Amt);
5123   MVT ShTy = ShAmt.getValueType();
5124   unsigned ShBits = ShTy.getSizeInBits();
5125   unsigned VTBits = Op.getValueType().getSizeInBits();
5126   unsigned NVTBits = NVT.getSizeInBits();
5127
5128   // Handle the case when Amt is an immediate.
5129   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Amt.Val)) {
5130     unsigned Cst = CN->getValue();
5131     // Expand the incoming operand to be shifted, so that we have its parts
5132     SDOperand InL, InH;
5133     ExpandOp(Op, InL, InH);
5134     switch(Opc) {
5135     case ISD::SHL:
5136       if (Cst > VTBits) {
5137         Lo = DAG.getConstant(0, NVT);
5138         Hi = DAG.getConstant(0, NVT);
5139       } else if (Cst > NVTBits) {
5140         Lo = DAG.getConstant(0, NVT);
5141         Hi = DAG.getNode(ISD::SHL, NVT, InL, DAG.getConstant(Cst-NVTBits,ShTy));
5142       } else if (Cst == NVTBits) {
5143         Lo = DAG.getConstant(0, NVT);
5144         Hi = InL;
5145       } else {
5146         Lo = DAG.getNode(ISD::SHL, NVT, InL, DAG.getConstant(Cst, ShTy));
5147         Hi = DAG.getNode(ISD::OR, NVT,
5148            DAG.getNode(ISD::SHL, NVT, InH, DAG.getConstant(Cst, ShTy)),
5149            DAG.getNode(ISD::SRL, NVT, InL, DAG.getConstant(NVTBits-Cst, ShTy)));
5150       }
5151       return true;
5152     case ISD::SRL:
5153       if (Cst > VTBits) {
5154         Lo = DAG.getConstant(0, NVT);
5155         Hi = DAG.getConstant(0, NVT);
5156       } else if (Cst > NVTBits) {
5157         Lo = DAG.getNode(ISD::SRL, NVT, InH, DAG.getConstant(Cst-NVTBits,ShTy));
5158         Hi = DAG.getConstant(0, NVT);
5159       } else if (Cst == NVTBits) {
5160         Lo = InH;
5161         Hi = DAG.getConstant(0, NVT);
5162       } else {
5163         Lo = DAG.getNode(ISD::OR, NVT,
5164            DAG.getNode(ISD::SRL, NVT, InL, DAG.getConstant(Cst, ShTy)),
5165            DAG.getNode(ISD::SHL, NVT, InH, DAG.getConstant(NVTBits-Cst, ShTy)));
5166         Hi = DAG.getNode(ISD::SRL, NVT, InH, DAG.getConstant(Cst, ShTy));
5167       }
5168       return true;
5169     case ISD::SRA:
5170       if (Cst > VTBits) {
5171         Hi = Lo = DAG.getNode(ISD::SRA, NVT, InH,
5172                               DAG.getConstant(NVTBits-1, ShTy));
5173       } else if (Cst > NVTBits) {
5174         Lo = DAG.getNode(ISD::SRA, NVT, InH,
5175                            DAG.getConstant(Cst-NVTBits, ShTy));
5176         Hi = DAG.getNode(ISD::SRA, NVT, InH,
5177                               DAG.getConstant(NVTBits-1, ShTy));
5178       } else if (Cst == NVTBits) {
5179         Lo = InH;
5180         Hi = DAG.getNode(ISD::SRA, NVT, InH,
5181                               DAG.getConstant(NVTBits-1, ShTy));
5182       } else {
5183         Lo = DAG.getNode(ISD::OR, NVT,
5184            DAG.getNode(ISD::SRL, NVT, InL, DAG.getConstant(Cst, ShTy)),
5185            DAG.getNode(ISD::SHL, NVT, InH, DAG.getConstant(NVTBits-Cst, ShTy)));
5186         Hi = DAG.getNode(ISD::SRA, NVT, InH, DAG.getConstant(Cst, ShTy));
5187       }
5188       return true;
5189     }
5190   }
5191   
5192   // Okay, the shift amount isn't constant.  However, if we can tell that it is
5193   // >= 32 or < 32, we can still simplify it, without knowing the actual value.
5194   APInt Mask = APInt::getHighBitsSet(ShBits, ShBits - Log2_32(NVTBits));
5195   APInt KnownZero, KnownOne;
5196   DAG.ComputeMaskedBits(Amt, Mask, KnownZero, KnownOne);
5197   
5198   // If we know that if any of the high bits of the shift amount are one, then
5199   // we can do this as a couple of simple shifts.
5200   if (KnownOne.intersects(Mask)) {
5201     // Mask out the high bit, which we know is set.
5202     Amt = DAG.getNode(ISD::AND, Amt.getValueType(), Amt,
5203                       DAG.getConstant(~Mask, Amt.getValueType()));
5204     
5205     // Expand the incoming operand to be shifted, so that we have its parts
5206     SDOperand InL, InH;
5207     ExpandOp(Op, InL, InH);
5208     switch(Opc) {
5209     case ISD::SHL:
5210       Lo = DAG.getConstant(0, NVT);              // Low part is zero.
5211       Hi = DAG.getNode(ISD::SHL, NVT, InL, Amt); // High part from Lo part.
5212       return true;
5213     case ISD::SRL:
5214       Hi = DAG.getConstant(0, NVT);              // Hi part is zero.
5215       Lo = DAG.getNode(ISD::SRL, NVT, InH, Amt); // Lo part from Hi part.
5216       return true;
5217     case ISD::SRA:
5218       Hi = DAG.getNode(ISD::SRA, NVT, InH,       // Sign extend high part.
5219                        DAG.getConstant(NVTBits-1, Amt.getValueType()));
5220       Lo = DAG.getNode(ISD::SRA, NVT, InH, Amt); // Lo part from Hi part.
5221       return true;
5222     }
5223   }
5224   
5225   // If we know that the high bits of the shift amount are all zero, then we can
5226   // do this as a couple of simple shifts.
5227   if ((KnownZero & Mask) == Mask) {
5228     // Compute 32-amt.
5229     SDOperand Amt2 = DAG.getNode(ISD::SUB, Amt.getValueType(),
5230                                  DAG.getConstant(NVTBits, Amt.getValueType()),
5231                                  Amt);
5232     
5233     // Expand the incoming operand to be shifted, so that we have its parts
5234     SDOperand InL, InH;
5235     ExpandOp(Op, InL, InH);
5236     switch(Opc) {
5237     case ISD::SHL:
5238       Lo = DAG.getNode(ISD::SHL, NVT, InL, Amt);
5239       Hi = DAG.getNode(ISD::OR, NVT,
5240                        DAG.getNode(ISD::SHL, NVT, InH, Amt),
5241                        DAG.getNode(ISD::SRL, NVT, InL, Amt2));
5242       return true;
5243     case ISD::SRL:
5244       Hi = DAG.getNode(ISD::SRL, NVT, InH, Amt);
5245       Lo = DAG.getNode(ISD::OR, NVT,
5246                        DAG.getNode(ISD::SRL, NVT, InL, Amt),
5247                        DAG.getNode(ISD::SHL, NVT, InH, Amt2));
5248       return true;
5249     case ISD::SRA:
5250       Hi = DAG.getNode(ISD::SRA, NVT, InH, Amt);
5251       Lo = DAG.getNode(ISD::OR, NVT,
5252                        DAG.getNode(ISD::SRL, NVT, InL, Amt),
5253                        DAG.getNode(ISD::SHL, NVT, InH, Amt2));
5254       return true;
5255     }
5256   }
5257   
5258   return false;
5259 }
5260
5261
5262 // ExpandLibCall - Expand a node into a call to a libcall.  If the result value
5263 // does not fit into a register, return the lo part and set the hi part to the
5264 // by-reg argument.  If it does fit into a single register, return the result
5265 // and leave the Hi part unset.
5266 SDOperand SelectionDAGLegalize::ExpandLibCall(RTLIB::Libcall LC, SDNode *Node,
5267                                               bool isSigned, SDOperand &Hi) {
5268   assert(!IsLegalizingCall && "Cannot overlap legalization of calls!");
5269   // The input chain to this libcall is the entry node of the function. 
5270   // Legalizing the call will automatically add the previous call to the
5271   // dependence.
5272   SDOperand InChain = DAG.getEntryNode();
5273   
5274   TargetLowering::ArgListTy Args;
5275   TargetLowering::ArgListEntry Entry;
5276   for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
5277     MVT ArgVT = Node->getOperand(i).getValueType();
5278     const Type *ArgTy = ArgVT.getTypeForMVT();
5279     Entry.Node = Node->getOperand(i); Entry.Ty = ArgTy; 
5280     Entry.isSExt = isSigned;
5281     Entry.isZExt = !isSigned;
5282     Args.push_back(Entry);
5283   }
5284   SDOperand Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
5285                                            TLI.getPointerTy());
5286
5287   // Splice the libcall in wherever FindInputOutputChains tells us to.
5288   const Type *RetTy = Node->getValueType(0).getTypeForMVT();
5289   std::pair<SDOperand,SDOperand> CallInfo =
5290     TLI.LowerCallTo(InChain, RetTy, isSigned, !isSigned, false, CallingConv::C,
5291                     false, Callee, Args, DAG);
5292
5293   // Legalize the call sequence, starting with the chain.  This will advance
5294   // the LastCALLSEQ_END to the legalized version of the CALLSEQ_END node that
5295   // was added by LowerCallTo (guaranteeing proper serialization of calls).
5296   LegalizeOp(CallInfo.second);
5297   SDOperand Result;
5298   switch (getTypeAction(CallInfo.first.getValueType())) {
5299   default: assert(0 && "Unknown thing");
5300   case Legal:
5301     Result = CallInfo.first;
5302     break;
5303   case Expand:
5304     ExpandOp(CallInfo.first, Result, Hi);
5305     break;
5306   }
5307   return Result;
5308 }
5309
5310
5311 /// ExpandIntToFP - Expand a [US]INT_TO_FP operation.
5312 ///
5313 SDOperand SelectionDAGLegalize::
5314 ExpandIntToFP(bool isSigned, MVT DestTy, SDOperand Source) {
5315   MVT SourceVT = Source.getValueType();
5316   bool ExpandSource = getTypeAction(SourceVT) == Expand;
5317
5318   // Special case for i32 source to take advantage of UINTTOFP_I32_F32, etc.
5319   if (!isSigned && SourceVT != MVT::i32) {
5320     // The integer value loaded will be incorrectly if the 'sign bit' of the
5321     // incoming integer is set.  To handle this, we dynamically test to see if
5322     // it is set, and, if so, add a fudge factor.
5323     SDOperand Hi;
5324     if (ExpandSource) {
5325       SDOperand Lo;
5326       ExpandOp(Source, Lo, Hi);
5327       Source = DAG.getNode(ISD::BUILD_PAIR, SourceVT, Lo, Hi);
5328     } else {
5329       // The comparison for the sign bit will use the entire operand.
5330       Hi = Source;
5331     }
5332
5333     // If this is unsigned, and not supported, first perform the conversion to
5334     // signed, then adjust the result if the sign bit is set.
5335     SDOperand SignedConv = ExpandIntToFP(true, DestTy, Source);
5336
5337     SDOperand SignSet = DAG.getSetCC(TLI.getSetCCResultType(Hi), Hi,
5338                                      DAG.getConstant(0, Hi.getValueType()),
5339                                      ISD::SETLT);
5340     SDOperand Zero = DAG.getIntPtrConstant(0), Four = DAG.getIntPtrConstant(4);
5341     SDOperand CstOffset = DAG.getNode(ISD::SELECT, Zero.getValueType(),
5342                                       SignSet, Four, Zero);
5343     uint64_t FF = 0x5f800000ULL;
5344     if (TLI.isLittleEndian()) FF <<= 32;
5345     static Constant *FudgeFactor = ConstantInt::get(Type::Int64Ty, FF);
5346
5347     SDOperand CPIdx = DAG.getConstantPool(FudgeFactor, TLI.getPointerTy());
5348     CPIdx = DAG.getNode(ISD::ADD, TLI.getPointerTy(), CPIdx, CstOffset);
5349     SDOperand FudgeInReg;
5350     if (DestTy == MVT::f32)
5351       FudgeInReg = DAG.getLoad(MVT::f32, DAG.getEntryNode(), CPIdx,
5352                                PseudoSourceValue::getConstantPool(), 0);
5353     else if (DestTy.bitsGT(MVT::f32))
5354       // FIXME: Avoid the extend by construction the right constantpool?
5355       FudgeInReg = DAG.getExtLoad(ISD::EXTLOAD, DestTy, DAG.getEntryNode(),
5356                                   CPIdx,
5357                                   PseudoSourceValue::getConstantPool(), 0,
5358                                   MVT::f32);
5359     else 
5360       assert(0 && "Unexpected conversion");
5361
5362     MVT SCVT = SignedConv.getValueType();
5363     if (SCVT != DestTy) {
5364       // Destination type needs to be expanded as well. The FADD now we are
5365       // constructing will be expanded into a libcall.
5366       if (SCVT.getSizeInBits() != DestTy.getSizeInBits()) {
5367         assert(SCVT.getSizeInBits() * 2 == DestTy.getSizeInBits());
5368         SignedConv = DAG.getNode(ISD::BUILD_PAIR, DestTy,
5369                                  SignedConv, SignedConv.getValue(1));
5370       }
5371       SignedConv = DAG.getNode(ISD::BIT_CONVERT, DestTy, SignedConv);
5372     }
5373     return DAG.getNode(ISD::FADD, DestTy, SignedConv, FudgeInReg);
5374   }
5375
5376   // Check to see if the target has a custom way to lower this.  If so, use it.
5377   switch (TLI.getOperationAction(ISD::SINT_TO_FP, SourceVT)) {
5378   default: assert(0 && "This action not implemented for this operation!");
5379   case TargetLowering::Legal:
5380   case TargetLowering::Expand:
5381     break;   // This case is handled below.
5382   case TargetLowering::Custom: {
5383     SDOperand NV = TLI.LowerOperation(DAG.getNode(ISD::SINT_TO_FP, DestTy,
5384                                                   Source), DAG);
5385     if (NV.Val)
5386       return LegalizeOp(NV);
5387     break;   // The target decided this was legal after all
5388   }
5389   }
5390
5391   // Expand the source, then glue it back together for the call.  We must expand
5392   // the source in case it is shared (this pass of legalize must traverse it).
5393   if (ExpandSource) {
5394     SDOperand SrcLo, SrcHi;
5395     ExpandOp(Source, SrcLo, SrcHi);
5396     Source = DAG.getNode(ISD::BUILD_PAIR, SourceVT, SrcLo, SrcHi);
5397   }
5398
5399   RTLIB::Libcall LC;
5400   if (SourceVT == MVT::i32) {
5401     if (DestTy == MVT::f32)
5402       LC = isSigned ? RTLIB::SINTTOFP_I32_F32 : RTLIB::UINTTOFP_I32_F32;
5403     else {
5404       assert(DestTy == MVT::f64 && "Unknown fp value type!");
5405       LC = isSigned ? RTLIB::SINTTOFP_I32_F64 : RTLIB::UINTTOFP_I32_F64;
5406     }
5407   } else if (SourceVT == MVT::i64) {
5408     if (DestTy == MVT::f32)
5409       LC = RTLIB::SINTTOFP_I64_F32;
5410     else if (DestTy == MVT::f64)
5411       LC = RTLIB::SINTTOFP_I64_F64;
5412     else if (DestTy == MVT::f80)
5413       LC = RTLIB::SINTTOFP_I64_F80;
5414     else {
5415       assert(DestTy == MVT::ppcf128 && "Unknown fp value type!");
5416       LC = RTLIB::SINTTOFP_I64_PPCF128;
5417     }
5418   } else if (SourceVT == MVT::i128) {
5419     if (DestTy == MVT::f32)
5420       LC = RTLIB::SINTTOFP_I128_F32;
5421     else if (DestTy == MVT::f64)
5422       LC = RTLIB::SINTTOFP_I128_F64;
5423     else if (DestTy == MVT::f80)
5424       LC = RTLIB::SINTTOFP_I128_F80;
5425     else {
5426       assert(DestTy == MVT::ppcf128 && "Unknown fp value type!");
5427       LC = RTLIB::SINTTOFP_I128_PPCF128;
5428     }
5429   } else {
5430     assert(0 && "Unknown int value type");
5431   }
5432   
5433   assert(TLI.getLibcallName(LC) && "Don't know how to expand this SINT_TO_FP!");
5434   Source = DAG.getNode(ISD::SINT_TO_FP, DestTy, Source);
5435   SDOperand HiPart;
5436   SDOperand Result = ExpandLibCall(LC, Source.Val, isSigned, HiPart);
5437   if (Result.getValueType() != DestTy && HiPart.Val)
5438     Result = DAG.getNode(ISD::BUILD_PAIR, DestTy, Result, HiPart);
5439   return Result;
5440 }
5441
5442 /// ExpandLegalINT_TO_FP - This function is responsible for legalizing a
5443 /// INT_TO_FP operation of the specified operand when the target requests that
5444 /// we expand it.  At this point, we know that the result and operand types are
5445 /// legal for the target.
5446 SDOperand SelectionDAGLegalize::ExpandLegalINT_TO_FP(bool isSigned,
5447                                                      SDOperand Op0,
5448                                                      MVT DestVT) {
5449   if (Op0.getValueType() == MVT::i32) {
5450     // simple 32-bit [signed|unsigned] integer to float/double expansion
5451     
5452     // Get the stack frame index of a 8 byte buffer.
5453     SDOperand StackSlot = DAG.CreateStackTemporary(MVT::f64);
5454     
5455     // word offset constant for Hi/Lo address computation
5456     SDOperand WordOff = DAG.getConstant(sizeof(int), TLI.getPointerTy());
5457     // set up Hi and Lo (into buffer) address based on endian
5458     SDOperand Hi = StackSlot;
5459     SDOperand Lo = DAG.getNode(ISD::ADD, TLI.getPointerTy(), StackSlot,WordOff);
5460     if (TLI.isLittleEndian())
5461       std::swap(Hi, Lo);
5462     
5463     // if signed map to unsigned space
5464     SDOperand Op0Mapped;
5465     if (isSigned) {
5466       // constant used to invert sign bit (signed to unsigned mapping)
5467       SDOperand SignBit = DAG.getConstant(0x80000000u, MVT::i32);
5468       Op0Mapped = DAG.getNode(ISD::XOR, MVT::i32, Op0, SignBit);
5469     } else {
5470       Op0Mapped = Op0;
5471     }
5472     // store the lo of the constructed double - based on integer input
5473     SDOperand Store1 = DAG.getStore(DAG.getEntryNode(),
5474                                     Op0Mapped, Lo, NULL, 0);
5475     // initial hi portion of constructed double
5476     SDOperand InitialHi = DAG.getConstant(0x43300000u, MVT::i32);
5477     // store the hi of the constructed double - biased exponent
5478     SDOperand Store2=DAG.getStore(Store1, InitialHi, Hi, NULL, 0);
5479     // load the constructed double
5480     SDOperand Load = DAG.getLoad(MVT::f64, Store2, StackSlot, NULL, 0);
5481     // FP constant to bias correct the final result
5482     SDOperand Bias = DAG.getConstantFP(isSigned ?
5483                                             BitsToDouble(0x4330000080000000ULL)
5484                                           : BitsToDouble(0x4330000000000000ULL),
5485                                      MVT::f64);
5486     // subtract the bias
5487     SDOperand Sub = DAG.getNode(ISD::FSUB, MVT::f64, Load, Bias);
5488     // final result
5489     SDOperand Result;
5490     // handle final rounding
5491     if (DestVT == MVT::f64) {
5492       // do nothing
5493       Result = Sub;
5494     } else if (DestVT.bitsLT(MVT::f64)) {
5495       Result = DAG.getNode(ISD::FP_ROUND, DestVT, Sub,
5496                            DAG.getIntPtrConstant(0));
5497     } else if (DestVT.bitsGT(MVT::f64)) {
5498       Result = DAG.getNode(ISD::FP_EXTEND, DestVT, Sub);
5499     }
5500     return Result;
5501   }
5502   assert(!isSigned && "Legalize cannot Expand SINT_TO_FP for i64 yet");
5503   SDOperand Tmp1 = DAG.getNode(ISD::SINT_TO_FP, DestVT, Op0);
5504
5505   SDOperand SignSet = DAG.getSetCC(TLI.getSetCCResultType(Op0), Op0,
5506                                    DAG.getConstant(0, Op0.getValueType()),
5507                                    ISD::SETLT);
5508   SDOperand Zero = DAG.getIntPtrConstant(0), Four = DAG.getIntPtrConstant(4);
5509   SDOperand CstOffset = DAG.getNode(ISD::SELECT, Zero.getValueType(),
5510                                     SignSet, Four, Zero);
5511
5512   // If the sign bit of the integer is set, the large number will be treated
5513   // as a negative number.  To counteract this, the dynamic code adds an
5514   // offset depending on the data type.
5515   uint64_t FF;
5516   switch (Op0.getValueType().getSimpleVT()) {
5517   default: assert(0 && "Unsupported integer type!");
5518   case MVT::i8 : FF = 0x43800000ULL; break;  // 2^8  (as a float)
5519   case MVT::i16: FF = 0x47800000ULL; break;  // 2^16 (as a float)
5520   case MVT::i32: FF = 0x4F800000ULL; break;  // 2^32 (as a float)
5521   case MVT::i64: FF = 0x5F800000ULL; break;  // 2^64 (as a float)
5522   }
5523   if (TLI.isLittleEndian()) FF <<= 32;
5524   static Constant *FudgeFactor = ConstantInt::get(Type::Int64Ty, FF);
5525
5526   SDOperand CPIdx = DAG.getConstantPool(FudgeFactor, TLI.getPointerTy());
5527   CPIdx = DAG.getNode(ISD::ADD, TLI.getPointerTy(), CPIdx, CstOffset);
5528   SDOperand FudgeInReg;
5529   if (DestVT == MVT::f32)
5530     FudgeInReg = DAG.getLoad(MVT::f32, DAG.getEntryNode(), CPIdx,
5531                              PseudoSourceValue::getConstantPool(), 0);
5532   else {
5533     FudgeInReg =
5534       LegalizeOp(DAG.getExtLoad(ISD::EXTLOAD, DestVT,
5535                                 DAG.getEntryNode(), CPIdx,
5536                                 PseudoSourceValue::getConstantPool(), 0,
5537                                 MVT::f32));
5538   }
5539
5540   return DAG.getNode(ISD::FADD, DestVT, Tmp1, FudgeInReg);
5541 }
5542
5543 /// PromoteLegalINT_TO_FP - This function is responsible for legalizing a
5544 /// *INT_TO_FP operation of the specified operand when the target requests that
5545 /// we promote it.  At this point, we know that the result and operand types are
5546 /// legal for the target, and that there is a legal UINT_TO_FP or SINT_TO_FP
5547 /// operation that takes a larger input.
5548 SDOperand SelectionDAGLegalize::PromoteLegalINT_TO_FP(SDOperand LegalOp,
5549                                                       MVT DestVT,
5550                                                       bool isSigned) {
5551   // First step, figure out the appropriate *INT_TO_FP operation to use.
5552   MVT NewInTy = LegalOp.getValueType();
5553
5554   unsigned OpToUse = 0;
5555
5556   // Scan for the appropriate larger type to use.
5557   while (1) {
5558     NewInTy = (MVT::SimpleValueType)(NewInTy.getSimpleVT()+1);
5559     assert(NewInTy.isInteger() && "Ran out of possibilities!");
5560
5561     // If the target supports SINT_TO_FP of this type, use it.
5562     switch (TLI.getOperationAction(ISD::SINT_TO_FP, NewInTy)) {
5563       default: break;
5564       case TargetLowering::Legal:
5565         if (!TLI.isTypeLegal(NewInTy))
5566           break;  // Can't use this datatype.
5567         // FALL THROUGH.
5568       case TargetLowering::Custom:
5569         OpToUse = ISD::SINT_TO_FP;
5570         break;
5571     }
5572     if (OpToUse) break;
5573     if (isSigned) continue;
5574
5575     // If the target supports UINT_TO_FP of this type, use it.
5576     switch (TLI.getOperationAction(ISD::UINT_TO_FP, NewInTy)) {
5577       default: break;
5578       case TargetLowering::Legal:
5579         if (!TLI.isTypeLegal(NewInTy))
5580           break;  // Can't use this datatype.
5581         // FALL THROUGH.
5582       case TargetLowering::Custom:
5583         OpToUse = ISD::UINT_TO_FP;
5584         break;
5585     }
5586     if (OpToUse) break;
5587
5588     // Otherwise, try a larger type.
5589   }
5590
5591   // Okay, we found the operation and type to use.  Zero extend our input to the
5592   // desired type then run the operation on it.
5593   return DAG.getNode(OpToUse, DestVT,
5594                      DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
5595                                  NewInTy, LegalOp));
5596 }
5597
5598 /// PromoteLegalFP_TO_INT - This function is responsible for legalizing a
5599 /// FP_TO_*INT operation of the specified operand when the target requests that
5600 /// we promote it.  At this point, we know that the result and operand types are
5601 /// legal for the target, and that there is a legal FP_TO_UINT or FP_TO_SINT
5602 /// operation that returns a larger result.
5603 SDOperand SelectionDAGLegalize::PromoteLegalFP_TO_INT(SDOperand LegalOp,
5604                                                       MVT DestVT,
5605                                                       bool isSigned) {
5606   // First step, figure out the appropriate FP_TO*INT operation to use.
5607   MVT NewOutTy = DestVT;
5608
5609   unsigned OpToUse = 0;
5610
5611   // Scan for the appropriate larger type to use.
5612   while (1) {
5613     NewOutTy = (MVT::SimpleValueType)(NewOutTy.getSimpleVT()+1);
5614     assert(NewOutTy.isInteger() && "Ran out of possibilities!");
5615
5616     // If the target supports FP_TO_SINT returning this type, use it.
5617     switch (TLI.getOperationAction(ISD::FP_TO_SINT, NewOutTy)) {
5618     default: break;
5619     case TargetLowering::Legal:
5620       if (!TLI.isTypeLegal(NewOutTy))
5621         break;  // Can't use this datatype.
5622       // FALL THROUGH.
5623     case TargetLowering::Custom:
5624       OpToUse = ISD::FP_TO_SINT;
5625       break;
5626     }
5627     if (OpToUse) break;
5628
5629     // If the target supports FP_TO_UINT of this type, use it.
5630     switch (TLI.getOperationAction(ISD::FP_TO_UINT, NewOutTy)) {
5631     default: break;
5632     case TargetLowering::Legal:
5633       if (!TLI.isTypeLegal(NewOutTy))
5634         break;  // Can't use this datatype.
5635       // FALL THROUGH.
5636     case TargetLowering::Custom:
5637       OpToUse = ISD::FP_TO_UINT;
5638       break;
5639     }
5640     if (OpToUse) break;
5641
5642     // Otherwise, try a larger type.
5643   }
5644
5645   
5646   // Okay, we found the operation and type to use.
5647   SDOperand Operation = DAG.getNode(OpToUse, NewOutTy, LegalOp);
5648
5649   // If the operation produces an invalid type, it must be custom lowered.  Use
5650   // the target lowering hooks to expand it.  Just keep the low part of the
5651   // expanded operation, we know that we're truncating anyway.
5652   if (getTypeAction(NewOutTy) == Expand) {
5653     Operation = SDOperand(TLI.ReplaceNodeResults(Operation.Val, DAG), 0);
5654     assert(Operation.Val && "Didn't return anything");
5655   }
5656
5657   // Truncate the result of the extended FP_TO_*INT operation to the desired
5658   // size.
5659   return DAG.getNode(ISD::TRUNCATE, DestVT, Operation);
5660 }
5661
5662 /// ExpandBSWAP - Open code the operations for BSWAP of the specified operation.
5663 ///
5664 SDOperand SelectionDAGLegalize::ExpandBSWAP(SDOperand Op) {
5665   MVT VT = Op.getValueType();
5666   MVT SHVT = TLI.getShiftAmountTy();
5667   SDOperand Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8;
5668   switch (VT.getSimpleVT()) {
5669   default: assert(0 && "Unhandled Expand type in BSWAP!"); abort();
5670   case MVT::i16:
5671     Tmp2 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(8, SHVT));
5672     Tmp1 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(8, SHVT));
5673     return DAG.getNode(ISD::OR, VT, Tmp1, Tmp2);
5674   case MVT::i32:
5675     Tmp4 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(24, SHVT));
5676     Tmp3 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(8, SHVT));
5677     Tmp2 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(8, SHVT));
5678     Tmp1 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(24, SHVT));
5679     Tmp3 = DAG.getNode(ISD::AND, VT, Tmp3, DAG.getConstant(0xFF0000, VT));
5680     Tmp2 = DAG.getNode(ISD::AND, VT, Tmp2, DAG.getConstant(0xFF00, VT));
5681     Tmp4 = DAG.getNode(ISD::OR, VT, Tmp4, Tmp3);
5682     Tmp2 = DAG.getNode(ISD::OR, VT, Tmp2, Tmp1);
5683     return DAG.getNode(ISD::OR, VT, Tmp4, Tmp2);
5684   case MVT::i64:
5685     Tmp8 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(56, SHVT));
5686     Tmp7 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(40, SHVT));
5687     Tmp6 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(24, SHVT));
5688     Tmp5 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(8, SHVT));
5689     Tmp4 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(8, SHVT));
5690     Tmp3 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(24, SHVT));
5691     Tmp2 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(40, SHVT));
5692     Tmp1 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(56, SHVT));
5693     Tmp7 = DAG.getNode(ISD::AND, VT, Tmp7, DAG.getConstant(255ULL<<48, VT));
5694     Tmp6 = DAG.getNode(ISD::AND, VT, Tmp6, DAG.getConstant(255ULL<<40, VT));
5695     Tmp5 = DAG.getNode(ISD::AND, VT, Tmp5, DAG.getConstant(255ULL<<32, VT));
5696     Tmp4 = DAG.getNode(ISD::AND, VT, Tmp4, DAG.getConstant(255ULL<<24, VT));
5697     Tmp3 = DAG.getNode(ISD::AND, VT, Tmp3, DAG.getConstant(255ULL<<16, VT));
5698     Tmp2 = DAG.getNode(ISD::AND, VT, Tmp2, DAG.getConstant(255ULL<<8 , VT));
5699     Tmp8 = DAG.getNode(ISD::OR, VT, Tmp8, Tmp7);
5700     Tmp6 = DAG.getNode(ISD::OR, VT, Tmp6, Tmp5);
5701     Tmp4 = DAG.getNode(ISD::OR, VT, Tmp4, Tmp3);
5702     Tmp2 = DAG.getNode(ISD::OR, VT, Tmp2, Tmp1);
5703     Tmp8 = DAG.getNode(ISD::OR, VT, Tmp8, Tmp6);
5704     Tmp4 = DAG.getNode(ISD::OR, VT, Tmp4, Tmp2);
5705     return DAG.getNode(ISD::OR, VT, Tmp8, Tmp4);
5706   }
5707 }
5708
5709 /// ExpandBitCount - Expand the specified bitcount instruction into operations.
5710 ///
5711 SDOperand SelectionDAGLegalize::ExpandBitCount(unsigned Opc, SDOperand Op) {
5712   switch (Opc) {
5713   default: assert(0 && "Cannot expand this yet!");
5714   case ISD::CTPOP: {
5715     static const uint64_t mask[6] = {
5716       0x5555555555555555ULL, 0x3333333333333333ULL,
5717       0x0F0F0F0F0F0F0F0FULL, 0x00FF00FF00FF00FFULL,
5718       0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL
5719     };
5720     MVT VT = Op.getValueType();
5721     MVT ShVT = TLI.getShiftAmountTy();
5722     unsigned len = VT.getSizeInBits();
5723     for (unsigned i = 0; (1U << i) <= (len / 2); ++i) {
5724       //x = (x & mask[i][len/8]) + (x >> (1 << i) & mask[i][len/8])
5725       SDOperand Tmp2 = DAG.getConstant(mask[i], VT);
5726       SDOperand Tmp3 = DAG.getConstant(1ULL << i, ShVT);
5727       Op = DAG.getNode(ISD::ADD, VT, DAG.getNode(ISD::AND, VT, Op, Tmp2),
5728                        DAG.getNode(ISD::AND, VT,
5729                                    DAG.getNode(ISD::SRL, VT, Op, Tmp3),Tmp2));
5730     }
5731     return Op;
5732   }
5733   case ISD::CTLZ: {
5734     // for now, we do this:
5735     // x = x | (x >> 1);
5736     // x = x | (x >> 2);
5737     // ...
5738     // x = x | (x >>16);
5739     // x = x | (x >>32); // for 64-bit input
5740     // return popcount(~x);
5741     //
5742     // but see also: http://www.hackersdelight.org/HDcode/nlz.cc
5743     MVT VT = Op.getValueType();
5744     MVT ShVT = TLI.getShiftAmountTy();
5745     unsigned len = VT.getSizeInBits();
5746     for (unsigned i = 0; (1U << i) <= (len / 2); ++i) {
5747       SDOperand Tmp3 = DAG.getConstant(1ULL << i, ShVT);
5748       Op = DAG.getNode(ISD::OR, VT, Op, DAG.getNode(ISD::SRL, VT, Op, Tmp3));
5749     }
5750     Op = DAG.getNode(ISD::XOR, VT, Op, DAG.getConstant(~0ULL, VT));
5751     return DAG.getNode(ISD::CTPOP, VT, Op);
5752   }
5753   case ISD::CTTZ: {
5754     // for now, we use: { return popcount(~x & (x - 1)); }
5755     // unless the target has ctlz but not ctpop, in which case we use:
5756     // { return 32 - nlz(~x & (x-1)); }
5757     // see also http://www.hackersdelight.org/HDcode/ntz.cc
5758     MVT VT = Op.getValueType();
5759     SDOperand Tmp2 = DAG.getConstant(~0ULL, VT);
5760     SDOperand Tmp3 = DAG.getNode(ISD::AND, VT,
5761                        DAG.getNode(ISD::XOR, VT, Op, Tmp2),
5762                        DAG.getNode(ISD::SUB, VT, Op, DAG.getConstant(1, VT)));
5763     // If ISD::CTLZ is legal and CTPOP isn't, then do that instead.
5764     if (!TLI.isOperationLegal(ISD::CTPOP, VT) &&
5765         TLI.isOperationLegal(ISD::CTLZ, VT))
5766       return DAG.getNode(ISD::SUB, VT,
5767                          DAG.getConstant(VT.getSizeInBits(), VT),
5768                          DAG.getNode(ISD::CTLZ, VT, Tmp3));
5769     return DAG.getNode(ISD::CTPOP, VT, Tmp3);
5770   }
5771   }
5772 }
5773
5774 /// ExpandOp - Expand the specified SDOperand into its two component pieces
5775 /// Lo&Hi.  Note that the Op MUST be an expanded type.  As a result of this, the
5776 /// LegalizeNodes map is filled in for any results that are not expanded, the
5777 /// ExpandedNodes map is filled in for any results that are expanded, and the
5778 /// Lo/Hi values are returned.
5779 void SelectionDAGLegalize::ExpandOp(SDOperand Op, SDOperand &Lo, SDOperand &Hi){
5780   MVT VT = Op.getValueType();
5781   MVT NVT = TLI.getTypeToTransformTo(VT);
5782   SDNode *Node = Op.Val;
5783   assert(getTypeAction(VT) == Expand && "Not an expanded type!");
5784   assert(((NVT.isInteger() && NVT.bitsLT(VT)) || VT.isFloatingPoint() ||
5785          VT.isVector()) && "Cannot expand to FP value or to larger int value!");
5786
5787   // See if we already expanded it.
5788   DenseMap<SDOperand, std::pair<SDOperand, SDOperand> >::iterator I
5789     = ExpandedNodes.find(Op);
5790   if (I != ExpandedNodes.end()) {
5791     Lo = I->second.first;
5792     Hi = I->second.second;
5793     return;
5794   }
5795
5796   switch (Node->getOpcode()) {
5797   case ISD::CopyFromReg:
5798     assert(0 && "CopyFromReg must be legal!");
5799   case ISD::FP_ROUND_INREG:
5800     if (VT == MVT::ppcf128 && 
5801         TLI.getOperationAction(ISD::FP_ROUND_INREG, VT) == 
5802             TargetLowering::Custom) {
5803       SDOperand SrcLo, SrcHi, Src;
5804       ExpandOp(Op.getOperand(0), SrcLo, SrcHi);
5805       Src = DAG.getNode(ISD::BUILD_PAIR, VT, SrcLo, SrcHi);
5806       SDOperand Result = TLI.LowerOperation(
5807         DAG.getNode(ISD::FP_ROUND_INREG, VT, Src, Op.getOperand(1)), DAG);
5808       assert(Result.Val->getOpcode() == ISD::BUILD_PAIR);
5809       Lo = Result.Val->getOperand(0);
5810       Hi = Result.Val->getOperand(1);
5811       break;
5812     }
5813     // fall through
5814   default:
5815 #ifndef NDEBUG
5816     cerr << "NODE: "; Node->dump(&DAG); cerr << "\n";
5817 #endif
5818     assert(0 && "Do not know how to expand this operator!");
5819     abort();
5820   case ISD::EXTRACT_ELEMENT:
5821     ExpandOp(Node->getOperand(0), Lo, Hi);
5822     if (cast<ConstantSDNode>(Node->getOperand(1))->getValue())
5823       return ExpandOp(Hi, Lo, Hi);
5824     return ExpandOp(Lo, Lo, Hi);
5825   case ISD::EXTRACT_VECTOR_ELT:
5826     assert(VT==MVT::i64 && "Do not know how to expand this operator!");
5827     // ExpandEXTRACT_VECTOR_ELT tolerates invalid result types.
5828     Lo  = ExpandEXTRACT_VECTOR_ELT(Op);
5829     return ExpandOp(Lo, Lo, Hi);
5830   case ISD::UNDEF:
5831     Lo = DAG.getNode(ISD::UNDEF, NVT);
5832     Hi = DAG.getNode(ISD::UNDEF, NVT);
5833     break;
5834   case ISD::Constant: {
5835     unsigned NVTBits = NVT.getSizeInBits();
5836     const APInt &Cst = cast<ConstantSDNode>(Node)->getAPIntValue();
5837     Lo = DAG.getConstant(APInt(Cst).trunc(NVTBits), NVT);
5838     Hi = DAG.getConstant(Cst.lshr(NVTBits).trunc(NVTBits), NVT);
5839     break;
5840   }
5841   case ISD::ConstantFP: {
5842     ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Node);
5843     if (CFP->getValueType(0) == MVT::ppcf128) {
5844       APInt api = CFP->getValueAPF().convertToAPInt();
5845       Lo = DAG.getConstantFP(APFloat(APInt(64, 1, &api.getRawData()[1])),
5846                              MVT::f64);
5847       Hi = DAG.getConstantFP(APFloat(APInt(64, 1, &api.getRawData()[0])), 
5848                              MVT::f64);
5849       break;
5850     }
5851     Lo = ExpandConstantFP(CFP, false, DAG, TLI);
5852     if (getTypeAction(Lo.getValueType()) == Expand)
5853       ExpandOp(Lo, Lo, Hi);
5854     break;
5855   }
5856   case ISD::BUILD_PAIR:
5857     // Return the operands.
5858     Lo = Node->getOperand(0);
5859     Hi = Node->getOperand(1);
5860     break;
5861       
5862   case ISD::MERGE_VALUES:
5863     if (Node->getNumValues() == 1) {
5864       ExpandOp(Op.getOperand(0), Lo, Hi);
5865       break;
5866     }
5867     // FIXME: For now only expand i64,chain = MERGE_VALUES (x, y)
5868     assert(Op.ResNo == 0 && Node->getNumValues() == 2 &&
5869            Op.getValue(1).getValueType() == MVT::Other &&
5870            "unhandled MERGE_VALUES");
5871     ExpandOp(Op.getOperand(0), Lo, Hi);
5872     // Remember that we legalized the chain.
5873     AddLegalizedOperand(Op.getValue(1), LegalizeOp(Op.getOperand(1)));
5874     break;
5875     
5876   case ISD::SIGN_EXTEND_INREG:
5877     ExpandOp(Node->getOperand(0), Lo, Hi);
5878     // sext_inreg the low part if needed.
5879     Lo = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Lo, Node->getOperand(1));
5880     
5881     // The high part gets the sign extension from the lo-part.  This handles
5882     // things like sextinreg V:i64 from i8.
5883     Hi = DAG.getNode(ISD::SRA, NVT, Lo,
5884                      DAG.getConstant(NVT.getSizeInBits()-1,
5885                                      TLI.getShiftAmountTy()));
5886     break;
5887
5888   case ISD::BSWAP: {
5889     ExpandOp(Node->getOperand(0), Lo, Hi);
5890     SDOperand TempLo = DAG.getNode(ISD::BSWAP, NVT, Hi);
5891     Hi = DAG.getNode(ISD::BSWAP, NVT, Lo);
5892     Lo = TempLo;
5893     break;
5894   }
5895     
5896   case ISD::CTPOP:
5897     ExpandOp(Node->getOperand(0), Lo, Hi);
5898     Lo = DAG.getNode(ISD::ADD, NVT,          // ctpop(HL) -> ctpop(H)+ctpop(L)
5899                      DAG.getNode(ISD::CTPOP, NVT, Lo),
5900                      DAG.getNode(ISD::CTPOP, NVT, Hi));
5901     Hi = DAG.getConstant(0, NVT);
5902     break;
5903
5904   case ISD::CTLZ: {
5905     // ctlz (HL) -> ctlz(H) != 32 ? ctlz(H) : (ctlz(L)+32)
5906     ExpandOp(Node->getOperand(0), Lo, Hi);
5907     SDOperand BitsC = DAG.getConstant(NVT.getSizeInBits(), NVT);
5908     SDOperand HLZ = DAG.getNode(ISD::CTLZ, NVT, Hi);
5909     SDOperand TopNotZero = DAG.getSetCC(TLI.getSetCCResultType(HLZ), HLZ, BitsC,
5910                                         ISD::SETNE);
5911     SDOperand LowPart = DAG.getNode(ISD::CTLZ, NVT, Lo);
5912     LowPart = DAG.getNode(ISD::ADD, NVT, LowPart, BitsC);
5913
5914     Lo = DAG.getNode(ISD::SELECT, NVT, TopNotZero, HLZ, LowPart);
5915     Hi = DAG.getConstant(0, NVT);
5916     break;
5917   }
5918
5919   case ISD::CTTZ: {
5920     // cttz (HL) -> cttz(L) != 32 ? cttz(L) : (cttz(H)+32)
5921     ExpandOp(Node->getOperand(0), Lo, Hi);
5922     SDOperand BitsC = DAG.getConstant(NVT.getSizeInBits(), NVT);
5923     SDOperand LTZ = DAG.getNode(ISD::CTTZ, NVT, Lo);
5924     SDOperand BotNotZero = DAG.getSetCC(TLI.getSetCCResultType(LTZ), LTZ, BitsC,
5925                                         ISD::SETNE);
5926     SDOperand HiPart = DAG.getNode(ISD::CTTZ, NVT, Hi);
5927     HiPart = DAG.getNode(ISD::ADD, NVT, HiPart, BitsC);
5928
5929     Lo = DAG.getNode(ISD::SELECT, NVT, BotNotZero, LTZ, HiPart);
5930     Hi = DAG.getConstant(0, NVT);
5931     break;
5932   }
5933
5934   case ISD::VAARG: {
5935     SDOperand Ch = Node->getOperand(0);   // Legalize the chain.
5936     SDOperand Ptr = Node->getOperand(1);  // Legalize the pointer.
5937     Lo = DAG.getVAArg(NVT, Ch, Ptr, Node->getOperand(2));
5938     Hi = DAG.getVAArg(NVT, Lo.getValue(1), Ptr, Node->getOperand(2));
5939
5940     // Remember that we legalized the chain.
5941     Hi = LegalizeOp(Hi);
5942     AddLegalizedOperand(Op.getValue(1), Hi.getValue(1));
5943     if (TLI.isBigEndian())
5944       std::swap(Lo, Hi);
5945     break;
5946   }
5947     
5948   case ISD::LOAD: {
5949     LoadSDNode *LD = cast<LoadSDNode>(Node);
5950     SDOperand Ch  = LD->getChain();    // Legalize the chain.
5951     SDOperand Ptr = LD->getBasePtr();  // Legalize the pointer.
5952     ISD::LoadExtType ExtType = LD->getExtensionType();
5953     int SVOffset = LD->getSrcValueOffset();
5954     unsigned Alignment = LD->getAlignment();
5955     bool isVolatile = LD->isVolatile();
5956
5957     if (ExtType == ISD::NON_EXTLOAD) {
5958       Lo = DAG.getLoad(NVT, Ch, Ptr, LD->getSrcValue(), SVOffset,
5959                        isVolatile, Alignment);
5960       if (VT == MVT::f32 || VT == MVT::f64) {
5961         // f32->i32 or f64->i64 one to one expansion.
5962         // Remember that we legalized the chain.
5963         AddLegalizedOperand(SDOperand(Node, 1), LegalizeOp(Lo.getValue(1)));
5964         // Recursively expand the new load.
5965         if (getTypeAction(NVT) == Expand)
5966           ExpandOp(Lo, Lo, Hi);
5967         break;
5968       }
5969
5970       // Increment the pointer to the other half.
5971       unsigned IncrementSize = Lo.getValueType().getSizeInBits()/8;
5972       Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
5973                         DAG.getIntPtrConstant(IncrementSize));
5974       SVOffset += IncrementSize;
5975       Alignment = MinAlign(Alignment, IncrementSize);
5976       Hi = DAG.getLoad(NVT, Ch, Ptr, LD->getSrcValue(), SVOffset,
5977                        isVolatile, Alignment);
5978
5979       // Build a factor node to remember that this load is independent of the
5980       // other one.
5981       SDOperand TF = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo.getValue(1),
5982                                  Hi.getValue(1));
5983
5984       // Remember that we legalized the chain.
5985       AddLegalizedOperand(Op.getValue(1), LegalizeOp(TF));
5986       if (TLI.isBigEndian())
5987         std::swap(Lo, Hi);
5988     } else {
5989       MVT EVT = LD->getMemoryVT();
5990
5991       if ((VT == MVT::f64 && EVT == MVT::f32) ||
5992           (VT == MVT::ppcf128 && (EVT==MVT::f64 || EVT==MVT::f32))) {
5993         // f64 = EXTLOAD f32 should expand to LOAD, FP_EXTEND
5994         SDOperand Load = DAG.getLoad(EVT, Ch, Ptr, LD->getSrcValue(),
5995                                      SVOffset, isVolatile, Alignment);
5996         // Remember that we legalized the chain.
5997         AddLegalizedOperand(SDOperand(Node, 1), LegalizeOp(Load.getValue(1)));
5998         ExpandOp(DAG.getNode(ISD::FP_EXTEND, VT, Load), Lo, Hi);
5999         break;
6000       }
6001     
6002       if (EVT == NVT)
6003         Lo = DAG.getLoad(NVT, Ch, Ptr, LD->getSrcValue(),
6004                          SVOffset, isVolatile, Alignment);
6005       else
6006         Lo = DAG.getExtLoad(ExtType, NVT, Ch, Ptr, LD->getSrcValue(),
6007                             SVOffset, EVT, isVolatile,
6008                             Alignment);
6009     
6010       // Remember that we legalized the chain.
6011       AddLegalizedOperand(SDOperand(Node, 1), LegalizeOp(Lo.getValue(1)));
6012
6013       if (ExtType == ISD::SEXTLOAD) {
6014         // The high part is obtained by SRA'ing all but one of the bits of the
6015         // lo part.
6016         unsigned LoSize = Lo.getValueType().getSizeInBits();
6017         Hi = DAG.getNode(ISD::SRA, NVT, Lo,
6018                          DAG.getConstant(LoSize-1, TLI.getShiftAmountTy()));
6019       } else if (ExtType == ISD::ZEXTLOAD) {
6020         // The high part is just a zero.
6021         Hi = DAG.getConstant(0, NVT);
6022       } else /* if (ExtType == ISD::EXTLOAD) */ {
6023         // The high part is undefined.
6024         Hi = DAG.getNode(ISD::UNDEF, NVT);
6025       }
6026     }
6027     break;
6028   }
6029   case ISD::AND:
6030   case ISD::OR:
6031   case ISD::XOR: {   // Simple logical operators -> two trivial pieces.
6032     SDOperand LL, LH, RL, RH;
6033     ExpandOp(Node->getOperand(0), LL, LH);
6034     ExpandOp(Node->getOperand(1), RL, RH);
6035     Lo = DAG.getNode(Node->getOpcode(), NVT, LL, RL);
6036     Hi = DAG.getNode(Node->getOpcode(), NVT, LH, RH);
6037     break;
6038   }
6039   case ISD::SELECT: {
6040     SDOperand LL, LH, RL, RH;
6041     ExpandOp(Node->getOperand(1), LL, LH);
6042     ExpandOp(Node->getOperand(2), RL, RH);
6043     if (getTypeAction(NVT) == Expand)
6044       NVT = TLI.getTypeToExpandTo(NVT);
6045     Lo = DAG.getNode(ISD::SELECT, NVT, Node->getOperand(0), LL, RL);
6046     if (VT != MVT::f32)
6047       Hi = DAG.getNode(ISD::SELECT, NVT, Node->getOperand(0), LH, RH);
6048     break;
6049   }
6050   case ISD::SELECT_CC: {
6051     SDOperand TL, TH, FL, FH;
6052     ExpandOp(Node->getOperand(2), TL, TH);
6053     ExpandOp(Node->getOperand(3), FL, FH);
6054     if (getTypeAction(NVT) == Expand)
6055       NVT = TLI.getTypeToExpandTo(NVT);
6056     Lo = DAG.getNode(ISD::SELECT_CC, NVT, Node->getOperand(0),
6057                      Node->getOperand(1), TL, FL, Node->getOperand(4));
6058     if (VT != MVT::f32)
6059       Hi = DAG.getNode(ISD::SELECT_CC, NVT, Node->getOperand(0),
6060                        Node->getOperand(1), TH, FH, Node->getOperand(4));
6061     break;
6062   }
6063   case ISD::ANY_EXTEND:
6064     // The low part is any extension of the input (which degenerates to a copy).
6065     Lo = DAG.getNode(ISD::ANY_EXTEND, NVT, Node->getOperand(0));
6066     // The high part is undefined.
6067     Hi = DAG.getNode(ISD::UNDEF, NVT);
6068     break;
6069   case ISD::SIGN_EXTEND: {
6070     // The low part is just a sign extension of the input (which degenerates to
6071     // a copy).
6072     Lo = DAG.getNode(ISD::SIGN_EXTEND, NVT, Node->getOperand(0));
6073
6074     // The high part is obtained by SRA'ing all but one of the bits of the lo
6075     // part.
6076     unsigned LoSize = Lo.getValueType().getSizeInBits();
6077     Hi = DAG.getNode(ISD::SRA, NVT, Lo,
6078                      DAG.getConstant(LoSize-1, TLI.getShiftAmountTy()));
6079     break;
6080   }
6081   case ISD::ZERO_EXTEND:
6082     // The low part is just a zero extension of the input (which degenerates to
6083     // a copy).
6084     Lo = DAG.getNode(ISD::ZERO_EXTEND, NVT, Node->getOperand(0));
6085
6086     // The high part is just a zero.
6087     Hi = DAG.getConstant(0, NVT);
6088     break;
6089     
6090   case ISD::TRUNCATE: {
6091     // The input value must be larger than this value.  Expand *it*.
6092     SDOperand NewLo;
6093     ExpandOp(Node->getOperand(0), NewLo, Hi);
6094     
6095     // The low part is now either the right size, or it is closer.  If not the
6096     // right size, make an illegal truncate so we recursively expand it.
6097     if (NewLo.getValueType() != Node->getValueType(0))
6098       NewLo = DAG.getNode(ISD::TRUNCATE, Node->getValueType(0), NewLo);
6099     ExpandOp(NewLo, Lo, Hi);
6100     break;
6101   }
6102     
6103   case ISD::BIT_CONVERT: {
6104     SDOperand Tmp;
6105     if (TLI.getOperationAction(ISD::BIT_CONVERT, VT) == TargetLowering::Custom){
6106       // If the target wants to, allow it to lower this itself.
6107       switch (getTypeAction(Node->getOperand(0).getValueType())) {
6108       case Expand: assert(0 && "cannot expand FP!");
6109       case Legal:   Tmp = LegalizeOp(Node->getOperand(0)); break;
6110       case Promote: Tmp = PromoteOp (Node->getOperand(0)); break;
6111       }
6112       Tmp = TLI.LowerOperation(DAG.getNode(ISD::BIT_CONVERT, VT, Tmp), DAG);
6113     }
6114
6115     // f32 / f64 must be expanded to i32 / i64.
6116     if (VT == MVT::f32 || VT == MVT::f64) {
6117       Lo = DAG.getNode(ISD::BIT_CONVERT, NVT, Node->getOperand(0));
6118       if (getTypeAction(NVT) == Expand)
6119         ExpandOp(Lo, Lo, Hi);
6120       break;
6121     }
6122
6123     // If source operand will be expanded to the same type as VT, i.e.
6124     // i64 <- f64, i32 <- f32, expand the source operand instead.
6125     MVT VT0 = Node->getOperand(0).getValueType();
6126     if (getTypeAction(VT0) == Expand && TLI.getTypeToTransformTo(VT0) == VT) {
6127       ExpandOp(Node->getOperand(0), Lo, Hi);
6128       break;
6129     }
6130
6131     // Turn this into a load/store pair by default.
6132     if (Tmp.Val == 0)
6133       Tmp = EmitStackConvert(Node->getOperand(0), VT, VT);
6134     
6135     ExpandOp(Tmp, Lo, Hi);
6136     break;
6137   }
6138
6139   case ISD::READCYCLECOUNTER: {
6140     assert(TLI.getOperationAction(ISD::READCYCLECOUNTER, VT) == 
6141                  TargetLowering::Custom &&
6142            "Must custom expand ReadCycleCounter");
6143     SDOperand Tmp = TLI.LowerOperation(Op, DAG);
6144     assert(Tmp.Val && "Node must be custom expanded!");
6145     ExpandOp(Tmp.getValue(0), Lo, Hi);
6146     AddLegalizedOperand(SDOperand(Node, 1), // Remember we legalized the chain.
6147                         LegalizeOp(Tmp.getValue(1)));
6148     break;
6149   }
6150
6151   case ISD::ATOMIC_CMP_SWAP: {
6152     SDOperand Tmp = TLI.LowerOperation(Op, DAG);
6153     assert(Tmp.Val && "Node must be custom expanded!");
6154     ExpandOp(Tmp.getValue(0), Lo, Hi);
6155     AddLegalizedOperand(SDOperand(Node, 1), // Remember we legalized the chain.
6156                         LegalizeOp(Tmp.getValue(1)));
6157     break;
6158   }
6159
6160
6161
6162     // These operators cannot be expanded directly, emit them as calls to
6163     // library functions.
6164   case ISD::FP_TO_SINT: {
6165     if (TLI.getOperationAction(ISD::FP_TO_SINT, VT) == TargetLowering::Custom) {
6166       SDOperand Op;
6167       switch (getTypeAction(Node->getOperand(0).getValueType())) {
6168       case Expand: assert(0 && "cannot expand FP!");
6169       case Legal:   Op = LegalizeOp(Node->getOperand(0)); break;
6170       case Promote: Op = PromoteOp (Node->getOperand(0)); break;
6171       }
6172
6173       Op = TLI.LowerOperation(DAG.getNode(ISD::FP_TO_SINT, VT, Op), DAG);
6174
6175       // Now that the custom expander is done, expand the result, which is still
6176       // VT.
6177       if (Op.Val) {
6178         ExpandOp(Op, Lo, Hi);
6179         break;
6180       }
6181     }
6182
6183     RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
6184     if (VT == MVT::i64) {
6185       if (Node->getOperand(0).getValueType() == MVT::f32)
6186         LC = RTLIB::FPTOSINT_F32_I64;
6187       else if (Node->getOperand(0).getValueType() == MVT::f64)
6188         LC = RTLIB::FPTOSINT_F64_I64;
6189       else if (Node->getOperand(0).getValueType() == MVT::f80)
6190         LC = RTLIB::FPTOSINT_F80_I64;
6191       else if (Node->getOperand(0).getValueType() == MVT::ppcf128)
6192         LC = RTLIB::FPTOSINT_PPCF128_I64;
6193       Lo = ExpandLibCall(LC, Node, false/*sign irrelevant*/, Hi);
6194     } else if (VT == MVT::i128) {
6195       if (Node->getOperand(0).getValueType() == MVT::f32)
6196         LC = RTLIB::FPTOSINT_F32_I128;
6197       else if (Node->getOperand(0).getValueType() == MVT::f64)
6198         LC = RTLIB::FPTOSINT_F64_I128;
6199       else if (Node->getOperand(0).getValueType() == MVT::f80)
6200         LC = RTLIB::FPTOSINT_F80_I128;
6201       else if (Node->getOperand(0).getValueType() == MVT::ppcf128)
6202         LC = RTLIB::FPTOSINT_PPCF128_I128;
6203       Lo = ExpandLibCall(LC, Node, false/*sign irrelevant*/, Hi);
6204     } else {
6205       assert(0 && "Unexpected uint-to-fp conversion!");
6206     }
6207     break;
6208   }
6209
6210   case ISD::FP_TO_UINT: {
6211     if (TLI.getOperationAction(ISD::FP_TO_UINT, VT) == TargetLowering::Custom) {
6212       SDOperand Op;
6213       switch (getTypeAction(Node->getOperand(0).getValueType())) {
6214         case Expand: assert(0 && "cannot expand FP!");
6215         case Legal:   Op = LegalizeOp(Node->getOperand(0)); break;
6216         case Promote: Op = PromoteOp (Node->getOperand(0)); break;
6217       }
6218         
6219       Op = TLI.LowerOperation(DAG.getNode(ISD::FP_TO_UINT, VT, Op), DAG);
6220
6221       // Now that the custom expander is done, expand the result.
6222       if (Op.Val) {
6223         ExpandOp(Op, Lo, Hi);
6224         break;
6225       }
6226     }
6227
6228     RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
6229     if (VT == MVT::i64) {
6230       if (Node->getOperand(0).getValueType() == MVT::f32)
6231         LC = RTLIB::FPTOUINT_F32_I64;
6232       else if (Node->getOperand(0).getValueType() == MVT::f64)
6233         LC = RTLIB::FPTOUINT_F64_I64;
6234       else if (Node->getOperand(0).getValueType() == MVT::f80)
6235         LC = RTLIB::FPTOUINT_F80_I64;
6236       else if (Node->getOperand(0).getValueType() == MVT::ppcf128)
6237         LC = RTLIB::FPTOUINT_PPCF128_I64;
6238       Lo = ExpandLibCall(LC, Node, false/*sign irrelevant*/, Hi);
6239     } else if (VT == MVT::i128) {
6240       if (Node->getOperand(0).getValueType() == MVT::f32)
6241         LC = RTLIB::FPTOUINT_F32_I128;
6242       else if (Node->getOperand(0).getValueType() == MVT::f64)
6243         LC = RTLIB::FPTOUINT_F64_I128;
6244       else if (Node->getOperand(0).getValueType() == MVT::f80)
6245         LC = RTLIB::FPTOUINT_F80_I128;
6246       else if (Node->getOperand(0).getValueType() == MVT::ppcf128)
6247         LC = RTLIB::FPTOUINT_PPCF128_I128;
6248       Lo = ExpandLibCall(LC, Node, false/*sign irrelevant*/, Hi);
6249     } else {
6250       assert(0 && "Unexpected uint-to-fp conversion!");
6251     }
6252     break;
6253   }
6254
6255   case ISD::SHL: {
6256     // If the target wants custom lowering, do so.
6257     SDOperand ShiftAmt = LegalizeOp(Node->getOperand(1));
6258     if (TLI.getOperationAction(ISD::SHL, VT) == TargetLowering::Custom) {
6259       SDOperand Op = DAG.getNode(ISD::SHL, VT, Node->getOperand(0), ShiftAmt);
6260       Op = TLI.LowerOperation(Op, DAG);
6261       if (Op.Val) {
6262         // Now that the custom expander is done, expand the result, which is
6263         // still VT.
6264         ExpandOp(Op, Lo, Hi);
6265         break;
6266       }
6267     }
6268     
6269     // If ADDC/ADDE are supported and if the shift amount is a constant 1, emit 
6270     // this X << 1 as X+X.
6271     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(ShiftAmt)) {
6272       if (ShAmt->getAPIntValue() == 1 && TLI.isOperationLegal(ISD::ADDC, NVT) && 
6273           TLI.isOperationLegal(ISD::ADDE, NVT)) {
6274         SDOperand LoOps[2], HiOps[3];
6275         ExpandOp(Node->getOperand(0), LoOps[0], HiOps[0]);
6276         SDVTList VTList = DAG.getVTList(LoOps[0].getValueType(), MVT::Flag);
6277         LoOps[1] = LoOps[0];
6278         Lo = DAG.getNode(ISD::ADDC, VTList, LoOps, 2);
6279
6280         HiOps[1] = HiOps[0];
6281         HiOps[2] = Lo.getValue(1);
6282         Hi = DAG.getNode(ISD::ADDE, VTList, HiOps, 3);
6283         break;
6284       }
6285     }
6286     
6287     // If we can emit an efficient shift operation, do so now.
6288     if (ExpandShift(ISD::SHL, Node->getOperand(0), ShiftAmt, Lo, Hi))
6289       break;
6290
6291     // If this target supports SHL_PARTS, use it.
6292     TargetLowering::LegalizeAction Action =
6293       TLI.getOperationAction(ISD::SHL_PARTS, NVT);
6294     if ((Action == TargetLowering::Legal && TLI.isTypeLegal(NVT)) ||
6295         Action == TargetLowering::Custom) {
6296       ExpandShiftParts(ISD::SHL_PARTS, Node->getOperand(0), ShiftAmt, Lo, Hi);
6297       break;
6298     }
6299
6300     // Otherwise, emit a libcall.
6301     Lo = ExpandLibCall(RTLIB::SHL_I64, Node, false/*left shift=unsigned*/, Hi);
6302     break;
6303   }
6304
6305   case ISD::SRA: {
6306     // If the target wants custom lowering, do so.
6307     SDOperand ShiftAmt = LegalizeOp(Node->getOperand(1));
6308     if (TLI.getOperationAction(ISD::SRA, VT) == TargetLowering::Custom) {
6309       SDOperand Op = DAG.getNode(ISD::SRA, VT, Node->getOperand(0), ShiftAmt);
6310       Op = TLI.LowerOperation(Op, DAG);
6311       if (Op.Val) {
6312         // Now that the custom expander is done, expand the result, which is
6313         // still VT.
6314         ExpandOp(Op, Lo, Hi);
6315         break;
6316       }
6317     }
6318     
6319     // If we can emit an efficient shift operation, do so now.
6320     if (ExpandShift(ISD::SRA, Node->getOperand(0), ShiftAmt, Lo, Hi))
6321       break;
6322
6323     // If this target supports SRA_PARTS, use it.
6324     TargetLowering::LegalizeAction Action =
6325       TLI.getOperationAction(ISD::SRA_PARTS, NVT);
6326     if ((Action == TargetLowering::Legal && TLI.isTypeLegal(NVT)) ||
6327         Action == TargetLowering::Custom) {
6328       ExpandShiftParts(ISD::SRA_PARTS, Node->getOperand(0), ShiftAmt, Lo, Hi);
6329       break;
6330     }
6331
6332     // Otherwise, emit a libcall.
6333     Lo = ExpandLibCall(RTLIB::SRA_I64, Node, true/*ashr is signed*/, Hi);
6334     break;
6335   }
6336
6337   case ISD::SRL: {
6338     // If the target wants custom lowering, do so.
6339     SDOperand ShiftAmt = LegalizeOp(Node->getOperand(1));
6340     if (TLI.getOperationAction(ISD::SRL, VT) == TargetLowering::Custom) {
6341       SDOperand Op = DAG.getNode(ISD::SRL, VT, Node->getOperand(0), ShiftAmt);
6342       Op = TLI.LowerOperation(Op, DAG);
6343       if (Op.Val) {
6344         // Now that the custom expander is done, expand the result, which is
6345         // still VT.
6346         ExpandOp(Op, Lo, Hi);
6347         break;
6348       }
6349     }
6350
6351     // If we can emit an efficient shift operation, do so now.
6352     if (ExpandShift(ISD::SRL, Node->getOperand(0), ShiftAmt, Lo, Hi))
6353       break;
6354
6355     // If this target supports SRL_PARTS, use it.
6356     TargetLowering::LegalizeAction Action =
6357       TLI.getOperationAction(ISD::SRL_PARTS, NVT);
6358     if ((Action == TargetLowering::Legal && TLI.isTypeLegal(NVT)) ||
6359         Action == TargetLowering::Custom) {
6360       ExpandShiftParts(ISD::SRL_PARTS, Node->getOperand(0), ShiftAmt, Lo, Hi);
6361       break;
6362     }
6363
6364     // Otherwise, emit a libcall.
6365     Lo = ExpandLibCall(RTLIB::SRL_I64, Node, false/*lshr is unsigned*/, Hi);
6366     break;
6367   }
6368
6369   case ISD::ADD:
6370   case ISD::SUB: {
6371     // If the target wants to custom expand this, let them.
6372     if (TLI.getOperationAction(Node->getOpcode(), VT) ==
6373             TargetLowering::Custom) {
6374       SDOperand Result = TLI.LowerOperation(Op, DAG);
6375       if (Result.Val) {
6376         ExpandOp(Result, Lo, Hi);
6377         break;
6378       }
6379     }
6380     
6381     // Expand the subcomponents.
6382     SDOperand LHSL, LHSH, RHSL, RHSH;
6383     ExpandOp(Node->getOperand(0), LHSL, LHSH);
6384     ExpandOp(Node->getOperand(1), RHSL, RHSH);
6385     SDVTList VTList = DAG.getVTList(LHSL.getValueType(), MVT::Flag);
6386     SDOperand LoOps[2], HiOps[3];
6387     LoOps[0] = LHSL;
6388     LoOps[1] = RHSL;
6389     HiOps[0] = LHSH;
6390     HiOps[1] = RHSH;
6391     if (Node->getOpcode() == ISD::ADD) {
6392       Lo = DAG.getNode(ISD::ADDC, VTList, LoOps, 2);
6393       HiOps[2] = Lo.getValue(1);
6394       Hi = DAG.getNode(ISD::ADDE, VTList, HiOps, 3);
6395     } else {
6396       Lo = DAG.getNode(ISD::SUBC, VTList, LoOps, 2);
6397       HiOps[2] = Lo.getValue(1);
6398       Hi = DAG.getNode(ISD::SUBE, VTList, HiOps, 3);
6399     }
6400     break;
6401   }
6402     
6403   case ISD::ADDC:
6404   case ISD::SUBC: {
6405     // Expand the subcomponents.
6406     SDOperand LHSL, LHSH, RHSL, RHSH;
6407     ExpandOp(Node->getOperand(0), LHSL, LHSH);
6408     ExpandOp(Node->getOperand(1), RHSL, RHSH);
6409     SDVTList VTList = DAG.getVTList(LHSL.getValueType(), MVT::Flag);
6410     SDOperand LoOps[2] = { LHSL, RHSL };
6411     SDOperand HiOps[3] = { LHSH, RHSH };
6412     
6413     if (Node->getOpcode() == ISD::ADDC) {
6414       Lo = DAG.getNode(ISD::ADDC, VTList, LoOps, 2);
6415       HiOps[2] = Lo.getValue(1);
6416       Hi = DAG.getNode(ISD::ADDE, VTList, HiOps, 3);
6417     } else {
6418       Lo = DAG.getNode(ISD::SUBC, VTList, LoOps, 2);
6419       HiOps[2] = Lo.getValue(1);
6420       Hi = DAG.getNode(ISD::SUBE, VTList, HiOps, 3);
6421     }
6422     // Remember that we legalized the flag.
6423     AddLegalizedOperand(Op.getValue(1), LegalizeOp(Hi.getValue(1)));
6424     break;
6425   }
6426   case ISD::ADDE:
6427   case ISD::SUBE: {
6428     // Expand the subcomponents.
6429     SDOperand LHSL, LHSH, RHSL, RHSH;
6430     ExpandOp(Node->getOperand(0), LHSL, LHSH);
6431     ExpandOp(Node->getOperand(1), RHSL, RHSH);
6432     SDVTList VTList = DAG.getVTList(LHSL.getValueType(), MVT::Flag);
6433     SDOperand LoOps[3] = { LHSL, RHSL, Node->getOperand(2) };
6434     SDOperand HiOps[3] = { LHSH, RHSH };
6435     
6436     Lo = DAG.getNode(Node->getOpcode(), VTList, LoOps, 3);
6437     HiOps[2] = Lo.getValue(1);
6438     Hi = DAG.getNode(Node->getOpcode(), VTList, HiOps, 3);
6439     
6440     // Remember that we legalized the flag.
6441     AddLegalizedOperand(Op.getValue(1), LegalizeOp(Hi.getValue(1)));
6442     break;
6443   }
6444   case ISD::MUL: {
6445     // If the target wants to custom expand this, let them.
6446     if (TLI.getOperationAction(ISD::MUL, VT) == TargetLowering::Custom) {
6447       SDOperand New = TLI.LowerOperation(Op, DAG);
6448       if (New.Val) {
6449         ExpandOp(New, Lo, Hi);
6450         break;
6451       }
6452     }
6453     
6454     bool HasMULHS = TLI.isOperationLegal(ISD::MULHS, NVT);
6455     bool HasMULHU = TLI.isOperationLegal(ISD::MULHU, NVT);
6456     bool HasSMUL_LOHI = TLI.isOperationLegal(ISD::SMUL_LOHI, NVT);
6457     bool HasUMUL_LOHI = TLI.isOperationLegal(ISD::UMUL_LOHI, NVT);
6458     if (HasMULHU || HasMULHS || HasUMUL_LOHI || HasSMUL_LOHI) {
6459       SDOperand LL, LH, RL, RH;
6460       ExpandOp(Node->getOperand(0), LL, LH);
6461       ExpandOp(Node->getOperand(1), RL, RH);
6462       unsigned OuterBitSize = Op.getValueSizeInBits();
6463       unsigned InnerBitSize = RH.getValueSizeInBits();
6464       unsigned LHSSB = DAG.ComputeNumSignBits(Op.getOperand(0));
6465       unsigned RHSSB = DAG.ComputeNumSignBits(Op.getOperand(1));
6466       APInt HighMask = APInt::getHighBitsSet(OuterBitSize, InnerBitSize);
6467       if (DAG.MaskedValueIsZero(Node->getOperand(0), HighMask) &&
6468           DAG.MaskedValueIsZero(Node->getOperand(1), HighMask)) {
6469         // The inputs are both zero-extended.
6470         if (HasUMUL_LOHI) {
6471           // We can emit a umul_lohi.
6472           Lo = DAG.getNode(ISD::UMUL_LOHI, DAG.getVTList(NVT, NVT), LL, RL);
6473           Hi = SDOperand(Lo.Val, 1);
6474           break;
6475         }
6476         if (HasMULHU) {
6477           // We can emit a mulhu+mul.
6478           Lo = DAG.getNode(ISD::MUL, NVT, LL, RL);
6479           Hi = DAG.getNode(ISD::MULHU, NVT, LL, RL);
6480           break;
6481         }
6482       }
6483       if (LHSSB > InnerBitSize && RHSSB > InnerBitSize) {
6484         // The input values are both sign-extended.
6485         if (HasSMUL_LOHI) {
6486           // We can emit a smul_lohi.
6487           Lo = DAG.getNode(ISD::SMUL_LOHI, DAG.getVTList(NVT, NVT), LL, RL);
6488           Hi = SDOperand(Lo.Val, 1);
6489           break;
6490         }
6491         if (HasMULHS) {
6492           // We can emit a mulhs+mul.
6493           Lo = DAG.getNode(ISD::MUL, NVT, LL, RL);
6494           Hi = DAG.getNode(ISD::MULHS, NVT, LL, RL);
6495           break;
6496         }
6497       }
6498       if (HasUMUL_LOHI) {
6499         // Lo,Hi = umul LHS, RHS.
6500         SDOperand UMulLOHI = DAG.getNode(ISD::UMUL_LOHI,
6501                                          DAG.getVTList(NVT, NVT), LL, RL);
6502         Lo = UMulLOHI;
6503         Hi = UMulLOHI.getValue(1);
6504         RH = DAG.getNode(ISD::MUL, NVT, LL, RH);
6505         LH = DAG.getNode(ISD::MUL, NVT, LH, RL);
6506         Hi = DAG.getNode(ISD::ADD, NVT, Hi, RH);
6507         Hi = DAG.getNode(ISD::ADD, NVT, Hi, LH);
6508         break;
6509       }
6510       if (HasMULHU) {
6511         Lo = DAG.getNode(ISD::MUL, NVT, LL, RL);
6512         Hi = DAG.getNode(ISD::MULHU, NVT, LL, RL);
6513         RH = DAG.getNode(ISD::MUL, NVT, LL, RH);
6514         LH = DAG.getNode(ISD::MUL, NVT, LH, RL);
6515         Hi = DAG.getNode(ISD::ADD, NVT, Hi, RH);
6516         Hi = DAG.getNode(ISD::ADD, NVT, Hi, LH);
6517         break;
6518       }
6519     }
6520
6521     // If nothing else, we can make a libcall.
6522     Lo = ExpandLibCall(RTLIB::MUL_I64, Node, false/*sign irrelevant*/, Hi);
6523     break;
6524   }
6525   case ISD::SDIV:
6526     Lo = ExpandLibCall(RTLIB::SDIV_I64, Node, true, Hi);
6527     break;
6528   case ISD::UDIV:
6529     Lo = ExpandLibCall(RTLIB::UDIV_I64, Node, true, Hi);
6530     break;
6531   case ISD::SREM:
6532     Lo = ExpandLibCall(RTLIB::SREM_I64, Node, true, Hi);
6533     break;
6534   case ISD::UREM:
6535     Lo = ExpandLibCall(RTLIB::UREM_I64, Node, true, Hi);
6536     break;
6537
6538   case ISD::FADD:
6539     Lo = ExpandLibCall(GetFPLibCall(VT, RTLIB::ADD_F32,
6540                                         RTLIB::ADD_F64,
6541                                         RTLIB::ADD_F80,
6542                                         RTLIB::ADD_PPCF128),
6543                        Node, false, Hi);
6544     break;
6545   case ISD::FSUB:
6546     Lo = ExpandLibCall(GetFPLibCall(VT, RTLIB::SUB_F32,
6547                                         RTLIB::SUB_F64,
6548                                         RTLIB::SUB_F80,
6549                                         RTLIB::SUB_PPCF128),
6550                        Node, false, Hi);
6551     break;
6552   case ISD::FMUL:
6553     Lo = ExpandLibCall(GetFPLibCall(VT, RTLIB::MUL_F32,
6554                                         RTLIB::MUL_F64,
6555                                         RTLIB::MUL_F80,
6556                                         RTLIB::MUL_PPCF128),
6557                        Node, false, Hi);
6558     break;
6559   case ISD::FDIV:
6560     Lo = ExpandLibCall(GetFPLibCall(VT, RTLIB::DIV_F32,
6561                                         RTLIB::DIV_F64,
6562                                         RTLIB::DIV_F80,
6563                                         RTLIB::DIV_PPCF128),
6564                        Node, false, Hi);
6565     break;
6566   case ISD::FP_EXTEND:
6567     if (VT == MVT::ppcf128) {
6568       assert(Node->getOperand(0).getValueType()==MVT::f32 ||
6569              Node->getOperand(0).getValueType()==MVT::f64);
6570       const uint64_t zero = 0;
6571       if (Node->getOperand(0).getValueType()==MVT::f32)
6572         Hi = DAG.getNode(ISD::FP_EXTEND, MVT::f64, Node->getOperand(0));
6573       else
6574         Hi = Node->getOperand(0);
6575       Lo = DAG.getConstantFP(APFloat(APInt(64, 1, &zero)), MVT::f64);
6576       break;
6577     }
6578     Lo = ExpandLibCall(RTLIB::FPEXT_F32_F64, Node, true, Hi);
6579     break;
6580   case ISD::FP_ROUND:
6581     Lo = ExpandLibCall(RTLIB::FPROUND_F64_F32, Node, true, Hi);
6582     break;
6583   case ISD::FPOWI:
6584     Lo = ExpandLibCall(GetFPLibCall(VT, RTLIB::POWI_F32,
6585                                         RTLIB::POWI_F64,
6586                                         RTLIB::POWI_F80,
6587                                         RTLIB::POWI_PPCF128),
6588                        Node, false, Hi);
6589     break;
6590   case ISD::FSQRT:
6591   case ISD::FSIN:
6592   case ISD::FCOS: {
6593     RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
6594     switch(Node->getOpcode()) {
6595     case ISD::FSQRT:
6596       LC = GetFPLibCall(VT, RTLIB::SQRT_F32, RTLIB::SQRT_F64,
6597                         RTLIB::SQRT_F80, RTLIB::SQRT_PPCF128);
6598       break;
6599     case ISD::FSIN:
6600       LC = GetFPLibCall(VT, RTLIB::SIN_F32, RTLIB::SIN_F64,
6601                         RTLIB::SIN_F80, RTLIB::SIN_PPCF128);
6602       break;
6603     case ISD::FCOS:
6604       LC = GetFPLibCall(VT, RTLIB::COS_F32, RTLIB::COS_F64,
6605                         RTLIB::COS_F80, RTLIB::COS_PPCF128);
6606       break;
6607     default: assert(0 && "Unreachable!");
6608     }
6609     Lo = ExpandLibCall(LC, Node, false, Hi);
6610     break;
6611   }
6612   case ISD::FABS: {
6613     if (VT == MVT::ppcf128) {
6614       SDOperand Tmp;
6615       ExpandOp(Node->getOperand(0), Lo, Tmp);
6616       Hi = DAG.getNode(ISD::FABS, NVT, Tmp);
6617       // lo = hi==fabs(hi) ? lo : -lo;
6618       Lo = DAG.getNode(ISD::SELECT_CC, NVT, Hi, Tmp,
6619                     Lo, DAG.getNode(ISD::FNEG, NVT, Lo),
6620                     DAG.getCondCode(ISD::SETEQ));
6621       break;
6622     }
6623     SDOperand Mask = (VT == MVT::f64)
6624       ? DAG.getConstantFP(BitsToDouble(~(1ULL << 63)), VT)
6625       : DAG.getConstantFP(BitsToFloat(~(1U << 31)), VT);
6626     Mask = DAG.getNode(ISD::BIT_CONVERT, NVT, Mask);
6627     Lo = DAG.getNode(ISD::BIT_CONVERT, NVT, Node->getOperand(0));
6628     Lo = DAG.getNode(ISD::AND, NVT, Lo, Mask);
6629     if (getTypeAction(NVT) == Expand)
6630       ExpandOp(Lo, Lo, Hi);
6631     break;
6632   }
6633   case ISD::FNEG: {
6634     if (VT == MVT::ppcf128) {
6635       ExpandOp(Node->getOperand(0), Lo, Hi);
6636       Lo = DAG.getNode(ISD::FNEG, MVT::f64, Lo);
6637       Hi = DAG.getNode(ISD::FNEG, MVT::f64, Hi);
6638       break;
6639     }
6640     SDOperand Mask = (VT == MVT::f64)
6641       ? DAG.getConstantFP(BitsToDouble(1ULL << 63), VT)
6642       : DAG.getConstantFP(BitsToFloat(1U << 31), VT);
6643     Mask = DAG.getNode(ISD::BIT_CONVERT, NVT, Mask);
6644     Lo = DAG.getNode(ISD::BIT_CONVERT, NVT, Node->getOperand(0));
6645     Lo = DAG.getNode(ISD::XOR, NVT, Lo, Mask);
6646     if (getTypeAction(NVT) == Expand)
6647       ExpandOp(Lo, Lo, Hi);
6648     break;
6649   }
6650   case ISD::FCOPYSIGN: {
6651     Lo = ExpandFCOPYSIGNToBitwiseOps(Node, NVT, DAG, TLI);
6652     if (getTypeAction(NVT) == Expand)
6653       ExpandOp(Lo, Lo, Hi);
6654     break;
6655   }
6656   case ISD::SINT_TO_FP:
6657   case ISD::UINT_TO_FP: {
6658     bool isSigned = Node->getOpcode() == ISD::SINT_TO_FP;
6659     MVT SrcVT = Node->getOperand(0).getValueType();
6660
6661     // Promote the operand if needed.  Do this before checking for
6662     // ppcf128 so conversions of i16 and i8 work.
6663     if (getTypeAction(SrcVT) == Promote) {
6664       SDOperand Tmp = PromoteOp(Node->getOperand(0));
6665       Tmp = isSigned
6666         ? DAG.getNode(ISD::SIGN_EXTEND_INREG, Tmp.getValueType(), Tmp,
6667                       DAG.getValueType(SrcVT))
6668         : DAG.getZeroExtendInReg(Tmp, SrcVT);
6669       Node = DAG.UpdateNodeOperands(Op, Tmp).Val;
6670       SrcVT = Node->getOperand(0).getValueType();
6671     }
6672
6673     if (VT == MVT::ppcf128 && SrcVT == MVT::i32) {
6674       static const uint64_t zero = 0;
6675       if (isSigned) {
6676         Hi = LegalizeOp(DAG.getNode(ISD::SINT_TO_FP, MVT::f64, 
6677                                     Node->getOperand(0)));
6678         Lo = DAG.getConstantFP(APFloat(APInt(64, 1, &zero)), MVT::f64);
6679       } else {
6680         static const uint64_t TwoE32[] = { 0x41f0000000000000LL, 0 };
6681         Hi = LegalizeOp(DAG.getNode(ISD::SINT_TO_FP, MVT::f64, 
6682                                     Node->getOperand(0)));
6683         Lo = DAG.getConstantFP(APFloat(APInt(64, 1, &zero)), MVT::f64);
6684         Hi = DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi);
6685         // X>=0 ? {(f64)x, 0} : {(f64)x, 0} + 2^32
6686         ExpandOp(DAG.getNode(ISD::SELECT_CC, MVT::ppcf128, Node->getOperand(0),
6687                              DAG.getConstant(0, MVT::i32), 
6688                              DAG.getNode(ISD::FADD, MVT::ppcf128, Hi,
6689                                          DAG.getConstantFP(
6690                                             APFloat(APInt(128, 2, TwoE32)),
6691                                             MVT::ppcf128)),
6692                              Hi,
6693                              DAG.getCondCode(ISD::SETLT)),
6694                  Lo, Hi);
6695       }
6696       break;
6697     }
6698     if (VT == MVT::ppcf128 && SrcVT == MVT::i64 && !isSigned) {
6699       // si64->ppcf128 done by libcall, below
6700       static const uint64_t TwoE64[] = { 0x43f0000000000000LL, 0 };
6701       ExpandOp(DAG.getNode(ISD::SINT_TO_FP, MVT::ppcf128, Node->getOperand(0)),
6702                Lo, Hi);
6703       Hi = DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi);
6704       // x>=0 ? (ppcf128)(i64)x : (ppcf128)(i64)x + 2^64
6705       ExpandOp(DAG.getNode(ISD::SELECT_CC, MVT::ppcf128, Node->getOperand(0),
6706                            DAG.getConstant(0, MVT::i64), 
6707                            DAG.getNode(ISD::FADD, MVT::ppcf128, Hi,
6708                                        DAG.getConstantFP(
6709                                           APFloat(APInt(128, 2, TwoE64)),
6710                                           MVT::ppcf128)),
6711                            Hi,
6712                            DAG.getCondCode(ISD::SETLT)),
6713                Lo, Hi);
6714       break;
6715     }
6716
6717     Lo = ExpandIntToFP(Node->getOpcode() == ISD::SINT_TO_FP, VT,
6718                        Node->getOperand(0));
6719     if (getTypeAction(Lo.getValueType()) == Expand)
6720       // float to i32 etc. can be 'expanded' to a single node.
6721       ExpandOp(Lo, Lo, Hi);
6722     break;
6723   }
6724   }
6725
6726   // Make sure the resultant values have been legalized themselves, unless this
6727   // is a type that requires multi-step expansion.
6728   if (getTypeAction(NVT) != Expand && NVT != MVT::isVoid) {
6729     Lo = LegalizeOp(Lo);
6730     if (Hi.Val)
6731       // Don't legalize the high part if it is expanded to a single node.
6732       Hi = LegalizeOp(Hi);
6733   }
6734
6735   // Remember in a map if the values will be reused later.
6736   bool isNew =
6737     ExpandedNodes.insert(std::make_pair(Op, std::make_pair(Lo, Hi))).second;
6738   assert(isNew && "Value already expanded?!?");
6739 }
6740
6741 /// SplitVectorOp - Given an operand of vector type, break it down into
6742 /// two smaller values, still of vector type.
6743 void SelectionDAGLegalize::SplitVectorOp(SDOperand Op, SDOperand &Lo,
6744                                          SDOperand &Hi) {
6745   assert(Op.getValueType().isVector() && "Cannot split non-vector type!");
6746   SDNode *Node = Op.Val;
6747   unsigned NumElements = Op.getValueType().getVectorNumElements();
6748   assert(NumElements > 1 && "Cannot split a single element vector!");
6749
6750   MVT NewEltVT = Op.getValueType().getVectorElementType();
6751
6752   unsigned NewNumElts_Lo = 1 << Log2_32(NumElements-1);
6753   unsigned NewNumElts_Hi = NumElements - NewNumElts_Lo;
6754
6755   MVT NewVT_Lo = MVT::getVectorVT(NewEltVT, NewNumElts_Lo);
6756   MVT NewVT_Hi = MVT::getVectorVT(NewEltVT, NewNumElts_Hi);
6757
6758   // See if we already split it.
6759   std::map<SDOperand, std::pair<SDOperand, SDOperand> >::iterator I
6760     = SplitNodes.find(Op);
6761   if (I != SplitNodes.end()) {
6762     Lo = I->second.first;
6763     Hi = I->second.second;
6764     return;
6765   }
6766   
6767   switch (Node->getOpcode()) {
6768   default: 
6769 #ifndef NDEBUG
6770     Node->dump(&DAG);
6771 #endif
6772     assert(0 && "Unhandled operation in SplitVectorOp!");
6773   case ISD::UNDEF:
6774     Lo = DAG.getNode(ISD::UNDEF, NewVT_Lo);
6775     Hi = DAG.getNode(ISD::UNDEF, NewVT_Hi);
6776     break;
6777   case ISD::BUILD_PAIR:
6778     Lo = Node->getOperand(0);
6779     Hi = Node->getOperand(1);
6780     break;
6781   case ISD::INSERT_VECTOR_ELT: {
6782     if (ConstantSDNode *Idx = dyn_cast<ConstantSDNode>(Node->getOperand(2))) {
6783       SplitVectorOp(Node->getOperand(0), Lo, Hi);
6784       unsigned Index = Idx->getValue();
6785       SDOperand ScalarOp = Node->getOperand(1);
6786       if (Index < NewNumElts_Lo)
6787         Lo = DAG.getNode(ISD::INSERT_VECTOR_ELT, NewVT_Lo, Lo, ScalarOp,
6788                          DAG.getIntPtrConstant(Index));
6789       else
6790         Hi = DAG.getNode(ISD::INSERT_VECTOR_ELT, NewVT_Hi, Hi, ScalarOp,
6791                          DAG.getIntPtrConstant(Index - NewNumElts_Lo));
6792       break;
6793     }
6794     SDOperand Tmp = PerformInsertVectorEltInMemory(Node->getOperand(0),
6795                                                    Node->getOperand(1),
6796                                                    Node->getOperand(2));
6797     SplitVectorOp(Tmp, Lo, Hi);
6798     break;
6799   }
6800   case ISD::VECTOR_SHUFFLE: {
6801     // Build the low part.
6802     SDOperand Mask = Node->getOperand(2);
6803     SmallVector<SDOperand, 8> Ops;
6804     MVT PtrVT = TLI.getPointerTy();
6805     
6806     // Insert all of the elements from the input that are needed.  We use 
6807     // buildvector of extractelement here because the input vectors will have
6808     // to be legalized, so this makes the code simpler.
6809     for (unsigned i = 0; i != NewNumElts_Lo; ++i) {
6810       SDOperand IdxNode = Mask.getOperand(i);
6811       if (IdxNode.getOpcode() == ISD::UNDEF) {
6812         Ops.push_back(DAG.getNode(ISD::UNDEF, NewEltVT));
6813         continue;
6814       }
6815       unsigned Idx = cast<ConstantSDNode>(IdxNode)->getValue();
6816       SDOperand InVec = Node->getOperand(0);
6817       if (Idx >= NumElements) {
6818         InVec = Node->getOperand(1);
6819         Idx -= NumElements;
6820       }
6821       Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, NewEltVT, InVec,
6822                                 DAG.getConstant(Idx, PtrVT)));
6823     }
6824     Lo = DAG.getNode(ISD::BUILD_VECTOR, NewVT_Lo, &Ops[0], Ops.size());
6825     Ops.clear();
6826     
6827     for (unsigned i = NewNumElts_Lo; i != NumElements; ++i) {
6828       SDOperand IdxNode = Mask.getOperand(i);
6829       if (IdxNode.getOpcode() == ISD::UNDEF) {
6830         Ops.push_back(DAG.getNode(ISD::UNDEF, NewEltVT));
6831         continue;
6832       }
6833       unsigned Idx = cast<ConstantSDNode>(IdxNode)->getValue();
6834       SDOperand InVec = Node->getOperand(0);
6835       if (Idx >= NumElements) {
6836         InVec = Node->getOperand(1);
6837         Idx -= NumElements;
6838       }
6839       Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, NewEltVT, InVec,
6840                                 DAG.getConstant(Idx, PtrVT)));
6841     }
6842     Hi = DAG.getNode(ISD::BUILD_VECTOR, NewVT_Lo, &Ops[0], Ops.size());
6843     break;
6844   }
6845   case ISD::BUILD_VECTOR: {
6846     SmallVector<SDOperand, 8> LoOps(Node->op_begin(), 
6847                                     Node->op_begin()+NewNumElts_Lo);
6848     Lo = DAG.getNode(ISD::BUILD_VECTOR, NewVT_Lo, &LoOps[0], LoOps.size());
6849
6850     SmallVector<SDOperand, 8> HiOps(Node->op_begin()+NewNumElts_Lo, 
6851                                     Node->op_end());
6852     Hi = DAG.getNode(ISD::BUILD_VECTOR, NewVT_Hi, &HiOps[0], HiOps.size());
6853     break;
6854   }
6855   case ISD::CONCAT_VECTORS: {
6856     // FIXME: Handle non-power-of-two vectors?
6857     unsigned NewNumSubvectors = Node->getNumOperands() / 2;
6858     if (NewNumSubvectors == 1) {
6859       Lo = Node->getOperand(0);
6860       Hi = Node->getOperand(1);
6861     } else {
6862       SmallVector<SDOperand, 8> LoOps(Node->op_begin(), 
6863                                       Node->op_begin()+NewNumSubvectors);
6864       Lo = DAG.getNode(ISD::CONCAT_VECTORS, NewVT_Lo, &LoOps[0], LoOps.size());
6865
6866       SmallVector<SDOperand, 8> HiOps(Node->op_begin()+NewNumSubvectors, 
6867                                       Node->op_end());
6868       Hi = DAG.getNode(ISD::CONCAT_VECTORS, NewVT_Hi, &HiOps[0], HiOps.size());
6869     }
6870     break;
6871   }
6872   case ISD::SELECT: {
6873     SDOperand Cond = Node->getOperand(0);
6874
6875     SDOperand LL, LH, RL, RH;
6876     SplitVectorOp(Node->getOperand(1), LL, LH);
6877     SplitVectorOp(Node->getOperand(2), RL, RH);
6878
6879     if (Cond.getValueType().isVector()) {
6880       // Handle a vector merge.
6881       SDOperand CL, CH;
6882       SplitVectorOp(Cond, CL, CH);
6883       Lo = DAG.getNode(Node->getOpcode(), NewVT_Lo, CL, LL, RL);
6884       Hi = DAG.getNode(Node->getOpcode(), NewVT_Hi, CH, LH, RH);
6885     } else {
6886       // Handle a simple select with vector operands.
6887       Lo = DAG.getNode(Node->getOpcode(), NewVT_Lo, Cond, LL, RL);
6888       Hi = DAG.getNode(Node->getOpcode(), NewVT_Hi, Cond, LH, RH);
6889     }
6890     break;
6891   }
6892   case ISD::SELECT_CC: {
6893     SDOperand CondLHS = Node->getOperand(0);
6894     SDOperand CondRHS = Node->getOperand(1);
6895     SDOperand CondCode = Node->getOperand(4);
6896     
6897     SDOperand LL, LH, RL, RH;
6898     SplitVectorOp(Node->getOperand(2), LL, LH);
6899     SplitVectorOp(Node->getOperand(3), RL, RH);
6900     
6901     // Handle a simple select with vector operands.
6902     Lo = DAG.getNode(ISD::SELECT_CC, NewVT_Lo, CondLHS, CondRHS,
6903                      LL, RL, CondCode);
6904     Hi = DAG.getNode(ISD::SELECT_CC, NewVT_Hi, CondLHS, CondRHS, 
6905                      LH, RH, CondCode);
6906     break;
6907   }
6908   case ISD::VSETCC: {
6909     SDOperand LL, LH, RL, RH;
6910     SplitVectorOp(Node->getOperand(0), LL, LH);
6911     SplitVectorOp(Node->getOperand(1), RL, RH);
6912     Lo = DAG.getNode(ISD::VSETCC, NewVT_Lo, LL, RL, Node->getOperand(2));
6913     Hi = DAG.getNode(ISD::VSETCC, NewVT_Hi, LH, RH, Node->getOperand(2));
6914     break;
6915   }
6916   case ISD::ADD:
6917   case ISD::SUB:
6918   case ISD::MUL:
6919   case ISD::FADD:
6920   case ISD::FSUB:
6921   case ISD::FMUL:
6922   case ISD::SDIV:
6923   case ISD::UDIV:
6924   case ISD::FDIV:
6925   case ISD::FPOW:
6926   case ISD::AND:
6927   case ISD::OR:
6928   case ISD::XOR:
6929   case ISD::UREM:
6930   case ISD::SREM:
6931   case ISD::FREM: {
6932     SDOperand LL, LH, RL, RH;
6933     SplitVectorOp(Node->getOperand(0), LL, LH);
6934     SplitVectorOp(Node->getOperand(1), RL, RH);
6935     
6936     Lo = DAG.getNode(Node->getOpcode(), NewVT_Lo, LL, RL);
6937     Hi = DAG.getNode(Node->getOpcode(), NewVT_Hi, LH, RH);
6938     break;
6939   }
6940   case ISD::FPOWI: {
6941     SDOperand L, H;
6942     SplitVectorOp(Node->getOperand(0), L, H);
6943
6944     Lo = DAG.getNode(Node->getOpcode(), NewVT_Lo, L, Node->getOperand(1));
6945     Hi = DAG.getNode(Node->getOpcode(), NewVT_Hi, H, Node->getOperand(1));
6946     break;
6947   }
6948   case ISD::CTTZ:
6949   case ISD::CTLZ:
6950   case ISD::CTPOP:
6951   case ISD::FNEG:
6952   case ISD::FABS:
6953   case ISD::FSQRT:
6954   case ISD::FSIN:
6955   case ISD::FCOS:
6956   case ISD::FP_TO_SINT:
6957   case ISD::FP_TO_UINT:
6958   case ISD::SINT_TO_FP:
6959   case ISD::UINT_TO_FP: {
6960     SDOperand L, H;
6961     SplitVectorOp(Node->getOperand(0), L, H);
6962
6963     Lo = DAG.getNode(Node->getOpcode(), NewVT_Lo, L);
6964     Hi = DAG.getNode(Node->getOpcode(), NewVT_Hi, H);
6965     break;
6966   }
6967   case ISD::LOAD: {
6968     LoadSDNode *LD = cast<LoadSDNode>(Node);
6969     SDOperand Ch = LD->getChain();
6970     SDOperand Ptr = LD->getBasePtr();
6971     const Value *SV = LD->getSrcValue();
6972     int SVOffset = LD->getSrcValueOffset();
6973     unsigned Alignment = LD->getAlignment();
6974     bool isVolatile = LD->isVolatile();
6975
6976     Lo = DAG.getLoad(NewVT_Lo, Ch, Ptr, SV, SVOffset, isVolatile, Alignment);
6977     unsigned IncrementSize = NewNumElts_Lo * NewEltVT.getSizeInBits()/8;
6978     Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
6979                       DAG.getIntPtrConstant(IncrementSize));
6980     SVOffset += IncrementSize;
6981     Alignment = MinAlign(Alignment, IncrementSize);
6982     Hi = DAG.getLoad(NewVT_Hi, Ch, Ptr, SV, SVOffset, isVolatile, Alignment);
6983     
6984     // Build a factor node to remember that this load is independent of the
6985     // other one.
6986     SDOperand TF = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo.getValue(1),
6987                                Hi.getValue(1));
6988     
6989     // Remember that we legalized the chain.
6990     AddLegalizedOperand(Op.getValue(1), LegalizeOp(TF));
6991     break;
6992   }
6993   case ISD::BIT_CONVERT: {
6994     // We know the result is a vector.  The input may be either a vector or a
6995     // scalar value.
6996     SDOperand InOp = Node->getOperand(0);
6997     if (!InOp.getValueType().isVector() ||
6998         InOp.getValueType().getVectorNumElements() == 1) {
6999       // The input is a scalar or single-element vector.
7000       // Lower to a store/load so that it can be split.
7001       // FIXME: this could be improved probably.
7002       SDOperand Ptr = DAG.CreateStackTemporary(InOp.getValueType());
7003       FrameIndexSDNode *FI = cast<FrameIndexSDNode>(Ptr.Val);
7004
7005       SDOperand St = DAG.getStore(DAG.getEntryNode(),
7006                                   InOp, Ptr,
7007                                   PseudoSourceValue::getFixedStack(),
7008                                   FI->getIndex());
7009       InOp = DAG.getLoad(Op.getValueType(), St, Ptr,
7010                          PseudoSourceValue::getFixedStack(),
7011                          FI->getIndex());
7012     }
7013     // Split the vector and convert each of the pieces now.
7014     SplitVectorOp(InOp, Lo, Hi);
7015     Lo = DAG.getNode(ISD::BIT_CONVERT, NewVT_Lo, Lo);
7016     Hi = DAG.getNode(ISD::BIT_CONVERT, NewVT_Hi, Hi);
7017     break;
7018   }
7019   }
7020       
7021   // Remember in a map if the values will be reused later.
7022   bool isNew = 
7023     SplitNodes.insert(std::make_pair(Op, std::make_pair(Lo, Hi))).second;
7024   assert(isNew && "Value already split?!?");
7025 }
7026
7027
7028 /// ScalarizeVectorOp - Given an operand of single-element vector type
7029 /// (e.g. v1f32), convert it into the equivalent operation that returns a
7030 /// scalar (e.g. f32) value.
7031 SDOperand SelectionDAGLegalize::ScalarizeVectorOp(SDOperand Op) {
7032   assert(Op.getValueType().isVector() && "Bad ScalarizeVectorOp invocation!");
7033   SDNode *Node = Op.Val;
7034   MVT NewVT = Op.getValueType().getVectorElementType();
7035   assert(Op.getValueType().getVectorNumElements() == 1);
7036   
7037   // See if we already scalarized it.
7038   std::map<SDOperand, SDOperand>::iterator I = ScalarizedNodes.find(Op);
7039   if (I != ScalarizedNodes.end()) return I->second;
7040   
7041   SDOperand Result;
7042   switch (Node->getOpcode()) {
7043   default: 
7044 #ifndef NDEBUG
7045     Node->dump(&DAG); cerr << "\n";
7046 #endif
7047     assert(0 && "Unknown vector operation in ScalarizeVectorOp!");
7048   case ISD::ADD:
7049   case ISD::FADD:
7050   case ISD::SUB:
7051   case ISD::FSUB:
7052   case ISD::MUL:
7053   case ISD::FMUL:
7054   case ISD::SDIV:
7055   case ISD::UDIV:
7056   case ISD::FDIV:
7057   case ISD::SREM:
7058   case ISD::UREM:
7059   case ISD::FREM:
7060   case ISD::FPOW:
7061   case ISD::AND:
7062   case ISD::OR:
7063   case ISD::XOR:
7064     Result = DAG.getNode(Node->getOpcode(),
7065                          NewVT, 
7066                          ScalarizeVectorOp(Node->getOperand(0)),
7067                          ScalarizeVectorOp(Node->getOperand(1)));
7068     break;
7069   case ISD::FNEG:
7070   case ISD::FABS:
7071   case ISD::FSQRT:
7072   case ISD::FSIN:
7073   case ISD::FCOS:
7074     Result = DAG.getNode(Node->getOpcode(),
7075                          NewVT, 
7076                          ScalarizeVectorOp(Node->getOperand(0)));
7077     break;
7078   case ISD::FPOWI:
7079     Result = DAG.getNode(Node->getOpcode(),
7080                          NewVT, 
7081                          ScalarizeVectorOp(Node->getOperand(0)),
7082                          Node->getOperand(1));
7083     break;
7084   case ISD::LOAD: {
7085     LoadSDNode *LD = cast<LoadSDNode>(Node);
7086     SDOperand Ch = LegalizeOp(LD->getChain());     // Legalize the chain.
7087     SDOperand Ptr = LegalizeOp(LD->getBasePtr());  // Legalize the pointer.
7088     
7089     const Value *SV = LD->getSrcValue();
7090     int SVOffset = LD->getSrcValueOffset();
7091     Result = DAG.getLoad(NewVT, Ch, Ptr, SV, SVOffset,
7092                          LD->isVolatile(), LD->getAlignment());
7093
7094     // Remember that we legalized the chain.
7095     AddLegalizedOperand(Op.getValue(1), LegalizeOp(Result.getValue(1)));
7096     break;
7097   }
7098   case ISD::BUILD_VECTOR:
7099     Result = Node->getOperand(0);
7100     break;
7101   case ISD::INSERT_VECTOR_ELT:
7102     // Returning the inserted scalar element.
7103     Result = Node->getOperand(1);
7104     break;
7105   case ISD::CONCAT_VECTORS:
7106     assert(Node->getOperand(0).getValueType() == NewVT &&
7107            "Concat of non-legal vectors not yet supported!");
7108     Result = Node->getOperand(0);
7109     break;
7110   case ISD::VECTOR_SHUFFLE: {
7111     // Figure out if the scalar is the LHS or RHS and return it.
7112     SDOperand EltNum = Node->getOperand(2).getOperand(0);
7113     if (cast<ConstantSDNode>(EltNum)->getValue())
7114       Result = ScalarizeVectorOp(Node->getOperand(1));
7115     else
7116       Result = ScalarizeVectorOp(Node->getOperand(0));
7117     break;
7118   }
7119   case ISD::EXTRACT_SUBVECTOR:
7120     Result = Node->getOperand(0);
7121     assert(Result.getValueType() == NewVT);
7122     break;
7123   case ISD::BIT_CONVERT: {
7124     SDOperand Op0 = Op.getOperand(0);
7125     if (Op0.getValueType().getVectorNumElements() == 1)
7126       Op0 = ScalarizeVectorOp(Op0);
7127     Result = DAG.getNode(ISD::BIT_CONVERT, NewVT, Op0);
7128     break;
7129   }
7130   case ISD::SELECT:
7131     Result = DAG.getNode(ISD::SELECT, NewVT, Op.getOperand(0),
7132                          ScalarizeVectorOp(Op.getOperand(1)),
7133                          ScalarizeVectorOp(Op.getOperand(2)));
7134     break;
7135   case ISD::SELECT_CC:
7136     Result = DAG.getNode(ISD::SELECT_CC, NewVT, Node->getOperand(0), 
7137                          Node->getOperand(1),
7138                          ScalarizeVectorOp(Op.getOperand(2)),
7139                          ScalarizeVectorOp(Op.getOperand(3)),
7140                          Node->getOperand(4));
7141     break;
7142   case ISD::VSETCC: {
7143     SDOperand Op0 = ScalarizeVectorOp(Op.getOperand(0));
7144     SDOperand Op1 = ScalarizeVectorOp(Op.getOperand(1));
7145     Result = DAG.getNode(ISD::SETCC, TLI.getSetCCResultType(Op0), Op0, Op1,
7146                          Op.getOperand(2));
7147     Result = DAG.getNode(ISD::SELECT, NewVT, Result,
7148                          DAG.getConstant(-1ULL, NewVT),
7149                          DAG.getConstant(0ULL, NewVT));
7150     break;
7151   }
7152   }
7153
7154   if (TLI.isTypeLegal(NewVT))
7155     Result = LegalizeOp(Result);
7156   bool isNew = ScalarizedNodes.insert(std::make_pair(Op, Result)).second;
7157   assert(isNew && "Value already scalarized?");
7158   return Result;
7159 }
7160
7161
7162 // SelectionDAG::Legalize - This is the entry point for the file.
7163 //
7164 void SelectionDAG::Legalize() {
7165   if (ViewLegalizeDAGs) viewGraph();
7166
7167   /// run - This is the main entry point to this class.
7168   ///
7169   SelectionDAGLegalize(*this).LegalizeDAG();
7170 }
7171