LegalizeDAG.cpp revision 4e3d982962b5816515cbe36e73a9f41ed5af6673
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/Analysis/DebugInfo.h"
20#include "llvm/CodeGen/PseudoSourceValue.h"
21#include "llvm/Target/TargetFrameInfo.h"
22#include "llvm/Target/TargetLowering.h"
23#include "llvm/Target/TargetData.h"
24#include "llvm/Target/TargetMachine.h"
25#include "llvm/Target/TargetOptions.h"
26#include "llvm/CallingConv.h"
27#include "llvm/Constants.h"
28#include "llvm/DerivedTypes.h"
29#include "llvm/Function.h"
30#include "llvm/GlobalVariable.h"
31#include "llvm/LLVMContext.h"
32#include "llvm/Support/CommandLine.h"
33#include "llvm/Support/Debug.h"
34#include "llvm/Support/MathExtras.h"
35#include "llvm/Support/raw_ostream.h"
36#include "llvm/ADT/DenseMap.h"
37#include "llvm/ADT/SmallVector.h"
38#include "llvm/ADT/SmallPtrSet.h"
39using namespace llvm;
40
41//===----------------------------------------------------------------------===//
42/// SelectionDAGLegalize - This takes an arbitrary SelectionDAG as input and
43/// hacks on it until the target machine can handle it.  This involves
44/// eliminating value sizes the machine cannot handle (promoting small sizes to
45/// large sizes or splitting up large values into small values) as well as
46/// eliminating operations the machine cannot handle.
47///
48/// This code also does a small amount of optimization and recognition of idioms
49/// as part of its processing.  For example, if a target does not support a
50/// 'setcc' instruction efficiently, but does support 'brcc' instruction, this
51/// will attempt merge setcc and brc instructions into brcc's.
52///
53namespace {
54class SelectionDAGLegalize {
55  const TargetMachine &TM;
56  const TargetLowering &TLI;
57  SelectionDAG &DAG;
58  CodeGenOpt::Level OptLevel;
59
60  // Libcall insertion helpers.
61
62  /// LastCALLSEQ_END - This keeps track of the CALLSEQ_END node that has been
63  /// legalized.  We use this to ensure that calls are properly serialized
64  /// against each other, including inserted libcalls.
65  SDValue LastCALLSEQ_END;
66
67  /// IsLegalizingCall - This member is used *only* for purposes of providing
68  /// helpful assertions that a libcall isn't created while another call is
69  /// being legalized (which could lead to non-serialized call sequences).
70  bool IsLegalizingCall;
71
72  enum LegalizeAction {
73    Legal,      // The target natively supports this operation.
74    Promote,    // This operation should be executed in a larger type.
75    Expand      // Try to expand this to other ops, otherwise use a libcall.
76  };
77
78  /// ValueTypeActions - This is a bitvector that contains two bits for each
79  /// value type, where the two bits correspond to the LegalizeAction enum.
80  /// This can be queried with "getTypeAction(VT)".
81  TargetLowering::ValueTypeActionImpl ValueTypeActions;
82
83  /// LegalizedNodes - For nodes that are of legal width, and that have more
84  /// than one use, this map indicates what regularized operand to use.  This
85  /// allows us to avoid legalizing the same thing more than once.
86  DenseMap<SDValue, SDValue> LegalizedNodes;
87
88  void AddLegalizedOperand(SDValue From, SDValue To) {
89    LegalizedNodes.insert(std::make_pair(From, To));
90    // If someone requests legalization of the new node, return itself.
91    if (From != To)
92      LegalizedNodes.insert(std::make_pair(To, To));
93  }
94
95public:
96  SelectionDAGLegalize(SelectionDAG &DAG, CodeGenOpt::Level ol);
97
98  /// getTypeAction - Return how we should legalize values of this type, either
99  /// it is already legal or we need to expand it into multiple registers of
100  /// smaller integer type, or we need to promote it to a larger type.
101  LegalizeAction getTypeAction(EVT VT) const {
102    return
103        (LegalizeAction)ValueTypeActions.getTypeAction(*DAG.getContext(), VT);
104  }
105
106  /// isTypeLegal - Return true if this type is legal on this target.
107  ///
108  bool isTypeLegal(EVT VT) const {
109    return getTypeAction(VT) == Legal;
110  }
111
112  void LegalizeDAG();
113
114private:
115  /// LegalizeOp - We know that the specified value has a legal type.
116  /// Recursively ensure that the operands have legal types, then return the
117  /// result.
118  SDValue LegalizeOp(SDValue O);
119
120  SDValue OptimizeFloatStore(StoreSDNode *ST);
121
122  /// PerformInsertVectorEltInMemory - Some target cannot handle a variable
123  /// insertion index for the INSERT_VECTOR_ELT instruction.  In this case, it
124  /// is necessary to spill the vector being inserted into to memory, perform
125  /// the insert there, and then read the result back.
126  SDValue PerformInsertVectorEltInMemory(SDValue Vec, SDValue Val,
127                                         SDValue Idx, DebugLoc dl);
128  SDValue ExpandINSERT_VECTOR_ELT(SDValue Vec, SDValue Val,
129                                  SDValue Idx, DebugLoc dl);
130
131  /// ShuffleWithNarrowerEltType - Return a vector shuffle operation which
132  /// performs the same shuffe in terms of order or result bytes, but on a type
133  /// whose vector element type is narrower than the original shuffle type.
134  /// e.g. <v4i32> <0, 1, 0, 1> -> v8i16 <0, 1, 2, 3, 0, 1, 2, 3>
135  SDValue ShuffleWithNarrowerEltType(EVT NVT, EVT VT, DebugLoc dl,
136                                     SDValue N1, SDValue N2,
137                                     SmallVectorImpl<int> &Mask) const;
138
139  bool LegalizeAllNodesNotLeadingTo(SDNode *N, SDNode *Dest,
140                                    SmallPtrSet<SDNode*, 32> &NodesLeadingTo);
141
142  void LegalizeSetCCCondCode(EVT VT, SDValue &LHS, SDValue &RHS, SDValue &CC,
143                             DebugLoc dl);
144
145  SDValue ExpandLibCall(RTLIB::Libcall LC, SDNode *Node, bool isSigned);
146  SDValue ExpandFPLibCall(SDNode *Node, RTLIB::Libcall Call_F32,
147                          RTLIB::Libcall Call_F64, RTLIB::Libcall Call_F80,
148                          RTLIB::Libcall Call_PPCF128);
149  SDValue ExpandIntLibCall(SDNode *Node, bool isSigned,
150                           RTLIB::Libcall Call_I8,
151                           RTLIB::Libcall Call_I16,
152                           RTLIB::Libcall Call_I32,
153                           RTLIB::Libcall Call_I64,
154                           RTLIB::Libcall Call_I128);
155
156  SDValue EmitStackConvert(SDValue SrcOp, EVT SlotVT, EVT DestVT, DebugLoc dl);
157  SDValue ExpandBUILD_VECTOR(SDNode *Node);
158  SDValue ExpandSCALAR_TO_VECTOR(SDNode *Node);
159  void ExpandDYNAMIC_STACKALLOC(SDNode *Node,
160                                SmallVectorImpl<SDValue> &Results);
161  SDValue ExpandFCOPYSIGN(SDNode *Node);
162  SDValue ExpandLegalINT_TO_FP(bool isSigned, SDValue LegalOp, EVT DestVT,
163                               DebugLoc dl);
164  SDValue PromoteLegalINT_TO_FP(SDValue LegalOp, EVT DestVT, bool isSigned,
165                                DebugLoc dl);
166  SDValue PromoteLegalFP_TO_INT(SDValue LegalOp, EVT DestVT, bool isSigned,
167                                DebugLoc dl);
168
169  SDValue ExpandBSWAP(SDValue Op, DebugLoc dl);
170  SDValue ExpandBitCount(unsigned Opc, SDValue Op, DebugLoc dl);
171
172  SDValue ExpandExtractFromVectorThroughStack(SDValue Op);
173  SDValue ExpandVectorBuildThroughStack(SDNode* Node);
174
175  void ExpandNode(SDNode *Node, SmallVectorImpl<SDValue> &Results);
176  void PromoteNode(SDNode *Node, SmallVectorImpl<SDValue> &Results);
177};
178}
179
180/// ShuffleWithNarrowerEltType - Return a vector shuffle operation which
181/// performs the same shuffe in terms of order or result bytes, but on a type
182/// whose vector element type is narrower than the original shuffle type.
183/// e.g. <v4i32> <0, 1, 0, 1> -> v8i16 <0, 1, 2, 3, 0, 1, 2, 3>
184SDValue
185SelectionDAGLegalize::ShuffleWithNarrowerEltType(EVT NVT, EVT VT,  DebugLoc dl,
186                                                 SDValue N1, SDValue N2,
187                                             SmallVectorImpl<int> &Mask) const {
188  unsigned NumMaskElts = VT.getVectorNumElements();
189  unsigned NumDestElts = NVT.getVectorNumElements();
190  unsigned NumEltsGrowth = NumDestElts / NumMaskElts;
191
192  assert(NumEltsGrowth && "Cannot promote to vector type with fewer elts!");
193
194  if (NumEltsGrowth == 1)
195    return DAG.getVectorShuffle(NVT, dl, N1, N2, &Mask[0]);
196
197  SmallVector<int, 8> NewMask;
198  for (unsigned i = 0; i != NumMaskElts; ++i) {
199    int Idx = Mask[i];
200    for (unsigned j = 0; j != NumEltsGrowth; ++j) {
201      if (Idx < 0)
202        NewMask.push_back(-1);
203      else
204        NewMask.push_back(Idx * NumEltsGrowth + j);
205    }
206  }
207  assert(NewMask.size() == NumDestElts && "Non-integer NumEltsGrowth?");
208  assert(TLI.isShuffleMaskLegal(NewMask, NVT) && "Shuffle not legal?");
209  return DAG.getVectorShuffle(NVT, dl, N1, N2, &NewMask[0]);
210}
211
212SelectionDAGLegalize::SelectionDAGLegalize(SelectionDAG &dag,
213                                           CodeGenOpt::Level ol)
214  : TM(dag.getTarget()), TLI(dag.getTargetLoweringInfo()),
215    DAG(dag), OptLevel(ol),
216    ValueTypeActions(TLI.getValueTypeActions()) {
217  assert(MVT::LAST_VALUETYPE <= MVT::MAX_ALLOWED_VALUETYPE &&
218         "Too many value types for ValueTypeActions to hold!");
219}
220
221void SelectionDAGLegalize::LegalizeDAG() {
222  LastCALLSEQ_END = DAG.getEntryNode();
223  IsLegalizingCall = false;
224
225  // The legalize process is inherently a bottom-up recursive process (users
226  // legalize their uses before themselves).  Given infinite stack space, we
227  // could just start legalizing on the root and traverse the whole graph.  In
228  // practice however, this causes us to run out of stack space on large basic
229  // blocks.  To avoid this problem, compute an ordering of the nodes where each
230  // node is only legalized after all of its operands are legalized.
231  DAG.AssignTopologicalOrder();
232  for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
233       E = prior(DAG.allnodes_end()); I != llvm::next(E); ++I)
234    LegalizeOp(SDValue(I, 0));
235
236  // Finally, it's possible the root changed.  Get the new root.
237  SDValue OldRoot = DAG.getRoot();
238  assert(LegalizedNodes.count(OldRoot) && "Root didn't get legalized?");
239  DAG.setRoot(LegalizedNodes[OldRoot]);
240
241  LegalizedNodes.clear();
242
243  // Remove dead nodes now.
244  DAG.RemoveDeadNodes();
245}
246
247
248/// FindCallEndFromCallStart - Given a chained node that is part of a call
249/// sequence, find the CALLSEQ_END node that terminates the call sequence.
250static SDNode *FindCallEndFromCallStart(SDNode *Node) {
251  if (Node->getOpcode() == ISD::CALLSEQ_END)
252    return Node;
253  if (Node->use_empty())
254    return 0;   // No CallSeqEnd
255
256  // The chain is usually at the end.
257  SDValue TheChain(Node, Node->getNumValues()-1);
258  if (TheChain.getValueType() != MVT::Other) {
259    // Sometimes it's at the beginning.
260    TheChain = SDValue(Node, 0);
261    if (TheChain.getValueType() != MVT::Other) {
262      // Otherwise, hunt for it.
263      for (unsigned i = 1, e = Node->getNumValues(); i != e; ++i)
264        if (Node->getValueType(i) == MVT::Other) {
265          TheChain = SDValue(Node, i);
266          break;
267        }
268
269      // Otherwise, we walked into a node without a chain.
270      if (TheChain.getValueType() != MVT::Other)
271        return 0;
272    }
273  }
274
275  for (SDNode::use_iterator UI = Node->use_begin(),
276       E = Node->use_end(); UI != E; ++UI) {
277
278    // Make sure to only follow users of our token chain.
279    SDNode *User = *UI;
280    for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
281      if (User->getOperand(i) == TheChain)
282        if (SDNode *Result = FindCallEndFromCallStart(User))
283          return Result;
284  }
285  return 0;
286}
287
288/// FindCallStartFromCallEnd - Given a chained node that is part of a call
289/// sequence, find the CALLSEQ_START node that initiates the call sequence.
290static SDNode *FindCallStartFromCallEnd(SDNode *Node) {
291  assert(Node && "Didn't find callseq_start for a call??");
292  if (Node->getOpcode() == ISD::CALLSEQ_START) return Node;
293
294  assert(Node->getOperand(0).getValueType() == MVT::Other &&
295         "Node doesn't have a token chain argument!");
296  return FindCallStartFromCallEnd(Node->getOperand(0).getNode());
297}
298
299/// LegalizeAllNodesNotLeadingTo - Recursively walk the uses of N, looking to
300/// see if any uses can reach Dest.  If no dest operands can get to dest,
301/// legalize them, legalize ourself, and return false, otherwise, return true.
302///
303/// Keep track of the nodes we fine that actually do lead to Dest in
304/// NodesLeadingTo.  This avoids retraversing them exponential number of times.
305///
306bool SelectionDAGLegalize::LegalizeAllNodesNotLeadingTo(SDNode *N, SDNode *Dest,
307                                     SmallPtrSet<SDNode*, 32> &NodesLeadingTo) {
308  if (N == Dest) return true;  // N certainly leads to Dest :)
309
310  // If we've already processed this node and it does lead to Dest, there is no
311  // need to reprocess it.
312  if (NodesLeadingTo.count(N)) return true;
313
314  // If the first result of this node has been already legalized, then it cannot
315  // reach N.
316  if (LegalizedNodes.count(SDValue(N, 0))) return false;
317
318  // Okay, this node has not already been legalized.  Check and legalize all
319  // operands.  If none lead to Dest, then we can legalize this node.
320  bool OperandsLeadToDest = false;
321  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
322    OperandsLeadToDest |=     // If an operand leads to Dest, so do we.
323      LegalizeAllNodesNotLeadingTo(N->getOperand(i).getNode(), Dest, NodesLeadingTo);
324
325  if (OperandsLeadToDest) {
326    NodesLeadingTo.insert(N);
327    return true;
328  }
329
330  // Okay, this node looks safe, legalize it and return false.
331  LegalizeOp(SDValue(N, 0));
332  return false;
333}
334
335/// ExpandConstantFP - Expands the ConstantFP node to an integer constant or
336/// a load from the constant pool.
337static SDValue ExpandConstantFP(ConstantFPSDNode *CFP, bool UseCP,
338                                SelectionDAG &DAG, const TargetLowering &TLI) {
339  bool Extend = false;
340  DebugLoc dl = CFP->getDebugLoc();
341
342  // If a FP immediate is precise when represented as a float and if the
343  // target can do an extending load from float to double, we put it into
344  // the constant pool as a float, even if it's is statically typed as a
345  // double.  This shrinks FP constants and canonicalizes them for targets where
346  // an FP extending load is the same cost as a normal load (such as on the x87
347  // fp stack or PPC FP unit).
348  EVT VT = CFP->getValueType(0);
349  ConstantFP *LLVMC = const_cast<ConstantFP*>(CFP->getConstantFPValue());
350  if (!UseCP) {
351    assert((VT == MVT::f64 || VT == MVT::f32) && "Invalid type expansion");
352    return DAG.getConstant(LLVMC->getValueAPF().bitcastToAPInt(),
353                           (VT == MVT::f64) ? MVT::i64 : MVT::i32);
354  }
355
356  EVT OrigVT = VT;
357  EVT SVT = VT;
358  while (SVT != MVT::f32) {
359    SVT = (MVT::SimpleValueType)(SVT.getSimpleVT().SimpleTy - 1);
360    if (ConstantFPSDNode::isValueValidForType(SVT, CFP->getValueAPF()) &&
361        // Only do this if the target has a native EXTLOAD instruction from
362        // smaller type.
363        TLI.isLoadExtLegal(ISD::EXTLOAD, SVT) &&
364        TLI.ShouldShrinkFPConstant(OrigVT)) {
365      const Type *SType = SVT.getTypeForEVT(*DAG.getContext());
366      LLVMC = cast<ConstantFP>(ConstantExpr::getFPTrunc(LLVMC, SType));
367      VT = SVT;
368      Extend = true;
369    }
370  }
371
372  SDValue CPIdx = DAG.getConstantPool(LLVMC, TLI.getPointerTy());
373  unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
374  if (Extend)
375    return DAG.getExtLoad(ISD::EXTLOAD, dl,
376                          OrigVT, DAG.getEntryNode(),
377                          CPIdx, PseudoSourceValue::getConstantPool(),
378                          0, VT, false, false, Alignment);
379  return DAG.getLoad(OrigVT, dl, DAG.getEntryNode(), CPIdx,
380                     PseudoSourceValue::getConstantPool(), 0, false, false,
381                     Alignment);
382}
383
384/// ExpandUnalignedStore - Expands an unaligned store to 2 half-size stores.
385static
386SDValue ExpandUnalignedStore(StoreSDNode *ST, SelectionDAG &DAG,
387                             const TargetLowering &TLI) {
388  SDValue Chain = ST->getChain();
389  SDValue Ptr = ST->getBasePtr();
390  SDValue Val = ST->getValue();
391  EVT VT = Val.getValueType();
392  int Alignment = ST->getAlignment();
393  int SVOffset = ST->getSrcValueOffset();
394  DebugLoc dl = ST->getDebugLoc();
395  if (ST->getMemoryVT().isFloatingPoint() ||
396      ST->getMemoryVT().isVector()) {
397    EVT intVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
398    if (TLI.isTypeLegal(intVT)) {
399      // Expand to a bitconvert of the value to the integer type of the
400      // same size, then a (misaligned) int store.
401      // FIXME: Does not handle truncating floating point stores!
402      SDValue Result = DAG.getNode(ISD::BIT_CONVERT, dl, intVT, Val);
403      return DAG.getStore(Chain, dl, Result, Ptr, ST->getSrcValue(),
404                          SVOffset, ST->isVolatile(), ST->isNonTemporal(),
405                          Alignment);
406    } else {
407      // Do a (aligned) store to a stack slot, then copy from the stack slot
408      // to the final destination using (unaligned) integer loads and stores.
409      EVT StoredVT = ST->getMemoryVT();
410      EVT RegVT =
411        TLI.getRegisterType(*DAG.getContext(),
412                            EVT::getIntegerVT(*DAG.getContext(),
413                                              StoredVT.getSizeInBits()));
414      unsigned StoredBytes = StoredVT.getSizeInBits() / 8;
415      unsigned RegBytes = RegVT.getSizeInBits() / 8;
416      unsigned NumRegs = (StoredBytes + RegBytes - 1) / RegBytes;
417
418      // Make sure the stack slot is also aligned for the register type.
419      SDValue StackPtr = DAG.CreateStackTemporary(StoredVT, RegVT);
420
421      // Perform the original store, only redirected to the stack slot.
422      SDValue Store = DAG.getTruncStore(Chain, dl,
423                                        Val, StackPtr, NULL, 0, StoredVT,
424                                        false, false, 0);
425      SDValue Increment = DAG.getConstant(RegBytes, TLI.getPointerTy());
426      SmallVector<SDValue, 8> Stores;
427      unsigned Offset = 0;
428
429      // Do all but one copies using the full register width.
430      for (unsigned i = 1; i < NumRegs; i++) {
431        // Load one integer register's worth from the stack slot.
432        SDValue Load = DAG.getLoad(RegVT, dl, Store, StackPtr, NULL, 0,
433                                   false, false, 0);
434        // Store it to the final location.  Remember the store.
435        Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, Ptr,
436                                      ST->getSrcValue(), SVOffset + Offset,
437                                      ST->isVolatile(), ST->isNonTemporal(),
438                                      MinAlign(ST->getAlignment(), Offset)));
439        // Increment the pointers.
440        Offset += RegBytes;
441        StackPtr = DAG.getNode(ISD::ADD, dl, StackPtr.getValueType(), StackPtr,
442                               Increment);
443        Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
444      }
445
446      // The last store may be partial.  Do a truncating store.  On big-endian
447      // machines this requires an extending load from the stack slot to ensure
448      // that the bits are in the right place.
449      EVT MemVT = EVT::getIntegerVT(*DAG.getContext(),
450                                    8 * (StoredBytes - Offset));
451
452      // Load from the stack slot.
453      SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Store, StackPtr,
454                                    NULL, 0, MemVT, false, false, 0);
455
456      Stores.push_back(DAG.getTruncStore(Load.getValue(1), dl, Load, Ptr,
457                                         ST->getSrcValue(), SVOffset + Offset,
458                                         MemVT, ST->isVolatile(),
459                                         ST->isNonTemporal(),
460                                         MinAlign(ST->getAlignment(), Offset)));
461      // The order of the stores doesn't matter - say it with a TokenFactor.
462      return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Stores[0],
463                         Stores.size());
464    }
465  }
466  assert(ST->getMemoryVT().isInteger() &&
467         !ST->getMemoryVT().isVector() &&
468         "Unaligned store of unknown type.");
469  // Get the half-size VT
470  EVT NewStoredVT = ST->getMemoryVT().getHalfSizedIntegerVT(*DAG.getContext());
471  int NumBits = NewStoredVT.getSizeInBits();
472  int IncrementSize = NumBits / 8;
473
474  // Divide the stored value in two parts.
475  SDValue ShiftAmount = DAG.getConstant(NumBits, TLI.getShiftAmountTy());
476  SDValue Lo = Val;
477  SDValue Hi = DAG.getNode(ISD::SRL, dl, VT, Val, ShiftAmount);
478
479  // Store the two parts
480  SDValue Store1, Store2;
481  Store1 = DAG.getTruncStore(Chain, dl, TLI.isLittleEndian()?Lo:Hi, Ptr,
482                             ST->getSrcValue(), SVOffset, NewStoredVT,
483                             ST->isVolatile(), ST->isNonTemporal(), Alignment);
484  Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
485                    DAG.getConstant(IncrementSize, TLI.getPointerTy()));
486  Alignment = MinAlign(Alignment, IncrementSize);
487  Store2 = DAG.getTruncStore(Chain, dl, TLI.isLittleEndian()?Hi:Lo, Ptr,
488                             ST->getSrcValue(), SVOffset + IncrementSize,
489                             NewStoredVT, ST->isVolatile(), ST->isNonTemporal(),
490                             Alignment);
491
492  return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2);
493}
494
495/// ExpandUnalignedLoad - Expands an unaligned load to 2 half-size loads.
496static
497SDValue ExpandUnalignedLoad(LoadSDNode *LD, SelectionDAG &DAG,
498                            const TargetLowering &TLI) {
499  int SVOffset = LD->getSrcValueOffset();
500  SDValue Chain = LD->getChain();
501  SDValue Ptr = LD->getBasePtr();
502  EVT VT = LD->getValueType(0);
503  EVT LoadedVT = LD->getMemoryVT();
504  DebugLoc dl = LD->getDebugLoc();
505  if (VT.isFloatingPoint() || VT.isVector()) {
506    EVT intVT = EVT::getIntegerVT(*DAG.getContext(), LoadedVT.getSizeInBits());
507    if (TLI.isTypeLegal(intVT)) {
508      // Expand to a (misaligned) integer load of the same size,
509      // then bitconvert to floating point or vector.
510      SDValue newLoad = DAG.getLoad(intVT, dl, Chain, Ptr, LD->getSrcValue(),
511                                    SVOffset, LD->isVolatile(),
512                                    LD->isNonTemporal(), LD->getAlignment());
513      SDValue Result = DAG.getNode(ISD::BIT_CONVERT, dl, LoadedVT, newLoad);
514      if (VT.isFloatingPoint() && LoadedVT != VT)
515        Result = DAG.getNode(ISD::FP_EXTEND, dl, VT, Result);
516
517      SDValue Ops[] = { Result, Chain };
518      return DAG.getMergeValues(Ops, 2, dl);
519    } else {
520      // Copy the value to a (aligned) stack slot using (unaligned) integer
521      // loads and stores, then do a (aligned) load from the stack slot.
522      EVT RegVT = TLI.getRegisterType(*DAG.getContext(), intVT);
523      unsigned LoadedBytes = LoadedVT.getSizeInBits() / 8;
524      unsigned RegBytes = RegVT.getSizeInBits() / 8;
525      unsigned NumRegs = (LoadedBytes + RegBytes - 1) / RegBytes;
526
527      // Make sure the stack slot is also aligned for the register type.
528      SDValue StackBase = DAG.CreateStackTemporary(LoadedVT, RegVT);
529
530      SDValue Increment = DAG.getConstant(RegBytes, TLI.getPointerTy());
531      SmallVector<SDValue, 8> Stores;
532      SDValue StackPtr = StackBase;
533      unsigned Offset = 0;
534
535      // Do all but one copies using the full register width.
536      for (unsigned i = 1; i < NumRegs; i++) {
537        // Load one integer register's worth from the original location.
538        SDValue Load = DAG.getLoad(RegVT, dl, Chain, Ptr, LD->getSrcValue(),
539                                   SVOffset + Offset, LD->isVolatile(),
540                                   LD->isNonTemporal(),
541                                   MinAlign(LD->getAlignment(), Offset));
542        // Follow the load with a store to the stack slot.  Remember the store.
543        Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, StackPtr,
544                                      NULL, 0, false, false, 0));
545        // Increment the pointers.
546        Offset += RegBytes;
547        Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
548        StackPtr = DAG.getNode(ISD::ADD, dl, StackPtr.getValueType(), StackPtr,
549                               Increment);
550      }
551
552      // The last copy may be partial.  Do an extending load.
553      EVT MemVT = EVT::getIntegerVT(*DAG.getContext(),
554                                    8 * (LoadedBytes - Offset));
555      SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Chain, Ptr,
556                                    LD->getSrcValue(), SVOffset + Offset,
557                                    MemVT, LD->isVolatile(),
558                                    LD->isNonTemporal(),
559                                    MinAlign(LD->getAlignment(), Offset));
560      // Follow the load with a store to the stack slot.  Remember the store.
561      // On big-endian machines this requires a truncating store to ensure
562      // that the bits end up in the right place.
563      Stores.push_back(DAG.getTruncStore(Load.getValue(1), dl, Load, StackPtr,
564                                         NULL, 0, MemVT, false, false, 0));
565
566      // The order of the stores doesn't matter - say it with a TokenFactor.
567      SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Stores[0],
568                               Stores.size());
569
570      // Finally, perform the original load only redirected to the stack slot.
571      Load = DAG.getExtLoad(LD->getExtensionType(), dl, VT, TF, StackBase,
572                            NULL, 0, LoadedVT, false, false, 0);
573
574      // Callers expect a MERGE_VALUES node.
575      SDValue Ops[] = { Load, TF };
576      return DAG.getMergeValues(Ops, 2, dl);
577    }
578  }
579  assert(LoadedVT.isInteger() && !LoadedVT.isVector() &&
580         "Unaligned load of unsupported type.");
581
582  // Compute the new VT that is half the size of the old one.  This is an
583  // integer MVT.
584  unsigned NumBits = LoadedVT.getSizeInBits();
585  EVT NewLoadedVT;
586  NewLoadedVT = EVT::getIntegerVT(*DAG.getContext(), NumBits/2);
587  NumBits >>= 1;
588
589  unsigned Alignment = LD->getAlignment();
590  unsigned IncrementSize = NumBits / 8;
591  ISD::LoadExtType HiExtType = LD->getExtensionType();
592
593  // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD.
594  if (HiExtType == ISD::NON_EXTLOAD)
595    HiExtType = ISD::ZEXTLOAD;
596
597  // Load the value in two parts
598  SDValue Lo, Hi;
599  if (TLI.isLittleEndian()) {
600    Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, LD->getSrcValue(),
601                        SVOffset, NewLoadedVT, LD->isVolatile(),
602                        LD->isNonTemporal(), Alignment);
603    Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
604                      DAG.getConstant(IncrementSize, TLI.getPointerTy()));
605    Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, LD->getSrcValue(),
606                        SVOffset + IncrementSize, NewLoadedVT, LD->isVolatile(),
607                        LD->isNonTemporal(), MinAlign(Alignment, IncrementSize));
608  } else {
609    Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, LD->getSrcValue(),
610                        SVOffset, NewLoadedVT, LD->isVolatile(),
611                        LD->isNonTemporal(), Alignment);
612    Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
613                      DAG.getConstant(IncrementSize, TLI.getPointerTy()));
614    Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, LD->getSrcValue(),
615                        SVOffset + IncrementSize, NewLoadedVT, LD->isVolatile(),
616                        LD->isNonTemporal(), MinAlign(Alignment, IncrementSize));
617  }
618
619  // aggregate the two parts
620  SDValue ShiftAmount = DAG.getConstant(NumBits, TLI.getShiftAmountTy());
621  SDValue Result = DAG.getNode(ISD::SHL, dl, VT, Hi, ShiftAmount);
622  Result = DAG.getNode(ISD::OR, dl, VT, Result, Lo);
623
624  SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
625                             Hi.getValue(1));
626
627  SDValue Ops[] = { Result, TF };
628  return DAG.getMergeValues(Ops, 2, dl);
629}
630
631/// PerformInsertVectorEltInMemory - Some target cannot handle a variable
632/// insertion index for the INSERT_VECTOR_ELT instruction.  In this case, it
633/// is necessary to spill the vector being inserted into to memory, perform
634/// the insert there, and then read the result back.
635SDValue SelectionDAGLegalize::
636PerformInsertVectorEltInMemory(SDValue Vec, SDValue Val, SDValue Idx,
637                               DebugLoc dl) {
638  SDValue Tmp1 = Vec;
639  SDValue Tmp2 = Val;
640  SDValue Tmp3 = Idx;
641
642  // If the target doesn't support this, we have to spill the input vector
643  // to a temporary stack slot, update the element, then reload it.  This is
644  // badness.  We could also load the value into a vector register (either
645  // with a "move to register" or "extload into register" instruction, then
646  // permute it into place, if the idx is a constant and if the idx is
647  // supported by the target.
648  EVT VT    = Tmp1.getValueType();
649  EVT EltVT = VT.getVectorElementType();
650  EVT IdxVT = Tmp3.getValueType();
651  EVT PtrVT = TLI.getPointerTy();
652  SDValue StackPtr = DAG.CreateStackTemporary(VT);
653
654  int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
655
656  // Store the vector.
657  SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, Tmp1, StackPtr,
658                            PseudoSourceValue::getFixedStack(SPFI), 0,
659                            false, false, 0);
660
661  // Truncate or zero extend offset to target pointer type.
662  unsigned CastOpc = IdxVT.bitsGT(PtrVT) ? ISD::TRUNCATE : ISD::ZERO_EXTEND;
663  Tmp3 = DAG.getNode(CastOpc, dl, PtrVT, Tmp3);
664  // Add the offset to the index.
665  unsigned EltSize = EltVT.getSizeInBits()/8;
666  Tmp3 = DAG.getNode(ISD::MUL, dl, IdxVT, Tmp3,DAG.getConstant(EltSize, IdxVT));
667  SDValue StackPtr2 = DAG.getNode(ISD::ADD, dl, IdxVT, Tmp3, StackPtr);
668  // Store the scalar value.
669  Ch = DAG.getTruncStore(Ch, dl, Tmp2, StackPtr2,
670                         PseudoSourceValue::getFixedStack(SPFI), 0, EltVT,
671                         false, false, 0);
672  // Load the updated vector.
673  return DAG.getLoad(VT, dl, Ch, StackPtr,
674                     PseudoSourceValue::getFixedStack(SPFI), 0,
675                     false, false, 0);
676}
677
678
679SDValue SelectionDAGLegalize::
680ExpandINSERT_VECTOR_ELT(SDValue Vec, SDValue Val, SDValue Idx, DebugLoc dl) {
681  if (ConstantSDNode *InsertPos = dyn_cast<ConstantSDNode>(Idx)) {
682    // SCALAR_TO_VECTOR requires that the type of the value being inserted
683    // match the element type of the vector being created, except for
684    // integers in which case the inserted value can be over width.
685    EVT EltVT = Vec.getValueType().getVectorElementType();
686    if (Val.getValueType() == EltVT ||
687        (EltVT.isInteger() && Val.getValueType().bitsGE(EltVT))) {
688      SDValue ScVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
689                                  Vec.getValueType(), Val);
690
691      unsigned NumElts = Vec.getValueType().getVectorNumElements();
692      // We generate a shuffle of InVec and ScVec, so the shuffle mask
693      // should be 0,1,2,3,4,5... with the appropriate element replaced with
694      // elt 0 of the RHS.
695      SmallVector<int, 8> ShufOps;
696      for (unsigned i = 0; i != NumElts; ++i)
697        ShufOps.push_back(i != InsertPos->getZExtValue() ? i : NumElts);
698
699      return DAG.getVectorShuffle(Vec.getValueType(), dl, Vec, ScVec,
700                                  &ShufOps[0]);
701    }
702  }
703  return PerformInsertVectorEltInMemory(Vec, Val, Idx, dl);
704}
705
706SDValue SelectionDAGLegalize::OptimizeFloatStore(StoreSDNode* ST) {
707  // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
708  // FIXME: We shouldn't do this for TargetConstantFP's.
709  // FIXME: move this to the DAG Combiner!  Note that we can't regress due
710  // to phase ordering between legalized code and the dag combiner.  This
711  // probably means that we need to integrate dag combiner and legalizer
712  // together.
713  // We generally can't do this one for long doubles.
714  SDValue Tmp1 = ST->getChain();
715  SDValue Tmp2 = ST->getBasePtr();
716  SDValue Tmp3;
717  int SVOffset = ST->getSrcValueOffset();
718  unsigned Alignment = ST->getAlignment();
719  bool isVolatile = ST->isVolatile();
720  bool isNonTemporal = ST->isNonTemporal();
721  DebugLoc dl = ST->getDebugLoc();
722  if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(ST->getValue())) {
723    if (CFP->getValueType(0) == MVT::f32 &&
724        getTypeAction(MVT::i32) == Legal) {
725      Tmp3 = DAG.getConstant(CFP->getValueAPF().
726                                      bitcastToAPInt().zextOrTrunc(32),
727                              MVT::i32);
728      return DAG.getStore(Tmp1, dl, Tmp3, Tmp2, ST->getSrcValue(),
729                          SVOffset, isVolatile, isNonTemporal, Alignment);
730    } else if (CFP->getValueType(0) == MVT::f64) {
731      // If this target supports 64-bit registers, do a single 64-bit store.
732      if (getTypeAction(MVT::i64) == Legal) {
733        Tmp3 = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
734                                  zextOrTrunc(64), MVT::i64);
735        return DAG.getStore(Tmp1, dl, Tmp3, Tmp2, ST->getSrcValue(),
736                            SVOffset, isVolatile, isNonTemporal, Alignment);
737      } else if (getTypeAction(MVT::i32) == Legal && !ST->isVolatile()) {
738        // Otherwise, if the target supports 32-bit registers, use 2 32-bit
739        // stores.  If the target supports neither 32- nor 64-bits, this
740        // xform is certainly not worth it.
741        const APInt &IntVal =CFP->getValueAPF().bitcastToAPInt();
742        SDValue Lo = DAG.getConstant(APInt(IntVal).trunc(32), MVT::i32);
743        SDValue Hi = DAG.getConstant(IntVal.lshr(32).trunc(32), MVT::i32);
744        if (TLI.isBigEndian()) std::swap(Lo, Hi);
745
746        Lo = DAG.getStore(Tmp1, dl, Lo, Tmp2, ST->getSrcValue(),
747                          SVOffset, isVolatile, isNonTemporal, Alignment);
748        Tmp2 = DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
749                            DAG.getIntPtrConstant(4));
750        Hi = DAG.getStore(Tmp1, dl, Hi, Tmp2, ST->getSrcValue(), SVOffset+4,
751                          isVolatile, isNonTemporal, MinAlign(Alignment, 4U));
752
753        return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi);
754      }
755    }
756  }
757  return SDValue();
758}
759
760/// LegalizeOp - We know that the specified value has a legal type, and
761/// that its operands are legal.  Now ensure that the operation itself
762/// is legal, recursively ensuring that the operands' operations remain
763/// legal.
764SDValue SelectionDAGLegalize::LegalizeOp(SDValue Op) {
765  if (Op.getOpcode() == ISD::TargetConstant) // Allow illegal target nodes.
766    return Op;
767
768  SDNode *Node = Op.getNode();
769  DebugLoc dl = Node->getDebugLoc();
770
771  for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
772    assert(getTypeAction(Node->getValueType(i)) == Legal &&
773           "Unexpected illegal type!");
774
775  for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
776    assert((isTypeLegal(Node->getOperand(i).getValueType()) ||
777            Node->getOperand(i).getOpcode() == ISD::TargetConstant) &&
778           "Unexpected illegal type!");
779
780  // Note that LegalizeOp may be reentered even from single-use nodes, which
781  // means that we always must cache transformed nodes.
782  DenseMap<SDValue, SDValue>::iterator I = LegalizedNodes.find(Op);
783  if (I != LegalizedNodes.end()) return I->second;
784
785  SDValue Tmp1, Tmp2, Tmp3, Tmp4;
786  SDValue Result = Op;
787  bool isCustom = false;
788
789  // Figure out the correct action; the way to query this varies by opcode
790  TargetLowering::LegalizeAction Action;
791  bool SimpleFinishLegalizing = true;
792  switch (Node->getOpcode()) {
793  case ISD::INTRINSIC_W_CHAIN:
794  case ISD::INTRINSIC_WO_CHAIN:
795  case ISD::INTRINSIC_VOID:
796  case ISD::VAARG:
797  case ISD::STACKSAVE:
798    Action = TLI.getOperationAction(Node->getOpcode(), MVT::Other);
799    break;
800  case ISD::SINT_TO_FP:
801  case ISD::UINT_TO_FP:
802  case ISD::EXTRACT_VECTOR_ELT:
803    Action = TLI.getOperationAction(Node->getOpcode(),
804                                    Node->getOperand(0).getValueType());
805    break;
806  case ISD::FP_ROUND_INREG:
807  case ISD::SIGN_EXTEND_INREG: {
808    EVT InnerType = cast<VTSDNode>(Node->getOperand(1))->getVT();
809    Action = TLI.getOperationAction(Node->getOpcode(), InnerType);
810    break;
811  }
812  case ISD::SELECT_CC:
813  case ISD::SETCC:
814  case ISD::BR_CC: {
815    unsigned CCOperand = Node->getOpcode() == ISD::SELECT_CC ? 4 :
816                         Node->getOpcode() == ISD::SETCC ? 2 : 1;
817    unsigned CompareOperand = Node->getOpcode() == ISD::BR_CC ? 2 : 0;
818    EVT OpVT = Node->getOperand(CompareOperand).getValueType();
819    ISD::CondCode CCCode =
820        cast<CondCodeSDNode>(Node->getOperand(CCOperand))->get();
821    Action = TLI.getCondCodeAction(CCCode, OpVT);
822    if (Action == TargetLowering::Legal) {
823      if (Node->getOpcode() == ISD::SELECT_CC)
824        Action = TLI.getOperationAction(Node->getOpcode(),
825                                        Node->getValueType(0));
826      else
827        Action = TLI.getOperationAction(Node->getOpcode(), OpVT);
828    }
829    break;
830  }
831  case ISD::LOAD:
832  case ISD::STORE:
833    // FIXME: Model these properly.  LOAD and STORE are complicated, and
834    // STORE expects the unlegalized operand in some cases.
835    SimpleFinishLegalizing = false;
836    break;
837  case ISD::CALLSEQ_START:
838  case ISD::CALLSEQ_END:
839    // FIXME: This shouldn't be necessary.  These nodes have special properties
840    // dealing with the recursive nature of legalization.  Removing this
841    // special case should be done as part of making LegalizeDAG non-recursive.
842    SimpleFinishLegalizing = false;
843    break;
844  case ISD::EXTRACT_ELEMENT:
845  case ISD::FLT_ROUNDS_:
846  case ISD::SADDO:
847  case ISD::SSUBO:
848  case ISD::UADDO:
849  case ISD::USUBO:
850  case ISD::SMULO:
851  case ISD::UMULO:
852  case ISD::FPOWI:
853  case ISD::MERGE_VALUES:
854  case ISD::EH_RETURN:
855  case ISD::FRAME_TO_ARGS_OFFSET:
856    // These operations lie about being legal: when they claim to be legal,
857    // they should actually be expanded.
858    Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
859    if (Action == TargetLowering::Legal)
860      Action = TargetLowering::Expand;
861    break;
862  case ISD::TRAMPOLINE:
863  case ISD::FRAMEADDR:
864  case ISD::RETURNADDR:
865  case ISD::EH_SJLJ_SETJMP:
866  case ISD::EH_SJLJ_LONGJMP:
867    // These operations lie about being legal: when they claim to be legal,
868    // they should actually be custom-lowered.
869    Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
870    if (Action == TargetLowering::Legal)
871      Action = TargetLowering::Custom;
872    break;
873  case ISD::BUILD_VECTOR:
874    // A weird case: legalization for BUILD_VECTOR never legalizes the
875    // operands!
876    // FIXME: This really sucks... changing it isn't semantically incorrect,
877    // but it massively pessimizes the code for floating-point BUILD_VECTORs
878    // because ConstantFP operands get legalized into constant pool loads
879    // before the BUILD_VECTOR code can see them.  It doesn't usually bite,
880    // though, because BUILD_VECTORS usually get lowered into other nodes
881    // which get legalized properly.
882    SimpleFinishLegalizing = false;
883    break;
884  default:
885    if (Node->getOpcode() >= ISD::BUILTIN_OP_END) {
886      Action = TargetLowering::Legal;
887    } else {
888      Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
889    }
890    break;
891  }
892
893  if (SimpleFinishLegalizing) {
894    SmallVector<SDValue, 8> Ops, ResultVals;
895    for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
896      Ops.push_back(LegalizeOp(Node->getOperand(i)));
897    switch (Node->getOpcode()) {
898    default: break;
899    case ISD::BR:
900    case ISD::BRIND:
901    case ISD::BR_JT:
902    case ISD::BR_CC:
903    case ISD::BRCOND:
904      // Branches tweak the chain to include LastCALLSEQ_END
905      Ops[0] = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ops[0],
906                            LastCALLSEQ_END);
907      Ops[0] = LegalizeOp(Ops[0]);
908      LastCALLSEQ_END = DAG.getEntryNode();
909      break;
910    case ISD::SHL:
911    case ISD::SRL:
912    case ISD::SRA:
913    case ISD::ROTL:
914    case ISD::ROTR:
915      // Legalizing shifts/rotates requires adjusting the shift amount
916      // to the appropriate width.
917      if (!Ops[1].getValueType().isVector())
918        Ops[1] = LegalizeOp(DAG.getShiftAmountOperand(Ops[1]));
919      break;
920    case ISD::SRL_PARTS:
921    case ISD::SRA_PARTS:
922    case ISD::SHL_PARTS:
923      // Legalizing shifts/rotates requires adjusting the shift amount
924      // to the appropriate width.
925      if (!Ops[2].getValueType().isVector())
926        Ops[2] = LegalizeOp(DAG.getShiftAmountOperand(Ops[2]));
927      break;
928    }
929
930    Result = SDValue(DAG.UpdateNodeOperands(Result.getNode(), Ops.data(),
931                                            Ops.size()), 0);
932    switch (Action) {
933    case TargetLowering::Legal:
934      for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
935        ResultVals.push_back(Result.getValue(i));
936      break;
937    case TargetLowering::Custom:
938      // FIXME: The handling for custom lowering with multiple results is
939      // a complete mess.
940      Tmp1 = TLI.LowerOperation(Result, DAG);
941      if (Tmp1.getNode()) {
942        for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i) {
943          if (e == 1)
944            ResultVals.push_back(Tmp1);
945          else
946            ResultVals.push_back(Tmp1.getValue(i));
947        }
948        break;
949      }
950
951      // FALL THROUGH
952    case TargetLowering::Expand:
953      ExpandNode(Result.getNode(), ResultVals);
954      break;
955    case TargetLowering::Promote:
956      PromoteNode(Result.getNode(), ResultVals);
957      break;
958    }
959    if (!ResultVals.empty()) {
960      for (unsigned i = 0, e = ResultVals.size(); i != e; ++i) {
961        if (ResultVals[i] != SDValue(Node, i))
962          ResultVals[i] = LegalizeOp(ResultVals[i]);
963        AddLegalizedOperand(SDValue(Node, i), ResultVals[i]);
964      }
965      return ResultVals[Op.getResNo()];
966    }
967  }
968
969  switch (Node->getOpcode()) {
970  default:
971#ifndef NDEBUG
972    dbgs() << "NODE: ";
973    Node->dump( &DAG);
974    dbgs() << "\n";
975#endif
976    assert(0 && "Do not know how to legalize this operator!");
977
978  case ISD::BUILD_VECTOR:
979    switch (TLI.getOperationAction(ISD::BUILD_VECTOR, Node->getValueType(0))) {
980    default: assert(0 && "This action is not supported yet!");
981    case TargetLowering::Custom:
982      Tmp3 = TLI.LowerOperation(Result, DAG);
983      if (Tmp3.getNode()) {
984        Result = Tmp3;
985        break;
986      }
987      // FALLTHROUGH
988    case TargetLowering::Expand:
989      Result = ExpandBUILD_VECTOR(Result.getNode());
990      break;
991    }
992    break;
993  case ISD::CALLSEQ_START: {
994    SDNode *CallEnd = FindCallEndFromCallStart(Node);
995
996    // Recursively Legalize all of the inputs of the call end that do not lead
997    // to this call start.  This ensures that any libcalls that need be inserted
998    // are inserted *before* the CALLSEQ_START.
999    {SmallPtrSet<SDNode*, 32> NodesLeadingTo;
1000    for (unsigned i = 0, e = CallEnd->getNumOperands(); i != e; ++i)
1001      LegalizeAllNodesNotLeadingTo(CallEnd->getOperand(i).getNode(), Node,
1002                                   NodesLeadingTo);
1003    }
1004
1005    // Now that we legalized all of the inputs (which may have inserted
1006    // libcalls) create the new CALLSEQ_START node.
1007    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1008
1009    // Merge in the last call, to ensure that this call start after the last
1010    // call ended.
1011    if (LastCALLSEQ_END.getOpcode() != ISD::EntryToken) {
1012      Tmp1 = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1013                         Tmp1, LastCALLSEQ_END);
1014      Tmp1 = LegalizeOp(Tmp1);
1015    }
1016
1017    // Do not try to legalize the target-specific arguments (#1+).
1018    if (Tmp1 != Node->getOperand(0)) {
1019      SmallVector<SDValue, 8> Ops(Node->op_begin(), Node->op_end());
1020      Ops[0] = Tmp1;
1021      Result = SDValue(DAG.UpdateNodeOperands(Result.getNode(), &Ops[0], Ops.size()),
1022                       Result.getResNo());
1023    }
1024
1025    // Remember that the CALLSEQ_START is legalized.
1026    AddLegalizedOperand(Op.getValue(0), Result);
1027    if (Node->getNumValues() == 2)    // If this has a flag result, remember it.
1028      AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
1029
1030    // Now that the callseq_start and all of the non-call nodes above this call
1031    // sequence have been legalized, legalize the call itself.  During this
1032    // process, no libcalls can/will be inserted, guaranteeing that no calls
1033    // can overlap.
1034    assert(!IsLegalizingCall && "Inconsistent sequentialization of calls!");
1035    // Note that we are selecting this call!
1036    LastCALLSEQ_END = SDValue(CallEnd, 0);
1037    IsLegalizingCall = true;
1038
1039    // Legalize the call, starting from the CALLSEQ_END.
1040    LegalizeOp(LastCALLSEQ_END);
1041    assert(!IsLegalizingCall && "CALLSEQ_END should have cleared this!");
1042    return Result;
1043  }
1044  case ISD::CALLSEQ_END:
1045    // If the CALLSEQ_START node hasn't been legalized first, legalize it.  This
1046    // will cause this node to be legalized as well as handling libcalls right.
1047    if (LastCALLSEQ_END.getNode() != Node) {
1048      LegalizeOp(SDValue(FindCallStartFromCallEnd(Node), 0));
1049      DenseMap<SDValue, SDValue>::iterator I = LegalizedNodes.find(Op);
1050      assert(I != LegalizedNodes.end() &&
1051             "Legalizing the call start should have legalized this node!");
1052      return I->second;
1053    }
1054
1055    // Otherwise, the call start has been legalized and everything is going
1056    // according to plan.  Just legalize ourselves normally here.
1057    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1058    // Do not try to legalize the target-specific arguments (#1+), except for
1059    // an optional flag input.
1060    if (Node->getOperand(Node->getNumOperands()-1).getValueType() != MVT::Flag){
1061      if (Tmp1 != Node->getOperand(0)) {
1062        SmallVector<SDValue, 8> Ops(Node->op_begin(), Node->op_end());
1063        Ops[0] = Tmp1;
1064        Result = SDValue(DAG.UpdateNodeOperands(Result.getNode(),
1065                                                &Ops[0], Ops.size()),
1066                         Result.getResNo());
1067      }
1068    } else {
1069      Tmp2 = LegalizeOp(Node->getOperand(Node->getNumOperands()-1));
1070      if (Tmp1 != Node->getOperand(0) ||
1071          Tmp2 != Node->getOperand(Node->getNumOperands()-1)) {
1072        SmallVector<SDValue, 8> Ops(Node->op_begin(), Node->op_end());
1073        Ops[0] = Tmp1;
1074        Ops.back() = Tmp2;
1075        Result = SDValue(DAG.UpdateNodeOperands(Result.getNode(),
1076                                                &Ops[0], Ops.size()),
1077                         Result.getResNo());
1078      }
1079    }
1080    assert(IsLegalizingCall && "Call sequence imbalance between start/end?");
1081    // This finishes up call legalization.
1082    IsLegalizingCall = false;
1083
1084    // If the CALLSEQ_END node has a flag, remember that we legalized it.
1085    AddLegalizedOperand(SDValue(Node, 0), Result.getValue(0));
1086    if (Node->getNumValues() == 2)
1087      AddLegalizedOperand(SDValue(Node, 1), Result.getValue(1));
1088    return Result.getValue(Op.getResNo());
1089  case ISD::LOAD: {
1090    LoadSDNode *LD = cast<LoadSDNode>(Node);
1091    Tmp1 = LegalizeOp(LD->getChain());   // Legalize the chain.
1092    Tmp2 = LegalizeOp(LD->getBasePtr()); // Legalize the base pointer.
1093
1094    ISD::LoadExtType ExtType = LD->getExtensionType();
1095    if (ExtType == ISD::NON_EXTLOAD) {
1096      EVT VT = Node->getValueType(0);
1097      Result = SDValue(DAG.UpdateNodeOperands(Result.getNode(),
1098                                              Tmp1, Tmp2, LD->getOffset()),
1099                       Result.getResNo());
1100      Tmp3 = Result.getValue(0);
1101      Tmp4 = Result.getValue(1);
1102
1103      switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
1104      default: assert(0 && "This action is not supported yet!");
1105      case TargetLowering::Legal:
1106        // If this is an unaligned load and the target doesn't support it,
1107        // expand it.
1108        if (!TLI.allowsUnalignedMemoryAccesses(LD->getMemoryVT())) {
1109          const Type *Ty = LD->getMemoryVT().getTypeForEVT(*DAG.getContext());
1110          unsigned ABIAlignment = TLI.getTargetData()->getABITypeAlignment(Ty);
1111          if (LD->getAlignment() < ABIAlignment){
1112            Result = ExpandUnalignedLoad(cast<LoadSDNode>(Result.getNode()),
1113                                         DAG, TLI);
1114            Tmp3 = Result.getOperand(0);
1115            Tmp4 = Result.getOperand(1);
1116            Tmp3 = LegalizeOp(Tmp3);
1117            Tmp4 = LegalizeOp(Tmp4);
1118          }
1119        }
1120        break;
1121      case TargetLowering::Custom:
1122        Tmp1 = TLI.LowerOperation(Tmp3, DAG);
1123        if (Tmp1.getNode()) {
1124          Tmp3 = LegalizeOp(Tmp1);
1125          Tmp4 = LegalizeOp(Tmp1.getValue(1));
1126        }
1127        break;
1128      case TargetLowering::Promote: {
1129        // Only promote a load of vector type to another.
1130        assert(VT.isVector() && "Cannot promote this load!");
1131        // Change base type to a different vector type.
1132        EVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), VT);
1133
1134        Tmp1 = DAG.getLoad(NVT, dl, Tmp1, Tmp2, LD->getSrcValue(),
1135                           LD->getSrcValueOffset(),
1136                           LD->isVolatile(), LD->isNonTemporal(),
1137                           LD->getAlignment());
1138        Tmp3 = LegalizeOp(DAG.getNode(ISD::BIT_CONVERT, dl, VT, Tmp1));
1139        Tmp4 = LegalizeOp(Tmp1.getValue(1));
1140        break;
1141      }
1142      }
1143      // Since loads produce two values, make sure to remember that we
1144      // legalized both of them.
1145      AddLegalizedOperand(SDValue(Node, 0), Tmp3);
1146      AddLegalizedOperand(SDValue(Node, 1), Tmp4);
1147      return Op.getResNo() ? Tmp4 : Tmp3;
1148    } else {
1149      EVT SrcVT = LD->getMemoryVT();
1150      unsigned SrcWidth = SrcVT.getSizeInBits();
1151      int SVOffset = LD->getSrcValueOffset();
1152      unsigned Alignment = LD->getAlignment();
1153      bool isVolatile = LD->isVolatile();
1154      bool isNonTemporal = LD->isNonTemporal();
1155
1156      if (SrcWidth != SrcVT.getStoreSizeInBits() &&
1157          // Some targets pretend to have an i1 loading operation, and actually
1158          // load an i8.  This trick is correct for ZEXTLOAD because the top 7
1159          // bits are guaranteed to be zero; it helps the optimizers understand
1160          // that these bits are zero.  It is also useful for EXTLOAD, since it
1161          // tells the optimizers that those bits are undefined.  It would be
1162          // nice to have an effective generic way of getting these benefits...
1163          // Until such a way is found, don't insist on promoting i1 here.
1164          (SrcVT != MVT::i1 ||
1165           TLI.getLoadExtAction(ExtType, MVT::i1) == TargetLowering::Promote)) {
1166        // Promote to a byte-sized load if not loading an integral number of
1167        // bytes.  For example, promote EXTLOAD:i20 -> EXTLOAD:i24.
1168        unsigned NewWidth = SrcVT.getStoreSizeInBits();
1169        EVT NVT = EVT::getIntegerVT(*DAG.getContext(), NewWidth);
1170        SDValue Ch;
1171
1172        // The extra bits are guaranteed to be zero, since we stored them that
1173        // way.  A zext load from NVT thus automatically gives zext from SrcVT.
1174
1175        ISD::LoadExtType NewExtType =
1176          ExtType == ISD::ZEXTLOAD ? ISD::ZEXTLOAD : ISD::EXTLOAD;
1177
1178        Result = DAG.getExtLoad(NewExtType, dl, Node->getValueType(0),
1179                                Tmp1, Tmp2, LD->getSrcValue(), SVOffset,
1180                                NVT, isVolatile, isNonTemporal, Alignment);
1181
1182        Ch = Result.getValue(1); // The chain.
1183
1184        if (ExtType == ISD::SEXTLOAD)
1185          // Having the top bits zero doesn't help when sign extending.
1186          Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl,
1187                               Result.getValueType(),
1188                               Result, DAG.getValueType(SrcVT));
1189        else if (ExtType == ISD::ZEXTLOAD || NVT == Result.getValueType())
1190          // All the top bits are guaranteed to be zero - inform the optimizers.
1191          Result = DAG.getNode(ISD::AssertZext, dl,
1192                               Result.getValueType(), Result,
1193                               DAG.getValueType(SrcVT));
1194
1195        Tmp1 = LegalizeOp(Result);
1196        Tmp2 = LegalizeOp(Ch);
1197      } else if (SrcWidth & (SrcWidth - 1)) {
1198        // If not loading a power-of-2 number of bits, expand as two loads.
1199        assert(!SrcVT.isVector() && "Unsupported extload!");
1200        unsigned RoundWidth = 1 << Log2_32(SrcWidth);
1201        assert(RoundWidth < SrcWidth);
1202        unsigned ExtraWidth = SrcWidth - RoundWidth;
1203        assert(ExtraWidth < RoundWidth);
1204        assert(!(RoundWidth % 8) && !(ExtraWidth % 8) &&
1205               "Load size not an integral number of bytes!");
1206        EVT RoundVT = EVT::getIntegerVT(*DAG.getContext(), RoundWidth);
1207        EVT ExtraVT = EVT::getIntegerVT(*DAG.getContext(), ExtraWidth);
1208        SDValue Lo, Hi, Ch;
1209        unsigned IncrementSize;
1210
1211        if (TLI.isLittleEndian()) {
1212          // EXTLOAD:i24 -> ZEXTLOAD:i16 | (shl EXTLOAD@+2:i8, 16)
1213          // Load the bottom RoundWidth bits.
1214          Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl,
1215                              Node->getValueType(0), Tmp1, Tmp2,
1216                              LD->getSrcValue(), SVOffset, RoundVT, isVolatile,
1217                              isNonTemporal, Alignment);
1218
1219          // Load the remaining ExtraWidth bits.
1220          IncrementSize = RoundWidth / 8;
1221          Tmp2 = DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
1222                             DAG.getIntPtrConstant(IncrementSize));
1223          Hi = DAG.getExtLoad(ExtType, dl, Node->getValueType(0), Tmp1, Tmp2,
1224                              LD->getSrcValue(), SVOffset + IncrementSize,
1225                              ExtraVT, isVolatile, isNonTemporal,
1226                              MinAlign(Alignment, IncrementSize));
1227
1228          // Build a factor node to remember that this load is independent of the
1229          // other one.
1230          Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
1231                           Hi.getValue(1));
1232
1233          // Move the top bits to the right place.
1234          Hi = DAG.getNode(ISD::SHL, dl, Hi.getValueType(), Hi,
1235                           DAG.getConstant(RoundWidth, TLI.getShiftAmountTy()));
1236
1237          // Join the hi and lo parts.
1238          Result = DAG.getNode(ISD::OR, dl, Node->getValueType(0), Lo, Hi);
1239        } else {
1240          // Big endian - avoid unaligned loads.
1241          // EXTLOAD:i24 -> (shl EXTLOAD:i16, 8) | ZEXTLOAD@+2:i8
1242          // Load the top RoundWidth bits.
1243          Hi = DAG.getExtLoad(ExtType, dl, Node->getValueType(0), Tmp1, Tmp2,
1244                              LD->getSrcValue(), SVOffset, RoundVT, isVolatile,
1245                              isNonTemporal, Alignment);
1246
1247          // Load the remaining ExtraWidth bits.
1248          IncrementSize = RoundWidth / 8;
1249          Tmp2 = DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
1250                             DAG.getIntPtrConstant(IncrementSize));
1251          Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl,
1252                              Node->getValueType(0), Tmp1, Tmp2,
1253                              LD->getSrcValue(), SVOffset + IncrementSize,
1254                              ExtraVT, isVolatile, isNonTemporal,
1255                              MinAlign(Alignment, IncrementSize));
1256
1257          // Build a factor node to remember that this load is independent of the
1258          // other one.
1259          Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
1260                           Hi.getValue(1));
1261
1262          // Move the top bits to the right place.
1263          Hi = DAG.getNode(ISD::SHL, dl, Hi.getValueType(), Hi,
1264                           DAG.getConstant(ExtraWidth, TLI.getShiftAmountTy()));
1265
1266          // Join the hi and lo parts.
1267          Result = DAG.getNode(ISD::OR, dl, Node->getValueType(0), Lo, Hi);
1268        }
1269
1270        Tmp1 = LegalizeOp(Result);
1271        Tmp2 = LegalizeOp(Ch);
1272      } else {
1273        switch (TLI.getLoadExtAction(ExtType, SrcVT)) {
1274        default: assert(0 && "This action is not supported yet!");
1275        case TargetLowering::Custom:
1276          isCustom = true;
1277          // FALLTHROUGH
1278        case TargetLowering::Legal:
1279          Result = SDValue(DAG.UpdateNodeOperands(Result.getNode(),
1280                                                  Tmp1, Tmp2, LD->getOffset()),
1281                           Result.getResNo());
1282          Tmp1 = Result.getValue(0);
1283          Tmp2 = Result.getValue(1);
1284
1285          if (isCustom) {
1286            Tmp3 = TLI.LowerOperation(Result, DAG);
1287            if (Tmp3.getNode()) {
1288              Tmp1 = LegalizeOp(Tmp3);
1289              Tmp2 = LegalizeOp(Tmp3.getValue(1));
1290            }
1291          } else {
1292            // If this is an unaligned load and the target doesn't support it,
1293            // expand it.
1294            if (!TLI.allowsUnalignedMemoryAccesses(LD->getMemoryVT())) {
1295              const Type *Ty = LD->getMemoryVT().getTypeForEVT(*DAG.getContext());
1296              unsigned ABIAlignment = TLI.getTargetData()->getABITypeAlignment(Ty);
1297              if (LD->getAlignment() < ABIAlignment){
1298                Result = ExpandUnalignedLoad(cast<LoadSDNode>(Result.getNode()),
1299                                             DAG, TLI);
1300                Tmp1 = Result.getOperand(0);
1301                Tmp2 = Result.getOperand(1);
1302                Tmp1 = LegalizeOp(Tmp1);
1303                Tmp2 = LegalizeOp(Tmp2);
1304              }
1305            }
1306          }
1307          break;
1308        case TargetLowering::Expand:
1309          // f64 = EXTLOAD f32 should expand to LOAD, FP_EXTEND
1310          // f128 = EXTLOAD {f32,f64} too
1311          if ((SrcVT == MVT::f32 && (Node->getValueType(0) == MVT::f64 ||
1312                                     Node->getValueType(0) == MVT::f128)) ||
1313              (SrcVT == MVT::f64 && Node->getValueType(0) == MVT::f128)) {
1314            SDValue Load = DAG.getLoad(SrcVT, dl, Tmp1, Tmp2, LD->getSrcValue(),
1315                                       LD->getSrcValueOffset(),
1316                                       LD->isVolatile(), LD->isNonTemporal(),
1317                                       LD->getAlignment());
1318            Result = DAG.getNode(ISD::FP_EXTEND, dl,
1319                                 Node->getValueType(0), Load);
1320            Tmp1 = LegalizeOp(Result);  // Relegalize new nodes.
1321            Tmp2 = LegalizeOp(Load.getValue(1));
1322            break;
1323          }
1324          assert(ExtType != ISD::EXTLOAD &&"EXTLOAD should always be supported!");
1325          // Turn the unsupported load into an EXTLOAD followed by an explicit
1326          // zero/sign extend inreg.
1327          Result = DAG.getExtLoad(ISD::EXTLOAD, dl, Node->getValueType(0),
1328                                  Tmp1, Tmp2, LD->getSrcValue(),
1329                                  LD->getSrcValueOffset(), SrcVT,
1330                                  LD->isVolatile(), LD->isNonTemporal(),
1331                                  LD->getAlignment());
1332          SDValue ValRes;
1333          if (ExtType == ISD::SEXTLOAD)
1334            ValRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl,
1335                                 Result.getValueType(),
1336                                 Result, DAG.getValueType(SrcVT));
1337          else
1338            ValRes = DAG.getZeroExtendInReg(Result, dl, SrcVT);
1339          Tmp1 = LegalizeOp(ValRes);  // Relegalize new nodes.
1340          Tmp2 = LegalizeOp(Result.getValue(1));  // Relegalize new nodes.
1341          break;
1342        }
1343      }
1344
1345      // Since loads produce two values, make sure to remember that we legalized
1346      // both of them.
1347      AddLegalizedOperand(SDValue(Node, 0), Tmp1);
1348      AddLegalizedOperand(SDValue(Node, 1), Tmp2);
1349      return Op.getResNo() ? Tmp2 : Tmp1;
1350    }
1351  }
1352  case ISD::STORE: {
1353    StoreSDNode *ST = cast<StoreSDNode>(Node);
1354    Tmp1 = LegalizeOp(ST->getChain());    // Legalize the chain.
1355    Tmp2 = LegalizeOp(ST->getBasePtr());  // Legalize the pointer.
1356    int SVOffset = ST->getSrcValueOffset();
1357    unsigned Alignment = ST->getAlignment();
1358    bool isVolatile = ST->isVolatile();
1359    bool isNonTemporal = ST->isNonTemporal();
1360
1361    if (!ST->isTruncatingStore()) {
1362      if (SDNode *OptStore = OptimizeFloatStore(ST).getNode()) {
1363        Result = SDValue(OptStore, 0);
1364        break;
1365      }
1366
1367      {
1368        Tmp3 = LegalizeOp(ST->getValue());
1369        Result = SDValue(DAG.UpdateNodeOperands(Result.getNode(),
1370                                                Tmp1, Tmp3, Tmp2,
1371                                                ST->getOffset()),
1372                         Result.getResNo());
1373
1374        EVT VT = Tmp3.getValueType();
1375        switch (TLI.getOperationAction(ISD::STORE, VT)) {
1376        default: assert(0 && "This action is not supported yet!");
1377        case TargetLowering::Legal:
1378          // If this is an unaligned store and the target doesn't support it,
1379          // expand it.
1380          if (!TLI.allowsUnalignedMemoryAccesses(ST->getMemoryVT())) {
1381            const Type *Ty = ST->getMemoryVT().getTypeForEVT(*DAG.getContext());
1382            unsigned ABIAlignment = TLI.getTargetData()->getABITypeAlignment(Ty);
1383            if (ST->getAlignment() < ABIAlignment)
1384              Result = ExpandUnalignedStore(cast<StoreSDNode>(Result.getNode()),
1385                                            DAG, TLI);
1386          }
1387          break;
1388        case TargetLowering::Custom:
1389          Tmp1 = TLI.LowerOperation(Result, DAG);
1390          if (Tmp1.getNode()) Result = Tmp1;
1391          break;
1392        case TargetLowering::Promote:
1393          assert(VT.isVector() && "Unknown legal promote case!");
1394          Tmp3 = DAG.getNode(ISD::BIT_CONVERT, dl,
1395                             TLI.getTypeToPromoteTo(ISD::STORE, VT), Tmp3);
1396          Result = DAG.getStore(Tmp1, dl, Tmp3, Tmp2,
1397                                ST->getSrcValue(), SVOffset, isVolatile,
1398                                isNonTemporal, Alignment);
1399          break;
1400        }
1401        break;
1402      }
1403    } else {
1404      Tmp3 = LegalizeOp(ST->getValue());
1405
1406      EVT StVT = ST->getMemoryVT();
1407      unsigned StWidth = StVT.getSizeInBits();
1408
1409      if (StWidth != StVT.getStoreSizeInBits()) {
1410        // Promote to a byte-sized store with upper bits zero if not
1411        // storing an integral number of bytes.  For example, promote
1412        // TRUNCSTORE:i1 X -> TRUNCSTORE:i8 (and X, 1)
1413        EVT NVT = EVT::getIntegerVT(*DAG.getContext(),
1414                                    StVT.getStoreSizeInBits());
1415        Tmp3 = DAG.getZeroExtendInReg(Tmp3, dl, StVT);
1416        Result = DAG.getTruncStore(Tmp1, dl, Tmp3, Tmp2, ST->getSrcValue(),
1417                                   SVOffset, NVT, isVolatile, isNonTemporal,
1418                                   Alignment);
1419      } else if (StWidth & (StWidth - 1)) {
1420        // If not storing a power-of-2 number of bits, expand as two stores.
1421        assert(!StVT.isVector() && "Unsupported truncstore!");
1422        unsigned RoundWidth = 1 << Log2_32(StWidth);
1423        assert(RoundWidth < StWidth);
1424        unsigned ExtraWidth = StWidth - RoundWidth;
1425        assert(ExtraWidth < RoundWidth);
1426        assert(!(RoundWidth % 8) && !(ExtraWidth % 8) &&
1427               "Store size not an integral number of bytes!");
1428        EVT RoundVT = EVT::getIntegerVT(*DAG.getContext(), RoundWidth);
1429        EVT ExtraVT = EVT::getIntegerVT(*DAG.getContext(), ExtraWidth);
1430        SDValue Lo, Hi;
1431        unsigned IncrementSize;
1432
1433        if (TLI.isLittleEndian()) {
1434          // TRUNCSTORE:i24 X -> TRUNCSTORE:i16 X, TRUNCSTORE@+2:i8 (srl X, 16)
1435          // Store the bottom RoundWidth bits.
1436          Lo = DAG.getTruncStore(Tmp1, dl, Tmp3, Tmp2, ST->getSrcValue(),
1437                                 SVOffset, RoundVT,
1438                                 isVolatile, isNonTemporal, Alignment);
1439
1440          // Store the remaining ExtraWidth bits.
1441          IncrementSize = RoundWidth / 8;
1442          Tmp2 = DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
1443                             DAG.getIntPtrConstant(IncrementSize));
1444          Hi = DAG.getNode(ISD::SRL, dl, Tmp3.getValueType(), Tmp3,
1445                           DAG.getConstant(RoundWidth, TLI.getShiftAmountTy()));
1446          Hi = DAG.getTruncStore(Tmp1, dl, Hi, Tmp2, ST->getSrcValue(),
1447                                 SVOffset + IncrementSize, ExtraVT, isVolatile,
1448                                 isNonTemporal,
1449                                 MinAlign(Alignment, IncrementSize));
1450        } else {
1451          // Big endian - avoid unaligned stores.
1452          // TRUNCSTORE:i24 X -> TRUNCSTORE:i16 (srl X, 8), TRUNCSTORE@+2:i8 X
1453          // Store the top RoundWidth bits.
1454          Hi = DAG.getNode(ISD::SRL, dl, Tmp3.getValueType(), Tmp3,
1455                           DAG.getConstant(ExtraWidth, TLI.getShiftAmountTy()));
1456          Hi = DAG.getTruncStore(Tmp1, dl, Hi, Tmp2, ST->getSrcValue(),
1457                                 SVOffset, RoundVT, isVolatile, isNonTemporal,
1458                                 Alignment);
1459
1460          // Store the remaining ExtraWidth bits.
1461          IncrementSize = RoundWidth / 8;
1462          Tmp2 = DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
1463                             DAG.getIntPtrConstant(IncrementSize));
1464          Lo = DAG.getTruncStore(Tmp1, dl, Tmp3, Tmp2, ST->getSrcValue(),
1465                                 SVOffset + IncrementSize, ExtraVT, isVolatile,
1466                                 isNonTemporal,
1467                                 MinAlign(Alignment, IncrementSize));
1468        }
1469
1470        // The order of the stores doesn't matter.
1471        Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi);
1472      } else {
1473        if (Tmp1 != ST->getChain() || Tmp3 != ST->getValue() ||
1474            Tmp2 != ST->getBasePtr())
1475          Result = SDValue(DAG.UpdateNodeOperands(Result.getNode(),
1476                                                  Tmp1, Tmp3, Tmp2,
1477                                                  ST->getOffset()),
1478                           Result.getResNo());
1479
1480        switch (TLI.getTruncStoreAction(ST->getValue().getValueType(), StVT)) {
1481        default: assert(0 && "This action is not supported yet!");
1482        case TargetLowering::Legal:
1483          // If this is an unaligned store and the target doesn't support it,
1484          // expand it.
1485          if (!TLI.allowsUnalignedMemoryAccesses(ST->getMemoryVT())) {
1486            const Type *Ty = ST->getMemoryVT().getTypeForEVT(*DAG.getContext());
1487            unsigned ABIAlignment = TLI.getTargetData()->getABITypeAlignment(Ty);
1488            if (ST->getAlignment() < ABIAlignment)
1489              Result = ExpandUnalignedStore(cast<StoreSDNode>(Result.getNode()),
1490                                            DAG, TLI);
1491          }
1492          break;
1493        case TargetLowering::Custom:
1494          Result = TLI.LowerOperation(Result, DAG);
1495          break;
1496        case Expand:
1497          // TRUNCSTORE:i16 i32 -> STORE i16
1498          assert(isTypeLegal(StVT) && "Do not know how to expand this store!");
1499          Tmp3 = DAG.getNode(ISD::TRUNCATE, dl, StVT, Tmp3);
1500          Result = DAG.getStore(Tmp1, dl, Tmp3, Tmp2, ST->getSrcValue(),
1501                                SVOffset, isVolatile, isNonTemporal,
1502                                Alignment);
1503          break;
1504        }
1505      }
1506    }
1507    break;
1508  }
1509  }
1510  assert(Result.getValueType() == Op.getValueType() &&
1511         "Bad legalization!");
1512
1513  // Make sure that the generated code is itself legal.
1514  if (Result != Op)
1515    Result = LegalizeOp(Result);
1516
1517  // Note that LegalizeOp may be reentered even from single-use nodes, which
1518  // means that we always must cache transformed nodes.
1519  AddLegalizedOperand(Op, Result);
1520  return Result;
1521}
1522
1523SDValue SelectionDAGLegalize::ExpandExtractFromVectorThroughStack(SDValue Op) {
1524  SDValue Vec = Op.getOperand(0);
1525  SDValue Idx = Op.getOperand(1);
1526  DebugLoc dl = Op.getDebugLoc();
1527  // Store the value to a temporary stack slot, then LOAD the returned part.
1528  SDValue StackPtr = DAG.CreateStackTemporary(Vec.getValueType());
1529  SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, Vec, StackPtr, NULL, 0,
1530                            false, false, 0);
1531
1532  // Add the offset to the index.
1533  unsigned EltSize =
1534      Vec.getValueType().getVectorElementType().getSizeInBits()/8;
1535  Idx = DAG.getNode(ISD::MUL, dl, Idx.getValueType(), Idx,
1536                    DAG.getConstant(EltSize, Idx.getValueType()));
1537
1538  if (Idx.getValueType().bitsGT(TLI.getPointerTy()))
1539    Idx = DAG.getNode(ISD::TRUNCATE, dl, TLI.getPointerTy(), Idx);
1540  else
1541    Idx = DAG.getNode(ISD::ZERO_EXTEND, dl, TLI.getPointerTy(), Idx);
1542
1543  StackPtr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(), Idx, StackPtr);
1544
1545  if (Op.getValueType().isVector())
1546    return DAG.getLoad(Op.getValueType(), dl, Ch, StackPtr, NULL, 0,
1547                       false, false, 0);
1548  else
1549    return DAG.getExtLoad(ISD::EXTLOAD, dl, Op.getValueType(), Ch, StackPtr,
1550                          NULL, 0, Vec.getValueType().getVectorElementType(),
1551                          false, false, 0);
1552}
1553
1554SDValue SelectionDAGLegalize::ExpandVectorBuildThroughStack(SDNode* Node) {
1555  // We can't handle this case efficiently.  Allocate a sufficiently
1556  // aligned object on the stack, store each element into it, then load
1557  // the result as a vector.
1558  // Create the stack frame object.
1559  EVT VT = Node->getValueType(0);
1560  EVT EltVT = VT.getVectorElementType();
1561  DebugLoc dl = Node->getDebugLoc();
1562  SDValue FIPtr = DAG.CreateStackTemporary(VT);
1563  int FI = cast<FrameIndexSDNode>(FIPtr.getNode())->getIndex();
1564  const Value *SV = PseudoSourceValue::getFixedStack(FI);
1565
1566  // Emit a store of each element to the stack slot.
1567  SmallVector<SDValue, 8> Stores;
1568  unsigned TypeByteSize = EltVT.getSizeInBits() / 8;
1569  // Store (in the right endianness) the elements to memory.
1570  for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
1571    // Ignore undef elements.
1572    if (Node->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1573
1574    unsigned Offset = TypeByteSize*i;
1575
1576    SDValue Idx = DAG.getConstant(Offset, FIPtr.getValueType());
1577    Idx = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, Idx);
1578
1579    // If the destination vector element type is narrower than the source
1580    // element type, only store the bits necessary.
1581    if (EltVT.bitsLT(Node->getOperand(i).getValueType().getScalarType())) {
1582      Stores.push_back(DAG.getTruncStore(DAG.getEntryNode(), dl,
1583                                         Node->getOperand(i), Idx, SV, Offset,
1584                                         EltVT, false, false, 0));
1585    } else
1586      Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl,
1587                                    Node->getOperand(i), Idx, SV, Offset,
1588                                    false, false, 0));
1589  }
1590
1591  SDValue StoreChain;
1592  if (!Stores.empty())    // Not all undef elements?
1593    StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1594                             &Stores[0], Stores.size());
1595  else
1596    StoreChain = DAG.getEntryNode();
1597
1598  // Result is a load from the stack slot.
1599  return DAG.getLoad(VT, dl, StoreChain, FIPtr, SV, 0, false, false, 0);
1600}
1601
1602SDValue SelectionDAGLegalize::ExpandFCOPYSIGN(SDNode* Node) {
1603  DebugLoc dl = Node->getDebugLoc();
1604  SDValue Tmp1 = Node->getOperand(0);
1605  SDValue Tmp2 = Node->getOperand(1);
1606
1607  // Get the sign bit of the RHS.  First obtain a value that has the same
1608  // sign as the sign bit, i.e. negative if and only if the sign bit is 1.
1609  SDValue SignBit;
1610  EVT FloatVT = Tmp2.getValueType();
1611  EVT IVT = EVT::getIntegerVT(*DAG.getContext(), FloatVT.getSizeInBits());
1612  if (isTypeLegal(IVT)) {
1613    // Convert to an integer with the same sign bit.
1614    SignBit = DAG.getNode(ISD::BIT_CONVERT, dl, IVT, Tmp2);
1615  } else {
1616    // Store the float to memory, then load the sign part out as an integer.
1617    MVT LoadTy = TLI.getPointerTy();
1618    // First create a temporary that is aligned for both the load and store.
1619    SDValue StackPtr = DAG.CreateStackTemporary(FloatVT, LoadTy);
1620    // Then store the float to it.
1621    SDValue Ch =
1622      DAG.getStore(DAG.getEntryNode(), dl, Tmp2, StackPtr, NULL, 0,
1623                   false, false, 0);
1624    if (TLI.isBigEndian()) {
1625      assert(FloatVT.isByteSized() && "Unsupported floating point type!");
1626      // Load out a legal integer with the same sign bit as the float.
1627      SignBit = DAG.getLoad(LoadTy, dl, Ch, StackPtr, NULL, 0, false, false, 0);
1628    } else { // Little endian
1629      SDValue LoadPtr = StackPtr;
1630      // The float may be wider than the integer we are going to load.  Advance
1631      // the pointer so that the loaded integer will contain the sign bit.
1632      unsigned Strides = (FloatVT.getSizeInBits()-1)/LoadTy.getSizeInBits();
1633      unsigned ByteOffset = (Strides * LoadTy.getSizeInBits()) / 8;
1634      LoadPtr = DAG.getNode(ISD::ADD, dl, LoadPtr.getValueType(),
1635                            LoadPtr, DAG.getIntPtrConstant(ByteOffset));
1636      // Load a legal integer containing the sign bit.
1637      SignBit = DAG.getLoad(LoadTy, dl, Ch, LoadPtr, NULL, 0, false, false, 0);
1638      // Move the sign bit to the top bit of the loaded integer.
1639      unsigned BitShift = LoadTy.getSizeInBits() -
1640        (FloatVT.getSizeInBits() - 8 * ByteOffset);
1641      assert(BitShift < LoadTy.getSizeInBits() && "Pointer advanced wrong?");
1642      if (BitShift)
1643        SignBit = DAG.getNode(ISD::SHL, dl, LoadTy, SignBit,
1644                              DAG.getConstant(BitShift,TLI.getShiftAmountTy()));
1645    }
1646  }
1647  // Now get the sign bit proper, by seeing whether the value is negative.
1648  SignBit = DAG.getSetCC(dl, TLI.getSetCCResultType(SignBit.getValueType()),
1649                         SignBit, DAG.getConstant(0, SignBit.getValueType()),
1650                         ISD::SETLT);
1651  // Get the absolute value of the result.
1652  SDValue AbsVal = DAG.getNode(ISD::FABS, dl, Tmp1.getValueType(), Tmp1);
1653  // Select between the nabs and abs value based on the sign bit of
1654  // the input.
1655  return DAG.getNode(ISD::SELECT, dl, AbsVal.getValueType(), SignBit,
1656                     DAG.getNode(ISD::FNEG, dl, AbsVal.getValueType(), AbsVal),
1657                     AbsVal);
1658}
1659
1660void SelectionDAGLegalize::ExpandDYNAMIC_STACKALLOC(SDNode* Node,
1661                                           SmallVectorImpl<SDValue> &Results) {
1662  unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
1663  assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
1664          " not tell us which reg is the stack pointer!");
1665  DebugLoc dl = Node->getDebugLoc();
1666  EVT VT = Node->getValueType(0);
1667  SDValue Tmp1 = SDValue(Node, 0);
1668  SDValue Tmp2 = SDValue(Node, 1);
1669  SDValue Tmp3 = Node->getOperand(2);
1670  SDValue Chain = Tmp1.getOperand(0);
1671
1672  // Chain the dynamic stack allocation so that it doesn't modify the stack
1673  // pointer when other instructions are using the stack.
1674  Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true));
1675
1676  SDValue Size  = Tmp2.getOperand(1);
1677  SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
1678  Chain = SP.getValue(1);
1679  unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
1680  unsigned StackAlign = TM.getFrameInfo()->getStackAlignment();
1681  if (Align > StackAlign)
1682    SP = DAG.getNode(ISD::AND, dl, VT, SP,
1683                      DAG.getConstant(-(uint64_t)Align, VT));
1684  Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size);       // Value
1685  Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1);     // Output chain
1686
1687  Tmp2 = DAG.getCALLSEQ_END(Chain,  DAG.getIntPtrConstant(0, true),
1688                            DAG.getIntPtrConstant(0, true), SDValue());
1689
1690  Results.push_back(Tmp1);
1691  Results.push_back(Tmp2);
1692}
1693
1694/// LegalizeSetCCCondCode - Legalize a SETCC with given LHS and RHS and
1695/// condition code CC on the current target. This routine expands SETCC with
1696/// illegal condition code into AND / OR of multiple SETCC values.
1697void SelectionDAGLegalize::LegalizeSetCCCondCode(EVT VT,
1698                                                 SDValue &LHS, SDValue &RHS,
1699                                                 SDValue &CC,
1700                                                 DebugLoc dl) {
1701  EVT OpVT = LHS.getValueType();
1702  ISD::CondCode CCCode = cast<CondCodeSDNode>(CC)->get();
1703  switch (TLI.getCondCodeAction(CCCode, OpVT)) {
1704  default: assert(0 && "Unknown condition code action!");
1705  case TargetLowering::Legal:
1706    // Nothing to do.
1707    break;
1708  case TargetLowering::Expand: {
1709    ISD::CondCode CC1 = ISD::SETCC_INVALID, CC2 = ISD::SETCC_INVALID;
1710    unsigned Opc = 0;
1711    switch (CCCode) {
1712    default: assert(0 && "Don't know how to expand this condition!");
1713    case ISD::SETOEQ: CC1 = ISD::SETEQ; CC2 = ISD::SETO;  Opc = ISD::AND; break;
1714    case ISD::SETOGT: CC1 = ISD::SETGT; CC2 = ISD::SETO;  Opc = ISD::AND; break;
1715    case ISD::SETOGE: CC1 = ISD::SETGE; CC2 = ISD::SETO;  Opc = ISD::AND; break;
1716    case ISD::SETOLT: CC1 = ISD::SETLT; CC2 = ISD::SETO;  Opc = ISD::AND; break;
1717    case ISD::SETOLE: CC1 = ISD::SETLE; CC2 = ISD::SETO;  Opc = ISD::AND; break;
1718    case ISD::SETONE: CC1 = ISD::SETNE; CC2 = ISD::SETO;  Opc = ISD::AND; break;
1719    case ISD::SETUEQ: CC1 = ISD::SETEQ; CC2 = ISD::SETUO; Opc = ISD::OR;  break;
1720    case ISD::SETUGT: CC1 = ISD::SETGT; CC2 = ISD::SETUO; Opc = ISD::OR;  break;
1721    case ISD::SETUGE: CC1 = ISD::SETGE; CC2 = ISD::SETUO; Opc = ISD::OR;  break;
1722    case ISD::SETULT: CC1 = ISD::SETLT; CC2 = ISD::SETUO; Opc = ISD::OR;  break;
1723    case ISD::SETULE: CC1 = ISD::SETLE; CC2 = ISD::SETUO; Opc = ISD::OR;  break;
1724    case ISD::SETUNE: CC1 = ISD::SETNE; CC2 = ISD::SETUO; Opc = ISD::OR;  break;
1725    // FIXME: Implement more expansions.
1726    }
1727
1728    SDValue SetCC1 = DAG.getSetCC(dl, VT, LHS, RHS, CC1);
1729    SDValue SetCC2 = DAG.getSetCC(dl, VT, LHS, RHS, CC2);
1730    LHS = DAG.getNode(Opc, dl, VT, SetCC1, SetCC2);
1731    RHS = SDValue();
1732    CC  = SDValue();
1733    break;
1734  }
1735  }
1736}
1737
1738/// EmitStackConvert - Emit a store/load combination to the stack.  This stores
1739/// SrcOp to a stack slot of type SlotVT, truncating it if needed.  It then does
1740/// a load from the stack slot to DestVT, extending it if needed.
1741/// The resultant code need not be legal.
1742SDValue SelectionDAGLegalize::EmitStackConvert(SDValue SrcOp,
1743                                               EVT SlotVT,
1744                                               EVT DestVT,
1745                                               DebugLoc dl) {
1746  // Create the stack frame object.
1747  unsigned SrcAlign =
1748    TLI.getTargetData()->getPrefTypeAlignment(SrcOp.getValueType().
1749                                              getTypeForEVT(*DAG.getContext()));
1750  SDValue FIPtr = DAG.CreateStackTemporary(SlotVT, SrcAlign);
1751
1752  FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(FIPtr);
1753  int SPFI = StackPtrFI->getIndex();
1754  const Value *SV = PseudoSourceValue::getFixedStack(SPFI);
1755
1756  unsigned SrcSize = SrcOp.getValueType().getSizeInBits();
1757  unsigned SlotSize = SlotVT.getSizeInBits();
1758  unsigned DestSize = DestVT.getSizeInBits();
1759  const Type *DestType = DestVT.getTypeForEVT(*DAG.getContext());
1760  unsigned DestAlign = TLI.getTargetData()->getPrefTypeAlignment(DestType);
1761
1762  // Emit a store to the stack slot.  Use a truncstore if the input value is
1763  // later than DestVT.
1764  SDValue Store;
1765
1766  if (SrcSize > SlotSize)
1767    Store = DAG.getTruncStore(DAG.getEntryNode(), dl, SrcOp, FIPtr,
1768                              SV, 0, SlotVT, false, false, SrcAlign);
1769  else {
1770    assert(SrcSize == SlotSize && "Invalid store");
1771    Store = DAG.getStore(DAG.getEntryNode(), dl, SrcOp, FIPtr,
1772                         SV, 0, false, false, SrcAlign);
1773  }
1774
1775  // Result is a load from the stack slot.
1776  if (SlotSize == DestSize)
1777    return DAG.getLoad(DestVT, dl, Store, FIPtr, SV, 0, false, false,
1778                       DestAlign);
1779
1780  assert(SlotSize < DestSize && "Unknown extension!");
1781  return DAG.getExtLoad(ISD::EXTLOAD, dl, DestVT, Store, FIPtr, SV, 0, SlotVT,
1782                        false, false, DestAlign);
1783}
1784
1785SDValue SelectionDAGLegalize::ExpandSCALAR_TO_VECTOR(SDNode *Node) {
1786  DebugLoc dl = Node->getDebugLoc();
1787  // Create a vector sized/aligned stack slot, store the value to element #0,
1788  // then load the whole vector back out.
1789  SDValue StackPtr = DAG.CreateStackTemporary(Node->getValueType(0));
1790
1791  FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(StackPtr);
1792  int SPFI = StackPtrFI->getIndex();
1793
1794  SDValue Ch = DAG.getTruncStore(DAG.getEntryNode(), dl, Node->getOperand(0),
1795                                 StackPtr,
1796                                 PseudoSourceValue::getFixedStack(SPFI), 0,
1797                                 Node->getValueType(0).getVectorElementType(),
1798                                 false, false, 0);
1799  return DAG.getLoad(Node->getValueType(0), dl, Ch, StackPtr,
1800                     PseudoSourceValue::getFixedStack(SPFI), 0,
1801                     false, false, 0);
1802}
1803
1804
1805/// ExpandBUILD_VECTOR - Expand a BUILD_VECTOR node on targets that don't
1806/// support the operation, but do support the resultant vector type.
1807SDValue SelectionDAGLegalize::ExpandBUILD_VECTOR(SDNode *Node) {
1808  unsigned NumElems = Node->getNumOperands();
1809  SDValue Value1, Value2;
1810  DebugLoc dl = Node->getDebugLoc();
1811  EVT VT = Node->getValueType(0);
1812  EVT OpVT = Node->getOperand(0).getValueType();
1813  EVT EltVT = VT.getVectorElementType();
1814
1815  // If the only non-undef value is the low element, turn this into a
1816  // SCALAR_TO_VECTOR node.  If this is { X, X, X, X }, determine X.
1817  bool isOnlyLowElement = true;
1818  bool MoreThanTwoValues = false;
1819  bool isConstant = true;
1820  for (unsigned i = 0; i < NumElems; ++i) {
1821    SDValue V = Node->getOperand(i);
1822    if (V.getOpcode() == ISD::UNDEF)
1823      continue;
1824    if (i > 0)
1825      isOnlyLowElement = false;
1826    if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
1827      isConstant = false;
1828
1829    if (!Value1.getNode()) {
1830      Value1 = V;
1831    } else if (!Value2.getNode()) {
1832      if (V != Value1)
1833        Value2 = V;
1834    } else if (V != Value1 && V != Value2) {
1835      MoreThanTwoValues = true;
1836    }
1837  }
1838
1839  if (!Value1.getNode())
1840    return DAG.getUNDEF(VT);
1841
1842  if (isOnlyLowElement)
1843    return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Node->getOperand(0));
1844
1845  // If all elements are constants, create a load from the constant pool.
1846  if (isConstant) {
1847    std::vector<Constant*> CV;
1848    for (unsigned i = 0, e = NumElems; i != e; ++i) {
1849      if (ConstantFPSDNode *V =
1850          dyn_cast<ConstantFPSDNode>(Node->getOperand(i))) {
1851        CV.push_back(const_cast<ConstantFP *>(V->getConstantFPValue()));
1852      } else if (ConstantSDNode *V =
1853                 dyn_cast<ConstantSDNode>(Node->getOperand(i))) {
1854        if (OpVT==EltVT)
1855          CV.push_back(const_cast<ConstantInt *>(V->getConstantIntValue()));
1856        else {
1857          // If OpVT and EltVT don't match, EltVT is not legal and the
1858          // element values have been promoted/truncated earlier.  Undo this;
1859          // we don't want a v16i8 to become a v16i32 for example.
1860          const ConstantInt *CI = V->getConstantIntValue();
1861          CV.push_back(ConstantInt::get(EltVT.getTypeForEVT(*DAG.getContext()),
1862                                        CI->getZExtValue()));
1863        }
1864      } else {
1865        assert(Node->getOperand(i).getOpcode() == ISD::UNDEF);
1866        const Type *OpNTy = EltVT.getTypeForEVT(*DAG.getContext());
1867        CV.push_back(UndefValue::get(OpNTy));
1868      }
1869    }
1870    Constant *CP = ConstantVector::get(CV);
1871    SDValue CPIdx = DAG.getConstantPool(CP, TLI.getPointerTy());
1872    unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
1873    return DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
1874                       PseudoSourceValue::getConstantPool(), 0,
1875                       false, false, Alignment);
1876  }
1877
1878  if (!MoreThanTwoValues) {
1879    SmallVector<int, 8> ShuffleVec(NumElems, -1);
1880    for (unsigned i = 0; i < NumElems; ++i) {
1881      SDValue V = Node->getOperand(i);
1882      if (V.getOpcode() == ISD::UNDEF)
1883        continue;
1884      ShuffleVec[i] = V == Value1 ? 0 : NumElems;
1885    }
1886    if (TLI.isShuffleMaskLegal(ShuffleVec, Node->getValueType(0))) {
1887      // Get the splatted value into the low element of a vector register.
1888      SDValue Vec1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value1);
1889      SDValue Vec2;
1890      if (Value2.getNode())
1891        Vec2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value2);
1892      else
1893        Vec2 = DAG.getUNDEF(VT);
1894
1895      // Return shuffle(LowValVec, undef, <0,0,0,0>)
1896      return DAG.getVectorShuffle(VT, dl, Vec1, Vec2, ShuffleVec.data());
1897    }
1898  }
1899
1900  // Otherwise, we can't handle this case efficiently.
1901  return ExpandVectorBuildThroughStack(Node);
1902}
1903
1904// ExpandLibCall - Expand a node into a call to a libcall.  If the result value
1905// does not fit into a register, return the lo part and set the hi part to the
1906// by-reg argument.  If it does fit into a single register, return the result
1907// and leave the Hi part unset.
1908SDValue SelectionDAGLegalize::ExpandLibCall(RTLIB::Libcall LC, SDNode *Node,
1909                                            bool isSigned) {
1910  assert(!IsLegalizingCall && "Cannot overlap legalization of calls!");
1911  // The input chain to this libcall is the entry node of the function.
1912  // Legalizing the call will automatically add the previous call to the
1913  // dependence.
1914  SDValue InChain = DAG.getEntryNode();
1915
1916  TargetLowering::ArgListTy Args;
1917  TargetLowering::ArgListEntry Entry;
1918  for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
1919    EVT ArgVT = Node->getOperand(i).getValueType();
1920    const Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
1921    Entry.Node = Node->getOperand(i); Entry.Ty = ArgTy;
1922    Entry.isSExt = isSigned;
1923    Entry.isZExt = !isSigned;
1924    Args.push_back(Entry);
1925  }
1926  SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
1927                                         TLI.getPointerTy());
1928
1929  // Splice the libcall in wherever FindInputOutputChains tells us to.
1930  const Type *RetTy = Node->getValueType(0).getTypeForEVT(*DAG.getContext());
1931  std::pair<SDValue, SDValue> CallInfo =
1932    TLI.LowerCallTo(InChain, RetTy, isSigned, !isSigned, false, false,
1933                    0, TLI.getLibcallCallingConv(LC), false,
1934                    /*isReturnValueUsed=*/true,
1935                    Callee, Args, DAG, Node->getDebugLoc());
1936
1937  // Legalize the call sequence, starting with the chain.  This will advance
1938  // the LastCALLSEQ_END to the legalized version of the CALLSEQ_END node that
1939  // was added by LowerCallTo (guaranteeing proper serialization of calls).
1940  LegalizeOp(CallInfo.second);
1941  return CallInfo.first;
1942}
1943
1944SDValue SelectionDAGLegalize::ExpandFPLibCall(SDNode* Node,
1945                                              RTLIB::Libcall Call_F32,
1946                                              RTLIB::Libcall Call_F64,
1947                                              RTLIB::Libcall Call_F80,
1948                                              RTLIB::Libcall Call_PPCF128) {
1949  RTLIB::Libcall LC;
1950  switch (Node->getValueType(0).getSimpleVT().SimpleTy) {
1951  default: assert(0 && "Unexpected request for libcall!");
1952  case MVT::f32: LC = Call_F32; break;
1953  case MVT::f64: LC = Call_F64; break;
1954  case MVT::f80: LC = Call_F80; break;
1955  case MVT::ppcf128: LC = Call_PPCF128; break;
1956  }
1957  return ExpandLibCall(LC, Node, false);
1958}
1959
1960SDValue SelectionDAGLegalize::ExpandIntLibCall(SDNode* Node, bool isSigned,
1961                                               RTLIB::Libcall Call_I8,
1962                                               RTLIB::Libcall Call_I16,
1963                                               RTLIB::Libcall Call_I32,
1964                                               RTLIB::Libcall Call_I64,
1965                                               RTLIB::Libcall Call_I128) {
1966  RTLIB::Libcall LC;
1967  switch (Node->getValueType(0).getSimpleVT().SimpleTy) {
1968  default: assert(0 && "Unexpected request for libcall!");
1969  case MVT::i8:   LC = Call_I8; break;
1970  case MVT::i16:  LC = Call_I16; break;
1971  case MVT::i32:  LC = Call_I32; break;
1972  case MVT::i64:  LC = Call_I64; break;
1973  case MVT::i128: LC = Call_I128; break;
1974  }
1975  return ExpandLibCall(LC, Node, isSigned);
1976}
1977
1978/// ExpandLegalINT_TO_FP - This function is responsible for legalizing a
1979/// INT_TO_FP operation of the specified operand when the target requests that
1980/// we expand it.  At this point, we know that the result and operand types are
1981/// legal for the target.
1982SDValue SelectionDAGLegalize::ExpandLegalINT_TO_FP(bool isSigned,
1983                                                   SDValue Op0,
1984                                                   EVT DestVT,
1985                                                   DebugLoc dl) {
1986  if (Op0.getValueType() == MVT::i32) {
1987    // simple 32-bit [signed|unsigned] integer to float/double expansion
1988
1989    // Get the stack frame index of a 8 byte buffer.
1990    SDValue StackSlot = DAG.CreateStackTemporary(MVT::f64);
1991
1992    // word offset constant for Hi/Lo address computation
1993    SDValue WordOff = DAG.getConstant(sizeof(int), TLI.getPointerTy());
1994    // set up Hi and Lo (into buffer) address based on endian
1995    SDValue Hi = StackSlot;
1996    SDValue Lo = DAG.getNode(ISD::ADD, dl,
1997                             TLI.getPointerTy(), StackSlot, WordOff);
1998    if (TLI.isLittleEndian())
1999      std::swap(Hi, Lo);
2000
2001    // if signed map to unsigned space
2002    SDValue Op0Mapped;
2003    if (isSigned) {
2004      // constant used to invert sign bit (signed to unsigned mapping)
2005      SDValue SignBit = DAG.getConstant(0x80000000u, MVT::i32);
2006      Op0Mapped = DAG.getNode(ISD::XOR, dl, MVT::i32, Op0, SignBit);
2007    } else {
2008      Op0Mapped = Op0;
2009    }
2010    // store the lo of the constructed double - based on integer input
2011    SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl,
2012                                  Op0Mapped, Lo, NULL, 0,
2013                                  false, false, 0);
2014    // initial hi portion of constructed double
2015    SDValue InitialHi = DAG.getConstant(0x43300000u, MVT::i32);
2016    // store the hi of the constructed double - biased exponent
2017    SDValue Store2=DAG.getStore(Store1, dl, InitialHi, Hi, NULL, 0,
2018                                false, false, 0);
2019    // load the constructed double
2020    SDValue Load = DAG.getLoad(MVT::f64, dl, Store2, StackSlot, NULL, 0,
2021                               false, false, 0);
2022    // FP constant to bias correct the final result
2023    SDValue Bias = DAG.getConstantFP(isSigned ?
2024                                     BitsToDouble(0x4330000080000000ULL) :
2025                                     BitsToDouble(0x4330000000000000ULL),
2026                                     MVT::f64);
2027    // subtract the bias
2028    SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Load, Bias);
2029    // final result
2030    SDValue Result;
2031    // handle final rounding
2032    if (DestVT == MVT::f64) {
2033      // do nothing
2034      Result = Sub;
2035    } else if (DestVT.bitsLT(MVT::f64)) {
2036      Result = DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
2037                           DAG.getIntPtrConstant(0));
2038    } else if (DestVT.bitsGT(MVT::f64)) {
2039      Result = DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
2040    }
2041    return Result;
2042  }
2043  assert(!isSigned && "Legalize cannot Expand SINT_TO_FP for i64 yet");
2044  // Code below here assumes !isSigned without checking again.
2045
2046  // Implementation of unsigned i64 to f64 following the algorithm in
2047  // __floatundidf in compiler_rt. This implementation has the advantage
2048  // of performing rounding correctly, both in the default rounding mode
2049  // and in all alternate rounding modes.
2050  // TODO: Generalize this for use with other types.
2051  if (Op0.getValueType() == MVT::i64 && DestVT == MVT::f64) {
2052    SDValue TwoP52 =
2053      DAG.getConstant(UINT64_C(0x4330000000000000), MVT::i64);
2054    SDValue TwoP84PlusTwoP52 =
2055      DAG.getConstantFP(BitsToDouble(UINT64_C(0x4530000000100000)), MVT::f64);
2056    SDValue TwoP84 =
2057      DAG.getConstant(UINT64_C(0x4530000000000000), MVT::i64);
2058
2059    SDValue Lo = DAG.getZeroExtendInReg(Op0, dl, MVT::i32);
2060    SDValue Hi = DAG.getNode(ISD::SRL, dl, MVT::i64, Op0,
2061                             DAG.getConstant(32, MVT::i64));
2062    SDValue LoOr = DAG.getNode(ISD::OR, dl, MVT::i64, Lo, TwoP52);
2063    SDValue HiOr = DAG.getNode(ISD::OR, dl, MVT::i64, Hi, TwoP84);
2064    SDValue LoFlt = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f64, LoOr);
2065    SDValue HiFlt = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f64, HiOr);
2066    SDValue HiSub = DAG.getNode(ISD::FSUB, dl, MVT::f64, HiFlt, TwoP84PlusTwoP52);
2067    return DAG.getNode(ISD::FADD, dl, MVT::f64, LoFlt, HiSub);
2068  }
2069
2070  // Implementation of unsigned i64 to f32.  This implementation has the
2071  // advantage of performing rounding correctly.
2072  // TODO: Generalize this for use with other types.
2073  if (Op0.getValueType() == MVT::i64 && DestVT == MVT::f32) {
2074    EVT SHVT = TLI.getShiftAmountTy();
2075
2076    SDValue And = DAG.getNode(ISD::AND, dl, MVT::i64, Op0,
2077         DAG.getConstant(UINT64_C(0xfffffffffffff800), MVT::i64));
2078    SDValue Or = DAG.getNode(ISD::OR, dl, MVT::i64, And,
2079         DAG.getConstant(UINT64_C(0x800), MVT::i64));
2080    SDValue And2 = DAG.getNode(ISD::AND, dl, MVT::i64, Op0,
2081         DAG.getConstant(UINT64_C(0x7ff), MVT::i64));
2082    SDValue Ne = DAG.getSetCC(dl, TLI.getSetCCResultType(MVT::i64),
2083                   And2, DAG.getConstant(UINT64_C(0), MVT::i64), ISD::SETNE);
2084    SDValue Sel = DAG.getNode(ISD::SELECT, dl, MVT::i64, Ne, Or, Op0);
2085    SDValue Ge = DAG.getSetCC(dl, TLI.getSetCCResultType(MVT::i64),
2086                   Op0, DAG.getConstant(UINT64_C(0x0020000000000000), MVT::i64),
2087                    ISD::SETUGE);
2088    SDValue Sel2 = DAG.getNode(ISD::SELECT, dl, MVT::i64, Ge, Sel, Op0);
2089
2090    SDValue Sh = DAG.getNode(ISD::SRL, dl, MVT::i64, Sel2,
2091                             DAG.getConstant(32, SHVT));
2092    SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Sh);
2093    SDValue Fcvt = DAG.getNode(ISD::UINT_TO_FP, dl, MVT::f64, Trunc);
2094    SDValue TwoP32 =
2095      DAG.getConstantFP(BitsToDouble(UINT64_C(0x41f0000000000000)), MVT::f64);
2096    SDValue Fmul = DAG.getNode(ISD::FMUL, dl, MVT::f64, TwoP32, Fcvt);
2097    SDValue Lo = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Sel2);
2098    SDValue Fcvt2 = DAG.getNode(ISD::UINT_TO_FP, dl, MVT::f64, Lo);
2099    SDValue Fadd = DAG.getNode(ISD::FADD, dl, MVT::f64, Fmul, Fcvt2);
2100    return DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, Fadd,
2101                       DAG.getIntPtrConstant(0));
2102
2103  }
2104
2105  SDValue Tmp1 = DAG.getNode(ISD::SINT_TO_FP, dl, DestVT, Op0);
2106
2107  SDValue SignSet = DAG.getSetCC(dl, TLI.getSetCCResultType(Op0.getValueType()),
2108                                 Op0, DAG.getConstant(0, Op0.getValueType()),
2109                                 ISD::SETLT);
2110  SDValue Zero = DAG.getIntPtrConstant(0), Four = DAG.getIntPtrConstant(4);
2111  SDValue CstOffset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(),
2112                                    SignSet, Four, Zero);
2113
2114  // If the sign bit of the integer is set, the large number will be treated
2115  // as a negative number.  To counteract this, the dynamic code adds an
2116  // offset depending on the data type.
2117  uint64_t FF;
2118  switch (Op0.getValueType().getSimpleVT().SimpleTy) {
2119  default: assert(0 && "Unsupported integer type!");
2120  case MVT::i8 : FF = 0x43800000ULL; break;  // 2^8  (as a float)
2121  case MVT::i16: FF = 0x47800000ULL; break;  // 2^16 (as a float)
2122  case MVT::i32: FF = 0x4F800000ULL; break;  // 2^32 (as a float)
2123  case MVT::i64: FF = 0x5F800000ULL; break;  // 2^64 (as a float)
2124  }
2125  if (TLI.isLittleEndian()) FF <<= 32;
2126  Constant *FudgeFactor = ConstantInt::get(
2127                                       Type::getInt64Ty(*DAG.getContext()), FF);
2128
2129  SDValue CPIdx = DAG.getConstantPool(FudgeFactor, TLI.getPointerTy());
2130  unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
2131  CPIdx = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(), CPIdx, CstOffset);
2132  Alignment = std::min(Alignment, 4u);
2133  SDValue FudgeInReg;
2134  if (DestVT == MVT::f32)
2135    FudgeInReg = DAG.getLoad(MVT::f32, dl, DAG.getEntryNode(), CPIdx,
2136                             PseudoSourceValue::getConstantPool(), 0,
2137                             false, false, Alignment);
2138  else {
2139    FudgeInReg =
2140      LegalizeOp(DAG.getExtLoad(ISD::EXTLOAD, dl, DestVT,
2141                                DAG.getEntryNode(), CPIdx,
2142                                PseudoSourceValue::getConstantPool(), 0,
2143                                MVT::f32, false, false, Alignment));
2144  }
2145
2146  return DAG.getNode(ISD::FADD, dl, DestVT, Tmp1, FudgeInReg);
2147}
2148
2149/// PromoteLegalINT_TO_FP - This function is responsible for legalizing a
2150/// *INT_TO_FP operation of the specified operand when the target requests that
2151/// we promote it.  At this point, we know that the result and operand types are
2152/// legal for the target, and that there is a legal UINT_TO_FP or SINT_TO_FP
2153/// operation that takes a larger input.
2154SDValue SelectionDAGLegalize::PromoteLegalINT_TO_FP(SDValue LegalOp,
2155                                                    EVT DestVT,
2156                                                    bool isSigned,
2157                                                    DebugLoc dl) {
2158  // First step, figure out the appropriate *INT_TO_FP operation to use.
2159  EVT NewInTy = LegalOp.getValueType();
2160
2161  unsigned OpToUse = 0;
2162
2163  // Scan for the appropriate larger type to use.
2164  while (1) {
2165    NewInTy = (MVT::SimpleValueType)(NewInTy.getSimpleVT().SimpleTy+1);
2166    assert(NewInTy.isInteger() && "Ran out of possibilities!");
2167
2168    // If the target supports SINT_TO_FP of this type, use it.
2169    if (TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, NewInTy)) {
2170      OpToUse = ISD::SINT_TO_FP;
2171      break;
2172    }
2173    if (isSigned) continue;
2174
2175    // If the target supports UINT_TO_FP of this type, use it.
2176    if (TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, NewInTy)) {
2177      OpToUse = ISD::UINT_TO_FP;
2178      break;
2179    }
2180
2181    // Otherwise, try a larger type.
2182  }
2183
2184  // Okay, we found the operation and type to use.  Zero extend our input to the
2185  // desired type then run the operation on it.
2186  return DAG.getNode(OpToUse, dl, DestVT,
2187                     DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
2188                                 dl, NewInTy, LegalOp));
2189}
2190
2191/// PromoteLegalFP_TO_INT - This function is responsible for legalizing a
2192/// FP_TO_*INT operation of the specified operand when the target requests that
2193/// we promote it.  At this point, we know that the result and operand types are
2194/// legal for the target, and that there is a legal FP_TO_UINT or FP_TO_SINT
2195/// operation that returns a larger result.
2196SDValue SelectionDAGLegalize::PromoteLegalFP_TO_INT(SDValue LegalOp,
2197                                                    EVT DestVT,
2198                                                    bool isSigned,
2199                                                    DebugLoc dl) {
2200  // First step, figure out the appropriate FP_TO*INT operation to use.
2201  EVT NewOutTy = DestVT;
2202
2203  unsigned OpToUse = 0;
2204
2205  // Scan for the appropriate larger type to use.
2206  while (1) {
2207    NewOutTy = (MVT::SimpleValueType)(NewOutTy.getSimpleVT().SimpleTy+1);
2208    assert(NewOutTy.isInteger() && "Ran out of possibilities!");
2209
2210    if (TLI.isOperationLegalOrCustom(ISD::FP_TO_SINT, NewOutTy)) {
2211      OpToUse = ISD::FP_TO_SINT;
2212      break;
2213    }
2214
2215    if (TLI.isOperationLegalOrCustom(ISD::FP_TO_UINT, NewOutTy)) {
2216      OpToUse = ISD::FP_TO_UINT;
2217      break;
2218    }
2219
2220    // Otherwise, try a larger type.
2221  }
2222
2223
2224  // Okay, we found the operation and type to use.
2225  SDValue Operation = DAG.getNode(OpToUse, dl, NewOutTy, LegalOp);
2226
2227  // Truncate the result of the extended FP_TO_*INT operation to the desired
2228  // size.
2229  return DAG.getNode(ISD::TRUNCATE, dl, DestVT, Operation);
2230}
2231
2232/// ExpandBSWAP - Open code the operations for BSWAP of the specified operation.
2233///
2234SDValue SelectionDAGLegalize::ExpandBSWAP(SDValue Op, DebugLoc dl) {
2235  EVT VT = Op.getValueType();
2236  EVT SHVT = TLI.getShiftAmountTy();
2237  SDValue Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8;
2238  switch (VT.getSimpleVT().SimpleTy) {
2239  default: assert(0 && "Unhandled Expand type in BSWAP!");
2240  case MVT::i16:
2241    Tmp2 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, SHVT));
2242    Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, SHVT));
2243    return DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
2244  case MVT::i32:
2245    Tmp4 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, SHVT));
2246    Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, SHVT));
2247    Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, SHVT));
2248    Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, SHVT));
2249    Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3, DAG.getConstant(0xFF0000, VT));
2250    Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(0xFF00, VT));
2251    Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
2252    Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
2253    return DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
2254  case MVT::i64:
2255    Tmp8 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(56, SHVT));
2256    Tmp7 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(40, SHVT));
2257    Tmp6 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, SHVT));
2258    Tmp5 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, SHVT));
2259    Tmp4 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, SHVT));
2260    Tmp3 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, SHVT));
2261    Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(40, SHVT));
2262    Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(56, SHVT));
2263    Tmp7 = DAG.getNode(ISD::AND, dl, VT, Tmp7, DAG.getConstant(255ULL<<48, VT));
2264    Tmp6 = DAG.getNode(ISD::AND, dl, VT, Tmp6, DAG.getConstant(255ULL<<40, VT));
2265    Tmp5 = DAG.getNode(ISD::AND, dl, VT, Tmp5, DAG.getConstant(255ULL<<32, VT));
2266    Tmp4 = DAG.getNode(ISD::AND, dl, VT, Tmp4, DAG.getConstant(255ULL<<24, VT));
2267    Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3, DAG.getConstant(255ULL<<16, VT));
2268    Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(255ULL<<8 , VT));
2269    Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp7);
2270    Tmp6 = DAG.getNode(ISD::OR, dl, VT, Tmp6, Tmp5);
2271    Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
2272    Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
2273    Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp6);
2274    Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
2275    return DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp4);
2276  }
2277}
2278
2279/// ExpandBitCount - Expand the specified bitcount instruction into operations.
2280///
2281SDValue SelectionDAGLegalize::ExpandBitCount(unsigned Opc, SDValue Op,
2282                                             DebugLoc dl) {
2283  switch (Opc) {
2284  default: assert(0 && "Cannot expand this yet!");
2285  case ISD::CTPOP: {
2286    static const uint64_t mask[6] = {
2287      0x5555555555555555ULL, 0x3333333333333333ULL,
2288      0x0F0F0F0F0F0F0F0FULL, 0x00FF00FF00FF00FFULL,
2289      0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL
2290    };
2291    EVT VT = Op.getValueType();
2292    EVT ShVT = TLI.getShiftAmountTy();
2293    unsigned len = VT.getSizeInBits();
2294    for (unsigned i = 0; (1U << i) <= (len / 2); ++i) {
2295      //x = (x & mask[i][len/8]) + (x >> (1 << i) & mask[i][len/8])
2296      unsigned EltSize = VT.isVector() ?
2297        VT.getVectorElementType().getSizeInBits() : len;
2298      SDValue Tmp2 = DAG.getConstant(APInt(EltSize, mask[i]), VT);
2299      SDValue Tmp3 = DAG.getConstant(1ULL << i, ShVT);
2300      Op = DAG.getNode(ISD::ADD, dl, VT,
2301                       DAG.getNode(ISD::AND, dl, VT, Op, Tmp2),
2302                       DAG.getNode(ISD::AND, dl, VT,
2303                                   DAG.getNode(ISD::SRL, dl, VT, Op, Tmp3),
2304                                   Tmp2));
2305    }
2306    return Op;
2307  }
2308  case ISD::CTLZ: {
2309    // for now, we do this:
2310    // x = x | (x >> 1);
2311    // x = x | (x >> 2);
2312    // ...
2313    // x = x | (x >>16);
2314    // x = x | (x >>32); // for 64-bit input
2315    // return popcount(~x);
2316    //
2317    // but see also: http://www.hackersdelight.org/HDcode/nlz.cc
2318    EVT VT = Op.getValueType();
2319    EVT ShVT = TLI.getShiftAmountTy();
2320    unsigned len = VT.getSizeInBits();
2321    for (unsigned i = 0; (1U << i) <= (len / 2); ++i) {
2322      SDValue Tmp3 = DAG.getConstant(1ULL << i, ShVT);
2323      Op = DAG.getNode(ISD::OR, dl, VT, Op,
2324                       DAG.getNode(ISD::SRL, dl, VT, Op, Tmp3));
2325    }
2326    Op = DAG.getNOT(dl, Op, VT);
2327    return DAG.getNode(ISD::CTPOP, dl, VT, Op);
2328  }
2329  case ISD::CTTZ: {
2330    // for now, we use: { return popcount(~x & (x - 1)); }
2331    // unless the target has ctlz but not ctpop, in which case we use:
2332    // { return 32 - nlz(~x & (x-1)); }
2333    // see also http://www.hackersdelight.org/HDcode/ntz.cc
2334    EVT VT = Op.getValueType();
2335    SDValue Tmp3 = DAG.getNode(ISD::AND, dl, VT,
2336                               DAG.getNOT(dl, Op, VT),
2337                               DAG.getNode(ISD::SUB, dl, VT, Op,
2338                                           DAG.getConstant(1, VT)));
2339    // If ISD::CTLZ is legal and CTPOP isn't, then do that instead.
2340    if (!TLI.isOperationLegalOrCustom(ISD::CTPOP, VT) &&
2341        TLI.isOperationLegalOrCustom(ISD::CTLZ, VT))
2342      return DAG.getNode(ISD::SUB, dl, VT,
2343                         DAG.getConstant(VT.getSizeInBits(), VT),
2344                         DAG.getNode(ISD::CTLZ, dl, VT, Tmp3));
2345    return DAG.getNode(ISD::CTPOP, dl, VT, Tmp3);
2346  }
2347  }
2348}
2349
2350void SelectionDAGLegalize::ExpandNode(SDNode *Node,
2351                                      SmallVectorImpl<SDValue> &Results) {
2352  DebugLoc dl = Node->getDebugLoc();
2353  SDValue Tmp1, Tmp2, Tmp3, Tmp4;
2354  switch (Node->getOpcode()) {
2355  case ISD::CTPOP:
2356  case ISD::CTLZ:
2357  case ISD::CTTZ:
2358    Tmp1 = ExpandBitCount(Node->getOpcode(), Node->getOperand(0), dl);
2359    Results.push_back(Tmp1);
2360    break;
2361  case ISD::BSWAP:
2362    Results.push_back(ExpandBSWAP(Node->getOperand(0), dl));
2363    break;
2364  case ISD::FRAMEADDR:
2365  case ISD::RETURNADDR:
2366  case ISD::FRAME_TO_ARGS_OFFSET:
2367    Results.push_back(DAG.getConstant(0, Node->getValueType(0)));
2368    break;
2369  case ISD::FLT_ROUNDS_:
2370    Results.push_back(DAG.getConstant(1, Node->getValueType(0)));
2371    break;
2372  case ISD::EH_RETURN:
2373  case ISD::EH_LABEL:
2374  case ISD::PREFETCH:
2375  case ISD::VAEND:
2376    Results.push_back(Node->getOperand(0));
2377    break;
2378  case ISD::MEMBARRIER: {
2379    // If the target didn't lower this, lower it to '__sync_synchronize()' call
2380    TargetLowering::ArgListTy Args;
2381    std::pair<SDValue, SDValue> CallResult =
2382      TLI.LowerCallTo(Node->getOperand(0), Type::getVoidTy(*DAG.getContext()),
2383                      false, false, false, false, 0, CallingConv::C, false,
2384                      /*isReturnValueUsed=*/true,
2385                      DAG.getExternalSymbol("__sync_synchronize",
2386                                            TLI.getPointerTy()),
2387                      Args, DAG, dl);
2388    Results.push_back(CallResult.second);
2389    break;
2390  }
2391  // By default, atomic intrinsics are marked Legal and lowered. Targets
2392  // which don't support them directly, however, may want libcalls, in which
2393  // case they mark them Expand, and we get here.
2394  // FIXME: Unimplemented for now. Add libcalls.
2395  case ISD::ATOMIC_SWAP:
2396  case ISD::ATOMIC_LOAD_ADD:
2397  case ISD::ATOMIC_LOAD_SUB:
2398  case ISD::ATOMIC_LOAD_AND:
2399  case ISD::ATOMIC_LOAD_OR:
2400  case ISD::ATOMIC_LOAD_XOR:
2401  case ISD::ATOMIC_LOAD_NAND:
2402  case ISD::ATOMIC_LOAD_MIN:
2403  case ISD::ATOMIC_LOAD_MAX:
2404  case ISD::ATOMIC_LOAD_UMIN:
2405  case ISD::ATOMIC_LOAD_UMAX:
2406  case ISD::ATOMIC_CMP_SWAP: {
2407    assert (0 && "atomic intrinsic not lowered!");
2408    Results.push_back(Node->getOperand(0));
2409    break;
2410  }
2411  case ISD::DYNAMIC_STACKALLOC:
2412    ExpandDYNAMIC_STACKALLOC(Node, Results);
2413    break;
2414  case ISD::MERGE_VALUES:
2415    for (unsigned i = 0; i < Node->getNumValues(); i++)
2416      Results.push_back(Node->getOperand(i));
2417    break;
2418  case ISD::UNDEF: {
2419    EVT VT = Node->getValueType(0);
2420    if (VT.isInteger())
2421      Results.push_back(DAG.getConstant(0, VT));
2422    else {
2423      assert(VT.isFloatingPoint() && "Unknown value type!");
2424      Results.push_back(DAG.getConstantFP(0, VT));
2425    }
2426    break;
2427  }
2428  case ISD::TRAP: {
2429    // If this operation is not supported, lower it to 'abort()' call
2430    TargetLowering::ArgListTy Args;
2431    std::pair<SDValue, SDValue> CallResult =
2432      TLI.LowerCallTo(Node->getOperand(0), Type::getVoidTy(*DAG.getContext()),
2433                      false, false, false, false, 0, CallingConv::C, false,
2434                      /*isReturnValueUsed=*/true,
2435                      DAG.getExternalSymbol("abort", TLI.getPointerTy()),
2436                      Args, DAG, dl);
2437    Results.push_back(CallResult.second);
2438    break;
2439  }
2440  case ISD::FP_ROUND:
2441  case ISD::BIT_CONVERT:
2442    Tmp1 = EmitStackConvert(Node->getOperand(0), Node->getValueType(0),
2443                            Node->getValueType(0), dl);
2444    Results.push_back(Tmp1);
2445    break;
2446  case ISD::FP_EXTEND:
2447    Tmp1 = EmitStackConvert(Node->getOperand(0),
2448                            Node->getOperand(0).getValueType(),
2449                            Node->getValueType(0), dl);
2450    Results.push_back(Tmp1);
2451    break;
2452  case ISD::SIGN_EXTEND_INREG: {
2453    // NOTE: we could fall back on load/store here too for targets without
2454    // SAR.  However, it is doubtful that any exist.
2455    EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
2456    EVT VT = Node->getValueType(0);
2457    EVT ShiftAmountTy = TLI.getShiftAmountTy();
2458    if (VT.isVector())
2459      ShiftAmountTy = VT;
2460    unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
2461                        ExtraVT.getScalarType().getSizeInBits();
2462    SDValue ShiftCst = DAG.getConstant(BitsDiff, ShiftAmountTy);
2463    Tmp1 = DAG.getNode(ISD::SHL, dl, Node->getValueType(0),
2464                       Node->getOperand(0), ShiftCst);
2465    Tmp1 = DAG.getNode(ISD::SRA, dl, Node->getValueType(0), Tmp1, ShiftCst);
2466    Results.push_back(Tmp1);
2467    break;
2468  }
2469  case ISD::FP_ROUND_INREG: {
2470    // The only way we can lower this is to turn it into a TRUNCSTORE,
2471    // EXTLOAD pair, targetting a temporary location (a stack slot).
2472
2473    // NOTE: there is a choice here between constantly creating new stack
2474    // slots and always reusing the same one.  We currently always create
2475    // new ones, as reuse may inhibit scheduling.
2476    EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
2477    Tmp1 = EmitStackConvert(Node->getOperand(0), ExtraVT,
2478                            Node->getValueType(0), dl);
2479    Results.push_back(Tmp1);
2480    break;
2481  }
2482  case ISD::SINT_TO_FP:
2483  case ISD::UINT_TO_FP:
2484    Tmp1 = ExpandLegalINT_TO_FP(Node->getOpcode() == ISD::SINT_TO_FP,
2485                                Node->getOperand(0), Node->getValueType(0), dl);
2486    Results.push_back(Tmp1);
2487    break;
2488  case ISD::FP_TO_UINT: {
2489    SDValue True, False;
2490    EVT VT =  Node->getOperand(0).getValueType();
2491    EVT NVT = Node->getValueType(0);
2492    const uint64_t zero[] = {0, 0};
2493    APFloat apf = APFloat(APInt(VT.getSizeInBits(), 2, zero));
2494    APInt x = APInt::getSignBit(NVT.getSizeInBits());
2495    (void)apf.convertFromAPInt(x, false, APFloat::rmNearestTiesToEven);
2496    Tmp1 = DAG.getConstantFP(apf, VT);
2497    Tmp2 = DAG.getSetCC(dl, TLI.getSetCCResultType(VT),
2498                        Node->getOperand(0),
2499                        Tmp1, ISD::SETLT);
2500    True = DAG.getNode(ISD::FP_TO_SINT, dl, NVT, Node->getOperand(0));
2501    False = DAG.getNode(ISD::FP_TO_SINT, dl, NVT,
2502                        DAG.getNode(ISD::FSUB, dl, VT,
2503                                    Node->getOperand(0), Tmp1));
2504    False = DAG.getNode(ISD::XOR, dl, NVT, False,
2505                        DAG.getConstant(x, NVT));
2506    Tmp1 = DAG.getNode(ISD::SELECT, dl, NVT, Tmp2, True, False);
2507    Results.push_back(Tmp1);
2508    break;
2509  }
2510  case ISD::VAARG: {
2511    const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2512    EVT VT = Node->getValueType(0);
2513    Tmp1 = Node->getOperand(0);
2514    Tmp2 = Node->getOperand(1);
2515    SDValue VAList = DAG.getLoad(TLI.getPointerTy(), dl, Tmp1, Tmp2, V, 0,
2516                                 false, false, 0);
2517    // Increment the pointer, VAList, to the next vaarg
2518    Tmp3 = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(), VAList,
2519                       DAG.getConstant(TLI.getTargetData()->
2520                          getTypeAllocSize(VT.getTypeForEVT(*DAG.getContext())),
2521                                       TLI.getPointerTy()));
2522    // Store the incremented VAList to the legalized pointer
2523    Tmp3 = DAG.getStore(VAList.getValue(1), dl, Tmp3, Tmp2, V, 0,
2524                        false, false, 0);
2525    // Load the actual argument out of the pointer VAList
2526    Results.push_back(DAG.getLoad(VT, dl, Tmp3, VAList, NULL, 0,
2527                                  false, false, 0));
2528    Results.push_back(Results[0].getValue(1));
2529    break;
2530  }
2531  case ISD::VACOPY: {
2532    // This defaults to loading a pointer from the input and storing it to the
2533    // output, returning the chain.
2534    const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
2535    const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
2536    Tmp1 = DAG.getLoad(TLI.getPointerTy(), dl, Node->getOperand(0),
2537                       Node->getOperand(2), VS, 0, false, false, 0);
2538    Tmp1 = DAG.getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1), VD, 0,
2539                        false, false, 0);
2540    Results.push_back(Tmp1);
2541    break;
2542  }
2543  case ISD::EXTRACT_VECTOR_ELT:
2544    if (Node->getOperand(0).getValueType().getVectorNumElements() == 1)
2545      // This must be an access of the only element.  Return it.
2546      Tmp1 = DAG.getNode(ISD::BIT_CONVERT, dl, Node->getValueType(0),
2547                         Node->getOperand(0));
2548    else
2549      Tmp1 = ExpandExtractFromVectorThroughStack(SDValue(Node, 0));
2550    Results.push_back(Tmp1);
2551    break;
2552  case ISD::EXTRACT_SUBVECTOR:
2553    Results.push_back(ExpandExtractFromVectorThroughStack(SDValue(Node, 0)));
2554    break;
2555  case ISD::CONCAT_VECTORS: {
2556    Results.push_back(ExpandVectorBuildThroughStack(Node));
2557    break;
2558  }
2559  case ISD::SCALAR_TO_VECTOR:
2560    Results.push_back(ExpandSCALAR_TO_VECTOR(Node));
2561    break;
2562  case ISD::INSERT_VECTOR_ELT:
2563    Results.push_back(ExpandINSERT_VECTOR_ELT(Node->getOperand(0),
2564                                              Node->getOperand(1),
2565                                              Node->getOperand(2), dl));
2566    break;
2567  case ISD::VECTOR_SHUFFLE: {
2568    SmallVector<int, 8> Mask;
2569    cast<ShuffleVectorSDNode>(Node)->getMask(Mask);
2570
2571    EVT VT = Node->getValueType(0);
2572    EVT EltVT = VT.getVectorElementType();
2573    if (getTypeAction(EltVT) == Promote)
2574      EltVT = TLI.getTypeToTransformTo(*DAG.getContext(), EltVT);
2575    unsigned NumElems = VT.getVectorNumElements();
2576    SmallVector<SDValue, 8> Ops;
2577    for (unsigned i = 0; i != NumElems; ++i) {
2578      if (Mask[i] < 0) {
2579        Ops.push_back(DAG.getUNDEF(EltVT));
2580        continue;
2581      }
2582      unsigned Idx = Mask[i];
2583      if (Idx < NumElems)
2584        Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
2585                                  Node->getOperand(0),
2586                                  DAG.getIntPtrConstant(Idx)));
2587      else
2588        Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
2589                                  Node->getOperand(1),
2590                                  DAG.getIntPtrConstant(Idx - NumElems)));
2591    }
2592    Tmp1 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Ops[0], Ops.size());
2593    Results.push_back(Tmp1);
2594    break;
2595  }
2596  case ISD::EXTRACT_ELEMENT: {
2597    EVT OpTy = Node->getOperand(0).getValueType();
2598    if (cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue()) {
2599      // 1 -> Hi
2600      Tmp1 = DAG.getNode(ISD::SRL, dl, OpTy, Node->getOperand(0),
2601                         DAG.getConstant(OpTy.getSizeInBits()/2,
2602                                         TLI.getShiftAmountTy()));
2603      Tmp1 = DAG.getNode(ISD::TRUNCATE, dl, Node->getValueType(0), Tmp1);
2604    } else {
2605      // 0 -> Lo
2606      Tmp1 = DAG.getNode(ISD::TRUNCATE, dl, Node->getValueType(0),
2607                         Node->getOperand(0));
2608    }
2609    Results.push_back(Tmp1);
2610    break;
2611  }
2612  case ISD::STACKSAVE:
2613    // Expand to CopyFromReg if the target set
2614    // StackPointerRegisterToSaveRestore.
2615    if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) {
2616      Results.push_back(DAG.getCopyFromReg(Node->getOperand(0), dl, SP,
2617                                           Node->getValueType(0)));
2618      Results.push_back(Results[0].getValue(1));
2619    } else {
2620      Results.push_back(DAG.getUNDEF(Node->getValueType(0)));
2621      Results.push_back(Node->getOperand(0));
2622    }
2623    break;
2624  case ISD::STACKRESTORE:
2625    // Expand to CopyToReg if the target set
2626    // StackPointerRegisterToSaveRestore.
2627    if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) {
2628      Results.push_back(DAG.getCopyToReg(Node->getOperand(0), dl, SP,
2629                                         Node->getOperand(1)));
2630    } else {
2631      Results.push_back(Node->getOperand(0));
2632    }
2633    break;
2634  case ISD::FCOPYSIGN:
2635    Results.push_back(ExpandFCOPYSIGN(Node));
2636    break;
2637  case ISD::FNEG:
2638    // Expand Y = FNEG(X) ->  Y = SUB -0.0, X
2639    Tmp1 = DAG.getConstantFP(-0.0, Node->getValueType(0));
2640    Tmp1 = DAG.getNode(ISD::FSUB, dl, Node->getValueType(0), Tmp1,
2641                       Node->getOperand(0));
2642    Results.push_back(Tmp1);
2643    break;
2644  case ISD::FABS: {
2645    // Expand Y = FABS(X) -> Y = (X >u 0.0) ? X : fneg(X).
2646    EVT VT = Node->getValueType(0);
2647    Tmp1 = Node->getOperand(0);
2648    Tmp2 = DAG.getConstantFP(0.0, VT);
2649    Tmp2 = DAG.getSetCC(dl, TLI.getSetCCResultType(Tmp1.getValueType()),
2650                        Tmp1, Tmp2, ISD::SETUGT);
2651    Tmp3 = DAG.getNode(ISD::FNEG, dl, VT, Tmp1);
2652    Tmp1 = DAG.getNode(ISD::SELECT, dl, VT, Tmp2, Tmp1, Tmp3);
2653    Results.push_back(Tmp1);
2654    break;
2655  }
2656  case ISD::FSQRT:
2657    Results.push_back(ExpandFPLibCall(Node, RTLIB::SQRT_F32, RTLIB::SQRT_F64,
2658                                      RTLIB::SQRT_F80, RTLIB::SQRT_PPCF128));
2659    break;
2660  case ISD::FSIN:
2661    Results.push_back(ExpandFPLibCall(Node, RTLIB::SIN_F32, RTLIB::SIN_F64,
2662                                      RTLIB::SIN_F80, RTLIB::SIN_PPCF128));
2663    break;
2664  case ISD::FCOS:
2665    Results.push_back(ExpandFPLibCall(Node, RTLIB::COS_F32, RTLIB::COS_F64,
2666                                      RTLIB::COS_F80, RTLIB::COS_PPCF128));
2667    break;
2668  case ISD::FLOG:
2669    Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG_F32, RTLIB::LOG_F64,
2670                                      RTLIB::LOG_F80, RTLIB::LOG_PPCF128));
2671    break;
2672  case ISD::FLOG2:
2673    Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG2_F32, RTLIB::LOG2_F64,
2674                                      RTLIB::LOG2_F80, RTLIB::LOG2_PPCF128));
2675    break;
2676  case ISD::FLOG10:
2677    Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG10_F32, RTLIB::LOG10_F64,
2678                                      RTLIB::LOG10_F80, RTLIB::LOG10_PPCF128));
2679    break;
2680  case ISD::FEXP:
2681    Results.push_back(ExpandFPLibCall(Node, RTLIB::EXP_F32, RTLIB::EXP_F64,
2682                                      RTLIB::EXP_F80, RTLIB::EXP_PPCF128));
2683    break;
2684  case ISD::FEXP2:
2685    Results.push_back(ExpandFPLibCall(Node, RTLIB::EXP2_F32, RTLIB::EXP2_F64,
2686                                      RTLIB::EXP2_F80, RTLIB::EXP2_PPCF128));
2687    break;
2688  case ISD::FTRUNC:
2689    Results.push_back(ExpandFPLibCall(Node, RTLIB::TRUNC_F32, RTLIB::TRUNC_F64,
2690                                      RTLIB::TRUNC_F80, RTLIB::TRUNC_PPCF128));
2691    break;
2692  case ISD::FFLOOR:
2693    Results.push_back(ExpandFPLibCall(Node, RTLIB::FLOOR_F32, RTLIB::FLOOR_F64,
2694                                      RTLIB::FLOOR_F80, RTLIB::FLOOR_PPCF128));
2695    break;
2696  case ISD::FCEIL:
2697    Results.push_back(ExpandFPLibCall(Node, RTLIB::CEIL_F32, RTLIB::CEIL_F64,
2698                                      RTLIB::CEIL_F80, RTLIB::CEIL_PPCF128));
2699    break;
2700  case ISD::FRINT:
2701    Results.push_back(ExpandFPLibCall(Node, RTLIB::RINT_F32, RTLIB::RINT_F64,
2702                                      RTLIB::RINT_F80, RTLIB::RINT_PPCF128));
2703    break;
2704  case ISD::FNEARBYINT:
2705    Results.push_back(ExpandFPLibCall(Node, RTLIB::NEARBYINT_F32,
2706                                      RTLIB::NEARBYINT_F64,
2707                                      RTLIB::NEARBYINT_F80,
2708                                      RTLIB::NEARBYINT_PPCF128));
2709    break;
2710  case ISD::FPOWI:
2711    Results.push_back(ExpandFPLibCall(Node, RTLIB::POWI_F32, RTLIB::POWI_F64,
2712                                      RTLIB::POWI_F80, RTLIB::POWI_PPCF128));
2713    break;
2714  case ISD::FPOW:
2715    Results.push_back(ExpandFPLibCall(Node, RTLIB::POW_F32, RTLIB::POW_F64,
2716                                      RTLIB::POW_F80, RTLIB::POW_PPCF128));
2717    break;
2718  case ISD::FDIV:
2719    Results.push_back(ExpandFPLibCall(Node, RTLIB::DIV_F32, RTLIB::DIV_F64,
2720                                      RTLIB::DIV_F80, RTLIB::DIV_PPCF128));
2721    break;
2722  case ISD::FREM:
2723    Results.push_back(ExpandFPLibCall(Node, RTLIB::REM_F32, RTLIB::REM_F64,
2724                                      RTLIB::REM_F80, RTLIB::REM_PPCF128));
2725    break;
2726  case ISD::FP16_TO_FP32:
2727    Results.push_back(ExpandLibCall(RTLIB::FPEXT_F16_F32, Node, false));
2728    break;
2729  case ISD::FP32_TO_FP16:
2730    Results.push_back(ExpandLibCall(RTLIB::FPROUND_F32_F16, Node, false));
2731    break;
2732  case ISD::ConstantFP: {
2733    ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Node);
2734    // Check to see if this FP immediate is already legal.
2735    // If this is a legal constant, turn it into a TargetConstantFP node.
2736    if (TLI.isFPImmLegal(CFP->getValueAPF(), Node->getValueType(0)))
2737      Results.push_back(SDValue(Node, 0));
2738    else
2739      Results.push_back(ExpandConstantFP(CFP, true, DAG, TLI));
2740    break;
2741  }
2742  case ISD::EHSELECTION: {
2743    unsigned Reg = TLI.getExceptionSelectorRegister();
2744    assert(Reg && "Can't expand to unknown register!");
2745    Results.push_back(DAG.getCopyFromReg(Node->getOperand(1), dl, Reg,
2746                                         Node->getValueType(0)));
2747    Results.push_back(Results[0].getValue(1));
2748    break;
2749  }
2750  case ISD::EXCEPTIONADDR: {
2751    unsigned Reg = TLI.getExceptionAddressRegister();
2752    assert(Reg && "Can't expand to unknown register!");
2753    Results.push_back(DAG.getCopyFromReg(Node->getOperand(0), dl, Reg,
2754                                         Node->getValueType(0)));
2755    Results.push_back(Results[0].getValue(1));
2756    break;
2757  }
2758  case ISD::SUB: {
2759    EVT VT = Node->getValueType(0);
2760    assert(TLI.isOperationLegalOrCustom(ISD::ADD, VT) &&
2761           TLI.isOperationLegalOrCustom(ISD::XOR, VT) &&
2762           "Don't know how to expand this subtraction!");
2763    Tmp1 = DAG.getNode(ISD::XOR, dl, VT, Node->getOperand(1),
2764               DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT));
2765    Tmp1 = DAG.getNode(ISD::ADD, dl, VT, Tmp2, DAG.getConstant(1, VT));
2766    Results.push_back(DAG.getNode(ISD::ADD, dl, VT, Node->getOperand(0), Tmp1));
2767    break;
2768  }
2769  case ISD::UREM:
2770  case ISD::SREM: {
2771    EVT VT = Node->getValueType(0);
2772    SDVTList VTs = DAG.getVTList(VT, VT);
2773    bool isSigned = Node->getOpcode() == ISD::SREM;
2774    unsigned DivOpc = isSigned ? ISD::SDIV : ISD::UDIV;
2775    unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
2776    Tmp2 = Node->getOperand(0);
2777    Tmp3 = Node->getOperand(1);
2778    if (TLI.isOperationLegalOrCustom(DivRemOpc, VT)) {
2779      Tmp1 = DAG.getNode(DivRemOpc, dl, VTs, Tmp2, Tmp3).getValue(1);
2780    } else if (TLI.isOperationLegalOrCustom(DivOpc, VT)) {
2781      // X % Y -> X-X/Y*Y
2782      Tmp1 = DAG.getNode(DivOpc, dl, VT, Tmp2, Tmp3);
2783      Tmp1 = DAG.getNode(ISD::MUL, dl, VT, Tmp1, Tmp3);
2784      Tmp1 = DAG.getNode(ISD::SUB, dl, VT, Tmp2, Tmp1);
2785    } else if (isSigned) {
2786      Tmp1 = ExpandIntLibCall(Node, true,
2787                              RTLIB::SREM_I8,
2788                              RTLIB::SREM_I16, RTLIB::SREM_I32,
2789                              RTLIB::SREM_I64, RTLIB::SREM_I128);
2790    } else {
2791      Tmp1 = ExpandIntLibCall(Node, false,
2792                              RTLIB::UREM_I8,
2793                              RTLIB::UREM_I16, RTLIB::UREM_I32,
2794                              RTLIB::UREM_I64, RTLIB::UREM_I128);
2795    }
2796    Results.push_back(Tmp1);
2797    break;
2798  }
2799  case ISD::UDIV:
2800  case ISD::SDIV: {
2801    bool isSigned = Node->getOpcode() == ISD::SDIV;
2802    unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
2803    EVT VT = Node->getValueType(0);
2804    SDVTList VTs = DAG.getVTList(VT, VT);
2805    if (TLI.isOperationLegalOrCustom(DivRemOpc, VT))
2806      Tmp1 = DAG.getNode(DivRemOpc, dl, VTs, Node->getOperand(0),
2807                         Node->getOperand(1));
2808    else if (isSigned)
2809      Tmp1 = ExpandIntLibCall(Node, true,
2810                              RTLIB::SDIV_I8,
2811                              RTLIB::SDIV_I16, RTLIB::SDIV_I32,
2812                              RTLIB::SDIV_I64, RTLIB::SDIV_I128);
2813    else
2814      Tmp1 = ExpandIntLibCall(Node, false,
2815                              RTLIB::UDIV_I8,
2816                              RTLIB::UDIV_I16, RTLIB::UDIV_I32,
2817                              RTLIB::UDIV_I64, RTLIB::UDIV_I128);
2818    Results.push_back(Tmp1);
2819    break;
2820  }
2821  case ISD::MULHU:
2822  case ISD::MULHS: {
2823    unsigned ExpandOpcode = Node->getOpcode() == ISD::MULHU ? ISD::UMUL_LOHI :
2824                                                              ISD::SMUL_LOHI;
2825    EVT VT = Node->getValueType(0);
2826    SDVTList VTs = DAG.getVTList(VT, VT);
2827    assert(TLI.isOperationLegalOrCustom(ExpandOpcode, VT) &&
2828           "If this wasn't legal, it shouldn't have been created!");
2829    Tmp1 = DAG.getNode(ExpandOpcode, dl, VTs, Node->getOperand(0),
2830                       Node->getOperand(1));
2831    Results.push_back(Tmp1.getValue(1));
2832    break;
2833  }
2834  case ISD::MUL: {
2835    EVT VT = Node->getValueType(0);
2836    SDVTList VTs = DAG.getVTList(VT, VT);
2837    // See if multiply or divide can be lowered using two-result operations.
2838    // We just need the low half of the multiply; try both the signed
2839    // and unsigned forms. If the target supports both SMUL_LOHI and
2840    // UMUL_LOHI, form a preference by checking which forms of plain
2841    // MULH it supports.
2842    bool HasSMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::SMUL_LOHI, VT);
2843    bool HasUMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::UMUL_LOHI, VT);
2844    bool HasMULHS = TLI.isOperationLegalOrCustom(ISD::MULHS, VT);
2845    bool HasMULHU = TLI.isOperationLegalOrCustom(ISD::MULHU, VT);
2846    unsigned OpToUse = 0;
2847    if (HasSMUL_LOHI && !HasMULHS) {
2848      OpToUse = ISD::SMUL_LOHI;
2849    } else if (HasUMUL_LOHI && !HasMULHU) {
2850      OpToUse = ISD::UMUL_LOHI;
2851    } else if (HasSMUL_LOHI) {
2852      OpToUse = ISD::SMUL_LOHI;
2853    } else if (HasUMUL_LOHI) {
2854      OpToUse = ISD::UMUL_LOHI;
2855    }
2856    if (OpToUse) {
2857      Results.push_back(DAG.getNode(OpToUse, dl, VTs, Node->getOperand(0),
2858                                    Node->getOperand(1)));
2859      break;
2860    }
2861    Tmp1 = ExpandIntLibCall(Node, false,
2862                            RTLIB::MUL_I8,
2863                            RTLIB::MUL_I16, RTLIB::MUL_I32,
2864                            RTLIB::MUL_I64, RTLIB::MUL_I128);
2865    Results.push_back(Tmp1);
2866    break;
2867  }
2868  case ISD::SADDO:
2869  case ISD::SSUBO: {
2870    SDValue LHS = Node->getOperand(0);
2871    SDValue RHS = Node->getOperand(1);
2872    SDValue Sum = DAG.getNode(Node->getOpcode() == ISD::SADDO ?
2873                              ISD::ADD : ISD::SUB, dl, LHS.getValueType(),
2874                              LHS, RHS);
2875    Results.push_back(Sum);
2876    EVT OType = Node->getValueType(1);
2877
2878    SDValue Zero = DAG.getConstant(0, LHS.getValueType());
2879
2880    //   LHSSign -> LHS >= 0
2881    //   RHSSign -> RHS >= 0
2882    //   SumSign -> Sum >= 0
2883    //
2884    //   Add:
2885    //   Overflow -> (LHSSign == RHSSign) && (LHSSign != SumSign)
2886    //   Sub:
2887    //   Overflow -> (LHSSign != RHSSign) && (LHSSign != SumSign)
2888    //
2889    SDValue LHSSign = DAG.getSetCC(dl, OType, LHS, Zero, ISD::SETGE);
2890    SDValue RHSSign = DAG.getSetCC(dl, OType, RHS, Zero, ISD::SETGE);
2891    SDValue SignsMatch = DAG.getSetCC(dl, OType, LHSSign, RHSSign,
2892                                      Node->getOpcode() == ISD::SADDO ?
2893                                      ISD::SETEQ : ISD::SETNE);
2894
2895    SDValue SumSign = DAG.getSetCC(dl, OType, Sum, Zero, ISD::SETGE);
2896    SDValue SumSignNE = DAG.getSetCC(dl, OType, LHSSign, SumSign, ISD::SETNE);
2897
2898    SDValue Cmp = DAG.getNode(ISD::AND, dl, OType, SignsMatch, SumSignNE);
2899    Results.push_back(Cmp);
2900    break;
2901  }
2902  case ISD::UADDO:
2903  case ISD::USUBO: {
2904    SDValue LHS = Node->getOperand(0);
2905    SDValue RHS = Node->getOperand(1);
2906    SDValue Sum = DAG.getNode(Node->getOpcode() == ISD::UADDO ?
2907                              ISD::ADD : ISD::SUB, dl, LHS.getValueType(),
2908                              LHS, RHS);
2909    Results.push_back(Sum);
2910    Results.push_back(DAG.getSetCC(dl, Node->getValueType(1), Sum, LHS,
2911                                   Node->getOpcode () == ISD::UADDO ?
2912                                   ISD::SETULT : ISD::SETUGT));
2913    break;
2914  }
2915  case ISD::UMULO:
2916  case ISD::SMULO: {
2917    EVT VT = Node->getValueType(0);
2918    SDValue LHS = Node->getOperand(0);
2919    SDValue RHS = Node->getOperand(1);
2920    SDValue BottomHalf;
2921    SDValue TopHalf;
2922    static const unsigned Ops[2][3] =
2923        { { ISD::MULHU, ISD::UMUL_LOHI, ISD::ZERO_EXTEND },
2924          { ISD::MULHS, ISD::SMUL_LOHI, ISD::SIGN_EXTEND }};
2925    bool isSigned = Node->getOpcode() == ISD::SMULO;
2926    if (TLI.isOperationLegalOrCustom(Ops[isSigned][0], VT)) {
2927      BottomHalf = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
2928      TopHalf = DAG.getNode(Ops[isSigned][0], dl, VT, LHS, RHS);
2929    } else if (TLI.isOperationLegalOrCustom(Ops[isSigned][1], VT)) {
2930      BottomHalf = DAG.getNode(Ops[isSigned][1], dl, DAG.getVTList(VT, VT), LHS,
2931                               RHS);
2932      TopHalf = BottomHalf.getValue(1);
2933    } else {
2934      // FIXME: We should be able to fall back to a libcall with an illegal
2935      // type in some cases.
2936      // Also, we can fall back to a division in some cases, but that's a big
2937      // performance hit in the general case.
2938      assert(TLI.isTypeLegal(EVT::getIntegerVT(*DAG.getContext(),
2939                                               VT.getSizeInBits() * 2)) &&
2940             "Don't know how to expand this operation yet!");
2941      EVT WideVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits() * 2);
2942      LHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, LHS);
2943      RHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, RHS);
2944      Tmp1 = DAG.getNode(ISD::MUL, dl, WideVT, LHS, RHS);
2945      BottomHalf = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VT, Tmp1,
2946                               DAG.getIntPtrConstant(0));
2947      TopHalf = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VT, Tmp1,
2948                            DAG.getIntPtrConstant(1));
2949    }
2950    if (isSigned) {
2951      Tmp1 = DAG.getConstant(VT.getSizeInBits() - 1, TLI.getShiftAmountTy());
2952      Tmp1 = DAG.getNode(ISD::SRA, dl, VT, BottomHalf, Tmp1);
2953      TopHalf = DAG.getSetCC(dl, TLI.getSetCCResultType(VT), TopHalf, Tmp1,
2954                             ISD::SETNE);
2955    } else {
2956      TopHalf = DAG.getSetCC(dl, TLI.getSetCCResultType(VT), TopHalf,
2957                             DAG.getConstant(0, VT), ISD::SETNE);
2958    }
2959    Results.push_back(BottomHalf);
2960    Results.push_back(TopHalf);
2961    break;
2962  }
2963  case ISD::BUILD_PAIR: {
2964    EVT PairTy = Node->getValueType(0);
2965    Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, PairTy, Node->getOperand(0));
2966    Tmp2 = DAG.getNode(ISD::ANY_EXTEND, dl, PairTy, Node->getOperand(1));
2967    Tmp2 = DAG.getNode(ISD::SHL, dl, PairTy, Tmp2,
2968                       DAG.getConstant(PairTy.getSizeInBits()/2,
2969                                       TLI.getShiftAmountTy()));
2970    Results.push_back(DAG.getNode(ISD::OR, dl, PairTy, Tmp1, Tmp2));
2971    break;
2972  }
2973  case ISD::SELECT:
2974    Tmp1 = Node->getOperand(0);
2975    Tmp2 = Node->getOperand(1);
2976    Tmp3 = Node->getOperand(2);
2977    if (Tmp1.getOpcode() == ISD::SETCC) {
2978      Tmp1 = DAG.getSelectCC(dl, Tmp1.getOperand(0), Tmp1.getOperand(1),
2979                             Tmp2, Tmp3,
2980                             cast<CondCodeSDNode>(Tmp1.getOperand(2))->get());
2981    } else {
2982      Tmp1 = DAG.getSelectCC(dl, Tmp1,
2983                             DAG.getConstant(0, Tmp1.getValueType()),
2984                             Tmp2, Tmp3, ISD::SETNE);
2985    }
2986    Results.push_back(Tmp1);
2987    break;
2988  case ISD::BR_JT: {
2989    SDValue Chain = Node->getOperand(0);
2990    SDValue Table = Node->getOperand(1);
2991    SDValue Index = Node->getOperand(2);
2992
2993    EVT PTy = TLI.getPointerTy();
2994
2995    const TargetData &TD = *TLI.getTargetData();
2996    unsigned EntrySize =
2997      DAG.getMachineFunction().getJumpTableInfo()->getEntrySize(TD);
2998
2999    Index = DAG.getNode(ISD::MUL, dl, PTy,
3000                        Index, DAG.getConstant(EntrySize, PTy));
3001    SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3002
3003    EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), EntrySize * 8);
3004    SDValue LD = DAG.getExtLoad(ISD::SEXTLOAD, dl, PTy, Chain, Addr,
3005                                PseudoSourceValue::getJumpTable(), 0, MemVT,
3006                                false, false, 0);
3007    Addr = LD;
3008    if (TM.getRelocationModel() == Reloc::PIC_) {
3009      // For PIC, the sequence is:
3010      // BRIND(load(Jumptable + index) + RelocBase)
3011      // RelocBase can be JumpTable, GOT or some sort of global base.
3012      Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr,
3013                          TLI.getPICJumpTableRelocBase(Table, DAG));
3014    }
3015    Tmp1 = DAG.getNode(ISD::BRIND, dl, MVT::Other, LD.getValue(1), Addr);
3016    Results.push_back(Tmp1);
3017    break;
3018  }
3019  case ISD::BRCOND:
3020    // Expand brcond's setcc into its constituent parts and create a BR_CC
3021    // Node.
3022    Tmp1 = Node->getOperand(0);
3023    Tmp2 = Node->getOperand(1);
3024    if (Tmp2.getOpcode() == ISD::SETCC) {
3025      Tmp1 = DAG.getNode(ISD::BR_CC, dl, MVT::Other,
3026                         Tmp1, Tmp2.getOperand(2),
3027                         Tmp2.getOperand(0), Tmp2.getOperand(1),
3028                         Node->getOperand(2));
3029    } else {
3030      Tmp1 = DAG.getNode(ISD::BR_CC, dl, MVT::Other, Tmp1,
3031                         DAG.getCondCode(ISD::SETNE), Tmp2,
3032                         DAG.getConstant(0, Tmp2.getValueType()),
3033                         Node->getOperand(2));
3034    }
3035    Results.push_back(Tmp1);
3036    break;
3037  case ISD::SETCC: {
3038    Tmp1 = Node->getOperand(0);
3039    Tmp2 = Node->getOperand(1);
3040    Tmp3 = Node->getOperand(2);
3041    LegalizeSetCCCondCode(Node->getValueType(0), Tmp1, Tmp2, Tmp3, dl);
3042
3043    // If we expanded the SETCC into an AND/OR, return the new node
3044    if (Tmp2.getNode() == 0) {
3045      Results.push_back(Tmp1);
3046      break;
3047    }
3048
3049    // Otherwise, SETCC for the given comparison type must be completely
3050    // illegal; expand it into a SELECT_CC.
3051    EVT VT = Node->getValueType(0);
3052    Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, VT, Tmp1, Tmp2,
3053                       DAG.getConstant(1, VT), DAG.getConstant(0, VT), Tmp3);
3054    Results.push_back(Tmp1);
3055    break;
3056  }
3057  case ISD::SELECT_CC: {
3058    Tmp1 = Node->getOperand(0);   // LHS
3059    Tmp2 = Node->getOperand(1);   // RHS
3060    Tmp3 = Node->getOperand(2);   // True
3061    Tmp4 = Node->getOperand(3);   // False
3062    SDValue CC = Node->getOperand(4);
3063
3064    LegalizeSetCCCondCode(TLI.getSetCCResultType(Tmp1.getValueType()),
3065                          Tmp1, Tmp2, CC, dl);
3066
3067    assert(!Tmp2.getNode() && "Can't legalize SELECT_CC with legal condition!");
3068    Tmp2 = DAG.getConstant(0, Tmp1.getValueType());
3069    CC = DAG.getCondCode(ISD::SETNE);
3070    Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, Node->getValueType(0), Tmp1, Tmp2,
3071                       Tmp3, Tmp4, CC);
3072    Results.push_back(Tmp1);
3073    break;
3074  }
3075  case ISD::BR_CC: {
3076    Tmp1 = Node->getOperand(0);              // Chain
3077    Tmp2 = Node->getOperand(2);              // LHS
3078    Tmp3 = Node->getOperand(3);              // RHS
3079    Tmp4 = Node->getOperand(1);              // CC
3080
3081    LegalizeSetCCCondCode(TLI.getSetCCResultType(Tmp2.getValueType()),
3082                          Tmp2, Tmp3, Tmp4, dl);
3083    LastCALLSEQ_END = DAG.getEntryNode();
3084
3085    assert(!Tmp3.getNode() && "Can't legalize BR_CC with legal condition!");
3086    Tmp3 = DAG.getConstant(0, Tmp2.getValueType());
3087    Tmp4 = DAG.getCondCode(ISD::SETNE);
3088    Tmp1 = DAG.getNode(ISD::BR_CC, dl, Node->getValueType(0), Tmp1, Tmp4, Tmp2,
3089                       Tmp3, Node->getOperand(4));
3090    Results.push_back(Tmp1);
3091    break;
3092  }
3093  case ISD::GLOBAL_OFFSET_TABLE:
3094  case ISD::GlobalAddress:
3095  case ISD::GlobalTLSAddress:
3096  case ISD::ExternalSymbol:
3097  case ISD::ConstantPool:
3098  case ISD::JumpTable:
3099  case ISD::INTRINSIC_W_CHAIN:
3100  case ISD::INTRINSIC_WO_CHAIN:
3101  case ISD::INTRINSIC_VOID:
3102    // FIXME: Custom lowering for these operations shouldn't return null!
3103    for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
3104      Results.push_back(SDValue(Node, i));
3105    break;
3106  }
3107}
3108void SelectionDAGLegalize::PromoteNode(SDNode *Node,
3109                                       SmallVectorImpl<SDValue> &Results) {
3110  EVT OVT = Node->getValueType(0);
3111  if (Node->getOpcode() == ISD::UINT_TO_FP ||
3112      Node->getOpcode() == ISD::SINT_TO_FP ||
3113      Node->getOpcode() == ISD::SETCC) {
3114    OVT = Node->getOperand(0).getValueType();
3115  }
3116  EVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
3117  DebugLoc dl = Node->getDebugLoc();
3118  SDValue Tmp1, Tmp2, Tmp3;
3119  switch (Node->getOpcode()) {
3120  case ISD::CTTZ:
3121  case ISD::CTLZ:
3122  case ISD::CTPOP:
3123    // Zero extend the argument.
3124    Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Node->getOperand(0));
3125    // Perform the larger operation.
3126    Tmp1 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1);
3127    if (Node->getOpcode() == ISD::CTTZ) {
3128      //if Tmp1 == sizeinbits(NVT) then Tmp1 = sizeinbits(Old VT)
3129      Tmp2 = DAG.getSetCC(dl, TLI.getSetCCResultType(NVT),
3130                          Tmp1, DAG.getConstant(NVT.getSizeInBits(), NVT),
3131                          ISD::SETEQ);
3132      Tmp1 = DAG.getNode(ISD::SELECT, dl, NVT, Tmp2,
3133                          DAG.getConstant(OVT.getSizeInBits(), NVT), Tmp1);
3134    } else if (Node->getOpcode() == ISD::CTLZ) {
3135      // Tmp1 = Tmp1 - (sizeinbits(NVT) - sizeinbits(Old VT))
3136      Tmp1 = DAG.getNode(ISD::SUB, dl, NVT, Tmp1,
3137                          DAG.getConstant(NVT.getSizeInBits() -
3138                                          OVT.getSizeInBits(), NVT));
3139    }
3140    Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp1));
3141    break;
3142  case ISD::BSWAP: {
3143    unsigned DiffBits = NVT.getSizeInBits() - OVT.getSizeInBits();
3144    Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Node->getOperand(0));
3145    Tmp1 = DAG.getNode(ISD::BSWAP, dl, NVT, Tmp1);
3146    Tmp1 = DAG.getNode(ISD::SRL, dl, NVT, Tmp1,
3147                          DAG.getConstant(DiffBits, TLI.getShiftAmountTy()));
3148    Results.push_back(Tmp1);
3149    break;
3150  }
3151  case ISD::FP_TO_UINT:
3152  case ISD::FP_TO_SINT:
3153    Tmp1 = PromoteLegalFP_TO_INT(Node->getOperand(0), Node->getValueType(0),
3154                                 Node->getOpcode() == ISD::FP_TO_SINT, dl);
3155    Results.push_back(Tmp1);
3156    break;
3157  case ISD::UINT_TO_FP:
3158  case ISD::SINT_TO_FP:
3159    Tmp1 = PromoteLegalINT_TO_FP(Node->getOperand(0), Node->getValueType(0),
3160                                 Node->getOpcode() == ISD::SINT_TO_FP, dl);
3161    Results.push_back(Tmp1);
3162    break;
3163  case ISD::AND:
3164  case ISD::OR:
3165  case ISD::XOR: {
3166    unsigned ExtOp, TruncOp;
3167    if (OVT.isVector()) {
3168      ExtOp   = ISD::BIT_CONVERT;
3169      TruncOp = ISD::BIT_CONVERT;
3170    } else {
3171      assert(OVT.isInteger() && "Cannot promote logic operation");
3172      ExtOp   = ISD::ANY_EXTEND;
3173      TruncOp = ISD::TRUNCATE;
3174    }
3175    // Promote each of the values to the new type.
3176    Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(0));
3177    Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
3178    // Perform the larger operation, then convert back
3179    Tmp1 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2);
3180    Results.push_back(DAG.getNode(TruncOp, dl, OVT, Tmp1));
3181    break;
3182  }
3183  case ISD::SELECT: {
3184    unsigned ExtOp, TruncOp;
3185    if (Node->getValueType(0).isVector()) {
3186      ExtOp   = ISD::BIT_CONVERT;
3187      TruncOp = ISD::BIT_CONVERT;
3188    } else if (Node->getValueType(0).isInteger()) {
3189      ExtOp   = ISD::ANY_EXTEND;
3190      TruncOp = ISD::TRUNCATE;
3191    } else {
3192      ExtOp   = ISD::FP_EXTEND;
3193      TruncOp = ISD::FP_ROUND;
3194    }
3195    Tmp1 = Node->getOperand(0);
3196    // Promote each of the values to the new type.
3197    Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
3198    Tmp3 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(2));
3199    // Perform the larger operation, then round down.
3200    Tmp1 = DAG.getNode(ISD::SELECT, dl, NVT, Tmp1, Tmp2, Tmp3);
3201    if (TruncOp != ISD::FP_ROUND)
3202      Tmp1 = DAG.getNode(TruncOp, dl, Node->getValueType(0), Tmp1);
3203    else
3204      Tmp1 = DAG.getNode(TruncOp, dl, Node->getValueType(0), Tmp1,
3205                         DAG.getIntPtrConstant(0));
3206    Results.push_back(Tmp1);
3207    break;
3208  }
3209  case ISD::VECTOR_SHUFFLE: {
3210    SmallVector<int, 8> Mask;
3211    cast<ShuffleVectorSDNode>(Node)->getMask(Mask);
3212
3213    // Cast the two input vectors.
3214    Tmp1 = DAG.getNode(ISD::BIT_CONVERT, dl, NVT, Node->getOperand(0));
3215    Tmp2 = DAG.getNode(ISD::BIT_CONVERT, dl, NVT, Node->getOperand(1));
3216
3217    // Convert the shuffle mask to the right # elements.
3218    Tmp1 = ShuffleWithNarrowerEltType(NVT, OVT, dl, Tmp1, Tmp2, Mask);
3219    Tmp1 = DAG.getNode(ISD::BIT_CONVERT, dl, OVT, Tmp1);
3220    Results.push_back(Tmp1);
3221    break;
3222  }
3223  case ISD::SETCC: {
3224    unsigned ExtOp = ISD::FP_EXTEND;
3225    if (NVT.isInteger()) {
3226      ISD::CondCode CCCode =
3227        cast<CondCodeSDNode>(Node->getOperand(2))->get();
3228      ExtOp = isSignedIntSetCC(CCCode) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
3229    }
3230    Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(0));
3231    Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
3232    Results.push_back(DAG.getNode(ISD::SETCC, dl, Node->getValueType(0),
3233                                  Tmp1, Tmp2, Node->getOperand(2)));
3234    break;
3235  }
3236  }
3237}
3238
3239// SelectionDAG::Legalize - This is the entry point for the file.
3240//
3241void SelectionDAG::Legalize(CodeGenOpt::Level OptLevel) {
3242  /// run - This is the main entry point to this class.
3243  ///
3244  SelectionDAGLegalize(*this, OptLevel).LegalizeDAG();
3245}
3246
3247