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