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