LegalizeDAG.cpp revision 193574
1193323Sed//===-- LegalizeDAG.cpp - Implement SelectionDAG::Legalize ----------------===//
2193323Sed//
3193323Sed//                     The LLVM Compiler Infrastructure
4193323Sed//
5193323Sed// This file is distributed under the University of Illinois Open Source
6193323Sed// License. See LICENSE.TXT for details.
7193323Sed//
8193323Sed//===----------------------------------------------------------------------===//
9193323Sed//
10193323Sed// This file implements the SelectionDAG::Legalize method.
11193323Sed//
12193323Sed//===----------------------------------------------------------------------===//
13193323Sed
14193323Sed#include "llvm/CodeGen/SelectionDAG.h"
15193323Sed#include "llvm/CodeGen/MachineFunction.h"
16193323Sed#include "llvm/CodeGen/MachineFrameInfo.h"
17193323Sed#include "llvm/CodeGen/MachineJumpTableInfo.h"
18193323Sed#include "llvm/CodeGen/MachineModuleInfo.h"
19193323Sed#include "llvm/CodeGen/DwarfWriter.h"
20193323Sed#include "llvm/Analysis/DebugInfo.h"
21193323Sed#include "llvm/CodeGen/PseudoSourceValue.h"
22193323Sed#include "llvm/Target/TargetFrameInfo.h"
23193323Sed#include "llvm/Target/TargetLowering.h"
24193323Sed#include "llvm/Target/TargetData.h"
25193323Sed#include "llvm/Target/TargetMachine.h"
26193323Sed#include "llvm/Target/TargetOptions.h"
27193323Sed#include "llvm/Target/TargetSubtarget.h"
28193323Sed#include "llvm/CallingConv.h"
29193323Sed#include "llvm/Constants.h"
30193323Sed#include "llvm/DerivedTypes.h"
31193323Sed#include "llvm/Function.h"
32193323Sed#include "llvm/GlobalVariable.h"
33193323Sed#include "llvm/Support/CommandLine.h"
34193323Sed#include "llvm/Support/Compiler.h"
35193323Sed#include "llvm/Support/MathExtras.h"
36193323Sed#include "llvm/ADT/DenseMap.h"
37193323Sed#include "llvm/ADT/SmallVector.h"
38193323Sed#include "llvm/ADT/SmallPtrSet.h"
39193323Sed#include <map>
40193323Sedusing namespace llvm;
41193323Sed
42193323Sed//===----------------------------------------------------------------------===//
43193323Sed/// SelectionDAGLegalize - This takes an arbitrary SelectionDAG as input and
44193323Sed/// hacks on it until the target machine can handle it.  This involves
45193323Sed/// eliminating value sizes the machine cannot handle (promoting small sizes to
46193323Sed/// large sizes or splitting up large values into small values) as well as
47193323Sed/// eliminating operations the machine cannot handle.
48193323Sed///
49193323Sed/// This code also does a small amount of optimization and recognition of idioms
50193323Sed/// as part of its processing.  For example, if a target does not support a
51193323Sed/// 'setcc' instruction efficiently, but does support 'brcc' instruction, this
52193323Sed/// will attempt merge setcc and brc instructions into brcc's.
53193323Sed///
54193323Sednamespace {
55193323Sedclass VISIBILITY_HIDDEN SelectionDAGLegalize {
56193323Sed  TargetLowering &TLI;
57193323Sed  SelectionDAG &DAG;
58193323Sed  CodeGenOpt::Level OptLevel;
59193323Sed
60193323Sed  // Libcall insertion helpers.
61193323Sed
62193323Sed  /// LastCALLSEQ_END - This keeps track of the CALLSEQ_END node that has been
63193323Sed  /// legalized.  We use this to ensure that calls are properly serialized
64193323Sed  /// against each other, including inserted libcalls.
65193323Sed  SDValue LastCALLSEQ_END;
66193323Sed
67193323Sed  /// IsLegalizingCall - This member is used *only* for purposes of providing
68193323Sed  /// helpful assertions that a libcall isn't created while another call is
69193323Sed  /// being legalized (which could lead to non-serialized call sequences).
70193323Sed  bool IsLegalizingCall;
71193323Sed
72193323Sed  enum LegalizeAction {
73193323Sed    Legal,      // The target natively supports this operation.
74193323Sed    Promote,    // This operation should be executed in a larger type.
75193323Sed    Expand      // Try to expand this to other ops, otherwise use a libcall.
76193323Sed  };
77193323Sed
78193323Sed  /// ValueTypeActions - This is a bitvector that contains two bits for each
79193323Sed  /// value type, where the two bits correspond to the LegalizeAction enum.
80193323Sed  /// This can be queried with "getTypeAction(VT)".
81193323Sed  TargetLowering::ValueTypeActionImpl ValueTypeActions;
82193323Sed
83193323Sed  /// LegalizedNodes - For nodes that are of legal width, and that have more
84193323Sed  /// than one use, this map indicates what regularized operand to use.  This
85193323Sed  /// allows us to avoid legalizing the same thing more than once.
86193323Sed  DenseMap<SDValue, SDValue> LegalizedNodes;
87193323Sed
88193323Sed  void AddLegalizedOperand(SDValue From, SDValue To) {
89193323Sed    LegalizedNodes.insert(std::make_pair(From, To));
90193323Sed    // If someone requests legalization of the new node, return itself.
91193323Sed    if (From != To)
92193323Sed      LegalizedNodes.insert(std::make_pair(To, To));
93193323Sed  }
94193323Sed
95193323Sedpublic:
96193323Sed  SelectionDAGLegalize(SelectionDAG &DAG, CodeGenOpt::Level ol);
97193323Sed
98193323Sed  /// getTypeAction - Return how we should legalize values of this type, either
99193323Sed  /// it is already legal or we need to expand it into multiple registers of
100193323Sed  /// smaller integer type, or we need to promote it to a larger type.
101193323Sed  LegalizeAction getTypeAction(MVT VT) const {
102193323Sed    return (LegalizeAction)ValueTypeActions.getTypeAction(VT);
103193323Sed  }
104193323Sed
105193323Sed  /// isTypeLegal - Return true if this type is legal on this target.
106193323Sed  ///
107193323Sed  bool isTypeLegal(MVT VT) const {
108193323Sed    return getTypeAction(VT) == Legal;
109193323Sed  }
110193323Sed
111193323Sed  void LegalizeDAG();
112193323Sed
113193323Sedprivate:
114193323Sed  /// LegalizeOp - We know that the specified value has a legal type.
115193323Sed  /// Recursively ensure that the operands have legal types, then return the
116193323Sed  /// result.
117193323Sed  SDValue LegalizeOp(SDValue O);
118193323Sed
119193574Sed  SDValue OptimizeFloatStore(StoreSDNode *ST);
120193574Sed
121193323Sed  /// PerformInsertVectorEltInMemory - Some target cannot handle a variable
122193323Sed  /// insertion index for the INSERT_VECTOR_ELT instruction.  In this case, it
123193323Sed  /// is necessary to spill the vector being inserted into to memory, perform
124193323Sed  /// the insert there, and then read the result back.
125193323Sed  SDValue PerformInsertVectorEltInMemory(SDValue Vec, SDValue Val,
126193323Sed                                         SDValue Idx, DebugLoc dl);
127193323Sed  SDValue ExpandINSERT_VECTOR_ELT(SDValue Vec, SDValue Val,
128193323Sed                                  SDValue Idx, DebugLoc dl);
129193323Sed
130193323Sed  /// ShuffleWithNarrowerEltType - Return a vector shuffle operation which
131193323Sed  /// performs the same shuffe in terms of order or result bytes, but on a type
132193323Sed  /// whose vector element type is narrower than the original shuffle type.
133193323Sed  /// e.g. <v4i32> <0, 1, 0, 1> -> v8i16 <0, 1, 2, 3, 0, 1, 2, 3>
134193323Sed  SDValue ShuffleWithNarrowerEltType(MVT NVT, MVT VT, DebugLoc dl,
135193323Sed                                     SDValue N1, SDValue N2,
136193323Sed                                     SmallVectorImpl<int> &Mask) const;
137193323Sed
138193323Sed  bool LegalizeAllNodesNotLeadingTo(SDNode *N, SDNode *Dest,
139193323Sed                                    SmallPtrSet<SDNode*, 32> &NodesLeadingTo);
140193323Sed
141193323Sed  void LegalizeSetCCCondCode(MVT VT, SDValue &LHS, SDValue &RHS, SDValue &CC,
142193323Sed                             DebugLoc dl);
143193323Sed
144193323Sed  SDValue ExpandLibCall(RTLIB::Libcall LC, SDNode *Node, bool isSigned);
145193323Sed  SDValue ExpandFPLibCall(SDNode *Node, RTLIB::Libcall Call_F32,
146193323Sed                          RTLIB::Libcall Call_F64, RTLIB::Libcall Call_F80,
147193323Sed                          RTLIB::Libcall Call_PPCF128);
148193323Sed  SDValue ExpandIntLibCall(SDNode *Node, bool isSigned, RTLIB::Libcall Call_I16,
149193323Sed                           RTLIB::Libcall Call_I32, RTLIB::Libcall Call_I64,
150193323Sed                           RTLIB::Libcall Call_I128);
151193323Sed
152193323Sed  SDValue EmitStackConvert(SDValue SrcOp, MVT SlotVT, MVT DestVT, DebugLoc dl);
153193323Sed  SDValue ExpandBUILD_VECTOR(SDNode *Node);
154193323Sed  SDValue ExpandSCALAR_TO_VECTOR(SDNode *Node);
155193323Sed  SDValue ExpandDBG_STOPPOINT(SDNode *Node);
156193323Sed  void ExpandDYNAMIC_STACKALLOC(SDNode *Node,
157193323Sed                                SmallVectorImpl<SDValue> &Results);
158193323Sed  SDValue ExpandFCOPYSIGN(SDNode *Node);
159193323Sed  SDValue ExpandLegalINT_TO_FP(bool isSigned, SDValue LegalOp, MVT DestVT,
160193323Sed                               DebugLoc dl);
161193323Sed  SDValue PromoteLegalINT_TO_FP(SDValue LegalOp, MVT DestVT, bool isSigned,
162193323Sed                                DebugLoc dl);
163193323Sed  SDValue PromoteLegalFP_TO_INT(SDValue LegalOp, MVT DestVT, bool isSigned,
164193323Sed                                DebugLoc dl);
165193323Sed
166193323Sed  SDValue ExpandBSWAP(SDValue Op, DebugLoc dl);
167193323Sed  SDValue ExpandBitCount(unsigned Opc, SDValue Op, DebugLoc dl);
168193323Sed
169193323Sed  SDValue ExpandExtractFromVectorThroughStack(SDValue Op);
170193574Sed  SDValue ExpandVectorBuildThroughStack(SDNode* Node);
171193323Sed
172193323Sed  void ExpandNode(SDNode *Node, SmallVectorImpl<SDValue> &Results);
173193323Sed  void PromoteNode(SDNode *Node, SmallVectorImpl<SDValue> &Results);
174193323Sed};
175193323Sed}
176193323Sed
177193323Sed/// ShuffleWithNarrowerEltType - Return a vector shuffle operation which
178193323Sed/// performs the same shuffe in terms of order or result bytes, but on a type
179193323Sed/// whose vector element type is narrower than the original shuffle type.
180193323Sed/// e.g. <v4i32> <0, 1, 0, 1> -> v8i16 <0, 1, 2, 3, 0, 1, 2, 3>
181193323SedSDValue
182193323SedSelectionDAGLegalize::ShuffleWithNarrowerEltType(MVT NVT, MVT VT,  DebugLoc dl,
183193323Sed                                                 SDValue N1, SDValue N2,
184193323Sed                                             SmallVectorImpl<int> &Mask) const {
185193323Sed  MVT EltVT = NVT.getVectorElementType();
186193323Sed  unsigned NumMaskElts = VT.getVectorNumElements();
187193323Sed  unsigned NumDestElts = NVT.getVectorNumElements();
188193323Sed  unsigned NumEltsGrowth = NumDestElts / NumMaskElts;
189193323Sed
190193323Sed  assert(NumEltsGrowth && "Cannot promote to vector type with fewer elts!");
191193323Sed
192193323Sed  if (NumEltsGrowth == 1)
193193323Sed    return DAG.getVectorShuffle(NVT, dl, N1, N2, &Mask[0]);
194193323Sed
195193323Sed  SmallVector<int, 8> NewMask;
196193323Sed  for (unsigned i = 0; i != NumMaskElts; ++i) {
197193323Sed    int Idx = Mask[i];
198193323Sed    for (unsigned j = 0; j != NumEltsGrowth; ++j) {
199193323Sed      if (Idx < 0)
200193323Sed        NewMask.push_back(-1);
201193323Sed      else
202193323Sed        NewMask.push_back(Idx * NumEltsGrowth + j);
203193323Sed    }
204193323Sed  }
205193323Sed  assert(NewMask.size() == NumDestElts && "Non-integer NumEltsGrowth?");
206193323Sed  assert(TLI.isShuffleMaskLegal(NewMask, NVT) && "Shuffle not legal?");
207193323Sed  return DAG.getVectorShuffle(NVT, dl, N1, N2, &NewMask[0]);
208193323Sed}
209193323Sed
210193323SedSelectionDAGLegalize::SelectionDAGLegalize(SelectionDAG &dag,
211193323Sed                                           CodeGenOpt::Level ol)
212193323Sed  : TLI(dag.getTargetLoweringInfo()), DAG(dag), OptLevel(ol),
213193323Sed    ValueTypeActions(TLI.getValueTypeActions()) {
214193323Sed  assert(MVT::LAST_VALUETYPE <= 32 &&
215193323Sed         "Too many value types for ValueTypeActions to hold!");
216193323Sed}
217193323Sed
218193323Sedvoid SelectionDAGLegalize::LegalizeDAG() {
219193323Sed  LastCALLSEQ_END = DAG.getEntryNode();
220193323Sed  IsLegalizingCall = false;
221193323Sed
222193323Sed  // The legalize process is inherently a bottom-up recursive process (users
223193323Sed  // legalize their uses before themselves).  Given infinite stack space, we
224193323Sed  // could just start legalizing on the root and traverse the whole graph.  In
225193323Sed  // practice however, this causes us to run out of stack space on large basic
226193323Sed  // blocks.  To avoid this problem, compute an ordering of the nodes where each
227193323Sed  // node is only legalized after all of its operands are legalized.
228193323Sed  DAG.AssignTopologicalOrder();
229193323Sed  for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
230193323Sed       E = prior(DAG.allnodes_end()); I != next(E); ++I)
231193323Sed    LegalizeOp(SDValue(I, 0));
232193323Sed
233193323Sed  // Finally, it's possible the root changed.  Get the new root.
234193323Sed  SDValue OldRoot = DAG.getRoot();
235193323Sed  assert(LegalizedNodes.count(OldRoot) && "Root didn't get legalized?");
236193323Sed  DAG.setRoot(LegalizedNodes[OldRoot]);
237193323Sed
238193323Sed  LegalizedNodes.clear();
239193323Sed
240193323Sed  // Remove dead nodes now.
241193323Sed  DAG.RemoveDeadNodes();
242193323Sed}
243193323Sed
244193323Sed
245193323Sed/// FindCallEndFromCallStart - Given a chained node that is part of a call
246193323Sed/// sequence, find the CALLSEQ_END node that terminates the call sequence.
247193323Sedstatic SDNode *FindCallEndFromCallStart(SDNode *Node) {
248193323Sed  if (Node->getOpcode() == ISD::CALLSEQ_END)
249193323Sed    return Node;
250193323Sed  if (Node->use_empty())
251193323Sed    return 0;   // No CallSeqEnd
252193323Sed
253193323Sed  // The chain is usually at the end.
254193323Sed  SDValue TheChain(Node, Node->getNumValues()-1);
255193323Sed  if (TheChain.getValueType() != MVT::Other) {
256193323Sed    // Sometimes it's at the beginning.
257193323Sed    TheChain = SDValue(Node, 0);
258193323Sed    if (TheChain.getValueType() != MVT::Other) {
259193323Sed      // Otherwise, hunt for it.
260193323Sed      for (unsigned i = 1, e = Node->getNumValues(); i != e; ++i)
261193323Sed        if (Node->getValueType(i) == MVT::Other) {
262193323Sed          TheChain = SDValue(Node, i);
263193323Sed          break;
264193323Sed        }
265193323Sed
266193323Sed      // Otherwise, we walked into a node without a chain.
267193323Sed      if (TheChain.getValueType() != MVT::Other)
268193323Sed        return 0;
269193323Sed    }
270193323Sed  }
271193323Sed
272193323Sed  for (SDNode::use_iterator UI = Node->use_begin(),
273193323Sed       E = Node->use_end(); UI != E; ++UI) {
274193323Sed
275193323Sed    // Make sure to only follow users of our token chain.
276193323Sed    SDNode *User = *UI;
277193323Sed    for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
278193323Sed      if (User->getOperand(i) == TheChain)
279193323Sed        if (SDNode *Result = FindCallEndFromCallStart(User))
280193323Sed          return Result;
281193323Sed  }
282193323Sed  return 0;
283193323Sed}
284193323Sed
285193323Sed/// FindCallStartFromCallEnd - Given a chained node that is part of a call
286193323Sed/// sequence, find the CALLSEQ_START node that initiates the call sequence.
287193323Sedstatic SDNode *FindCallStartFromCallEnd(SDNode *Node) {
288193323Sed  assert(Node && "Didn't find callseq_start for a call??");
289193323Sed  if (Node->getOpcode() == ISD::CALLSEQ_START) return Node;
290193323Sed
291193323Sed  assert(Node->getOperand(0).getValueType() == MVT::Other &&
292193323Sed         "Node doesn't have a token chain argument!");
293193323Sed  return FindCallStartFromCallEnd(Node->getOperand(0).getNode());
294193323Sed}
295193323Sed
296193323Sed/// LegalizeAllNodesNotLeadingTo - Recursively walk the uses of N, looking to
297193323Sed/// see if any uses can reach Dest.  If no dest operands can get to dest,
298193323Sed/// legalize them, legalize ourself, and return false, otherwise, return true.
299193323Sed///
300193323Sed/// Keep track of the nodes we fine that actually do lead to Dest in
301193323Sed/// NodesLeadingTo.  This avoids retraversing them exponential number of times.
302193323Sed///
303193323Sedbool SelectionDAGLegalize::LegalizeAllNodesNotLeadingTo(SDNode *N, SDNode *Dest,
304193323Sed                                     SmallPtrSet<SDNode*, 32> &NodesLeadingTo) {
305193323Sed  if (N == Dest) return true;  // N certainly leads to Dest :)
306193323Sed
307193323Sed  // If we've already processed this node and it does lead to Dest, there is no
308193323Sed  // need to reprocess it.
309193323Sed  if (NodesLeadingTo.count(N)) return true;
310193323Sed
311193323Sed  // If the first result of this node has been already legalized, then it cannot
312193323Sed  // reach N.
313193323Sed  if (LegalizedNodes.count(SDValue(N, 0))) return false;
314193323Sed
315193323Sed  // Okay, this node has not already been legalized.  Check and legalize all
316193323Sed  // operands.  If none lead to Dest, then we can legalize this node.
317193323Sed  bool OperandsLeadToDest = false;
318193323Sed  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
319193323Sed    OperandsLeadToDest |=     // If an operand leads to Dest, so do we.
320193323Sed      LegalizeAllNodesNotLeadingTo(N->getOperand(i).getNode(), Dest, NodesLeadingTo);
321193323Sed
322193323Sed  if (OperandsLeadToDest) {
323193323Sed    NodesLeadingTo.insert(N);
324193323Sed    return true;
325193323Sed  }
326193323Sed
327193323Sed  // Okay, this node looks safe, legalize it and return false.
328193323Sed  LegalizeOp(SDValue(N, 0));
329193323Sed  return false;
330193323Sed}
331193323Sed
332193323Sed/// ExpandConstantFP - Expands the ConstantFP node to an integer constant or
333193323Sed/// a load from the constant pool.
334193323Sedstatic SDValue ExpandConstantFP(ConstantFPSDNode *CFP, bool UseCP,
335193323Sed                                SelectionDAG &DAG, const TargetLowering &TLI) {
336193323Sed  bool Extend = false;
337193323Sed  DebugLoc dl = CFP->getDebugLoc();
338193323Sed
339193323Sed  // If a FP immediate is precise when represented as a float and if the
340193323Sed  // target can do an extending load from float to double, we put it into
341193323Sed  // the constant pool as a float, even if it's is statically typed as a
342193323Sed  // double.  This shrinks FP constants and canonicalizes them for targets where
343193323Sed  // an FP extending load is the same cost as a normal load (such as on the x87
344193323Sed  // fp stack or PPC FP unit).
345193323Sed  MVT VT = CFP->getValueType(0);
346193323Sed  ConstantFP *LLVMC = const_cast<ConstantFP*>(CFP->getConstantFPValue());
347193323Sed  if (!UseCP) {
348193323Sed    assert((VT == MVT::f64 || VT == MVT::f32) && "Invalid type expansion");
349193323Sed    return DAG.getConstant(LLVMC->getValueAPF().bitcastToAPInt(),
350193323Sed                           (VT == MVT::f64) ? MVT::i64 : MVT::i32);
351193323Sed  }
352193323Sed
353193323Sed  MVT OrigVT = VT;
354193323Sed  MVT SVT = VT;
355193323Sed  while (SVT != MVT::f32) {
356193323Sed    SVT = (MVT::SimpleValueType)(SVT.getSimpleVT() - 1);
357193323Sed    if (CFP->isValueValidForType(SVT, CFP->getValueAPF()) &&
358193323Sed        // Only do this if the target has a native EXTLOAD instruction from
359193323Sed        // smaller type.
360193323Sed        TLI.isLoadExtLegal(ISD::EXTLOAD, SVT) &&
361193323Sed        TLI.ShouldShrinkFPConstant(OrigVT)) {
362193323Sed      const Type *SType = SVT.getTypeForMVT();
363193323Sed      LLVMC = cast<ConstantFP>(ConstantExpr::getFPTrunc(LLVMC, SType));
364193323Sed      VT = SVT;
365193323Sed      Extend = true;
366193323Sed    }
367193323Sed  }
368193323Sed
369193323Sed  SDValue CPIdx = DAG.getConstantPool(LLVMC, TLI.getPointerTy());
370193323Sed  unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
371193323Sed  if (Extend)
372193323Sed    return DAG.getExtLoad(ISD::EXTLOAD, dl,
373193323Sed                          OrigVT, DAG.getEntryNode(),
374193323Sed                          CPIdx, PseudoSourceValue::getConstantPool(),
375193323Sed                          0, VT, false, Alignment);
376193323Sed  return DAG.getLoad(OrigVT, dl, DAG.getEntryNode(), CPIdx,
377193323Sed                     PseudoSourceValue::getConstantPool(), 0, false, Alignment);
378193323Sed}
379193323Sed
380193323Sed/// ExpandUnalignedStore - Expands an unaligned store to 2 half-size stores.
381193323Sedstatic
382193323SedSDValue ExpandUnalignedStore(StoreSDNode *ST, SelectionDAG &DAG,
383193323Sed                             const TargetLowering &TLI) {
384193323Sed  SDValue Chain = ST->getChain();
385193323Sed  SDValue Ptr = ST->getBasePtr();
386193323Sed  SDValue Val = ST->getValue();
387193323Sed  MVT VT = Val.getValueType();
388193323Sed  int Alignment = ST->getAlignment();
389193323Sed  int SVOffset = ST->getSrcValueOffset();
390193323Sed  DebugLoc dl = ST->getDebugLoc();
391193323Sed  if (ST->getMemoryVT().isFloatingPoint() ||
392193323Sed      ST->getMemoryVT().isVector()) {
393193323Sed    MVT intVT = MVT::getIntegerVT(VT.getSizeInBits());
394193323Sed    if (TLI.isTypeLegal(intVT)) {
395193323Sed      // Expand to a bitconvert of the value to the integer type of the
396193323Sed      // same size, then a (misaligned) int store.
397193323Sed      // FIXME: Does not handle truncating floating point stores!
398193323Sed      SDValue Result = DAG.getNode(ISD::BIT_CONVERT, dl, intVT, Val);
399193323Sed      return DAG.getStore(Chain, dl, Result, Ptr, ST->getSrcValue(),
400193323Sed                          SVOffset, ST->isVolatile(), Alignment);
401193323Sed    } else {
402193323Sed      // Do a (aligned) store to a stack slot, then copy from the stack slot
403193323Sed      // to the final destination using (unaligned) integer loads and stores.
404193323Sed      MVT StoredVT = ST->getMemoryVT();
405193323Sed      MVT RegVT =
406193323Sed        TLI.getRegisterType(MVT::getIntegerVT(StoredVT.getSizeInBits()));
407193323Sed      unsigned StoredBytes = StoredVT.getSizeInBits() / 8;
408193323Sed      unsigned RegBytes = RegVT.getSizeInBits() / 8;
409193323Sed      unsigned NumRegs = (StoredBytes + RegBytes - 1) / RegBytes;
410193323Sed
411193323Sed      // Make sure the stack slot is also aligned for the register type.
412193323Sed      SDValue StackPtr = DAG.CreateStackTemporary(StoredVT, RegVT);
413193323Sed
414193323Sed      // Perform the original store, only redirected to the stack slot.
415193323Sed      SDValue Store = DAG.getTruncStore(Chain, dl,
416193323Sed                                        Val, StackPtr, NULL, 0, StoredVT);
417193323Sed      SDValue Increment = DAG.getConstant(RegBytes, TLI.getPointerTy());
418193323Sed      SmallVector<SDValue, 8> Stores;
419193323Sed      unsigned Offset = 0;
420193323Sed
421193323Sed      // Do all but one copies using the full register width.
422193323Sed      for (unsigned i = 1; i < NumRegs; i++) {
423193323Sed        // Load one integer register's worth from the stack slot.
424193323Sed        SDValue Load = DAG.getLoad(RegVT, dl, Store, StackPtr, NULL, 0);
425193323Sed        // Store it to the final location.  Remember the store.
426193323Sed        Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, Ptr,
427193323Sed                                      ST->getSrcValue(), SVOffset + Offset,
428193323Sed                                      ST->isVolatile(),
429193323Sed                                      MinAlign(ST->getAlignment(), Offset)));
430193323Sed        // Increment the pointers.
431193323Sed        Offset += RegBytes;
432193323Sed        StackPtr = DAG.getNode(ISD::ADD, dl, StackPtr.getValueType(), StackPtr,
433193323Sed                               Increment);
434193323Sed        Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
435193323Sed      }
436193323Sed
437193323Sed      // The last store may be partial.  Do a truncating store.  On big-endian
438193323Sed      // machines this requires an extending load from the stack slot to ensure
439193323Sed      // that the bits are in the right place.
440193323Sed      MVT MemVT = MVT::getIntegerVT(8 * (StoredBytes - Offset));
441193323Sed
442193323Sed      // Load from the stack slot.
443193323Sed      SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Store, StackPtr,
444193323Sed                                    NULL, 0, MemVT);
445193323Sed
446193323Sed      Stores.push_back(DAG.getTruncStore(Load.getValue(1), dl, Load, Ptr,
447193323Sed                                         ST->getSrcValue(), SVOffset + Offset,
448193323Sed                                         MemVT, ST->isVolatile(),
449193323Sed                                         MinAlign(ST->getAlignment(), Offset)));
450193323Sed      // The order of the stores doesn't matter - say it with a TokenFactor.
451193323Sed      return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Stores[0],
452193323Sed                         Stores.size());
453193323Sed    }
454193323Sed  }
455193323Sed  assert(ST->getMemoryVT().isInteger() &&
456193323Sed         !ST->getMemoryVT().isVector() &&
457193323Sed         "Unaligned store of unknown type.");
458193323Sed  // Get the half-size VT
459193323Sed  MVT NewStoredVT =
460193323Sed    (MVT::SimpleValueType)(ST->getMemoryVT().getSimpleVT() - 1);
461193323Sed  int NumBits = NewStoredVT.getSizeInBits();
462193323Sed  int IncrementSize = NumBits / 8;
463193323Sed
464193323Sed  // Divide the stored value in two parts.
465193323Sed  SDValue ShiftAmount = DAG.getConstant(NumBits, TLI.getShiftAmountTy());
466193323Sed  SDValue Lo = Val;
467193323Sed  SDValue Hi = DAG.getNode(ISD::SRL, dl, VT, Val, ShiftAmount);
468193323Sed
469193323Sed  // Store the two parts
470193323Sed  SDValue Store1, Store2;
471193323Sed  Store1 = DAG.getTruncStore(Chain, dl, TLI.isLittleEndian()?Lo:Hi, Ptr,
472193323Sed                             ST->getSrcValue(), SVOffset, NewStoredVT,
473193323Sed                             ST->isVolatile(), Alignment);
474193323Sed  Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
475193323Sed                    DAG.getConstant(IncrementSize, TLI.getPointerTy()));
476193323Sed  Alignment = MinAlign(Alignment, IncrementSize);
477193323Sed  Store2 = DAG.getTruncStore(Chain, dl, TLI.isLittleEndian()?Hi:Lo, Ptr,
478193323Sed                             ST->getSrcValue(), SVOffset + IncrementSize,
479193323Sed                             NewStoredVT, ST->isVolatile(), Alignment);
480193323Sed
481193323Sed  return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2);
482193323Sed}
483193323Sed
484193323Sed/// ExpandUnalignedLoad - Expands an unaligned load to 2 half-size loads.
485193323Sedstatic
486193323SedSDValue ExpandUnalignedLoad(LoadSDNode *LD, SelectionDAG &DAG,
487193323Sed                            const TargetLowering &TLI) {
488193323Sed  int SVOffset = LD->getSrcValueOffset();
489193323Sed  SDValue Chain = LD->getChain();
490193323Sed  SDValue Ptr = LD->getBasePtr();
491193323Sed  MVT VT = LD->getValueType(0);
492193323Sed  MVT LoadedVT = LD->getMemoryVT();
493193323Sed  DebugLoc dl = LD->getDebugLoc();
494193323Sed  if (VT.isFloatingPoint() || VT.isVector()) {
495193323Sed    MVT intVT = MVT::getIntegerVT(LoadedVT.getSizeInBits());
496193323Sed    if (TLI.isTypeLegal(intVT)) {
497193323Sed      // Expand to a (misaligned) integer load of the same size,
498193323Sed      // then bitconvert to floating point or vector.
499193323Sed      SDValue newLoad = DAG.getLoad(intVT, dl, Chain, Ptr, LD->getSrcValue(),
500193323Sed                                    SVOffset, LD->isVolatile(),
501193323Sed                                    LD->getAlignment());
502193323Sed      SDValue Result = DAG.getNode(ISD::BIT_CONVERT, dl, LoadedVT, newLoad);
503193323Sed      if (VT.isFloatingPoint() && LoadedVT != VT)
504193323Sed        Result = DAG.getNode(ISD::FP_EXTEND, dl, VT, Result);
505193323Sed
506193323Sed      SDValue Ops[] = { Result, Chain };
507193323Sed      return DAG.getMergeValues(Ops, 2, dl);
508193323Sed    } else {
509193323Sed      // Copy the value to a (aligned) stack slot using (unaligned) integer
510193323Sed      // loads and stores, then do a (aligned) load from the stack slot.
511193323Sed      MVT RegVT = TLI.getRegisterType(intVT);
512193323Sed      unsigned LoadedBytes = LoadedVT.getSizeInBits() / 8;
513193323Sed      unsigned RegBytes = RegVT.getSizeInBits() / 8;
514193323Sed      unsigned NumRegs = (LoadedBytes + RegBytes - 1) / RegBytes;
515193323Sed
516193323Sed      // Make sure the stack slot is also aligned for the register type.
517193323Sed      SDValue StackBase = DAG.CreateStackTemporary(LoadedVT, RegVT);
518193323Sed
519193323Sed      SDValue Increment = DAG.getConstant(RegBytes, TLI.getPointerTy());
520193323Sed      SmallVector<SDValue, 8> Stores;
521193323Sed      SDValue StackPtr = StackBase;
522193323Sed      unsigned Offset = 0;
523193323Sed
524193323Sed      // Do all but one copies using the full register width.
525193323Sed      for (unsigned i = 1; i < NumRegs; i++) {
526193323Sed        // Load one integer register's worth from the original location.
527193323Sed        SDValue Load = DAG.getLoad(RegVT, dl, Chain, Ptr, LD->getSrcValue(),
528193323Sed                                   SVOffset + Offset, LD->isVolatile(),
529193323Sed                                   MinAlign(LD->getAlignment(), Offset));
530193323Sed        // Follow the load with a store to the stack slot.  Remember the store.
531193323Sed        Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, StackPtr,
532193323Sed                                      NULL, 0));
533193323Sed        // Increment the pointers.
534193323Sed        Offset += RegBytes;
535193323Sed        Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
536193323Sed        StackPtr = DAG.getNode(ISD::ADD, dl, StackPtr.getValueType(), StackPtr,
537193323Sed                               Increment);
538193323Sed      }
539193323Sed
540193323Sed      // The last copy may be partial.  Do an extending load.
541193323Sed      MVT MemVT = MVT::getIntegerVT(8 * (LoadedBytes - Offset));
542193323Sed      SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Chain, Ptr,
543193323Sed                                    LD->getSrcValue(), SVOffset + Offset,
544193323Sed                                    MemVT, LD->isVolatile(),
545193323Sed                                    MinAlign(LD->getAlignment(), Offset));
546193323Sed      // Follow the load with a store to the stack slot.  Remember the store.
547193323Sed      // On big-endian machines this requires a truncating store to ensure
548193323Sed      // that the bits end up in the right place.
549193323Sed      Stores.push_back(DAG.getTruncStore(Load.getValue(1), dl, Load, StackPtr,
550193323Sed                                         NULL, 0, MemVT));
551193323Sed
552193323Sed      // The order of the stores doesn't matter - say it with a TokenFactor.
553193323Sed      SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Stores[0],
554193323Sed                               Stores.size());
555193323Sed
556193323Sed      // Finally, perform the original load only redirected to the stack slot.
557193323Sed      Load = DAG.getExtLoad(LD->getExtensionType(), dl, VT, TF, StackBase,
558193323Sed                            NULL, 0, LoadedVT);
559193323Sed
560193323Sed      // Callers expect a MERGE_VALUES node.
561193323Sed      SDValue Ops[] = { Load, TF };
562193323Sed      return DAG.getMergeValues(Ops, 2, dl);
563193323Sed    }
564193323Sed  }
565193323Sed  assert(LoadedVT.isInteger() && !LoadedVT.isVector() &&
566193323Sed         "Unaligned load of unsupported type.");
567193323Sed
568193323Sed  // Compute the new VT that is half the size of the old one.  This is an
569193323Sed  // integer MVT.
570193323Sed  unsigned NumBits = LoadedVT.getSizeInBits();
571193323Sed  MVT NewLoadedVT;
572193323Sed  NewLoadedVT = MVT::getIntegerVT(NumBits/2);
573193323Sed  NumBits >>= 1;
574193323Sed
575193323Sed  unsigned Alignment = LD->getAlignment();
576193323Sed  unsigned IncrementSize = NumBits / 8;
577193323Sed  ISD::LoadExtType HiExtType = LD->getExtensionType();
578193323Sed
579193323Sed  // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD.
580193323Sed  if (HiExtType == ISD::NON_EXTLOAD)
581193323Sed    HiExtType = ISD::ZEXTLOAD;
582193323Sed
583193323Sed  // Load the value in two parts
584193323Sed  SDValue Lo, Hi;
585193323Sed  if (TLI.isLittleEndian()) {
586193323Sed    Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, LD->getSrcValue(),
587193323Sed                        SVOffset, NewLoadedVT, LD->isVolatile(), Alignment);
588193323Sed    Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
589193323Sed                      DAG.getConstant(IncrementSize, TLI.getPointerTy()));
590193323Sed    Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, LD->getSrcValue(),
591193323Sed                        SVOffset + IncrementSize, NewLoadedVT, LD->isVolatile(),
592193323Sed                        MinAlign(Alignment, IncrementSize));
593193323Sed  } else {
594193323Sed    Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, LD->getSrcValue(),
595193323Sed                        SVOffset, NewLoadedVT, LD->isVolatile(), Alignment);
596193323Sed    Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
597193323Sed                      DAG.getConstant(IncrementSize, TLI.getPointerTy()));
598193323Sed    Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, LD->getSrcValue(),
599193323Sed                        SVOffset + IncrementSize, NewLoadedVT, LD->isVolatile(),
600193323Sed                        MinAlign(Alignment, IncrementSize));
601193323Sed  }
602193323Sed
603193323Sed  // aggregate the two parts
604193323Sed  SDValue ShiftAmount = DAG.getConstant(NumBits, TLI.getShiftAmountTy());
605193323Sed  SDValue Result = DAG.getNode(ISD::SHL, dl, VT, Hi, ShiftAmount);
606193323Sed  Result = DAG.getNode(ISD::OR, dl, VT, Result, Lo);
607193323Sed
608193323Sed  SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
609193323Sed                             Hi.getValue(1));
610193323Sed
611193323Sed  SDValue Ops[] = { Result, TF };
612193323Sed  return DAG.getMergeValues(Ops, 2, dl);
613193323Sed}
614193323Sed
615193323Sed/// PerformInsertVectorEltInMemory - Some target cannot handle a variable
616193323Sed/// insertion index for the INSERT_VECTOR_ELT instruction.  In this case, it
617193323Sed/// is necessary to spill the vector being inserted into to memory, perform
618193323Sed/// the insert there, and then read the result back.
619193323SedSDValue SelectionDAGLegalize::
620193323SedPerformInsertVectorEltInMemory(SDValue Vec, SDValue Val, SDValue Idx,
621193323Sed                               DebugLoc dl) {
622193323Sed  SDValue Tmp1 = Vec;
623193323Sed  SDValue Tmp2 = Val;
624193323Sed  SDValue Tmp3 = Idx;
625193323Sed
626193323Sed  // If the target doesn't support this, we have to spill the input vector
627193323Sed  // to a temporary stack slot, update the element, then reload it.  This is
628193323Sed  // badness.  We could also load the value into a vector register (either
629193323Sed  // with a "move to register" or "extload into register" instruction, then
630193323Sed  // permute it into place, if the idx is a constant and if the idx is
631193323Sed  // supported by the target.
632193323Sed  MVT VT    = Tmp1.getValueType();
633193323Sed  MVT EltVT = VT.getVectorElementType();
634193323Sed  MVT IdxVT = Tmp3.getValueType();
635193323Sed  MVT PtrVT = TLI.getPointerTy();
636193323Sed  SDValue StackPtr = DAG.CreateStackTemporary(VT);
637193323Sed
638193323Sed  int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
639193323Sed
640193323Sed  // Store the vector.
641193323Sed  SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, Tmp1, StackPtr,
642193323Sed                            PseudoSourceValue::getFixedStack(SPFI), 0);
643193323Sed
644193323Sed  // Truncate or zero extend offset to target pointer type.
645193323Sed  unsigned CastOpc = IdxVT.bitsGT(PtrVT) ? ISD::TRUNCATE : ISD::ZERO_EXTEND;
646193323Sed  Tmp3 = DAG.getNode(CastOpc, dl, PtrVT, Tmp3);
647193323Sed  // Add the offset to the index.
648193323Sed  unsigned EltSize = EltVT.getSizeInBits()/8;
649193323Sed  Tmp3 = DAG.getNode(ISD::MUL, dl, IdxVT, Tmp3,DAG.getConstant(EltSize, IdxVT));
650193323Sed  SDValue StackPtr2 = DAG.getNode(ISD::ADD, dl, IdxVT, Tmp3, StackPtr);
651193323Sed  // Store the scalar value.
652193323Sed  Ch = DAG.getTruncStore(Ch, dl, Tmp2, StackPtr2,
653193323Sed                         PseudoSourceValue::getFixedStack(SPFI), 0, EltVT);
654193323Sed  // Load the updated vector.
655193323Sed  return DAG.getLoad(VT, dl, Ch, StackPtr,
656193323Sed                     PseudoSourceValue::getFixedStack(SPFI), 0);
657193323Sed}
658193323Sed
659193323Sed
660193323SedSDValue SelectionDAGLegalize::
661193323SedExpandINSERT_VECTOR_ELT(SDValue Vec, SDValue Val, SDValue Idx, DebugLoc dl) {
662193323Sed  if (ConstantSDNode *InsertPos = dyn_cast<ConstantSDNode>(Idx)) {
663193323Sed    // SCALAR_TO_VECTOR requires that the type of the value being inserted
664193323Sed    // match the element type of the vector being created, except for
665193323Sed    // integers in which case the inserted value can be over width.
666193323Sed    MVT EltVT = Vec.getValueType().getVectorElementType();
667193323Sed    if (Val.getValueType() == EltVT ||
668193323Sed        (EltVT.isInteger() && Val.getValueType().bitsGE(EltVT))) {
669193323Sed      SDValue ScVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
670193323Sed                                  Vec.getValueType(), Val);
671193323Sed
672193323Sed      unsigned NumElts = Vec.getValueType().getVectorNumElements();
673193323Sed      // We generate a shuffle of InVec and ScVec, so the shuffle mask
674193323Sed      // should be 0,1,2,3,4,5... with the appropriate element replaced with
675193323Sed      // elt 0 of the RHS.
676193323Sed      SmallVector<int, 8> ShufOps;
677193323Sed      for (unsigned i = 0; i != NumElts; ++i)
678193323Sed        ShufOps.push_back(i != InsertPos->getZExtValue() ? i : NumElts);
679193323Sed
680193323Sed      return DAG.getVectorShuffle(Vec.getValueType(), dl, Vec, ScVec,
681193323Sed                                  &ShufOps[0]);
682193323Sed    }
683193323Sed  }
684193323Sed  return PerformInsertVectorEltInMemory(Vec, Val, Idx, dl);
685193323Sed}
686193323Sed
687193574SedSDValue SelectionDAGLegalize::OptimizeFloatStore(StoreSDNode* ST) {
688193574Sed  // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
689193574Sed  // FIXME: We shouldn't do this for TargetConstantFP's.
690193574Sed  // FIXME: move this to the DAG Combiner!  Note that we can't regress due
691193574Sed  // to phase ordering between legalized code and the dag combiner.  This
692193574Sed  // probably means that we need to integrate dag combiner and legalizer
693193574Sed  // together.
694193574Sed  // We generally can't do this one for long doubles.
695193574Sed  SDValue Tmp1 = ST->getChain();
696193574Sed  SDValue Tmp2 = ST->getBasePtr();
697193574Sed  SDValue Tmp3;
698193574Sed  int SVOffset = ST->getSrcValueOffset();
699193574Sed  unsigned Alignment = ST->getAlignment();
700193574Sed  bool isVolatile = ST->isVolatile();
701193574Sed  DebugLoc dl = ST->getDebugLoc();
702193574Sed  if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(ST->getValue())) {
703193574Sed    if (CFP->getValueType(0) == MVT::f32 &&
704193574Sed        getTypeAction(MVT::i32) == Legal) {
705193574Sed      Tmp3 = DAG.getConstant(CFP->getValueAPF().
706193574Sed                                      bitcastToAPInt().zextOrTrunc(32),
707193574Sed                              MVT::i32);
708193574Sed      return DAG.getStore(Tmp1, dl, Tmp3, Tmp2, ST->getSrcValue(),
709193574Sed                          SVOffset, isVolatile, Alignment);
710193574Sed    } else if (CFP->getValueType(0) == MVT::f64) {
711193574Sed      // If this target supports 64-bit registers, do a single 64-bit store.
712193574Sed      if (getTypeAction(MVT::i64) == Legal) {
713193574Sed        Tmp3 = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
714193574Sed                                  zextOrTrunc(64), MVT::i64);
715193574Sed        return DAG.getStore(Tmp1, dl, Tmp3, Tmp2, ST->getSrcValue(),
716193574Sed                            SVOffset, isVolatile, Alignment);
717193574Sed      } else if (getTypeAction(MVT::i32) == Legal && !ST->isVolatile()) {
718193574Sed        // Otherwise, if the target supports 32-bit registers, use 2 32-bit
719193574Sed        // stores.  If the target supports neither 32- nor 64-bits, this
720193574Sed        // xform is certainly not worth it.
721193574Sed        const APInt &IntVal =CFP->getValueAPF().bitcastToAPInt();
722193574Sed        SDValue Lo = DAG.getConstant(APInt(IntVal).trunc(32), MVT::i32);
723193574Sed        SDValue Hi = DAG.getConstant(IntVal.lshr(32).trunc(32), MVT::i32);
724193574Sed        if (TLI.isBigEndian()) std::swap(Lo, Hi);
725193574Sed
726193574Sed        Lo = DAG.getStore(Tmp1, dl, Lo, Tmp2, ST->getSrcValue(),
727193574Sed                          SVOffset, isVolatile, Alignment);
728193574Sed        Tmp2 = DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
729193574Sed                            DAG.getIntPtrConstant(4));
730193574Sed        Hi = DAG.getStore(Tmp1, dl, Hi, Tmp2, ST->getSrcValue(), SVOffset+4,
731193574Sed                          isVolatile, MinAlign(Alignment, 4U));
732193574Sed
733193574Sed        return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi);
734193574Sed      }
735193574Sed    }
736193574Sed  }
737193574Sed  return SDValue();
738193574Sed}
739193574Sed
740193323Sed/// LegalizeOp - We know that the specified value has a legal type, and
741193323Sed/// that its operands are legal.  Now ensure that the operation itself
742193323Sed/// is legal, recursively ensuring that the operands' operations remain
743193323Sed/// legal.
744193323SedSDValue SelectionDAGLegalize::LegalizeOp(SDValue Op) {
745193323Sed  if (Op.getOpcode() == ISD::TargetConstant) // Allow illegal target nodes.
746193323Sed    return Op;
747193323Sed
748193323Sed  SDNode *Node = Op.getNode();
749193323Sed  DebugLoc dl = Node->getDebugLoc();
750193323Sed
751193323Sed  for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
752193323Sed    assert(getTypeAction(Node->getValueType(i)) == Legal &&
753193323Sed           "Unexpected illegal type!");
754193323Sed
755193323Sed  for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
756193323Sed    assert((isTypeLegal(Node->getOperand(i).getValueType()) ||
757193323Sed            Node->getOperand(i).getOpcode() == ISD::TargetConstant) &&
758193323Sed           "Unexpected illegal type!");
759193323Sed
760193323Sed  // Note that LegalizeOp may be reentered even from single-use nodes, which
761193323Sed  // means that we always must cache transformed nodes.
762193323Sed  DenseMap<SDValue, SDValue>::iterator I = LegalizedNodes.find(Op);
763193323Sed  if (I != LegalizedNodes.end()) return I->second;
764193323Sed
765193323Sed  SDValue Tmp1, Tmp2, Tmp3, Tmp4;
766193323Sed  SDValue Result = Op;
767193323Sed  bool isCustom = false;
768193323Sed
769193323Sed  // Figure out the correct action; the way to query this varies by opcode
770193323Sed  TargetLowering::LegalizeAction Action;
771193323Sed  bool SimpleFinishLegalizing = true;
772193323Sed  switch (Node->getOpcode()) {
773193323Sed  case ISD::INTRINSIC_W_CHAIN:
774193323Sed  case ISD::INTRINSIC_WO_CHAIN:
775193323Sed  case ISD::INTRINSIC_VOID:
776193323Sed  case ISD::VAARG:
777193323Sed  case ISD::STACKSAVE:
778193323Sed    Action = TLI.getOperationAction(Node->getOpcode(), MVT::Other);
779193323Sed    break;
780193323Sed  case ISD::SINT_TO_FP:
781193323Sed  case ISD::UINT_TO_FP:
782193323Sed  case ISD::EXTRACT_VECTOR_ELT:
783193323Sed    Action = TLI.getOperationAction(Node->getOpcode(),
784193323Sed                                    Node->getOperand(0).getValueType());
785193323Sed    break;
786193323Sed  case ISD::FP_ROUND_INREG:
787193323Sed  case ISD::SIGN_EXTEND_INREG: {
788193323Sed    MVT InnerType = cast<VTSDNode>(Node->getOperand(1))->getVT();
789193323Sed    Action = TLI.getOperationAction(Node->getOpcode(), InnerType);
790193323Sed    break;
791193323Sed  }
792193323Sed  case ISD::SELECT_CC:
793193323Sed  case ISD::SETCC:
794193323Sed  case ISD::BR_CC: {
795193323Sed    unsigned CCOperand = Node->getOpcode() == ISD::SELECT_CC ? 4 :
796193323Sed                         Node->getOpcode() == ISD::SETCC ? 2 : 1;
797193323Sed    unsigned CompareOperand = Node->getOpcode() == ISD::BR_CC ? 2 : 0;
798193323Sed    MVT OpVT = Node->getOperand(CompareOperand).getValueType();
799193323Sed    ISD::CondCode CCCode =
800193323Sed        cast<CondCodeSDNode>(Node->getOperand(CCOperand))->get();
801193323Sed    Action = TLI.getCondCodeAction(CCCode, OpVT);
802193323Sed    if (Action == TargetLowering::Legal) {
803193323Sed      if (Node->getOpcode() == ISD::SELECT_CC)
804193323Sed        Action = TLI.getOperationAction(Node->getOpcode(),
805193323Sed                                        Node->getValueType(0));
806193323Sed      else
807193323Sed        Action = TLI.getOperationAction(Node->getOpcode(), OpVT);
808193323Sed    }
809193323Sed    break;
810193323Sed  }
811193323Sed  case ISD::LOAD:
812193323Sed  case ISD::STORE:
813193323Sed    // FIXME: Model these properly.  LOAD and STORE are complicated, and
814193323Sed    // STORE expects the unlegalized operand in some cases.
815193323Sed    SimpleFinishLegalizing = false;
816193323Sed    break;
817193323Sed  case ISD::CALLSEQ_START:
818193323Sed  case ISD::CALLSEQ_END:
819193323Sed    // FIXME: This shouldn't be necessary.  These nodes have special properties
820193323Sed    // dealing with the recursive nature of legalization.  Removing this
821193323Sed    // special case should be done as part of making LegalizeDAG non-recursive.
822193323Sed    SimpleFinishLegalizing = false;
823193323Sed    break;
824193323Sed  case ISD::CALL:
825193323Sed    // FIXME: Legalization for calls requires custom-lowering the call before
826193323Sed    // legalizing the operands!  (I haven't looked into precisely why.)
827193323Sed    SimpleFinishLegalizing = false;
828193323Sed    break;
829193323Sed  case ISD::EXTRACT_ELEMENT:
830193323Sed  case ISD::FLT_ROUNDS_:
831193323Sed  case ISD::SADDO:
832193323Sed  case ISD::SSUBO:
833193323Sed  case ISD::UADDO:
834193323Sed  case ISD::USUBO:
835193323Sed  case ISD::SMULO:
836193323Sed  case ISD::UMULO:
837193323Sed  case ISD::FPOWI:
838193323Sed  case ISD::MERGE_VALUES:
839193323Sed  case ISD::EH_RETURN:
840193323Sed  case ISD::FRAME_TO_ARGS_OFFSET:
841193323Sed    // These operations lie about being legal: when they claim to be legal,
842193323Sed    // they should actually be expanded.
843193323Sed    Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
844193323Sed    if (Action == TargetLowering::Legal)
845193323Sed      Action = TargetLowering::Expand;
846193323Sed    break;
847193323Sed  case ISD::TRAMPOLINE:
848193323Sed  case ISD::FRAMEADDR:
849193323Sed  case ISD::RETURNADDR:
850193323Sed  case ISD::FORMAL_ARGUMENTS:
851193323Sed    // These operations lie about being legal: when they claim to be legal,
852193323Sed    // they should actually be custom-lowered.
853193323Sed    Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
854193323Sed    if (Action == TargetLowering::Legal)
855193323Sed      Action = TargetLowering::Custom;
856193323Sed    break;
857193323Sed  case ISD::BUILD_VECTOR:
858193323Sed    // A weird case: legalization for BUILD_VECTOR never legalizes the
859193323Sed    // operands!
860193323Sed    // FIXME: This really sucks... changing it isn't semantically incorrect,
861193323Sed    // but it massively pessimizes the code for floating-point BUILD_VECTORs
862193323Sed    // because ConstantFP operands get legalized into constant pool loads
863193323Sed    // before the BUILD_VECTOR code can see them.  It doesn't usually bite,
864193323Sed    // though, because BUILD_VECTORS usually get lowered into other nodes
865193323Sed    // which get legalized properly.
866193323Sed    SimpleFinishLegalizing = false;
867193323Sed    break;
868193323Sed  default:
869193323Sed    if (Node->getOpcode() >= ISD::BUILTIN_OP_END) {
870193323Sed      Action = TargetLowering::Legal;
871193323Sed    } else {
872193323Sed      Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
873193323Sed    }
874193323Sed    break;
875193323Sed  }
876193323Sed
877193323Sed  if (SimpleFinishLegalizing) {
878193323Sed    SmallVector<SDValue, 8> Ops, ResultVals;
879193323Sed    for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
880193323Sed      Ops.push_back(LegalizeOp(Node->getOperand(i)));
881193323Sed    switch (Node->getOpcode()) {
882193323Sed    default: break;
883193323Sed    case ISD::BR:
884193323Sed    case ISD::BRIND:
885193323Sed    case ISD::BR_JT:
886193323Sed    case ISD::BR_CC:
887193323Sed    case ISD::BRCOND:
888193323Sed    case ISD::RET:
889193323Sed      // Branches tweak the chain to include LastCALLSEQ_END
890193323Sed      Ops[0] = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ops[0],
891193323Sed                            LastCALLSEQ_END);
892193323Sed      Ops[0] = LegalizeOp(Ops[0]);
893193323Sed      LastCALLSEQ_END = DAG.getEntryNode();
894193323Sed      break;
895193323Sed    case ISD::SHL:
896193323Sed    case ISD::SRL:
897193323Sed    case ISD::SRA:
898193323Sed    case ISD::ROTL:
899193323Sed    case ISD::ROTR:
900193323Sed      // Legalizing shifts/rotates requires adjusting the shift amount
901193323Sed      // to the appropriate width.
902193323Sed      if (!Ops[1].getValueType().isVector())
903193323Sed        Ops[1] = LegalizeOp(DAG.getShiftAmountOperand(Ops[1]));
904193323Sed      break;
905193323Sed    }
906193323Sed
907193323Sed    Result = DAG.UpdateNodeOperands(Result.getValue(0), Ops.data(),
908193323Sed                                    Ops.size());
909193323Sed    switch (Action) {
910193323Sed    case TargetLowering::Legal:
911193323Sed      for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
912193323Sed        ResultVals.push_back(Result.getValue(i));
913193323Sed      break;
914193323Sed    case TargetLowering::Custom:
915193323Sed      // FIXME: The handling for custom lowering with multiple results is
916193323Sed      // a complete mess.
917193323Sed      Tmp1 = TLI.LowerOperation(Result, DAG);
918193323Sed      if (Tmp1.getNode()) {
919193323Sed        for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i) {
920193323Sed          if (e == 1)
921193323Sed            ResultVals.push_back(Tmp1);
922193323Sed          else
923193323Sed            ResultVals.push_back(Tmp1.getValue(i));
924193323Sed        }
925193323Sed        break;
926193323Sed      }
927193323Sed
928193323Sed      // FALL THROUGH
929193323Sed    case TargetLowering::Expand:
930193323Sed      ExpandNode(Result.getNode(), ResultVals);
931193323Sed      break;
932193323Sed    case TargetLowering::Promote:
933193323Sed      PromoteNode(Result.getNode(), ResultVals);
934193323Sed      break;
935193323Sed    }
936193323Sed    if (!ResultVals.empty()) {
937193323Sed      for (unsigned i = 0, e = ResultVals.size(); i != e; ++i) {
938193323Sed        if (ResultVals[i] != SDValue(Node, i))
939193323Sed          ResultVals[i] = LegalizeOp(ResultVals[i]);
940193323Sed        AddLegalizedOperand(SDValue(Node, i), ResultVals[i]);
941193323Sed      }
942193323Sed      return ResultVals[Op.getResNo()];
943193323Sed    }
944193323Sed  }
945193323Sed
946193323Sed  switch (Node->getOpcode()) {
947193323Sed  default:
948193323Sed#ifndef NDEBUG
949193323Sed    cerr << "NODE: "; Node->dump(&DAG); cerr << "\n";
950193323Sed#endif
951193323Sed    assert(0 && "Do not know how to legalize this operator!");
952193323Sed    abort();
953193323Sed  case ISD::CALL:
954193323Sed    // The only option for this is to custom lower it.
955193323Sed    Tmp3 = TLI.LowerOperation(Result.getValue(0), DAG);
956193323Sed    assert(Tmp3.getNode() && "Target didn't custom lower this node!");
957193323Sed    // A call within a calling sequence must be legalized to something
958193323Sed    // other than the normal CALLSEQ_END.  Violating this gets Legalize
959193323Sed    // into an infinite loop.
960193323Sed    assert ((!IsLegalizingCall ||
961193323Sed             Node->getOpcode() != ISD::CALL ||
962193323Sed             Tmp3.getNode()->getOpcode() != ISD::CALLSEQ_END) &&
963193323Sed            "Nested CALLSEQ_START..CALLSEQ_END not supported.");
964193323Sed
965193323Sed    // The number of incoming and outgoing values should match; unless the final
966193323Sed    // outgoing value is a flag.
967193323Sed    assert((Tmp3.getNode()->getNumValues() == Result.getNode()->getNumValues() ||
968193323Sed            (Tmp3.getNode()->getNumValues() == Result.getNode()->getNumValues() + 1 &&
969193323Sed             Tmp3.getNode()->getValueType(Tmp3.getNode()->getNumValues() - 1) ==
970193323Sed               MVT::Flag)) &&
971193323Sed           "Lowering call/formal_arguments produced unexpected # results!");
972193323Sed
973193323Sed    // Since CALL/FORMAL_ARGUMENTS nodes produce multiple values, make sure to
974193323Sed    // remember that we legalized all of them, so it doesn't get relegalized.
975193323Sed    for (unsigned i = 0, e = Tmp3.getNode()->getNumValues(); i != e; ++i) {
976193323Sed      if (Tmp3.getNode()->getValueType(i) == MVT::Flag)
977193323Sed        continue;
978193323Sed      Tmp1 = LegalizeOp(Tmp3.getValue(i));
979193323Sed      if (Op.getResNo() == i)
980193323Sed        Tmp2 = Tmp1;
981193323Sed      AddLegalizedOperand(SDValue(Node, i), Tmp1);
982193323Sed    }
983193323Sed    return Tmp2;
984193323Sed  case ISD::BUILD_VECTOR:
985193323Sed    switch (TLI.getOperationAction(ISD::BUILD_VECTOR, Node->getValueType(0))) {
986193323Sed    default: assert(0 && "This action is not supported yet!");
987193323Sed    case TargetLowering::Custom:
988193323Sed      Tmp3 = TLI.LowerOperation(Result, DAG);
989193323Sed      if (Tmp3.getNode()) {
990193323Sed        Result = Tmp3;
991193323Sed        break;
992193323Sed      }
993193323Sed      // FALLTHROUGH
994193323Sed    case TargetLowering::Expand:
995193323Sed      Result = ExpandBUILD_VECTOR(Result.getNode());
996193323Sed      break;
997193323Sed    }
998193323Sed    break;
999193323Sed  case ISD::CALLSEQ_START: {
1000193323Sed    SDNode *CallEnd = FindCallEndFromCallStart(Node);
1001193323Sed
1002193323Sed    // Recursively Legalize all of the inputs of the call end that do not lead
1003193323Sed    // to this call start.  This ensures that any libcalls that need be inserted
1004193323Sed    // are inserted *before* the CALLSEQ_START.
1005193323Sed    {SmallPtrSet<SDNode*, 32> NodesLeadingTo;
1006193323Sed    for (unsigned i = 0, e = CallEnd->getNumOperands(); i != e; ++i)
1007193323Sed      LegalizeAllNodesNotLeadingTo(CallEnd->getOperand(i).getNode(), Node,
1008193323Sed                                   NodesLeadingTo);
1009193323Sed    }
1010193323Sed
1011193323Sed    // Now that we legalized all of the inputs (which may have inserted
1012193323Sed    // libcalls) create the new CALLSEQ_START node.
1013193323Sed    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1014193323Sed
1015193323Sed    // Merge in the last call, to ensure that this call start after the last
1016193323Sed    // call ended.
1017193323Sed    if (LastCALLSEQ_END.getOpcode() != ISD::EntryToken) {
1018193323Sed      Tmp1 = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1019193323Sed                         Tmp1, LastCALLSEQ_END);
1020193323Sed      Tmp1 = LegalizeOp(Tmp1);
1021193323Sed    }
1022193323Sed
1023193323Sed    // Do not try to legalize the target-specific arguments (#1+).
1024193323Sed    if (Tmp1 != Node->getOperand(0)) {
1025193323Sed      SmallVector<SDValue, 8> Ops(Node->op_begin(), Node->op_end());
1026193323Sed      Ops[0] = Tmp1;
1027193323Sed      Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
1028193323Sed    }
1029193323Sed
1030193323Sed    // Remember that the CALLSEQ_START is legalized.
1031193323Sed    AddLegalizedOperand(Op.getValue(0), Result);
1032193323Sed    if (Node->getNumValues() == 2)    // If this has a flag result, remember it.
1033193323Sed      AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
1034193323Sed
1035193323Sed    // Now that the callseq_start and all of the non-call nodes above this call
1036193323Sed    // sequence have been legalized, legalize the call itself.  During this
1037193323Sed    // process, no libcalls can/will be inserted, guaranteeing that no calls
1038193323Sed    // can overlap.
1039193323Sed    assert(!IsLegalizingCall && "Inconsistent sequentialization of calls!");
1040193323Sed    // Note that we are selecting this call!
1041193323Sed    LastCALLSEQ_END = SDValue(CallEnd, 0);
1042193323Sed    IsLegalizingCall = true;
1043193323Sed
1044193323Sed    // Legalize the call, starting from the CALLSEQ_END.
1045193323Sed    LegalizeOp(LastCALLSEQ_END);
1046193323Sed    assert(!IsLegalizingCall && "CALLSEQ_END should have cleared this!");
1047193323Sed    return Result;
1048193323Sed  }
1049193323Sed  case ISD::CALLSEQ_END:
1050193323Sed    // If the CALLSEQ_START node hasn't been legalized first, legalize it.  This
1051193323Sed    // will cause this node to be legalized as well as handling libcalls right.
1052193323Sed    if (LastCALLSEQ_END.getNode() != Node) {
1053193323Sed      LegalizeOp(SDValue(FindCallStartFromCallEnd(Node), 0));
1054193323Sed      DenseMap<SDValue, SDValue>::iterator I = LegalizedNodes.find(Op);
1055193323Sed      assert(I != LegalizedNodes.end() &&
1056193323Sed             "Legalizing the call start should have legalized this node!");
1057193323Sed      return I->second;
1058193323Sed    }
1059193323Sed
1060193323Sed    // Otherwise, the call start has been legalized and everything is going
1061193323Sed    // according to plan.  Just legalize ourselves normally here.
1062193323Sed    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1063193323Sed    // Do not try to legalize the target-specific arguments (#1+), except for
1064193323Sed    // an optional flag input.
1065193323Sed    if (Node->getOperand(Node->getNumOperands()-1).getValueType() != MVT::Flag){
1066193323Sed      if (Tmp1 != Node->getOperand(0)) {
1067193323Sed        SmallVector<SDValue, 8> Ops(Node->op_begin(), Node->op_end());
1068193323Sed        Ops[0] = Tmp1;
1069193323Sed        Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
1070193323Sed      }
1071193323Sed    } else {
1072193323Sed      Tmp2 = LegalizeOp(Node->getOperand(Node->getNumOperands()-1));
1073193323Sed      if (Tmp1 != Node->getOperand(0) ||
1074193323Sed          Tmp2 != Node->getOperand(Node->getNumOperands()-1)) {
1075193323Sed        SmallVector<SDValue, 8> Ops(Node->op_begin(), Node->op_end());
1076193323Sed        Ops[0] = Tmp1;
1077193323Sed        Ops.back() = Tmp2;
1078193323Sed        Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
1079193323Sed      }
1080193323Sed    }
1081193323Sed    assert(IsLegalizingCall && "Call sequence imbalance between start/end?");
1082193323Sed    // This finishes up call legalization.
1083193323Sed    IsLegalizingCall = false;
1084193323Sed
1085193323Sed    // If the CALLSEQ_END node has a flag, remember that we legalized it.
1086193323Sed    AddLegalizedOperand(SDValue(Node, 0), Result.getValue(0));
1087193323Sed    if (Node->getNumValues() == 2)
1088193323Sed      AddLegalizedOperand(SDValue(Node, 1), Result.getValue(1));
1089193323Sed    return Result.getValue(Op.getResNo());
1090193323Sed  case ISD::LOAD: {
1091193323Sed    LoadSDNode *LD = cast<LoadSDNode>(Node);
1092193323Sed    Tmp1 = LegalizeOp(LD->getChain());   // Legalize the chain.
1093193323Sed    Tmp2 = LegalizeOp(LD->getBasePtr()); // Legalize the base pointer.
1094193323Sed
1095193323Sed    ISD::LoadExtType ExtType = LD->getExtensionType();
1096193323Sed    if (ExtType == ISD::NON_EXTLOAD) {
1097193323Sed      MVT VT = Node->getValueType(0);
1098193323Sed      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, LD->getOffset());
1099193323Sed      Tmp3 = Result.getValue(0);
1100193323Sed      Tmp4 = Result.getValue(1);
1101193323Sed
1102193323Sed      switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
1103193323Sed      default: assert(0 && "This action is not supported yet!");
1104193323Sed      case TargetLowering::Legal:
1105193323Sed        // If this is an unaligned load and the target doesn't support it,
1106193323Sed        // expand it.
1107193323Sed        if (!TLI.allowsUnalignedMemoryAccesses()) {
1108193323Sed          unsigned ABIAlignment = TLI.getTargetData()->
1109193323Sed            getABITypeAlignment(LD->getMemoryVT().getTypeForMVT());
1110193323Sed          if (LD->getAlignment() < ABIAlignment){
1111193323Sed            Result = ExpandUnalignedLoad(cast<LoadSDNode>(Result.getNode()), DAG,
1112193323Sed                                         TLI);
1113193323Sed            Tmp3 = Result.getOperand(0);
1114193323Sed            Tmp4 = Result.getOperand(1);
1115193323Sed            Tmp3 = LegalizeOp(Tmp3);
1116193323Sed            Tmp4 = LegalizeOp(Tmp4);
1117193323Sed          }
1118193323Sed        }
1119193323Sed        break;
1120193323Sed      case TargetLowering::Custom:
1121193323Sed        Tmp1 = TLI.LowerOperation(Tmp3, DAG);
1122193323Sed        if (Tmp1.getNode()) {
1123193323Sed          Tmp3 = LegalizeOp(Tmp1);
1124193323Sed          Tmp4 = LegalizeOp(Tmp1.getValue(1));
1125193323Sed        }
1126193323Sed        break;
1127193323Sed      case TargetLowering::Promote: {
1128193323Sed        // Only promote a load of vector type to another.
1129193323Sed        assert(VT.isVector() && "Cannot promote this load!");
1130193323Sed        // Change base type to a different vector type.
1131193323Sed        MVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), VT);
1132193323Sed
1133193323Sed        Tmp1 = DAG.getLoad(NVT, dl, Tmp1, Tmp2, LD->getSrcValue(),
1134193323Sed                           LD->getSrcValueOffset(),
1135193323Sed                           LD->isVolatile(), LD->getAlignment());
1136193323Sed        Tmp3 = LegalizeOp(DAG.getNode(ISD::BIT_CONVERT, dl, VT, Tmp1));
1137193323Sed        Tmp4 = LegalizeOp(Tmp1.getValue(1));
1138193323Sed        break;
1139193323Sed      }
1140193323Sed      }
1141193323Sed      // Since loads produce two values, make sure to remember that we
1142193323Sed      // legalized both of them.
1143193323Sed      AddLegalizedOperand(SDValue(Node, 0), Tmp3);
1144193323Sed      AddLegalizedOperand(SDValue(Node, 1), Tmp4);
1145193323Sed      return Op.getResNo() ? Tmp4 : Tmp3;
1146193323Sed    } else {
1147193323Sed      MVT SrcVT = LD->getMemoryVT();
1148193323Sed      unsigned SrcWidth = SrcVT.getSizeInBits();
1149193323Sed      int SVOffset = LD->getSrcValueOffset();
1150193323Sed      unsigned Alignment = LD->getAlignment();
1151193323Sed      bool isVolatile = LD->isVolatile();
1152193323Sed
1153193323Sed      if (SrcWidth != SrcVT.getStoreSizeInBits() &&
1154193323Sed          // Some targets pretend to have an i1 loading operation, and actually
1155193323Sed          // load an i8.  This trick is correct for ZEXTLOAD because the top 7
1156193323Sed          // bits are guaranteed to be zero; it helps the optimizers understand
1157193323Sed          // that these bits are zero.  It is also useful for EXTLOAD, since it
1158193323Sed          // tells the optimizers that those bits are undefined.  It would be
1159193323Sed          // nice to have an effective generic way of getting these benefits...
1160193323Sed          // Until such a way is found, don't insist on promoting i1 here.
1161193323Sed          (SrcVT != MVT::i1 ||
1162193323Sed           TLI.getLoadExtAction(ExtType, MVT::i1) == TargetLowering::Promote)) {
1163193323Sed        // Promote to a byte-sized load if not loading an integral number of
1164193323Sed        // bytes.  For example, promote EXTLOAD:i20 -> EXTLOAD:i24.
1165193323Sed        unsigned NewWidth = SrcVT.getStoreSizeInBits();
1166193323Sed        MVT NVT = MVT::getIntegerVT(NewWidth);
1167193323Sed        SDValue Ch;
1168193323Sed
1169193323Sed        // The extra bits are guaranteed to be zero, since we stored them that
1170193323Sed        // way.  A zext load from NVT thus automatically gives zext from SrcVT.
1171193323Sed
1172193323Sed        ISD::LoadExtType NewExtType =
1173193323Sed          ExtType == ISD::ZEXTLOAD ? ISD::ZEXTLOAD : ISD::EXTLOAD;
1174193323Sed
1175193323Sed        Result = DAG.getExtLoad(NewExtType, dl, Node->getValueType(0),
1176193323Sed                                Tmp1, Tmp2, LD->getSrcValue(), SVOffset,
1177193323Sed                                NVT, isVolatile, Alignment);
1178193323Sed
1179193323Sed        Ch = Result.getValue(1); // The chain.
1180193323Sed
1181193323Sed        if (ExtType == ISD::SEXTLOAD)
1182193323Sed          // Having the top bits zero doesn't help when sign extending.
1183193323Sed          Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl,
1184193323Sed                               Result.getValueType(),
1185193323Sed                               Result, DAG.getValueType(SrcVT));
1186193323Sed        else if (ExtType == ISD::ZEXTLOAD || NVT == Result.getValueType())
1187193323Sed          // All the top bits are guaranteed to be zero - inform the optimizers.
1188193323Sed          Result = DAG.getNode(ISD::AssertZext, dl,
1189193323Sed                               Result.getValueType(), Result,
1190193323Sed                               DAG.getValueType(SrcVT));
1191193323Sed
1192193323Sed        Tmp1 = LegalizeOp(Result);
1193193323Sed        Tmp2 = LegalizeOp(Ch);
1194193323Sed      } else if (SrcWidth & (SrcWidth - 1)) {
1195193323Sed        // If not loading a power-of-2 number of bits, expand as two loads.
1196193323Sed        assert(SrcVT.isExtended() && !SrcVT.isVector() &&
1197193323Sed               "Unsupported extload!");
1198193323Sed        unsigned RoundWidth = 1 << Log2_32(SrcWidth);
1199193323Sed        assert(RoundWidth < SrcWidth);
1200193323Sed        unsigned ExtraWidth = SrcWidth - RoundWidth;
1201193323Sed        assert(ExtraWidth < RoundWidth);
1202193323Sed        assert(!(RoundWidth % 8) && !(ExtraWidth % 8) &&
1203193323Sed               "Load size not an integral number of bytes!");
1204193323Sed        MVT RoundVT = MVT::getIntegerVT(RoundWidth);
1205193323Sed        MVT ExtraVT = MVT::getIntegerVT(ExtraWidth);
1206193323Sed        SDValue Lo, Hi, Ch;
1207193323Sed        unsigned IncrementSize;
1208193323Sed
1209193323Sed        if (TLI.isLittleEndian()) {
1210193323Sed          // EXTLOAD:i24 -> ZEXTLOAD:i16 | (shl EXTLOAD@+2:i8, 16)
1211193323Sed          // Load the bottom RoundWidth bits.
1212193323Sed          Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl,
1213193323Sed                              Node->getValueType(0), Tmp1, Tmp2,
1214193323Sed                              LD->getSrcValue(), SVOffset, RoundVT, isVolatile,
1215193323Sed                              Alignment);
1216193323Sed
1217193323Sed          // Load the remaining ExtraWidth bits.
1218193323Sed          IncrementSize = RoundWidth / 8;
1219193323Sed          Tmp2 = DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
1220193323Sed                             DAG.getIntPtrConstant(IncrementSize));
1221193323Sed          Hi = DAG.getExtLoad(ExtType, dl, Node->getValueType(0), Tmp1, Tmp2,
1222193323Sed                              LD->getSrcValue(), SVOffset + IncrementSize,
1223193323Sed                              ExtraVT, isVolatile,
1224193323Sed                              MinAlign(Alignment, IncrementSize));
1225193323Sed
1226193323Sed          // Build a factor node to remember that this load is independent of the
1227193323Sed          // other one.
1228193323Sed          Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
1229193323Sed                           Hi.getValue(1));
1230193323Sed
1231193323Sed          // Move the top bits to the right place.
1232193323Sed          Hi = DAG.getNode(ISD::SHL, dl, Hi.getValueType(), Hi,
1233193323Sed                           DAG.getConstant(RoundWidth, TLI.getShiftAmountTy()));
1234193323Sed
1235193323Sed          // Join the hi and lo parts.
1236193323Sed          Result = DAG.getNode(ISD::OR, dl, Node->getValueType(0), Lo, Hi);
1237193323Sed        } else {
1238193323Sed          // Big endian - avoid unaligned loads.
1239193323Sed          // EXTLOAD:i24 -> (shl EXTLOAD:i16, 8) | ZEXTLOAD@+2:i8
1240193323Sed          // Load the top RoundWidth bits.
1241193323Sed          Hi = DAG.getExtLoad(ExtType, dl, Node->getValueType(0), Tmp1, Tmp2,
1242193323Sed                              LD->getSrcValue(), SVOffset, RoundVT, isVolatile,
1243193323Sed                              Alignment);
1244193323Sed
1245193323Sed          // Load the remaining ExtraWidth bits.
1246193323Sed          IncrementSize = RoundWidth / 8;
1247193323Sed          Tmp2 = DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
1248193323Sed                             DAG.getIntPtrConstant(IncrementSize));
1249193323Sed          Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl,
1250193323Sed                              Node->getValueType(0), Tmp1, Tmp2,
1251193323Sed                              LD->getSrcValue(), SVOffset + IncrementSize,
1252193323Sed                              ExtraVT, isVolatile,
1253193323Sed                              MinAlign(Alignment, IncrementSize));
1254193323Sed
1255193323Sed          // Build a factor node to remember that this load is independent of the
1256193323Sed          // other one.
1257193323Sed          Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
1258193323Sed                           Hi.getValue(1));
1259193323Sed
1260193323Sed          // Move the top bits to the right place.
1261193323Sed          Hi = DAG.getNode(ISD::SHL, dl, Hi.getValueType(), Hi,
1262193323Sed                           DAG.getConstant(ExtraWidth, TLI.getShiftAmountTy()));
1263193323Sed
1264193323Sed          // Join the hi and lo parts.
1265193323Sed          Result = DAG.getNode(ISD::OR, dl, Node->getValueType(0), Lo, Hi);
1266193323Sed        }
1267193323Sed
1268193323Sed        Tmp1 = LegalizeOp(Result);
1269193323Sed        Tmp2 = LegalizeOp(Ch);
1270193323Sed      } else {
1271193323Sed        switch (TLI.getLoadExtAction(ExtType, SrcVT)) {
1272193323Sed        default: assert(0 && "This action is not supported yet!");
1273193323Sed        case TargetLowering::Custom:
1274193323Sed          isCustom = true;
1275193323Sed          // FALLTHROUGH
1276193323Sed        case TargetLowering::Legal:
1277193323Sed          Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, LD->getOffset());
1278193323Sed          Tmp1 = Result.getValue(0);
1279193323Sed          Tmp2 = Result.getValue(1);
1280193323Sed
1281193323Sed          if (isCustom) {
1282193323Sed            Tmp3 = TLI.LowerOperation(Result, DAG);
1283193323Sed            if (Tmp3.getNode()) {
1284193323Sed              Tmp1 = LegalizeOp(Tmp3);
1285193323Sed              Tmp2 = LegalizeOp(Tmp3.getValue(1));
1286193323Sed            }
1287193323Sed          } else {
1288193323Sed            // If this is an unaligned load and the target doesn't support it,
1289193323Sed            // expand it.
1290193323Sed            if (!TLI.allowsUnalignedMemoryAccesses()) {
1291193323Sed              unsigned ABIAlignment = TLI.getTargetData()->
1292193323Sed                getABITypeAlignment(LD->getMemoryVT().getTypeForMVT());
1293193323Sed              if (LD->getAlignment() < ABIAlignment){
1294193323Sed                Result = ExpandUnalignedLoad(cast<LoadSDNode>(Result.getNode()), DAG,
1295193323Sed                                             TLI);
1296193323Sed                Tmp1 = Result.getOperand(0);
1297193323Sed                Tmp2 = Result.getOperand(1);
1298193323Sed                Tmp1 = LegalizeOp(Tmp1);
1299193323Sed                Tmp2 = LegalizeOp(Tmp2);
1300193323Sed              }
1301193323Sed            }
1302193323Sed          }
1303193323Sed          break;
1304193323Sed        case TargetLowering::Expand:
1305193323Sed          // f64 = EXTLOAD f32 should expand to LOAD, FP_EXTEND
1306193323Sed          if (SrcVT == MVT::f32 && Node->getValueType(0) == MVT::f64) {
1307193323Sed            SDValue Load = DAG.getLoad(SrcVT, dl, Tmp1, Tmp2, LD->getSrcValue(),
1308193323Sed                                         LD->getSrcValueOffset(),
1309193323Sed                                         LD->isVolatile(), LD->getAlignment());
1310193323Sed            Result = DAG.getNode(ISD::FP_EXTEND, dl,
1311193323Sed                                 Node->getValueType(0), Load);
1312193323Sed            Tmp1 = LegalizeOp(Result);  // Relegalize new nodes.
1313193323Sed            Tmp2 = LegalizeOp(Load.getValue(1));
1314193323Sed            break;
1315193323Sed          }
1316193323Sed          assert(ExtType != ISD::EXTLOAD &&"EXTLOAD should always be supported!");
1317193323Sed          // Turn the unsupported load into an EXTLOAD followed by an explicit
1318193323Sed          // zero/sign extend inreg.
1319193323Sed          Result = DAG.getExtLoad(ISD::EXTLOAD, dl, Node->getValueType(0),
1320193323Sed                                  Tmp1, Tmp2, LD->getSrcValue(),
1321193323Sed                                  LD->getSrcValueOffset(), SrcVT,
1322193323Sed                                  LD->isVolatile(), LD->getAlignment());
1323193323Sed          SDValue ValRes;
1324193323Sed          if (ExtType == ISD::SEXTLOAD)
1325193323Sed            ValRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl,
1326193323Sed                                 Result.getValueType(),
1327193323Sed                                 Result, DAG.getValueType(SrcVT));
1328193323Sed          else
1329193323Sed            ValRes = DAG.getZeroExtendInReg(Result, dl, SrcVT);
1330193323Sed          Tmp1 = LegalizeOp(ValRes);  // Relegalize new nodes.
1331193323Sed          Tmp2 = LegalizeOp(Result.getValue(1));  // Relegalize new nodes.
1332193323Sed          break;
1333193323Sed        }
1334193323Sed      }
1335193323Sed
1336193323Sed      // Since loads produce two values, make sure to remember that we legalized
1337193323Sed      // both of them.
1338193323Sed      AddLegalizedOperand(SDValue(Node, 0), Tmp1);
1339193323Sed      AddLegalizedOperand(SDValue(Node, 1), Tmp2);
1340193323Sed      return Op.getResNo() ? Tmp2 : Tmp1;
1341193323Sed    }
1342193323Sed  }
1343193323Sed  case ISD::STORE: {
1344193323Sed    StoreSDNode *ST = cast<StoreSDNode>(Node);
1345193323Sed    Tmp1 = LegalizeOp(ST->getChain());    // Legalize the chain.
1346193323Sed    Tmp2 = LegalizeOp(ST->getBasePtr());  // Legalize the pointer.
1347193323Sed    int SVOffset = ST->getSrcValueOffset();
1348193323Sed    unsigned Alignment = ST->getAlignment();
1349193323Sed    bool isVolatile = ST->isVolatile();
1350193323Sed
1351193323Sed    if (!ST->isTruncatingStore()) {
1352193574Sed      if (SDNode *OptStore = OptimizeFloatStore(ST).getNode()) {
1353193574Sed        Result = SDValue(OptStore, 0);
1354193574Sed        break;
1355193323Sed      }
1356193323Sed
1357193323Sed      {
1358193323Sed        Tmp3 = LegalizeOp(ST->getValue());
1359193323Sed        Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp3, Tmp2,
1360193323Sed                                        ST->getOffset());
1361193323Sed
1362193323Sed        MVT VT = Tmp3.getValueType();
1363193323Sed        switch (TLI.getOperationAction(ISD::STORE, VT)) {
1364193323Sed        default: assert(0 && "This action is not supported yet!");
1365193323Sed        case TargetLowering::Legal:
1366193323Sed          // If this is an unaligned store and the target doesn't support it,
1367193323Sed          // expand it.
1368193323Sed          if (!TLI.allowsUnalignedMemoryAccesses()) {
1369193323Sed            unsigned ABIAlignment = TLI.getTargetData()->
1370193323Sed              getABITypeAlignment(ST->getMemoryVT().getTypeForMVT());
1371193323Sed            if (ST->getAlignment() < ABIAlignment)
1372193323Sed              Result = ExpandUnalignedStore(cast<StoreSDNode>(Result.getNode()), DAG,
1373193323Sed                                            TLI);
1374193323Sed          }
1375193323Sed          break;
1376193323Sed        case TargetLowering::Custom:
1377193323Sed          Tmp1 = TLI.LowerOperation(Result, DAG);
1378193323Sed          if (Tmp1.getNode()) Result = Tmp1;
1379193323Sed          break;
1380193323Sed        case TargetLowering::Promote:
1381193323Sed          assert(VT.isVector() && "Unknown legal promote case!");
1382193323Sed          Tmp3 = DAG.getNode(ISD::BIT_CONVERT, dl,
1383193323Sed                             TLI.getTypeToPromoteTo(ISD::STORE, VT), Tmp3);
1384193323Sed          Result = DAG.getStore(Tmp1, dl, Tmp3, Tmp2,
1385193323Sed                                ST->getSrcValue(), SVOffset, isVolatile,
1386193323Sed                                Alignment);
1387193323Sed          break;
1388193323Sed        }
1389193323Sed        break;
1390193323Sed      }
1391193323Sed    } else {
1392193323Sed      Tmp3 = LegalizeOp(ST->getValue());
1393193323Sed
1394193323Sed      MVT StVT = ST->getMemoryVT();
1395193323Sed      unsigned StWidth = StVT.getSizeInBits();
1396193323Sed
1397193323Sed      if (StWidth != StVT.getStoreSizeInBits()) {
1398193323Sed        // Promote to a byte-sized store with upper bits zero if not
1399193323Sed        // storing an integral number of bytes.  For example, promote
1400193323Sed        // TRUNCSTORE:i1 X -> TRUNCSTORE:i8 (and X, 1)
1401193323Sed        MVT NVT = MVT::getIntegerVT(StVT.getStoreSizeInBits());
1402193323Sed        Tmp3 = DAG.getZeroExtendInReg(Tmp3, dl, StVT);
1403193323Sed        Result = DAG.getTruncStore(Tmp1, dl, Tmp3, Tmp2, ST->getSrcValue(),
1404193323Sed                                   SVOffset, NVT, isVolatile, Alignment);
1405193323Sed      } else if (StWidth & (StWidth - 1)) {
1406193323Sed        // If not storing a power-of-2 number of bits, expand as two stores.
1407193323Sed        assert(StVT.isExtended() && !StVT.isVector() &&
1408193323Sed               "Unsupported truncstore!");
1409193323Sed        unsigned RoundWidth = 1 << Log2_32(StWidth);
1410193323Sed        assert(RoundWidth < StWidth);
1411193323Sed        unsigned ExtraWidth = StWidth - RoundWidth;
1412193323Sed        assert(ExtraWidth < RoundWidth);
1413193323Sed        assert(!(RoundWidth % 8) && !(ExtraWidth % 8) &&
1414193323Sed               "Store size not an integral number of bytes!");
1415193323Sed        MVT RoundVT = MVT::getIntegerVT(RoundWidth);
1416193323Sed        MVT ExtraVT = MVT::getIntegerVT(ExtraWidth);
1417193323Sed        SDValue Lo, Hi;
1418193323Sed        unsigned IncrementSize;
1419193323Sed
1420193323Sed        if (TLI.isLittleEndian()) {
1421193323Sed          // TRUNCSTORE:i24 X -> TRUNCSTORE:i16 X, TRUNCSTORE@+2:i8 (srl X, 16)
1422193323Sed          // Store the bottom RoundWidth bits.
1423193323Sed          Lo = DAG.getTruncStore(Tmp1, dl, Tmp3, Tmp2, ST->getSrcValue(),
1424193323Sed                                 SVOffset, RoundVT,
1425193323Sed                                 isVolatile, Alignment);
1426193323Sed
1427193323Sed          // Store the remaining ExtraWidth bits.
1428193323Sed          IncrementSize = RoundWidth / 8;
1429193323Sed          Tmp2 = DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
1430193323Sed                             DAG.getIntPtrConstant(IncrementSize));
1431193323Sed          Hi = DAG.getNode(ISD::SRL, dl, Tmp3.getValueType(), Tmp3,
1432193323Sed                           DAG.getConstant(RoundWidth, TLI.getShiftAmountTy()));
1433193323Sed          Hi = DAG.getTruncStore(Tmp1, dl, Hi, Tmp2, ST->getSrcValue(),
1434193323Sed                                 SVOffset + IncrementSize, ExtraVT, isVolatile,
1435193323Sed                                 MinAlign(Alignment, IncrementSize));
1436193323Sed        } else {
1437193323Sed          // Big endian - avoid unaligned stores.
1438193323Sed          // TRUNCSTORE:i24 X -> TRUNCSTORE:i16 (srl X, 8), TRUNCSTORE@+2:i8 X
1439193323Sed          // Store the top RoundWidth bits.
1440193323Sed          Hi = DAG.getNode(ISD::SRL, dl, Tmp3.getValueType(), Tmp3,
1441193323Sed                           DAG.getConstant(ExtraWidth, TLI.getShiftAmountTy()));
1442193323Sed          Hi = DAG.getTruncStore(Tmp1, dl, Hi, Tmp2, ST->getSrcValue(),
1443193323Sed                                 SVOffset, RoundVT, isVolatile, Alignment);
1444193323Sed
1445193323Sed          // Store the remaining ExtraWidth bits.
1446193323Sed          IncrementSize = RoundWidth / 8;
1447193323Sed          Tmp2 = DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
1448193323Sed                             DAG.getIntPtrConstant(IncrementSize));
1449193323Sed          Lo = DAG.getTruncStore(Tmp1, dl, Tmp3, Tmp2, ST->getSrcValue(),
1450193323Sed                                 SVOffset + IncrementSize, ExtraVT, isVolatile,
1451193323Sed                                 MinAlign(Alignment, IncrementSize));
1452193323Sed        }
1453193323Sed
1454193323Sed        // The order of the stores doesn't matter.
1455193323Sed        Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi);
1456193323Sed      } else {
1457193323Sed        if (Tmp1 != ST->getChain() || Tmp3 != ST->getValue() ||
1458193323Sed            Tmp2 != ST->getBasePtr())
1459193323Sed          Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp3, Tmp2,
1460193323Sed                                          ST->getOffset());
1461193323Sed
1462193323Sed        switch (TLI.getTruncStoreAction(ST->getValue().getValueType(), StVT)) {
1463193323Sed        default: assert(0 && "This action is not supported yet!");
1464193323Sed        case TargetLowering::Legal:
1465193323Sed          // If this is an unaligned store and the target doesn't support it,
1466193323Sed          // expand it.
1467193323Sed          if (!TLI.allowsUnalignedMemoryAccesses()) {
1468193323Sed            unsigned ABIAlignment = TLI.getTargetData()->
1469193323Sed              getABITypeAlignment(ST->getMemoryVT().getTypeForMVT());
1470193323Sed            if (ST->getAlignment() < ABIAlignment)
1471193323Sed              Result = ExpandUnalignedStore(cast<StoreSDNode>(Result.getNode()), DAG,
1472193323Sed                                            TLI);
1473193323Sed          }
1474193323Sed          break;
1475193323Sed        case TargetLowering::Custom:
1476193323Sed          Result = TLI.LowerOperation(Result, DAG);
1477193323Sed          break;
1478193323Sed        case Expand:
1479193323Sed          // TRUNCSTORE:i16 i32 -> STORE i16
1480193323Sed          assert(isTypeLegal(StVT) && "Do not know how to expand this store!");
1481193323Sed          Tmp3 = DAG.getNode(ISD::TRUNCATE, dl, StVT, Tmp3);
1482193323Sed          Result = DAG.getStore(Tmp1, dl, Tmp3, Tmp2, ST->getSrcValue(),
1483193323Sed                                SVOffset, isVolatile, Alignment);
1484193323Sed          break;
1485193323Sed        }
1486193323Sed      }
1487193323Sed    }
1488193323Sed    break;
1489193323Sed  }
1490193323Sed  }
1491193323Sed  assert(Result.getValueType() == Op.getValueType() &&
1492193323Sed         "Bad legalization!");
1493193323Sed
1494193323Sed  // Make sure that the generated code is itself legal.
1495193323Sed  if (Result != Op)
1496193323Sed    Result = LegalizeOp(Result);
1497193323Sed
1498193323Sed  // Note that LegalizeOp may be reentered even from single-use nodes, which
1499193323Sed  // means that we always must cache transformed nodes.
1500193323Sed  AddLegalizedOperand(Op, Result);
1501193323Sed  return Result;
1502193323Sed}
1503193323Sed
1504193323SedSDValue SelectionDAGLegalize::ExpandExtractFromVectorThroughStack(SDValue Op) {
1505193323Sed  SDValue Vec = Op.getOperand(0);
1506193323Sed  SDValue Idx = Op.getOperand(1);
1507193323Sed  DebugLoc dl = Op.getDebugLoc();
1508193323Sed  // Store the value to a temporary stack slot, then LOAD the returned part.
1509193323Sed  SDValue StackPtr = DAG.CreateStackTemporary(Vec.getValueType());
1510193323Sed  SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, Vec, StackPtr, NULL, 0);
1511193323Sed
1512193323Sed  // Add the offset to the index.
1513193323Sed  unsigned EltSize =
1514193323Sed      Vec.getValueType().getVectorElementType().getSizeInBits()/8;
1515193323Sed  Idx = DAG.getNode(ISD::MUL, dl, Idx.getValueType(), Idx,
1516193323Sed                    DAG.getConstant(EltSize, Idx.getValueType()));
1517193323Sed
1518193323Sed  if (Idx.getValueType().bitsGT(TLI.getPointerTy()))
1519193323Sed    Idx = DAG.getNode(ISD::TRUNCATE, dl, TLI.getPointerTy(), Idx);
1520193323Sed  else
1521193323Sed    Idx = DAG.getNode(ISD::ZERO_EXTEND, dl, TLI.getPointerTy(), Idx);
1522193323Sed
1523193323Sed  StackPtr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(), Idx, StackPtr);
1524193323Sed
1525193323Sed  return DAG.getLoad(Op.getValueType(), dl, Ch, StackPtr, NULL, 0);
1526193323Sed}
1527193323Sed
1528193574SedSDValue SelectionDAGLegalize::ExpandVectorBuildThroughStack(SDNode* Node) {
1529193574Sed  // We can't handle this case efficiently.  Allocate a sufficiently
1530193574Sed  // aligned object on the stack, store each element into it, then load
1531193574Sed  // the result as a vector.
1532193574Sed  // Create the stack frame object.
1533193574Sed  MVT VT = Node->getValueType(0);
1534193574Sed  MVT OpVT = Node->getOperand(0).getValueType();
1535193574Sed  DebugLoc dl = Node->getDebugLoc();
1536193574Sed  SDValue FIPtr = DAG.CreateStackTemporary(VT);
1537193574Sed  int FI = cast<FrameIndexSDNode>(FIPtr.getNode())->getIndex();
1538193574Sed  const Value *SV = PseudoSourceValue::getFixedStack(FI);
1539193574Sed
1540193574Sed  // Emit a store of each element to the stack slot.
1541193574Sed  SmallVector<SDValue, 8> Stores;
1542193574Sed  unsigned TypeByteSize = OpVT.getSizeInBits() / 8;
1543193574Sed  // Store (in the right endianness) the elements to memory.
1544193574Sed  for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
1545193574Sed    // Ignore undef elements.
1546193574Sed    if (Node->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1547193574Sed
1548193574Sed    unsigned Offset = TypeByteSize*i;
1549193574Sed
1550193574Sed    SDValue Idx = DAG.getConstant(Offset, FIPtr.getValueType());
1551193574Sed    Idx = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, Idx);
1552193574Sed
1553193574Sed    Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, Node->getOperand(i),
1554193574Sed                                  Idx, SV, Offset));
1555193574Sed  }
1556193574Sed
1557193574Sed  SDValue StoreChain;
1558193574Sed  if (!Stores.empty())    // Not all undef elements?
1559193574Sed    StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1560193574Sed                             &Stores[0], Stores.size());
1561193574Sed  else
1562193574Sed    StoreChain = DAG.getEntryNode();
1563193574Sed
1564193574Sed  // Result is a load from the stack slot.
1565193574Sed  return DAG.getLoad(VT, dl, StoreChain, FIPtr, SV, 0);
1566193574Sed}
1567193574Sed
1568193323SedSDValue SelectionDAGLegalize::ExpandFCOPYSIGN(SDNode* Node) {
1569193323Sed  DebugLoc dl = Node->getDebugLoc();
1570193323Sed  SDValue Tmp1 = Node->getOperand(0);
1571193323Sed  SDValue Tmp2 = Node->getOperand(1);
1572193323Sed  assert((Tmp2.getValueType() == MVT::f32 ||
1573193323Sed          Tmp2.getValueType() == MVT::f64) &&
1574193323Sed          "Ugly special-cased code!");
1575193323Sed  // Get the sign bit of the RHS.
1576193323Sed  SDValue SignBit;
1577193323Sed  MVT IVT = Tmp2.getValueType() == MVT::f64 ? MVT::i64 : MVT::i32;
1578193323Sed  if (isTypeLegal(IVT)) {
1579193323Sed    SignBit = DAG.getNode(ISD::BIT_CONVERT, dl, IVT, Tmp2);
1580193323Sed  } else {
1581193323Sed    assert(isTypeLegal(TLI.getPointerTy()) &&
1582193323Sed            (TLI.getPointerTy() == MVT::i32 ||
1583193323Sed            TLI.getPointerTy() == MVT::i64) &&
1584193323Sed            "Legal type for load?!");
1585193323Sed    SDValue StackPtr = DAG.CreateStackTemporary(Tmp2.getValueType());
1586193323Sed    SDValue StorePtr = StackPtr, LoadPtr = StackPtr;
1587193323Sed    SDValue Ch =
1588193323Sed        DAG.getStore(DAG.getEntryNode(), dl, Tmp2, StorePtr, NULL, 0);
1589193323Sed    if (Tmp2.getValueType() == MVT::f64 && TLI.isLittleEndian())
1590193323Sed      LoadPtr = DAG.getNode(ISD::ADD, dl, StackPtr.getValueType(),
1591193323Sed                            LoadPtr, DAG.getIntPtrConstant(4));
1592193323Sed    SignBit = DAG.getExtLoad(ISD::SEXTLOAD, dl, TLI.getPointerTy(),
1593193323Sed                              Ch, LoadPtr, NULL, 0, MVT::i32);
1594193323Sed  }
1595193323Sed  SignBit =
1596193323Sed      DAG.getSetCC(dl, TLI.getSetCCResultType(SignBit.getValueType()),
1597193323Sed                    SignBit, DAG.getConstant(0, SignBit.getValueType()),
1598193323Sed                    ISD::SETLT);
1599193323Sed  // Get the absolute value of the result.
1600193323Sed  SDValue AbsVal = DAG.getNode(ISD::FABS, dl, Tmp1.getValueType(), Tmp1);
1601193323Sed  // Select between the nabs and abs value based on the sign bit of
1602193323Sed  // the input.
1603193323Sed  return DAG.getNode(ISD::SELECT, dl, AbsVal.getValueType(), SignBit,
1604193323Sed                     DAG.getNode(ISD::FNEG, dl, AbsVal.getValueType(), AbsVal),
1605193323Sed                     AbsVal);
1606193323Sed}
1607193323Sed
1608193323SedSDValue SelectionDAGLegalize::ExpandDBG_STOPPOINT(SDNode* Node) {
1609193323Sed  DebugLoc dl = Node->getDebugLoc();
1610193323Sed  DwarfWriter *DW = DAG.getDwarfWriter();
1611193323Sed  bool useDEBUG_LOC = TLI.isOperationLegalOrCustom(ISD::DEBUG_LOC,
1612193323Sed                                                    MVT::Other);
1613193323Sed  bool useLABEL = TLI.isOperationLegalOrCustom(ISD::DBG_LABEL, MVT::Other);
1614193323Sed
1615193323Sed  const DbgStopPointSDNode *DSP = cast<DbgStopPointSDNode>(Node);
1616193323Sed  GlobalVariable *CU_GV = cast<GlobalVariable>(DSP->getCompileUnit());
1617193323Sed  if (DW && (useDEBUG_LOC || useLABEL) && !CU_GV->isDeclaration()) {
1618193323Sed    DICompileUnit CU(cast<GlobalVariable>(DSP->getCompileUnit()));
1619193323Sed
1620193323Sed    unsigned Line = DSP->getLine();
1621193323Sed    unsigned Col = DSP->getColumn();
1622193323Sed
1623193323Sed    if (OptLevel == CodeGenOpt::None) {
1624193323Sed      // A bit self-referential to have DebugLoc on Debug_Loc nodes, but it
1625193323Sed      // won't hurt anything.
1626193323Sed      if (useDEBUG_LOC) {
1627193323Sed        return DAG.getNode(ISD::DEBUG_LOC, dl, MVT::Other, Node->getOperand(0),
1628193323Sed                           DAG.getConstant(Line, MVT::i32),
1629193323Sed                           DAG.getConstant(Col, MVT::i32),
1630193323Sed                           DAG.getSrcValue(CU.getGV()));
1631193323Sed      } else {
1632193323Sed        unsigned ID = DW->RecordSourceLine(Line, Col, CU);
1633193323Sed        return DAG.getLabel(ISD::DBG_LABEL, dl, Node->getOperand(0), ID);
1634193323Sed      }
1635193323Sed    }
1636193323Sed  }
1637193323Sed  return Node->getOperand(0);
1638193323Sed}
1639193323Sed
1640193323Sedvoid SelectionDAGLegalize::ExpandDYNAMIC_STACKALLOC(SDNode* Node,
1641193323Sed                                           SmallVectorImpl<SDValue> &Results) {
1642193323Sed  unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
1643193323Sed  assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
1644193323Sed          " not tell us which reg is the stack pointer!");
1645193323Sed  DebugLoc dl = Node->getDebugLoc();
1646193323Sed  MVT VT = Node->getValueType(0);
1647193323Sed  SDValue Tmp1 = SDValue(Node, 0);
1648193323Sed  SDValue Tmp2 = SDValue(Node, 1);
1649193323Sed  SDValue Tmp3 = Node->getOperand(2);
1650193323Sed  SDValue Chain = Tmp1.getOperand(0);
1651193323Sed
1652193323Sed  // Chain the dynamic stack allocation so that it doesn't modify the stack
1653193323Sed  // pointer when other instructions are using the stack.
1654193323Sed  Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true));
1655193323Sed
1656193323Sed  SDValue Size  = Tmp2.getOperand(1);
1657193323Sed  SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
1658193323Sed  Chain = SP.getValue(1);
1659193323Sed  unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
1660193323Sed  unsigned StackAlign =
1661193323Sed    TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
1662193323Sed  if (Align > StackAlign)
1663193323Sed    SP = DAG.getNode(ISD::AND, dl, VT, SP,
1664193323Sed                      DAG.getConstant(-(uint64_t)Align, VT));
1665193323Sed  Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size);       // Value
1666193323Sed  Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1);     // Output chain
1667193323Sed
1668193323Sed  Tmp2 = DAG.getCALLSEQ_END(Chain,  DAG.getIntPtrConstant(0, true),
1669193323Sed                            DAG.getIntPtrConstant(0, true), SDValue());
1670193323Sed
1671193323Sed  Results.push_back(Tmp1);
1672193323Sed  Results.push_back(Tmp2);
1673193323Sed}
1674193323Sed
1675193323Sed/// LegalizeSetCCCondCode - Legalize a SETCC with given LHS and RHS and
1676193323Sed/// condition code CC on the current target. This routine assumes LHS and rHS
1677193323Sed/// have already been legalized by LegalizeSetCCOperands. It expands SETCC with
1678193323Sed/// illegal condition code into AND / OR of multiple SETCC values.
1679193323Sedvoid SelectionDAGLegalize::LegalizeSetCCCondCode(MVT VT,
1680193323Sed                                                 SDValue &LHS, SDValue &RHS,
1681193323Sed                                                 SDValue &CC,
1682193323Sed                                                 DebugLoc dl) {
1683193323Sed  MVT OpVT = LHS.getValueType();
1684193323Sed  ISD::CondCode CCCode = cast<CondCodeSDNode>(CC)->get();
1685193323Sed  switch (TLI.getCondCodeAction(CCCode, OpVT)) {
1686193323Sed  default: assert(0 && "Unknown condition code action!");
1687193323Sed  case TargetLowering::Legal:
1688193323Sed    // Nothing to do.
1689193323Sed    break;
1690193323Sed  case TargetLowering::Expand: {
1691193323Sed    ISD::CondCode CC1 = ISD::SETCC_INVALID, CC2 = ISD::SETCC_INVALID;
1692193323Sed    unsigned Opc = 0;
1693193323Sed    switch (CCCode) {
1694193323Sed    default: assert(0 && "Don't know how to expand this condition!"); abort();
1695193323Sed    case ISD::SETOEQ: CC1 = ISD::SETEQ; CC2 = ISD::SETO;  Opc = ISD::AND; break;
1696193323Sed    case ISD::SETOGT: CC1 = ISD::SETGT; CC2 = ISD::SETO;  Opc = ISD::AND; break;
1697193323Sed    case ISD::SETOGE: CC1 = ISD::SETGE; CC2 = ISD::SETO;  Opc = ISD::AND; break;
1698193323Sed    case ISD::SETOLT: CC1 = ISD::SETLT; CC2 = ISD::SETO;  Opc = ISD::AND; break;
1699193323Sed    case ISD::SETOLE: CC1 = ISD::SETLE; CC2 = ISD::SETO;  Opc = ISD::AND; break;
1700193323Sed    case ISD::SETONE: CC1 = ISD::SETNE; CC2 = ISD::SETO;  Opc = ISD::AND; break;
1701193323Sed    case ISD::SETUEQ: CC1 = ISD::SETEQ; CC2 = ISD::SETUO; Opc = ISD::OR;  break;
1702193323Sed    case ISD::SETUGT: CC1 = ISD::SETGT; CC2 = ISD::SETUO; Opc = ISD::OR;  break;
1703193323Sed    case ISD::SETUGE: CC1 = ISD::SETGE; CC2 = ISD::SETUO; Opc = ISD::OR;  break;
1704193323Sed    case ISD::SETULT: CC1 = ISD::SETLT; CC2 = ISD::SETUO; Opc = ISD::OR;  break;
1705193323Sed    case ISD::SETULE: CC1 = ISD::SETLE; CC2 = ISD::SETUO; Opc = ISD::OR;  break;
1706193323Sed    case ISD::SETUNE: CC1 = ISD::SETNE; CC2 = ISD::SETUO; Opc = ISD::OR;  break;
1707193323Sed    // FIXME: Implement more expansions.
1708193323Sed    }
1709193323Sed
1710193323Sed    SDValue SetCC1 = DAG.getSetCC(dl, VT, LHS, RHS, CC1);
1711193323Sed    SDValue SetCC2 = DAG.getSetCC(dl, VT, LHS, RHS, CC2);
1712193323Sed    LHS = DAG.getNode(Opc, dl, VT, SetCC1, SetCC2);
1713193323Sed    RHS = SDValue();
1714193323Sed    CC  = SDValue();
1715193323Sed    break;
1716193323Sed  }
1717193323Sed  }
1718193323Sed}
1719193323Sed
1720193323Sed/// EmitStackConvert - Emit a store/load combination to the stack.  This stores
1721193323Sed/// SrcOp to a stack slot of type SlotVT, truncating it if needed.  It then does
1722193323Sed/// a load from the stack slot to DestVT, extending it if needed.
1723193323Sed/// The resultant code need not be legal.
1724193323SedSDValue SelectionDAGLegalize::EmitStackConvert(SDValue SrcOp,
1725193323Sed                                               MVT SlotVT,
1726193323Sed                                               MVT DestVT,
1727193323Sed                                               DebugLoc dl) {
1728193323Sed  // Create the stack frame object.
1729193323Sed  unsigned SrcAlign =
1730193323Sed    TLI.getTargetData()->getPrefTypeAlignment(SrcOp.getValueType().
1731193323Sed                                              getTypeForMVT());
1732193323Sed  SDValue FIPtr = DAG.CreateStackTemporary(SlotVT, SrcAlign);
1733193323Sed
1734193323Sed  FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(FIPtr);
1735193323Sed  int SPFI = StackPtrFI->getIndex();
1736193323Sed  const Value *SV = PseudoSourceValue::getFixedStack(SPFI);
1737193323Sed
1738193323Sed  unsigned SrcSize = SrcOp.getValueType().getSizeInBits();
1739193323Sed  unsigned SlotSize = SlotVT.getSizeInBits();
1740193323Sed  unsigned DestSize = DestVT.getSizeInBits();
1741193323Sed  unsigned DestAlign =
1742193323Sed    TLI.getTargetData()->getPrefTypeAlignment(DestVT.getTypeForMVT());
1743193323Sed
1744193323Sed  // Emit a store to the stack slot.  Use a truncstore if the input value is
1745193323Sed  // later than DestVT.
1746193323Sed  SDValue Store;
1747193323Sed
1748193323Sed  if (SrcSize > SlotSize)
1749193323Sed    Store = DAG.getTruncStore(DAG.getEntryNode(), dl, SrcOp, FIPtr,
1750193323Sed                              SV, 0, SlotVT, false, SrcAlign);
1751193323Sed  else {
1752193323Sed    assert(SrcSize == SlotSize && "Invalid store");
1753193323Sed    Store = DAG.getStore(DAG.getEntryNode(), dl, SrcOp, FIPtr,
1754193323Sed                         SV, 0, false, SrcAlign);
1755193323Sed  }
1756193323Sed
1757193323Sed  // Result is a load from the stack slot.
1758193323Sed  if (SlotSize == DestSize)
1759193323Sed    return DAG.getLoad(DestVT, dl, Store, FIPtr, SV, 0, false, DestAlign);
1760193323Sed
1761193323Sed  assert(SlotSize < DestSize && "Unknown extension!");
1762193323Sed  return DAG.getExtLoad(ISD::EXTLOAD, dl, DestVT, Store, FIPtr, SV, 0, SlotVT,
1763193323Sed                        false, DestAlign);
1764193323Sed}
1765193323Sed
1766193323SedSDValue SelectionDAGLegalize::ExpandSCALAR_TO_VECTOR(SDNode *Node) {
1767193323Sed  DebugLoc dl = Node->getDebugLoc();
1768193323Sed  // Create a vector sized/aligned stack slot, store the value to element #0,
1769193323Sed  // then load the whole vector back out.
1770193323Sed  SDValue StackPtr = DAG.CreateStackTemporary(Node->getValueType(0));
1771193323Sed
1772193323Sed  FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(StackPtr);
1773193323Sed  int SPFI = StackPtrFI->getIndex();
1774193323Sed
1775193323Sed  SDValue Ch = DAG.getTruncStore(DAG.getEntryNode(), dl, Node->getOperand(0),
1776193323Sed                                 StackPtr,
1777193323Sed                                 PseudoSourceValue::getFixedStack(SPFI), 0,
1778193323Sed                                 Node->getValueType(0).getVectorElementType());
1779193323Sed  return DAG.getLoad(Node->getValueType(0), dl, Ch, StackPtr,
1780193323Sed                     PseudoSourceValue::getFixedStack(SPFI), 0);
1781193323Sed}
1782193323Sed
1783193323Sed
1784193323Sed/// ExpandBUILD_VECTOR - Expand a BUILD_VECTOR node on targets that don't
1785193323Sed/// support the operation, but do support the resultant vector type.
1786193323SedSDValue SelectionDAGLegalize::ExpandBUILD_VECTOR(SDNode *Node) {
1787193323Sed  unsigned NumElems = Node->getNumOperands();
1788193323Sed  SDValue SplatValue = Node->getOperand(0);
1789193323Sed  DebugLoc dl = Node->getDebugLoc();
1790193323Sed  MVT VT = Node->getValueType(0);
1791193323Sed  MVT OpVT = SplatValue.getValueType();
1792193323Sed  MVT EltVT = VT.getVectorElementType();
1793193323Sed
1794193323Sed  // If the only non-undef value is the low element, turn this into a
1795193323Sed  // SCALAR_TO_VECTOR node.  If this is { X, X, X, X }, determine X.
1796193323Sed  bool isOnlyLowElement = true;
1797193323Sed
1798193323Sed  // FIXME: it would be far nicer to change this into map<SDValue,uint64_t>
1799193323Sed  // and use a bitmask instead of a list of elements.
1800193323Sed  // FIXME: this doesn't treat <0, u, 0, u> for example, as a splat.
1801193323Sed  std::map<SDValue, std::vector<unsigned> > Values;
1802193323Sed  Values[SplatValue].push_back(0);
1803193323Sed  bool isConstant = true;
1804193323Sed  if (!isa<ConstantFPSDNode>(SplatValue) && !isa<ConstantSDNode>(SplatValue) &&
1805193323Sed      SplatValue.getOpcode() != ISD::UNDEF)
1806193323Sed    isConstant = false;
1807193323Sed
1808193323Sed  for (unsigned i = 1; i < NumElems; ++i) {
1809193323Sed    SDValue V = Node->getOperand(i);
1810193323Sed    Values[V].push_back(i);
1811193323Sed    if (V.getOpcode() != ISD::UNDEF)
1812193323Sed      isOnlyLowElement = false;
1813193323Sed    if (SplatValue != V)
1814193323Sed      SplatValue = SDValue(0, 0);
1815193323Sed
1816193323Sed    // If this isn't a constant element or an undef, we can't use a constant
1817193323Sed    // pool load.
1818193323Sed    if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V) &&
1819193323Sed        V.getOpcode() != ISD::UNDEF)
1820193323Sed      isConstant = false;
1821193323Sed  }
1822193323Sed
1823193323Sed  if (isOnlyLowElement) {
1824193323Sed    // If the low element is an undef too, then this whole things is an undef.
1825193323Sed    if (Node->getOperand(0).getOpcode() == ISD::UNDEF)
1826193323Sed      return DAG.getUNDEF(VT);
1827193323Sed    // Otherwise, turn this into a scalar_to_vector node.
1828193323Sed    return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Node->getOperand(0));
1829193323Sed  }
1830193323Sed
1831193323Sed  // If all elements are constants, create a load from the constant pool.
1832193323Sed  if (isConstant) {
1833193323Sed    std::vector<Constant*> CV;
1834193323Sed    for (unsigned i = 0, e = NumElems; i != e; ++i) {
1835193323Sed      if (ConstantFPSDNode *V =
1836193323Sed          dyn_cast<ConstantFPSDNode>(Node->getOperand(i))) {
1837193323Sed        CV.push_back(const_cast<ConstantFP *>(V->getConstantFPValue()));
1838193323Sed      } else if (ConstantSDNode *V =
1839193323Sed                 dyn_cast<ConstantSDNode>(Node->getOperand(i))) {
1840193323Sed        CV.push_back(const_cast<ConstantInt *>(V->getConstantIntValue()));
1841193323Sed      } else {
1842193323Sed        assert(Node->getOperand(i).getOpcode() == ISD::UNDEF);
1843193323Sed        const Type *OpNTy = OpVT.getTypeForMVT();
1844193323Sed        CV.push_back(UndefValue::get(OpNTy));
1845193323Sed      }
1846193323Sed    }
1847193323Sed    Constant *CP = ConstantVector::get(CV);
1848193323Sed    SDValue CPIdx = DAG.getConstantPool(CP, TLI.getPointerTy());
1849193323Sed    unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
1850193323Sed    return DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
1851193323Sed                       PseudoSourceValue::getConstantPool(), 0,
1852193323Sed                       false, Alignment);
1853193323Sed  }
1854193323Sed
1855193323Sed  if (SplatValue.getNode()) {   // Splat of one value?
1856193323Sed    // Build the shuffle constant vector: <0, 0, 0, 0>
1857193323Sed    SmallVector<int, 8> ZeroVec(NumElems, 0);
1858193323Sed
1859193323Sed    // If the target supports VECTOR_SHUFFLE and this shuffle mask, use it.
1860193323Sed    if (TLI.isShuffleMaskLegal(ZeroVec, Node->getValueType(0))) {
1861193323Sed      // Get the splatted value into the low element of a vector register.
1862193323Sed      SDValue LowValVec =
1863193323Sed        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, SplatValue);
1864193323Sed
1865193323Sed      // Return shuffle(LowValVec, undef, <0,0,0,0>)
1866193323Sed      return DAG.getVectorShuffle(VT, dl, LowValVec, DAG.getUNDEF(VT),
1867193323Sed                                  &ZeroVec[0]);
1868193323Sed    }
1869193323Sed  }
1870193323Sed
1871193323Sed  // If there are only two unique elements, we may be able to turn this into a
1872193323Sed  // vector shuffle.
1873193323Sed  if (Values.size() == 2) {
1874193323Sed    // Get the two values in deterministic order.
1875193323Sed    SDValue Val1 = Node->getOperand(1);
1876193323Sed    SDValue Val2;
1877193323Sed    std::map<SDValue, std::vector<unsigned> >::iterator MI = Values.begin();
1878193323Sed    if (MI->first != Val1)
1879193323Sed      Val2 = MI->first;
1880193323Sed    else
1881193323Sed      Val2 = (++MI)->first;
1882193323Sed
1883193323Sed    // If Val1 is an undef, make sure it ends up as Val2, to ensure that our
1884193323Sed    // vector shuffle has the undef vector on the RHS.
1885193323Sed    if (Val1.getOpcode() == ISD::UNDEF)
1886193323Sed      std::swap(Val1, Val2);
1887193323Sed
1888193323Sed    // Build the shuffle constant vector: e.g. <0, 4, 0, 4>
1889193323Sed    SmallVector<int, 8> ShuffleMask(NumElems, -1);
1890193323Sed
1891193323Sed    // Set elements of the shuffle mask for Val1.
1892193323Sed    std::vector<unsigned> &Val1Elts = Values[Val1];
1893193323Sed    for (unsigned i = 0, e = Val1Elts.size(); i != e; ++i)
1894193323Sed      ShuffleMask[Val1Elts[i]] = 0;
1895193323Sed
1896193323Sed    // Set elements of the shuffle mask for Val2.
1897193323Sed    std::vector<unsigned> &Val2Elts = Values[Val2];
1898193323Sed    for (unsigned i = 0, e = Val2Elts.size(); i != e; ++i)
1899193323Sed      if (Val2.getOpcode() != ISD::UNDEF)
1900193323Sed        ShuffleMask[Val2Elts[i]] = NumElems;
1901193323Sed
1902193323Sed    // If the target supports SCALAR_TO_VECTOR and this shuffle mask, use it.
1903193323Sed    if (TLI.isOperationLegalOrCustom(ISD::SCALAR_TO_VECTOR, VT) &&
1904193323Sed        TLI.isShuffleMaskLegal(ShuffleMask, VT)) {
1905193323Sed      Val1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Val1);
1906193323Sed      Val2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Val2);
1907193323Sed      return DAG.getVectorShuffle(VT, dl, Val1, Val2, &ShuffleMask[0]);
1908193323Sed    }
1909193323Sed  }
1910193323Sed
1911193574Sed  // Otherwise, we can't handle this case efficiently.
1912193574Sed  return ExpandVectorBuildThroughStack(Node);
1913193323Sed}
1914193323Sed
1915193323Sed// ExpandLibCall - Expand a node into a call to a libcall.  If the result value
1916193323Sed// does not fit into a register, return the lo part and set the hi part to the
1917193323Sed// by-reg argument.  If it does fit into a single register, return the result
1918193323Sed// and leave the Hi part unset.
1919193323SedSDValue SelectionDAGLegalize::ExpandLibCall(RTLIB::Libcall LC, SDNode *Node,
1920193323Sed                                            bool isSigned) {
1921193323Sed  assert(!IsLegalizingCall && "Cannot overlap legalization of calls!");
1922193323Sed  // The input chain to this libcall is the entry node of the function.
1923193323Sed  // Legalizing the call will automatically add the previous call to the
1924193323Sed  // dependence.
1925193323Sed  SDValue InChain = DAG.getEntryNode();
1926193323Sed
1927193323Sed  TargetLowering::ArgListTy Args;
1928193323Sed  TargetLowering::ArgListEntry Entry;
1929193323Sed  for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
1930193323Sed    MVT ArgVT = Node->getOperand(i).getValueType();
1931193323Sed    const Type *ArgTy = ArgVT.getTypeForMVT();
1932193323Sed    Entry.Node = Node->getOperand(i); Entry.Ty = ArgTy;
1933193323Sed    Entry.isSExt = isSigned;
1934193323Sed    Entry.isZExt = !isSigned;
1935193323Sed    Args.push_back(Entry);
1936193323Sed  }
1937193323Sed  SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
1938193323Sed                                         TLI.getPointerTy());
1939193323Sed
1940193323Sed  // Splice the libcall in wherever FindInputOutputChains tells us to.
1941193323Sed  const Type *RetTy = Node->getValueType(0).getTypeForMVT();
1942193323Sed  std::pair<SDValue, SDValue> CallInfo =
1943193323Sed    TLI.LowerCallTo(InChain, RetTy, isSigned, !isSigned, false, false,
1944193323Sed                    CallingConv::C, false, Callee, Args, DAG,
1945193323Sed                    Node->getDebugLoc());
1946193323Sed
1947193323Sed  // Legalize the call sequence, starting with the chain.  This will advance
1948193323Sed  // the LastCALLSEQ_END to the legalized version of the CALLSEQ_END node that
1949193323Sed  // was added by LowerCallTo (guaranteeing proper serialization of calls).
1950193323Sed  LegalizeOp(CallInfo.second);
1951193323Sed  return CallInfo.first;
1952193323Sed}
1953193323Sed
1954193323SedSDValue SelectionDAGLegalize::ExpandFPLibCall(SDNode* Node,
1955193323Sed                                              RTLIB::Libcall Call_F32,
1956193323Sed                                              RTLIB::Libcall Call_F64,
1957193323Sed                                              RTLIB::Libcall Call_F80,
1958193323Sed                                              RTLIB::Libcall Call_PPCF128) {
1959193323Sed  RTLIB::Libcall LC;
1960193323Sed  switch (Node->getValueType(0).getSimpleVT()) {
1961193323Sed  default: assert(0 && "Unexpected request for libcall!");
1962193323Sed  case MVT::f32: LC = Call_F32; break;
1963193323Sed  case MVT::f64: LC = Call_F64; break;
1964193323Sed  case MVT::f80: LC = Call_F80; break;
1965193323Sed  case MVT::ppcf128: LC = Call_PPCF128; break;
1966193323Sed  }
1967193323Sed  return ExpandLibCall(LC, Node, false);
1968193323Sed}
1969193323Sed
1970193323SedSDValue SelectionDAGLegalize::ExpandIntLibCall(SDNode* Node, bool isSigned,
1971193323Sed                                               RTLIB::Libcall Call_I16,
1972193323Sed                                               RTLIB::Libcall Call_I32,
1973193323Sed                                               RTLIB::Libcall Call_I64,
1974193323Sed                                               RTLIB::Libcall Call_I128) {
1975193323Sed  RTLIB::Libcall LC;
1976193323Sed  switch (Node->getValueType(0).getSimpleVT()) {
1977193323Sed  default: assert(0 && "Unexpected request for libcall!");
1978193323Sed  case MVT::i16: LC = Call_I16; break;
1979193323Sed  case MVT::i32: LC = Call_I32; break;
1980193323Sed  case MVT::i64: LC = Call_I64; break;
1981193323Sed  case MVT::i128: LC = Call_I128; break;
1982193323Sed  }
1983193323Sed  return ExpandLibCall(LC, Node, isSigned);
1984193323Sed}
1985193323Sed
1986193323Sed/// ExpandLegalINT_TO_FP - This function is responsible for legalizing a
1987193323Sed/// INT_TO_FP operation of the specified operand when the target requests that
1988193323Sed/// we expand it.  At this point, we know that the result and operand types are
1989193323Sed/// legal for the target.
1990193323SedSDValue SelectionDAGLegalize::ExpandLegalINT_TO_FP(bool isSigned,
1991193323Sed                                                   SDValue Op0,
1992193323Sed                                                   MVT DestVT,
1993193323Sed                                                   DebugLoc dl) {
1994193323Sed  if (Op0.getValueType() == MVT::i32) {
1995193323Sed    // simple 32-bit [signed|unsigned] integer to float/double expansion
1996193323Sed
1997193323Sed    // Get the stack frame index of a 8 byte buffer.
1998193323Sed    SDValue StackSlot = DAG.CreateStackTemporary(MVT::f64);
1999193323Sed
2000193323Sed    // word offset constant for Hi/Lo address computation
2001193323Sed    SDValue WordOff = DAG.getConstant(sizeof(int), TLI.getPointerTy());
2002193323Sed    // set up Hi and Lo (into buffer) address based on endian
2003193323Sed    SDValue Hi = StackSlot;
2004193323Sed    SDValue Lo = DAG.getNode(ISD::ADD, dl,
2005193323Sed                             TLI.getPointerTy(), StackSlot, WordOff);
2006193323Sed    if (TLI.isLittleEndian())
2007193323Sed      std::swap(Hi, Lo);
2008193323Sed
2009193323Sed    // if signed map to unsigned space
2010193323Sed    SDValue Op0Mapped;
2011193323Sed    if (isSigned) {
2012193323Sed      // constant used to invert sign bit (signed to unsigned mapping)
2013193323Sed      SDValue SignBit = DAG.getConstant(0x80000000u, MVT::i32);
2014193323Sed      Op0Mapped = DAG.getNode(ISD::XOR, dl, MVT::i32, Op0, SignBit);
2015193323Sed    } else {
2016193323Sed      Op0Mapped = Op0;
2017193323Sed    }
2018193323Sed    // store the lo of the constructed double - based on integer input
2019193323Sed    SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl,
2020193323Sed                                  Op0Mapped, Lo, NULL, 0);
2021193323Sed    // initial hi portion of constructed double
2022193323Sed    SDValue InitialHi = DAG.getConstant(0x43300000u, MVT::i32);
2023193323Sed    // store the hi of the constructed double - biased exponent
2024193323Sed    SDValue Store2=DAG.getStore(Store1, dl, InitialHi, Hi, NULL, 0);
2025193323Sed    // load the constructed double
2026193323Sed    SDValue Load = DAG.getLoad(MVT::f64, dl, Store2, StackSlot, NULL, 0);
2027193323Sed    // FP constant to bias correct the final result
2028193323Sed    SDValue Bias = DAG.getConstantFP(isSigned ?
2029193323Sed                                     BitsToDouble(0x4330000080000000ULL) :
2030193323Sed                                     BitsToDouble(0x4330000000000000ULL),
2031193323Sed                                     MVT::f64);
2032193323Sed    // subtract the bias
2033193323Sed    SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Load, Bias);
2034193323Sed    // final result
2035193323Sed    SDValue Result;
2036193323Sed    // handle final rounding
2037193323Sed    if (DestVT == MVT::f64) {
2038193323Sed      // do nothing
2039193323Sed      Result = Sub;
2040193323Sed    } else if (DestVT.bitsLT(MVT::f64)) {
2041193323Sed      Result = DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
2042193323Sed                           DAG.getIntPtrConstant(0));
2043193323Sed    } else if (DestVT.bitsGT(MVT::f64)) {
2044193323Sed      Result = DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
2045193323Sed    }
2046193323Sed    return Result;
2047193323Sed  }
2048193323Sed  assert(!isSigned && "Legalize cannot Expand SINT_TO_FP for i64 yet");
2049193323Sed  SDValue Tmp1 = DAG.getNode(ISD::SINT_TO_FP, dl, DestVT, Op0);
2050193323Sed
2051193323Sed  SDValue SignSet = DAG.getSetCC(dl, TLI.getSetCCResultType(Op0.getValueType()),
2052193323Sed                                 Op0, DAG.getConstant(0, Op0.getValueType()),
2053193323Sed                                 ISD::SETLT);
2054193323Sed  SDValue Zero = DAG.getIntPtrConstant(0), Four = DAG.getIntPtrConstant(4);
2055193323Sed  SDValue CstOffset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(),
2056193323Sed                                    SignSet, Four, Zero);
2057193323Sed
2058193323Sed  // If the sign bit of the integer is set, the large number will be treated
2059193323Sed  // as a negative number.  To counteract this, the dynamic code adds an
2060193323Sed  // offset depending on the data type.
2061193323Sed  uint64_t FF;
2062193323Sed  switch (Op0.getValueType().getSimpleVT()) {
2063193323Sed  default: assert(0 && "Unsupported integer type!");
2064193323Sed  case MVT::i8 : FF = 0x43800000ULL; break;  // 2^8  (as a float)
2065193323Sed  case MVT::i16: FF = 0x47800000ULL; break;  // 2^16 (as a float)
2066193323Sed  case MVT::i32: FF = 0x4F800000ULL; break;  // 2^32 (as a float)
2067193323Sed  case MVT::i64: FF = 0x5F800000ULL; break;  // 2^64 (as a float)
2068193323Sed  }
2069193323Sed  if (TLI.isLittleEndian()) FF <<= 32;
2070193323Sed  Constant *FudgeFactor = ConstantInt::get(Type::Int64Ty, FF);
2071193323Sed
2072193323Sed  SDValue CPIdx = DAG.getConstantPool(FudgeFactor, TLI.getPointerTy());
2073193323Sed  unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
2074193323Sed  CPIdx = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(), CPIdx, CstOffset);
2075193323Sed  Alignment = std::min(Alignment, 4u);
2076193323Sed  SDValue FudgeInReg;
2077193323Sed  if (DestVT == MVT::f32)
2078193323Sed    FudgeInReg = DAG.getLoad(MVT::f32, dl, DAG.getEntryNode(), CPIdx,
2079193323Sed                             PseudoSourceValue::getConstantPool(), 0,
2080193323Sed                             false, Alignment);
2081193323Sed  else {
2082193323Sed    FudgeInReg =
2083193323Sed      LegalizeOp(DAG.getExtLoad(ISD::EXTLOAD, dl, DestVT,
2084193323Sed                                DAG.getEntryNode(), CPIdx,
2085193323Sed                                PseudoSourceValue::getConstantPool(), 0,
2086193323Sed                                MVT::f32, false, Alignment));
2087193323Sed  }
2088193323Sed
2089193323Sed  return DAG.getNode(ISD::FADD, dl, DestVT, Tmp1, FudgeInReg);
2090193323Sed}
2091193323Sed
2092193323Sed/// PromoteLegalINT_TO_FP - This function is responsible for legalizing a
2093193323Sed/// *INT_TO_FP operation of the specified operand when the target requests that
2094193323Sed/// we promote it.  At this point, we know that the result and operand types are
2095193323Sed/// legal for the target, and that there is a legal UINT_TO_FP or SINT_TO_FP
2096193323Sed/// operation that takes a larger input.
2097193323SedSDValue SelectionDAGLegalize::PromoteLegalINT_TO_FP(SDValue LegalOp,
2098193323Sed                                                    MVT DestVT,
2099193323Sed                                                    bool isSigned,
2100193323Sed                                                    DebugLoc dl) {
2101193323Sed  // First step, figure out the appropriate *INT_TO_FP operation to use.
2102193323Sed  MVT NewInTy = LegalOp.getValueType();
2103193323Sed
2104193323Sed  unsigned OpToUse = 0;
2105193323Sed
2106193323Sed  // Scan for the appropriate larger type to use.
2107193323Sed  while (1) {
2108193323Sed    NewInTy = (MVT::SimpleValueType)(NewInTy.getSimpleVT()+1);
2109193323Sed    assert(NewInTy.isInteger() && "Ran out of possibilities!");
2110193323Sed
2111193323Sed    // If the target supports SINT_TO_FP of this type, use it.
2112193323Sed    if (TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, NewInTy)) {
2113193323Sed      OpToUse = ISD::SINT_TO_FP;
2114193323Sed      break;
2115193323Sed    }
2116193323Sed    if (isSigned) continue;
2117193323Sed
2118193323Sed    // If the target supports UINT_TO_FP of this type, use it.
2119193323Sed    if (TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, NewInTy)) {
2120193323Sed      OpToUse = ISD::UINT_TO_FP;
2121193323Sed      break;
2122193323Sed    }
2123193323Sed
2124193323Sed    // Otherwise, try a larger type.
2125193323Sed  }
2126193323Sed
2127193323Sed  // Okay, we found the operation and type to use.  Zero extend our input to the
2128193323Sed  // desired type then run the operation on it.
2129193323Sed  return DAG.getNode(OpToUse, dl, DestVT,
2130193323Sed                     DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
2131193323Sed                                 dl, NewInTy, LegalOp));
2132193323Sed}
2133193323Sed
2134193323Sed/// PromoteLegalFP_TO_INT - This function is responsible for legalizing a
2135193323Sed/// FP_TO_*INT operation of the specified operand when the target requests that
2136193323Sed/// we promote it.  At this point, we know that the result and operand types are
2137193323Sed/// legal for the target, and that there is a legal FP_TO_UINT or FP_TO_SINT
2138193323Sed/// operation that returns a larger result.
2139193323SedSDValue SelectionDAGLegalize::PromoteLegalFP_TO_INT(SDValue LegalOp,
2140193323Sed                                                    MVT DestVT,
2141193323Sed                                                    bool isSigned,
2142193323Sed                                                    DebugLoc dl) {
2143193323Sed  // First step, figure out the appropriate FP_TO*INT operation to use.
2144193323Sed  MVT NewOutTy = DestVT;
2145193323Sed
2146193323Sed  unsigned OpToUse = 0;
2147193323Sed
2148193323Sed  // Scan for the appropriate larger type to use.
2149193323Sed  while (1) {
2150193323Sed    NewOutTy = (MVT::SimpleValueType)(NewOutTy.getSimpleVT()+1);
2151193323Sed    assert(NewOutTy.isInteger() && "Ran out of possibilities!");
2152193323Sed
2153193323Sed    if (TLI.isOperationLegalOrCustom(ISD::FP_TO_SINT, NewOutTy)) {
2154193323Sed      OpToUse = ISD::FP_TO_SINT;
2155193323Sed      break;
2156193323Sed    }
2157193323Sed
2158193323Sed    if (TLI.isOperationLegalOrCustom(ISD::FP_TO_UINT, NewOutTy)) {
2159193323Sed      OpToUse = ISD::FP_TO_UINT;
2160193323Sed      break;
2161193323Sed    }
2162193323Sed
2163193323Sed    // Otherwise, try a larger type.
2164193323Sed  }
2165193323Sed
2166193323Sed
2167193323Sed  // Okay, we found the operation and type to use.
2168193323Sed  SDValue Operation = DAG.getNode(OpToUse, dl, NewOutTy, LegalOp);
2169193323Sed
2170193323Sed  // Truncate the result of the extended FP_TO_*INT operation to the desired
2171193323Sed  // size.
2172193323Sed  return DAG.getNode(ISD::TRUNCATE, dl, DestVT, Operation);
2173193323Sed}
2174193323Sed
2175193323Sed/// ExpandBSWAP - Open code the operations for BSWAP of the specified operation.
2176193323Sed///
2177193323SedSDValue SelectionDAGLegalize::ExpandBSWAP(SDValue Op, DebugLoc dl) {
2178193323Sed  MVT VT = Op.getValueType();
2179193323Sed  MVT SHVT = TLI.getShiftAmountTy();
2180193323Sed  SDValue Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8;
2181193323Sed  switch (VT.getSimpleVT()) {
2182193323Sed  default: assert(0 && "Unhandled Expand type in BSWAP!"); abort();
2183193323Sed  case MVT::i16:
2184193323Sed    Tmp2 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, SHVT));
2185193323Sed    Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, SHVT));
2186193323Sed    return DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
2187193323Sed  case MVT::i32:
2188193323Sed    Tmp4 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, SHVT));
2189193323Sed    Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, SHVT));
2190193323Sed    Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, SHVT));
2191193323Sed    Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, SHVT));
2192193323Sed    Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3, DAG.getConstant(0xFF0000, VT));
2193193323Sed    Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(0xFF00, VT));
2194193323Sed    Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
2195193323Sed    Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
2196193323Sed    return DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
2197193323Sed  case MVT::i64:
2198193323Sed    Tmp8 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(56, SHVT));
2199193323Sed    Tmp7 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(40, SHVT));
2200193323Sed    Tmp6 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, SHVT));
2201193323Sed    Tmp5 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, SHVT));
2202193323Sed    Tmp4 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, SHVT));
2203193323Sed    Tmp3 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, SHVT));
2204193323Sed    Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(40, SHVT));
2205193323Sed    Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(56, SHVT));
2206193323Sed    Tmp7 = DAG.getNode(ISD::AND, dl, VT, Tmp7, DAG.getConstant(255ULL<<48, VT));
2207193323Sed    Tmp6 = DAG.getNode(ISD::AND, dl, VT, Tmp6, DAG.getConstant(255ULL<<40, VT));
2208193323Sed    Tmp5 = DAG.getNode(ISD::AND, dl, VT, Tmp5, DAG.getConstant(255ULL<<32, VT));
2209193323Sed    Tmp4 = DAG.getNode(ISD::AND, dl, VT, Tmp4, DAG.getConstant(255ULL<<24, VT));
2210193323Sed    Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3, DAG.getConstant(255ULL<<16, VT));
2211193323Sed    Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(255ULL<<8 , VT));
2212193323Sed    Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp7);
2213193323Sed    Tmp6 = DAG.getNode(ISD::OR, dl, VT, Tmp6, Tmp5);
2214193323Sed    Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
2215193323Sed    Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
2216193323Sed    Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp6);
2217193323Sed    Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
2218193323Sed    return DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp4);
2219193323Sed  }
2220193323Sed}
2221193323Sed
2222193323Sed/// ExpandBitCount - Expand the specified bitcount instruction into operations.
2223193323Sed///
2224193323SedSDValue SelectionDAGLegalize::ExpandBitCount(unsigned Opc, SDValue Op,
2225193323Sed                                             DebugLoc dl) {
2226193323Sed  switch (Opc) {
2227193323Sed  default: assert(0 && "Cannot expand this yet!");
2228193323Sed  case ISD::CTPOP: {
2229193323Sed    static const uint64_t mask[6] = {
2230193323Sed      0x5555555555555555ULL, 0x3333333333333333ULL,
2231193323Sed      0x0F0F0F0F0F0F0F0FULL, 0x00FF00FF00FF00FFULL,
2232193323Sed      0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL
2233193323Sed    };
2234193323Sed    MVT VT = Op.getValueType();
2235193323Sed    MVT ShVT = TLI.getShiftAmountTy();
2236193323Sed    unsigned len = VT.getSizeInBits();
2237193323Sed    for (unsigned i = 0; (1U << i) <= (len / 2); ++i) {
2238193323Sed      //x = (x & mask[i][len/8]) + (x >> (1 << i) & mask[i][len/8])
2239193323Sed      unsigned EltSize = VT.isVector() ?
2240193323Sed        VT.getVectorElementType().getSizeInBits() : len;
2241193323Sed      SDValue Tmp2 = DAG.getConstant(APInt(EltSize, mask[i]), VT);
2242193323Sed      SDValue Tmp3 = DAG.getConstant(1ULL << i, ShVT);
2243193323Sed      Op = DAG.getNode(ISD::ADD, dl, VT,
2244193323Sed                       DAG.getNode(ISD::AND, dl, VT, Op, Tmp2),
2245193323Sed                       DAG.getNode(ISD::AND, dl, VT,
2246193323Sed                                   DAG.getNode(ISD::SRL, dl, VT, Op, Tmp3),
2247193323Sed                                   Tmp2));
2248193323Sed    }
2249193323Sed    return Op;
2250193323Sed  }
2251193323Sed  case ISD::CTLZ: {
2252193323Sed    // for now, we do this:
2253193323Sed    // x = x | (x >> 1);
2254193323Sed    // x = x | (x >> 2);
2255193323Sed    // ...
2256193323Sed    // x = x | (x >>16);
2257193323Sed    // x = x | (x >>32); // for 64-bit input
2258193323Sed    // return popcount(~x);
2259193323Sed    //
2260193323Sed    // but see also: http://www.hackersdelight.org/HDcode/nlz.cc
2261193323Sed    MVT VT = Op.getValueType();
2262193323Sed    MVT ShVT = TLI.getShiftAmountTy();
2263193323Sed    unsigned len = VT.getSizeInBits();
2264193323Sed    for (unsigned i = 0; (1U << i) <= (len / 2); ++i) {
2265193323Sed      SDValue Tmp3 = DAG.getConstant(1ULL << i, ShVT);
2266193323Sed      Op = DAG.getNode(ISD::OR, dl, VT, Op,
2267193323Sed                       DAG.getNode(ISD::SRL, dl, VT, Op, Tmp3));
2268193323Sed    }
2269193323Sed    Op = DAG.getNOT(dl, Op, VT);
2270193323Sed    return DAG.getNode(ISD::CTPOP, dl, VT, Op);
2271193323Sed  }
2272193323Sed  case ISD::CTTZ: {
2273193323Sed    // for now, we use: { return popcount(~x & (x - 1)); }
2274193323Sed    // unless the target has ctlz but not ctpop, in which case we use:
2275193323Sed    // { return 32 - nlz(~x & (x-1)); }
2276193323Sed    // see also http://www.hackersdelight.org/HDcode/ntz.cc
2277193323Sed    MVT VT = Op.getValueType();
2278193323Sed    SDValue Tmp3 = DAG.getNode(ISD::AND, dl, VT,
2279193323Sed                               DAG.getNOT(dl, Op, VT),
2280193323Sed                               DAG.getNode(ISD::SUB, dl, VT, Op,
2281193323Sed                                           DAG.getConstant(1, VT)));
2282193323Sed    // If ISD::CTLZ is legal and CTPOP isn't, then do that instead.
2283193323Sed    if (!TLI.isOperationLegalOrCustom(ISD::CTPOP, VT) &&
2284193323Sed        TLI.isOperationLegalOrCustom(ISD::CTLZ, VT))
2285193323Sed      return DAG.getNode(ISD::SUB, dl, VT,
2286193323Sed                         DAG.getConstant(VT.getSizeInBits(), VT),
2287193323Sed                         DAG.getNode(ISD::CTLZ, dl, VT, Tmp3));
2288193323Sed    return DAG.getNode(ISD::CTPOP, dl, VT, Tmp3);
2289193323Sed  }
2290193323Sed  }
2291193323Sed}
2292193323Sed
2293193323Sedvoid SelectionDAGLegalize::ExpandNode(SDNode *Node,
2294193323Sed                                      SmallVectorImpl<SDValue> &Results) {
2295193323Sed  DebugLoc dl = Node->getDebugLoc();
2296193323Sed  SDValue Tmp1, Tmp2, Tmp3, Tmp4;
2297193323Sed  switch (Node->getOpcode()) {
2298193323Sed  case ISD::CTPOP:
2299193323Sed  case ISD::CTLZ:
2300193323Sed  case ISD::CTTZ:
2301193323Sed    Tmp1 = ExpandBitCount(Node->getOpcode(), Node->getOperand(0), dl);
2302193323Sed    Results.push_back(Tmp1);
2303193323Sed    break;
2304193323Sed  case ISD::BSWAP:
2305193323Sed    Results.push_back(ExpandBSWAP(Node->getOperand(0), dl));
2306193323Sed    break;
2307193323Sed  case ISD::FRAMEADDR:
2308193323Sed  case ISD::RETURNADDR:
2309193323Sed  case ISD::FRAME_TO_ARGS_OFFSET:
2310193323Sed    Results.push_back(DAG.getConstant(0, Node->getValueType(0)));
2311193323Sed    break;
2312193323Sed  case ISD::FLT_ROUNDS_:
2313193323Sed    Results.push_back(DAG.getConstant(1, Node->getValueType(0)));
2314193323Sed    break;
2315193323Sed  case ISD::EH_RETURN:
2316193323Sed  case ISD::DECLARE:
2317193323Sed  case ISD::DBG_LABEL:
2318193323Sed  case ISD::EH_LABEL:
2319193323Sed  case ISD::PREFETCH:
2320193323Sed  case ISD::MEMBARRIER:
2321193323Sed  case ISD::VAEND:
2322193323Sed    Results.push_back(Node->getOperand(0));
2323193323Sed    break;
2324193323Sed  case ISD::DBG_STOPPOINT:
2325193323Sed    Results.push_back(ExpandDBG_STOPPOINT(Node));
2326193323Sed    break;
2327193323Sed  case ISD::DYNAMIC_STACKALLOC:
2328193323Sed    ExpandDYNAMIC_STACKALLOC(Node, Results);
2329193323Sed    break;
2330193323Sed  case ISD::MERGE_VALUES:
2331193323Sed    for (unsigned i = 0; i < Node->getNumValues(); i++)
2332193323Sed      Results.push_back(Node->getOperand(i));
2333193323Sed    break;
2334193323Sed  case ISD::UNDEF: {
2335193323Sed    MVT VT = Node->getValueType(0);
2336193323Sed    if (VT.isInteger())
2337193323Sed      Results.push_back(DAG.getConstant(0, VT));
2338193323Sed    else if (VT.isFloatingPoint())
2339193323Sed      Results.push_back(DAG.getConstantFP(0, VT));
2340193323Sed    else
2341193323Sed      assert(0 && "Unknown value type!");
2342193323Sed    break;
2343193323Sed  }
2344193323Sed  case ISD::TRAP: {
2345193323Sed    // If this operation is not supported, lower it to 'abort()' call
2346193323Sed    TargetLowering::ArgListTy Args;
2347193323Sed    std::pair<SDValue, SDValue> CallResult =
2348193323Sed      TLI.LowerCallTo(Node->getOperand(0), Type::VoidTy,
2349193323Sed                      false, false, false, false, CallingConv::C, false,
2350193323Sed                      DAG.getExternalSymbol("abort", TLI.getPointerTy()),
2351193323Sed                      Args, DAG, dl);
2352193323Sed    Results.push_back(CallResult.second);
2353193323Sed    break;
2354193323Sed  }
2355193323Sed  case ISD::FP_ROUND:
2356193323Sed  case ISD::BIT_CONVERT:
2357193323Sed    Tmp1 = EmitStackConvert(Node->getOperand(0), Node->getValueType(0),
2358193323Sed                            Node->getValueType(0), dl);
2359193323Sed    Results.push_back(Tmp1);
2360193323Sed    break;
2361193323Sed  case ISD::FP_EXTEND:
2362193323Sed    Tmp1 = EmitStackConvert(Node->getOperand(0),
2363193323Sed                            Node->getOperand(0).getValueType(),
2364193323Sed                            Node->getValueType(0), dl);
2365193323Sed    Results.push_back(Tmp1);
2366193323Sed    break;
2367193323Sed  case ISD::SIGN_EXTEND_INREG: {
2368193323Sed    // NOTE: we could fall back on load/store here too for targets without
2369193323Sed    // SAR.  However, it is doubtful that any exist.
2370193323Sed    MVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
2371193323Sed    unsigned BitsDiff = Node->getValueType(0).getSizeInBits() -
2372193323Sed                        ExtraVT.getSizeInBits();
2373193323Sed    SDValue ShiftCst = DAG.getConstant(BitsDiff, TLI.getShiftAmountTy());
2374193323Sed    Tmp1 = DAG.getNode(ISD::SHL, dl, Node->getValueType(0),
2375193323Sed                       Node->getOperand(0), ShiftCst);
2376193323Sed    Tmp1 = DAG.getNode(ISD::SRA, dl, Node->getValueType(0), Tmp1, ShiftCst);
2377193323Sed    Results.push_back(Tmp1);
2378193323Sed    break;
2379193323Sed  }
2380193323Sed  case ISD::FP_ROUND_INREG: {
2381193323Sed    // The only way we can lower this is to turn it into a TRUNCSTORE,
2382193323Sed    // EXTLOAD pair, targetting a temporary location (a stack slot).
2383193323Sed
2384193323Sed    // NOTE: there is a choice here between constantly creating new stack
2385193323Sed    // slots and always reusing the same one.  We currently always create
2386193323Sed    // new ones, as reuse may inhibit scheduling.
2387193323Sed    MVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
2388193323Sed    Tmp1 = EmitStackConvert(Node->getOperand(0), ExtraVT,
2389193323Sed                            Node->getValueType(0), dl);
2390193323Sed    Results.push_back(Tmp1);
2391193323Sed    break;
2392193323Sed  }
2393193323Sed  case ISD::SINT_TO_FP:
2394193323Sed  case ISD::UINT_TO_FP:
2395193323Sed    Tmp1 = ExpandLegalINT_TO_FP(Node->getOpcode() == ISD::SINT_TO_FP,
2396193323Sed                                Node->getOperand(0), Node->getValueType(0), dl);
2397193323Sed    Results.push_back(Tmp1);
2398193323Sed    break;
2399193323Sed  case ISD::FP_TO_UINT: {
2400193323Sed    SDValue True, False;
2401193323Sed    MVT VT =  Node->getOperand(0).getValueType();
2402193323Sed    MVT NVT = Node->getValueType(0);
2403193323Sed    const uint64_t zero[] = {0, 0};
2404193323Sed    APFloat apf = APFloat(APInt(VT.getSizeInBits(), 2, zero));
2405193323Sed    APInt x = APInt::getSignBit(NVT.getSizeInBits());
2406193323Sed    (void)apf.convertFromAPInt(x, false, APFloat::rmNearestTiesToEven);
2407193323Sed    Tmp1 = DAG.getConstantFP(apf, VT);
2408193323Sed    Tmp2 = DAG.getSetCC(dl, TLI.getSetCCResultType(VT),
2409193323Sed                        Node->getOperand(0),
2410193323Sed                        Tmp1, ISD::SETLT);
2411193323Sed    True = DAG.getNode(ISD::FP_TO_SINT, dl, NVT, Node->getOperand(0));
2412193323Sed    False = DAG.getNode(ISD::FP_TO_SINT, dl, NVT,
2413193323Sed                        DAG.getNode(ISD::FSUB, dl, VT,
2414193323Sed                                    Node->getOperand(0), Tmp1));
2415193323Sed    False = DAG.getNode(ISD::XOR, dl, NVT, False,
2416193323Sed                        DAG.getConstant(x, NVT));
2417193323Sed    Tmp1 = DAG.getNode(ISD::SELECT, dl, NVT, Tmp2, True, False);
2418193323Sed    Results.push_back(Tmp1);
2419193323Sed    break;
2420193323Sed  }
2421193323Sed  case ISD::VAARG: {
2422193323Sed    const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2423193323Sed    MVT VT = Node->getValueType(0);
2424193323Sed    Tmp1 = Node->getOperand(0);
2425193323Sed    Tmp2 = Node->getOperand(1);
2426193323Sed    SDValue VAList = DAG.getLoad(TLI.getPointerTy(), dl, Tmp1, Tmp2, V, 0);
2427193323Sed    // Increment the pointer, VAList, to the next vaarg
2428193323Sed    Tmp3 = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(), VAList,
2429193323Sed                       DAG.getConstant(TLI.getTargetData()->
2430193323Sed                                       getTypeAllocSize(VT.getTypeForMVT()),
2431193323Sed                                       TLI.getPointerTy()));
2432193323Sed    // Store the incremented VAList to the legalized pointer
2433193323Sed    Tmp3 = DAG.getStore(VAList.getValue(1), dl, Tmp3, Tmp2, V, 0);
2434193323Sed    // Load the actual argument out of the pointer VAList
2435193323Sed    Results.push_back(DAG.getLoad(VT, dl, Tmp3, VAList, NULL, 0));
2436193323Sed    Results.push_back(Results[0].getValue(1));
2437193323Sed    break;
2438193323Sed  }
2439193323Sed  case ISD::VACOPY: {
2440193323Sed    // This defaults to loading a pointer from the input and storing it to the
2441193323Sed    // output, returning the chain.
2442193323Sed    const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
2443193323Sed    const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
2444193323Sed    Tmp1 = DAG.getLoad(TLI.getPointerTy(), dl, Node->getOperand(0),
2445193323Sed                       Node->getOperand(2), VS, 0);
2446193323Sed    Tmp1 = DAG.getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1), VD, 0);
2447193323Sed    Results.push_back(Tmp1);
2448193323Sed    break;
2449193323Sed  }
2450193323Sed  case ISD::EXTRACT_VECTOR_ELT:
2451193323Sed    if (Node->getOperand(0).getValueType().getVectorNumElements() == 1)
2452193323Sed      // This must be an access of the only element.  Return it.
2453193323Sed      Tmp1 = DAG.getNode(ISD::BIT_CONVERT, dl, Node->getValueType(0),
2454193323Sed                         Node->getOperand(0));
2455193323Sed    else
2456193323Sed      Tmp1 = ExpandExtractFromVectorThroughStack(SDValue(Node, 0));
2457193323Sed    Results.push_back(Tmp1);
2458193323Sed    break;
2459193323Sed  case ISD::EXTRACT_SUBVECTOR:
2460193323Sed    Results.push_back(ExpandExtractFromVectorThroughStack(SDValue(Node, 0)));
2461193323Sed    break;
2462193323Sed  case ISD::CONCAT_VECTORS: {
2463193574Sed    Results.push_back(ExpandVectorBuildThroughStack(Node));
2464193323Sed    break;
2465193323Sed  }
2466193323Sed  case ISD::SCALAR_TO_VECTOR:
2467193323Sed    Results.push_back(ExpandSCALAR_TO_VECTOR(Node));
2468193323Sed    break;
2469193323Sed  case ISD::INSERT_VECTOR_ELT:
2470193323Sed    Results.push_back(ExpandINSERT_VECTOR_ELT(Node->getOperand(0),
2471193323Sed                                              Node->getOperand(1),
2472193323Sed                                              Node->getOperand(2), dl));
2473193323Sed    break;
2474193323Sed  case ISD::VECTOR_SHUFFLE: {
2475193323Sed    SmallVector<int, 8> Mask;
2476193323Sed    cast<ShuffleVectorSDNode>(Node)->getMask(Mask);
2477193323Sed
2478193323Sed    MVT VT = Node->getValueType(0);
2479193323Sed    MVT EltVT = VT.getVectorElementType();
2480193323Sed    unsigned NumElems = VT.getVectorNumElements();
2481193323Sed    SmallVector<SDValue, 8> Ops;
2482193323Sed    for (unsigned i = 0; i != NumElems; ++i) {
2483193323Sed      if (Mask[i] < 0) {
2484193323Sed        Ops.push_back(DAG.getUNDEF(EltVT));
2485193323Sed        continue;
2486193323Sed      }
2487193323Sed      unsigned Idx = Mask[i];
2488193323Sed      if (Idx < NumElems)
2489193323Sed        Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
2490193323Sed                                  Node->getOperand(0),
2491193323Sed                                  DAG.getIntPtrConstant(Idx)));
2492193323Sed      else
2493193323Sed        Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
2494193323Sed                                  Node->getOperand(1),
2495193323Sed                                  DAG.getIntPtrConstant(Idx - NumElems)));
2496193323Sed    }
2497193323Sed    Tmp1 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Ops[0], Ops.size());
2498193323Sed    Results.push_back(Tmp1);
2499193323Sed    break;
2500193323Sed  }
2501193323Sed  case ISD::EXTRACT_ELEMENT: {
2502193323Sed    MVT OpTy = Node->getOperand(0).getValueType();
2503193323Sed    if (cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue()) {
2504193323Sed      // 1 -> Hi
2505193323Sed      Tmp1 = DAG.getNode(ISD::SRL, dl, OpTy, Node->getOperand(0),
2506193323Sed                         DAG.getConstant(OpTy.getSizeInBits()/2,
2507193323Sed                                         TLI.getShiftAmountTy()));
2508193323Sed      Tmp1 = DAG.getNode(ISD::TRUNCATE, dl, Node->getValueType(0), Tmp1);
2509193323Sed    } else {
2510193323Sed      // 0 -> Lo
2511193323Sed      Tmp1 = DAG.getNode(ISD::TRUNCATE, dl, Node->getValueType(0),
2512193323Sed                         Node->getOperand(0));
2513193323Sed    }
2514193323Sed    Results.push_back(Tmp1);
2515193323Sed    break;
2516193323Sed  }
2517193323Sed  case ISD::STACKSAVE:
2518193323Sed    // Expand to CopyFromReg if the target set
2519193323Sed    // StackPointerRegisterToSaveRestore.
2520193323Sed    if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) {
2521193323Sed      Results.push_back(DAG.getCopyFromReg(Node->getOperand(0), dl, SP,
2522193323Sed                                           Node->getValueType(0)));
2523193323Sed      Results.push_back(Results[0].getValue(1));
2524193323Sed    } else {
2525193323Sed      Results.push_back(DAG.getUNDEF(Node->getValueType(0)));
2526193323Sed      Results.push_back(Node->getOperand(0));
2527193323Sed    }
2528193323Sed    break;
2529193323Sed  case ISD::STACKRESTORE:
2530193323Sed    // Expand to CopyToReg if the target set
2531193323Sed    // StackPointerRegisterToSaveRestore.
2532193323Sed    if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) {
2533193323Sed      Results.push_back(DAG.getCopyToReg(Node->getOperand(0), dl, SP,
2534193323Sed                                         Node->getOperand(1)));
2535193323Sed    } else {
2536193323Sed      Results.push_back(Node->getOperand(0));
2537193323Sed    }
2538193323Sed    break;
2539193323Sed  case ISD::FCOPYSIGN:
2540193323Sed    Results.push_back(ExpandFCOPYSIGN(Node));
2541193323Sed    break;
2542193323Sed  case ISD::FNEG:
2543193323Sed    // Expand Y = FNEG(X) ->  Y = SUB -0.0, X
2544193323Sed    Tmp1 = DAG.getConstantFP(-0.0, Node->getValueType(0));
2545193323Sed    Tmp1 = DAG.getNode(ISD::FSUB, dl, Node->getValueType(0), Tmp1,
2546193323Sed                       Node->getOperand(0));
2547193323Sed    Results.push_back(Tmp1);
2548193323Sed    break;
2549193323Sed  case ISD::FABS: {
2550193323Sed    // Expand Y = FABS(X) -> Y = (X >u 0.0) ? X : fneg(X).
2551193323Sed    MVT VT = Node->getValueType(0);
2552193323Sed    Tmp1 = Node->getOperand(0);
2553193323Sed    Tmp2 = DAG.getConstantFP(0.0, VT);
2554193323Sed    Tmp2 = DAG.getSetCC(dl, TLI.getSetCCResultType(Tmp1.getValueType()),
2555193323Sed                        Tmp1, Tmp2, ISD::SETUGT);
2556193323Sed    Tmp3 = DAG.getNode(ISD::FNEG, dl, VT, Tmp1);
2557193323Sed    Tmp1 = DAG.getNode(ISD::SELECT, dl, VT, Tmp2, Tmp1, Tmp3);
2558193323Sed    Results.push_back(Tmp1);
2559193323Sed    break;
2560193323Sed  }
2561193323Sed  case ISD::FSQRT:
2562193323Sed    Results.push_back(ExpandFPLibCall(Node, RTLIB::SQRT_F32, RTLIB::SQRT_F64,
2563193323Sed                                      RTLIB::SQRT_F80, RTLIB::SQRT_PPCF128));
2564193323Sed    break;
2565193323Sed  case ISD::FSIN:
2566193323Sed    Results.push_back(ExpandFPLibCall(Node, RTLIB::SIN_F32, RTLIB::SIN_F64,
2567193323Sed                                      RTLIB::SIN_F80, RTLIB::SIN_PPCF128));
2568193323Sed    break;
2569193323Sed  case ISD::FCOS:
2570193323Sed    Results.push_back(ExpandFPLibCall(Node, RTLIB::COS_F32, RTLIB::COS_F64,
2571193323Sed                                      RTLIB::COS_F80, RTLIB::COS_PPCF128));
2572193323Sed    break;
2573193323Sed  case ISD::FLOG:
2574193323Sed    Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG_F32, RTLIB::LOG_F64,
2575193323Sed                                      RTLIB::LOG_F80, RTLIB::LOG_PPCF128));
2576193323Sed    break;
2577193323Sed  case ISD::FLOG2:
2578193323Sed    Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG2_F32, RTLIB::LOG2_F64,
2579193323Sed                                      RTLIB::LOG2_F80, RTLIB::LOG2_PPCF128));
2580193323Sed    break;
2581193323Sed  case ISD::FLOG10:
2582193323Sed    Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG10_F32, RTLIB::LOG10_F64,
2583193323Sed                                      RTLIB::LOG10_F80, RTLIB::LOG10_PPCF128));
2584193323Sed    break;
2585193323Sed  case ISD::FEXP:
2586193323Sed    Results.push_back(ExpandFPLibCall(Node, RTLIB::EXP_F32, RTLIB::EXP_F64,
2587193323Sed                                      RTLIB::EXP_F80, RTLIB::EXP_PPCF128));
2588193323Sed    break;
2589193323Sed  case ISD::FEXP2:
2590193323Sed    Results.push_back(ExpandFPLibCall(Node, RTLIB::EXP2_F32, RTLIB::EXP2_F64,
2591193323Sed                                      RTLIB::EXP2_F80, RTLIB::EXP2_PPCF128));
2592193323Sed    break;
2593193323Sed  case ISD::FTRUNC:
2594193323Sed    Results.push_back(ExpandFPLibCall(Node, RTLIB::TRUNC_F32, RTLIB::TRUNC_F64,
2595193323Sed                                      RTLIB::TRUNC_F80, RTLIB::TRUNC_PPCF128));
2596193323Sed    break;
2597193323Sed  case ISD::FFLOOR:
2598193323Sed    Results.push_back(ExpandFPLibCall(Node, RTLIB::FLOOR_F32, RTLIB::FLOOR_F64,
2599193323Sed                                      RTLIB::FLOOR_F80, RTLIB::FLOOR_PPCF128));
2600193323Sed    break;
2601193323Sed  case ISD::FCEIL:
2602193323Sed    Results.push_back(ExpandFPLibCall(Node, RTLIB::CEIL_F32, RTLIB::CEIL_F64,
2603193323Sed                                      RTLIB::CEIL_F80, RTLIB::CEIL_PPCF128));
2604193323Sed    break;
2605193323Sed  case ISD::FRINT:
2606193323Sed    Results.push_back(ExpandFPLibCall(Node, RTLIB::RINT_F32, RTLIB::RINT_F64,
2607193323Sed                                      RTLIB::RINT_F80, RTLIB::RINT_PPCF128));
2608193323Sed    break;
2609193323Sed  case ISD::FNEARBYINT:
2610193323Sed    Results.push_back(ExpandFPLibCall(Node, RTLIB::NEARBYINT_F32,
2611193323Sed                                      RTLIB::NEARBYINT_F64,
2612193323Sed                                      RTLIB::NEARBYINT_F80,
2613193323Sed                                      RTLIB::NEARBYINT_PPCF128));
2614193323Sed    break;
2615193323Sed  case ISD::FPOWI:
2616193323Sed    Results.push_back(ExpandFPLibCall(Node, RTLIB::POWI_F32, RTLIB::POWI_F64,
2617193323Sed                                      RTLIB::POWI_F80, RTLIB::POWI_PPCF128));
2618193323Sed    break;
2619193323Sed  case ISD::FPOW:
2620193323Sed    Results.push_back(ExpandFPLibCall(Node, RTLIB::POW_F32, RTLIB::POW_F64,
2621193323Sed                                      RTLIB::POW_F80, RTLIB::POW_PPCF128));
2622193323Sed    break;
2623193323Sed  case ISD::FDIV:
2624193323Sed    Results.push_back(ExpandFPLibCall(Node, RTLIB::DIV_F32, RTLIB::DIV_F64,
2625193323Sed                                      RTLIB::DIV_F80, RTLIB::DIV_PPCF128));
2626193323Sed    break;
2627193323Sed  case ISD::FREM:
2628193323Sed    Results.push_back(ExpandFPLibCall(Node, RTLIB::REM_F32, RTLIB::REM_F64,
2629193323Sed                                      RTLIB::REM_F80, RTLIB::REM_PPCF128));
2630193323Sed    break;
2631193323Sed  case ISD::ConstantFP: {
2632193323Sed    ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Node);
2633193323Sed    // Check to see if this FP immediate is already legal.
2634193323Sed    bool isLegal = false;
2635193323Sed    for (TargetLowering::legal_fpimm_iterator I = TLI.legal_fpimm_begin(),
2636193323Sed            E = TLI.legal_fpimm_end(); I != E; ++I) {
2637193323Sed      if (CFP->isExactlyValue(*I)) {
2638193323Sed        isLegal = true;
2639193323Sed        break;
2640193323Sed      }
2641193323Sed    }
2642193323Sed    // If this is a legal constant, turn it into a TargetConstantFP node.
2643193323Sed    if (isLegal)
2644193323Sed      Results.push_back(SDValue(Node, 0));
2645193323Sed    else
2646193323Sed      Results.push_back(ExpandConstantFP(CFP, true, DAG, TLI));
2647193323Sed    break;
2648193323Sed  }
2649193323Sed  case ISD::EHSELECTION: {
2650193323Sed    unsigned Reg = TLI.getExceptionSelectorRegister();
2651193323Sed    assert(Reg && "Can't expand to unknown register!");
2652193323Sed    Results.push_back(DAG.getCopyFromReg(Node->getOperand(1), dl, Reg,
2653193323Sed                                         Node->getValueType(0)));
2654193323Sed    Results.push_back(Results[0].getValue(1));
2655193323Sed    break;
2656193323Sed  }
2657193323Sed  case ISD::EXCEPTIONADDR: {
2658193323Sed    unsigned Reg = TLI.getExceptionAddressRegister();
2659193323Sed    assert(Reg && "Can't expand to unknown register!");
2660193323Sed    Results.push_back(DAG.getCopyFromReg(Node->getOperand(0), dl, Reg,
2661193323Sed                                         Node->getValueType(0)));
2662193323Sed    Results.push_back(Results[0].getValue(1));
2663193323Sed    break;
2664193323Sed  }
2665193323Sed  case ISD::SUB: {
2666193323Sed    MVT VT = Node->getValueType(0);
2667193323Sed    assert(TLI.isOperationLegalOrCustom(ISD::ADD, VT) &&
2668193323Sed           TLI.isOperationLegalOrCustom(ISD::XOR, VT) &&
2669193323Sed           "Don't know how to expand this subtraction!");
2670193323Sed    Tmp1 = DAG.getNode(ISD::XOR, dl, VT, Node->getOperand(1),
2671193323Sed               DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT));
2672193323Sed    Tmp1 = DAG.getNode(ISD::ADD, dl, VT, Tmp2, DAG.getConstant(1, VT));
2673193323Sed    Results.push_back(DAG.getNode(ISD::ADD, dl, VT, Node->getOperand(0), Tmp1));
2674193323Sed    break;
2675193323Sed  }
2676193323Sed  case ISD::UREM:
2677193323Sed  case ISD::SREM: {
2678193323Sed    MVT VT = Node->getValueType(0);
2679193323Sed    SDVTList VTs = DAG.getVTList(VT, VT);
2680193323Sed    bool isSigned = Node->getOpcode() == ISD::SREM;
2681193323Sed    unsigned DivOpc = isSigned ? ISD::SDIV : ISD::UDIV;
2682193323Sed    unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
2683193323Sed    Tmp2 = Node->getOperand(0);
2684193323Sed    Tmp3 = Node->getOperand(1);
2685193323Sed    if (TLI.isOperationLegalOrCustom(DivRemOpc, VT)) {
2686193323Sed      Tmp1 = DAG.getNode(DivRemOpc, dl, VTs, Tmp2, Tmp3).getValue(1);
2687193323Sed    } else if (TLI.isOperationLegalOrCustom(DivOpc, VT)) {
2688193323Sed      // X % Y -> X-X/Y*Y
2689193323Sed      Tmp1 = DAG.getNode(DivOpc, dl, VT, Tmp2, Tmp3);
2690193323Sed      Tmp1 = DAG.getNode(ISD::MUL, dl, VT, Tmp1, Tmp3);
2691193323Sed      Tmp1 = DAG.getNode(ISD::SUB, dl, VT, Tmp2, Tmp1);
2692193323Sed    } else if (isSigned) {
2693193323Sed      Tmp1 = ExpandIntLibCall(Node, true, RTLIB::SREM_I16, RTLIB::SREM_I32,
2694193323Sed                              RTLIB::SREM_I64, RTLIB::SREM_I128);
2695193323Sed    } else {
2696193323Sed      Tmp1 = ExpandIntLibCall(Node, false, RTLIB::UREM_I16, RTLIB::UREM_I32,
2697193323Sed                              RTLIB::UREM_I64, RTLIB::UREM_I128);
2698193323Sed    }
2699193323Sed    Results.push_back(Tmp1);
2700193323Sed    break;
2701193323Sed  }
2702193323Sed  case ISD::UDIV:
2703193323Sed  case ISD::SDIV: {
2704193323Sed    bool isSigned = Node->getOpcode() == ISD::SDIV;
2705193323Sed    unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
2706193323Sed    MVT VT = Node->getValueType(0);
2707193323Sed    SDVTList VTs = DAG.getVTList(VT, VT);
2708193323Sed    if (TLI.isOperationLegalOrCustom(DivRemOpc, VT))
2709193323Sed      Tmp1 = DAG.getNode(DivRemOpc, dl, VTs, Node->getOperand(0),
2710193323Sed                         Node->getOperand(1));
2711193323Sed    else if (isSigned)
2712193323Sed      Tmp1 = ExpandIntLibCall(Node, true, RTLIB::SDIV_I16, RTLIB::SDIV_I32,
2713193323Sed                              RTLIB::SDIV_I64, RTLIB::SDIV_I128);
2714193323Sed    else
2715193323Sed      Tmp1 = ExpandIntLibCall(Node, false, RTLIB::UDIV_I16, RTLIB::UDIV_I32,
2716193323Sed                              RTLIB::UDIV_I64, RTLIB::UDIV_I128);
2717193323Sed    Results.push_back(Tmp1);
2718193323Sed    break;
2719193323Sed  }
2720193323Sed  case ISD::MULHU:
2721193323Sed  case ISD::MULHS: {
2722193323Sed    unsigned ExpandOpcode = Node->getOpcode() == ISD::MULHU ? ISD::UMUL_LOHI :
2723193323Sed                                                              ISD::SMUL_LOHI;
2724193323Sed    MVT VT = Node->getValueType(0);
2725193323Sed    SDVTList VTs = DAG.getVTList(VT, VT);
2726193323Sed    assert(TLI.isOperationLegalOrCustom(ExpandOpcode, VT) &&
2727193323Sed           "If this wasn't legal, it shouldn't have been created!");
2728193323Sed    Tmp1 = DAG.getNode(ExpandOpcode, dl, VTs, Node->getOperand(0),
2729193323Sed                       Node->getOperand(1));
2730193323Sed    Results.push_back(Tmp1.getValue(1));
2731193323Sed    break;
2732193323Sed  }
2733193323Sed  case ISD::MUL: {
2734193323Sed    MVT VT = Node->getValueType(0);
2735193323Sed    SDVTList VTs = DAG.getVTList(VT, VT);
2736193323Sed    // See if multiply or divide can be lowered using two-result operations.
2737193323Sed    // We just need the low half of the multiply; try both the signed
2738193323Sed    // and unsigned forms. If the target supports both SMUL_LOHI and
2739193323Sed    // UMUL_LOHI, form a preference by checking which forms of plain
2740193323Sed    // MULH it supports.
2741193323Sed    bool HasSMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::SMUL_LOHI, VT);
2742193323Sed    bool HasUMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::UMUL_LOHI, VT);
2743193323Sed    bool HasMULHS = TLI.isOperationLegalOrCustom(ISD::MULHS, VT);
2744193323Sed    bool HasMULHU = TLI.isOperationLegalOrCustom(ISD::MULHU, VT);
2745193323Sed    unsigned OpToUse = 0;
2746193323Sed    if (HasSMUL_LOHI && !HasMULHS) {
2747193323Sed      OpToUse = ISD::SMUL_LOHI;
2748193323Sed    } else if (HasUMUL_LOHI && !HasMULHU) {
2749193323Sed      OpToUse = ISD::UMUL_LOHI;
2750193323Sed    } else if (HasSMUL_LOHI) {
2751193323Sed      OpToUse = ISD::SMUL_LOHI;
2752193323Sed    } else if (HasUMUL_LOHI) {
2753193323Sed      OpToUse = ISD::UMUL_LOHI;
2754193323Sed    }
2755193323Sed    if (OpToUse) {
2756193323Sed      Results.push_back(DAG.getNode(OpToUse, dl, VTs, Node->getOperand(0),
2757193323Sed                                    Node->getOperand(1)));
2758193323Sed      break;
2759193323Sed    }
2760193323Sed    Tmp1 = ExpandIntLibCall(Node, false, RTLIB::MUL_I16, RTLIB::MUL_I32,
2761193323Sed                            RTLIB::MUL_I64, RTLIB::MUL_I128);
2762193323Sed    Results.push_back(Tmp1);
2763193323Sed    break;
2764193323Sed  }
2765193323Sed  case ISD::SADDO:
2766193323Sed  case ISD::SSUBO: {
2767193323Sed    SDValue LHS = Node->getOperand(0);
2768193323Sed    SDValue RHS = Node->getOperand(1);
2769193323Sed    SDValue Sum = DAG.getNode(Node->getOpcode() == ISD::SADDO ?
2770193323Sed                              ISD::ADD : ISD::SUB, dl, LHS.getValueType(),
2771193323Sed                              LHS, RHS);
2772193323Sed    Results.push_back(Sum);
2773193323Sed    MVT OType = Node->getValueType(1);
2774193323Sed
2775193323Sed    SDValue Zero = DAG.getConstant(0, LHS.getValueType());
2776193323Sed
2777193323Sed    //   LHSSign -> LHS >= 0
2778193323Sed    //   RHSSign -> RHS >= 0
2779193323Sed    //   SumSign -> Sum >= 0
2780193323Sed    //
2781193323Sed    //   Add:
2782193323Sed    //   Overflow -> (LHSSign == RHSSign) && (LHSSign != SumSign)
2783193323Sed    //   Sub:
2784193323Sed    //   Overflow -> (LHSSign != RHSSign) && (LHSSign != SumSign)
2785193323Sed    //
2786193323Sed    SDValue LHSSign = DAG.getSetCC(dl, OType, LHS, Zero, ISD::SETGE);
2787193323Sed    SDValue RHSSign = DAG.getSetCC(dl, OType, RHS, Zero, ISD::SETGE);
2788193323Sed    SDValue SignsMatch = DAG.getSetCC(dl, OType, LHSSign, RHSSign,
2789193323Sed                                      Node->getOpcode() == ISD::SADDO ?
2790193323Sed                                      ISD::SETEQ : ISD::SETNE);
2791193323Sed
2792193323Sed    SDValue SumSign = DAG.getSetCC(dl, OType, Sum, Zero, ISD::SETGE);
2793193323Sed    SDValue SumSignNE = DAG.getSetCC(dl, OType, LHSSign, SumSign, ISD::SETNE);
2794193323Sed
2795193323Sed    SDValue Cmp = DAG.getNode(ISD::AND, dl, OType, SignsMatch, SumSignNE);
2796193323Sed    Results.push_back(Cmp);
2797193323Sed    break;
2798193323Sed  }
2799193323Sed  case ISD::UADDO:
2800193323Sed  case ISD::USUBO: {
2801193323Sed    SDValue LHS = Node->getOperand(0);
2802193323Sed    SDValue RHS = Node->getOperand(1);
2803193323Sed    SDValue Sum = DAG.getNode(Node->getOpcode() == ISD::UADDO ?
2804193323Sed                              ISD::ADD : ISD::SUB, dl, LHS.getValueType(),
2805193323Sed                              LHS, RHS);
2806193323Sed    Results.push_back(Sum);
2807193323Sed    Results.push_back(DAG.getSetCC(dl, Node->getValueType(1), Sum, LHS,
2808193323Sed                                   Node->getOpcode () == ISD::UADDO ?
2809193323Sed                                   ISD::SETULT : ISD::SETUGT));
2810193323Sed    break;
2811193323Sed  }
2812193323Sed  case ISD::BUILD_PAIR: {
2813193323Sed    MVT PairTy = Node->getValueType(0);
2814193323Sed    Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, PairTy, Node->getOperand(0));
2815193323Sed    Tmp2 = DAG.getNode(ISD::ANY_EXTEND, dl, PairTy, Node->getOperand(1));
2816193323Sed    Tmp2 = DAG.getNode(ISD::SHL, dl, PairTy, Tmp2,
2817193323Sed                       DAG.getConstant(PairTy.getSizeInBits()/2,
2818193323Sed                                       TLI.getShiftAmountTy()));
2819193323Sed    Results.push_back(DAG.getNode(ISD::OR, dl, PairTy, Tmp1, Tmp2));
2820193323Sed    break;
2821193323Sed  }
2822193323Sed  case ISD::SELECT:
2823193323Sed    Tmp1 = Node->getOperand(0);
2824193323Sed    Tmp2 = Node->getOperand(1);
2825193323Sed    Tmp3 = Node->getOperand(2);
2826193323Sed    if (Tmp1.getOpcode() == ISD::SETCC) {
2827193323Sed      Tmp1 = DAG.getSelectCC(dl, Tmp1.getOperand(0), Tmp1.getOperand(1),
2828193323Sed                             Tmp2, Tmp3,
2829193323Sed                             cast<CondCodeSDNode>(Tmp1.getOperand(2))->get());
2830193323Sed    } else {
2831193323Sed      Tmp1 = DAG.getSelectCC(dl, Tmp1,
2832193323Sed                             DAG.getConstant(0, Tmp1.getValueType()),
2833193323Sed                             Tmp2, Tmp3, ISD::SETNE);
2834193323Sed    }
2835193323Sed    Results.push_back(Tmp1);
2836193323Sed    break;
2837193323Sed  case ISD::BR_JT: {
2838193323Sed    SDValue Chain = Node->getOperand(0);
2839193323Sed    SDValue Table = Node->getOperand(1);
2840193323Sed    SDValue Index = Node->getOperand(2);
2841193323Sed
2842193323Sed    MVT PTy = TLI.getPointerTy();
2843193323Sed    MachineFunction &MF = DAG.getMachineFunction();
2844193323Sed    unsigned EntrySize = MF.getJumpTableInfo()->getEntrySize();
2845193323Sed    Index= DAG.getNode(ISD::MUL, dl, PTy,
2846193323Sed                        Index, DAG.getConstant(EntrySize, PTy));
2847193323Sed    SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
2848193323Sed
2849193323Sed    MVT MemVT = MVT::getIntegerVT(EntrySize * 8);
2850193323Sed    SDValue LD = DAG.getExtLoad(ISD::SEXTLOAD, dl, PTy, Chain, Addr,
2851193323Sed                                PseudoSourceValue::getJumpTable(), 0, MemVT);
2852193323Sed    Addr = LD;
2853193323Sed    if (TLI.getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2854193323Sed      // For PIC, the sequence is:
2855193323Sed      // BRIND(load(Jumptable + index) + RelocBase)
2856193323Sed      // RelocBase can be JumpTable, GOT or some sort of global base.
2857193323Sed      Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr,
2858193323Sed                          TLI.getPICJumpTableRelocBase(Table, DAG));
2859193323Sed    }
2860193323Sed    Tmp1 = DAG.getNode(ISD::BRIND, dl, MVT::Other, LD.getValue(1), Addr);
2861193323Sed    Results.push_back(Tmp1);
2862193323Sed    break;
2863193323Sed  }
2864193323Sed  case ISD::BRCOND:
2865193323Sed    // Expand brcond's setcc into its constituent parts and create a BR_CC
2866193323Sed    // Node.
2867193323Sed    Tmp1 = Node->getOperand(0);
2868193323Sed    Tmp2 = Node->getOperand(1);
2869193323Sed    if (Tmp2.getOpcode() == ISD::SETCC) {
2870193323Sed      Tmp1 = DAG.getNode(ISD::BR_CC, dl, MVT::Other,
2871193323Sed                         Tmp1, Tmp2.getOperand(2),
2872193323Sed                         Tmp2.getOperand(0), Tmp2.getOperand(1),
2873193323Sed                         Node->getOperand(2));
2874193323Sed    } else {
2875193323Sed      Tmp1 = DAG.getNode(ISD::BR_CC, dl, MVT::Other, Tmp1,
2876193323Sed                         DAG.getCondCode(ISD::SETNE), Tmp2,
2877193323Sed                         DAG.getConstant(0, Tmp2.getValueType()),
2878193323Sed                         Node->getOperand(2));
2879193323Sed    }
2880193323Sed    Results.push_back(Tmp1);
2881193323Sed    break;
2882193323Sed  case ISD::SETCC: {
2883193323Sed    Tmp1 = Node->getOperand(0);
2884193323Sed    Tmp2 = Node->getOperand(1);
2885193323Sed    Tmp3 = Node->getOperand(2);
2886193323Sed    LegalizeSetCCCondCode(Node->getValueType(0), Tmp1, Tmp2, Tmp3, dl);
2887193323Sed
2888193323Sed    // If we expanded the SETCC into an AND/OR, return the new node
2889193323Sed    if (Tmp2.getNode() == 0) {
2890193323Sed      Results.push_back(Tmp1);
2891193323Sed      break;
2892193323Sed    }
2893193323Sed
2894193323Sed    // Otherwise, SETCC for the given comparison type must be completely
2895193323Sed    // illegal; expand it into a SELECT_CC.
2896193323Sed    MVT VT = Node->getValueType(0);
2897193323Sed    Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, VT, Tmp1, Tmp2,
2898193323Sed                       DAG.getConstant(1, VT), DAG.getConstant(0, VT), Tmp3);
2899193323Sed    Results.push_back(Tmp1);
2900193323Sed    break;
2901193323Sed  }
2902193323Sed  case ISD::SELECT_CC: {
2903193323Sed    Tmp1 = Node->getOperand(0);   // LHS
2904193323Sed    Tmp2 = Node->getOperand(1);   // RHS
2905193323Sed    Tmp3 = Node->getOperand(2);   // True
2906193323Sed    Tmp4 = Node->getOperand(3);   // False
2907193323Sed    SDValue CC = Node->getOperand(4);
2908193323Sed
2909193323Sed    LegalizeSetCCCondCode(TLI.getSetCCResultType(Tmp1.getValueType()),
2910193323Sed                          Tmp1, Tmp2, CC, dl);
2911193323Sed
2912193323Sed    assert(!Tmp2.getNode() && "Can't legalize SELECT_CC with legal condition!");
2913193323Sed    Tmp2 = DAG.getConstant(0, Tmp1.getValueType());
2914193323Sed    CC = DAG.getCondCode(ISD::SETNE);
2915193323Sed    Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, Node->getValueType(0), Tmp1, Tmp2,
2916193323Sed                       Tmp3, Tmp4, CC);
2917193323Sed    Results.push_back(Tmp1);
2918193323Sed    break;
2919193323Sed  }
2920193323Sed  case ISD::BR_CC: {
2921193323Sed    Tmp1 = Node->getOperand(0);              // Chain
2922193323Sed    Tmp2 = Node->getOperand(2);              // LHS
2923193323Sed    Tmp3 = Node->getOperand(3);              // RHS
2924193323Sed    Tmp4 = Node->getOperand(1);              // CC
2925193323Sed
2926193323Sed    LegalizeSetCCCondCode(TLI.getSetCCResultType(Tmp2.getValueType()),
2927193323Sed                          Tmp2, Tmp3, Tmp4, dl);
2928193323Sed    LastCALLSEQ_END = DAG.getEntryNode();
2929193323Sed
2930193323Sed    assert(!Tmp3.getNode() && "Can't legalize BR_CC with legal condition!");
2931193323Sed    Tmp3 = DAG.getConstant(0, Tmp2.getValueType());
2932193323Sed    Tmp4 = DAG.getCondCode(ISD::SETNE);
2933193323Sed    Tmp1 = DAG.getNode(ISD::BR_CC, dl, Node->getValueType(0), Tmp1, Tmp4, Tmp2,
2934193323Sed                       Tmp3, Node->getOperand(4));
2935193323Sed    Results.push_back(Tmp1);
2936193323Sed    break;
2937193323Sed  }
2938193323Sed  case ISD::GLOBAL_OFFSET_TABLE:
2939193323Sed  case ISD::GlobalAddress:
2940193323Sed  case ISD::GlobalTLSAddress:
2941193323Sed  case ISD::ExternalSymbol:
2942193323Sed  case ISD::ConstantPool:
2943193323Sed  case ISD::JumpTable:
2944193323Sed  case ISD::INTRINSIC_W_CHAIN:
2945193323Sed  case ISD::INTRINSIC_WO_CHAIN:
2946193323Sed  case ISD::INTRINSIC_VOID:
2947193323Sed    // FIXME: Custom lowering for these operations shouldn't return null!
2948193323Sed    for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
2949193323Sed      Results.push_back(SDValue(Node, i));
2950193323Sed    break;
2951193323Sed  }
2952193323Sed}
2953193323Sedvoid SelectionDAGLegalize::PromoteNode(SDNode *Node,
2954193323Sed                                       SmallVectorImpl<SDValue> &Results) {
2955193323Sed  MVT OVT = Node->getValueType(0);
2956193323Sed  if (Node->getOpcode() == ISD::UINT_TO_FP ||
2957193323Sed      Node->getOpcode() == ISD::SINT_TO_FP) {
2958193323Sed    OVT = Node->getOperand(0).getValueType();
2959193323Sed  }
2960193323Sed  MVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
2961193323Sed  DebugLoc dl = Node->getDebugLoc();
2962193323Sed  SDValue Tmp1, Tmp2, Tmp3;
2963193323Sed  switch (Node->getOpcode()) {
2964193323Sed  case ISD::CTTZ:
2965193323Sed  case ISD::CTLZ:
2966193323Sed  case ISD::CTPOP:
2967193323Sed    // Zero extend the argument.
2968193323Sed    Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Node->getOperand(0));
2969193323Sed    // Perform the larger operation.
2970193323Sed    Tmp1 = DAG.getNode(Node->getOpcode(), dl, Node->getValueType(0), Tmp1);
2971193323Sed    if (Node->getOpcode() == ISD::CTTZ) {
2972193323Sed      //if Tmp1 == sizeinbits(NVT) then Tmp1 = sizeinbits(Old VT)
2973193323Sed      Tmp2 = DAG.getSetCC(dl, TLI.getSetCCResultType(Tmp1.getValueType()),
2974193323Sed                          Tmp1, DAG.getConstant(NVT.getSizeInBits(), NVT),
2975193323Sed                          ISD::SETEQ);
2976193323Sed      Tmp1 = DAG.getNode(ISD::SELECT, dl, NVT, Tmp2,
2977193323Sed                          DAG.getConstant(OVT.getSizeInBits(), NVT), Tmp1);
2978193323Sed    } else if (Node->getOpcode() == ISD::CTLZ) {
2979193323Sed      // Tmp1 = Tmp1 - (sizeinbits(NVT) - sizeinbits(Old VT))
2980193323Sed      Tmp1 = DAG.getNode(ISD::SUB, dl, NVT, Tmp1,
2981193323Sed                          DAG.getConstant(NVT.getSizeInBits() -
2982193323Sed                                          OVT.getSizeInBits(), NVT));
2983193323Sed    }
2984193323Sed    Results.push_back(Tmp1);
2985193323Sed    break;
2986193323Sed  case ISD::BSWAP: {
2987193323Sed    unsigned DiffBits = NVT.getSizeInBits() - OVT.getSizeInBits();
2988193323Sed    Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Tmp1);
2989193323Sed    Tmp1 = DAG.getNode(ISD::BSWAP, dl, NVT, Tmp1);
2990193323Sed    Tmp1 = DAG.getNode(ISD::SRL, dl, NVT, Tmp1,
2991193323Sed                          DAG.getConstant(DiffBits, TLI.getShiftAmountTy()));
2992193323Sed    Results.push_back(Tmp1);
2993193323Sed    break;
2994193323Sed  }
2995193323Sed  case ISD::FP_TO_UINT:
2996193323Sed  case ISD::FP_TO_SINT:
2997193323Sed    Tmp1 = PromoteLegalFP_TO_INT(Node->getOperand(0), Node->getValueType(0),
2998193323Sed                                 Node->getOpcode() == ISD::FP_TO_SINT, dl);
2999193323Sed    Results.push_back(Tmp1);
3000193323Sed    break;
3001193323Sed  case ISD::UINT_TO_FP:
3002193323Sed  case ISD::SINT_TO_FP:
3003193323Sed    Tmp1 = PromoteLegalINT_TO_FP(Node->getOperand(0), Node->getValueType(0),
3004193323Sed                                 Node->getOpcode() == ISD::SINT_TO_FP, dl);
3005193323Sed    Results.push_back(Tmp1);
3006193323Sed    break;
3007193323Sed  case ISD::AND:
3008193323Sed  case ISD::OR:
3009193323Sed  case ISD::XOR:
3010193323Sed    assert(OVT.isVector() && "Don't know how to promote scalar logic ops");
3011193323Sed    // Bit convert each of the values to the new type.
3012193323Sed    Tmp1 = DAG.getNode(ISD::BIT_CONVERT, dl, NVT, Node->getOperand(0));
3013193323Sed    Tmp2 = DAG.getNode(ISD::BIT_CONVERT, dl, NVT, Node->getOperand(1));
3014193323Sed    Tmp1 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2);
3015193323Sed    // Bit convert the result back the original type.
3016193323Sed    Results.push_back(DAG.getNode(ISD::BIT_CONVERT, dl, OVT, Tmp1));
3017193323Sed    break;
3018193323Sed  case ISD::SELECT:
3019193323Sed    unsigned ExtOp, TruncOp;
3020193323Sed    if (Node->getValueType(0).isVector()) {
3021193323Sed      ExtOp   = ISD::BIT_CONVERT;
3022193323Sed      TruncOp = ISD::BIT_CONVERT;
3023193323Sed    } else if (Node->getValueType(0).isInteger()) {
3024193323Sed      ExtOp   = ISD::ANY_EXTEND;
3025193323Sed      TruncOp = ISD::TRUNCATE;
3026193323Sed    } else {
3027193323Sed      ExtOp   = ISD::FP_EXTEND;
3028193323Sed      TruncOp = ISD::FP_ROUND;
3029193323Sed    }
3030193323Sed    Tmp1 = Node->getOperand(0);
3031193323Sed    // Promote each of the values to the new type.
3032193323Sed    Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
3033193323Sed    Tmp3 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(2));
3034193323Sed    // Perform the larger operation, then round down.
3035193323Sed    Tmp1 = DAG.getNode(ISD::SELECT, dl, NVT, Tmp1, Tmp2, Tmp3);
3036193323Sed    if (TruncOp != ISD::FP_ROUND)
3037193323Sed      Tmp1 = DAG.getNode(TruncOp, dl, Node->getValueType(0), Tmp1);
3038193323Sed    else
3039193323Sed      Tmp1 = DAG.getNode(TruncOp, dl, Node->getValueType(0), Tmp1,
3040193323Sed                         DAG.getIntPtrConstant(0));
3041193323Sed    Results.push_back(Tmp1);
3042193323Sed    break;
3043193323Sed  case ISD::VECTOR_SHUFFLE: {
3044193323Sed    SmallVector<int, 8> Mask;
3045193323Sed    cast<ShuffleVectorSDNode>(Node)->getMask(Mask);
3046193323Sed
3047193323Sed    // Cast the two input vectors.
3048193323Sed    Tmp1 = DAG.getNode(ISD::BIT_CONVERT, dl, NVT, Node->getOperand(0));
3049193323Sed    Tmp2 = DAG.getNode(ISD::BIT_CONVERT, dl, NVT, Node->getOperand(1));
3050193323Sed
3051193323Sed    // Convert the shuffle mask to the right # elements.
3052193323Sed    Tmp1 = ShuffleWithNarrowerEltType(NVT, OVT, dl, Tmp1, Tmp2, Mask);
3053193323Sed    Tmp1 = DAG.getNode(ISD::BIT_CONVERT, dl, OVT, Tmp1);
3054193323Sed    Results.push_back(Tmp1);
3055193323Sed    break;
3056193323Sed  }
3057193323Sed  case ISD::SETCC: {
3058193323Sed    // First step, figure out the appropriate operation to use.
3059193323Sed    // Allow SETCC to not be supported for all legal data types
3060193323Sed    // Mostly this targets FP
3061193323Sed    MVT NewInTy = Node->getOperand(0).getValueType();
3062193323Sed    MVT OldVT = NewInTy; OldVT = OldVT;
3063193323Sed
3064193323Sed    // Scan for the appropriate larger type to use.
3065193323Sed    while (1) {
3066193323Sed      NewInTy = (MVT::SimpleValueType)(NewInTy.getSimpleVT()+1);
3067193323Sed
3068193323Sed      assert(NewInTy.isInteger() == OldVT.isInteger() &&
3069193323Sed              "Fell off of the edge of the integer world");
3070193323Sed      assert(NewInTy.isFloatingPoint() == OldVT.isFloatingPoint() &&
3071193323Sed              "Fell off of the edge of the floating point world");
3072193323Sed
3073193323Sed      // If the target supports SETCC of this type, use it.
3074193323Sed      if (TLI.isOperationLegalOrCustom(ISD::SETCC, NewInTy))
3075193323Sed        break;
3076193323Sed    }
3077193323Sed    if (NewInTy.isInteger())
3078193323Sed      assert(0 && "Cannot promote Legal Integer SETCC yet");
3079193323Sed    else {
3080193323Sed      Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NewInTy, Tmp1);
3081193323Sed      Tmp2 = DAG.getNode(ISD::FP_EXTEND, dl, NewInTy, Tmp2);
3082193323Sed    }
3083193323Sed    Results.push_back(DAG.getNode(ISD::SETCC, dl, Node->getValueType(0),
3084193323Sed                                  Tmp1, Tmp2, Node->getOperand(2)));
3085193323Sed    break;
3086193323Sed  }
3087193323Sed  }
3088193323Sed}
3089193323Sed
3090193323Sed// SelectionDAG::Legalize - This is the entry point for the file.
3091193323Sed//
3092193323Sedvoid SelectionDAG::Legalize(bool TypesNeedLegalizing,
3093193323Sed                            CodeGenOpt::Level OptLevel) {
3094193323Sed  /// run - This is the main entry point to this class.
3095193323Sed  ///
3096193323Sed  SelectionDAGLegalize(*this, OptLevel).LegalizeDAG();
3097193323Sed}
3098193323Sed
3099