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