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