4c2e1ed05ec9de901fdbe6ca18fba4abd9157203
[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/Support/CommandLine.h"
34 #include "llvm/Support/Compiler.h"
35 #include "llvm/Support/MathExtras.h"
36 #include "llvm/ADT/DenseMap.h"
37 #include "llvm/ADT/SmallVector.h"
38 #include "llvm/ADT/SmallPtrSet.h"
39 #include <map>
40 using namespace llvm;
41
42 //===----------------------------------------------------------------------===//
43 /// SelectionDAGLegalize - This takes an arbitrary SelectionDAG as input and
44 /// hacks on it until the target machine can handle it.  This involves
45 /// eliminating value sizes the machine cannot handle (promoting small sizes to
46 /// large sizes or splitting up large values into small values) as well as
47 /// eliminating operations the machine cannot handle.
48 ///
49 /// This code also does a small amount of optimization and recognition of idioms
50 /// as part of its processing.  For example, if a target does not support a
51 /// 'setcc' instruction efficiently, but does support 'brcc' instruction, this
52 /// will attempt merge setcc and brc instructions into brcc's.
53 ///
54 namespace {
55 class VISIBILITY_HIDDEN SelectionDAGLegalize {
56   TargetLowering &TLI;
57   SelectionDAG &DAG;
58   CodeGenOpt::Level OptLevel;
59   bool TypesNeedLegalizing;
60
61   // Libcall insertion helpers.
62
63   /// LastCALLSEQ_END - This keeps track of the CALLSEQ_END node that has been
64   /// legalized.  We use this to ensure that calls are properly serialized
65   /// against each other, including inserted libcalls.
66   SDValue LastCALLSEQ_END;
67
68   /// IsLegalizingCall - This member is used *only* for purposes of providing
69   /// helpful assertions that a libcall isn't created while another call is
70   /// being legalized (which could lead to non-serialized call sequences).
71   bool IsLegalizingCall;
72
73   /// IsLegalizingCallArguments - This member is used only for the purpose
74   /// of providing assert to check for LegalizeTypes because legalizing an
75   /// operation might introduce call nodes that might need type legalization.
76   bool IsLegalizingCallArgs;
77
78   enum LegalizeAction {
79     Legal,      // The target natively supports this operation.
80     Promote,    // This operation should be executed in a larger type.
81     Expand      // Try to expand this to other ops, otherwise use a libcall.
82   };
83
84   /// ValueTypeActions - This is a bitvector that contains two bits for each
85   /// value type, where the two bits correspond to the LegalizeAction enum.
86   /// This can be queried with "getTypeAction(VT)".
87   TargetLowering::ValueTypeActionImpl ValueTypeActions;
88
89   /// LegalizedNodes - For nodes that are of legal width, and that have more
90   /// than one use, this map indicates what regularized operand to use.  This
91   /// allows us to avoid legalizing the same thing more than once.
92   DenseMap<SDValue, SDValue> LegalizedNodes;
93
94   /// PromotedNodes - For nodes that are below legal width, and that have more
95   /// than one use, this map indicates what promoted value to use.  This allows
96   /// us to avoid promoting the same thing more than once.
97   DenseMap<SDValue, SDValue> PromotedNodes;
98
99   /// ExpandedNodes - For nodes that need to be expanded this map indicates
100   /// which operands are the expanded version of the input.  This allows
101   /// us to avoid expanding the same node more than once.
102   DenseMap<SDValue, std::pair<SDValue, SDValue> > ExpandedNodes;
103
104   /// SplitNodes - For vector nodes that need to be split, this map indicates
105   /// which operands are the split version of the input.  This allows us
106   /// to avoid splitting the same node more than once.
107   std::map<SDValue, std::pair<SDValue, SDValue> > SplitNodes;
108
109   /// ScalarizedNodes - For nodes that need to be converted from vector types to
110   /// scalar types, this contains the mapping of ones we have already
111   /// processed to the result.
112   std::map<SDValue, SDValue> ScalarizedNodes;
113
114   /// WidenNodes - For nodes that need to be widened from one vector type to
115   /// another, this contains the mapping of those that we have already widen.
116   /// This allows us to avoid widening more than once.
117   std::map<SDValue, SDValue> WidenNodes;
118
119   void AddLegalizedOperand(SDValue From, SDValue To) {
120     LegalizedNodes.insert(std::make_pair(From, To));
121     // If someone requests legalization of the new node, return itself.
122     if (From != To)
123       LegalizedNodes.insert(std::make_pair(To, To));
124   }
125   void AddPromotedOperand(SDValue From, SDValue To) {
126     bool isNew = PromotedNodes.insert(std::make_pair(From, To)).second;
127     assert(isNew && "Got into the map somehow?");
128     isNew = isNew;
129     // If someone requests legalization of the new node, return itself.
130     LegalizedNodes.insert(std::make_pair(To, To));
131   }
132   void AddWidenedOperand(SDValue From, SDValue To) {
133     bool isNew = WidenNodes.insert(std::make_pair(From, To)).second;
134     assert(isNew && "Got into the map somehow?");
135     isNew = isNew;
136     // If someone requests legalization of the new node, return itself.
137     LegalizedNodes.insert(std::make_pair(To, To));
138   }
139
140 public:
141   explicit SelectionDAGLegalize(SelectionDAG &DAG, bool TypesNeedLegalizing,
142                                 CodeGenOpt::Level ol);
143
144   /// getTypeAction - Return how we should legalize values of this type, either
145   /// it is already legal or we need to expand it into multiple registers of
146   /// smaller integer type, or we need to promote it to a larger type.
147   LegalizeAction getTypeAction(MVT VT) const {
148     return (LegalizeAction)ValueTypeActions.getTypeAction(VT);
149   }
150
151   /// isTypeLegal - Return true if this type is legal on this target.
152   ///
153   bool isTypeLegal(MVT VT) const {
154     return getTypeAction(VT) == Legal;
155   }
156
157   void LegalizeDAG();
158
159 private:
160   /// HandleOp - Legalize, Promote, or Expand the specified operand as
161   /// appropriate for its type.
162   void HandleOp(SDValue Op);
163
164   /// LegalizeOp - We know that the specified value has a legal type.
165   /// Recursively ensure that the operands have legal types, then return the
166   /// result.
167   SDValue LegalizeOp(SDValue O);
168
169   /// UnrollVectorOp - We know that the given vector has a legal type, however
170   /// the operation it performs is not legal and is an operation that we have
171   /// no way of lowering.  "Unroll" the vector, splitting out the scalars and
172   /// operating on each element individually.
173   SDValue UnrollVectorOp(SDValue O);
174
175   /// PerformInsertVectorEltInMemory - Some target cannot handle a variable
176   /// insertion index for the INSERT_VECTOR_ELT instruction.  In this case, it
177   /// is necessary to spill the vector being inserted into to memory, perform
178   /// the insert there, and then read the result back.
179   SDValue PerformInsertVectorEltInMemory(SDValue Vec, SDValue Val,
180                                            SDValue Idx, DebugLoc dl);
181
182   /// PromoteOp - Given an operation that produces a value in an invalid type,
183   /// promote it to compute the value into a larger type.  The produced value
184   /// will have the correct bits for the low portion of the register, but no
185   /// guarantee is made about the top bits: it may be zero, sign-extended, or
186   /// garbage.
187   SDValue PromoteOp(SDValue O);
188
189   /// ExpandOp - Expand the specified SDValue into its two component pieces
190   /// Lo&Hi.  Note that the Op MUST be an expanded type.  As a result of this,
191   /// the LegalizedNodes map is filled in for any results that are not expanded,
192   /// the ExpandedNodes map is filled in for any results that are expanded, and
193   /// the Lo/Hi values are returned.   This applies to integer types and Vector
194   /// types.
195   void ExpandOp(SDValue O, SDValue &Lo, SDValue &Hi);
196
197   /// WidenVectorOp - Widen a vector operation to a wider type given by WidenVT
198   /// (e.g., v3i32 to v4i32).  The produced value will have the correct value
199   /// for the existing elements but no guarantee is made about the new elements
200   /// at the end of the vector: it may be zero, ones, or garbage. This is useful
201   /// when we have an instruction operating on an illegal vector type and we
202   /// want to widen it to do the computation on a legal wider vector type.
203   SDValue WidenVectorOp(SDValue Op, MVT WidenVT);
204
205   /// SplitVectorOp - Given an operand of vector type, break it down into
206   /// two smaller values.
207   void SplitVectorOp(SDValue O, SDValue &Lo, SDValue &Hi);
208
209   /// ScalarizeVectorOp - Given an operand of single-element vector type
210   /// (e.g. v1f32), convert it into the equivalent operation that returns a
211   /// scalar (e.g. f32) value.
212   SDValue ScalarizeVectorOp(SDValue O);
213
214   /// Useful 16 element vector type that is used to pass operands for widening.
215   typedef SmallVector<SDValue, 16> SDValueVector;
216
217   /// LoadWidenVectorOp - Load a vector for a wider type. Returns true if
218   /// the LdChain contains a single load and false if it contains a token
219   /// factor for multiple loads. It takes
220   ///   Result:  location to return the result
221   ///   LdChain: location to return the load chain
222   ///   Op:      load operation to widen
223   ///   NVT:     widen vector result type we want for the load
224   bool LoadWidenVectorOp(SDValue& Result, SDValue& LdChain,
225                          SDValue Op, MVT NVT);
226
227   /// Helper genWidenVectorLoads - Helper function to generate a set of
228   /// loads to load a vector with a resulting wider type. It takes
229   ///   LdChain: list of chains for the load we have generated
230   ///   Chain:   incoming chain for the ld vector
231   ///   BasePtr: base pointer to load from
232   ///   SV:      memory disambiguation source value
233   ///   SVOffset:  memory disambiugation offset
234   ///   Alignment: alignment of the memory
235   ///   isVolatile: volatile load
236   ///   LdWidth:    width of memory that we want to load
237   ///   ResType:    the wider result result type for the resulting loaded vector
238   SDValue genWidenVectorLoads(SDValueVector& LdChain, SDValue Chain,
239                                 SDValue BasePtr, const Value *SV,
240                                 int SVOffset, unsigned Alignment,
241                                 bool isVolatile, unsigned LdWidth,
242                                 MVT ResType, DebugLoc dl);
243
244   /// StoreWidenVectorOp - Stores a widen vector into non widen memory
245   /// location. It takes
246   ///     ST:      store node that we want to replace
247   ///     Chain:   incoming store chain
248   ///     BasePtr: base address of where we want to store into
249   SDValue StoreWidenVectorOp(StoreSDNode *ST, SDValue Chain,
250                                SDValue BasePtr);
251
252   /// Helper genWidenVectorStores - Helper function to generate a set of
253   /// stores to store a widen vector into non widen memory
254   // It takes
255   //   StChain: list of chains for the stores we have generated
256   //   Chain:   incoming chain for the ld vector
257   //   BasePtr: base pointer to load from
258   //   SV:      memory disambiguation source value
259   //   SVOffset:   memory disambiugation offset
260   //   Alignment:  alignment of the memory
261   //   isVolatile: volatile lod
262   //   ValOp:   value to store
263   //   StWidth: width of memory that we want to store
264   void genWidenVectorStores(SDValueVector& StChain, SDValue Chain,
265                             SDValue BasePtr, const Value *SV,
266                             int SVOffset, unsigned Alignment,
267                             bool isVolatile, SDValue ValOp,
268                             unsigned StWidth, DebugLoc dl);
269
270   /// ShuffleWithNarrowerEltType - Return a vector shuffle operation which
271   /// performs the same shuffe in terms of order or result bytes, but on a type
272   /// whose vector element type is narrower than the original shuffle type.
273   /// e.g. <v4i32> <0, 1, 0, 1> -> v8i16 <0, 1, 2, 3, 0, 1, 2, 3>
274   SDValue ShuffleWithNarrowerEltType(MVT NVT, MVT VT, DebugLoc dl,
275                                      SDValue N1, SDValue N2, 
276                                      SmallVectorImpl<int> &Mask) const;
277
278   bool LegalizeAllNodesNotLeadingTo(SDNode *N, SDNode *Dest,
279                                     SmallPtrSet<SDNode*, 32> &NodesLeadingTo);
280
281   void LegalizeSetCCOperands(SDValue &LHS, SDValue &RHS, SDValue &CC,
282                              DebugLoc dl);
283   void LegalizeSetCCCondCode(MVT VT, SDValue &LHS, SDValue &RHS, SDValue &CC,
284                              DebugLoc dl);
285   void LegalizeSetCC(MVT VT, SDValue &LHS, SDValue &RHS, SDValue &CC,
286                      DebugLoc dl) {
287     LegalizeSetCCOperands(LHS, RHS, CC, dl);
288     LegalizeSetCCCondCode(VT, LHS, RHS, CC, dl);
289   }
290
291   SDValue ExpandLibCall(RTLIB::Libcall LC, SDNode *Node, bool isSigned,
292                           SDValue &Hi);
293   SDValue ExpandIntToFP(bool isSigned, MVT DestTy, SDValue Source, DebugLoc dl);
294
295   SDValue EmitStackConvert(SDValue SrcOp, MVT SlotVT, MVT DestVT, DebugLoc dl);
296   SDValue ExpandBUILD_VECTOR(SDNode *Node);
297   SDValue ExpandSCALAR_TO_VECTOR(SDNode *Node);
298   SDValue LegalizeINT_TO_FP(SDValue Result, bool isSigned, MVT DestTy,
299                             SDValue Op, DebugLoc dl);
300   SDValue ExpandLegalINT_TO_FP(bool isSigned, SDValue LegalOp, MVT DestVT,
301                                DebugLoc dl);
302   SDValue PromoteLegalINT_TO_FP(SDValue LegalOp, MVT DestVT, bool isSigned,
303                                 DebugLoc dl);
304   SDValue PromoteLegalFP_TO_INT(SDValue LegalOp, MVT DestVT, bool isSigned,
305                                 DebugLoc dl);
306
307   SDValue ExpandBSWAP(SDValue Op, DebugLoc dl);
308   SDValue ExpandBitCount(unsigned Opc, SDValue Op, DebugLoc dl);
309   bool ExpandShift(unsigned Opc, SDValue Op, SDValue Amt,
310                    SDValue &Lo, SDValue &Hi, DebugLoc dl);
311   void ExpandShiftParts(unsigned NodeOp, SDValue Op, SDValue Amt,
312                         SDValue &Lo, SDValue &Hi, DebugLoc dl);
313
314   SDValue ExpandEXTRACT_SUBVECTOR(SDValue Op);
315   SDValue ExpandEXTRACT_VECTOR_ELT(SDValue Op);
316   SDValue ExpandExtractFromVectorThroughStack(SDValue Op);
317 };
318 }
319
320 /// ShuffleWithNarrowerEltType - Return a vector shuffle operation which
321 /// performs the same shuffe in terms of order or result bytes, but on a type
322 /// whose vector element type is narrower than the original shuffle type.
323 /// e.g. <v4i32> <0, 1, 0, 1> -> v8i16 <0, 1, 2, 3, 0, 1, 2, 3>
324 SDValue 
325 SelectionDAGLegalize::ShuffleWithNarrowerEltType(MVT NVT, MVT VT,  DebugLoc dl, 
326                                                  SDValue N1, SDValue N2,
327                                              SmallVectorImpl<int> &Mask) const {
328   MVT EltVT = NVT.getVectorElementType();
329   unsigned NumMaskElts = VT.getVectorNumElements();
330   unsigned NumDestElts = NVT.getVectorNumElements();
331   unsigned NumEltsGrowth = NumDestElts / NumMaskElts;
332
333   assert(NumEltsGrowth && "Cannot promote to vector type with fewer elts!");
334
335   if (NumEltsGrowth == 1)
336     return DAG.getVectorShuffle(NVT, dl, N1, N2, &Mask[0]);
337   
338   SmallVector<int, 8> NewMask;
339   for (unsigned i = 0; i != NumMaskElts; ++i) {
340     int Idx = Mask[i];
341     for (unsigned j = 0; j != NumEltsGrowth; ++j) {
342       if (Idx < 0) 
343         NewMask.push_back(-1);
344       else
345         NewMask.push_back(Idx * NumEltsGrowth + j);
346     }
347   }
348   assert(NewMask.size() == NumDestElts && "Non-integer NumEltsGrowth?");
349   assert(TLI.isShuffleMaskLegal(NewMask, NVT) && "Shuffle not legal?");
350   return DAG.getVectorShuffle(NVT, dl, N1, N2, &NewMask[0]);
351 }
352
353 SelectionDAGLegalize::SelectionDAGLegalize(SelectionDAG &dag,
354                                            bool types, CodeGenOpt::Level ol)
355   : TLI(dag.getTargetLoweringInfo()), DAG(dag), OptLevel(ol),
356     TypesNeedLegalizing(types), ValueTypeActions(TLI.getValueTypeActions()) {
357   assert(MVT::LAST_VALUETYPE <= 32 &&
358          "Too many value types for ValueTypeActions to hold!");
359 }
360
361 void SelectionDAGLegalize::LegalizeDAG() {
362   LastCALLSEQ_END = DAG.getEntryNode();
363   IsLegalizingCall = false;
364   IsLegalizingCallArgs = false;
365
366   // The legalize process is inherently a bottom-up recursive process (users
367   // legalize their uses before themselves).  Given infinite stack space, we
368   // could just start legalizing on the root and traverse the whole graph.  In
369   // practice however, this causes us to run out of stack space on large basic
370   // blocks.  To avoid this problem, compute an ordering of the nodes where each
371   // node is only legalized after all of its operands are legalized.
372   DAG.AssignTopologicalOrder();
373   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
374        E = prior(DAG.allnodes_end()); I != next(E); ++I)
375     HandleOp(SDValue(I, 0));
376
377   // Finally, it's possible the root changed.  Get the new root.
378   SDValue OldRoot = DAG.getRoot();
379   assert(LegalizedNodes.count(OldRoot) && "Root didn't get legalized?");
380   DAG.setRoot(LegalizedNodes[OldRoot]);
381
382   ExpandedNodes.clear();
383   LegalizedNodes.clear();
384   PromotedNodes.clear();
385   SplitNodes.clear();
386   ScalarizedNodes.clear();
387   WidenNodes.clear();
388
389   // Remove dead nodes now.
390   DAG.RemoveDeadNodes();
391 }
392
393
394 /// FindCallEndFromCallStart - Given a chained node that is part of a call
395 /// sequence, find the CALLSEQ_END node that terminates the call sequence.
396 static SDNode *FindCallEndFromCallStart(SDNode *Node) {
397   if (Node->getOpcode() == ISD::CALLSEQ_END)
398     return Node;
399   if (Node->use_empty())
400     return 0;   // No CallSeqEnd
401
402   // The chain is usually at the end.
403   SDValue TheChain(Node, Node->getNumValues()-1);
404   if (TheChain.getValueType() != MVT::Other) {
405     // Sometimes it's at the beginning.
406     TheChain = SDValue(Node, 0);
407     if (TheChain.getValueType() != MVT::Other) {
408       // Otherwise, hunt for it.
409       for (unsigned i = 1, e = Node->getNumValues(); i != e; ++i)
410         if (Node->getValueType(i) == MVT::Other) {
411           TheChain = SDValue(Node, i);
412           break;
413         }
414
415       // Otherwise, we walked into a node without a chain.
416       if (TheChain.getValueType() != MVT::Other)
417         return 0;
418     }
419   }
420
421   for (SDNode::use_iterator UI = Node->use_begin(),
422        E = Node->use_end(); UI != E; ++UI) {
423
424     // Make sure to only follow users of our token chain.
425     SDNode *User = *UI;
426     for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
427       if (User->getOperand(i) == TheChain)
428         if (SDNode *Result = FindCallEndFromCallStart(User))
429           return Result;
430   }
431   return 0;
432 }
433
434 /// FindCallStartFromCallEnd - Given a chained node that is part of a call
435 /// sequence, find the CALLSEQ_START node that initiates the call sequence.
436 static SDNode *FindCallStartFromCallEnd(SDNode *Node) {
437   assert(Node && "Didn't find callseq_start for a call??");
438   if (Node->getOpcode() == ISD::CALLSEQ_START) return Node;
439
440   assert(Node->getOperand(0).getValueType() == MVT::Other &&
441          "Node doesn't have a token chain argument!");
442   return FindCallStartFromCallEnd(Node->getOperand(0).getNode());
443 }
444
445 /// LegalizeAllNodesNotLeadingTo - Recursively walk the uses of N, looking to
446 /// see if any uses can reach Dest.  If no dest operands can get to dest,
447 /// legalize them, legalize ourself, and return false, otherwise, return true.
448 ///
449 /// Keep track of the nodes we fine that actually do lead to Dest in
450 /// NodesLeadingTo.  This avoids retraversing them exponential number of times.
451 ///
452 bool SelectionDAGLegalize::LegalizeAllNodesNotLeadingTo(SDNode *N, SDNode *Dest,
453                                      SmallPtrSet<SDNode*, 32> &NodesLeadingTo) {
454   if (N == Dest) return true;  // N certainly leads to Dest :)
455
456   // If we've already processed this node and it does lead to Dest, there is no
457   // need to reprocess it.
458   if (NodesLeadingTo.count(N)) return true;
459
460   // If the first result of this node has been already legalized, then it cannot
461   // reach N.
462   switch (getTypeAction(N->getValueType(0))) {
463   case Legal:
464     if (LegalizedNodes.count(SDValue(N, 0))) return false;
465     break;
466   case Promote:
467     if (PromotedNodes.count(SDValue(N, 0))) return false;
468     break;
469   case Expand:
470     if (ExpandedNodes.count(SDValue(N, 0))) return false;
471     break;
472   }
473
474   // Okay, this node has not already been legalized.  Check and legalize all
475   // operands.  If none lead to Dest, then we can legalize this node.
476   bool OperandsLeadToDest = false;
477   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
478     OperandsLeadToDest |=     // If an operand leads to Dest, so do we.
479       LegalizeAllNodesNotLeadingTo(N->getOperand(i).getNode(), Dest, NodesLeadingTo);
480
481   if (OperandsLeadToDest) {
482     NodesLeadingTo.insert(N);
483     return true;
484   }
485
486   // Okay, this node looks safe, legalize it and return false.
487   HandleOp(SDValue(N, 0));
488   return false;
489 }
490
491 /// HandleOp - Legalize, Promote, Widen, or Expand the specified operand as
492 /// appropriate for its type.
493 void SelectionDAGLegalize::HandleOp(SDValue Op) {
494   MVT VT = Op.getValueType();
495   // If the type legalizer was run then we should never see any illegal result
496   // types here except for target constants (the type legalizer does not touch
497   // those) or for build vector used as a mask for a vector shuffle.
498   assert((TypesNeedLegalizing || getTypeAction(VT) == Legal ||
499           IsLegalizingCallArgs || Op.getOpcode() == ISD::TargetConstant) &&
500          "Illegal type introduced after type legalization?");
501   switch (getTypeAction(VT)) {
502   default: assert(0 && "Bad type action!");
503   case Legal:   (void)LegalizeOp(Op); break;
504   case Promote:
505     if (!VT.isVector()) {
506       (void)PromoteOp(Op);
507       break;
508     }
509     else  {
510       // See if we can widen otherwise use Expand to either scalarize or split
511       MVT WidenVT = TLI.getWidenVectorType(VT);
512       if (WidenVT != MVT::Other) {
513         (void) WidenVectorOp(Op, WidenVT);
514         break;
515       }
516       // else fall thru to expand since we can't widen the vector
517     }
518   case Expand:
519     if (!VT.isVector()) {
520       // If this is an illegal scalar, expand it into its two component
521       // pieces.
522       SDValue X, Y;
523       if (Op.getOpcode() == ISD::TargetConstant)
524         break;  // Allow illegal target nodes.
525       ExpandOp(Op, X, Y);
526     } else if (VT.getVectorNumElements() == 1) {
527       // If this is an illegal single element vector, convert it to a
528       // scalar operation.
529       (void)ScalarizeVectorOp(Op);
530     } else {
531       // This is an illegal multiple element vector.
532       // Split it in half and legalize both parts.
533       SDValue X, Y;
534       SplitVectorOp(Op, X, Y);
535     }
536     break;
537   }
538 }
539
540 /// ExpandConstantFP - Expands the ConstantFP node to an integer constant or
541 /// a load from the constant pool.
542 static SDValue ExpandConstantFP(ConstantFPSDNode *CFP, bool UseCP,
543                                 SelectionDAG &DAG, const TargetLowering &TLI) {
544   bool Extend = false;
545   DebugLoc dl = CFP->getDebugLoc();
546
547   // If a FP immediate is precise when represented as a float and if the
548   // target can do an extending load from float to double, we put it into
549   // the constant pool as a float, even if it's is statically typed as a
550   // double.  This shrinks FP constants and canonicalizes them for targets where
551   // an FP extending load is the same cost as a normal load (such as on the x87
552   // fp stack or PPC FP unit).
553   MVT VT = CFP->getValueType(0);
554   ConstantFP *LLVMC = const_cast<ConstantFP*>(CFP->getConstantFPValue());
555   if (!UseCP) {
556     assert((VT == MVT::f64 || VT == MVT::f32) && "Invalid type expansion");
557     return DAG.getConstant(LLVMC->getValueAPF().bitcastToAPInt(),
558                            (VT == MVT::f64) ? MVT::i64 : MVT::i32);
559   }
560
561   MVT OrigVT = VT;
562   MVT SVT = VT;
563   while (SVT != MVT::f32) {
564     SVT = (MVT::SimpleValueType)(SVT.getSimpleVT() - 1);
565     if (CFP->isValueValidForType(SVT, CFP->getValueAPF()) &&
566         // Only do this if the target has a native EXTLOAD instruction from
567         // smaller type.
568         TLI.isLoadExtLegal(ISD::EXTLOAD, SVT) &&
569         TLI.ShouldShrinkFPConstant(OrigVT)) {
570       const Type *SType = SVT.getTypeForMVT();
571       LLVMC = cast<ConstantFP>(ConstantExpr::getFPTrunc(LLVMC, SType));
572       VT = SVT;
573       Extend = true;
574     }
575   }
576
577   SDValue CPIdx = DAG.getConstantPool(LLVMC, TLI.getPointerTy());
578   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
579   if (Extend)
580     return DAG.getExtLoad(ISD::EXTLOAD, dl,
581                           OrigVT, DAG.getEntryNode(),
582                           CPIdx, PseudoSourceValue::getConstantPool(),
583                           0, VT, false, Alignment);
584   return DAG.getLoad(OrigVT, dl, DAG.getEntryNode(), CPIdx,
585                      PseudoSourceValue::getConstantPool(), 0, false, Alignment);
586 }
587
588
589 /// ExpandFCOPYSIGNToBitwiseOps - Expands fcopysign to a series of bitwise
590 /// operations.
591 static
592 SDValue ExpandFCOPYSIGNToBitwiseOps(SDNode *Node, MVT NVT,
593                                     SelectionDAG &DAG,
594                                     const TargetLowering &TLI) {
595   DebugLoc dl = Node->getDebugLoc();
596   MVT VT = Node->getValueType(0);
597   MVT SrcVT = Node->getOperand(1).getValueType();
598   assert((SrcVT == MVT::f32 || SrcVT == MVT::f64) &&
599          "fcopysign expansion only supported for f32 and f64");
600   MVT SrcNVT = (SrcVT == MVT::f64) ? MVT::i64 : MVT::i32;
601
602   // First get the sign bit of second operand.
603   SDValue Mask1 = (SrcVT == MVT::f64)
604     ? DAG.getConstantFP(BitsToDouble(1ULL << 63), SrcVT)
605     : DAG.getConstantFP(BitsToFloat(1U << 31), SrcVT);
606   Mask1 = DAG.getNode(ISD::BIT_CONVERT, dl, SrcNVT, Mask1);
607   SDValue SignBit= DAG.getNode(ISD::BIT_CONVERT, dl, SrcNVT,
608                                Node->getOperand(1));
609   SignBit = DAG.getNode(ISD::AND, dl, SrcNVT, SignBit, Mask1);
610   // Shift right or sign-extend it if the two operands have different types.
611   int SizeDiff = SrcNVT.getSizeInBits() - NVT.getSizeInBits();
612   if (SizeDiff > 0) {
613     SignBit = DAG.getNode(ISD::SRL, dl, SrcNVT, SignBit,
614                           DAG.getConstant(SizeDiff, TLI.getShiftAmountTy()));
615     SignBit = DAG.getNode(ISD::TRUNCATE, dl, NVT, SignBit);
616   } else if (SizeDiff < 0) {
617     SignBit = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, SignBit);
618     SignBit = DAG.getNode(ISD::SHL, dl, NVT, SignBit,
619                           DAG.getConstant(-SizeDiff, TLI.getShiftAmountTy()));
620   }
621
622   // Clear the sign bit of first operand.
623   SDValue Mask2 = (VT == MVT::f64)
624     ? DAG.getConstantFP(BitsToDouble(~(1ULL << 63)), VT)
625     : DAG.getConstantFP(BitsToFloat(~(1U << 31)), VT);
626   Mask2 = DAG.getNode(ISD::BIT_CONVERT, dl, NVT, Mask2);
627   SDValue Result = DAG.getNode(ISD::BIT_CONVERT, dl, NVT, Node->getOperand(0));
628   Result = DAG.getNode(ISD::AND, dl, NVT, Result, Mask2);
629
630   // Or the value with the sign bit.
631   Result = DAG.getNode(ISD::OR, dl, NVT, Result, SignBit);
632   return Result;
633 }
634
635 /// ExpandUnalignedStore - Expands an unaligned store to 2 half-size stores.
636 static
637 SDValue ExpandUnalignedStore(StoreSDNode *ST, SelectionDAG &DAG,
638                              const TargetLowering &TLI) {
639   SDValue Chain = ST->getChain();
640   SDValue Ptr = ST->getBasePtr();
641   SDValue Val = ST->getValue();
642   MVT VT = Val.getValueType();
643   int Alignment = ST->getAlignment();
644   int SVOffset = ST->getSrcValueOffset();
645   DebugLoc dl = ST->getDebugLoc();
646   if (ST->getMemoryVT().isFloatingPoint() ||
647       ST->getMemoryVT().isVector()) {
648     MVT intVT = MVT::getIntegerVT(VT.getSizeInBits());
649     if (TLI.isTypeLegal(intVT)) {
650       // Expand to a bitconvert of the value to the integer type of the
651       // same size, then a (misaligned) int store.
652       // FIXME: Does not handle truncating floating point stores!
653       SDValue Result = DAG.getNode(ISD::BIT_CONVERT, dl, intVT, Val);
654       return DAG.getStore(Chain, dl, Result, Ptr, ST->getSrcValue(),
655                           SVOffset, ST->isVolatile(), Alignment);
656     } else {
657       // Do a (aligned) store to a stack slot, then copy from the stack slot
658       // to the final destination using (unaligned) integer loads and stores.
659       MVT StoredVT = ST->getMemoryVT();
660       MVT RegVT =
661         TLI.getRegisterType(MVT::getIntegerVT(StoredVT.getSizeInBits()));
662       unsigned StoredBytes = StoredVT.getSizeInBits() / 8;
663       unsigned RegBytes = RegVT.getSizeInBits() / 8;
664       unsigned NumRegs = (StoredBytes + RegBytes - 1) / RegBytes;
665
666       // Make sure the stack slot is also aligned for the register type.
667       SDValue StackPtr = DAG.CreateStackTemporary(StoredVT, RegVT);
668
669       // Perform the original store, only redirected to the stack slot.
670       SDValue Store = DAG.getTruncStore(Chain, dl,
671                                         Val, StackPtr, NULL, 0, StoredVT);
672       SDValue Increment = DAG.getConstant(RegBytes, TLI.getPointerTy());
673       SmallVector<SDValue, 8> Stores;
674       unsigned Offset = 0;
675
676       // Do all but one copies using the full register width.
677       for (unsigned i = 1; i < NumRegs; i++) {
678         // Load one integer register's worth from the stack slot.
679         SDValue Load = DAG.getLoad(RegVT, dl, Store, StackPtr, NULL, 0);
680         // Store it to the final location.  Remember the store.
681         Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, Ptr,
682                                       ST->getSrcValue(), SVOffset + Offset,
683                                       ST->isVolatile(),
684                                       MinAlign(ST->getAlignment(), Offset)));
685         // Increment the pointers.
686         Offset += RegBytes;
687         StackPtr = DAG.getNode(ISD::ADD, dl, StackPtr.getValueType(), StackPtr,
688                                Increment);
689         Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
690       }
691
692       // The last store may be partial.  Do a truncating store.  On big-endian
693       // machines this requires an extending load from the stack slot to ensure
694       // that the bits are in the right place.
695       MVT MemVT = MVT::getIntegerVT(8 * (StoredBytes - Offset));
696
697       // Load from the stack slot.
698       SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Store, StackPtr,
699                                     NULL, 0, MemVT);
700
701       Stores.push_back(DAG.getTruncStore(Load.getValue(1), dl, Load, Ptr,
702                                          ST->getSrcValue(), SVOffset + Offset,
703                                          MemVT, ST->isVolatile(),
704                                          MinAlign(ST->getAlignment(), Offset)));
705       // The order of the stores doesn't matter - say it with a TokenFactor.
706       return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Stores[0],
707                          Stores.size());
708     }
709   }
710   assert(ST->getMemoryVT().isInteger() &&
711          !ST->getMemoryVT().isVector() &&
712          "Unaligned store of unknown type.");
713   // Get the half-size VT
714   MVT NewStoredVT =
715     (MVT::SimpleValueType)(ST->getMemoryVT().getSimpleVT() - 1);
716   int NumBits = NewStoredVT.getSizeInBits();
717   int IncrementSize = NumBits / 8;
718
719   // Divide the stored value in two parts.
720   SDValue ShiftAmount = DAG.getConstant(NumBits, TLI.getShiftAmountTy());
721   SDValue Lo = Val;
722   SDValue Hi = DAG.getNode(ISD::SRL, dl, VT, Val, ShiftAmount);
723
724   // Store the two parts
725   SDValue Store1, Store2;
726   Store1 = DAG.getTruncStore(Chain, dl, TLI.isLittleEndian()?Lo:Hi, Ptr,
727                              ST->getSrcValue(), SVOffset, NewStoredVT,
728                              ST->isVolatile(), Alignment);
729   Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
730                     DAG.getConstant(IncrementSize, TLI.getPointerTy()));
731   Alignment = MinAlign(Alignment, IncrementSize);
732   Store2 = DAG.getTruncStore(Chain, dl, TLI.isLittleEndian()?Hi:Lo, Ptr,
733                              ST->getSrcValue(), SVOffset + IncrementSize,
734                              NewStoredVT, ST->isVolatile(), Alignment);
735
736   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2);
737 }
738
739 /// ExpandUnalignedLoad - Expands an unaligned load to 2 half-size loads.
740 static
741 SDValue ExpandUnalignedLoad(LoadSDNode *LD, SelectionDAG &DAG,
742                             const TargetLowering &TLI) {
743   int SVOffset = LD->getSrcValueOffset();
744   SDValue Chain = LD->getChain();
745   SDValue Ptr = LD->getBasePtr();
746   MVT VT = LD->getValueType(0);
747   MVT LoadedVT = LD->getMemoryVT();
748   DebugLoc dl = LD->getDebugLoc();
749   if (VT.isFloatingPoint() || VT.isVector()) {
750     MVT intVT = MVT::getIntegerVT(LoadedVT.getSizeInBits());
751     if (TLI.isTypeLegal(intVT)) {
752       // Expand to a (misaligned) integer load of the same size,
753       // then bitconvert to floating point or vector.
754       SDValue newLoad = DAG.getLoad(intVT, dl, Chain, Ptr, LD->getSrcValue(),
755                                     SVOffset, LD->isVolatile(),
756                                     LD->getAlignment());
757       SDValue Result = DAG.getNode(ISD::BIT_CONVERT, dl, LoadedVT, newLoad);
758       if (VT.isFloatingPoint() && LoadedVT != VT)
759         Result = DAG.getNode(ISD::FP_EXTEND, dl, VT, Result);
760
761       SDValue Ops[] = { Result, Chain };
762       return DAG.getMergeValues(Ops, 2, dl);
763     } else {
764       // Copy the value to a (aligned) stack slot using (unaligned) integer
765       // loads and stores, then do a (aligned) load from the stack slot.
766       MVT RegVT = TLI.getRegisterType(intVT);
767       unsigned LoadedBytes = LoadedVT.getSizeInBits() / 8;
768       unsigned RegBytes = RegVT.getSizeInBits() / 8;
769       unsigned NumRegs = (LoadedBytes + RegBytes - 1) / RegBytes;
770
771       // Make sure the stack slot is also aligned for the register type.
772       SDValue StackBase = DAG.CreateStackTemporary(LoadedVT, RegVT);
773
774       SDValue Increment = DAG.getConstant(RegBytes, TLI.getPointerTy());
775       SmallVector<SDValue, 8> Stores;
776       SDValue StackPtr = StackBase;
777       unsigned Offset = 0;
778
779       // Do all but one copies using the full register width.
780       for (unsigned i = 1; i < NumRegs; i++) {
781         // Load one integer register's worth from the original location.
782         SDValue Load = DAG.getLoad(RegVT, dl, Chain, Ptr, LD->getSrcValue(),
783                                    SVOffset + Offset, LD->isVolatile(),
784                                    MinAlign(LD->getAlignment(), Offset));
785         // Follow the load with a store to the stack slot.  Remember the store.
786         Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, StackPtr,
787                                       NULL, 0));
788         // Increment the pointers.
789         Offset += RegBytes;
790         Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
791         StackPtr = DAG.getNode(ISD::ADD, dl, StackPtr.getValueType(), StackPtr,
792                                Increment);
793       }
794
795       // The last copy may be partial.  Do an extending load.
796       MVT MemVT = MVT::getIntegerVT(8 * (LoadedBytes - Offset));
797       SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Chain, Ptr,
798                                     LD->getSrcValue(), SVOffset + Offset,
799                                     MemVT, LD->isVolatile(),
800                                     MinAlign(LD->getAlignment(), Offset));
801       // Follow the load with a store to the stack slot.  Remember the store.
802       // On big-endian machines this requires a truncating store to ensure
803       // that the bits end up in the right place.
804       Stores.push_back(DAG.getTruncStore(Load.getValue(1), dl, Load, StackPtr,
805                                          NULL, 0, MemVT));
806
807       // The order of the stores doesn't matter - say it with a TokenFactor.
808       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Stores[0],
809                                Stores.size());
810
811       // Finally, perform the original load only redirected to the stack slot.
812       Load = DAG.getExtLoad(LD->getExtensionType(), dl, VT, TF, StackBase,
813                             NULL, 0, LoadedVT);
814
815       // Callers expect a MERGE_VALUES node.
816       SDValue Ops[] = { Load, TF };
817       return DAG.getMergeValues(Ops, 2, dl);
818     }
819   }
820   assert(LoadedVT.isInteger() && !LoadedVT.isVector() &&
821          "Unaligned load of unsupported type.");
822
823   // Compute the new VT that is half the size of the old one.  This is an
824   // integer MVT.
825   unsigned NumBits = LoadedVT.getSizeInBits();
826   MVT NewLoadedVT;
827   NewLoadedVT = MVT::getIntegerVT(NumBits/2);
828   NumBits >>= 1;
829
830   unsigned Alignment = LD->getAlignment();
831   unsigned IncrementSize = NumBits / 8;
832   ISD::LoadExtType HiExtType = LD->getExtensionType();
833
834   // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD.
835   if (HiExtType == ISD::NON_EXTLOAD)
836     HiExtType = ISD::ZEXTLOAD;
837
838   // Load the value in two parts
839   SDValue Lo, Hi;
840   if (TLI.isLittleEndian()) {
841     Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, LD->getSrcValue(),
842                         SVOffset, NewLoadedVT, LD->isVolatile(), Alignment);
843     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
844                       DAG.getConstant(IncrementSize, TLI.getPointerTy()));
845     Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, LD->getSrcValue(),
846                         SVOffset + IncrementSize, NewLoadedVT, LD->isVolatile(),
847                         MinAlign(Alignment, IncrementSize));
848   } else {
849     Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, LD->getSrcValue(),
850                         SVOffset, NewLoadedVT, LD->isVolatile(), Alignment);
851     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
852                       DAG.getConstant(IncrementSize, TLI.getPointerTy()));
853     Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, LD->getSrcValue(),
854                         SVOffset + IncrementSize, NewLoadedVT, LD->isVolatile(),
855                         MinAlign(Alignment, IncrementSize));
856   }
857
858   // aggregate the two parts
859   SDValue ShiftAmount = DAG.getConstant(NumBits, TLI.getShiftAmountTy());
860   SDValue Result = DAG.getNode(ISD::SHL, dl, VT, Hi, ShiftAmount);
861   Result = DAG.getNode(ISD::OR, dl, VT, Result, Lo);
862
863   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
864                              Hi.getValue(1));
865
866   SDValue Ops[] = { Result, TF };
867   return DAG.getMergeValues(Ops, 2, dl);
868 }
869
870 /// UnrollVectorOp - We know that the given vector has a legal type, however
871 /// the operation it performs is not legal and is an operation that we have
872 /// no way of lowering.  "Unroll" the vector, splitting out the scalars and
873 /// operating on each element individually.
874 SDValue SelectionDAGLegalize::UnrollVectorOp(SDValue Op) {
875   MVT VT = Op.getValueType();
876   assert(isTypeLegal(VT) &&
877          "Caller should expand or promote operands that are not legal!");
878   assert(Op.getNode()->getNumValues() == 1 &&
879          "Can't unroll a vector with multiple results!");
880   unsigned NE = VT.getVectorNumElements();
881   MVT EltVT = VT.getVectorElementType();
882   DebugLoc dl = Op.getDebugLoc();
883
884   SmallVector<SDValue, 8> Scalars;
885   SmallVector<SDValue, 4> Operands(Op.getNumOperands());
886   for (unsigned i = 0; i != NE; ++i) {
887     for (unsigned j = 0; j != Op.getNumOperands(); ++j) {
888       SDValue Operand = Op.getOperand(j);
889       MVT OperandVT = Operand.getValueType();
890       if (OperandVT.isVector()) {
891         // A vector operand; extract a single element.
892         MVT OperandEltVT = OperandVT.getVectorElementType();
893         Operands[j] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
894                                   OperandEltVT,
895                                   Operand,
896                                   DAG.getConstant(i, MVT::i32));
897       } else {
898         // A scalar operand; just use it as is.
899         Operands[j] = Operand;
900       }
901     }
902
903     switch (Op.getOpcode()) {
904     default:
905       Scalars.push_back(DAG.getNode(Op.getOpcode(), dl, EltVT,
906                                     &Operands[0], Operands.size()));
907       break;
908     case ISD::SHL:
909     case ISD::SRA:
910     case ISD::SRL:
911     case ISD::ROTL:
912     case ISD::ROTR:
913       Scalars.push_back(DAG.getNode(Op.getOpcode(), dl, EltVT, Operands[0],
914                                     DAG.getShiftAmountOperand(Operands[1])));
915       break;
916     }
917   }
918
919   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Scalars[0], Scalars.size());
920 }
921
922 /// GetFPLibCall - Return the right libcall for the given floating point type.
923 static RTLIB::Libcall GetFPLibCall(MVT VT,
924                                    RTLIB::Libcall Call_F32,
925                                    RTLIB::Libcall Call_F64,
926                                    RTLIB::Libcall Call_F80,
927                                    RTLIB::Libcall Call_PPCF128) {
928   return
929     VT == MVT::f32 ? Call_F32 :
930     VT == MVT::f64 ? Call_F64 :
931     VT == MVT::f80 ? Call_F80 :
932     VT == MVT::ppcf128 ? Call_PPCF128 :
933     RTLIB::UNKNOWN_LIBCALL;
934 }
935
936 /// PerformInsertVectorEltInMemory - Some target cannot handle a variable
937 /// insertion index for the INSERT_VECTOR_ELT instruction.  In this case, it
938 /// is necessary to spill the vector being inserted into to memory, perform
939 /// the insert there, and then read the result back.
940 SDValue SelectionDAGLegalize::
941 PerformInsertVectorEltInMemory(SDValue Vec, SDValue Val, SDValue Idx,
942                                DebugLoc dl) {
943   SDValue Tmp1 = Vec;
944   SDValue Tmp2 = Val;
945   SDValue Tmp3 = Idx;
946
947   // If the target doesn't support this, we have to spill the input vector
948   // to a temporary stack slot, update the element, then reload it.  This is
949   // badness.  We could also load the value into a vector register (either
950   // with a "move to register" or "extload into register" instruction, then
951   // permute it into place, if the idx is a constant and if the idx is
952   // supported by the target.
953   MVT VT    = Tmp1.getValueType();
954   MVT EltVT = VT.getVectorElementType();
955   MVT IdxVT = Tmp3.getValueType();
956   MVT PtrVT = TLI.getPointerTy();
957   SDValue StackPtr = DAG.CreateStackTemporary(VT);
958
959   int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
960
961   // Store the vector.
962   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, Tmp1, StackPtr,
963                             PseudoSourceValue::getFixedStack(SPFI), 0);
964
965   // Truncate or zero extend offset to target pointer type.
966   unsigned CastOpc = IdxVT.bitsGT(PtrVT) ? ISD::TRUNCATE : ISD::ZERO_EXTEND;
967   Tmp3 = DAG.getNode(CastOpc, dl, PtrVT, Tmp3);
968   // Add the offset to the index.
969   unsigned EltSize = EltVT.getSizeInBits()/8;
970   Tmp3 = DAG.getNode(ISD::MUL, dl, IdxVT, Tmp3,DAG.getConstant(EltSize, IdxVT));
971   SDValue StackPtr2 = DAG.getNode(ISD::ADD, dl, IdxVT, Tmp3, StackPtr);
972   // Store the scalar value.
973   Ch = DAG.getTruncStore(Ch, dl, Tmp2, StackPtr2,
974                          PseudoSourceValue::getFixedStack(SPFI), 0, EltVT);
975   // Load the updated vector.
976   return DAG.getLoad(VT, dl, Ch, StackPtr,
977                      PseudoSourceValue::getFixedStack(SPFI), 0);
978 }
979
980
981 /// LegalizeOp - We know that the specified value has a legal type, and
982 /// that its operands are legal.  Now ensure that the operation itself
983 /// is legal, recursively ensuring that the operands' operations remain
984 /// legal.
985 SDValue SelectionDAGLegalize::LegalizeOp(SDValue Op) {
986   if (Op.getOpcode() == ISD::TargetConstant) // Allow illegal target nodes.
987     return Op;
988
989   assert(isTypeLegal(Op.getValueType()) &&
990          "Caller should expand or promote operands that are not legal!");
991   SDNode *Node = Op.getNode();
992   DebugLoc dl = Node->getDebugLoc();
993
994   // If this operation defines any values that cannot be represented in a
995   // register on this target, make sure to expand or promote them.
996   if (Node->getNumValues() > 1) {
997     for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
998       if (getTypeAction(Node->getValueType(i)) != Legal) {
999         HandleOp(Op.getValue(i));
1000         assert(LegalizedNodes.count(Op) &&
1001                "Handling didn't add legal operands!");
1002         return LegalizedNodes[Op];
1003       }
1004   }
1005
1006   // Note that LegalizeOp may be reentered even from single-use nodes, which
1007   // means that we always must cache transformed nodes.
1008   DenseMap<SDValue, SDValue>::iterator I = LegalizedNodes.find(Op);
1009   if (I != LegalizedNodes.end()) return I->second;
1010
1011   SDValue Tmp1, Tmp2, Tmp3, Tmp4;
1012   SDValue Result = Op;
1013   bool isCustom = false;
1014
1015   switch (Node->getOpcode()) {
1016   case ISD::FrameIndex:
1017   case ISD::EntryToken:
1018   case ISD::Register:
1019   case ISD::BasicBlock:
1020   case ISD::TargetFrameIndex:
1021   case ISD::TargetJumpTable:
1022   case ISD::TargetConstant:
1023   case ISD::TargetConstantFP:
1024   case ISD::TargetConstantPool:
1025   case ISD::TargetGlobalAddress:
1026   case ISD::TargetGlobalTLSAddress:
1027   case ISD::TargetExternalSymbol:
1028   case ISD::VALUETYPE:
1029   case ISD::SRCVALUE:
1030   case ISD::MEMOPERAND:
1031   case ISD::CONDCODE:
1032   case ISD::ARG_FLAGS:
1033     // Primitives must all be legal.
1034     assert(TLI.isOperationLegal(Node->getOpcode(), Node->getValueType(0)) &&
1035            "This must be legal!");
1036     break;
1037   default:
1038     if (Node->getOpcode() >= ISD::BUILTIN_OP_END) {
1039       // If this is a target node, legalize it by legalizing the operands then
1040       // passing it through.
1041       SmallVector<SDValue, 8> Ops;
1042       for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
1043         Ops.push_back(LegalizeOp(Node->getOperand(i)));
1044
1045       Result = DAG.UpdateNodeOperands(Result.getValue(0), Ops.data(), Ops.size());
1046
1047       for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
1048         AddLegalizedOperand(Op.getValue(i), Result.getValue(i));
1049       return Result.getValue(Op.getResNo());
1050     }
1051     // Otherwise this is an unhandled builtin node.  splat.
1052 #ifndef NDEBUG
1053     cerr << "NODE: "; Node->dump(&DAG); cerr << "\n";
1054 #endif
1055     assert(0 && "Do not know how to legalize this operator!");
1056     abort();
1057   case ISD::GLOBAL_OFFSET_TABLE:
1058   case ISD::GlobalAddress:
1059   case ISD::GlobalTLSAddress:
1060   case ISD::ExternalSymbol:
1061   case ISD::ConstantPool:
1062   case ISD::JumpTable: // Nothing to do.
1063     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
1064     default: assert(0 && "This action is not supported yet!");
1065     case TargetLowering::Custom:
1066       Tmp1 = TLI.LowerOperation(Op, DAG);
1067       if (Tmp1.getNode()) Result = Tmp1;
1068       // FALLTHROUGH if the target doesn't want to lower this op after all.
1069     case TargetLowering::Legal:
1070       break;
1071     }
1072     break;
1073   case ISD::FRAMEADDR:
1074   case ISD::RETURNADDR:
1075     // The only option for these nodes is to custom lower them.  If the target
1076     // does not custom lower them, then return zero.
1077     Tmp1 = TLI.LowerOperation(Op, DAG);
1078     if (Tmp1.getNode())
1079       Result = Tmp1;
1080     else
1081       Result = DAG.getConstant(0, TLI.getPointerTy());
1082     break;
1083   case ISD::FRAME_TO_ARGS_OFFSET: {
1084     MVT VT = Node->getValueType(0);
1085     switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
1086     default: assert(0 && "This action is not supported yet!");
1087     case TargetLowering::Custom:
1088       Result = TLI.LowerOperation(Op, DAG);
1089       if (Result.getNode()) break;
1090       // Fall Thru
1091     case TargetLowering::Legal:
1092       Result = DAG.getConstant(0, VT);
1093       break;
1094     }
1095     }
1096     break;
1097   case ISD::EXCEPTIONADDR: {
1098     Tmp1 = LegalizeOp(Node->getOperand(0));
1099     MVT VT = Node->getValueType(0);
1100     switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
1101     default: assert(0 && "This action is not supported yet!");
1102     case TargetLowering::Expand: {
1103         unsigned Reg = TLI.getExceptionAddressRegister();
1104         Result = DAG.getCopyFromReg(Tmp1, dl, Reg, VT);
1105       }
1106       break;
1107     case TargetLowering::Custom:
1108       Result = TLI.LowerOperation(Op, DAG);
1109       if (Result.getNode()) break;
1110       // Fall Thru
1111     case TargetLowering::Legal: {
1112       SDValue Ops[] = { DAG.getConstant(0, VT), Tmp1 };
1113       Result = DAG.getMergeValues(Ops, 2, dl);
1114       break;
1115     }
1116     }
1117     }
1118     if (Result.getNode()->getNumValues() == 1) break;
1119
1120     assert(Result.getNode()->getNumValues() == 2 &&
1121            "Cannot return more than two values!");
1122
1123     // Since we produced two values, make sure to remember that we
1124     // legalized both of them.
1125     Tmp1 = LegalizeOp(Result);
1126     Tmp2 = LegalizeOp(Result.getValue(1));
1127     AddLegalizedOperand(Op.getValue(0), Tmp1);
1128     AddLegalizedOperand(Op.getValue(1), Tmp2);
1129     return Op.getResNo() ? Tmp2 : Tmp1;
1130   case ISD::EHSELECTION: {
1131     Tmp1 = LegalizeOp(Node->getOperand(0));
1132     Tmp2 = LegalizeOp(Node->getOperand(1));
1133     MVT VT = Node->getValueType(0);
1134     switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
1135     default: assert(0 && "This action is not supported yet!");
1136     case TargetLowering::Expand: {
1137         unsigned Reg = TLI.getExceptionSelectorRegister();
1138         Result = DAG.getCopyFromReg(Tmp2, dl, Reg, VT);
1139       }
1140       break;
1141     case TargetLowering::Custom:
1142       Result = TLI.LowerOperation(Op, DAG);
1143       if (Result.getNode()) break;
1144       // Fall Thru
1145     case TargetLowering::Legal: {
1146       SDValue Ops[] = { DAG.getConstant(0, VT), Tmp2 };
1147       Result = DAG.getMergeValues(Ops, 2, dl);
1148       break;
1149     }
1150     }
1151     }
1152     if (Result.getNode()->getNumValues() == 1) break;
1153
1154     assert(Result.getNode()->getNumValues() == 2 &&
1155            "Cannot return more than two values!");
1156
1157     // Since we produced two values, make sure to remember that we
1158     // legalized both of them.
1159     Tmp1 = LegalizeOp(Result);
1160     Tmp2 = LegalizeOp(Result.getValue(1));
1161     AddLegalizedOperand(Op.getValue(0), Tmp1);
1162     AddLegalizedOperand(Op.getValue(1), Tmp2);
1163     return Op.getResNo() ? Tmp2 : Tmp1;
1164   case ISD::EH_RETURN: {
1165     MVT VT = Node->getValueType(0);
1166     // The only "good" option for this node is to custom lower it.
1167     switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
1168     default: assert(0 && "This action is not supported at all!");
1169     case TargetLowering::Custom:
1170       Result = TLI.LowerOperation(Op, DAG);
1171       if (Result.getNode()) break;
1172       // Fall Thru
1173     case TargetLowering::Legal:
1174       // Target does not know, how to lower this, lower to noop
1175       Result = LegalizeOp(Node->getOperand(0));
1176       break;
1177     }
1178     }
1179     break;
1180   case ISD::AssertSext:
1181   case ISD::AssertZext:
1182     Tmp1 = LegalizeOp(Node->getOperand(0));
1183     Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
1184     break;
1185   case ISD::MERGE_VALUES:
1186     // Legalize eliminates MERGE_VALUES nodes.
1187     Result = Node->getOperand(Op.getResNo());
1188     break;
1189   case ISD::CopyFromReg:
1190     Tmp1 = LegalizeOp(Node->getOperand(0));
1191     Result = Op.getValue(0);
1192     if (Node->getNumValues() == 2) {
1193       Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
1194     } else {
1195       assert(Node->getNumValues() == 3 && "Invalid copyfromreg!");
1196       if (Node->getNumOperands() == 3) {
1197         Tmp2 = LegalizeOp(Node->getOperand(2));
1198         Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1),Tmp2);
1199       } else {
1200         Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
1201       }
1202       AddLegalizedOperand(Op.getValue(2), Result.getValue(2));
1203     }
1204     // Since CopyFromReg produces two values, make sure to remember that we
1205     // legalized both of them.
1206     AddLegalizedOperand(Op.getValue(0), Result);
1207     AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
1208     return Result.getValue(Op.getResNo());
1209   case ISD::UNDEF: {
1210     MVT VT = Op.getValueType();
1211     switch (TLI.getOperationAction(ISD::UNDEF, VT)) {
1212     default: assert(0 && "This action is not supported yet!");
1213     case TargetLowering::Expand:
1214       if (VT.isInteger())
1215         Result = DAG.getConstant(0, VT);
1216       else if (VT.isFloatingPoint())
1217         Result = DAG.getConstantFP(APFloat(APInt(VT.getSizeInBits(), 0)),
1218                                    VT);
1219       else
1220         assert(0 && "Unknown value type!");
1221       break;
1222     case TargetLowering::Legal:
1223       break;
1224     }
1225     break;
1226   }
1227
1228   case ISD::INTRINSIC_W_CHAIN:
1229   case ISD::INTRINSIC_WO_CHAIN:
1230   case ISD::INTRINSIC_VOID: {
1231     SmallVector<SDValue, 8> Ops;
1232     for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
1233       Ops.push_back(LegalizeOp(Node->getOperand(i)));
1234     Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
1235
1236     // Allow the target to custom lower its intrinsics if it wants to.
1237     if (TLI.getOperationAction(Node->getOpcode(), MVT::Other) ==
1238         TargetLowering::Custom) {
1239       Tmp3 = TLI.LowerOperation(Result, DAG);
1240       if (Tmp3.getNode()) Result = Tmp3;
1241     }
1242
1243     if (Result.getNode()->getNumValues() == 1) break;
1244
1245     // Must have return value and chain result.
1246     assert(Result.getNode()->getNumValues() == 2 &&
1247            "Cannot return more than two values!");
1248
1249     // Since loads produce two values, make sure to remember that we
1250     // legalized both of them.
1251     AddLegalizedOperand(SDValue(Node, 0), Result.getValue(0));
1252     AddLegalizedOperand(SDValue(Node, 1), Result.getValue(1));
1253     return Result.getValue(Op.getResNo());
1254   }
1255
1256   case ISD::DBG_STOPPOINT:
1257     assert(Node->getNumOperands() == 1 && "Invalid DBG_STOPPOINT node!");
1258     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the input chain.
1259
1260     switch (TLI.getOperationAction(ISD::DBG_STOPPOINT, MVT::Other)) {
1261     case TargetLowering::Promote:
1262     default: assert(0 && "This action is not supported yet!");
1263     case TargetLowering::Expand: {
1264       DwarfWriter *DW = DAG.getDwarfWriter();
1265       bool useDEBUG_LOC = TLI.isOperationLegalOrCustom(ISD::DEBUG_LOC,
1266                                                        MVT::Other);
1267       bool useLABEL = TLI.isOperationLegalOrCustom(ISD::DBG_LABEL, MVT::Other);
1268
1269       const DbgStopPointSDNode *DSP = cast<DbgStopPointSDNode>(Node);
1270       GlobalVariable *CU_GV = cast<GlobalVariable>(DSP->getCompileUnit());
1271       if (DW && (useDEBUG_LOC || useLABEL) && !CU_GV->isDeclaration()) {
1272         DICompileUnit CU(cast<GlobalVariable>(DSP->getCompileUnit()));
1273
1274         unsigned Line = DSP->getLine();
1275         unsigned Col = DSP->getColumn();
1276
1277         if (OptLevel == CodeGenOpt::None) {
1278           // A bit self-referential to have DebugLoc on Debug_Loc nodes, but it
1279           // won't hurt anything.
1280           if (useDEBUG_LOC) {
1281             SDValue Ops[] = { Tmp1, DAG.getConstant(Line, MVT::i32),
1282                               DAG.getConstant(Col, MVT::i32),
1283                               DAG.getSrcValue(CU.getGV()) };
1284             Result = DAG.getNode(ISD::DEBUG_LOC, dl, MVT::Other, Ops, 4);
1285           } else {
1286             unsigned ID = DW->RecordSourceLine(Line, Col, CU);
1287             Result = DAG.getLabel(ISD::DBG_LABEL, dl, Tmp1, ID);
1288           }
1289         } else {
1290           Result = Tmp1;  // chain
1291         }
1292       } else {
1293         Result = Tmp1;  // chain
1294       }
1295       break;
1296     }
1297    case TargetLowering::Custom:
1298       Result = TLI.LowerOperation(Op, DAG);
1299       if (Result.getNode())
1300         break;
1301     case TargetLowering::Legal: {
1302       LegalizeAction Action = getTypeAction(Node->getOperand(1).getValueType());
1303       if (Action == Legal && Tmp1 == Node->getOperand(0))
1304         break;
1305
1306       SmallVector<SDValue, 8> Ops;
1307       Ops.push_back(Tmp1);
1308       if (Action == Legal) {
1309         Ops.push_back(Node->getOperand(1));  // line # must be legal.
1310         Ops.push_back(Node->getOperand(2));  // col # must be legal.
1311       } else {
1312         // Otherwise promote them.
1313         Ops.push_back(PromoteOp(Node->getOperand(1)));
1314         Ops.push_back(PromoteOp(Node->getOperand(2)));
1315       }
1316       Ops.push_back(Node->getOperand(3));  // filename must be legal.
1317       Ops.push_back(Node->getOperand(4));  // working dir # must be legal.
1318       Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
1319       break;
1320     }
1321     }
1322     break;
1323
1324   case ISD::DECLARE:
1325     assert(Node->getNumOperands() == 3 && "Invalid DECLARE node!");
1326     switch (TLI.getOperationAction(ISD::DECLARE, MVT::Other)) {
1327     default: assert(0 && "This action is not supported yet!");
1328     case TargetLowering::Legal:
1329       Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1330       Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the address.
1331       Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the variable.
1332       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
1333       break;
1334     case TargetLowering::Expand:
1335       Result = LegalizeOp(Node->getOperand(0));
1336       break;
1337     }
1338     break;
1339
1340   case ISD::DEBUG_LOC:
1341     assert(Node->getNumOperands() == 4 && "Invalid DEBUG_LOC node!");
1342     switch (TLI.getOperationAction(ISD::DEBUG_LOC, MVT::Other)) {
1343     default: assert(0 && "This action is not supported yet!");
1344     case TargetLowering::Legal: {
1345       LegalizeAction Action = getTypeAction(Node->getOperand(1).getValueType());
1346       Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1347       if (Action == Legal && Tmp1 == Node->getOperand(0))
1348         break;
1349       if (Action == Legal) {
1350         Tmp2 = Node->getOperand(1);
1351         Tmp3 = Node->getOperand(2);
1352         Tmp4 = Node->getOperand(3);
1353       } else {
1354         Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the line #.
1355         Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the col #.
1356         Tmp4 = LegalizeOp(Node->getOperand(3));  // Legalize the source file id.
1357       }
1358       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3, Tmp4);
1359       break;
1360     }
1361     }
1362     break;
1363
1364   case ISD::DBG_LABEL:
1365   case ISD::EH_LABEL:
1366     assert(Node->getNumOperands() == 1 && "Invalid LABEL node!");
1367     switch (TLI.getOperationAction(Node->getOpcode(), MVT::Other)) {
1368     default: assert(0 && "This action is not supported yet!");
1369     case TargetLowering::Legal:
1370       Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1371       Result = DAG.UpdateNodeOperands(Result, Tmp1);
1372       break;
1373     case TargetLowering::Expand:
1374       Result = LegalizeOp(Node->getOperand(0));
1375       break;
1376     }
1377     break;
1378
1379   case ISD::PREFETCH:
1380     assert(Node->getNumOperands() == 4 && "Invalid Prefetch node!");
1381     switch (TLI.getOperationAction(ISD::PREFETCH, MVT::Other)) {
1382     default: assert(0 && "This action is not supported yet!");
1383     case TargetLowering::Legal:
1384       Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1385       Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the address.
1386       Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the rw specifier.
1387       Tmp4 = LegalizeOp(Node->getOperand(3));  // Legalize locality specifier.
1388       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3, Tmp4);
1389       break;
1390     case TargetLowering::Expand:
1391       // It's a noop.
1392       Result = LegalizeOp(Node->getOperand(0));
1393       break;
1394     }
1395     break;
1396
1397   case ISD::MEMBARRIER: {
1398     assert(Node->getNumOperands() == 6 && "Invalid MemBarrier node!");
1399     switch (TLI.getOperationAction(ISD::MEMBARRIER, MVT::Other)) {
1400     default: assert(0 && "This action is not supported yet!");
1401     case TargetLowering::Legal: {
1402       SDValue Ops[6];
1403       Ops[0] = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1404       for (int x = 1; x < 6; ++x) {
1405         Ops[x] = Node->getOperand(x);
1406         if (!isTypeLegal(Ops[x].getValueType()))
1407           Ops[x] = PromoteOp(Ops[x]);
1408       }
1409       Result = DAG.UpdateNodeOperands(Result, &Ops[0], 6);
1410       break;
1411     }
1412     case TargetLowering::Expand:
1413       //There is no libgcc call for this op
1414       Result = Node->getOperand(0);  // Noop
1415     break;
1416     }
1417     break;
1418   }
1419
1420   case ISD::ATOMIC_CMP_SWAP: {
1421     unsigned int num_operands = 4;
1422     assert(Node->getNumOperands() == num_operands && "Invalid Atomic node!");
1423     SDValue Ops[4];
1424     for (unsigned int x = 0; x < num_operands; ++x)
1425       Ops[x] = LegalizeOp(Node->getOperand(x));
1426     Result = DAG.UpdateNodeOperands(Result, &Ops[0], num_operands);
1427
1428     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
1429       default: assert(0 && "This action is not supported yet!");
1430       case TargetLowering::Custom:
1431         Result = TLI.LowerOperation(Result, DAG);
1432         break;
1433       case TargetLowering::Legal:
1434         break;
1435     }
1436     AddLegalizedOperand(SDValue(Node, 0), Result.getValue(0));
1437     AddLegalizedOperand(SDValue(Node, 1), Result.getValue(1));
1438     return Result.getValue(Op.getResNo());
1439   }
1440   case ISD::ATOMIC_LOAD_ADD:
1441   case ISD::ATOMIC_LOAD_SUB:
1442   case ISD::ATOMIC_LOAD_AND:
1443   case ISD::ATOMIC_LOAD_OR:
1444   case ISD::ATOMIC_LOAD_XOR:
1445   case ISD::ATOMIC_LOAD_NAND:
1446   case ISD::ATOMIC_LOAD_MIN:
1447   case ISD::ATOMIC_LOAD_MAX:
1448   case ISD::ATOMIC_LOAD_UMIN:
1449   case ISD::ATOMIC_LOAD_UMAX:
1450   case ISD::ATOMIC_SWAP: {
1451     unsigned int num_operands = 3;
1452     assert(Node->getNumOperands() == num_operands && "Invalid Atomic node!");
1453     SDValue Ops[3];
1454     for (unsigned int x = 0; x < num_operands; ++x)
1455       Ops[x] = LegalizeOp(Node->getOperand(x));
1456     Result = DAG.UpdateNodeOperands(Result, &Ops[0], num_operands);
1457
1458     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
1459     default: assert(0 && "This action is not supported yet!");
1460     case TargetLowering::Custom:
1461       Result = TLI.LowerOperation(Result, DAG);
1462       break;
1463     case TargetLowering::Legal:
1464       break;
1465     }
1466     AddLegalizedOperand(SDValue(Node, 0), Result.getValue(0));
1467     AddLegalizedOperand(SDValue(Node, 1), Result.getValue(1));
1468     return Result.getValue(Op.getResNo());
1469   }
1470   case ISD::Constant: {
1471     ConstantSDNode *CN = cast<ConstantSDNode>(Node);
1472     unsigned opAction =
1473       TLI.getOperationAction(ISD::Constant, CN->getValueType(0));
1474
1475     // We know we don't need to expand constants here, constants only have one
1476     // value and we check that it is fine above.
1477
1478     if (opAction == TargetLowering::Custom) {
1479       Tmp1 = TLI.LowerOperation(Result, DAG);
1480       if (Tmp1.getNode())
1481         Result = Tmp1;
1482     }
1483     break;
1484   }
1485   case ISD::ConstantFP: {
1486     // Spill FP immediates to the constant pool if the target cannot directly
1487     // codegen them.  Targets often have some immediate values that can be
1488     // efficiently generated into an FP register without a load.  We explicitly
1489     // leave these constants as ConstantFP nodes for the target to deal with.
1490     ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Node);
1491
1492     switch (TLI.getOperationAction(ISD::ConstantFP, CFP->getValueType(0))) {
1493     default: assert(0 && "This action is not supported yet!");
1494     case TargetLowering::Legal:
1495       break;
1496     case TargetLowering::Custom:
1497       Tmp3 = TLI.LowerOperation(Result, DAG);
1498       if (Tmp3.getNode()) {
1499         Result = Tmp3;
1500         break;
1501       }
1502       // FALLTHROUGH
1503     case TargetLowering::Expand: {
1504       // Check to see if this FP immediate is already legal.
1505       bool isLegal = false;
1506       for (TargetLowering::legal_fpimm_iterator I = TLI.legal_fpimm_begin(),
1507              E = TLI.legal_fpimm_end(); I != E; ++I) {
1508         if (CFP->isExactlyValue(*I)) {
1509           isLegal = true;
1510           break;
1511         }
1512       }
1513       // If this is a legal constant, turn it into a TargetConstantFP node.
1514       if (isLegal)
1515         break;
1516       Result = ExpandConstantFP(CFP, true, DAG, TLI);
1517     }
1518     }
1519     break;
1520   }
1521   case ISD::TokenFactor:
1522     if (Node->getNumOperands() == 2) {
1523       Tmp1 = LegalizeOp(Node->getOperand(0));
1524       Tmp2 = LegalizeOp(Node->getOperand(1));
1525       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
1526     } else if (Node->getNumOperands() == 3) {
1527       Tmp1 = LegalizeOp(Node->getOperand(0));
1528       Tmp2 = LegalizeOp(Node->getOperand(1));
1529       Tmp3 = LegalizeOp(Node->getOperand(2));
1530       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
1531     } else {
1532       SmallVector<SDValue, 8> Ops;
1533       // Legalize the operands.
1534       for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
1535         Ops.push_back(LegalizeOp(Node->getOperand(i)));
1536       Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
1537     }
1538     break;
1539
1540   case ISD::FORMAL_ARGUMENTS:
1541   case ISD::CALL:
1542     // The only option for this is to custom lower it.
1543     Tmp3 = TLI.LowerOperation(Result.getValue(0), DAG);
1544     assert(Tmp3.getNode() && "Target didn't custom lower this node!");
1545     // A call within a calling sequence must be legalized to something
1546     // other than the normal CALLSEQ_END.  Violating this gets Legalize
1547     // into an infinite loop.
1548     assert ((!IsLegalizingCall ||
1549              Node->getOpcode() != ISD::CALL ||
1550              Tmp3.getNode()->getOpcode() != ISD::CALLSEQ_END) &&
1551             "Nested CALLSEQ_START..CALLSEQ_END not supported.");
1552
1553     // The number of incoming and outgoing values should match; unless the final
1554     // outgoing value is a flag.
1555     assert((Tmp3.getNode()->getNumValues() == Result.getNode()->getNumValues() ||
1556             (Tmp3.getNode()->getNumValues() == Result.getNode()->getNumValues() + 1 &&
1557              Tmp3.getNode()->getValueType(Tmp3.getNode()->getNumValues() - 1) ==
1558                MVT::Flag)) &&
1559            "Lowering call/formal_arguments produced unexpected # results!");
1560
1561     // Since CALL/FORMAL_ARGUMENTS nodes produce multiple values, make sure to
1562     // remember that we legalized all of them, so it doesn't get relegalized.
1563     for (unsigned i = 0, e = Tmp3.getNode()->getNumValues(); i != e; ++i) {
1564       if (Tmp3.getNode()->getValueType(i) == MVT::Flag)
1565         continue;
1566       Tmp1 = LegalizeOp(Tmp3.getValue(i));
1567       if (Op.getResNo() == i)
1568         Tmp2 = Tmp1;
1569       AddLegalizedOperand(SDValue(Node, i), Tmp1);
1570     }
1571     return Tmp2;
1572   case ISD::BUILD_VECTOR:
1573     switch (TLI.getOperationAction(ISD::BUILD_VECTOR, Node->getValueType(0))) {
1574     default: assert(0 && "This action is not supported yet!");
1575     case TargetLowering::Custom:
1576       Tmp3 = TLI.LowerOperation(Result, DAG);
1577       if (Tmp3.getNode()) {
1578         Result = Tmp3;
1579         break;
1580       }
1581       // FALLTHROUGH
1582     case TargetLowering::Expand:
1583       Result = ExpandBUILD_VECTOR(Result.getNode());
1584       break;
1585     }
1586     break;
1587   case ISD::INSERT_VECTOR_ELT:
1588     Tmp1 = LegalizeOp(Node->getOperand(0));  // InVec
1589     Tmp3 = LegalizeOp(Node->getOperand(2));  // InEltNo
1590
1591     // The type of the value to insert may not be legal, even though the vector
1592     // type is legal.  Legalize/Promote accordingly.  We do not handle Expand
1593     // here.
1594     switch (getTypeAction(Node->getOperand(1).getValueType())) {
1595     default: assert(0 && "Cannot expand insert element operand");
1596     case Legal:   Tmp2 = LegalizeOp(Node->getOperand(1)); break;
1597     case Promote: Tmp2 = PromoteOp(Node->getOperand(1));  break;
1598     case Expand:
1599       // FIXME: An alternative would be to check to see if the target is not
1600       // going to custom lower this operation, we could bitcast to half elt
1601       // width and perform two inserts at that width, if that is legal.
1602       Tmp2 = Node->getOperand(1);
1603       break;
1604     }
1605     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
1606
1607     switch (TLI.getOperationAction(ISD::INSERT_VECTOR_ELT,
1608                                    Node->getValueType(0))) {
1609     default: assert(0 && "This action is not supported yet!");
1610     case TargetLowering::Legal:
1611       break;
1612     case TargetLowering::Custom:
1613       Tmp4 = TLI.LowerOperation(Result, DAG);
1614       if (Tmp4.getNode()) {
1615         Result = Tmp4;
1616         break;
1617       }
1618       // FALLTHROUGH
1619     case TargetLowering::Promote:
1620       // Fall thru for vector case
1621     case TargetLowering::Expand: {
1622       // If the insert index is a constant, codegen this as a scalar_to_vector,
1623       // then a shuffle that inserts it into the right position in the vector.
1624       if (ConstantSDNode *InsertPos = dyn_cast<ConstantSDNode>(Tmp3)) {
1625         // SCALAR_TO_VECTOR requires that the type of the value being inserted
1626         // match the element type of the vector being created, except for
1627         // integers in which case the inserted value can be over width.
1628         MVT EltVT = Op.getValueType().getVectorElementType();
1629         if (Tmp2.getValueType() == EltVT ||
1630             (EltVT.isInteger() && Tmp2.getValueType().bitsGE(EltVT))) {
1631           SDValue ScVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
1632                                       Tmp1.getValueType(), Tmp2);
1633
1634           unsigned NumElts = Tmp1.getValueType().getVectorNumElements();
1635           // We generate a shuffle of InVec and ScVec, so the shuffle mask
1636           // should be 0,1,2,3,4,5... with the appropriate element replaced with
1637           // elt 0 of the RHS.
1638           SmallVector<int, 8> ShufOps;
1639           for (unsigned i = 0; i != NumElts; ++i)
1640             ShufOps.push_back(i != InsertPos->getZExtValue() ? i : NumElts);
1641           
1642           Result = DAG.getVectorShuffle(Tmp1.getValueType(), dl, Tmp1, ScVec,
1643                                         &ShufOps[0]);
1644           Result = LegalizeOp(Result);
1645           break;
1646         }
1647       }
1648       Result = PerformInsertVectorEltInMemory(Tmp1, Tmp2, Tmp3, dl);
1649       break;
1650     }
1651     }
1652     break;
1653   case ISD::SCALAR_TO_VECTOR:
1654     if (!TLI.isTypeLegal(Node->getOperand(0).getValueType())) {
1655       Result = LegalizeOp(ExpandSCALAR_TO_VECTOR(Node));
1656       break;
1657     }
1658
1659     Tmp1 = LegalizeOp(Node->getOperand(0));  // InVal
1660     Result = DAG.UpdateNodeOperands(Result, Tmp1);
1661     switch (TLI.getOperationAction(ISD::SCALAR_TO_VECTOR,
1662                                    Node->getValueType(0))) {
1663     default: assert(0 && "This action is not supported yet!");
1664     case TargetLowering::Legal:
1665       break;
1666     case TargetLowering::Custom:
1667       Tmp3 = TLI.LowerOperation(Result, DAG);
1668       if (Tmp3.getNode()) {
1669         Result = Tmp3;
1670         break;
1671       }
1672       // FALLTHROUGH
1673     case TargetLowering::Expand:
1674       Result = LegalizeOp(ExpandSCALAR_TO_VECTOR(Node));
1675       break;
1676     }
1677     break;
1678   case ISD::VECTOR_SHUFFLE: {
1679     Tmp1 = LegalizeOp(Node->getOperand(0));   // Legalize the input vectors,
1680     Tmp2 = LegalizeOp(Node->getOperand(1));   // but not the shuffle mask.
1681     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
1682     MVT VT = Result.getValueType();
1683
1684     // Copy the Mask to a local SmallVector for use with isShuffleMaskLegal.
1685     SmallVector<int, 8> Mask;
1686     cast<ShuffleVectorSDNode>(Result)->getMask(Mask);
1687
1688     // Allow targets to custom lower the SHUFFLEs they support.
1689     switch (TLI.getOperationAction(ISD::VECTOR_SHUFFLE, VT)) {
1690     default: assert(0 && "Unknown operation action!");
1691     case TargetLowering::Legal:
1692       assert(TLI.isShuffleMaskLegal(Mask, VT) &&
1693              "vector shuffle should not be created if not legal!");
1694       break;
1695     case TargetLowering::Custom:
1696       Tmp3 = TLI.LowerOperation(Result, DAG);
1697       if (Tmp3.getNode()) {
1698         Result = Tmp3;
1699         break;
1700       }
1701       // FALLTHROUGH
1702     case TargetLowering::Expand: {
1703       MVT EltVT = VT.getVectorElementType();
1704       unsigned NumElems = VT.getVectorNumElements();
1705       SmallVector<SDValue, 8> Ops;
1706       for (unsigned i = 0; i != NumElems; ++i) {
1707         if (Mask[i] < 0) {
1708           Ops.push_back(DAG.getUNDEF(EltVT));
1709           continue;
1710         }
1711         unsigned Idx = Mask[i];
1712         if (Idx < NumElems)
1713           Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Tmp1,
1714                                     DAG.getIntPtrConstant(Idx)));
1715         else
1716           Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Tmp2,
1717                                     DAG.getIntPtrConstant(Idx - NumElems)));
1718       }
1719       Result = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Ops[0], Ops.size());
1720       break;
1721     }
1722     case TargetLowering::Promote: {
1723       // Change base type to a different vector type.
1724       MVT OVT = Node->getValueType(0);
1725       MVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
1726
1727       // Cast the two input vectors.
1728       Tmp1 = DAG.getNode(ISD::BIT_CONVERT, dl, NVT, Tmp1);
1729       Tmp2 = DAG.getNode(ISD::BIT_CONVERT, dl, NVT, Tmp2);
1730
1731       // Convert the shuffle mask to the right # elements.
1732       Result = ShuffleWithNarrowerEltType(NVT, OVT, dl, Tmp1, Tmp2, Mask);
1733       Result = DAG.getNode(ISD::BIT_CONVERT, dl, OVT, Result);
1734       break;
1735     }
1736     }
1737     break;
1738   }
1739   case ISD::EXTRACT_VECTOR_ELT:
1740     Tmp1 = Node->getOperand(0);
1741     Tmp2 = LegalizeOp(Node->getOperand(1));
1742     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
1743     Result = ExpandEXTRACT_VECTOR_ELT(Result);
1744     break;
1745
1746   case ISD::EXTRACT_SUBVECTOR:
1747     Tmp1 = Node->getOperand(0);
1748     Tmp2 = LegalizeOp(Node->getOperand(1));
1749     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
1750     switch (TLI.getOperationAction(ISD::EXTRACT_SUBVECTOR,
1751                                    Node->getValueType(0))) {
1752     default: assert(0 && "Unknown operation action!");
1753     case TargetLowering::Legal:
1754       break;
1755     case TargetLowering::Custom:
1756       Tmp3 = TLI.LowerOperation(Result, DAG);
1757       if (Tmp3.getNode()) {
1758         Result = Tmp3;
1759         break;
1760       }
1761       // FALLTHROUGH
1762     case TargetLowering::Expand: {
1763       Result = ExpandExtractFromVectorThroughStack(Result);
1764       break;
1765     }
1766     }
1767     break;
1768
1769   case ISD::CONCAT_VECTORS: {
1770     // Legalize the operands.
1771     SmallVector<SDValue, 8> Ops;
1772     for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
1773       Ops.push_back(LegalizeOp(Node->getOperand(i)));
1774     Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
1775
1776     switch (TLI.getOperationAction(ISD::CONCAT_VECTORS,
1777                                    Node->getValueType(0))) {
1778     default: assert(0 && "Unknown operation action!");
1779     case TargetLowering::Legal:
1780       break;
1781     case TargetLowering::Custom:
1782       Tmp3 = TLI.LowerOperation(Result, DAG);
1783       if (Tmp3.getNode()) {
1784         Result = Tmp3;
1785         break;
1786       }
1787       // FALLTHROUGH
1788     case TargetLowering::Expand: {
1789       // Use extract/insert/build vector for now. We might try to be
1790       // more clever later.
1791       MVT PtrVT = TLI.getPointerTy();
1792       SmallVector<SDValue, 8> Ops;
1793       unsigned NumOperands = Node->getNumOperands();
1794       for (unsigned i=0; i < NumOperands; ++i) {
1795         SDValue SubOp = Node->getOperand(i);
1796         MVT VVT = SubOp.getNode()->getValueType(0);
1797         MVT EltVT = VVT.getVectorElementType();
1798         unsigned NumSubElem = VVT.getVectorNumElements();
1799         for (unsigned j=0; j < NumSubElem; ++j) {
1800           Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, SubOp,
1801                                     DAG.getConstant(j, PtrVT)));
1802         }
1803       }
1804       return LegalizeOp(DAG.getNode(ISD::BUILD_VECTOR, dl,
1805                                     Node->getValueType(0),
1806                                     &Ops[0], Ops.size()));
1807     }
1808     }
1809     break;
1810   }
1811
1812   case ISD::CALLSEQ_START: {
1813     SDNode *CallEnd = FindCallEndFromCallStart(Node);
1814
1815     // Recursively Legalize all of the inputs of the call end that do not lead
1816     // to this call start.  This ensures that any libcalls that need be inserted
1817     // are inserted *before* the CALLSEQ_START.
1818     IsLegalizingCallArgs = true;
1819     {SmallPtrSet<SDNode*, 32> NodesLeadingTo;
1820     for (unsigned i = 0, e = CallEnd->getNumOperands(); i != e; ++i)
1821       LegalizeAllNodesNotLeadingTo(CallEnd->getOperand(i).getNode(), Node,
1822                                    NodesLeadingTo);
1823     }
1824     IsLegalizingCallArgs = false;
1825
1826     // Now that we legalized all of the inputs (which may have inserted
1827     // libcalls) create the new CALLSEQ_START node.
1828     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1829
1830     // Merge in the last call, to ensure that this call start after the last
1831     // call ended.
1832     if (LastCALLSEQ_END.getOpcode() != ISD::EntryToken) {
1833       Tmp1 = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1834                          Tmp1, LastCALLSEQ_END);
1835       Tmp1 = LegalizeOp(Tmp1);
1836     }
1837
1838     // Do not try to legalize the target-specific arguments (#1+).
1839     if (Tmp1 != Node->getOperand(0)) {
1840       SmallVector<SDValue, 8> Ops(Node->op_begin(), Node->op_end());
1841       Ops[0] = Tmp1;
1842       Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
1843     }
1844
1845     // Remember that the CALLSEQ_START is legalized.
1846     AddLegalizedOperand(Op.getValue(0), Result);
1847     if (Node->getNumValues() == 2)    // If this has a flag result, remember it.
1848       AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
1849
1850     // Now that the callseq_start and all of the non-call nodes above this call
1851     // sequence have been legalized, legalize the call itself.  During this
1852     // process, no libcalls can/will be inserted, guaranteeing that no calls
1853     // can overlap.
1854     assert(!IsLegalizingCall && "Inconsistent sequentialization of calls!");
1855     // Note that we are selecting this call!
1856     LastCALLSEQ_END = SDValue(CallEnd, 0);
1857     IsLegalizingCall = true;
1858
1859     // Legalize the call, starting from the CALLSEQ_END.
1860     LegalizeOp(LastCALLSEQ_END);
1861     assert(!IsLegalizingCall && "CALLSEQ_END should have cleared this!");
1862     return Result;
1863   }
1864   case ISD::CALLSEQ_END:
1865     // If the CALLSEQ_START node hasn't been legalized first, legalize it.  This
1866     // will cause this node to be legalized as well as handling libcalls right.
1867     if (LastCALLSEQ_END.getNode() != Node) {
1868       LegalizeOp(SDValue(FindCallStartFromCallEnd(Node), 0));
1869       DenseMap<SDValue, SDValue>::iterator I = LegalizedNodes.find(Op);
1870       assert(I != LegalizedNodes.end() &&
1871              "Legalizing the call start should have legalized this node!");
1872       return I->second;
1873     }
1874
1875     // Otherwise, the call start has been legalized and everything is going
1876     // according to plan.  Just legalize ourselves normally here.
1877     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1878     // Do not try to legalize the target-specific arguments (#1+), except for
1879     // an optional flag input.
1880     if (Node->getOperand(Node->getNumOperands()-1).getValueType() != MVT::Flag){
1881       if (Tmp1 != Node->getOperand(0)) {
1882         SmallVector<SDValue, 8> Ops(Node->op_begin(), Node->op_end());
1883         Ops[0] = Tmp1;
1884         Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
1885       }
1886     } else {
1887       Tmp2 = LegalizeOp(Node->getOperand(Node->getNumOperands()-1));
1888       if (Tmp1 != Node->getOperand(0) ||
1889           Tmp2 != Node->getOperand(Node->getNumOperands()-1)) {
1890         SmallVector<SDValue, 8> Ops(Node->op_begin(), Node->op_end());
1891         Ops[0] = Tmp1;
1892         Ops.back() = Tmp2;
1893         Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
1894       }
1895     }
1896     assert(IsLegalizingCall && "Call sequence imbalance between start/end?");
1897     // This finishes up call legalization.
1898     IsLegalizingCall = false;
1899
1900     // If the CALLSEQ_END node has a flag, remember that we legalized it.
1901     AddLegalizedOperand(SDValue(Node, 0), Result.getValue(0));
1902     if (Node->getNumValues() == 2)
1903       AddLegalizedOperand(SDValue(Node, 1), Result.getValue(1));
1904     return Result.getValue(Op.getResNo());
1905   case ISD::DYNAMIC_STACKALLOC: {
1906     MVT VT = Node->getValueType(0);
1907     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1908     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the size.
1909     Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the alignment.
1910     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
1911
1912     Tmp1 = Result.getValue(0);
1913     Tmp2 = Result.getValue(1);
1914     switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
1915     default: assert(0 && "This action is not supported yet!");
1916     case TargetLowering::Expand: {
1917       unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
1918       assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
1919              " not tell us which reg is the stack pointer!");
1920       SDValue Chain = Tmp1.getOperand(0);
1921
1922       // Chain the dynamic stack allocation so that it doesn't modify the stack
1923       // pointer when other instructions are using the stack.
1924       Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true));
1925
1926       SDValue Size  = Tmp2.getOperand(1);
1927       SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
1928       Chain = SP.getValue(1);
1929       unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
1930       unsigned StackAlign =
1931         TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
1932       if (Align > StackAlign)
1933         SP = DAG.getNode(ISD::AND, dl, VT, SP,
1934                          DAG.getConstant(-(uint64_t)Align, VT));
1935       Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size);       // Value
1936       Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1);     // Output chain
1937
1938       Tmp2 = DAG.getCALLSEQ_END(Chain,  DAG.getIntPtrConstant(0, true),
1939                                 DAG.getIntPtrConstant(0, true), SDValue());
1940
1941       Tmp1 = LegalizeOp(Tmp1);
1942       Tmp2 = LegalizeOp(Tmp2);
1943       break;
1944     }
1945     case TargetLowering::Custom:
1946       Tmp3 = TLI.LowerOperation(Tmp1, DAG);
1947       if (Tmp3.getNode()) {
1948         Tmp1 = LegalizeOp(Tmp3);
1949         Tmp2 = LegalizeOp(Tmp3.getValue(1));
1950       }
1951       break;
1952     case TargetLowering::Legal:
1953       break;
1954     }
1955     // Since this op produce two values, make sure to remember that we
1956     // legalized both of them.
1957     AddLegalizedOperand(SDValue(Node, 0), Tmp1);
1958     AddLegalizedOperand(SDValue(Node, 1), Tmp2);
1959     return Op.getResNo() ? Tmp2 : Tmp1;
1960   }
1961   case ISD::INLINEASM: {
1962     SmallVector<SDValue, 8> Ops(Node->op_begin(), Node->op_end());
1963     bool Changed = false;
1964     // Legalize all of the operands of the inline asm, in case they are nodes
1965     // that need to be expanded or something.  Note we skip the asm string and
1966     // all of the TargetConstant flags.
1967     SDValue Op = LegalizeOp(Ops[0]);
1968     Changed = Op != Ops[0];
1969     Ops[0] = Op;
1970
1971     bool HasInFlag = Ops.back().getValueType() == MVT::Flag;
1972     for (unsigned i = 2, e = Ops.size()-HasInFlag; i < e; ) {
1973       unsigned NumVals = InlineAsm::
1974         getNumOperandRegisters(cast<ConstantSDNode>(Ops[i])->getZExtValue());
1975       for (++i; NumVals; ++i, --NumVals) {
1976         SDValue Op = LegalizeOp(Ops[i]);
1977         if (Op != Ops[i]) {
1978           Changed = true;
1979           Ops[i] = Op;
1980         }
1981       }
1982     }
1983
1984     if (HasInFlag) {
1985       Op = LegalizeOp(Ops.back());
1986       Changed |= Op != Ops.back();
1987       Ops.back() = Op;
1988     }
1989
1990     if (Changed)
1991       Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
1992
1993     // INLINE asm returns a chain and flag, make sure to add both to the map.
1994     AddLegalizedOperand(SDValue(Node, 0), Result.getValue(0));
1995     AddLegalizedOperand(SDValue(Node, 1), Result.getValue(1));
1996     return Result.getValue(Op.getResNo());
1997   }
1998   case ISD::BR:
1999     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2000     // Ensure that libcalls are emitted before a branch.
2001     Tmp1 = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Tmp1, LastCALLSEQ_END);
2002     Tmp1 = LegalizeOp(Tmp1);
2003     LastCALLSEQ_END = DAG.getEntryNode();
2004
2005     Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
2006     break;
2007   case ISD::BRIND:
2008     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2009     // Ensure that libcalls are emitted before a branch.
2010     Tmp1 = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Tmp1, LastCALLSEQ_END);
2011     Tmp1 = LegalizeOp(Tmp1);
2012     LastCALLSEQ_END = DAG.getEntryNode();
2013
2014     switch (getTypeAction(Node->getOperand(1).getValueType())) {
2015     default: assert(0 && "Indirect target must be legal type (pointer)!");
2016     case Legal:
2017       Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the condition.
2018       break;
2019     }
2020     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
2021     break;
2022   case ISD::BR_JT:
2023     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2024     // Ensure that libcalls are emitted before a branch.
2025     Tmp1 = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Tmp1, LastCALLSEQ_END);
2026     Tmp1 = LegalizeOp(Tmp1);
2027     LastCALLSEQ_END = DAG.getEntryNode();
2028
2029     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the jumptable node.
2030     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
2031
2032     switch (TLI.getOperationAction(ISD::BR_JT, MVT::Other)) {
2033     default: assert(0 && "This action is not supported yet!");
2034     case TargetLowering::Legal: break;
2035     case TargetLowering::Custom:
2036       Tmp1 = TLI.LowerOperation(Result, DAG);
2037       if (Tmp1.getNode()) Result = Tmp1;
2038       break;
2039     case TargetLowering::Expand: {
2040       SDValue Chain = Result.getOperand(0);
2041       SDValue Table = Result.getOperand(1);
2042       SDValue Index = Result.getOperand(2);
2043
2044       MVT PTy = TLI.getPointerTy();
2045       MachineFunction &MF = DAG.getMachineFunction();
2046       unsigned EntrySize = MF.getJumpTableInfo()->getEntrySize();
2047       Index= DAG.getNode(ISD::MUL, dl, PTy,
2048                          Index, DAG.getConstant(EntrySize, PTy));
2049       SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
2050
2051       MVT MemVT = MVT::getIntegerVT(EntrySize * 8);
2052       SDValue LD = DAG.getExtLoad(ISD::SEXTLOAD, dl, PTy, Chain, Addr,
2053                                   PseudoSourceValue::getJumpTable(), 0, MemVT);
2054       Addr = LD;
2055       if (TLI.getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2056         // For PIC, the sequence is:
2057         // BRIND(load(Jumptable + index) + RelocBase)
2058         // RelocBase can be JumpTable, GOT or some sort of global base.
2059         Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr,
2060                            TLI.getPICJumpTableRelocBase(Table, DAG));
2061       }
2062       Result = DAG.getNode(ISD::BRIND, dl, MVT::Other, LD.getValue(1), Addr);
2063     }
2064     }
2065     break;
2066   case ISD::BRCOND:
2067     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2068     // Ensure that libcalls are emitted before a return.
2069     Tmp1 = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Tmp1, LastCALLSEQ_END);
2070     Tmp1 = LegalizeOp(Tmp1);
2071     LastCALLSEQ_END = DAG.getEntryNode();
2072
2073     switch (getTypeAction(Node->getOperand(1).getValueType())) {
2074     case Expand: assert(0 && "It's impossible to expand bools");
2075     case Legal:
2076       Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the condition.
2077       break;
2078     case Promote: {
2079       Tmp2 = PromoteOp(Node->getOperand(1));  // Promote the condition.
2080
2081       // The top bits of the promoted condition are not necessarily zero, ensure
2082       // that the value is properly zero extended.
2083       unsigned BitWidth = Tmp2.getValueSizeInBits();
2084       if (!DAG.MaskedValueIsZero(Tmp2,
2085                                  APInt::getHighBitsSet(BitWidth, BitWidth-1)))
2086         Tmp2 = DAG.getZeroExtendInReg(Tmp2, dl, MVT::i1);
2087       break;
2088     }
2089     }
2090
2091     // Basic block destination (Op#2) is always legal.
2092     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
2093
2094     switch (TLI.getOperationAction(ISD::BRCOND, MVT::Other)) {
2095     default: assert(0 && "This action is not supported yet!");
2096     case TargetLowering::Legal: break;
2097     case TargetLowering::Custom:
2098       Tmp1 = TLI.LowerOperation(Result, DAG);
2099       if (Tmp1.getNode()) Result = Tmp1;
2100       break;
2101     case TargetLowering::Expand:
2102       // Expand brcond's setcc into its constituent parts and create a BR_CC
2103       // Node.
2104       if (Tmp2.getOpcode() == ISD::SETCC) {
2105         Result = DAG.getNode(ISD::BR_CC, dl, MVT::Other,
2106                              Tmp1, Tmp2.getOperand(2),
2107                              Tmp2.getOperand(0), Tmp2.getOperand(1),
2108                              Node->getOperand(2));
2109       } else {
2110         Result = DAG.getNode(ISD::BR_CC, dl, MVT::Other, Tmp1,
2111                              DAG.getCondCode(ISD::SETNE), Tmp2,
2112                              DAG.getConstant(0, Tmp2.getValueType()),
2113                              Node->getOperand(2));
2114       }
2115       break;
2116     }
2117     break;
2118   case ISD::BR_CC:
2119     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2120     // Ensure that libcalls are emitted before a branch.
2121     Tmp1 = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Tmp1, LastCALLSEQ_END);
2122     Tmp1 = LegalizeOp(Tmp1);
2123     Tmp2 = Node->getOperand(2);              // LHS
2124     Tmp3 = Node->getOperand(3);              // RHS
2125     Tmp4 = Node->getOperand(1);              // CC
2126
2127     LegalizeSetCC(TLI.getSetCCResultType(Tmp2.getValueType()),
2128                   Tmp2, Tmp3, Tmp4, dl);
2129     LastCALLSEQ_END = DAG.getEntryNode();
2130
2131     // If we didn't get both a LHS and RHS back from LegalizeSetCC,
2132     // the LHS is a legal SETCC itself.  In this case, we need to compare
2133     // the result against zero to select between true and false values.
2134     if (Tmp3.getNode() == 0) {
2135       Tmp3 = DAG.getConstant(0, Tmp2.getValueType());
2136       Tmp4 = DAG.getCondCode(ISD::SETNE);
2137     }
2138
2139     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp4, Tmp2, Tmp3,
2140                                     Node->getOperand(4));
2141
2142     switch (TLI.getOperationAction(ISD::BR_CC, Tmp3.getValueType())) {
2143     default: assert(0 && "Unexpected action for BR_CC!");
2144     case TargetLowering::Legal: break;
2145     case TargetLowering::Custom:
2146       Tmp4 = TLI.LowerOperation(Result, DAG);
2147       if (Tmp4.getNode()) Result = Tmp4;
2148       break;
2149     }
2150     break;
2151   case ISD::LOAD: {
2152     LoadSDNode *LD = cast<LoadSDNode>(Node);
2153     Tmp1 = LegalizeOp(LD->getChain());   // Legalize the chain.
2154     Tmp2 = LegalizeOp(LD->getBasePtr()); // Legalize the base pointer.
2155
2156     ISD::LoadExtType ExtType = LD->getExtensionType();
2157     if (ExtType == ISD::NON_EXTLOAD) {
2158       MVT VT = Node->getValueType(0);
2159       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, LD->getOffset());
2160       Tmp3 = Result.getValue(0);
2161       Tmp4 = Result.getValue(1);
2162
2163       switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
2164       default: assert(0 && "This action is not supported yet!");
2165       case TargetLowering::Legal:
2166         // If this is an unaligned load and the target doesn't support it,
2167         // expand it.
2168         if (!TLI.allowsUnalignedMemoryAccesses()) {
2169           unsigned ABIAlignment = TLI.getTargetData()->
2170             getABITypeAlignment(LD->getMemoryVT().getTypeForMVT());
2171           if (LD->getAlignment() < ABIAlignment){
2172             Result = ExpandUnalignedLoad(cast<LoadSDNode>(Result.getNode()), DAG,
2173                                          TLI);
2174             Tmp3 = Result.getOperand(0);
2175             Tmp4 = Result.getOperand(1);
2176             Tmp3 = LegalizeOp(Tmp3);
2177             Tmp4 = LegalizeOp(Tmp4);
2178           }
2179         }
2180         break;
2181       case TargetLowering::Custom:
2182         Tmp1 = TLI.LowerOperation(Tmp3, DAG);
2183         if (Tmp1.getNode()) {
2184           Tmp3 = LegalizeOp(Tmp1);
2185           Tmp4 = LegalizeOp(Tmp1.getValue(1));
2186         }
2187         break;
2188       case TargetLowering::Promote: {
2189         // Only promote a load of vector type to another.
2190         assert(VT.isVector() && "Cannot promote this load!");
2191         // Change base type to a different vector type.
2192         MVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), VT);
2193
2194         Tmp1 = DAG.getLoad(NVT, dl, Tmp1, Tmp2, LD->getSrcValue(),
2195                            LD->getSrcValueOffset(),
2196                            LD->isVolatile(), LD->getAlignment());
2197         Tmp3 = LegalizeOp(DAG.getNode(ISD::BIT_CONVERT, dl, VT, Tmp1));
2198         Tmp4 = LegalizeOp(Tmp1.getValue(1));
2199         break;
2200       }
2201       }
2202       // Since loads produce two values, make sure to remember that we
2203       // legalized both of them.
2204       AddLegalizedOperand(SDValue(Node, 0), Tmp3);
2205       AddLegalizedOperand(SDValue(Node, 1), Tmp4);
2206       return Op.getResNo() ? Tmp4 : Tmp3;
2207     } else {
2208       MVT SrcVT = LD->getMemoryVT();
2209       unsigned SrcWidth = SrcVT.getSizeInBits();
2210       int SVOffset = LD->getSrcValueOffset();
2211       unsigned Alignment = LD->getAlignment();
2212       bool isVolatile = LD->isVolatile();
2213
2214       if (SrcWidth != SrcVT.getStoreSizeInBits() &&
2215           // Some targets pretend to have an i1 loading operation, and actually
2216           // load an i8.  This trick is correct for ZEXTLOAD because the top 7
2217           // bits are guaranteed to be zero; it helps the optimizers understand
2218           // that these bits are zero.  It is also useful for EXTLOAD, since it
2219           // tells the optimizers that those bits are undefined.  It would be
2220           // nice to have an effective generic way of getting these benefits...
2221           // Until such a way is found, don't insist on promoting i1 here.
2222           (SrcVT != MVT::i1 ||
2223            TLI.getLoadExtAction(ExtType, MVT::i1) == TargetLowering::Promote)) {
2224         // Promote to a byte-sized load if not loading an integral number of
2225         // bytes.  For example, promote EXTLOAD:i20 -> EXTLOAD:i24.
2226         unsigned NewWidth = SrcVT.getStoreSizeInBits();
2227         MVT NVT = MVT::getIntegerVT(NewWidth);
2228         SDValue Ch;
2229
2230         // The extra bits are guaranteed to be zero, since we stored them that
2231         // way.  A zext load from NVT thus automatically gives zext from SrcVT.
2232
2233         ISD::LoadExtType NewExtType =
2234           ExtType == ISD::ZEXTLOAD ? ISD::ZEXTLOAD : ISD::EXTLOAD;
2235
2236         Result = DAG.getExtLoad(NewExtType, dl, Node->getValueType(0),
2237                                 Tmp1, Tmp2, LD->getSrcValue(), SVOffset,
2238                                 NVT, isVolatile, Alignment);
2239
2240         Ch = Result.getValue(1); // The chain.
2241
2242         if (ExtType == ISD::SEXTLOAD)
2243           // Having the top bits zero doesn't help when sign extending.
2244           Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl,
2245                                Result.getValueType(),
2246                                Result, DAG.getValueType(SrcVT));
2247         else if (ExtType == ISD::ZEXTLOAD || NVT == Result.getValueType())
2248           // All the top bits are guaranteed to be zero - inform the optimizers.
2249           Result = DAG.getNode(ISD::AssertZext, dl,
2250                                Result.getValueType(), Result,
2251                                DAG.getValueType(SrcVT));
2252
2253         Tmp1 = LegalizeOp(Result);
2254         Tmp2 = LegalizeOp(Ch);
2255       } else if (SrcWidth & (SrcWidth - 1)) {
2256         // If not loading a power-of-2 number of bits, expand as two loads.
2257         assert(SrcVT.isExtended() && !SrcVT.isVector() &&
2258                "Unsupported extload!");
2259         unsigned RoundWidth = 1 << Log2_32(SrcWidth);
2260         assert(RoundWidth < SrcWidth);
2261         unsigned ExtraWidth = SrcWidth - RoundWidth;
2262         assert(ExtraWidth < RoundWidth);
2263         assert(!(RoundWidth % 8) && !(ExtraWidth % 8) &&
2264                "Load size not an integral number of bytes!");
2265         MVT RoundVT = MVT::getIntegerVT(RoundWidth);
2266         MVT ExtraVT = MVT::getIntegerVT(ExtraWidth);
2267         SDValue Lo, Hi, Ch;
2268         unsigned IncrementSize;
2269
2270         if (TLI.isLittleEndian()) {
2271           // EXTLOAD:i24 -> ZEXTLOAD:i16 | (shl EXTLOAD@+2:i8, 16)
2272           // Load the bottom RoundWidth bits.
2273           Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl,
2274                               Node->getValueType(0), Tmp1, Tmp2,
2275                               LD->getSrcValue(), SVOffset, RoundVT, isVolatile,
2276                               Alignment);
2277
2278           // Load the remaining ExtraWidth bits.
2279           IncrementSize = RoundWidth / 8;
2280           Tmp2 = DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
2281                              DAG.getIntPtrConstant(IncrementSize));
2282           Hi = DAG.getExtLoad(ExtType, dl, Node->getValueType(0), Tmp1, Tmp2,
2283                               LD->getSrcValue(), SVOffset + IncrementSize,
2284                               ExtraVT, isVolatile,
2285                               MinAlign(Alignment, IncrementSize));
2286
2287           // Build a factor node to remember that this load is independent of the
2288           // other one.
2289           Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
2290                            Hi.getValue(1));
2291
2292           // Move the top bits to the right place.
2293           Hi = DAG.getNode(ISD::SHL, dl, Hi.getValueType(), Hi,
2294                            DAG.getConstant(RoundWidth, TLI.getShiftAmountTy()));
2295
2296           // Join the hi and lo parts.
2297           Result = DAG.getNode(ISD::OR, dl, Node->getValueType(0), Lo, Hi);
2298         } else {
2299           // Big endian - avoid unaligned loads.
2300           // EXTLOAD:i24 -> (shl EXTLOAD:i16, 8) | ZEXTLOAD@+2:i8
2301           // Load the top RoundWidth bits.
2302           Hi = DAG.getExtLoad(ExtType, dl, Node->getValueType(0), Tmp1, Tmp2,
2303                               LD->getSrcValue(), SVOffset, RoundVT, isVolatile,
2304                               Alignment);
2305
2306           // Load the remaining ExtraWidth bits.
2307           IncrementSize = RoundWidth / 8;
2308           Tmp2 = DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
2309                              DAG.getIntPtrConstant(IncrementSize));
2310           Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl,
2311                               Node->getValueType(0), Tmp1, Tmp2,
2312                               LD->getSrcValue(), SVOffset + IncrementSize,
2313                               ExtraVT, isVolatile,
2314                               MinAlign(Alignment, IncrementSize));
2315
2316           // Build a factor node to remember that this load is independent of the
2317           // other one.
2318           Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
2319                            Hi.getValue(1));
2320
2321           // Move the top bits to the right place.
2322           Hi = DAG.getNode(ISD::SHL, dl, Hi.getValueType(), Hi,
2323                            DAG.getConstant(ExtraWidth, TLI.getShiftAmountTy()));
2324
2325           // Join the hi and lo parts.
2326           Result = DAG.getNode(ISD::OR, dl, Node->getValueType(0), Lo, Hi);
2327         }
2328
2329         Tmp1 = LegalizeOp(Result);
2330         Tmp2 = LegalizeOp(Ch);
2331       } else {
2332         switch (TLI.getLoadExtAction(ExtType, SrcVT)) {
2333         default: assert(0 && "This action is not supported yet!");
2334         case TargetLowering::Custom:
2335           isCustom = true;
2336           // FALLTHROUGH
2337         case TargetLowering::Legal:
2338           Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, LD->getOffset());
2339           Tmp1 = Result.getValue(0);
2340           Tmp2 = Result.getValue(1);
2341
2342           if (isCustom) {
2343             Tmp3 = TLI.LowerOperation(Result, DAG);
2344             if (Tmp3.getNode()) {
2345               Tmp1 = LegalizeOp(Tmp3);
2346               Tmp2 = LegalizeOp(Tmp3.getValue(1));
2347             }
2348           } else {
2349             // If this is an unaligned load and the target doesn't support it,
2350             // expand it.
2351             if (!TLI.allowsUnalignedMemoryAccesses()) {
2352               unsigned ABIAlignment = TLI.getTargetData()->
2353                 getABITypeAlignment(LD->getMemoryVT().getTypeForMVT());
2354               if (LD->getAlignment() < ABIAlignment){
2355                 Result = ExpandUnalignedLoad(cast<LoadSDNode>(Result.getNode()), DAG,
2356                                              TLI);
2357                 Tmp1 = Result.getOperand(0);
2358                 Tmp2 = Result.getOperand(1);
2359                 Tmp1 = LegalizeOp(Tmp1);
2360                 Tmp2 = LegalizeOp(Tmp2);
2361               }
2362             }
2363           }
2364           break;
2365         case TargetLowering::Expand:
2366           // f64 = EXTLOAD f32 should expand to LOAD, FP_EXTEND
2367           if (SrcVT == MVT::f32 && Node->getValueType(0) == MVT::f64) {
2368             SDValue Load = DAG.getLoad(SrcVT, dl, Tmp1, Tmp2, LD->getSrcValue(),
2369                                          LD->getSrcValueOffset(),
2370                                          LD->isVolatile(), LD->getAlignment());
2371             Result = DAG.getNode(ISD::FP_EXTEND, dl,
2372                                  Node->getValueType(0), Load);
2373             Tmp1 = LegalizeOp(Result);  // Relegalize new nodes.
2374             Tmp2 = LegalizeOp(Load.getValue(1));
2375             break;
2376           }
2377           assert(ExtType != ISD::EXTLOAD &&"EXTLOAD should always be supported!");
2378           // Turn the unsupported load into an EXTLOAD followed by an explicit
2379           // zero/sign extend inreg.
2380           Result = DAG.getExtLoad(ISD::EXTLOAD, dl, Node->getValueType(0),
2381                                   Tmp1, Tmp2, LD->getSrcValue(),
2382                                   LD->getSrcValueOffset(), SrcVT,
2383                                   LD->isVolatile(), LD->getAlignment());
2384           SDValue ValRes;
2385           if (ExtType == ISD::SEXTLOAD)
2386             ValRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl,
2387                                  Result.getValueType(),
2388                                  Result, DAG.getValueType(SrcVT));
2389           else
2390             ValRes = DAG.getZeroExtendInReg(Result, dl, SrcVT);
2391           Tmp1 = LegalizeOp(ValRes);  // Relegalize new nodes.
2392           Tmp2 = LegalizeOp(Result.getValue(1));  // Relegalize new nodes.
2393           break;
2394         }
2395       }
2396
2397       // Since loads produce two values, make sure to remember that we legalized
2398       // both of them.
2399       AddLegalizedOperand(SDValue(Node, 0), Tmp1);
2400       AddLegalizedOperand(SDValue(Node, 1), Tmp2);
2401       return Op.getResNo() ? Tmp2 : Tmp1;
2402     }
2403   }
2404   case ISD::EXTRACT_ELEMENT: {
2405     MVT OpTy = Node->getOperand(0).getValueType();
2406     switch (getTypeAction(OpTy)) {
2407     default: assert(0 && "EXTRACT_ELEMENT action for type unimplemented!");
2408     case Legal:
2409       if (cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue()) {
2410         // 1 -> Hi
2411         Result = DAG.getNode(ISD::SRL, dl, OpTy, Node->getOperand(0),
2412                              DAG.getConstant(OpTy.getSizeInBits()/2,
2413                                              TLI.getShiftAmountTy()));
2414         Result = DAG.getNode(ISD::TRUNCATE, dl, Node->getValueType(0), Result);
2415       } else {
2416         // 0 -> Lo
2417         Result = DAG.getNode(ISD::TRUNCATE, dl, Node->getValueType(0),
2418                              Node->getOperand(0));
2419       }
2420       break;
2421     case Expand:
2422       // Get both the low and high parts.
2423       ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
2424       if (cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue())
2425         Result = Tmp2;  // 1 -> Hi
2426       else
2427         Result = Tmp1;  // 0 -> Lo
2428       break;
2429     }
2430     break;
2431   }
2432
2433   case ISD::CopyToReg:
2434     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2435
2436     assert(isTypeLegal(Node->getOperand(2).getValueType()) &&
2437            "Register type must be legal!");
2438     // Legalize the incoming value (must be a legal type).
2439     Tmp2 = LegalizeOp(Node->getOperand(2));
2440     if (Node->getNumValues() == 1) {
2441       Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1), Tmp2);
2442     } else {
2443       assert(Node->getNumValues() == 2 && "Unknown CopyToReg");
2444       if (Node->getNumOperands() == 4) {
2445         Tmp3 = LegalizeOp(Node->getOperand(3));
2446         Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1), Tmp2,
2447                                         Tmp3);
2448       } else {
2449         Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1),Tmp2);
2450       }
2451
2452       // Since this produces two values, make sure to remember that we legalized
2453       // both of them.
2454       AddLegalizedOperand(SDValue(Node, 0), Result.getValue(0));
2455       AddLegalizedOperand(SDValue(Node, 1), Result.getValue(1));
2456       return Result;
2457     }
2458     break;
2459
2460   case ISD::RET:
2461     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2462
2463     // Ensure that libcalls are emitted before a return.
2464     Tmp1 = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Tmp1, LastCALLSEQ_END);
2465     Tmp1 = LegalizeOp(Tmp1);
2466     LastCALLSEQ_END = DAG.getEntryNode();
2467
2468     switch (Node->getNumOperands()) {
2469     case 3:  // ret val
2470       Tmp2 = Node->getOperand(1);
2471       Tmp3 = Node->getOperand(2);  // Signness
2472       switch (getTypeAction(Tmp2.getValueType())) {
2473       case Legal:
2474         Result = DAG.UpdateNodeOperands(Result, Tmp1, LegalizeOp(Tmp2), Tmp3);
2475         break;
2476       case Expand:
2477         if (!Tmp2.getValueType().isVector()) {
2478           SDValue Lo, Hi;
2479           ExpandOp(Tmp2, Lo, Hi);
2480
2481           // Big endian systems want the hi reg first.
2482           if (TLI.isBigEndian())
2483             std::swap(Lo, Hi);
2484
2485           if (Hi.getNode())
2486             Result = DAG.getNode(ISD::RET, dl, MVT::Other,
2487                                  Tmp1, Lo, Tmp3, Hi, Tmp3);
2488           else
2489             Result = DAG.getNode(ISD::RET, dl, MVT::Other, Tmp1, Lo, Tmp3);
2490           Result = LegalizeOp(Result);
2491         } else {
2492           SDNode *InVal = Tmp2.getNode();
2493           int InIx = Tmp2.getResNo();
2494           unsigned NumElems = InVal->getValueType(InIx).getVectorNumElements();
2495           MVT EVT = InVal->getValueType(InIx).getVectorElementType();
2496
2497           // Figure out if there is a simple type corresponding to this Vector
2498           // type.  If so, convert to the vector type.
2499           MVT TVT = MVT::getVectorVT(EVT, NumElems);
2500           if (TLI.isTypeLegal(TVT)) {
2501             // Turn this into a return of the vector type.
2502             Tmp2 = LegalizeOp(Tmp2);
2503             Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
2504           } else if (NumElems == 1) {
2505             // Turn this into a return of the scalar type.
2506             Tmp2 = ScalarizeVectorOp(Tmp2);
2507             Tmp2 = LegalizeOp(Tmp2);
2508             Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
2509
2510             // FIXME: Returns of gcc generic vectors smaller than a legal type
2511             // should be returned in integer registers!
2512
2513             // The scalarized value type may not be legal, e.g. it might require
2514             // promotion or expansion.  Relegalize the return.
2515             Result = LegalizeOp(Result);
2516           } else {
2517             // FIXME: Returns of gcc generic vectors larger than a legal vector
2518             // type should be returned by reference!
2519             SDValue Lo, Hi;
2520             SplitVectorOp(Tmp2, Lo, Hi);
2521             Result = DAG.getNode(ISD::RET, dl, MVT::Other,
2522                                  Tmp1, Lo, Tmp3, Hi, Tmp3);
2523             Result = LegalizeOp(Result);
2524           }
2525         }
2526         break;
2527       case Promote:
2528         Tmp2 = PromoteOp(Node->getOperand(1));
2529         Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
2530         Result = LegalizeOp(Result);
2531         break;
2532       }
2533       break;
2534     case 1:  // ret void
2535       Result = DAG.UpdateNodeOperands(Result, Tmp1);
2536       break;
2537     default: { // ret <values>
2538       SmallVector<SDValue, 8> NewValues;
2539       NewValues.push_back(Tmp1);
2540       for (unsigned i = 1, e = Node->getNumOperands(); i < e; i += 2)
2541         switch (getTypeAction(Node->getOperand(i).getValueType())) {
2542         case Legal:
2543           NewValues.push_back(LegalizeOp(Node->getOperand(i)));
2544           NewValues.push_back(Node->getOperand(i+1));
2545           break;
2546         case Expand: {
2547           SDValue Lo, Hi;
2548           assert(!Node->getOperand(i).getValueType().isExtended() &&
2549                  "FIXME: TODO: implement returning non-legal vector types!");
2550           ExpandOp(Node->getOperand(i), Lo, Hi);
2551           NewValues.push_back(Lo);
2552           NewValues.push_back(Node->getOperand(i+1));
2553           if (Hi.getNode()) {
2554             NewValues.push_back(Hi);
2555             NewValues.push_back(Node->getOperand(i+1));
2556           }
2557           break;
2558         }
2559         case Promote:
2560           assert(0 && "Can't promote multiple return value yet!");
2561         }
2562
2563       if (NewValues.size() == Node->getNumOperands())
2564         Result = DAG.UpdateNodeOperands(Result, &NewValues[0],NewValues.size());
2565       else
2566         Result = DAG.getNode(ISD::RET, dl, MVT::Other,
2567                              &NewValues[0], NewValues.size());
2568       break;
2569     }
2570     }
2571
2572     if (Result.getOpcode() == ISD::RET) {
2573       switch (TLI.getOperationAction(Result.getOpcode(), MVT::Other)) {
2574       default: assert(0 && "This action is not supported yet!");
2575       case TargetLowering::Legal: break;
2576       case TargetLowering::Custom:
2577         Tmp1 = TLI.LowerOperation(Result, DAG);
2578         if (Tmp1.getNode()) Result = Tmp1;
2579         break;
2580       }
2581     }
2582     break;
2583   case ISD::STORE: {
2584     StoreSDNode *ST = cast<StoreSDNode>(Node);
2585     Tmp1 = LegalizeOp(ST->getChain());    // Legalize the chain.
2586     Tmp2 = LegalizeOp(ST->getBasePtr());  // Legalize the pointer.
2587     int SVOffset = ST->getSrcValueOffset();
2588     unsigned Alignment = ST->getAlignment();
2589     bool isVolatile = ST->isVolatile();
2590
2591     if (!ST->isTruncatingStore()) {
2592       // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
2593       // FIXME: We shouldn't do this for TargetConstantFP's.
2594       // FIXME: move this to the DAG Combiner!  Note that we can't regress due
2595       // to phase ordering between legalized code and the dag combiner.  This
2596       // probably means that we need to integrate dag combiner and legalizer
2597       // together.
2598       // We generally can't do this one for long doubles.
2599       if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(ST->getValue())) {
2600         if (CFP->getValueType(0) == MVT::f32 &&
2601             getTypeAction(MVT::i32) == Legal) {
2602           Tmp3 = DAG.getConstant(CFP->getValueAPF().
2603                                           bitcastToAPInt().zextOrTrunc(32),
2604                                   MVT::i32);
2605           Result = DAG.getStore(Tmp1, dl, Tmp3, Tmp2, ST->getSrcValue(),
2606                                 SVOffset, isVolatile, Alignment);
2607           break;
2608         } else if (CFP->getValueType(0) == MVT::f64) {
2609           // If this target supports 64-bit registers, do a single 64-bit store.
2610           if (getTypeAction(MVT::i64) == Legal) {
2611             Tmp3 = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
2612                                      zextOrTrunc(64), MVT::i64);
2613             Result = DAG.getStore(Tmp1, dl, Tmp3, Tmp2, ST->getSrcValue(),
2614                                   SVOffset, isVolatile, Alignment);
2615             break;
2616           } else if (getTypeAction(MVT::i32) == Legal && !ST->isVolatile()) {
2617             // Otherwise, if the target supports 32-bit registers, use 2 32-bit
2618             // stores.  If the target supports neither 32- nor 64-bits, this
2619             // xform is certainly not worth it.
2620             const APInt &IntVal =CFP->getValueAPF().bitcastToAPInt();
2621             SDValue Lo = DAG.getConstant(APInt(IntVal).trunc(32), MVT::i32);
2622             SDValue Hi = DAG.getConstant(IntVal.lshr(32).trunc(32), MVT::i32);
2623             if (TLI.isBigEndian()) std::swap(Lo, Hi);
2624
2625             Lo = DAG.getStore(Tmp1, dl, Lo, Tmp2, ST->getSrcValue(),
2626                               SVOffset, isVolatile, Alignment);
2627             Tmp2 = DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
2628                                DAG.getIntPtrConstant(4));
2629             Hi = DAG.getStore(Tmp1, dl, Hi, Tmp2, ST->getSrcValue(), SVOffset+4,
2630                               isVolatile, MinAlign(Alignment, 4U));
2631
2632             Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi);
2633             break;
2634           }
2635         }
2636       }
2637
2638       switch (getTypeAction(ST->getMemoryVT())) {
2639       case Legal: {
2640         Tmp3 = LegalizeOp(ST->getValue());
2641         Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp3, Tmp2,
2642                                         ST->getOffset());
2643
2644         MVT VT = Tmp3.getValueType();
2645         switch (TLI.getOperationAction(ISD::STORE, VT)) {
2646         default: assert(0 && "This action is not supported yet!");
2647         case TargetLowering::Legal:
2648           // If this is an unaligned store and the target doesn't support it,
2649           // expand it.
2650           if (!TLI.allowsUnalignedMemoryAccesses()) {
2651             unsigned ABIAlignment = TLI.getTargetData()->
2652               getABITypeAlignment(ST->getMemoryVT().getTypeForMVT());
2653             if (ST->getAlignment() < ABIAlignment)
2654               Result = ExpandUnalignedStore(cast<StoreSDNode>(Result.getNode()), DAG,
2655                                             TLI);
2656           }
2657           break;
2658         case TargetLowering::Custom:
2659           Tmp1 = TLI.LowerOperation(Result, DAG);
2660           if (Tmp1.getNode()) Result = Tmp1;
2661           break;
2662         case TargetLowering::Promote:
2663           assert(VT.isVector() && "Unknown legal promote case!");
2664           Tmp3 = DAG.getNode(ISD::BIT_CONVERT, dl,
2665                              TLI.getTypeToPromoteTo(ISD::STORE, VT), Tmp3);
2666           Result = DAG.getStore(Tmp1, dl, Tmp3, Tmp2,
2667                                 ST->getSrcValue(), SVOffset, isVolatile,
2668                                 Alignment);
2669           break;
2670         }
2671         break;
2672       }
2673       case Promote:
2674         if (!ST->getMemoryVT().isVector()) {
2675           // Truncate the value and store the result.
2676           Tmp3 = PromoteOp(ST->getValue());
2677           Result = DAG.getTruncStore(Tmp1, dl, Tmp3, Tmp2, ST->getSrcValue(),
2678                                      SVOffset, ST->getMemoryVT(),
2679                                      isVolatile, Alignment);
2680           break;
2681         }
2682         // Fall thru to expand for vector
2683       case Expand: {
2684         unsigned IncrementSize = 0;
2685         SDValue Lo, Hi;
2686
2687         // If this is a vector type, then we have to calculate the increment as
2688         // the product of the element size in bytes, and the number of elements
2689         // in the high half of the vector.
2690         if (ST->getValue().getValueType().isVector()) {
2691           SDNode *InVal = ST->getValue().getNode();
2692           int InIx = ST->getValue().getResNo();
2693           MVT InVT = InVal->getValueType(InIx);
2694           unsigned NumElems = InVT.getVectorNumElements();
2695           MVT EVT = InVT.getVectorElementType();
2696
2697           // Figure out if there is a simple type corresponding to this Vector
2698           // type.  If so, convert to the vector type.
2699           MVT TVT = MVT::getVectorVT(EVT, NumElems);
2700           if (TLI.isTypeLegal(TVT)) {
2701             // Turn this into a normal store of the vector type.
2702             Tmp3 = LegalizeOp(ST->getValue());
2703             Result = DAG.getStore(Tmp1, dl, Tmp3, Tmp2, ST->getSrcValue(),
2704                                   SVOffset, isVolatile, Alignment);
2705             Result = LegalizeOp(Result);
2706             break;
2707           } else if (NumElems == 1) {
2708             // Turn this into a normal store of the scalar type.
2709             Tmp3 = ScalarizeVectorOp(ST->getValue());
2710             Result = DAG.getStore(Tmp1, dl, Tmp3, Tmp2, ST->getSrcValue(),
2711                                   SVOffset, isVolatile, Alignment);
2712             // The scalarized value type may not be legal, e.g. it might require
2713             // promotion or expansion.  Relegalize the scalar store.
2714             Result = LegalizeOp(Result);
2715             break;
2716           } else {
2717             // Check if we have widen this node with another value
2718             std::map<SDValue, SDValue>::iterator I =
2719               WidenNodes.find(ST->getValue());
2720             if (I != WidenNodes.end()) {
2721               Result = StoreWidenVectorOp(ST, Tmp1, Tmp2);
2722               break;
2723             }
2724             else {
2725               SplitVectorOp(ST->getValue(), Lo, Hi);
2726               IncrementSize = Lo.getNode()->getValueType(0).getVectorNumElements() *
2727                               EVT.getSizeInBits()/8;
2728             }
2729           }
2730         } else {
2731           ExpandOp(ST->getValue(), Lo, Hi);
2732           IncrementSize = Hi.getNode() ? Hi.getValueType().getSizeInBits()/8 : 0;
2733
2734           if (Hi.getNode() && TLI.isBigEndian())
2735             std::swap(Lo, Hi);
2736         }
2737
2738         Lo = DAG.getStore(Tmp1, dl, Lo, Tmp2, ST->getSrcValue(),
2739                           SVOffset, isVolatile, Alignment);
2740
2741         if (Hi.getNode() == NULL) {
2742           // Must be int <-> float one-to-one expansion.
2743           Result = Lo;
2744           break;
2745         }
2746
2747         Tmp2 = DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
2748                            DAG.getIntPtrConstant(IncrementSize));
2749         assert(isTypeLegal(Tmp2.getValueType()) &&
2750                "Pointers must be legal!");
2751         SVOffset += IncrementSize;
2752         Alignment = MinAlign(Alignment, IncrementSize);
2753         Hi = DAG.getStore(Tmp1, dl, Hi, Tmp2, ST->getSrcValue(),
2754                           SVOffset, isVolatile, Alignment);
2755         Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi);
2756         break;
2757       }  // case Expand
2758       }
2759     } else {
2760       switch (getTypeAction(ST->getValue().getValueType())) {
2761       case Legal:
2762         Tmp3 = LegalizeOp(ST->getValue());
2763         break;
2764       case Promote:
2765         if (!ST->getValue().getValueType().isVector()) {
2766           // We can promote the value, the truncstore will still take care of it.
2767           Tmp3 = PromoteOp(ST->getValue());
2768           break;
2769         }
2770         // Vector case falls through to expand
2771       case Expand:
2772         // Just store the low part.  This may become a non-trunc store, so make
2773         // sure to use getTruncStore, not UpdateNodeOperands below.
2774         ExpandOp(ST->getValue(), Tmp3, Tmp4);
2775         return DAG.getTruncStore(Tmp1, dl, Tmp3, Tmp2, ST->getSrcValue(),
2776                                  SVOffset, MVT::i8, isVolatile, Alignment);
2777       }
2778
2779       MVT StVT = ST->getMemoryVT();
2780       unsigned StWidth = StVT.getSizeInBits();
2781
2782       if (StWidth != StVT.getStoreSizeInBits()) {
2783         // Promote to a byte-sized store with upper bits zero if not
2784         // storing an integral number of bytes.  For example, promote
2785         // TRUNCSTORE:i1 X -> TRUNCSTORE:i8 (and X, 1)
2786         MVT NVT = MVT::getIntegerVT(StVT.getStoreSizeInBits());
2787         Tmp3 = DAG.getZeroExtendInReg(Tmp3, dl, StVT);
2788         Result = DAG.getTruncStore(Tmp1, dl, Tmp3, Tmp2, ST->getSrcValue(),
2789                                    SVOffset, NVT, isVolatile, Alignment);
2790       } else if (StWidth & (StWidth - 1)) {
2791         // If not storing a power-of-2 number of bits, expand as two stores.
2792         assert(StVT.isExtended() && !StVT.isVector() &&
2793                "Unsupported truncstore!");
2794         unsigned RoundWidth = 1 << Log2_32(StWidth);
2795         assert(RoundWidth < StWidth);
2796         unsigned ExtraWidth = StWidth - RoundWidth;
2797         assert(ExtraWidth < RoundWidth);
2798         assert(!(RoundWidth % 8) && !(ExtraWidth % 8) &&
2799                "Store size not an integral number of bytes!");
2800         MVT RoundVT = MVT::getIntegerVT(RoundWidth);
2801         MVT ExtraVT = MVT::getIntegerVT(ExtraWidth);
2802         SDValue Lo, Hi;
2803         unsigned IncrementSize;
2804
2805         if (TLI.isLittleEndian()) {
2806           // TRUNCSTORE:i24 X -> TRUNCSTORE:i16 X, TRUNCSTORE@+2:i8 (srl X, 16)
2807           // Store the bottom RoundWidth bits.
2808           Lo = DAG.getTruncStore(Tmp1, dl, Tmp3, Tmp2, ST->getSrcValue(),
2809                                  SVOffset, RoundVT,
2810                                  isVolatile, Alignment);
2811
2812           // Store the remaining ExtraWidth bits.
2813           IncrementSize = RoundWidth / 8;
2814           Tmp2 = DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
2815                              DAG.getIntPtrConstant(IncrementSize));
2816           Hi = DAG.getNode(ISD::SRL, dl, Tmp3.getValueType(), Tmp3,
2817                            DAG.getConstant(RoundWidth, TLI.getShiftAmountTy()));
2818           Hi = DAG.getTruncStore(Tmp1, dl, Hi, Tmp2, ST->getSrcValue(),
2819                                  SVOffset + IncrementSize, ExtraVT, isVolatile,
2820                                  MinAlign(Alignment, IncrementSize));
2821         } else {
2822           // Big endian - avoid unaligned stores.
2823           // TRUNCSTORE:i24 X -> TRUNCSTORE:i16 (srl X, 8), TRUNCSTORE@+2:i8 X
2824           // Store the top RoundWidth bits.
2825           Hi = DAG.getNode(ISD::SRL, dl, Tmp3.getValueType(), Tmp3,
2826                            DAG.getConstant(ExtraWidth, TLI.getShiftAmountTy()));
2827           Hi = DAG.getTruncStore(Tmp1, dl, Hi, Tmp2, ST->getSrcValue(),
2828                                  SVOffset, RoundVT, isVolatile, Alignment);
2829
2830           // Store the remaining ExtraWidth bits.
2831           IncrementSize = RoundWidth / 8;
2832           Tmp2 = DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
2833                              DAG.getIntPtrConstant(IncrementSize));
2834           Lo = DAG.getTruncStore(Tmp1, dl, Tmp3, Tmp2, ST->getSrcValue(),
2835                                  SVOffset + IncrementSize, ExtraVT, isVolatile,
2836                                  MinAlign(Alignment, IncrementSize));
2837         }
2838
2839         // The order of the stores doesn't matter.
2840         Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi);
2841       } else {
2842         if (Tmp1 != ST->getChain() || Tmp3 != ST->getValue() ||
2843             Tmp2 != ST->getBasePtr())
2844           Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp3, Tmp2,
2845                                           ST->getOffset());
2846
2847         switch (TLI.getTruncStoreAction(ST->getValue().getValueType(), StVT)) {
2848         default: assert(0 && "This action is not supported yet!");
2849         case TargetLowering::Legal:
2850           // If this is an unaligned store and the target doesn't support it,
2851           // expand it.
2852           if (!TLI.allowsUnalignedMemoryAccesses()) {
2853             unsigned ABIAlignment = TLI.getTargetData()->
2854               getABITypeAlignment(ST->getMemoryVT().getTypeForMVT());
2855             if (ST->getAlignment() < ABIAlignment)
2856               Result = ExpandUnalignedStore(cast<StoreSDNode>(Result.getNode()), DAG,
2857                                             TLI);
2858           }
2859           break;
2860         case TargetLowering::Custom:
2861           Result = TLI.LowerOperation(Result, DAG);
2862           break;
2863         case Expand:
2864           // TRUNCSTORE:i16 i32 -> STORE i16
2865           assert(isTypeLegal(StVT) && "Do not know how to expand this store!");
2866           Tmp3 = DAG.getNode(ISD::TRUNCATE, dl, StVT, Tmp3);
2867           Result = DAG.getStore(Tmp1, dl, Tmp3, Tmp2, ST->getSrcValue(),
2868                                 SVOffset, isVolatile, Alignment);
2869           break;
2870         }
2871       }
2872     }
2873     break;
2874   }
2875   case ISD::PCMARKER:
2876     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2877     Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
2878     break;
2879   case ISD::STACKSAVE:
2880     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2881     Result = DAG.UpdateNodeOperands(Result, Tmp1);
2882     Tmp1 = Result.getValue(0);
2883     Tmp2 = Result.getValue(1);
2884
2885     switch (TLI.getOperationAction(ISD::STACKSAVE, MVT::Other)) {
2886     default: assert(0 && "This action is not supported yet!");
2887     case TargetLowering::Legal: break;
2888     case TargetLowering::Custom:
2889       Tmp3 = TLI.LowerOperation(Result, DAG);
2890       if (Tmp3.getNode()) {
2891         Tmp1 = LegalizeOp(Tmp3);
2892         Tmp2 = LegalizeOp(Tmp3.getValue(1));
2893       }
2894       break;
2895     case TargetLowering::Expand:
2896       // Expand to CopyFromReg if the target set
2897       // StackPointerRegisterToSaveRestore.
2898       if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) {
2899         Tmp1 = DAG.getCopyFromReg(Result.getOperand(0), dl, SP,
2900                                   Node->getValueType(0));
2901         Tmp2 = Tmp1.getValue(1);
2902       } else {
2903         Tmp1 = DAG.getUNDEF(Node->getValueType(0));
2904         Tmp2 = Node->getOperand(0);
2905       }
2906       break;
2907     }
2908
2909     // Since stacksave produce two values, make sure to remember that we
2910     // legalized both of them.
2911     AddLegalizedOperand(SDValue(Node, 0), Tmp1);
2912     AddLegalizedOperand(SDValue(Node, 1), Tmp2);
2913     return Op.getResNo() ? Tmp2 : Tmp1;
2914
2915   case ISD::STACKRESTORE:
2916     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2917     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
2918     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
2919
2920     switch (TLI.getOperationAction(ISD::STACKRESTORE, MVT::Other)) {
2921     default: assert(0 && "This action is not supported yet!");
2922     case TargetLowering::Legal: break;
2923     case TargetLowering::Custom:
2924       Tmp1 = TLI.LowerOperation(Result, DAG);
2925       if (Tmp1.getNode()) Result = Tmp1;
2926       break;
2927     case TargetLowering::Expand:
2928       // Expand to CopyToReg if the target set
2929       // StackPointerRegisterToSaveRestore.
2930       if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) {
2931         Result = DAG.getCopyToReg(Tmp1, dl, SP, Tmp2);
2932       } else {
2933         Result = Tmp1;
2934       }
2935       break;
2936     }
2937     break;
2938
2939   case ISD::READCYCLECOUNTER:
2940     Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the chain
2941     Result = DAG.UpdateNodeOperands(Result, Tmp1);
2942     switch (TLI.getOperationAction(ISD::READCYCLECOUNTER,
2943                                    Node->getValueType(0))) {
2944     default: assert(0 && "This action is not supported yet!");
2945     case TargetLowering::Legal:
2946       Tmp1 = Result.getValue(0);
2947       Tmp2 = Result.getValue(1);
2948       break;
2949     case TargetLowering::Custom:
2950       Result = TLI.LowerOperation(Result, DAG);
2951       Tmp1 = LegalizeOp(Result.getValue(0));
2952       Tmp2 = LegalizeOp(Result.getValue(1));
2953       break;
2954     }
2955
2956     // Since rdcc produce two values, make sure to remember that we legalized
2957     // both of them.
2958     AddLegalizedOperand(SDValue(Node, 0), Tmp1);
2959     AddLegalizedOperand(SDValue(Node, 1), Tmp2);
2960     return Result;
2961
2962   case ISD::SELECT:
2963     switch (getTypeAction(Node->getOperand(0).getValueType())) {
2964     case Expand: assert(0 && "It's impossible to expand bools");
2965     case Legal:
2966       Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the condition.
2967       break;
2968     case Promote: {
2969       assert(!Node->getOperand(0).getValueType().isVector() && "not possible");
2970       Tmp1 = PromoteOp(Node->getOperand(0));  // Promote the condition.
2971       // Make sure the condition is either zero or one.
2972       unsigned BitWidth = Tmp1.getValueSizeInBits();
2973       if (!DAG.MaskedValueIsZero(Tmp1,
2974                                  APInt::getHighBitsSet(BitWidth, BitWidth-1)))
2975         Tmp1 = DAG.getZeroExtendInReg(Tmp1, dl, MVT::i1);
2976       break;
2977     }
2978     }
2979     Tmp2 = LegalizeOp(Node->getOperand(1));   // TrueVal
2980     Tmp3 = LegalizeOp(Node->getOperand(2));   // FalseVal
2981
2982     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
2983
2984     switch (TLI.getOperationAction(ISD::SELECT, Tmp2.getValueType())) {
2985     default: assert(0 && "This action is not supported yet!");
2986     case TargetLowering::Legal: break;
2987     case TargetLowering::Custom: {
2988       Tmp1 = TLI.LowerOperation(Result, DAG);
2989       if (Tmp1.getNode()) Result = Tmp1;
2990       break;
2991     }
2992     case TargetLowering::Expand:
2993       if (Tmp1.getOpcode() == ISD::SETCC) {
2994         Result = DAG.getSelectCC(dl, Tmp1.getOperand(0), Tmp1.getOperand(1),
2995                               Tmp2, Tmp3,
2996                               cast<CondCodeSDNode>(Tmp1.getOperand(2))->get());
2997       } else {
2998         Result = DAG.getSelectCC(dl, Tmp1,
2999                                  DAG.getConstant(0, Tmp1.getValueType()),
3000                                  Tmp2, Tmp3, ISD::SETNE);
3001       }
3002       break;
3003     case TargetLowering::Promote: {
3004       MVT NVT =
3005         TLI.getTypeToPromoteTo(ISD::SELECT, Tmp2.getValueType());
3006       unsigned ExtOp, TruncOp;
3007       if (Tmp2.getValueType().isVector()) {
3008         ExtOp   = ISD::BIT_CONVERT;
3009         TruncOp = ISD::BIT_CONVERT;
3010       } else if (Tmp2.getValueType().isInteger()) {
3011         ExtOp   = ISD::ANY_EXTEND;
3012         TruncOp = ISD::TRUNCATE;
3013       } else {
3014         ExtOp   = ISD::FP_EXTEND;
3015         TruncOp = ISD::FP_ROUND;
3016       }
3017       // Promote each of the values to the new type.
3018       Tmp2 = DAG.getNode(ExtOp, dl, NVT, Tmp2);
3019       Tmp3 = DAG.getNode(ExtOp, dl, NVT, Tmp3);
3020       // Perform the larger operation, then round down.
3021       Result = DAG.getNode(ISD::SELECT, dl, NVT, Tmp1, Tmp2, Tmp3);
3022       if (TruncOp != ISD::FP_ROUND)
3023         Result = DAG.getNode(TruncOp, dl, Node->getValueType(0), Result);
3024       else
3025         Result = DAG.getNode(TruncOp, dl, Node->getValueType(0), Result,
3026                              DAG.getIntPtrConstant(0));
3027       break;
3028     }
3029     }
3030     break;
3031   case ISD::SELECT_CC: {
3032     Tmp1 = Node->getOperand(0);               // LHS
3033     Tmp2 = Node->getOperand(1);               // RHS
3034     Tmp3 = LegalizeOp(Node->getOperand(2));   // True
3035     Tmp4 = LegalizeOp(Node->getOperand(3));   // False
3036     SDValue CC = Node->getOperand(4);
3037
3038     LegalizeSetCC(TLI.getSetCCResultType(Tmp1.getValueType()),
3039                   Tmp1, Tmp2, CC, dl);
3040
3041     // If we didn't get both a LHS and RHS back from LegalizeSetCC,
3042     // the LHS is a legal SETCC itself.  In this case, we need to compare
3043     // the result against zero to select between true and false values.
3044     if (Tmp2.getNode() == 0) {
3045       Tmp2 = DAG.getConstant(0, Tmp1.getValueType());
3046       CC = DAG.getCondCode(ISD::SETNE);
3047     }
3048     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3, Tmp4, CC);
3049
3050     // Everything is legal, see if we should expand this op or something.
3051     switch (TLI.getOperationAction(ISD::SELECT_CC, Tmp3.getValueType())) {
3052     default: assert(0 && "This action is not supported yet!");
3053     case TargetLowering::Legal: break;
3054     case TargetLowering::Custom:
3055       Tmp1 = TLI.LowerOperation(Result, DAG);
3056       if (Tmp1.getNode()) Result = Tmp1;
3057       break;
3058     }
3059     break;
3060   }
3061   case ISD::SETCC:
3062     Tmp1 = Node->getOperand(0);
3063     Tmp2 = Node->getOperand(1);
3064     Tmp3 = Node->getOperand(2);
3065     LegalizeSetCC(Node->getValueType(0), Tmp1, Tmp2, Tmp3, dl);
3066
3067     // If we had to Expand the SetCC operands into a SELECT node, then it may
3068     // not always be possible to return a true LHS & RHS.  In this case, just
3069     // return the value we legalized, returned in the LHS
3070     if (Tmp2.getNode() == 0) {
3071       Result = Tmp1;
3072       break;
3073     }
3074
3075     switch (TLI.getOperationAction(ISD::SETCC, Tmp1.getValueType())) {
3076     default: assert(0 && "Cannot handle this action for SETCC yet!");
3077     case TargetLowering::Custom:
3078       isCustom = true;
3079       // FALLTHROUGH.
3080     case TargetLowering::Legal:
3081       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
3082       if (isCustom) {
3083         Tmp4 = TLI.LowerOperation(Result, DAG);
3084         if (Tmp4.getNode()) Result = Tmp4;
3085       }
3086       break;
3087     case TargetLowering::Promote: {
3088       // First step, figure out the appropriate operation to use.
3089       // Allow SETCC to not be supported for all legal data types
3090       // Mostly this targets FP
3091       MVT NewInTy = Node->getOperand(0).getValueType();
3092       MVT OldVT = NewInTy; OldVT = OldVT;
3093
3094       // Scan for the appropriate larger type to use.
3095       while (1) {
3096         NewInTy = (MVT::SimpleValueType)(NewInTy.getSimpleVT()+1);
3097
3098         assert(NewInTy.isInteger() == OldVT.isInteger() &&
3099                "Fell off of the edge of the integer world");
3100         assert(NewInTy.isFloatingPoint() == OldVT.isFloatingPoint() &&
3101                "Fell off of the edge of the floating point world");
3102
3103         // If the target supports SETCC of this type, use it.
3104         if (TLI.isOperationLegalOrCustom(ISD::SETCC, NewInTy))
3105           break;
3106       }
3107       if (NewInTy.isInteger())
3108         assert(0 && "Cannot promote Legal Integer SETCC yet");
3109       else {
3110         Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NewInTy, Tmp1);
3111         Tmp2 = DAG.getNode(ISD::FP_EXTEND, dl, NewInTy, Tmp2);
3112       }
3113       Tmp1 = LegalizeOp(Tmp1);
3114       Tmp2 = LegalizeOp(Tmp2);
3115       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
3116       Result = LegalizeOp(Result);
3117       break;
3118     }
3119     case TargetLowering::Expand:
3120       // Expand a setcc node into a select_cc of the same condition, lhs, and
3121       // rhs that selects between const 1 (true) and const 0 (false).
3122       MVT VT = Node->getValueType(0);
3123       Result = DAG.getNode(ISD::SELECT_CC, dl, VT, Tmp1, Tmp2,
3124                            DAG.getConstant(1, VT), DAG.getConstant(0, VT),
3125                            Tmp3);
3126       break;
3127     }
3128     break;
3129   case ISD::VSETCC: {
3130     Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
3131     Tmp2 = LegalizeOp(Node->getOperand(1));   // RHS
3132     SDValue CC = Node->getOperand(2);
3133
3134     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, CC);
3135
3136     // Everything is legal, see if we should expand this op or something.
3137     switch (TLI.getOperationAction(ISD::VSETCC, Tmp1.getValueType())) {
3138     default: assert(0 && "This action is not supported yet!");
3139     case TargetLowering::Legal: break;
3140     case TargetLowering::Custom:
3141       Tmp1 = TLI.LowerOperation(Result, DAG);
3142       if (Tmp1.getNode()) Result = Tmp1;
3143       break;
3144     case TargetLowering::Expand: {
3145       // Unroll into a nasty set of scalar code for now.
3146       MVT VT = Node->getValueType(0);
3147       unsigned NumElems = VT.getVectorNumElements();
3148       MVT EltVT = VT.getVectorElementType();
3149       MVT TmpEltVT = Tmp1.getValueType().getVectorElementType();
3150       SmallVector<SDValue, 8> Ops(NumElems);
3151       for (unsigned i = 0; i < NumElems; ++i) {
3152         SDValue In1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, TmpEltVT,
3153                                   Tmp1, DAG.getIntPtrConstant(i));
3154         Ops[i] = DAG.getNode(ISD::SETCC, dl, TLI.getSetCCResultType(TmpEltVT),
3155                              In1, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
3156                                               TmpEltVT, Tmp2,
3157                                               DAG.getIntPtrConstant(i)),
3158                              CC);
3159         Ops[i] = DAG.getNode(ISD::SELECT, dl, EltVT, Ops[i],
3160                              DAG.getConstant(APInt::getAllOnesValue
3161                                              (EltVT.getSizeInBits()), EltVT),
3162                              DAG.getConstant(0, EltVT));
3163       }
3164       Result = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Ops[0], NumElems);
3165       break;
3166     }
3167     }
3168     break;
3169   }
3170
3171   case ISD::SHL_PARTS:
3172   case ISD::SRA_PARTS:
3173   case ISD::SRL_PARTS: {
3174     SmallVector<SDValue, 8> Ops;
3175     bool Changed = false;
3176     unsigned N = Node->getNumOperands();
3177     for (unsigned i = 0; i + 1 < N; ++i) {
3178       Ops.push_back(LegalizeOp(Node->getOperand(i)));
3179       Changed |= Ops.back() != Node->getOperand(i);
3180     }
3181     Ops.push_back(LegalizeOp(DAG.getShiftAmountOperand(Node->getOperand(N-1))));
3182     Changed |= Ops.back() != Node->getOperand(N-1);
3183     if (Changed)
3184       Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
3185
3186     switch (TLI.getOperationAction(Node->getOpcode(),
3187                                    Node->getValueType(0))) {
3188     default: assert(0 && "This action is not supported yet!");
3189     case TargetLowering::Legal: break;
3190     case TargetLowering::Custom:
3191       Tmp1 = TLI.LowerOperation(Result, DAG);
3192       if (Tmp1.getNode()) {
3193         SDValue Tmp2, RetVal(0, 0);
3194         for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i) {
3195           Tmp2 = LegalizeOp(Tmp1.getValue(i));
3196           AddLegalizedOperand(SDValue(Node, i), Tmp2);
3197           if (i == Op.getResNo())
3198             RetVal = Tmp2;
3199         }
3200         assert(RetVal.getNode() && "Illegal result number");
3201         return RetVal;
3202       }
3203       break;
3204     }
3205
3206     // Since these produce multiple values, make sure to remember that we
3207     // legalized all of them.
3208     for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
3209       AddLegalizedOperand(SDValue(Node, i), Result.getValue(i));
3210     return Result.getValue(Op.getResNo());
3211   }
3212
3213     // Binary operators
3214   case ISD::ADD:
3215   case ISD::SUB:
3216   case ISD::MUL:
3217   case ISD::MULHS:
3218   case ISD::MULHU:
3219   case ISD::UDIV:
3220   case ISD::SDIV:
3221   case ISD::AND:
3222   case ISD::OR:
3223   case ISD::XOR:
3224   case ISD::SHL:
3225   case ISD::SRL:
3226   case ISD::SRA:
3227   case ISD::FADD:
3228   case ISD::FSUB:
3229   case ISD::FMUL:
3230   case ISD::FDIV:
3231   case ISD::FPOW:
3232     Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
3233     Tmp2 = LegalizeOp(Node->getOperand(1));   // RHS
3234
3235     if ((Node->getOpcode() == ISD::SHL ||
3236          Node->getOpcode() == ISD::SRL ||
3237          Node->getOpcode() == ISD::SRA) &&
3238         !Node->getValueType(0).isVector())
3239       Tmp2 = DAG.getShiftAmountOperand(Tmp2);
3240
3241     switch (getTypeAction(Tmp2.getValueType())) {
3242     case Expand: assert(0 && "Not possible");
3243     case Legal:
3244       Tmp2 = LegalizeOp(Tmp2); // Legalize the RHS.
3245       break;
3246     case Promote:
3247       Tmp2 = PromoteOp(Tmp2);  // Promote the RHS.
3248       break;
3249     }
3250
3251     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
3252
3253     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
3254     default: assert(0 && "BinOp legalize operation not supported");
3255     case TargetLowering::Legal: break;
3256     case TargetLowering::Custom:
3257       Tmp1 = TLI.LowerOperation(Result, DAG);
3258       if (Tmp1.getNode()) {
3259         Result = Tmp1;
3260         break;
3261       }
3262       // Fall through if the custom lower can't deal with the operation
3263     case TargetLowering::Expand: {
3264       MVT VT = Op.getValueType();
3265
3266       // See if multiply or divide can be lowered using two-result operations.
3267       SDVTList VTs = DAG.getVTList(VT, VT);
3268       if (Node->getOpcode() == ISD::MUL) {
3269         // We just need the low half of the multiply; try both the signed
3270         // and unsigned forms. If the target supports both SMUL_LOHI and
3271         // UMUL_LOHI, form a preference by checking which forms of plain
3272         // MULH it supports.
3273         bool HasSMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::SMUL_LOHI, VT);
3274         bool HasUMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::UMUL_LOHI, VT);
3275         bool HasMULHS = TLI.isOperationLegalOrCustom(ISD::MULHS, VT);
3276         bool HasMULHU = TLI.isOperationLegalOrCustom(ISD::MULHU, VT);
3277         unsigned OpToUse = 0;
3278         if (HasSMUL_LOHI && !HasMULHS) {
3279           OpToUse = ISD::SMUL_LOHI;
3280         } else if (HasUMUL_LOHI && !HasMULHU) {
3281           OpToUse = ISD::UMUL_LOHI;
3282         } else if (HasSMUL_LOHI) {
3283           OpToUse = ISD::SMUL_LOHI;
3284         } else if (HasUMUL_LOHI) {
3285           OpToUse = ISD::UMUL_LOHI;
3286         }
3287         if (OpToUse) {
3288           Result = DAG.getNode(OpToUse, dl, VTs, Tmp1, Tmp2);
3289           break;
3290         }
3291       }
3292       if (Node->getOpcode() == ISD::MULHS &&
3293           TLI.isOperationLegalOrCustom(ISD::SMUL_LOHI, VT)) {
3294         Result = SDValue(DAG.getNode(ISD::SMUL_LOHI, dl,
3295                                      VTs, Tmp1, Tmp2).getNode(),
3296                          1);
3297         break;
3298       }
3299       if (Node->getOpcode() == ISD::MULHU &&
3300           TLI.isOperationLegalOrCustom(ISD::UMUL_LOHI, VT)) {
3301         Result = SDValue(DAG.getNode(ISD::UMUL_LOHI, dl,
3302                                      VTs, Tmp1, Tmp2).getNode(),
3303                          1);
3304         break;
3305       }
3306       if (Node->getOpcode() == ISD::SDIV &&
3307           TLI.isOperationLegalOrCustom(ISD::SDIVREM, VT)) {
3308         Result = DAG.getNode(ISD::SDIVREM, dl, VTs, Tmp1, Tmp2);
3309         break;
3310       }
3311       if (Node->getOpcode() == ISD::UDIV &&
3312           TLI.isOperationLegalOrCustom(ISD::UDIVREM, VT)) {
3313         Result = DAG.getNode(ISD::UDIVREM, dl, VTs, Tmp1, Tmp2);
3314         break;
3315       }
3316       if (Node->getOpcode() == ISD::SUB &&
3317           TLI.isOperationLegalOrCustom(ISD::ADD, VT) &&
3318           TLI.isOperationLegalOrCustom(ISD::XOR, VT)) {
3319         Tmp2 = DAG.getNode(ISD::XOR, dl, VT, Tmp2,
3320                DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT));
3321         Tmp2 = DAG.getNode(ISD::ADD, dl, VT, Tmp2, DAG.getConstant(1, VT));
3322         Result = DAG.getNode(ISD::ADD, dl, VT, Tmp1, Tmp2);
3323         break;
3324       }
3325
3326       // Check to see if we have a libcall for this operator.
3327       RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
3328       bool isSigned = false;
3329       switch (Node->getOpcode()) {
3330       case ISD::UDIV:
3331       case ISD::SDIV:
3332        isSigned = Node->getOpcode() == ISD::SDIV;
3333        if (VT == MVT::i16)
3334          LC = (isSigned ? RTLIB::SDIV_I16  : RTLIB::UDIV_I16);
3335        else if (VT == MVT::i32)
3336          LC = (isSigned ? RTLIB::SDIV_I32  : RTLIB::UDIV_I32);
3337        else if (VT == MVT::i64)
3338          LC = (isSigned ? RTLIB::SDIV_I64  : RTLIB::UDIV_I64);
3339        else if (VT == MVT::i128)
3340          LC = (isSigned ? RTLIB::SDIV_I128 : RTLIB::UDIV_I128);
3341        break;
3342       case ISD::MUL:
3343         if (VT == MVT::i16)
3344           LC = RTLIB::MUL_I16;
3345         else if (VT == MVT::i32)
3346           LC = RTLIB::MUL_I32;
3347         else if (VT == MVT::i64)
3348           LC = RTLIB::MUL_I64;
3349         else if (VT == MVT::i128)
3350           LC = RTLIB::MUL_I128;
3351         break;
3352       case ISD::FPOW:
3353         LC = GetFPLibCall(VT, RTLIB::POW_F32, RTLIB::POW_F64, RTLIB::POW_F80,
3354                           RTLIB::POW_PPCF128);
3355         break;
3356       case ISD::FDIV:
3357         LC = GetFPLibCall(VT, RTLIB::DIV_F32, RTLIB::DIV_F64, RTLIB::DIV_F80,
3358                           RTLIB::DIV_PPCF128);
3359         break;
3360       default: break;
3361       }
3362       if (LC != RTLIB::UNKNOWN_LIBCALL) {
3363         SDValue Dummy;
3364         Result = ExpandLibCall(LC, Node, isSigned, Dummy);
3365         break;
3366       }
3367
3368       assert(Node->getValueType(0).isVector() &&
3369              "Cannot expand this binary operator!");
3370       // Expand the operation into a bunch of nasty scalar code.
3371       Result = LegalizeOp(UnrollVectorOp(Op));
3372       break;
3373     }
3374     case TargetLowering::Promote: {
3375       switch (Node->getOpcode()) {
3376       default:  assert(0 && "Do not know how to promote this BinOp!");
3377       case ISD::AND:
3378       case ISD::OR:
3379       case ISD::XOR: {
3380         MVT OVT = Node->getValueType(0);
3381         MVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
3382         assert(OVT.isVector() && "Cannot promote this BinOp!");
3383         // Bit convert each of the values to the new type.
3384         Tmp1 = DAG.getNode(ISD::BIT_CONVERT, dl, NVT, Tmp1);
3385         Tmp2 = DAG.getNode(ISD::BIT_CONVERT, dl, NVT, Tmp2);
3386         Result = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2);
3387         // Bit convert the result back the original type.
3388         Result = DAG.getNode(ISD::BIT_CONVERT, dl, OVT, Result);
3389         break;
3390       }
3391       }
3392     }
3393     }
3394     break;
3395
3396   case ISD::SMUL_LOHI:
3397   case ISD::UMUL_LOHI:
3398   case ISD::SDIVREM:
3399   case ISD::UDIVREM:
3400     // These nodes will only be produced by target-specific lowering, so
3401     // they shouldn't be here if they aren't legal.
3402     assert(TLI.isOperationLegal(Node->getOpcode(), Node->getValueType(0)) &&
3403            "This must be legal!");
3404
3405     Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
3406     Tmp2 = LegalizeOp(Node->getOperand(1));   // RHS
3407     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
3408     break;
3409
3410   case ISD::FCOPYSIGN:  // FCOPYSIGN does not require LHS/RHS to match type!
3411     Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
3412     switch (getTypeAction(Node->getOperand(1).getValueType())) {
3413       case Expand: assert(0 && "Not possible");
3414       case Legal:
3415         Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the RHS.
3416         break;
3417       case Promote:
3418         Tmp2 = PromoteOp(Node->getOperand(1));  // Promote the RHS.
3419         break;
3420     }
3421
3422     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
3423
3424     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
3425     default: assert(0 && "Operation not supported");
3426     case TargetLowering::Custom:
3427       Tmp1 = TLI.LowerOperation(Result, DAG);
3428       if (Tmp1.getNode()) Result = Tmp1;
3429       break;
3430     case TargetLowering::Legal: break;
3431     case TargetLowering::Expand: {
3432       // If this target supports fabs/fneg natively and select is cheap,
3433       // do this efficiently.
3434       if (!TLI.isSelectExpensive() &&
3435           TLI.getOperationAction(ISD::FABS, Tmp1.getValueType()) ==
3436           TargetLowering::Legal &&
3437           TLI.getOperationAction(ISD::FNEG, Tmp1.getValueType()) ==
3438           TargetLowering::Legal) {
3439         // Get the sign bit of the RHS.
3440         MVT IVT =
3441           Tmp2.getValueType() == MVT::f32 ? MVT::i32 : MVT::i64;
3442         SDValue SignBit = DAG.getNode(ISD::BIT_CONVERT, dl, IVT, Tmp2);
3443         SignBit = DAG.getSetCC(dl, TLI.getSetCCResultType(IVT),
3444                                SignBit, DAG.getConstant(0, IVT), ISD::SETLT);
3445         // Get the absolute value of the result.
3446         SDValue AbsVal = DAG.getNode(ISD::FABS, dl, Tmp1.getValueType(), Tmp1);
3447         // Select between the nabs and abs value based on the sign bit of
3448         // the input.
3449         Result = DAG.getNode(ISD::SELECT, dl, AbsVal.getValueType(), SignBit,
3450                              DAG.getNode(ISD::FNEG, dl, AbsVal.getValueType(),
3451                                          AbsVal),
3452                              AbsVal);
3453         Result = LegalizeOp(Result);
3454         break;
3455       }
3456
3457       // Otherwise, do bitwise ops!
3458       MVT NVT =
3459         Node->getValueType(0) == MVT::f32 ? MVT::i32 : MVT::i64;
3460       Result = ExpandFCOPYSIGNToBitwiseOps(Node, NVT, DAG, TLI);
3461       Result = DAG.getNode(ISD::BIT_CONVERT, dl, Node->getValueType(0), Result);
3462       Result = LegalizeOp(Result);
3463       break;
3464     }
3465     }
3466     break;
3467
3468   case ISD::ADDC:
3469   case ISD::SUBC:
3470     Tmp1 = LegalizeOp(Node->getOperand(0));
3471     Tmp2 = LegalizeOp(Node->getOperand(1));
3472     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
3473     Tmp3 = Result.getValue(0);
3474     Tmp4 = Result.getValue(1);
3475
3476     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
3477     default: assert(0 && "This action is not supported yet!");
3478     case TargetLowering::Legal:
3479       break;
3480     case TargetLowering::Custom:
3481       Tmp1 = TLI.LowerOperation(Tmp3, DAG);
3482       if (Tmp1.getNode() != NULL) {
3483         Tmp3 = LegalizeOp(Tmp1);
3484         Tmp4 = LegalizeOp(Tmp1.getValue(1));
3485       }
3486       break;
3487     }
3488     // Since this produces two values, make sure to remember that we legalized
3489     // both of them.
3490     AddLegalizedOperand(SDValue(Node, 0), Tmp3);
3491     AddLegalizedOperand(SDValue(Node, 1), Tmp4);
3492     return Op.getResNo() ? Tmp4 : Tmp3;
3493
3494   case ISD::ADDE:
3495   case ISD::SUBE:
3496     Tmp1 = LegalizeOp(Node->getOperand(0));
3497     Tmp2 = LegalizeOp(Node->getOperand(1));
3498     Tmp3 = LegalizeOp(Node->getOperand(2));
3499     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
3500     Tmp3 = Result.getValue(0);
3501     Tmp4 = Result.getValue(1);
3502
3503     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
3504     default: assert(0 && "This action is not supported yet!");
3505     case TargetLowering::Legal:
3506       break;
3507     case TargetLowering::Custom:
3508       Tmp1 = TLI.LowerOperation(Tmp3, DAG);
3509       if (Tmp1.getNode() != NULL) {
3510         Tmp3 = LegalizeOp(Tmp1);
3511         Tmp4 = LegalizeOp(Tmp1.getValue(1));
3512       }
3513       break;
3514     }
3515     // Since this produces two values, make sure to remember that we legalized
3516     // both of them.
3517     AddLegalizedOperand(SDValue(Node, 0), Tmp3);
3518     AddLegalizedOperand(SDValue(Node, 1), Tmp4);
3519     return Op.getResNo() ? Tmp4 : Tmp3;
3520
3521   case ISD::BUILD_PAIR: {
3522     MVT PairTy = Node->getValueType(0);
3523     // TODO: handle the case where the Lo and Hi operands are not of legal type
3524     Tmp1 = LegalizeOp(Node->getOperand(0));   // Lo
3525     Tmp2 = LegalizeOp(Node->getOperand(1));   // Hi
3526     switch (TLI.getOperationAction(ISD::BUILD_PAIR, PairTy)) {
3527     case TargetLowering::Promote:
3528     case TargetLowering::Custom:
3529       assert(0 && "Cannot promote/custom this yet!");
3530     case TargetLowering::Legal:
3531       if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
3532         Result = DAG.getNode(ISD::BUILD_PAIR, dl, PairTy, Tmp1, Tmp2);
3533       break;
3534     case TargetLowering::Expand:
3535       Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, PairTy, Tmp1);
3536       Tmp2 = DAG.getNode(ISD::ANY_EXTEND, dl, PairTy, Tmp2);
3537       Tmp2 = DAG.getNode(ISD::SHL, dl, PairTy, Tmp2,
3538                          DAG.getConstant(PairTy.getSizeInBits()/2,
3539                                          TLI.getShiftAmountTy()));
3540       Result = DAG.getNode(ISD::OR, dl, PairTy, Tmp1, Tmp2);
3541       break;
3542     }
3543     break;
3544   }
3545
3546   case ISD::UREM:
3547   case ISD::SREM:
3548   case ISD::FREM:
3549     Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
3550     Tmp2 = LegalizeOp(Node->getOperand(1));   // RHS
3551
3552     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
3553     case TargetLowering::Promote: assert(0 && "Cannot promote this yet!");
3554     case TargetLowering::Custom:
3555       isCustom = true;
3556       // FALLTHROUGH
3557     case TargetLowering::Legal:
3558       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
3559       if (isCustom) {
3560         Tmp1 = TLI.LowerOperation(Result, DAG);
3561         if (Tmp1.getNode()) Result = Tmp1;
3562       }
3563       break;
3564     case TargetLowering::Expand: {
3565       unsigned DivOpc= (Node->getOpcode() == ISD::UREM) ? ISD::UDIV : ISD::SDIV;
3566       bool isSigned = DivOpc == ISD::SDIV;
3567       MVT VT = Node->getValueType(0);
3568
3569       // See if remainder can be lowered using two-result operations.
3570       SDVTList VTs = DAG.getVTList(VT, VT);
3571       if (Node->getOpcode() == ISD::SREM &&
3572           TLI.isOperationLegalOrCustom(ISD::SDIVREM, VT)) {
3573         Result = SDValue(DAG.getNode(ISD::SDIVREM, dl,
3574                                      VTs, Tmp1, Tmp2).getNode(), 1);
3575         break;
3576       }
3577       if (Node->getOpcode() == ISD::UREM &&
3578           TLI.isOperationLegalOrCustom(ISD::UDIVREM, VT)) {
3579         Result = SDValue(DAG.getNode(ISD::UDIVREM, dl,
3580                                      VTs, Tmp1, Tmp2).getNode(), 1);
3581         break;
3582       }
3583
3584       if (VT.isInteger() &&
3585           TLI.getOperationAction(DivOpc, VT) == TargetLowering::Legal) {
3586         // X % Y -> X-X/Y*Y
3587         Result = DAG.getNode(DivOpc, dl, VT, Tmp1, Tmp2);
3588         Result = DAG.getNode(ISD::MUL, dl, VT, Result, Tmp2);
3589         Result = DAG.getNode(ISD::SUB, dl, VT, Tmp1, Result);
3590         break;
3591       }
3592
3593       // Check to see if we have a libcall for this operator.
3594       RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
3595       switch (Node->getOpcode()) {
3596       default: break;
3597       case ISD::UREM:
3598       case ISD::SREM:
3599        if (VT == MVT::i16)
3600          LC = (isSigned ? RTLIB::SREM_I16  : RTLIB::UREM_I16);
3601        else if (VT == MVT::i32)
3602          LC = (isSigned ? RTLIB::SREM_I32  : RTLIB::UREM_I32);
3603        else if (VT == MVT::i64)
3604          LC = (isSigned ? RTLIB::SREM_I64  : RTLIB::UREM_I64);
3605        else if (VT == MVT::i128)
3606          LC = (isSigned ? RTLIB::SREM_I128 : RTLIB::UREM_I128);
3607        break;
3608        case ISD::FREM:
3609         // Floating point mod -> fmod libcall.
3610         LC = GetFPLibCall(VT, RTLIB::REM_F32, RTLIB::REM_F64,
3611                           RTLIB::REM_F80, RTLIB::REM_PPCF128);
3612         break;
3613       }
3614
3615       if (LC != RTLIB::UNKNOWN_LIBCALL) {
3616         SDValue Dummy;
3617         Result = ExpandLibCall(LC, Node, isSigned, Dummy);
3618         break;
3619       }
3620
3621       assert(VT.isVector() &&
3622              "Cannot expand this binary operator!");
3623       // Expand the operation into a bunch of nasty scalar code.
3624       Result = LegalizeOp(UnrollVectorOp(Op));
3625       break;
3626     }
3627     }
3628     break;
3629   case ISD::VAARG: {
3630     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
3631     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
3632
3633     MVT VT = Node->getValueType(0);
3634     switch (TLI.getOperationAction(Node->getOpcode(), MVT::Other)) {
3635     default: assert(0 && "This action is not supported yet!");
3636     case TargetLowering::Custom:
3637       isCustom = true;
3638       // FALLTHROUGH
3639     case TargetLowering::Legal:
3640       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
3641       Result = Result.getValue(0);
3642       Tmp1 = Result.getValue(1);
3643
3644       if (isCustom) {
3645         Tmp2 = TLI.LowerOperation(Result, DAG);
3646         if (Tmp2.getNode()) {
3647           Result = LegalizeOp(Tmp2);
3648           Tmp1 = LegalizeOp(Tmp2.getValue(1));
3649         }
3650       }
3651       break;
3652     case TargetLowering::Expand: {
3653       const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
3654       SDValue VAList = DAG.getLoad(TLI.getPointerTy(), dl, Tmp1, Tmp2, V, 0);
3655       // Increment the pointer, VAList, to the next vaarg
3656       Tmp3 = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(), VAList,
3657                          DAG.getConstant(TLI.getTargetData()->
3658                                          getTypeAllocSize(VT.getTypeForMVT()),
3659                                          TLI.getPointerTy()));
3660       // Store the incremented VAList to the legalized pointer
3661       Tmp3 = DAG.getStore(VAList.getValue(1), dl, Tmp3, Tmp2, V, 0);
3662       // Load the actual argument out of the pointer VAList
3663       Result = DAG.getLoad(VT, dl, Tmp3, VAList, NULL, 0);
3664       Tmp1 = LegalizeOp(Result.getValue(1));
3665       Result = LegalizeOp(Result);
3666       break;
3667     }
3668     }
3669     // Since VAARG produces two values, make sure to remember that we
3670     // legalized both of them.
3671     AddLegalizedOperand(SDValue(Node, 0), Result);
3672     AddLegalizedOperand(SDValue(Node, 1), Tmp1);
3673     return Op.getResNo() ? Tmp1 : Result;
3674   }
3675
3676   case ISD::VACOPY:
3677     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
3678     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the dest pointer.
3679     Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the source pointer.
3680
3681     switch (TLI.getOperationAction(ISD::VACOPY, MVT::Other)) {
3682     default: assert(0 && "This action is not supported yet!");
3683     case TargetLowering::Custom:
3684       isCustom = true;
3685       // FALLTHROUGH
3686     case TargetLowering::Legal:
3687       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3,
3688                                       Node->getOperand(3), Node->getOperand(4));
3689       if (isCustom) {
3690         Tmp1 = TLI.LowerOperation(Result, DAG);
3691         if (Tmp1.getNode()) Result = Tmp1;
3692       }
3693       break;
3694     case TargetLowering::Expand:
3695       // This defaults to loading a pointer from the input and storing it to the
3696       // output, returning the chain.
3697       const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
3698       const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
3699       Tmp4 = DAG.getLoad(TLI.getPointerTy(), dl, Tmp1, Tmp3, VS, 0);
3700       Result = DAG.getStore(Tmp4.getValue(1), dl, Tmp4, Tmp2, VD, 0);
3701       break;
3702     }
3703     break;
3704
3705   case ISD::VAEND:
3706     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
3707     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
3708
3709     switch (TLI.getOperationAction(ISD::VAEND, MVT::Other)) {
3710     default: assert(0 && "This action is not supported yet!");
3711     case TargetLowering::Custom:
3712       isCustom = true;
3713       // FALLTHROUGH
3714     case TargetLowering::Legal:
3715       Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
3716       if (isCustom) {
3717         Tmp1 = TLI.LowerOperation(Tmp1, DAG);
3718         if (Tmp1.getNode()) Result = Tmp1;
3719       }
3720       break;
3721     case TargetLowering::Expand:
3722       Result = Tmp1; // Default to a no-op, return the chain
3723       break;
3724     }
3725     break;
3726
3727   case ISD::VASTART:
3728     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
3729     Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
3730
3731     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
3732
3733     switch (TLI.getOperationAction(ISD::VASTART, MVT::Other)) {
3734     default: assert(0 && "This action is not supported yet!");
3735     case TargetLowering::Legal: break;
3736     case TargetLowering::Custom:
3737       Tmp1 = TLI.LowerOperation(Result, DAG);
3738       if (Tmp1.getNode()) Result = Tmp1;
3739       break;
3740     }
3741     break;
3742
3743   case ISD::ROTL:
3744   case ISD::ROTR:
3745     Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
3746     Tmp2 = LegalizeOp(DAG.getShiftAmountOperand(Node->getOperand(1)));   // RHS
3747     Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
3748     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
3749     default:
3750       assert(0 && "ROTL/ROTR legalize operation not supported");
3751       break;
3752     case TargetLowering::Legal:
3753       break;
3754     case TargetLowering::Custom:
3755       Tmp1 = TLI.LowerOperation(Result, DAG);
3756       if (Tmp1.getNode()) Result = Tmp1;
3757       break;
3758     case TargetLowering::Promote:
3759       assert(0 && "Do not know how to promote ROTL/ROTR");
3760       break;
3761     case TargetLowering::Expand:
3762       assert(0 && "Do not know how to expand ROTL/ROTR");
3763       break;
3764     }
3765     break;
3766
3767   case ISD::BSWAP:
3768     Tmp1 = LegalizeOp(Node->getOperand(0));   // Op
3769     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
3770     case TargetLowering::Custom:
3771       assert(0 && "Cannot custom legalize this yet!");
3772     case TargetLowering::Legal:
3773       Result = DAG.UpdateNodeOperands(Result, Tmp1);
3774       break;
3775     case TargetLowering::Promote: {
3776       MVT OVT = Tmp1.getValueType();
3777       MVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
3778       unsigned DiffBits = NVT.getSizeInBits() - OVT.getSizeInBits();
3779
3780       Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Tmp1);
3781       Tmp1 = DAG.getNode(ISD::BSWAP, dl, NVT, Tmp1);
3782       Result = DAG.getNode(ISD::SRL, dl, NVT, Tmp1,
3783                            DAG.getConstant(DiffBits, TLI.getShiftAmountTy()));
3784       break;
3785     }
3786     case TargetLowering::Expand:
3787       Result = ExpandBSWAP(Tmp1, dl);
3788       break;
3789     }
3790     break;
3791
3792   case ISD::CTPOP:
3793   case ISD::CTTZ:
3794   case ISD::CTLZ:
3795     Tmp1 = LegalizeOp(Node->getOperand(0));   // Op
3796     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
3797     case TargetLowering::Custom:
3798     case TargetLowering::Legal:
3799       Result = DAG.UpdateNodeOperands(Result, Tmp1);
3800       if (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0)) ==
3801           TargetLowering::Custom) {
3802         Tmp1 = TLI.LowerOperation(Result, DAG);
3803         if (Tmp1.getNode()) {
3804           Result = Tmp1;
3805         }
3806       }
3807       break;
3808     case TargetLowering::Promote: {
3809       MVT OVT = Tmp1.getValueType();
3810       MVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
3811
3812       // Zero extend the argument.
3813       Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Tmp1);
3814       // Perform the larger operation, then subtract if needed.
3815       Tmp1 = DAG.getNode(Node->getOpcode(), dl, Node->getValueType(0), Tmp1);
3816       switch (Node->getOpcode()) {
3817       case ISD::CTPOP:
3818         Result = Tmp1;
3819         break;
3820       case ISD::CTTZ:
3821         //if Tmp1 == sizeinbits(NVT) then Tmp1 = sizeinbits(Old VT)
3822         Tmp2 = DAG.getSetCC(dl, TLI.getSetCCResultType(Tmp1.getValueType()),
3823                             Tmp1, DAG.getConstant(NVT.getSizeInBits(), NVT),
3824                             ISD::SETEQ);
3825         Result = DAG.getNode(ISD::SELECT, dl, NVT, Tmp2,
3826                              DAG.getConstant(OVT.getSizeInBits(), NVT), Tmp1);
3827         break;
3828       case ISD::CTLZ:
3829         // Tmp1 = Tmp1 - (sizeinbits(NVT) - sizeinbits(Old VT))
3830         Result = DAG.getNode(ISD::SUB, dl, NVT, Tmp1,
3831                              DAG.getConstant(NVT.getSizeInBits() -
3832                                              OVT.getSizeInBits(), NVT));
3833         break;
3834       }
3835       break;
3836     }
3837     case TargetLowering::Expand:
3838       Result = ExpandBitCount(Node->getOpcode(), Tmp1, dl);
3839       break;
3840     }
3841     break;
3842
3843     // Unary operators
3844   case ISD::FABS:
3845   case ISD::FNEG:
3846   case ISD::FSQRT:
3847   case ISD::FSIN:
3848   case ISD::FCOS:
3849   case ISD::FLOG:
3850   case ISD::FLOG2:
3851   case ISD::FLOG10:
3852   case ISD::FEXP:
3853   case ISD::FEXP2:
3854   case ISD::FTRUNC:
3855   case ISD::FFLOOR:
3856   case ISD::FCEIL:
3857   case ISD::FRINT:
3858   case ISD::FNEARBYINT:
3859     Tmp1 = LegalizeOp(Node->getOperand(0));
3860     switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
3861     case TargetLowering::Promote:
3862     case TargetLowering::Custom:
3863      isCustom = true;
3864      // FALLTHROUGH
3865     case TargetLowering::Legal:
3866       Result = DAG.UpdateNodeOperands(Result, Tmp1);
3867       if (isCustom) {
3868         Tmp1 = TLI.LowerOperation(Result, DAG);
3869         if (Tmp1.getNode()) Result = Tmp1;
3870       }
3871       break;
3872     case TargetLowering::Expand:
3873       switch (Node->getOpcode()) {
3874       default: assert(0 && "Unreachable!");
3875       case ISD::FNEG:
3876         // Expand Y = FNEG(X) ->  Y = SUB -0.0, X
3877         Tmp2 = DAG.getConstantFP(-0.0, Node->getValueType(0));
3878         Result = DAG.getNode(ISD::FSUB, dl, Node->getValueType(0), Tmp2, Tmp1);
3879         break;
3880       case ISD::FABS: {
3881         // Expand Y = FABS(X) -> Y = (X >u 0.0) ? X : fneg(X).
3882         MVT VT = Node->getValueType(0);
3883         Tmp2 = DAG.getConstantFP(0.0, VT);
3884         Tmp2 = DAG.getSetCC(dl, TLI.getSetCCResultType(Tmp1.getValueType()),
3885                             Tmp1, Tmp2, ISD::SETUGT);
3886         Tmp3 = DAG.getNode(ISD::FNEG, dl, VT, Tmp1);
3887         Result = DAG.getNode(ISD::SELECT, dl, VT, Tmp2, Tmp1, Tmp3);
3888         break;
3889       }
3890       case ISD::FSQRT:
3891       case ISD::FSIN:
3892       case ISD::FCOS:
3893       case ISD::FLOG:
3894       case ISD::FLOG2:
3895       case ISD::FLOG10:
3896       case ISD::FEXP:
3897       case ISD::FEXP2:
3898       case ISD::FTRUNC:
3899       case ISD::FFLOOR:
3900       case ISD::FCEIL:
3901       case ISD::FRINT:
3902       case ISD::FNEARBYINT: {
3903         MVT VT = Node->getValueType(0);
3904
3905         // Expand unsupported unary vector operators by unrolling them.
3906         if (VT.isVector()) {
3907           Result = LegalizeOp(UnrollVectorOp(Op));
3908           break;
3909         }
3910
3911         RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
3912         switch(Node->getOpcode()) {
3913         case ISD::FSQRT:
3914           LC = GetFPLibCall(VT, RTLIB::SQRT_F32, RTLIB::SQRT_F64,
3915                             RTLIB::SQRT_F80, RTLIB::SQRT_PPCF128);
3916           break;
3917         case ISD::FSIN:
3918           LC = GetFPLibCall(VT, RTLIB::SIN_F32, RTLIB::SIN_F64,
3919                             RTLIB::SIN_F80, RTLIB::SIN_PPCF128);
3920           break;
3921         case ISD::FCOS:
3922           LC = GetFPLibCall(VT, RTLIB::COS_F32, RTLIB::COS_F64,
3923                             RTLIB::COS_F80, RTLIB::COS_PPCF128);
3924           break;
3925         case ISD::FLOG:
3926           LC = GetFPLibCall(VT, RTLIB::LOG_F32, RTLIB::LOG_F64,
3927                             RTLIB::LOG_F80, RTLIB::LOG_PPCF128);
3928           break;
3929         case ISD::FLOG2:
3930           LC = GetFPLibCall(VT, RTLIB::LOG2_F32, RTLIB::LOG2_F64,
3931                             RTLIB::LOG2_F80, RTLIB::LOG2_PPCF128);
3932           break;
3933         case ISD::FLOG10:
3934           LC = GetFPLibCall(VT, RTLIB::LOG10_F32, RTLIB::LOG10_F64,
3935                             RTLIB::LOG10_F80, RTLIB::LOG10_PPCF128);
3936           break;
3937         case ISD::FEXP:
3938           LC = GetFPLibCall(VT, RTLIB::EXP_F32, RTLIB::EXP_F64,
3939                             RTLIB::EXP_F80, RTLIB::EXP_PPCF128);
3940           break;
3941         case ISD::FEXP2:
3942           LC = GetFPLibCall(VT, RTLIB::EXP2_F32, RTLIB::EXP2_F64,
3943                             RTLIB::EXP2_F80, RTLIB::EXP2_PPCF128);
3944           break;
3945         case ISD::FTRUNC:
3946           LC = GetFPLibCall(VT, RTLIB::TRUNC_F32, RTLIB::TRUNC_F64,
3947                             RTLIB::TRUNC_F80, RTLIB::TRUNC_PPCF128);
3948           break;
3949         case ISD::FFLOOR:
3950           LC = GetFPLibCall(VT, RTLIB::FLOOR_F32, RTLIB::FLOOR_F64,
3951                             RTLIB::FLOOR_F80, RTLIB::FLOOR_PPCF128);
3952           break;
3953         case ISD::FCEIL:
3954           LC = GetFPLibCall(VT, RTLIB::CEIL_F32, RTLIB::CEIL_F64,
3955                             RTLIB::CEIL_F80, RTLIB::CEIL_PPCF128);
3956           break;
3957         case ISD::FRINT:
3958           LC = GetFPLibCall(VT, RTLIB::RINT_F32, RTLIB::RINT_F64,
3959                             RTLIB::RINT_F80, RTLIB::RINT_PPCF128);
3960           break;
3961         case ISD::FNEARBYINT:
3962           LC = GetFPLibCall(VT, RTLIB::NEARBYINT_F32, RTLIB::NEARBYINT_F64,
3963                             RTLIB::NEARBYINT_F80, RTLIB::NEARBYINT_PPCF128);
3964           break;
3965       break;
3966         default: assert(0 && "Unreachable!");
3967         }
3968         SDValue Dummy;
3969         Result = ExpandLibCall(LC, Node, false/*sign irrelevant*/, Dummy);
3970         break;
3971       }
3972       }
3973       break;
3974     }
3975     break;
3976   case ISD::FPOWI: {
3977     MVT VT = Node->getValueType(0);
3978
3979     // Expand unsupported unary vector operators by unrolling them.
3980     if (VT.isVector()) {
3981       Result = LegalizeOp(UnrollVectorOp(Op));
3982       break;
3983     }
3984
3985     // We always lower FPOWI into a libcall.  No target support for it yet.
3986     RTLIB::Libcall LC = GetFPLibCall(VT, RTLIB::POWI_F32, RTLIB::POWI_F64,
3987                                      RTLIB::POWI_F80, RTLIB::POWI_PPCF128);
3988     SDValue Dummy;
3989     Result = ExpandLibCall(LC, Node, false/*sign irrelevant*/, Dummy);
3990     break;
3991   }
3992   case ISD::BIT_CONVERT:
3993     if (!isTypeLegal(Node->getOperand(0).getValueType())) {
3994       Result = EmitStackConvert(Node->getOperand(0), Node->getValueType(0),
3995                                 Node->getValueType(0), dl);
3996     } else if (Op.getOperand(0).getValueType().isVector()) {
3997       // The input has to be a vector type, we have to either scalarize it, pack
3998       // it, or convert it based on whether the input vector type is legal.
3999       SDNode *InVal = Node->getOperand(0).getNode();
4000       int InIx = Node->getOperand(0).getResNo();
4001       unsigned NumElems = InVal->getValueType(InIx).getVectorNumElements();
4002       MVT EVT = InVal->getValueType(InIx).getVectorElementType();
4003
4004       // Figure out if there is a simple type corresponding to this Vector
4005       // type.  If so, convert to the vector type.
4006       MVT TVT = MVT::getVectorVT(EVT, NumElems);
4007       if (TLI.isTypeLegal(TVT)) {
4008         // Turn this into a bit convert of the vector input.
4009         Tmp1 = LegalizeOp(Node->getOperand(0));
4010         Result = DAG.getNode(ISD::BIT_CONVERT, dl, Node->getValueType(0), Tmp1);
4011         break;
4012       } else if (NumElems == 1) {
4013         // Turn this into a bit convert of the scalar input.
4014         Result = DAG.getNode(ISD::BIT_CONVERT, dl, Node->getValueType(0),
4015                              ScalarizeVectorOp(Node->getOperand(0)));
4016         break;
4017       } else {
4018         // FIXME: UNIMP!  Store then reload
4019         assert(0 && "Cast from unsupported vector type not implemented yet!");
4020       }
4021     } else {
4022       switch (TLI.getOperationAction(ISD::BIT_CONVERT,
4023                                      Node->getOperand(0).getValueType())) {
4024       default: assert(0 && "Unknown operation action!");
4025       case TargetLowering::Expand:
4026         Result = EmitStackConvert(Node->getOperand(0), Node->getValueType(0),
4027                                   Node->getValueType(0), dl);
4028         break;
4029       case TargetLowering::Legal:
4030         Tmp1 = LegalizeOp(Node->getOperand(0));
4031         Result = DAG.UpdateNodeOperands(Result, Tmp1);
4032         break;
4033       }
4034     }
4035     break;
4036   case ISD::CONVERT_RNDSAT: {
4037     ISD::CvtCode CvtCode = cast<CvtRndSatSDNode>(Node)->getCvtCode();
4038     switch (CvtCode) {
4039     default: assert(0 && "Unknown cvt code!");
4040     case ISD::CVT_SF:
4041     case ISD::CVT_UF:
4042     case ISD::CVT_FF:
4043       break;
4044     case ISD::CVT_FS:
4045     case ISD::CVT_FU:
4046     case ISD::CVT_SS:
4047     case ISD::CVT_SU:
4048     case ISD::CVT_US:
4049     case ISD::CVT_UU: {
4050       SDValue DTyOp = Node->getOperand(1);
4051       SDValue STyOp = Node->getOperand(2);
4052       SDValue RndOp = Node->getOperand(3);
4053       SDValue SatOp = Node->getOperand(4);
4054       switch (getTypeAction(Node->getOperand(0).getValueType())) {
4055       case Expand: assert(0 && "Shouldn't need to expand other operators here!");
4056       case Legal:
4057         Tmp1 = LegalizeOp(Node->getOperand(0));
4058         Result = DAG.UpdateNodeOperands(Result, Tmp1, DTyOp, STyOp,
4059                                         RndOp, SatOp);
4060         if (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0)) ==
4061             TargetLowering::Custom) {
4062           Tmp1 = TLI.LowerOperation(Result, DAG);
4063           if (Tmp1.getNode()) Result = Tmp1;
4064         }
4065         break;
4066       case Promote:
4067         Result = PromoteOp(Node->getOperand(0));
4068         // For FP, make Op1 a i32
4069
4070         Result = DAG.getConvertRndSat(Op.getValueType(), dl, Result,
4071                                       DTyOp, STyOp, RndOp, SatOp, CvtCode);
4072         break;
4073       }
4074       break;
4075     }
4076     } // end switch CvtCode
4077     break;
4078   }
4079     // Conversion operators.  The source and destination have different types.
4080   case ISD::SINT_TO_FP:
4081   case ISD::UINT_TO_FP: {
4082     bool isSigned = Node->getOpcode() == ISD::SINT_TO_FP;
4083     Result = LegalizeINT_TO_FP(Result, isSigned,
4084                                Node->getValueType(0), Node->getOperand(0), dl);
4085     break;
4086   }
4087   case ISD::TRUNCATE:
4088     switch (getTypeAction(Node->getOperand(0).getValueType())) {
4089     case Legal:
4090       Tmp1 = LegalizeOp(Node->getOperand(0));
4091       switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
4092       default: assert(0 && "Unknown TRUNCATE legalization operation action!");
4093       case TargetLowering::Custom:
4094         isCustom = true;
4095         // FALLTHROUGH
4096       case TargetLowering::Legal:
4097         Result = DAG.UpdateNodeOperands(Result, Tmp1);
4098         if (isCustom) {
4099           Tmp1 = TLI.LowerOperation(Result, DAG);
4100           if (Tmp1.getNode()) Result = Tmp1;
4101         }
4102         break;
4103       case TargetLowering::Expand:
4104         assert(Result.getValueType().isVector() && "must be vector type");
4105         // Unroll the truncate.  We should do better.
4106         Result = LegalizeOp(UnrollVectorOp(Result));
4107       }
4108       break;
4109     case Expand:
4110       ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
4111
4112       // Since the result is legal, we should just be able to truncate the low
4113       // part of the source.
4114       Result = DAG.getNode(ISD::TRUNCATE, dl, Node->getValueType(0), Tmp1);
4115       break;
4116     case Promote:
4117       Result = PromoteOp(Node->getOperand(0));
4118       Result = DAG.getNode(ISD::TRUNCATE, dl, Op.getValueType(), Result);
4119       break;
4120     }
4121     break;
4122
4123   case ISD::FP_TO_SINT:
4124   case ISD::FP_TO_UINT:
4125     switch (getTypeAction(Node->getOperand(0).getValueType())) {
4126     case Legal:
4127       Tmp1 = LegalizeOp(Node->getOperand(0));
4128
4129       switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))){
4130       default: assert(0 && "Unknown operation action!");
4131       case TargetLowering::Custom:
4132         isCustom = true;
4133         // FALLTHROUGH
4134       case TargetLowering::Legal:
4135         Result = DAG.UpdateNodeOperands(Result, Tmp1);
4136         if (isCustom) {
4137           Tmp1 = TLI.LowerOperation(Result, DAG);
4138           if (Tmp1.getNode()) Result = Tmp1;
4139         }
4140         break;
4141       case TargetLowering::Promote:
4142         Result = PromoteLegalFP_TO_INT(Tmp1, Node->getValueType(0),
4143                                        Node->getOpcode() == ISD::FP_TO_SINT,
4144                                        dl);
4145         break;
4146       case TargetLowering::Expand:
4147         if (Node->getOpcode() == ISD::FP_TO_UINT) {
4148           SDValue True, False;
4149           MVT VT =  Node->getOperand(0).getValueType();
4150           MVT NVT = Node->getValueType(0);
4151           const uint64_t zero[] = {0, 0};
4152           APFloat apf = APFloat(APInt(VT.getSizeInBits(), 2, zero));
4153           APInt x = APInt::getSignBit(NVT.getSizeInBits());
4154           (void)apf.convertFromAPInt(x, false, APFloat::rmNearestTiesToEven);
4155           Tmp2 = DAG.getConstantFP(apf, VT);
4156           Tmp3 = DAG.getSetCC(dl, TLI.getSetCCResultType(VT),
4157                               Node->getOperand(0),
4158                               Tmp2, ISD::SETLT);
4159           True = DAG.getNode(ISD::FP_TO_SINT, dl, NVT, Node->getOperand(0));
4160           False = DAG.getNode(ISD::FP_TO_SINT, dl, NVT,
4161                               DAG.getNode(ISD::FSUB, dl, VT,
4162                                           Node->getOperand(0), Tmp2));
4163           False = DAG.getNode(ISD::XOR, dl, NVT, False,
4164                               DAG.getConstant(x, NVT));
4165           Result = DAG.getNode(ISD::SELECT, dl, NVT, Tmp3, True, False);
4166           break;
4167         } else {
4168           assert(0 && "Do not know how to expand FP_TO_SINT yet!");
4169         }
4170         break;
4171       }
4172       break;
4173     case Expand: {
4174       MVT VT = Op.getValueType();
4175       MVT OVT = Node->getOperand(0).getValueType();
4176       // Convert ppcf128 to i32
4177       if (OVT == MVT::ppcf128 && VT == MVT::i32) {
4178         if (Node->getOpcode() == ISD::FP_TO_SINT) {
4179           Result = DAG.getNode(ISD::FP_ROUND_INREG, dl, MVT::ppcf128,
4180                                Node->getOperand(0), DAG.getValueType(MVT::f64));
4181           Result = DAG.getNode(ISD::FP_ROUND, dl, MVT::f64, Result,
4182                                DAG.getIntPtrConstant(1));
4183           Result = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Result);
4184         } else {
4185           const uint64_t TwoE31[] = {0x41e0000000000000LL, 0};
4186           APFloat apf = APFloat(APInt(128, 2, TwoE31));
4187           Tmp2 = DAG.getConstantFP(apf, OVT);
4188           //  X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X
4189           // FIXME: generated code sucks.
4190           Result = DAG.getNode(ISD::SELECT_CC, dl, VT, Node->getOperand(0),
4191                                Tmp2,
4192                                DAG.getNode(ISD::ADD, dl, MVT::i32,
4193                                  DAG.getNode(ISD::FP_TO_SINT, dl, VT,
4194                                    DAG.getNode(ISD::FSUB, dl, OVT,
4195                                                  Node->getOperand(0), Tmp2)),
4196                                  DAG.getConstant(0x80000000, MVT::i32)),
4197                                DAG.getNode(ISD::FP_TO_SINT, dl, VT,
4198                                            Node->getOperand(0)),
4199                                DAG.getCondCode(ISD::SETGE));
4200         }
4201         break;
4202       }
4203       // Convert f32 / f64 to i32 / i64 / i128.
4204       RTLIB::Libcall LC = (Node->getOpcode() == ISD::FP_TO_SINT) ?
4205         RTLIB::getFPTOSINT(OVT, VT) : RTLIB::getFPTOUINT(OVT, VT);
4206       assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unexpectd fp-to-int conversion!");
4207       SDValue Dummy;
4208       Result = ExpandLibCall(LC, Node, false/*sign irrelevant*/, Dummy);
4209       break;
4210     }
4211     case Promote:
4212       Tmp1 = PromoteOp(Node->getOperand(0));
4213       Result = DAG.UpdateNodeOperands(Result, LegalizeOp(Tmp1));
4214       Result = LegalizeOp(Result);
4215       break;
4216     }
4217     break;
4218
4219   case ISD::FP_EXTEND: {
4220     MVT DstVT = Op.getValueType();
4221     MVT SrcVT = Op.getOperand(0).getValueType();
4222     if (TLI.getConvertAction(SrcVT, DstVT) == TargetLowering::Expand) {
4223       // The only other way we can lower this is to turn it into a STORE,
4224       // LOAD pair, targetting a temporary location (a stack slot).
4225       Result = EmitStackConvert(Node->getOperand(0), SrcVT, DstVT, dl);
4226       break;
4227     }
4228     switch (getTypeAction(Node->getOperand(0).getValueType())) {
4229     case Expand: assert(0 && "Shouldn't need to expand other operators here!");
4230     case Legal:
4231       Tmp1 = LegalizeOp(Node->getOperand(0));
4232       Result = DAG.UpdateNodeOperands(Result, Tmp1);
4233       break;
4234     case Promote:
4235       Tmp1 = PromoteOp(Node->getOperand(0));
4236       Result = DAG.getNode(ISD::FP_EXTEND, dl, Op.getValueType(), Tmp1);
4237       break;
4238     }
4239     break;
4240   }
4241   case ISD::FP_ROUND: {
4242     MVT DstVT = Op.getValueType();
4243     MVT SrcVT = Op.getOperand(0).getValueType();
4244     if (TLI.getConvertAction(SrcVT, DstVT) == TargetLowering::Expand) {
4245       if (SrcVT == MVT::ppcf128) {
4246         SDValue Lo;
4247         ExpandOp(Node->getOperand(0), Lo, Result);
4248         // Round it the rest of the way (e.g. to f32) if needed.
4249         if (DstVT!=MVT::f64)
4250           Result = DAG.getNode(ISD::FP_ROUND, dl,
4251                                DstVT, Result, Op.getOperand(1));
4252         break;
4253       }
4254       // The only other way we can lower this is to turn it into a STORE,
4255       // LOAD pair, targetting a temporary location (a stack slot).
4256       Result = EmitStackConvert(Node->getOperand(0), DstVT, DstVT, dl);
4257       break;
4258     }
4259     switch (getTypeAction(Node->getOperand(0).getValueType())) {
4260     case Expand: assert(0 && "Shouldn't need to expand other operators here!");
4261     case Legal:
4262       Tmp1 = LegalizeOp(Node->getOperand(0));
4263       Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
4264       break;
4265     case Promote:
4266       Tmp1 = PromoteOp(Node->getOperand(0));
4267       Result = DAG.getNode(ISD::FP_ROUND, dl, Op.getValueType(), Tmp1,
4268                            Node->getOperand(1));
4269       break;
4270     }
4271     break;
4272   }
4273   case ISD::ANY_EXTEND:
4274   case ISD::ZERO_EXTEND:
4275   case ISD::SIGN_EXTEND:
4276     switch (getTypeAction(Node->getOperand(0).getValueType())) {
4277     case Expand: assert(0 && "Shouldn't need to expand other operators here!");
4278     case Legal:
4279       Tmp1 = LegalizeOp(Node->getOperand(0));
4280       Result = DAG.UpdateNodeOperands(Result, Tmp1);
4281       if (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0)) ==
4282           TargetLowering::Custom) {
4283         Tmp1 = TLI.LowerOperation(Result, DAG);
4284         if (Tmp1.getNode()) Result = Tmp1;
4285       }
4286       break;
4287     case Promote:
4288       switch (Node->getOpcode()) {
4289       case ISD::ANY_EXTEND:
4290         Tmp1 = PromoteOp(Node->getOperand(0));
4291         Result = DAG.getNode(ISD::ANY_EXTEND, dl, Op.getValueType(), Tmp1);
4292         break;
4293       case ISD::ZERO_EXTEND:
4294         Result = PromoteOp(Node->getOperand(0));
4295         Result = DAG.getNode(ISD::ANY_EXTEND, dl, Op.getValueType(), Result);
4296         Result = DAG.getZeroExtendInReg(Result, dl,
4297                                         Node->getOperand(0).getValueType());
4298         break;
4299       case ISD::SIGN_EXTEND:
4300         Result = PromoteOp(Node->getOperand(0));
4301         Result = DAG.getNode(ISD::ANY_EXTEND, dl, Op.getValueType(), Result);
4302         Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, Result.getValueType(),
4303                              Result,
4304                           DAG.getValueType(Node->getOperand(0).getValueType()));
4305         break;
4306       }
4307     }
4308     break;
4309   case ISD::FP_ROUND_INREG:
4310   case ISD::SIGN_EXTEND_INREG: {
4311     Tmp1 = LegalizeOp(Node->getOperand(0));
4312     MVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
4313
4314     // If this operation is not supported, convert it to a shl/shr or load/store
4315     // pair.
4316     switch (TLI.getOperationAction(Node->getOpcode(), ExtraVT)) {
4317     default: assert(0 && "This action not supported for this op yet!");
4318     case TargetLowering::Legal:
4319       Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
4320       break;
4321     case TargetLowering::Expand:
4322       // If this is an integer extend and shifts are supported, do that.
4323       if (Node->getOpcode() == ISD::SIGN_EXTEND_INREG) {
4324         // NOTE: we could fall back on load/store here too for targets without
4325         // SAR.  However, it is doubtful that any exist.
4326         unsigned BitsDiff = Node->getValueType(0).getSizeInBits() -
4327                             ExtraVT.getSizeInBits();
4328         SDValue ShiftCst = DAG.getConstant(BitsDiff, TLI.getShiftAmountTy());
4329         Result = DAG.getNode(ISD::SHL, dl, Node->getValueType(0),
4330                              Node->getOperand(0), ShiftCst);
4331         Result = DAG.getNode(ISD::SRA, dl, Node->getValueType(0),
4332                              Result, ShiftCst);
4333       } else if (Node->getOpcode() == ISD::FP_ROUND_INREG) {
4334         // The only way we can lower this is to turn it into a TRUNCSTORE,
4335         // EXTLOAD pair, targetting a temporary location (a stack slot).
4336
4337         // NOTE: there is a choice here between constantly creating new stack
4338         // slots and always reusing the same one.  We currently always create
4339         // new ones, as reuse may inhibit scheduling.
4340         Result = EmitStackConvert(Node->getOperand(0), ExtraVT,
4341                                   Node->getValueType(0), dl);
4342       } else {
4343         assert(0 && "Unknown op");
4344       }
4345       break;
4346     }
4347     break;
4348   }
4349   case ISD::TRAMPOLINE: {
4350     SDValue Ops[6];
4351     for (unsigned i = 0; i != 6; ++i)
4352       Ops[i] = LegalizeOp(Node->getOperand(i));
4353     Result = DAG.UpdateNodeOperands(Result, Ops, 6);
4354     // The only option for this node is to custom lower it.
4355     Result = TLI.LowerOperation(Result, DAG);
4356     assert(Result.getNode() && "Should always custom lower!");
4357
4358     // Since trampoline produces two values, make sure to remember that we
4359     // legalized both of them.
4360     Tmp1 = LegalizeOp(Result.getValue(1));
4361     Result = LegalizeOp(Result);
4362     AddLegalizedOperand(SDValue(Node, 0), Result);
4363     AddLegalizedOperand(SDValue(Node, 1), Tmp1);
4364     return Op.getResNo() ? Tmp1 : Result;
4365   }
4366   case ISD::FLT_ROUNDS_: {
4367     MVT VT = Node->getValueType(0);
4368     switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
4369     default: assert(0 && "This action not supported for this op yet!");
4370     case TargetLowering::Custom:
4371       Result = TLI.LowerOperation(Op, DAG);
4372       if (Result.getNode()) break;
4373       // Fall Thru
4374     case TargetLowering::Legal:
4375       // If this operation is not supported, lower it to constant 1
4376       Result = DAG.getConstant(1, VT);
4377       break;
4378     }
4379     break;
4380   }
4381   case ISD::TRAP: {
4382     MVT VT = Node->getValueType(0);
4383     switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
4384     default: assert(0 && "This action not supported for this op yet!");
4385     case TargetLowering::Legal:
4386       Tmp1 = LegalizeOp(Node->getOperand(0));
4387       Result = DAG.UpdateNodeOperands(Result, Tmp1);
4388       break;
4389     case TargetLowering::Custom:
4390       Result = TLI.LowerOperation(Op, DAG);
4391       if (Result.getNode()) break;
4392       // Fall Thru
4393     case TargetLowering::Expand:
4394       // If this operation is not supported, lower it to 'abort()' call
4395       Tmp1 = LegalizeOp(Node->getOperand(0));
4396       TargetLowering::ArgListTy Args;
4397       std::pair<SDValue, SDValue> CallResult =
4398         TLI.LowerCallTo(Tmp1, Type::VoidTy,
4399                         false, false, false, false, CallingConv::C, false,
4400                         DAG.getExternalSymbol("abort", TLI.getPointerTy()),
4401                         Args, DAG, dl);
4402       Result = CallResult.second;
4403       break;
4404     }
4405     break;
4406   }
4407
4408   case ISD::SADDO:
4409   case ISD::SSUBO: {
4410     MVT VT = Node->getValueType(0);
4411     switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
4412     default: assert(0 && "This action not supported for this op yet!");
4413     case TargetLowering::Custom:
4414       Result = TLI.LowerOperation(Op, DAG);
4415       if (Result.getNode()) break;
4416       // FALLTHROUGH
4417     case TargetLowering::Legal: {
4418       SDValue LHS = LegalizeOp(Node->getOperand(0));
4419       SDValue RHS = LegalizeOp(Node->getOperand(1));
4420
4421       SDValue Sum = DAG.getNode(Node->getOpcode() == ISD::SADDO ?
4422                                 ISD::ADD : ISD::SUB, dl, LHS.getValueType(),
4423                                 LHS, RHS);
4424       MVT OType = Node->getValueType(1);
4425
4426       SDValue Zero = DAG.getConstant(0, LHS.getValueType());
4427
4428       //   LHSSign -> LHS >= 0
4429       //   RHSSign -> RHS >= 0
4430       //   SumSign -> Sum >= 0
4431       //
4432       //   Add:
4433       //   Overflow -> (LHSSign == RHSSign) && (LHSSign != SumSign)
4434       //   Sub:
4435       //   Overflow -> (LHSSign != RHSSign) && (LHSSign != SumSign)
4436       //
4437       SDValue LHSSign = DAG.getSetCC(dl, OType, LHS, Zero, ISD::SETGE);
4438       SDValue RHSSign = DAG.getSetCC(dl, OType, RHS, Zero, ISD::SETGE);
4439       SDValue SignsMatch = DAG.getSetCC(dl, OType, LHSSign, RHSSign,
4440                                         Node->getOpcode() == ISD::SADDO ?
4441                                         ISD::SETEQ : ISD::SETNE);
4442
4443       SDValue SumSign = DAG.getSetCC(dl, OType, Sum, Zero, ISD::SETGE);
4444       SDValue SumSignNE = DAG.getSetCC(dl, OType, LHSSign, SumSign, ISD::SETNE);
4445
4446       SDValue Cmp = DAG.getNode(ISD::AND, dl, OType, SignsMatch, SumSignNE);
4447
4448       MVT ValueVTs[] = { LHS.getValueType(), OType };
4449       SDValue Ops[] = { Sum, Cmp };
4450
4451       Result = DAG.getNode(ISD::MERGE_VALUES, dl,
4452                            DAG.getVTList(&ValueVTs[0], 2),
4453                            &Ops[0], 2);
4454       SDNode *RNode = Result.getNode();
4455       DAG.ReplaceAllUsesWith(Node, RNode);
4456       break;
4457     }
4458     }
4459
4460     break;
4461   }
4462   case ISD::UADDO:
4463   case ISD::USUBO: {
4464     MVT VT = Node->getValueType(0);
4465     switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
4466     default: assert(0 && "This action not supported for this op yet!");
4467     case TargetLowering::Custom:
4468       Result = TLI.LowerOperation(Op, DAG);
4469       if (Result.getNode()) break;
4470       // FALLTHROUGH
4471     case TargetLowering::Legal: {
4472       SDValue LHS = LegalizeOp(Node->getOperand(0));
4473       SDValue RHS = LegalizeOp(Node->getOperand(1));
4474
4475       SDValue Sum = DAG.getNode(Node->getOpcode() == ISD::UADDO ?
4476                                 ISD::ADD : ISD::SUB, dl, LHS.getValueType(),
4477                                 LHS, RHS);
4478       MVT OType = Node->getValueType(1);
4479       SDValue Cmp = DAG.getSetCC(dl, OType, Sum, LHS,
4480                                  Node->getOpcode () == ISD::UADDO ?
4481                                  ISD::SETULT : ISD::SETUGT);
4482
4483       MVT ValueVTs[] = { LHS.getValueType(), OType };
4484       SDValue Ops[] = { Sum, Cmp };
4485
4486       Result = DAG.getNode(ISD::MERGE_VALUES, dl,
4487                            DAG.getVTList(&ValueVTs[0], 2),
4488                            &Ops[0], 2);
4489       SDNode *RNode = Result.getNode();
4490       DAG.ReplaceAllUsesWith(Node, RNode);
4491       break;
4492     }
4493     }
4494
4495     break;
4496   }
4497   case ISD::SMULO:
4498   case ISD::UMULO: {
4499     MVT VT = Node->getValueType(0);
4500     switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
4501     default: assert(0 && "This action is not supported at all!");
4502     case TargetLowering::Custom:
4503       Result = TLI.LowerOperation(Op, DAG);
4504       if (Result.getNode()) break;
4505       // Fall Thru
4506     case TargetLowering::Legal:
4507       // FIXME: According to Hacker's Delight, this can be implemented in
4508       // target independent lowering, but it would be inefficient, since it
4509       // requires a division + a branch.
4510       assert(0 && "Target independent lowering is not supported for SMULO/UMULO!");
4511     break;
4512     }
4513     break;
4514   }
4515
4516   }
4517
4518   assert(Result.getValueType() == Op.getValueType() &&
4519          "Bad legalization!");
4520
4521   // Make sure that the generated code is itself legal.
4522   if (Result != Op)
4523     Result = LegalizeOp(Result);
4524
4525   // Note that LegalizeOp may be reentered even from single-use nodes, which
4526   // means that we always must cache transformed nodes.
4527   AddLegalizedOperand(Op, Result);
4528   return Result;
4529 }
4530
4531 /// PromoteOp - Given an operation that produces a value in an invalid type,
4532 /// promote it to compute the value into a larger type.  The produced value will
4533 /// have the correct bits for the low portion of the register, but no guarantee
4534 /// is made about the top bits: it may be zero, sign-extended, or garbage.
4535 SDValue SelectionDAGLegalize::PromoteOp(SDValue Op) {
4536   MVT VT = Op.getValueType();
4537   MVT NVT = TLI.getTypeToTransformTo(VT);
4538   assert(getTypeAction(VT) == Promote &&
4539          "Caller should expand or legalize operands that are not promotable!");
4540   assert(NVT.bitsGT(VT) && NVT.isInteger() == VT.isInteger() &&
4541          "Cannot promote to smaller type!");
4542
4543   SDValue Tmp1, Tmp2, Tmp3;
4544   SDValue Result;
4545   SDNode *Node = Op.getNode();
4546   DebugLoc dl = Node->getDebugLoc();
4547
4548   DenseMap<SDValue, SDValue>::iterator I = PromotedNodes.find(Op);
4549   if (I != PromotedNodes.end()) return I->second;
4550
4551   switch (Node->getOpcode()) {
4552   case ISD::CopyFromReg:
4553     assert(0 && "CopyFromReg must be legal!");
4554   default:
4555 #ifndef NDEBUG
4556     cerr << "NODE: "; Node->dump(&DAG); cerr << "\n";
4557 #endif
4558     assert(0 && "Do not know how to promote this operator!");
4559     abort();
4560   case ISD::UNDEF:
4561     Result = DAG.getUNDEF(NVT);
4562     break;
4563   case ISD::Constant:
4564     if (VT != MVT::i1)
4565       Result = DAG.getNode(ISD::SIGN_EXTEND, dl, NVT, Op);
4566     else
4567       Result = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Op);
4568     assert(isa<ConstantSDNode>(Result) && "Didn't constant fold zext?");
4569     break;
4570   case ISD::ConstantFP:
4571     Result = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Op);
4572     assert(isa<ConstantFPSDNode>(Result) && "Didn't constant fold fp_extend?");
4573     break;
4574
4575   case ISD::SETCC: {
4576     MVT VT0 = Node->getOperand(0).getValueType();
4577     assert(isTypeLegal(TLI.getSetCCResultType(VT0))
4578            && "SetCC type is not legal??");
4579     Result = DAG.getNode(ISD::SETCC, dl, TLI.getSetCCResultType(VT0),
4580                          Node->getOperand(0), Node->getOperand(1),
4581                          Node->getOperand(2));
4582     break;
4583   }
4584   case ISD::TRUNCATE:
4585     switch (getTypeAction(Node->getOperand(0).getValueType())) {
4586     case Legal:
4587       Result = LegalizeOp(Node->getOperand(0));
4588       assert(Result.getValueType().bitsGE(NVT) &&
4589              "This truncation doesn't make sense!");
4590       if (Result.getValueType().bitsGT(NVT))    // Truncate to NVT instead of VT
4591         Result = DAG.getNode(ISD::TRUNCATE, dl, NVT, Result);
4592       break;
4593     case Promote:
4594       // The truncation is not required, because we don't guarantee anything
4595       // about high bits anyway.
4596       Result = PromoteOp(Node->getOperand(0));
4597       break;
4598     case Expand:
4599       ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
4600       // Truncate the low part of the expanded value to the result type
4601       Result = DAG.getNode(ISD::TRUNCATE, dl, NVT, Tmp1);
4602     }
4603     break;
4604   case ISD::SIGN_EXTEND:
4605   case ISD::ZERO_EXTEND:
4606   case ISD::ANY_EXTEND:
4607     switch (getTypeAction(Node->getOperand(0).getValueType())) {
4608     case Expand: assert(0 && "BUG: Smaller reg should have been promoted!");
4609     case Legal:
4610       // Input is legal?  Just do extend all the way to the larger type.
4611       Result = DAG.getNode(Node->getOpcode(), dl, NVT, Node->getOperand(0));
4612       break;
4613     case Promote:
4614       // Promote the reg if it's smaller.
4615       Result = PromoteOp(Node->getOperand(0));
4616       // The high bits are not guaranteed to be anything.  Insert an extend.
4617       if (Node->getOpcode() == ISD::SIGN_EXTEND)
4618         Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NVT, Result,
4619                          DAG.getValueType(Node->getOperand(0).getValueType()));
4620       else if (Node->getOpcode() == ISD::ZERO_EXTEND)
4621         Result = DAG.getZeroExtendInReg(Result, dl,
4622                                         Node->getOperand(0).getValueType());
4623       break;
4624     }
4625     break;
4626   case ISD::CONVERT_RNDSAT: {
4627     ISD::CvtCode CvtCode = cast<CvtRndSatSDNode>(Node)->getCvtCode();
4628     assert ((CvtCode == ISD::CVT_SS || CvtCode == ISD::CVT_SU ||
4629              CvtCode == ISD::CVT_US || CvtCode == ISD::CVT_UU ||
4630              CvtCode == ISD::CVT_SF || CvtCode == ISD::CVT_UF) &&
4631             "can only promote integers");
4632     Result = DAG.getConvertRndSat(NVT, dl, Node->getOperand(0),
4633                                   Node->getOperand(1), Node->getOperand(2),
4634                                   Node->getOperand(3), Node->getOperand(4),
4635                                   CvtCode);
4636     break;
4637
4638   }
4639   case ISD::BIT_CONVERT:
4640     Result = EmitStackConvert(Node->getOperand(0), Node->getValueType(0),
4641                               Node->getValueType(0), dl);
4642     Result = PromoteOp(Result);
4643     break;
4644
4645   case ISD::FP_EXTEND:
4646     assert(0 && "Case not implemented.  Dynamically dead with 2 FP types!");
4647   case ISD::FP_ROUND:
4648     switch (getTypeAction(Node->getOperand(0).getValueType())) {
4649     case Expand: assert(0 && "BUG: Cannot expand FP regs!");
4650     case Promote:  assert(0 && "Unreachable with 2 FP types!");
4651     case Legal:
4652       if (Node->getConstantOperandVal(1) == 0) {
4653         // Input is legal?  Do an FP_ROUND_INREG.
4654         Result = DAG.getNode(ISD::FP_ROUND_INREG, dl, NVT, Node->getOperand(0),
4655                              DAG.getValueType(VT));
4656       } else {
4657         // Just remove the truncate, it isn't affecting the value.
4658         Result = DAG.getNode(ISD::FP_ROUND, dl, NVT, Node->getOperand(0),
4659                              Node->getOperand(1));
4660       }
4661       break;
4662     }
4663     break;
4664   case ISD::SINT_TO_FP:
4665   case ISD::UINT_TO_FP:
4666     switch (getTypeAction(Node->getOperand(0).getValueType())) {
4667     case Legal:
4668       // No extra round required here.
4669       Result = DAG.getNode(Node->getOpcode(), dl, NVT, Node->getOperand(0));
4670       break;
4671
4672     case Promote:
4673       Result = PromoteOp(Node->getOperand(0));
4674       if (Node->getOpcode() == ISD::SINT_TO_FP)
4675         Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, Result.getValueType(),
4676                              Result,
4677                          DAG.getValueType(Node->getOperand(0).getValueType()));
4678       else
4679         Result = DAG.getZeroExtendInReg(Result, dl,
4680                                         Node->getOperand(0).getValueType());
4681       // No extra round required here.
4682       Result = DAG.getNode(Node->getOpcode(), dl, NVT, Result);
4683       break;
4684     case Expand:
4685       Result = ExpandIntToFP(Node->getOpcode() == ISD::SINT_TO_FP, NVT,
4686                              Node->getOperand(0), dl);
4687       // Round if we cannot tolerate excess precision.
4688       if (NoExcessFPPrecision)
4689         Result = DAG.getNode(ISD::FP_ROUND_INREG, dl, NVT, Result,
4690                              DAG.getValueType(VT));
4691       break;
4692     }
4693     break;
4694
4695   case ISD::SIGN_EXTEND_INREG:
4696     Result = PromoteOp(Node->getOperand(0));
4697     Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NVT, Result,
4698                          Node->getOperand(1));
4699     break;
4700   case ISD::FP_TO_SINT:
4701   case ISD::FP_TO_UINT:
4702     switch (getTypeAction(Node->getOperand(0).getValueType())) {
4703     case Legal:
4704     case Expand:
4705       Tmp1 = Node->getOperand(0);
4706       break;
4707     case Promote:
4708       // The input result is prerounded, so we don't have to do anything
4709       // special.
4710       Tmp1 = PromoteOp(Node->getOperand(0));
4711       break;
4712     }
4713     // If we're promoting a UINT to a larger size, check to see if the new node
4714     // will be legal.  If it isn't, check to see if FP_TO_SINT is legal, since
4715     // we can use that instead.  This allows us to generate better code for
4716     // FP_TO_UINT for small destination sizes on targets where FP_TO_UINT is not
4717     // legal, such as PowerPC.
4718     if (Node->getOpcode() == ISD::FP_TO_UINT &&
4719         !TLI.isOperationLegalOrCustom(ISD::FP_TO_UINT, NVT) &&
4720         (TLI.isOperationLegalOrCustom(ISD::FP_TO_SINT, NVT) ||
4721          TLI.getOperationAction(ISD::FP_TO_SINT, NVT)==TargetLowering::Custom)){
4722       Result = DAG.getNode(ISD::FP_TO_SINT, dl, NVT, Tmp1);
4723     } else {
4724       Result = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1);
4725     }
4726     break;
4727
4728   case ISD::FABS:
4729   case ISD::FNEG:
4730     Tmp1 = PromoteOp(Node->getOperand(0));
4731     assert(Tmp1.getValueType() == NVT);
4732     Result = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1);
4733     // NOTE: we do not have to do any extra rounding here for
4734     // NoExcessFPPrecision, because we know the input will have the appropriate
4735     // precision, and these operations don't modify precision at all.
4736     break;
4737
4738   case ISD::FLOG:
4739   case ISD::FLOG2:
4740   case ISD::FLOG10:
4741   case ISD::FEXP:
4742   case ISD::FEXP2:
4743   case ISD::FSQRT:
4744   case ISD::FSIN:
4745   case ISD::FCOS:
4746   case ISD::FTRUNC:
4747   case ISD::FFLOOR:
4748   case ISD::FCEIL:
4749   case ISD::FRINT:
4750   case ISD::FNEARBYINT:
4751     Tmp1 = PromoteOp(Node->getOperand(0));
4752     assert(Tmp1.getValueType() == NVT);
4753     Result = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1);
4754     if (NoExcessFPPrecision)
4755       Result = DAG.getNode(ISD::FP_ROUND_INREG, dl, NVT, Result,
4756                            DAG.getValueType(VT));
4757     break;
4758
4759   case ISD::FPOW:
4760   case ISD::FPOWI: {
4761     // Promote f32 pow(i) to f64 pow(i).  Note that this could insert a libcall
4762     // directly as well, which may be better.
4763     Tmp1 = PromoteOp(Node->getOperand(0));
4764     Tmp2 = Node->getOperand(1);
4765     if (Node->getOpcode() == ISD::FPOW)
4766       Tmp2 = PromoteOp(Tmp2);
4767     assert(Tmp1.getValueType() == NVT);
4768     Result = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2);
4769     if (NoExcessFPPrecision)
4770       Result = DAG.getNode(ISD::FP_ROUND_INREG, dl, NVT, Result,
4771                            DAG.getValueType(VT));
4772     break;
4773   }
4774
4775   case ISD::ATOMIC_CMP_SWAP: {
4776     AtomicSDNode* AtomNode = cast<AtomicSDNode>(Node);
4777     Tmp2 = PromoteOp(Node->getOperand(2));
4778     Tmp3 = PromoteOp(Node->getOperand(3));
4779     Result = DAG.getAtomic(Node->getOpcode(), dl, AtomNode->getMemoryVT(),
4780                            AtomNode->getChain(),
4781                            AtomNode->getBasePtr(), Tmp2, Tmp3,
4782                            AtomNode->getSrcValue(),
4783                            AtomNode->getAlignment());
4784     // Remember that we legalized the chain.
4785     AddLegalizedOperand(Op.getValue(1), LegalizeOp(Result.getValue(1)));
4786     break;
4787   }
4788   case ISD::ATOMIC_LOAD_ADD:
4789   case ISD::ATOMIC_LOAD_SUB:
4790   case ISD::ATOMIC_LOAD_AND:
4791   case ISD::ATOMIC_LOAD_OR:
4792   case ISD::ATOMIC_LOAD_XOR:
4793   case ISD::ATOMIC_LOAD_NAND:
4794   case ISD::ATOMIC_LOAD_MIN:
4795   case ISD::ATOMIC_LOAD_MAX:
4796   case ISD::ATOMIC_LOAD_UMIN:
4797   case ISD::ATOMIC_LOAD_UMAX:
4798   case ISD::ATOMIC_SWAP: {
4799     AtomicSDNode* AtomNode = cast<AtomicSDNode>(Node);
4800     Tmp2 = PromoteOp(Node->getOperand(2));
4801     Result = DAG.getAtomic(Node->getOpcode(), dl, AtomNode->getMemoryVT(),
4802                            AtomNode->getChain(),
4803                            AtomNode->getBasePtr(), Tmp2,
4804                            AtomNode->getSrcValue(),
4805                            AtomNode->getAlignment());
4806     // Remember that we legalized the chain.
4807     AddLegalizedOperand(Op.getValue(1), LegalizeOp(Result.getValue(1)));
4808     break;
4809   }
4810
4811   case ISD::AND:
4812   case ISD::OR:
4813   case ISD::XOR:
4814   case ISD::ADD:
4815   case ISD::SUB:
4816   case ISD::MUL:
4817     // The input may have strange things in the top bits of the registers, but
4818     // these operations don't care.  They may have weird bits going out, but
4819     // that too is okay if they are integer operations.
4820     Tmp1 = PromoteOp(Node->getOperand(0));
4821     Tmp2 = PromoteOp(Node->getOperand(1));
4822     assert(Tmp1.getValueType() == NVT && Tmp2.getValueType() == NVT);
4823     Result = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2);
4824     break;
4825   case ISD::FADD:
4826   case ISD::FSUB:
4827   case ISD::FMUL:
4828     Tmp1 = PromoteOp(Node->getOperand(0));
4829     Tmp2 = PromoteOp(Node->getOperand(1));
4830     assert(Tmp1.getValueType() == NVT && Tmp2.getValueType() == NVT);
4831     Result = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2);
4832
4833     // Floating point operations will give excess precision that we may not be
4834     // able to tolerate.  If we DO allow excess precision, just leave it,
4835     // otherwise excise it.
4836     // FIXME: Why would we need to round FP ops more than integer ones?
4837     //     Is Round(Add(Add(A,B),C)) != Round(Add(Round(Add(A,B)), C))
4838     if (NoExcessFPPrecision)
4839       Result = DAG.getNode(ISD::FP_ROUND_INREG, dl, NVT, Result,
4840                            DAG.getValueType(VT));
4841     break;
4842
4843   case ISD::SDIV:
4844   case ISD::SREM:
4845     // These operators require that their input be sign extended.
4846     Tmp1 = PromoteOp(Node->getOperand(0));
4847     Tmp2 = PromoteOp(Node->getOperand(1));
4848     if (NVT.isInteger()) {
4849       Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NVT, Tmp1,
4850                          DAG.getValueType(VT));
4851       Tmp2 = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NVT, Tmp2,
4852                          DAG.getValueType(VT));
4853     }
4854     Result = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2);
4855
4856     // Perform FP_ROUND: this is probably overly pessimistic.
4857     if (NVT.isFloatingPoint() && NoExcessFPPrecision)
4858       Result = DAG.getNode(ISD::FP_ROUND_INREG, dl, NVT, Result,
4859                            DAG.getValueType(VT));
4860     break;
4861   case ISD::FDIV:
4862   case ISD::FREM:
4863   case ISD::FCOPYSIGN:
4864     // These operators require that their input be fp extended.
4865     switch (getTypeAction(Node->getOperand(0).getValueType())) {
4866     case Expand: assert(0 && "not implemented");
4867     case Legal:   Tmp1 = LegalizeOp(Node->getOperand(0)); break;
4868     case Promote: Tmp1 = PromoteOp(Node->getOperand(0));  break;
4869     }
4870     switch (getTypeAction(Node->getOperand(1).getValueType())) {
4871     case Expand: assert(0 && "not implemented");
4872     case Legal:   Tmp2 = LegalizeOp(Node->getOperand(1)); break;
4873     case Promote: Tmp2 = PromoteOp(Node->getOperand(1)); break;
4874     }
4875     Result = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2);
4876
4877     // Perform FP_ROUND: this is probably overly pessimistic.
4878     if (NoExcessFPPrecision && Node->getOpcode() != ISD::FCOPYSIGN)
4879       Result = DAG.getNode(ISD::FP_ROUND_INREG, dl, NVT, Result,
4880                            DAG.getValueType(VT));
4881     break;
4882
4883   case ISD::UDIV:
4884   case ISD::UREM:
4885     // These operators require that their input be zero extended.
4886     Tmp1 = PromoteOp(Node->getOperand(0));
4887     Tmp2 = PromoteOp(Node->getOperand(1));
4888     assert(NVT.isInteger() && "Operators don't apply to FP!");
4889     Tmp1 = DAG.getZeroExtendInReg(Tmp1, dl, VT);
4890     Tmp2 = DAG.getZeroExtendInReg(Tmp2, dl, VT);
4891     Result = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2);
4892     break;
4893
4894   case ISD::SHL:
4895     Tmp1 = PromoteOp(Node->getOperand(0));
4896     Result = DAG.getNode(ISD::SHL, dl, NVT, Tmp1, Node->getOperand(1));
4897     break;
4898   case ISD::SRA:
4899     // The input value must be properly sign extended.
4900     Tmp1 = PromoteOp(Node->getOperand(0));
4901     Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NVT, Tmp1,
4902                        DAG.getValueType(VT));
4903     Result = DAG.getNode(ISD::SRA, dl, NVT, Tmp1, Node->getOperand(1));
4904     break;
4905   case ISD::SRL:
4906     // The input value must be properly zero extended.
4907     Tmp1 = PromoteOp(Node->getOperand(0));
4908     Tmp1 = DAG.getZeroExtendInReg(Tmp1, dl, VT);
4909     Result = DAG.getNode(ISD::SRL, dl, NVT, Tmp1, Node->getOperand(1));
4910     break;
4911
4912   case ISD::VAARG:
4913     Tmp1 = Node->getOperand(0);   // Get the chain.
4914     Tmp2 = Node->getOperand(1);   // Get the pointer.
4915     if (TLI.getOperationAction(ISD::VAARG, VT) == TargetLowering::Custom) {
4916       Tmp3 = DAG.getVAArg(VT, dl, Tmp1, Tmp2, Node->getOperand(2));
4917       Result = TLI.LowerOperation(Tmp3, DAG);
4918     } else {
4919       const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
4920       SDValue VAList = DAG.getLoad(TLI.getPointerTy(), dl, Tmp1, Tmp2, V, 0);
4921       // Increment the pointer, VAList, to the next vaarg
4922       Tmp3 = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(), VAList,
4923                          DAG.getConstant(VT.getSizeInBits()/8,
4924                                          TLI.getPointerTy()));
4925       // Store the incremented VAList to the legalized pointer
4926       Tmp3 = DAG.getStore(VAList.getValue(1), dl, Tmp3, Tmp2, V, 0);
4927       // Load the actual argument out of the pointer VAList
4928       Result = DAG.getExtLoad(ISD::EXTLOAD, dl, NVT, Tmp3, VAList, NULL, 0, VT);
4929     }
4930     // Remember that we legalized the chain.
4931     AddLegalizedOperand(Op.getValue(1), LegalizeOp(Result.getValue(1)));
4932     break;
4933
4934   case ISD::LOAD: {
4935     LoadSDNode *LD = cast<LoadSDNode>(Node);
4936     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(Node)
4937       ? ISD::EXTLOAD : LD->getExtensionType();
4938     Result = DAG.getExtLoad(ExtType, dl, NVT,
4939                             LD->getChain(), LD->getBasePtr(),
4940                             LD->getSrcValue(), LD->getSrcValueOffset(),
4941                             LD->getMemoryVT(),
4942                             LD->isVolatile(),
4943                             LD->getAlignment());
4944     // Remember that we legalized the chain.
4945     AddLegalizedOperand(Op.getValue(1), LegalizeOp(Result.getValue(1)));
4946     break;
4947   }
4948   case ISD::SELECT: {
4949     Tmp2 = PromoteOp(Node->getOperand(1));   // Legalize the op0
4950     Tmp3 = PromoteOp(Node->getOperand(2));   // Legalize the op1
4951
4952     MVT VT2 = Tmp2.getValueType();
4953     assert(VT2 == Tmp3.getValueType()
4954            && "PromoteOp SELECT: Operands 2 and 3 ValueTypes don't match");
4955     // Ensure that the resulting node is at least the same size as the operands'
4956     // value types, because we cannot assume that TLI.getSetCCValueType() is
4957     // constant.
4958     Result = DAG.getNode(ISD::SELECT, dl, VT2, Node->getOperand(0), Tmp2, Tmp3);
4959     break;
4960   }
4961   case ISD::SELECT_CC:
4962     Tmp2 = PromoteOp(Node->getOperand(2));   // True
4963     Tmp3 = PromoteOp(Node->getOperand(3));   // False
4964     Result = DAG.getNode(ISD::SELECT_CC, dl, NVT, Node->getOperand(0),
4965                          Node->getOperand(1), Tmp2, Tmp3, Node->getOperand(4));
4966     break;
4967   case ISD::BSWAP:
4968     Tmp1 = Node->getOperand(0);
4969     Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Tmp1);
4970     Tmp1 = DAG.getNode(ISD::BSWAP, dl, NVT, Tmp1);
4971     Result = DAG.getNode(ISD::SRL, dl, NVT, Tmp1,
4972                          DAG.getConstant(NVT.getSizeInBits() -
4973                                          VT.getSizeInBits(),
4974                                          TLI.getShiftAmountTy()));
4975     break;
4976   case ISD::CTPOP:
4977   case ISD::CTTZ:
4978   case ISD::CTLZ:
4979     // Zero extend the argument
4980     Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Node->getOperand(0));
4981     // Perform the larger operation, then subtract if needed.
4982     Tmp1 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1);
4983     switch(Node->getOpcode()) {
4984     case ISD::CTPOP:
4985       Result = Tmp1;
4986       break;
4987     case ISD::CTTZ:
4988       // if Tmp1 == sizeinbits(NVT) then Tmp1 = sizeinbits(Old VT)
4989       Tmp2 = DAG.getSetCC(dl, TLI.getSetCCResultType(Tmp1.getValueType()), Tmp1,
4990                           DAG.getConstant(NVT.getSizeInBits(), NVT),
4991                           ISD::SETEQ);
4992       Result = DAG.getNode(ISD::SELECT, dl, NVT, Tmp2,
4993                            DAG.getConstant(VT.getSizeInBits(), NVT), Tmp1);
4994       break;
4995     case ISD::CTLZ:
4996       //Tmp1 = Tmp1 - (sizeinbits(NVT) - sizeinbits(Old VT))
4997       Result = DAG.getNode(ISD::SUB, dl, NVT, Tmp1,
4998                            DAG.getConstant(NVT.getSizeInBits() -
4999                                            VT.getSizeInBits(), NVT));
5000       break;
5001     }
5002     break;
5003   case ISD::EXTRACT_SUBVECTOR:
5004     Result = PromoteOp(ExpandEXTRACT_SUBVECTOR(Op));
5005     break;
5006   case ISD::EXTRACT_VECTOR_ELT:
5007     Result = PromoteOp(ExpandEXTRACT_VECTOR_ELT(Op));
5008     break;
5009   }
5010
5011   assert(Result.getNode() && "Didn't set a result!");
5012
5013   // Make sure the result is itself legal.
5014   Result = LegalizeOp(Result);
5015
5016   // Remember that we promoted this!
5017   AddPromotedOperand(Op, Result);
5018   return Result;
5019 }
5020
5021 /// ExpandEXTRACT_VECTOR_ELT - Expand an EXTRACT_VECTOR_ELT operation into
5022 /// a legal EXTRACT_VECTOR_ELT operation, scalar code, or memory traffic,
5023 /// based on the vector type. The return type of this matches the element type
5024 /// of the vector, which may not be legal for the target.
5025 SDValue SelectionDAGLegalize::ExpandEXTRACT_VECTOR_ELT(SDValue Op) {
5026   // We know that operand #0 is the Vec vector.  If the index is a constant
5027   // or if the invec is a supported hardware type, we can use it.  Otherwise,
5028   // lower to a store then an indexed load.
5029   SDValue Vec = Op.getOperand(0);
5030   SDValue Idx = Op.getOperand(1);
5031   DebugLoc dl = Op.getDebugLoc();
5032
5033   MVT TVT = Vec.getValueType();
5034   unsigned NumElems = TVT.getVectorNumElements();
5035
5036   switch (TLI.getOperationAction(ISD::EXTRACT_VECTOR_ELT, TVT)) {
5037   default: assert(0 && "This action is not supported yet!");
5038   case TargetLowering::Custom: {
5039     Vec = LegalizeOp(Vec);
5040     Op = DAG.UpdateNodeOperands(Op, Vec, Idx);
5041     SDValue Tmp3 = TLI.LowerOperation(Op, DAG);
5042     if (Tmp3.getNode())
5043       return Tmp3;
5044     break;
5045   }
5046   case TargetLowering::Legal:
5047     if (isTypeLegal(TVT)) {
5048       Vec = LegalizeOp(Vec);
5049       Op = DAG.UpdateNodeOperands(Op, Vec, Idx);
5050       return Op;
5051     }
5052     break;
5053   case TargetLowering::Promote:
5054     assert(TVT.isVector() && "not vector type");
5055     // fall thru to expand since vectors are by default are promote
5056   case TargetLowering::Expand:
5057     break;
5058   }
5059
5060   if (NumElems == 1) {
5061     // This must be an access of the only element.  Return it.
5062     Op = ScalarizeVectorOp(Vec);
5063   } else if (!TLI.isTypeLegal(TVT) && isa<ConstantSDNode>(Idx)) {
5064     unsigned NumLoElts =  1 << Log2_32(NumElems-1);
5065     ConstantSDNode *CIdx = cast<ConstantSDNode>(Idx);
5066     SDValue Lo, Hi;
5067     SplitVectorOp(Vec, Lo, Hi);
5068     if (CIdx->getZExtValue() < NumLoElts) {
5069       Vec = Lo;
5070     } else {
5071       Vec = Hi;
5072       Idx = DAG.getConstant(CIdx->getZExtValue() - NumLoElts,
5073                             Idx.getValueType());
5074     }
5075
5076     // It's now an extract from the appropriate high or low part.  Recurse.
5077     Op = DAG.UpdateNodeOperands(Op, Vec, Idx);
5078     Op = ExpandEXTRACT_VECTOR_ELT(Op);
5079   } else {
5080     Op = ExpandExtractFromVectorThroughStack(Op);
5081   }
5082   return Op;
5083 }
5084
5085 SDValue SelectionDAGLegalize::ExpandExtractFromVectorThroughStack(SDValue Op) {
5086   SDValue Vec = Op.getOperand(0);
5087   SDValue Idx = Op.getOperand(1);
5088   DebugLoc dl = Op.getDebugLoc();
5089   // Store the value to a temporary stack slot, then LOAD the returned part.
5090   SDValue StackPtr = DAG.CreateStackTemporary(Vec.getValueType());
5091   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, Vec, StackPtr, NULL, 0);
5092
5093   // Add the offset to the index.
5094   unsigned EltSize = Op.getValueType().getSizeInBits()/8;
5095   Idx = DAG.getNode(ISD::MUL, dl, Idx.getValueType(), Idx,
5096                     DAG.getConstant(EltSize, Idx.getValueType()));
5097
5098   if (Idx.getValueType().bitsGT(TLI.getPointerTy()))
5099     Idx = DAG.getNode(ISD::TRUNCATE, dl, TLI.getPointerTy(), Idx);
5100   else
5101     Idx = DAG.getNode(ISD::ZERO_EXTEND, dl, TLI.getPointerTy(), Idx);
5102
5103   StackPtr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(), Idx, StackPtr);
5104
5105   return DAG.getLoad(Op.getValueType(), dl, Ch, StackPtr, NULL, 0);
5106 }
5107
5108 /// ExpandEXTRACT_SUBVECTOR - Expand a EXTRACT_SUBVECTOR operation.  For now
5109 /// we assume the operation can be split if it is not already legal.
5110 SDValue SelectionDAGLegalize::ExpandEXTRACT_SUBVECTOR(SDValue Op) {
5111   // We know that operand #0 is the Vec vector.  For now we assume the index
5112   // is a constant and that the extracted result is a supported hardware type.
5113   SDValue Vec = Op.getOperand(0);
5114   SDValue Idx = LegalizeOp(Op.getOperand(1));
5115
5116   unsigned NumElems = Vec.getValueType().getVectorNumElements();
5117
5118   if (NumElems == Op.getValueType().getVectorNumElements()) {
5119     // This must be an access of the desired vector length.  Return it.
5120     return Vec;
5121   }
5122
5123   ConstantSDNode *CIdx = cast<ConstantSDNode>(Idx);
5124   SDValue Lo, Hi;
5125   SplitVectorOp(Vec, Lo, Hi);
5126   if (CIdx->getZExtValue() < NumElems/2) {
5127     Vec = Lo;
5128   } else {
5129     Vec = Hi;
5130     Idx = DAG.getConstant(CIdx->getZExtValue() - NumElems/2,
5131                           Idx.getValueType());
5132   }
5133
5134   // It's now an extract from the appropriate high or low part.  Recurse.
5135   Op = DAG.UpdateNodeOperands(Op, Vec, Idx);
5136   return ExpandEXTRACT_SUBVECTOR(Op);
5137 }
5138
5139 /// LegalizeSetCCOperands - Attempts to create a legal LHS and RHS for a SETCC
5140 /// with condition CC on the current target.  This usually involves legalizing
5141 /// or promoting the arguments.  In the case where LHS and RHS must be expanded,
5142 /// there may be no choice but to create a new SetCC node to represent the
5143 /// legalized value of setcc lhs, rhs.  In this case, the value is returned in
5144 /// LHS, and the SDValue returned in RHS has a nil SDNode value.
5145 void SelectionDAGLegalize::LegalizeSetCCOperands(SDValue &LHS,
5146                                                  SDValue &RHS,
5147                                                  SDValue &CC,
5148                                                  DebugLoc dl) {
5149   SDValue Tmp1, Tmp2, Tmp3, Result;
5150
5151   switch (getTypeAction(LHS.getValueType())) {
5152   case Legal:
5153     Tmp1 = LegalizeOp(LHS);   // LHS
5154     Tmp2 = LegalizeOp(RHS);   // RHS
5155     break;
5156   case Promote:
5157     Tmp1 = PromoteOp(LHS);   // LHS
5158     Tmp2 = PromoteOp(RHS);   // RHS
5159
5160     // If this is an FP compare, the operands have already been extended.
5161     if (LHS.getValueType().isInteger()) {
5162       MVT VT = LHS.getValueType();
5163       MVT NVT = TLI.getTypeToTransformTo(VT);
5164
5165       // Otherwise, we have to insert explicit sign or zero extends.  Note
5166       // that we could insert sign extends for ALL conditions, but zero extend
5167       // is cheaper on many machines (an AND instead of two shifts), so prefer
5168       // it.
5169       switch (cast<CondCodeSDNode>(CC)->get()) {
5170       default: assert(0 && "Unknown integer comparison!");
5171       case ISD::SETEQ:
5172       case ISD::SETNE:
5173       case ISD::SETUGE:
5174       case ISD::SETUGT:
5175       case ISD::SETULE:
5176       case ISD::SETULT:
5177         // ALL of these operations will work if we either sign or zero extend
5178         // the operands (including the unsigned comparisons!).  Zero extend is
5179         // usually a simpler/cheaper operation, so prefer it.
5180         Tmp1 = DAG.getZeroExtendInReg(Tmp1, dl, VT);
5181         Tmp2 = DAG.getZeroExtendInReg(Tmp2, dl, VT);
5182         break;
5183       case ISD::SETGE:
5184       case ISD::SETGT:
5185       case ISD::SETLT:
5186       case ISD::SETLE:
5187         Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NVT, Tmp1,
5188                            DAG.getValueType(VT));
5189         Tmp2 = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NVT, Tmp2,
5190                            DAG.getValueType(VT));
5191         Tmp1 = LegalizeOp(Tmp1); // Relegalize new nodes.
5192         Tmp2 = LegalizeOp(Tmp2); // Relegalize new nodes.
5193         break;
5194       }
5195     }
5196     break;
5197   case Expand: {
5198     MVT VT = LHS.getValueType();
5199     if (VT == MVT::f32 || VT == MVT::f64) {
5200       // Expand into one or more soft-fp libcall(s).
5201       RTLIB::Libcall LC1 = RTLIB::UNKNOWN_LIBCALL, LC2 = RTLIB::UNKNOWN_LIBCALL;
5202       switch (cast<CondCodeSDNode>(CC)->get()) {
5203       case ISD::SETEQ:
5204       case ISD::SETOEQ:
5205         LC1 = (VT == MVT::f32) ? RTLIB::OEQ_F32 : RTLIB::OEQ_F64;
5206         break;
5207       case ISD::SETNE:
5208       case ISD::SETUNE:
5209         LC1 = (VT == MVT::f32) ? RTLIB::UNE_F32 : RTLIB::UNE_F64;
5210         break;
5211       case ISD::SETGE:
5212       case ISD::SETOGE:
5213         LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 : RTLIB::OGE_F64;
5214         break;
5215       case ISD::SETLT:
5216       case ISD::SETOLT:
5217         LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 : RTLIB::OLT_F64;
5218         break;
5219       case ISD::SETLE:
5220       case ISD::SETOLE:
5221         LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 : RTLIB::OLE_F64;
5222         break;
5223       case ISD::SETGT:
5224       case ISD::SETOGT:
5225         LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 : RTLIB::OGT_F64;
5226         break;
5227       case ISD::SETUO:
5228         LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 : RTLIB::UO_F64;
5229         break;
5230       case ISD::SETO:
5231         LC1 = (VT == MVT::f32) ? RTLIB::O_F32 : RTLIB::O_F64;
5232         break;
5233       default:
5234         LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 : RTLIB::UO_F64;
5235         switch (cast<CondCodeSDNode>(CC)->get()) {
5236         case ISD::SETONE:
5237           // SETONE = SETOLT | SETOGT
5238           LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 : RTLIB::OLT_F64;
5239           // Fallthrough
5240         case ISD::SETUGT:
5241           LC2 = (VT == MVT::f32) ? RTLIB::OGT_F32 : RTLIB::OGT_F64;
5242           break;
5243         case ISD::SETUGE:
5244           LC2 = (VT == MVT::f32) ? RTLIB::OGE_F32 : RTLIB::OGE_F64;
5245           break;
5246         case ISD::SETULT:
5247           LC2 = (VT == MVT::f32) ? RTLIB::OLT_F32 : RTLIB::OLT_F64;
5248           break;
5249         case ISD::SETULE:
5250           LC2 = (VT == MVT::f32) ? RTLIB::OLE_F32 : RTLIB::OLE_F64;
5251           break;
5252         case ISD::SETUEQ:
5253           LC2 = (VT == MVT::f32) ? RTLIB::OEQ_F32 : RTLIB::OEQ_F64;
5254           break;
5255         default: assert(0 && "Unsupported FP setcc!");
5256         }
5257       }
5258
5259       SDValue Dummy;
5260       SDValue Ops[2] = { LHS, RHS };
5261       Tmp1 = ExpandLibCall(LC1, DAG.getMergeValues(Ops, 2, dl).getNode(),
5262                            false /*sign irrelevant*/, Dummy);
5263       Tmp2 = DAG.getConstant(0, MVT::i32);
5264       CC = DAG.getCondCode(TLI.getCmpLibcallCC(LC1));
5265       if (LC2 != RTLIB::UNKNOWN_LIBCALL) {
5266         Tmp1 = DAG.getNode(ISD::SETCC, dl,
5267                            TLI.getSetCCResultType(Tmp1.getValueType()),
5268                            Tmp1, Tmp2, CC);
5269         LHS = ExpandLibCall(LC2, DAG.getMergeValues(Ops, 2, dl).getNode(),
5270                             false /*sign irrelevant*/, Dummy);
5271         Tmp2 = DAG.getNode(ISD::SETCC, dl,
5272                            TLI.getSetCCResultType(LHS.getValueType()), LHS,
5273                            Tmp2, DAG.getCondCode(TLI.getCmpLibcallCC(LC2)));
5274         Tmp1 = DAG.getNode(ISD::OR, dl, Tmp1.getValueType(), Tmp1, Tmp2);
5275         Tmp2 = SDValue();
5276       }
5277       LHS = LegalizeOp(Tmp1);
5278       RHS = Tmp2;
5279       return;
5280     }
5281
5282     SDValue LHSLo, LHSHi, RHSLo, RHSHi;
5283     ExpandOp(LHS, LHSLo, LHSHi);
5284     ExpandOp(RHS, RHSLo, RHSHi);
5285     ISD::CondCode CCCode = cast<CondCodeSDNode>(CC)->get();
5286
5287     if (VT==MVT::ppcf128) {
5288       // FIXME:  This generated code sucks.  We want to generate
5289       //         FCMPU crN, hi1, hi2
5290       //         BNE crN, L:
5291       //         FCMPU crN, lo1, lo2
5292       // The following can be improved, but not that much.
5293       Tmp1 = DAG.getSetCC(dl, TLI.getSetCCResultType(LHSHi.getValueType()),
5294                           LHSHi, RHSHi, ISD::SETOEQ);
5295       Tmp2 = DAG.getSetCC(dl, TLI.getSetCCResultType(LHSLo.getValueType()),
5296                           LHSLo, RHSLo, CCCode);
5297       Tmp3 = DAG.getNode(ISD::AND, dl, Tmp1.getValueType(), Tmp1, Tmp2);
5298       Tmp1 = DAG.getSetCC(dl, TLI.getSetCCResultType(LHSHi.getValueType()),
5299                           LHSHi, RHSHi, ISD::SETUNE);
5300       Tmp2 = DAG.getSetCC(dl, TLI.getSetCCResultType(LHSHi.getValueType()),
5301                           LHSHi, RHSHi, CCCode);
5302       Tmp1 = DAG.getNode(ISD::AND, dl, Tmp1.getValueType(), Tmp1, Tmp2);
5303       Tmp1 = DAG.getNode(ISD::OR, dl, Tmp1.getValueType(), Tmp1, Tmp3);
5304       Tmp2 = SDValue();
5305       break;
5306     }
5307
5308     switch (CCCode) {
5309     case ISD::SETEQ:
5310     case ISD::SETNE:
5311       if (RHSLo == RHSHi)
5312         if (ConstantSDNode *RHSCST = dyn_cast<ConstantSDNode>(RHSLo))
5313           if (RHSCST->isAllOnesValue()) {
5314             // Comparison to -1.
5315             Tmp1 = DAG.getNode(ISD::AND, dl,LHSLo.getValueType(), LHSLo, LHSHi);
5316             Tmp2 = RHSLo;
5317             break;
5318           }
5319
5320       Tmp1 = DAG.getNode(ISD::XOR, dl, LHSLo.getValueType(), LHSLo, RHSLo);
5321       Tmp2 = DAG.getNode(ISD::XOR, dl, LHSLo.getValueType(), LHSHi, RHSHi);
5322       Tmp1 = DAG.getNode(ISD::OR, dl, Tmp1.getValueType(), Tmp1, Tmp2);
5323       Tmp2 = DAG.getConstant(0, Tmp1.getValueType());
5324       break;
5325     default:
5326       // If this is a comparison of the sign bit, just look at the top part.
5327       // X > -1,  x < 0
5328       if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(RHS))
5329         if ((cast<CondCodeSDNode>(CC)->get() == ISD::SETLT &&
5330              CST->isNullValue()) ||               // X < 0
5331             (cast<CondCodeSDNode>(CC)->get() == ISD::SETGT &&
5332              CST->isAllOnesValue())) {            // X > -1
5333           Tmp1 = LHSHi;
5334           Tmp2 = RHSHi;
5335           break;
5336         }
5337
5338       // FIXME: This generated code sucks.
5339       ISD::CondCode LowCC;
5340       switch (CCCode) {
5341       default: assert(0 && "Unknown integer setcc!");
5342       case ISD::SETLT:
5343       case ISD::SETULT: LowCC = ISD::SETULT; break;
5344       case ISD::SETGT:
5345       case ISD::SETUGT: LowCC = ISD::SETUGT; break;
5346       case ISD::SETLE:
5347       case ISD::SETULE: LowCC = ISD::SETULE; break;
5348       case ISD::SETGE:
5349       case ISD::SETUGE: LowCC = ISD::SETUGE; break;
5350       }
5351
5352       // Tmp1 = lo(op1) < lo(op2)   // Always unsigned comparison
5353       // Tmp2 = hi(op1) < hi(op2)   // Signedness depends on operands
5354       // dest = hi(op1) == hi(op2) ? Tmp1 : Tmp2;
5355
5356       // NOTE: on targets without efficient SELECT of bools, we can always use
5357       // this identity: (B1 ? B2 : B3) --> (B1 & B2)|(!B1&B3)
5358       TargetLowering::DAGCombinerInfo DagCombineInfo(DAG, false, true, NULL);
5359       Tmp1 = TLI.SimplifySetCC(TLI.getSetCCResultType(LHSLo.getValueType()),
5360                                LHSLo, RHSLo, LowCC, false, DagCombineInfo, dl);
5361       if (!Tmp1.getNode())
5362         Tmp1 = DAG.getSetCC(dl, TLI.getSetCCResultType(LHSLo.getValueType()),
5363                             LHSLo, RHSLo, LowCC);
5364       Tmp2 = TLI.SimplifySetCC(TLI.getSetCCResultType(LHSHi.getValueType()),
5365                                LHSHi, RHSHi, CCCode, false, DagCombineInfo, dl);
5366       if (!Tmp2.getNode())
5367         Tmp2 = DAG.getNode(ISD::SETCC, dl,
5368                            TLI.getSetCCResultType(LHSHi.getValueType()),
5369                            LHSHi, RHSHi, CC);
5370
5371       ConstantSDNode *Tmp1C = dyn_cast<ConstantSDNode>(Tmp1.getNode());
5372       ConstantSDNode *Tmp2C = dyn_cast<ConstantSDNode>(Tmp2.getNode());
5373       if ((Tmp1C && Tmp1C->isNullValue()) ||
5374           (Tmp2C && Tmp2C->isNullValue() &&
5375            (CCCode == ISD::SETLE || CCCode == ISD::SETGE ||
5376             CCCode == ISD::SETUGE || CCCode == ISD::SETULE)) ||
5377           (Tmp2C && Tmp2C->getAPIntValue() == 1 &&
5378            (CCCode == ISD::SETLT || CCCode == ISD::SETGT ||
5379             CCCode == ISD::SETUGT || CCCode == ISD::SETULT))) {
5380         // low part is known false, returns high part.
5381         // For LE / GE, if high part is known false, ignore the low part.
5382         // For LT / GT, if high part is known true, ignore the low part.
5383         Tmp1 = Tmp2;
5384         Tmp2 = SDValue();
5385       } else {
5386         Result = TLI.SimplifySetCC(TLI.getSetCCResultType(LHSHi.getValueType()),
5387                                    LHSHi, RHSHi, ISD::SETEQ, false,
5388                                    DagCombineInfo, dl);
5389         if (!Result.getNode())
5390           Result=DAG.getSetCC(dl, TLI.getSetCCResultType(LHSHi.getValueType()),
5391                               LHSHi, RHSHi, ISD::SETEQ);
5392         Result = LegalizeOp(DAG.getNode(ISD::SELECT, dl, Tmp1.getValueType(),
5393                                         Result, Tmp1, Tmp2));
5394         Tmp1 = Result;
5395         Tmp2 = SDValue();
5396       }
5397     }
5398   }
5399   }
5400   LHS = Tmp1;
5401   RHS = Tmp2;
5402 }
5403
5404 /// LegalizeSetCCCondCode - Legalize a SETCC with given LHS and RHS and
5405 /// condition code CC on the current target. This routine assumes LHS and rHS
5406 /// have already been legalized by LegalizeSetCCOperands. It expands SETCC with
5407 /// illegal condition code into AND / OR of multiple SETCC values.
5408 void SelectionDAGLegalize::LegalizeSetCCCondCode(MVT VT,
5409                                                  SDValue &LHS, SDValue &RHS,
5410                                                  SDValue &CC,
5411                                                  DebugLoc dl) {
5412   MVT OpVT = LHS.getValueType();
5413   ISD::CondCode CCCode = cast<CondCodeSDNode>(CC)->get();
5414   switch (TLI.getCondCodeAction(CCCode, OpVT)) {
5415   default: assert(0 && "Unknown condition code action!");
5416   case TargetLowering::Legal:
5417     // Nothing to do.
5418     break;
5419   case TargetLowering::Expand: {
5420     ISD::CondCode CC1 = ISD::SETCC_INVALID, CC2 = ISD::SETCC_INVALID;
5421     unsigned Opc = 0;
5422     switch (CCCode) {
5423     default: assert(0 && "Don't know how to expand this condition!"); abort();
5424     case ISD::SETOEQ: CC1 = ISD::SETEQ; CC2 = ISD::SETO;  Opc = ISD::AND; break;
5425     case ISD::SETOGT: CC1 = ISD::SETGT; CC2 = ISD::SETO;  Opc = ISD::AND; break;
5426     case ISD::SETOGE: CC1 = ISD::SETGE; CC2 = ISD::SETO;  Opc = ISD::AND; break;
5427     case ISD::SETOLT: CC1 = ISD::SETLT; CC2 = ISD::SETO;  Opc = ISD::AND; break;
5428     case ISD::SETOLE: CC1 = ISD::SETLE; CC2 = ISD::SETO;  Opc = ISD::AND; break;
5429     case ISD::SETONE: CC1 = ISD::SETNE; CC2 = ISD::SETO;  Opc = ISD::AND; break;
5430     case ISD::SETUEQ: CC1 = ISD::SETEQ; CC2 = ISD::SETUO; Opc = ISD::OR;  break;
5431     case ISD::SETUGT: CC1 = ISD::SETGT; CC2 = ISD::SETUO; Opc = ISD::OR;  break;
5432     case ISD::SETUGE: CC1 = ISD::SETGE; CC2 = ISD::SETUO; Opc = ISD::OR;  break;
5433     case ISD::SETULT: CC1 = ISD::SETLT; CC2 = ISD::SETUO; Opc = ISD::OR;  break;
5434     case ISD::SETULE: CC1 = ISD::SETLE; CC2 = ISD::SETUO; Opc = ISD::OR;  break;
5435     case ISD::SETUNE: CC1 = ISD::SETNE; CC2 = ISD::SETUO; Opc = ISD::OR;  break;
5436     // FIXME: Implement more expansions.
5437     }
5438
5439     SDValue SetCC1 = DAG.getSetCC(dl, VT, LHS, RHS, CC1);
5440     SDValue SetCC2 = DAG.getSetCC(dl, VT, LHS, RHS, CC2);
5441     LHS = DAG.getNode(Opc, dl, VT, SetCC1, SetCC2);
5442     RHS = SDValue();
5443     CC  = SDValue();
5444     break;
5445   }
5446   }
5447 }
5448
5449 /// EmitStackConvert - Emit a store/load combination to the stack.  This stores
5450 /// SrcOp to a stack slot of type SlotVT, truncating it if needed.  It then does
5451 /// a load from the stack slot to DestVT, extending it if needed.
5452 /// The resultant code need not be legal.
5453 SDValue SelectionDAGLegalize::EmitStackConvert(SDValue SrcOp,
5454                                                MVT SlotVT,
5455                                                MVT DestVT,
5456                                                DebugLoc dl) {
5457   // Create the stack frame object.
5458   unsigned SrcAlign =
5459     TLI.getTargetData()->getPrefTypeAlignment(SrcOp.getValueType().
5460                                               getTypeForMVT());
5461   SDValue FIPtr = DAG.CreateStackTemporary(SlotVT, SrcAlign);
5462
5463   FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(FIPtr);
5464   int SPFI = StackPtrFI->getIndex();
5465   const Value *SV = PseudoSourceValue::getFixedStack(SPFI);
5466
5467   unsigned SrcSize = SrcOp.getValueType().getSizeInBits();
5468   unsigned SlotSize = SlotVT.getSizeInBits();
5469   unsigned DestSize = DestVT.getSizeInBits();
5470   unsigned DestAlign =
5471     TLI.getTargetData()->getPrefTypeAlignment(DestVT.getTypeForMVT());
5472
5473   // Emit a store to the stack slot.  Use a truncstore if the input value is
5474   // later than DestVT.
5475   SDValue Store;
5476
5477   if (SrcSize > SlotSize)
5478     Store = DAG.getTruncStore(DAG.getEntryNode(), dl, SrcOp, FIPtr,
5479                               SV, 0, SlotVT, false, SrcAlign);
5480   else {
5481     assert(SrcSize == SlotSize && "Invalid store");
5482     Store = DAG.getStore(DAG.getEntryNode(), dl, SrcOp, FIPtr,
5483                          SV, 0, false, SrcAlign);
5484   }
5485
5486   // Result is a load from the stack slot.
5487   if (SlotSize == DestSize)
5488     return DAG.getLoad(DestVT, dl, Store, FIPtr, SV, 0, false, DestAlign);
5489
5490   assert(SlotSize < DestSize && "Unknown extension!");
5491   return DAG.getExtLoad(ISD::EXTLOAD, dl, DestVT, Store, FIPtr, SV, 0, SlotVT,
5492                         false, DestAlign);
5493 }
5494
5495 SDValue SelectionDAGLegalize::ExpandSCALAR_TO_VECTOR(SDNode *Node) {
5496   DebugLoc dl = Node->getDebugLoc();
5497   // Create a vector sized/aligned stack slot, store the value to element #0,
5498   // then load the whole vector back out.
5499   SDValue StackPtr = DAG.CreateStackTemporary(Node->getValueType(0));
5500
5501   FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(StackPtr);
5502   int SPFI = StackPtrFI->getIndex();
5503
5504   SDValue Ch = DAG.getTruncStore(DAG.getEntryNode(), dl, Node->getOperand(0),
5505                                  StackPtr,
5506                                  PseudoSourceValue::getFixedStack(SPFI), 0,
5507                                  Node->getValueType(0).getVectorElementType());
5508   return DAG.getLoad(Node->getValueType(0), dl, Ch, StackPtr,
5509                      PseudoSourceValue::getFixedStack(SPFI), 0);
5510 }
5511
5512
5513 /// ExpandBUILD_VECTOR - Expand a BUILD_VECTOR node on targets that don't
5514 /// support the operation, but do support the resultant vector type.
5515 SDValue SelectionDAGLegalize::ExpandBUILD_VECTOR(SDNode *Node) {
5516   unsigned NumElems = Node->getNumOperands();
5517   SDValue SplatValue = Node->getOperand(0);
5518   DebugLoc dl = Node->getDebugLoc();
5519   MVT VT = Node->getValueType(0);
5520   MVT OpVT = SplatValue.getValueType();
5521   MVT EltVT = VT.getVectorElementType();
5522
5523   // If the only non-undef value is the low element, turn this into a
5524   // SCALAR_TO_VECTOR node.  If this is { X, X, X, X }, determine X.
5525   bool isOnlyLowElement = true;
5526
5527   // FIXME: it would be far nicer to change this into map<SDValue,uint64_t>
5528   // and use a bitmask instead of a list of elements.
5529   // FIXME: this doesn't treat <0, u, 0, u> for example, as a splat.
5530   std::map<SDValue, std::vector<unsigned> > Values;
5531   Values[SplatValue].push_back(0);
5532   bool isConstant = true;
5533   if (!isa<ConstantFPSDNode>(SplatValue) && !isa<ConstantSDNode>(SplatValue) &&
5534       SplatValue.getOpcode() != ISD::UNDEF)
5535     isConstant = false;
5536
5537   for (unsigned i = 1; i < NumElems; ++i) {
5538     SDValue V = Node->getOperand(i);
5539     Values[V].push_back(i);
5540     if (V.getOpcode() != ISD::UNDEF)
5541       isOnlyLowElement = false;
5542     if (SplatValue != V)
5543       SplatValue = SDValue(0, 0);
5544
5545     // If this isn't a constant element or an undef, we can't use a constant
5546     // pool load.
5547     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V) &&
5548         V.getOpcode() != ISD::UNDEF)
5549       isConstant = false;
5550   }
5551
5552   if (isOnlyLowElement) {
5553     // If the low element is an undef too, then this whole things is an undef.
5554     if (Node->getOperand(0).getOpcode() == ISD::UNDEF)
5555       return DAG.getUNDEF(VT);
5556     // Otherwise, turn this into a scalar_to_vector node.
5557     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Node->getOperand(0));
5558   }
5559
5560   // If all elements are constants, create a load from the constant pool.
5561   if (isConstant) {
5562     std::vector<Constant*> CV;
5563     for (unsigned i = 0, e = NumElems; i != e; ++i) {
5564       if (ConstantFPSDNode *V =
5565           dyn_cast<ConstantFPSDNode>(Node->getOperand(i))) {
5566         CV.push_back(const_cast<ConstantFP *>(V->getConstantFPValue()));
5567       } else if (ConstantSDNode *V =
5568                  dyn_cast<ConstantSDNode>(Node->getOperand(i))) {
5569         CV.push_back(const_cast<ConstantInt *>(V->getConstantIntValue()));
5570       } else {
5571         assert(Node->getOperand(i).getOpcode() == ISD::UNDEF);
5572         const Type *OpNTy = OpVT.getTypeForMVT();
5573         CV.push_back(UndefValue::get(OpNTy));
5574       }
5575     }
5576     Constant *CP = ConstantVector::get(CV);
5577     SDValue CPIdx = DAG.getConstantPool(CP, TLI.getPointerTy());
5578     unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
5579     return DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5580                        PseudoSourceValue::getConstantPool(), 0,
5581                        false, Alignment);
5582   }
5583
5584   if (SplatValue.getNode()) {   // Splat of one value?
5585     // Build the shuffle constant vector: <0, 0, 0, 0>
5586     SmallVector<int, 8> ZeroVec(NumElems, 0);
5587
5588     // If the target supports VECTOR_SHUFFLE and this shuffle mask, use it.
5589     if (TLI.isShuffleMaskLegal(ZeroVec, Node->getValueType(0))) {
5590       // Get the splatted value into the low element of a vector register.
5591       SDValue LowValVec =
5592         DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, SplatValue);
5593
5594       // Return shuffle(LowValVec, undef, <0,0,0,0>)
5595       return DAG.getVectorShuffle(VT, dl, LowValVec, DAG.getUNDEF(VT),
5596                                   &ZeroVec[0]);
5597     }
5598   }
5599
5600   // If there are only two unique elements, we may be able to turn this into a
5601   // vector shuffle.
5602   if (Values.size() == 2) {
5603     // Get the two values in deterministic order.
5604     SDValue Val1 = Node->getOperand(1);
5605     SDValue Val2;
5606     std::map<SDValue, std::vector<unsigned> >::iterator MI = Values.begin();
5607     if (MI->first != Val1)
5608       Val2 = MI->first;
5609     else
5610       Val2 = (++MI)->first;
5611
5612     // If Val1 is an undef, make sure it ends up as Val2, to ensure that our
5613     // vector shuffle has the undef vector on the RHS.
5614     if (Val1.getOpcode() == ISD::UNDEF)
5615       std::swap(Val1, Val2);
5616
5617     // Build the shuffle constant vector: e.g. <0, 4, 0, 4>
5618     SmallVector<int, 8> ShuffleMask(NumElems, -1);
5619
5620     // Set elements of the shuffle mask for Val1.
5621     std::vector<unsigned> &Val1Elts = Values[Val1];
5622     for (unsigned i = 0, e = Val1Elts.size(); i != e; ++i)
5623       ShuffleMask[Val1Elts[i]] = 0;
5624
5625     // Set elements of the shuffle mask for Val2.
5626     std::vector<unsigned> &Val2Elts = Values[Val2];
5627     for (unsigned i = 0, e = Val2Elts.size(); i != e; ++i)
5628       if (Val2.getOpcode() != ISD::UNDEF)
5629         ShuffleMask[Val2Elts[i]] = NumElems;
5630
5631     // If the target supports SCALAR_TO_VECTOR and this shuffle mask, use it.
5632     if (TLI.isOperationLegalOrCustom(ISD::SCALAR_TO_VECTOR, VT) &&
5633         TLI.isShuffleMaskLegal(ShuffleMask, VT)) {
5634       Val1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Val1);
5635       Val2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Val2);
5636       return DAG.getVectorShuffle(VT, dl, Val1, Val2, &ShuffleMask[0]);
5637     }
5638   }
5639
5640   // Otherwise, we can't handle this case efficiently.  Allocate a sufficiently
5641   // aligned object on the stack, store each element into it, then load
5642   // the result as a vector.
5643   // Create the stack frame object.
5644   SDValue FIPtr = DAG.CreateStackTemporary(VT);
5645   int FI = cast<FrameIndexSDNode>(FIPtr.getNode())->getIndex();
5646   const Value *SV = PseudoSourceValue::getFixedStack(FI);
5647
5648   // Emit a store of each element to the stack slot.
5649   SmallVector<SDValue, 8> Stores;
5650   unsigned TypeByteSize = OpVT.getSizeInBits() / 8;
5651   // Store (in the right endianness) the elements to memory.
5652   for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
5653     // Ignore undef elements.
5654     if (Node->getOperand(i).getOpcode() == ISD::UNDEF) continue;
5655
5656     unsigned Offset = TypeByteSize*i;
5657
5658     SDValue Idx = DAG.getConstant(Offset, FIPtr.getValueType());
5659     Idx = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, Idx);
5660
5661     Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, Node->getOperand(i),
5662                                   Idx, SV, Offset));
5663   }
5664
5665   SDValue StoreChain;
5666   if (!Stores.empty())    // Not all undef elements?
5667     StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
5668                              &Stores[0], Stores.size());
5669   else
5670     StoreChain = DAG.getEntryNode();
5671
5672   // Result is a load from the stack slot.
5673   return DAG.getLoad(VT, dl, StoreChain, FIPtr, SV, 0);
5674 }
5675
5676 void SelectionDAGLegalize::ExpandShiftParts(unsigned NodeOp,
5677                                             SDValue Op, SDValue Amt,
5678                                             SDValue &Lo, SDValue &Hi,
5679                                             DebugLoc dl) {
5680   // Expand the subcomponents.
5681   SDValue LHSL, LHSH;
5682   ExpandOp(Op, LHSL, LHSH);
5683
5684   SDValue Ops[] = { LHSL, LHSH, Amt };
5685   MVT VT = LHSL.getValueType();
5686   Lo = DAG.getNode(NodeOp, dl, DAG.getVTList(VT, VT), Ops, 3);
5687   Hi = Lo.getValue(1);
5688 }
5689
5690
5691 /// ExpandShift - Try to find a clever way to expand this shift operation out to
5692 /// smaller elements.  If we can't find a way that is more efficient than a
5693 /// libcall on this target, return false.  Otherwise, return true with the
5694 /// low-parts expanded into Lo and Hi.
5695 bool SelectionDAGLegalize::ExpandShift(unsigned Opc, SDValue Op, SDValue Amt,
5696                                        SDValue &Lo, SDValue &Hi,
5697                                        DebugLoc dl) {
5698   assert((Opc == ISD::SHL || Opc == ISD::SRA || Opc == ISD::SRL) &&
5699          "This is not a shift!");
5700
5701   MVT NVT = TLI.getTypeToTransformTo(Op.getValueType());
5702   SDValue ShAmt = LegalizeOp(Amt);
5703   MVT ShTy = ShAmt.getValueType();
5704   unsigned ShBits = ShTy.getSizeInBits();
5705   unsigned VTBits = Op.getValueType().getSizeInBits();
5706   unsigned NVTBits = NVT.getSizeInBits();
5707
5708   // Handle the case when Amt is an immediate.
5709   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Amt.getNode())) {
5710     unsigned Cst = CN->getZExtValue();
5711     // Expand the incoming operand to be shifted, so that we have its parts
5712     SDValue InL, InH;
5713     ExpandOp(Op, InL, InH);
5714     switch(Opc) {
5715     case ISD::SHL:
5716       if (Cst > VTBits) {
5717         Lo = DAG.getConstant(0, NVT);
5718         Hi = DAG.getConstant(0, NVT);
5719       } else if (Cst > NVTBits) {
5720         Lo = DAG.getConstant(0, NVT);
5721         Hi = DAG.getNode(ISD::SHL, dl,
5722                          NVT, InL, DAG.getConstant(Cst-NVTBits, ShTy));
5723       } else if (Cst == NVTBits) {
5724         Lo = DAG.getConstant(0, NVT);
5725         Hi = InL;
5726       } else {
5727         Lo = DAG.getNode(ISD::SHL, dl, NVT, InL, DAG.getConstant(Cst, ShTy));
5728         Hi = DAG.getNode(ISD::OR, dl, NVT,
5729            DAG.getNode(ISD::SHL, dl, NVT, InH, DAG.getConstant(Cst, ShTy)),
5730            DAG.getNode(ISD::SRL, dl, NVT, InL,
5731                        DAG.getConstant(NVTBits-Cst, ShTy)));
5732       }
5733       return true;
5734     case ISD::SRL:
5735       if (Cst > VTBits) {
5736         Lo = DAG.getConstant(0, NVT);
5737         Hi = DAG.getConstant(0, NVT);
5738       } else if (Cst > NVTBits) {
5739         Lo = DAG.getNode(ISD::SRL, dl, NVT,
5740                          InH, DAG.getConstant(Cst-NVTBits, ShTy));
5741         Hi = DAG.getConstant(0, NVT);
5742       } else if (Cst == NVTBits) {
5743         Lo = InH;
5744         Hi = DAG.getConstant(0, NVT);
5745       } else {
5746         Lo = DAG.getNode(ISD::OR, dl, NVT,
5747            DAG.getNode(ISD::SRL, dl, NVT, InL, DAG.getConstant(Cst, ShTy)),
5748            DAG.getNode(ISD::SHL, dl, NVT, InH,
5749                        DAG.getConstant(NVTBits-Cst, ShTy)));
5750         Hi = DAG.getNode(ISD::SRL, dl, NVT, InH, DAG.getConstant(Cst, ShTy));
5751       }
5752       return true;
5753     case ISD::SRA:
5754       if (Cst > VTBits) {
5755         Hi = Lo = DAG.getNode(ISD::SRA, dl, NVT, InH,
5756                               DAG.getConstant(NVTBits-1, ShTy));
5757       } else if (Cst > NVTBits) {
5758         Lo = DAG.getNode(ISD::SRA, dl, NVT, InH,
5759                            DAG.getConstant(Cst-NVTBits, ShTy));
5760         Hi = DAG.getNode(ISD::SRA, dl, NVT, InH,
5761                               DAG.getConstant(NVTBits-1, ShTy));
5762       } else if (Cst == NVTBits) {
5763         Lo = InH;
5764         Hi = DAG.getNode(ISD::SRA, dl, NVT, InH,
5765                               DAG.getConstant(NVTBits-1, ShTy));
5766       } else {
5767         Lo = DAG.getNode(ISD::OR, dl, NVT,
5768            DAG.getNode(ISD::SRL, dl, NVT, InL, DAG.getConstant(Cst, ShTy)),
5769            DAG.getNode(ISD::SHL, dl,
5770                        NVT, InH, DAG.getConstant(NVTBits-Cst, ShTy)));
5771         Hi = DAG.getNode(ISD::SRA, dl, NVT, InH, DAG.getConstant(Cst, ShTy));
5772       }
5773       return true;
5774     }
5775   }
5776
5777   // Okay, the shift amount isn't constant.  However, if we can tell that it is
5778   // >= 32 or < 32, we can still simplify it, without knowing the actual value.
5779   APInt Mask = APInt::getHighBitsSet(ShBits, ShBits - Log2_32(NVTBits));
5780   APInt KnownZero, KnownOne;
5781   DAG.ComputeMaskedBits(Amt, Mask, KnownZero, KnownOne);
5782
5783   // If we know that if any of the high bits of the shift amount are one, then
5784   // we can do this as a couple of simple shifts.
5785   if (KnownOne.intersects(Mask)) {
5786     // Mask out the high bit, which we know is set.
5787     Amt = DAG.getNode(ISD::AND, dl, Amt.getValueType(), Amt,
5788                       DAG.getConstant(~Mask, Amt.getValueType()));
5789
5790     // Expand the incoming operand to be shifted, so that we have its parts
5791     SDValue InL, InH;
5792     ExpandOp(Op, InL, InH);
5793     switch(Opc) {
5794     case ISD::SHL:
5795       Lo = DAG.getConstant(0, NVT);              // Low part is zero.
5796       Hi = DAG.getNode(ISD::SHL, dl, NVT, InL, Amt); // High part from Lo part.
5797       return true;
5798     case ISD::SRL:
5799       Hi = DAG.getConstant(0, NVT);              // Hi part is zero.
5800       Lo = DAG.getNode(ISD::SRL, dl, NVT, InH, Amt); // Lo part from Hi part.
5801       return true;
5802     case ISD::SRA:
5803       Hi = DAG.getNode(ISD::SRA, dl, NVT, InH,       // Sign extend high part.
5804                        DAG.getConstant(NVTBits-1, Amt.getValueType()));
5805       Lo = DAG.getNode(ISD::SRA, dl, NVT, InH, Amt); // Lo part from Hi part.
5806       return true;
5807     }
5808   }
5809
5810   // If we know that the high bits of the shift amount are all zero, then we can
5811   // do this as a couple of simple shifts.
5812   if ((KnownZero & Mask) == Mask) {
5813     // Compute 32-amt.
5814     SDValue Amt2 = DAG.getNode(ISD::SUB, dl, Amt.getValueType(),
5815                                  DAG.getConstant(NVTBits, Amt.getValueType()),
5816                                  Amt);
5817
5818     // Expand the incoming operand to be shifted, so that we have its parts
5819     SDValue InL, InH;
5820     ExpandOp(Op, InL, InH);
5821     switch(Opc) {
5822     case ISD::SHL:
5823       Lo = DAG.getNode(ISD::SHL, dl, NVT, InL, Amt);
5824       Hi = DAG.getNode(ISD::OR, dl, NVT,
5825                        DAG.getNode(ISD::SHL, dl, NVT, InH, Amt),
5826                        DAG.getNode(ISD::SRL, dl, NVT, InL, Amt2));
5827       return true;
5828     case ISD::SRL:
5829       Hi = DAG.getNode(ISD::SRL, dl, NVT, InH, Amt);
5830       Lo = DAG.getNode(ISD::OR, dl, NVT,
5831                        DAG.getNode(ISD::SRL, dl, NVT, InL, Amt),
5832                        DAG.getNode(ISD::SHL, dl, NVT, InH, Amt2));
5833       return true;
5834     case ISD::SRA:
5835       Hi = DAG.getNode(ISD::SRA, dl, NVT, InH, Amt);
5836       Lo = DAG.getNode(ISD::OR, dl, NVT,
5837                        DAG.getNode(ISD::SRL, dl, NVT, InL, Amt),
5838                        DAG.getNode(ISD::SHL, dl, NVT, InH, Amt2));
5839       return true;
5840     }
5841   }
5842
5843   return false;
5844 }
5845
5846
5847 // ExpandLibCall - Expand a node into a call to a libcall.  If the result value
5848 // does not fit into a register, return the lo part and set the hi part to the
5849 // by-reg argument.  If it does fit into a single register, return the result
5850 // and leave the Hi part unset.
5851 SDValue SelectionDAGLegalize::ExpandLibCall(RTLIB::Libcall LC, SDNode *Node,
5852                                             bool isSigned, SDValue &Hi) {
5853   assert(!IsLegalizingCall && "Cannot overlap legalization of calls!");
5854   // The input chain to this libcall is the entry node of the function.
5855   // Legalizing the call will automatically add the previous call to the
5856   // dependence.
5857   SDValue InChain = DAG.getEntryNode();
5858
5859   TargetLowering::ArgListTy Args;
5860   TargetLowering::ArgListEntry Entry;
5861   for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
5862     MVT ArgVT = Node->getOperand(i).getValueType();
5863     const Type *ArgTy = ArgVT.getTypeForMVT();
5864     Entry.Node = Node->getOperand(i); Entry.Ty = ArgTy;
5865     Entry.isSExt = isSigned;
5866     Entry.isZExt = !isSigned;
5867     Args.push_back(Entry);
5868   }
5869   SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
5870                                          TLI.getPointerTy());
5871
5872   // Splice the libcall in wherever FindInputOutputChains tells us to.
5873   const Type *RetTy = Node->getValueType(0).getTypeForMVT();
5874   std::pair<SDValue, SDValue> CallInfo =
5875     TLI.LowerCallTo(InChain, RetTy, isSigned, !isSigned, false, false,
5876                     CallingConv::C, false, Callee, Args, DAG,
5877                     Node->getDebugLoc());
5878
5879   // Legalize the call sequence, starting with the chain.  This will advance
5880   // the LastCALLSEQ_END to the legalized version of the CALLSEQ_END node that
5881   // was added by LowerCallTo (guaranteeing proper serialization of calls).
5882   LegalizeOp(CallInfo.second);
5883   SDValue Result;
5884   switch (getTypeAction(CallInfo.first.getValueType())) {
5885   default: assert(0 && "Unknown thing");
5886   case Legal:
5887     Result = CallInfo.first;
5888     break;
5889   case Expand:
5890     ExpandOp(CallInfo.first, Result, Hi);
5891     break;
5892   }
5893   return Result;
5894 }
5895
5896 /// LegalizeINT_TO_FP - Legalize a [US]INT_TO_FP operation.
5897 ///
5898 SDValue SelectionDAGLegalize::
5899 LegalizeINT_TO_FP(SDValue Result, bool isSigned, MVT DestTy, SDValue Op,
5900                   DebugLoc dl) {
5901   bool isCustom = false;
5902   SDValue Tmp1;
5903   switch (getTypeAction(Op.getValueType())) {
5904   case Legal:
5905     switch (TLI.getOperationAction(isSigned ? ISD::SINT_TO_FP : ISD::UINT_TO_FP,
5906                                    Op.getValueType())) {
5907     default: assert(0 && "Unknown operation action!");
5908     case TargetLowering::Custom:
5909       isCustom = true;
5910       // FALLTHROUGH
5911     case TargetLowering::Legal:
5912       Tmp1 = LegalizeOp(Op);
5913       if (Result.getNode())
5914         Result = DAG.UpdateNodeOperands(Result, Tmp1);
5915       else
5916         Result = DAG.getNode(isSigned ? ISD::SINT_TO_FP : ISD::UINT_TO_FP, dl,
5917                              DestTy, Tmp1);
5918       if (isCustom) {
5919         Tmp1 = TLI.LowerOperation(Result, DAG);
5920         if (Tmp1.getNode()) Result = Tmp1;
5921       }
5922       break;
5923     case TargetLowering::Expand:
5924       Result = ExpandLegalINT_TO_FP(isSigned, LegalizeOp(Op), DestTy, dl);
5925       break;
5926     case TargetLowering::Promote:
5927       Result = PromoteLegalINT_TO_FP(LegalizeOp(Op), DestTy, isSigned, dl);
5928       break;
5929     }
5930     break;
5931   case Expand:
5932     Result = ExpandIntToFP(isSigned, DestTy, Op, dl) ;
5933     break;
5934   case Promote:
5935     Tmp1 = PromoteOp(Op);
5936     if (isSigned) {
5937       Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, Tmp1.getValueType(),
5938                          Tmp1, DAG.getValueType(Op.getValueType()));
5939     } else {
5940       Tmp1 = DAG.getZeroExtendInReg(Tmp1, dl, Op.getValueType());
5941     }
5942     if (Result.getNode())
5943       Result = DAG.UpdateNodeOperands(Result, Tmp1);
5944     else
5945       Result = DAG.getNode(isSigned ? ISD::SINT_TO_FP : ISD::UINT_TO_FP, dl,
5946                            DestTy, Tmp1);
5947     Result = LegalizeOp(Result);  // The 'op' is not necessarily legal!
5948     break;
5949   }
5950   return Result;
5951 }
5952
5953 /// ExpandIntToFP - Expand a [US]INT_TO_FP operation.
5954 ///
5955 SDValue SelectionDAGLegalize::
5956 ExpandIntToFP(bool isSigned, MVT DestTy, SDValue Source, DebugLoc dl) {
5957   MVT SourceVT = Source.getValueType();
5958   bool ExpandSource = getTypeAction(SourceVT) == Expand;
5959
5960   // Expand unsupported int-to-fp vector casts by unrolling them.
5961   if (DestTy.isVector()) {
5962     if (!ExpandSource)
5963       return LegalizeOp(UnrollVectorOp(Source));
5964     MVT DestEltTy = DestTy.getVectorElementType();
5965     if (DestTy.getVectorNumElements() == 1) {
5966       SDValue Scalar = ScalarizeVectorOp(Source);
5967       SDValue Result = LegalizeINT_TO_FP(SDValue(), isSigned,
5968                                          DestEltTy, Scalar, dl);
5969       return DAG.getNode(ISD::BUILD_VECTOR, dl, DestTy, Result);
5970     }
5971     SDValue Lo, Hi;
5972     SplitVectorOp(Source, Lo, Hi);
5973     MVT SplitDestTy = MVT::getVectorVT(DestEltTy,
5974                                        DestTy.getVectorNumElements() / 2);
5975     SDValue LoResult = LegalizeINT_TO_FP(SDValue(), isSigned, SplitDestTy,
5976                                          Lo, dl);
5977     SDValue HiResult = LegalizeINT_TO_FP(SDValue(), isSigned, SplitDestTy,
5978                                          Hi, dl);
5979     return LegalizeOp(DAG.getNode(ISD::CONCAT_VECTORS, dl, DestTy, LoResult,
5980                                   HiResult));
5981   }
5982
5983   // Special case for i32 source to take advantage of UINTTOFP_I32_F32, etc.
5984   if (!isSigned && SourceVT != MVT::i32) {
5985     // The integer value loaded will be incorrectly if the 'sign bit' of the
5986     // incoming integer is set.  To handle this, we dynamically test to see if
5987     // it is set, and, if so, add a fudge factor.
5988     SDValue Hi;
5989     if (ExpandSource) {
5990       SDValue Lo;
5991       ExpandOp(Source, Lo, Hi);
5992       Source = DAG.getNode(ISD::BUILD_PAIR, dl, SourceVT, Lo, Hi);
5993     } else {
5994       // The comparison for the sign bit will use the entire operand.
5995       Hi = Source;
5996     }
5997
5998     // Check to see if the target has a custom way to lower this.  If so, use
5999     // it.  (Note we've already expanded the operand in this case.)
6000     switch (TLI.getOperationAction(ISD::UINT_TO_FP, SourceVT)) {
6001     default: assert(0 && "This action not implemented for this operation!");
6002     case TargetLowering::Legal:
6003     case TargetLowering::Expand:
6004       break;   // This case is handled below.
6005     case TargetLowering::Custom: {
6006       SDValue NV = TLI.LowerOperation(DAG.getNode(ISD::UINT_TO_FP, dl, DestTy,
6007                                                   Source), DAG);
6008       if (NV.getNode())
6009         return LegalizeOp(NV);
6010       break;   // The target decided this was legal after all
6011     }
6012     }
6013
6014     // If this is unsigned, and not supported, first perform the conversion to
6015     // signed, then adjust the result if the sign bit is set.
6016     SDValue SignedConv = ExpandIntToFP(true, DestTy, Source, dl);
6017
6018     SDValue SignSet = DAG.getSetCC(dl,
6019                                    TLI.getSetCCResultType(Hi.getValueType()),
6020                                    Hi, DAG.getConstant(0, Hi.getValueType()),
6021                                    ISD::SETLT);
6022     SDValue Zero = DAG.getIntPtrConstant(0), Four = DAG.getIntPtrConstant(4);
6023     SDValue CstOffset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(),
6024                                       SignSet, Four, Zero);
6025     uint64_t FF = 0x5f800000ULL;
6026     if (TLI.isLittleEndian()) FF <<= 32;
6027     Constant *FudgeFactor = ConstantInt::get(Type::Int64Ty, FF);
6028
6029     SDValue CPIdx = DAG.getConstantPool(FudgeFactor, TLI.getPointerTy());
6030     unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
6031     CPIdx = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(), CPIdx, CstOffset);
6032     Alignment = std::min(Alignment, 4u);
6033     SDValue FudgeInReg;
6034     if (DestTy == MVT::f32)
6035       FudgeInReg = DAG.getLoad(MVT::f32, dl, DAG.getEntryNode(), CPIdx,
6036                                PseudoSourceValue::getConstantPool(), 0,
6037                                false, Alignment);
6038     else if (DestTy.bitsGT(MVT::f32))
6039       // FIXME: Avoid the extend by construction the right constantpool?
6040       FudgeInReg = DAG.getExtLoad(ISD::EXTLOAD, dl, DestTy, DAG.getEntryNode(),
6041                                   CPIdx,
6042                                   PseudoSourceValue::getConstantPool(), 0,
6043                                   MVT::f32, false, Alignment);
6044     else
6045       assert(0 && "Unexpected conversion");
6046
6047     MVT SCVT = SignedConv.getValueType();
6048     if (SCVT != DestTy) {
6049       // Destination type needs to be expanded as well. The FADD now we are
6050       // constructing will be expanded into a libcall.
6051       if (SCVT.getSizeInBits() != DestTy.getSizeInBits()) {
6052         assert(SCVT.getSizeInBits() * 2 == DestTy.getSizeInBits());
6053         SignedConv = DAG.getNode(ISD::BUILD_PAIR, dl, DestTy,
6054                                  SignedConv, SignedConv.getValue(1));
6055       }
6056       SignedConv = DAG.getNode(ISD::BIT_CONVERT, dl, DestTy, SignedConv);
6057     }
6058     return DAG.getNode(ISD::FADD, dl, DestTy, SignedConv, FudgeInReg);
6059   }
6060
6061   // Check to see if the target has a custom way to lower this.  If so, use it.
6062   switch (TLI.getOperationAction(ISD::SINT_TO_FP, SourceVT)) {
6063   default: assert(0 && "This action not implemented for this operation!");
6064   case TargetLowering::Legal:
6065   case TargetLowering::Expand:
6066     break;   // This case is handled below.
6067   case TargetLowering::Custom: {
6068     SDValue NV = TLI.LowerOperation(DAG.getNode(ISD::SINT_TO_FP, dl, DestTy,
6069                                                 Source), DAG);
6070     if (NV.getNode())
6071       return LegalizeOp(NV);
6072     break;   // The target decided this was legal after all
6073   }
6074   }
6075
6076   // Expand the source, then glue it back together for the call.  We must expand
6077   // the source in case it is shared (this pass of legalize must traverse it).
6078   if (ExpandSource) {
6079     SDValue SrcLo, SrcHi;
6080     ExpandOp(Source, SrcLo, SrcHi);
6081     Source = DAG.getNode(ISD::BUILD_PAIR, dl, SourceVT, SrcLo, SrcHi);
6082   }
6083
6084   RTLIB::Libcall LC = isSigned ?
6085     RTLIB::getSINTTOFP(SourceVT, DestTy) :
6086     RTLIB::getUINTTOFP(SourceVT, DestTy);
6087   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unknown int value type");
6088
6089   Source = DAG.getNode(ISD::SINT_TO_FP, dl, DestTy, Source);
6090   SDValue HiPart;
6091   SDValue Result = ExpandLibCall(LC, Source.getNode(), isSigned, HiPart);
6092   if (Result.getValueType() != DestTy && HiPart.getNode())
6093     Result = DAG.getNode(ISD::BUILD_PAIR, dl, DestTy, Result, HiPart);
6094   return Result;
6095 }
6096
6097 /// ExpandLegalINT_TO_FP - This function is responsible for legalizing a
6098 /// INT_TO_FP operation of the specified operand when the target requests that
6099 /// we expand it.  At this point, we know that the result and operand types are
6100 /// legal for the target.
6101 SDValue SelectionDAGLegalize::ExpandLegalINT_TO_FP(bool isSigned,
6102                                                    SDValue Op0,
6103                                                    MVT DestVT,
6104                                                    DebugLoc dl) {
6105   if (Op0.getValueType() == MVT::i32) {
6106     // simple 32-bit [signed|unsigned] integer to float/double expansion
6107
6108     // Get the stack frame index of a 8 byte buffer.
6109     SDValue StackSlot = DAG.CreateStackTemporary(MVT::f64);
6110
6111     // word offset constant for Hi/Lo address computation
6112     SDValue WordOff = DAG.getConstant(sizeof(int), TLI.getPointerTy());
6113     // set up Hi and Lo (into buffer) address based on endian
6114     SDValue Hi = StackSlot;
6115     SDValue Lo = DAG.getNode(ISD::ADD, dl,
6116                              TLI.getPointerTy(), StackSlot, WordOff);
6117     if (TLI.isLittleEndian())
6118       std::swap(Hi, Lo);
6119
6120     // if signed map to unsigned space
6121     SDValue Op0Mapped;
6122     if (isSigned) {
6123       // constant used to invert sign bit (signed to unsigned mapping)
6124       SDValue SignBit = DAG.getConstant(0x80000000u, MVT::i32);
6125       Op0Mapped = DAG.getNode(ISD::XOR, dl, MVT::i32, Op0, SignBit);
6126     } else {
6127       Op0Mapped = Op0;
6128     }
6129     // store the lo of the constructed double - based on integer input
6130     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl,
6131                                   Op0Mapped, Lo, NULL, 0);
6132     // initial hi portion of constructed double
6133     SDValue InitialHi = DAG.getConstant(0x43300000u, MVT::i32);
6134     // store the hi of the constructed double - biased exponent
6135     SDValue Store2=DAG.getStore(Store1, dl, InitialHi, Hi, NULL, 0);
6136     // load the constructed double
6137     SDValue Load = DAG.getLoad(MVT::f64, dl, Store2, StackSlot, NULL, 0);
6138     // FP constant to bias correct the final result
6139     SDValue Bias = DAG.getConstantFP(isSigned ?
6140                                      BitsToDouble(0x4330000080000000ULL) :
6141                                      BitsToDouble(0x4330000000000000ULL),
6142                                      MVT::f64);
6143     // subtract the bias
6144     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Load, Bias);
6145     // final result
6146     SDValue Result;
6147     // handle final rounding
6148     if (DestVT == MVT::f64) {
6149       // do nothing
6150       Result = Sub;
6151     } else if (DestVT.bitsLT(MVT::f64)) {
6152       Result = DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
6153                            DAG.getIntPtrConstant(0));
6154     } else if (DestVT.bitsGT(MVT::f64)) {
6155       Result = DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
6156     }
6157     return Result;
6158   }
6159   assert(!isSigned && "Legalize cannot Expand SINT_TO_FP for i64 yet");
6160   SDValue Tmp1 = DAG.getNode(ISD::SINT_TO_FP, dl, DestVT, Op0);
6161
6162   SDValue SignSet = DAG.getSetCC(dl, TLI.getSetCCResultType(Op0.getValueType()),
6163                                  Op0, DAG.getConstant(0, Op0.getValueType()),
6164                                  ISD::SETLT);
6165   SDValue Zero = DAG.getIntPtrConstant(0), Four = DAG.getIntPtrConstant(4);
6166   SDValue CstOffset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(),
6167                                     SignSet, Four, Zero);
6168
6169   // If the sign bit of the integer is set, the large number will be treated
6170   // as a negative number.  To counteract this, the dynamic code adds an
6171   // offset depending on the data type.
6172   uint64_t FF;
6173   switch (Op0.getValueType().getSimpleVT()) {
6174   default: assert(0 && "Unsupported integer type!");
6175   case MVT::i8 : FF = 0x43800000ULL; break;  // 2^8  (as a float)
6176   case MVT::i16: FF = 0x47800000ULL; break;  // 2^16 (as a float)
6177   case MVT::i32: FF = 0x4F800000ULL; break;  // 2^32 (as a float)
6178   case MVT::i64: FF = 0x5F800000ULL; break;  // 2^64 (as a float)
6179   }
6180   if (TLI.isLittleEndian()) FF <<= 32;
6181   Constant *FudgeFactor = ConstantInt::get(Type::Int64Ty, FF);
6182
6183   SDValue CPIdx = DAG.getConstantPool(FudgeFactor, TLI.getPointerTy());
6184   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
6185   CPIdx = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(), CPIdx, CstOffset);
6186   Alignment = std::min(Alignment, 4u);
6187   SDValue FudgeInReg;
6188   if (DestVT == MVT::f32)
6189     FudgeInReg = DAG.getLoad(MVT::f32, dl, DAG.getEntryNode(), CPIdx,
6190                              PseudoSourceValue::getConstantPool(), 0,
6191                              false, Alignment);
6192   else {
6193     FudgeInReg =
6194       LegalizeOp(DAG.getExtLoad(ISD::EXTLOAD, dl, DestVT,
6195                                 DAG.getEntryNode(), CPIdx,
6196                                 PseudoSourceValue::getConstantPool(), 0,
6197                                 MVT::f32, false, Alignment));
6198   }
6199
6200   return DAG.getNode(ISD::FADD, dl, DestVT, Tmp1, FudgeInReg);
6201 }
6202
6203 /// PromoteLegalINT_TO_FP - This function is responsible for legalizing a
6204 /// *INT_TO_FP operation of the specified operand when the target requests that
6205 /// we promote it.  At this point, we know that the result and operand types are
6206 /// legal for the target, and that there is a legal UINT_TO_FP or SINT_TO_FP
6207 /// operation that takes a larger input.
6208 SDValue SelectionDAGLegalize::PromoteLegalINT_TO_FP(SDValue LegalOp,
6209                                                     MVT DestVT,
6210                                                     bool isSigned,
6211                                                     DebugLoc dl) {
6212   // First step, figure out the appropriate *INT_TO_FP operation to use.
6213   MVT NewInTy = LegalOp.getValueType();
6214
6215   unsigned OpToUse = 0;
6216
6217   // Scan for the appropriate larger type to use.
6218   while (1) {
6219     NewInTy = (MVT::SimpleValueType)(NewInTy.getSimpleVT()+1);
6220     assert(NewInTy.isInteger() && "Ran out of possibilities!");
6221
6222     // If the target supports SINT_TO_FP of this type, use it.
6223     switch (TLI.getOperationAction(ISD::SINT_TO_FP, NewInTy)) {
6224       default: break;
6225       case TargetLowering::Legal:
6226         if (!TLI.isTypeLegal(NewInTy))
6227           break;  // Can't use this datatype.
6228         // FALL THROUGH.
6229       case TargetLowering::Custom:
6230         OpToUse = ISD::SINT_TO_FP;
6231         break;
6232     }
6233     if (OpToUse) break;
6234     if (isSigned) continue;
6235
6236     // If the target supports UINT_TO_FP of this type, use it.
6237     switch (TLI.getOperationAction(ISD::UINT_TO_FP, NewInTy)) {
6238       default: break;
6239       case TargetLowering::Legal:
6240         if (!TLI.isTypeLegal(NewInTy))
6241           break;  // Can't use this datatype.
6242         // FALL THROUGH.
6243       case TargetLowering::Custom:
6244         OpToUse = ISD::UINT_TO_FP;
6245         break;
6246     }
6247     if (OpToUse) break;
6248
6249     // Otherwise, try a larger type.
6250   }
6251
6252   // Okay, we found the operation and type to use.  Zero extend our input to the
6253   // desired type then run the operation on it.
6254   return DAG.getNode(OpToUse, dl, DestVT,
6255                      DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
6256                                  dl, NewInTy, LegalOp));
6257 }
6258
6259 /// PromoteLegalFP_TO_INT - This function is responsible for legalizing a
6260 /// FP_TO_*INT operation of the specified operand when the target requests that
6261 /// we promote it.  At this point, we know that the result and operand types are
6262 /// legal for the target, and that there is a legal FP_TO_UINT or FP_TO_SINT
6263 /// operation that returns a larger result.
6264 SDValue SelectionDAGLegalize::PromoteLegalFP_TO_INT(SDValue LegalOp,
6265                                                     MVT DestVT,
6266                                                     bool isSigned,
6267                                                     DebugLoc dl) {
6268   // First step, figure out the appropriate FP_TO*INT operation to use.
6269   MVT NewOutTy = DestVT;
6270
6271   unsigned OpToUse = 0;
6272
6273   // Scan for the appropriate larger type to use.
6274   while (1) {
6275     NewOutTy = (MVT::SimpleValueType)(NewOutTy.getSimpleVT()+1);
6276     assert(NewOutTy.isInteger() && "Ran out of possibilities!");
6277
6278     // If the target supports FP_TO_SINT returning this type, use it.
6279     switch (TLI.getOperationAction(ISD::FP_TO_SINT, NewOutTy)) {
6280     default: break;
6281     case TargetLowering::Legal:
6282       if (!TLI.isTypeLegal(NewOutTy))
6283         break;  // Can't use this datatype.
6284       // FALL THROUGH.
6285     case TargetLowering::Custom:
6286       OpToUse = ISD::FP_TO_SINT;
6287       break;
6288     }
6289     if (OpToUse) break;
6290
6291     // If the target supports FP_TO_UINT of this type, use it.
6292     switch (TLI.getOperationAction(ISD::FP_TO_UINT, NewOutTy)) {
6293     default: break;
6294     case TargetLowering::Legal:
6295       if (!TLI.isTypeLegal(NewOutTy))
6296         break;  // Can't use this datatype.
6297       // FALL THROUGH.
6298     case TargetLowering::Custom:
6299       OpToUse = ISD::FP_TO_UINT;
6300       break;
6301     }
6302     if (OpToUse) break;
6303
6304     // Otherwise, try a larger type.
6305   }
6306
6307
6308   // Okay, we found the operation and type to use.
6309   SDValue Operation = DAG.getNode(OpToUse, dl, NewOutTy, LegalOp);
6310
6311   // If the operation produces an invalid type, it must be custom lowered.  Use
6312   // the target lowering hooks to expand it.  Just keep the low part of the
6313   // expanded operation, we know that we're truncating anyway.
6314   if (getTypeAction(NewOutTy) == Expand) {
6315     SmallVector<SDValue, 2> Results;
6316     TLI.ReplaceNodeResults(Operation.getNode(), Results, DAG);
6317     assert(Results.size() == 1 && "Incorrect FP_TO_XINT lowering!");
6318     Operation = Results[0];
6319   }
6320
6321   // Truncate the result of the extended FP_TO_*INT operation to the desired
6322   // size.
6323   return DAG.getNode(ISD::TRUNCATE, dl, DestVT, Operation);
6324 }
6325
6326 /// ExpandBSWAP - Open code the operations for BSWAP of the specified operation.
6327 ///
6328 SDValue SelectionDAGLegalize::ExpandBSWAP(SDValue Op, DebugLoc dl) {
6329   MVT VT = Op.getValueType();
6330   MVT SHVT = TLI.getShiftAmountTy();
6331   SDValue Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8;
6332   switch (VT.getSimpleVT()) {
6333   default: assert(0 && "Unhandled Expand type in BSWAP!"); abort();
6334   case MVT::i16:
6335     Tmp2 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, SHVT));
6336     Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, SHVT));
6337     return DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
6338   case MVT::i32:
6339     Tmp4 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, SHVT));
6340     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, SHVT));
6341     Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, SHVT));
6342     Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, SHVT));
6343     Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3, DAG.getConstant(0xFF0000, VT));
6344     Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(0xFF00, VT));
6345     Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
6346     Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
6347     return DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
6348   case MVT::i64:
6349     Tmp8 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(56, SHVT));
6350     Tmp7 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(40, SHVT));
6351     Tmp6 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, SHVT));
6352     Tmp5 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, SHVT));
6353     Tmp4 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, SHVT));
6354     Tmp3 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, SHVT));
6355     Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(40, SHVT));
6356     Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(56, SHVT));
6357     Tmp7 = DAG.getNode(ISD::AND, dl, VT, Tmp7, DAG.getConstant(255ULL<<48, VT));
6358     Tmp6 = DAG.getNode(ISD::AND, dl, VT, Tmp6, DAG.getConstant(255ULL<<40, VT));
6359     Tmp5 = DAG.getNode(ISD::AND, dl, VT, Tmp5, DAG.getConstant(255ULL<<32, VT));
6360     Tmp4 = DAG.getNode(ISD::AND, dl, VT, Tmp4, DAG.getConstant(255ULL<<24, VT));
6361     Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3, DAG.getConstant(255ULL<<16, VT));
6362     Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(255ULL<<8 , VT));
6363     Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp7);
6364     Tmp6 = DAG.getNode(ISD::OR, dl, VT, Tmp6, Tmp5);
6365     Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
6366     Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
6367     Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp6);
6368     Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
6369     return DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp4);
6370   }
6371 }
6372
6373 /// ExpandBitCount - Expand the specified bitcount instruction into operations.
6374 ///
6375 SDValue SelectionDAGLegalize::ExpandBitCount(unsigned Opc, SDValue Op,
6376                                              DebugLoc dl) {
6377   switch (Opc) {
6378   default: assert(0 && "Cannot expand this yet!");
6379   case ISD::CTPOP: {
6380     static const uint64_t mask[6] = {
6381       0x5555555555555555ULL, 0x3333333333333333ULL,
6382       0x0F0F0F0F0F0F0F0FULL, 0x00FF00FF00FF00FFULL,
6383       0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL
6384     };
6385     MVT VT = Op.getValueType();
6386     MVT ShVT = TLI.getShiftAmountTy();
6387     unsigned len = VT.getSizeInBits();
6388     for (unsigned i = 0; (1U << i) <= (len / 2); ++i) {
6389       //x = (x & mask[i][len/8]) + (x >> (1 << i) & mask[i][len/8])
6390       unsigned EltSize = VT.isVector() ?
6391         VT.getVectorElementType().getSizeInBits() : len;
6392       SDValue Tmp2 = DAG.getConstant(APInt(EltSize, mask[i]), VT);
6393       SDValue Tmp3 = DAG.getConstant(1ULL << i, ShVT);
6394       Op = DAG.getNode(ISD::ADD, dl, VT,
6395                        DAG.getNode(ISD::AND, dl, VT, Op, Tmp2),
6396                        DAG.getNode(ISD::AND, dl, VT,
6397                                    DAG.getNode(ISD::SRL, dl, VT, Op, Tmp3),
6398                                    Tmp2));
6399     }
6400     return Op;
6401   }
6402   case ISD::CTLZ: {
6403     // for now, we do this:
6404     // x = x | (x >> 1);
6405     // x = x | (x >> 2);
6406     // ...
6407     // x = x | (x >>16);
6408     // x = x | (x >>32); // for 64-bit input
6409     // return popcount(~x);
6410     //
6411     // but see also: http://www.hackersdelight.org/HDcode/nlz.cc
6412     MVT VT = Op.getValueType();
6413     MVT ShVT = TLI.getShiftAmountTy();
6414     unsigned len = VT.getSizeInBits();
6415     for (unsigned i = 0; (1U << i) <= (len / 2); ++i) {
6416       SDValue Tmp3 = DAG.getConstant(1ULL << i, ShVT);
6417       Op = DAG.getNode(ISD::OR, dl, VT, Op,
6418                        DAG.getNode(ISD::SRL, dl, VT, Op, Tmp3));
6419     }
6420     Op = DAG.getNOT(dl, Op, VT);
6421     return DAG.getNode(ISD::CTPOP, dl, VT, Op);
6422   }
6423   case ISD::CTTZ: {
6424     // for now, we use: { return popcount(~x & (x - 1)); }
6425     // unless the target has ctlz but not ctpop, in which case we use:
6426     // { return 32 - nlz(~x & (x-1)); }
6427     // see also http://www.hackersdelight.org/HDcode/ntz.cc
6428     MVT VT = Op.getValueType();
6429     SDValue Tmp3 = DAG.getNode(ISD::AND, dl, VT,
6430                                DAG.getNOT(dl, Op, VT),
6431                                DAG.getNode(ISD::SUB, dl, VT, Op,
6432                                            DAG.getConstant(1, VT)));
6433     // If ISD::CTLZ is legal and CTPOP isn't, then do that instead.
6434     if (!TLI.isOperationLegalOrCustom(ISD::CTPOP, VT) &&
6435         TLI.isOperationLegalOrCustom(ISD::CTLZ, VT))
6436       return DAG.getNode(ISD::SUB, dl, VT,
6437                          DAG.getConstant(VT.getSizeInBits(), VT),
6438                          DAG.getNode(ISD::CTLZ, dl, VT, Tmp3));
6439     return DAG.getNode(ISD::CTPOP, dl, VT, Tmp3);
6440   }
6441   }
6442 }
6443
6444 /// ExpandOp - Expand the specified SDValue into its two component pieces
6445 /// Lo&Hi.  Note that the Op MUST be an expanded type.  As a result of this, the
6446 /// LegalizedNodes map is filled in for any results that are not expanded, the
6447 /// ExpandedNodes map is filled in for any results that are expanded, and the
6448 /// Lo/Hi values are returned.
6449 void SelectionDAGLegalize::ExpandOp(SDValue Op, SDValue &Lo, SDValue &Hi){
6450   MVT VT = Op.getValueType();
6451   MVT NVT = TLI.getTypeToTransformTo(VT);
6452   SDNode *Node = Op.getNode();
6453   DebugLoc dl = Node->getDebugLoc();
6454   assert(getTypeAction(VT) == Expand && "Not an expanded type!");
6455   assert(((NVT.isInteger() && NVT.bitsLT(VT)) || VT.isFloatingPoint() ||
6456          VT.isVector()) && "Cannot expand to FP value or to larger int value!");
6457
6458   // See if we already expanded it.
6459   DenseMap<SDValue, std::pair<SDValue, SDValue> >::iterator I
6460     = ExpandedNodes.find(Op);
6461   if (I != ExpandedNodes.end()) {
6462     Lo = I->second.first;
6463     Hi = I->second.second;
6464     return;
6465   }
6466
6467   switch (Node->getOpcode()) {
6468   case ISD::CopyFromReg:
6469     assert(0 && "CopyFromReg must be legal!");
6470   case ISD::FP_ROUND_INREG:
6471     if (VT == MVT::ppcf128 &&
6472         TLI.getOperationAction(ISD::FP_ROUND_INREG, VT) ==
6473             TargetLowering::Custom) {
6474       SDValue SrcLo, SrcHi, Src;
6475       ExpandOp(Op.getOperand(0), SrcLo, SrcHi);
6476       Src = DAG.getNode(ISD::BUILD_PAIR, dl, VT, SrcLo, SrcHi);
6477       SDValue Result =
6478         TLI.LowerOperation(DAG.getNode(ISD::FP_ROUND_INREG, dl, VT, Src,
6479                                        Op.getOperand(1)), DAG);
6480       assert(Result.getNode()->getOpcode() == ISD::BUILD_PAIR);
6481       Lo = Result.getNode()->getOperand(0);
6482       Hi = Result.getNode()->getOperand(1);
6483       break;
6484     }
6485     // fall through
6486   default:
6487 #ifndef NDEBUG
6488     cerr << "NODE: "; Node->dump(&DAG); cerr << "\n";
6489 #endif
6490     assert(0 && "Do not know how to expand this operator!");
6491     abort();
6492   case ISD::EXTRACT_ELEMENT:
6493     ExpandOp(Node->getOperand(0), Lo, Hi);
6494     if (cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue())
6495       return ExpandOp(Hi, Lo, Hi);
6496     return ExpandOp(Lo, Lo, Hi);
6497   case ISD::EXTRACT_VECTOR_ELT:
6498     // ExpandEXTRACT_VECTOR_ELT tolerates invalid result types.
6499     Lo  = ExpandEXTRACT_VECTOR_ELT(Op);
6500     return ExpandOp(Lo, Lo, Hi);
6501   case ISD::UNDEF:
6502     Lo = DAG.getUNDEF(NVT);
6503     Hi = DAG.getUNDEF(NVT);
6504     break;
6505   case ISD::Constant: {
6506     unsigned NVTBits = NVT.getSizeInBits();
6507     const APInt &Cst = cast<ConstantSDNode>(Node)->getAPIntValue();
6508     Lo = DAG.getConstant(APInt(Cst).trunc(NVTBits), NVT);
6509     Hi = DAG.getConstant(Cst.lshr(NVTBits).trunc(NVTBits), NVT);
6510     break;
6511   }
6512   case ISD::ConstantFP: {
6513     ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Node);
6514     if (CFP->getValueType(0) == MVT::ppcf128) {
6515       APInt api = CFP->getValueAPF().bitcastToAPInt();
6516       Lo = DAG.getConstantFP(APFloat(APInt(64, 1, &api.getRawData()[1])),
6517                              MVT::f64);
6518       Hi = DAG.getConstantFP(APFloat(APInt(64, 1, &api.getRawData()[0])),
6519                              MVT::f64);
6520       break;
6521     }
6522     Lo = ExpandConstantFP(CFP, false, DAG, TLI);
6523     if (getTypeAction(Lo.getValueType()) == Expand)
6524       ExpandOp(Lo, Lo, Hi);
6525     break;
6526   }
6527   case ISD::BUILD_PAIR:
6528     // Return the operands.
6529     Lo = Node->getOperand(0);
6530     Hi = Node->getOperand(1);
6531     break;
6532
6533   case ISD::MERGE_VALUES:
6534     if (Node->getNumValues() == 1) {
6535       ExpandOp(Op.getOperand(0), Lo, Hi);
6536       break;
6537     }
6538     // FIXME: For now only expand i64,chain = MERGE_VALUES (x, y)
6539     assert(Op.getResNo() == 0 && Node->getNumValues() == 2 &&
6540            Op.getValue(1).getValueType() == MVT::Other &&
6541            "unhandled MERGE_VALUES");
6542     ExpandOp(Op.getOperand(0), Lo, Hi);
6543     // Remember that we legalized the chain.
6544     AddLegalizedOperand(Op.getValue(1), LegalizeOp(Op.getOperand(1)));
6545     break;
6546
6547   case ISD::SIGN_EXTEND_INREG:
6548     ExpandOp(Node->getOperand(0), Lo, Hi);
6549     // sext_inreg the low part if needed.
6550     Lo = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NVT, Lo, Node->getOperand(1));
6551
6552     // The high part gets the sign extension from the lo-part.  This handles
6553     // things like sextinreg V:i64 from i8.
6554     Hi = DAG.getNode(ISD::SRA, dl, NVT, Lo,
6555                      DAG.getConstant(NVT.getSizeInBits()-1,
6556                                      TLI.getShiftAmountTy()));
6557     break;
6558
6559   case ISD::BSWAP: {
6560     ExpandOp(Node->getOperand(0), Lo, Hi);
6561     SDValue TempLo = DAG.getNode(ISD::BSWAP, dl, NVT, Hi);
6562     Hi = DAG.getNode(ISD::BSWAP, dl, NVT, Lo);
6563     Lo = TempLo;
6564     break;
6565   }
6566
6567   case ISD::CTPOP:
6568     ExpandOp(Node->getOperand(0), Lo, Hi);
6569     Lo = DAG.getNode(ISD::ADD, dl, NVT,      // ctpop(HL) -> ctpop(H)+ctpop(L)
6570                      DAG.getNode(ISD::CTPOP, dl, NVT, Lo),
6571                      DAG.getNode(ISD::CTPOP, dl, NVT, Hi));
6572     Hi = DAG.getConstant(0, NVT);
6573     break;
6574
6575   case ISD::CTLZ: {
6576     // ctlz (HL) -> ctlz(H) != 32 ? ctlz(H) : (ctlz(L)+32)
6577     ExpandOp(Node->getOperand(0), Lo, Hi);
6578     SDValue BitsC = DAG.getConstant(NVT.getSizeInBits(), NVT);
6579     SDValue HLZ = DAG.getNode(ISD::CTLZ, dl, NVT, Hi);
6580     SDValue TopNotZero = DAG.getSetCC(dl, TLI.getSetCCResultType(NVT), HLZ,
6581                                       BitsC, ISD::SETNE);
6582     SDValue LowPart = DAG.getNode(ISD::CTLZ, dl, NVT, Lo);
6583     LowPart = DAG.getNode(ISD::ADD, dl, NVT, LowPart, BitsC);
6584
6585     Lo = DAG.getNode(ISD::SELECT, dl, NVT, TopNotZero, HLZ, LowPart);
6586     Hi = DAG.getConstant(0, NVT);
6587     break;
6588   }
6589
6590   case ISD::CTTZ: {
6591     // cttz (HL) -> cttz(L) != 32 ? cttz(L) : (cttz(H)+32)
6592     ExpandOp(Node->getOperand(0), Lo, Hi);
6593     SDValue BitsC = DAG.getConstant(NVT.getSizeInBits(), NVT);
6594     SDValue LTZ = DAG.getNode(ISD::CTTZ, dl, NVT, Lo);
6595     SDValue BotNotZero = DAG.getSetCC(dl, TLI.getSetCCResultType(NVT), LTZ,
6596                                       BitsC, ISD::SETNE);
6597     SDValue HiPart = DAG.getNode(ISD::CTTZ, dl, NVT, Hi);
6598     HiPart = DAG.getNode(ISD::ADD, dl, NVT, HiPart, BitsC);
6599
6600     Lo = DAG.getNode(ISD::SELECT, dl, NVT, BotNotZero, LTZ, HiPart);
6601     Hi = DAG.getConstant(0, NVT);
6602     break;
6603   }
6604
6605   case ISD::VAARG: {
6606     SDValue Ch = Node->getOperand(0);   // Legalize the chain.
6607     SDValue Ptr = Node->getOperand(1);  // Legalize the pointer.
6608     Lo = DAG.getVAArg(NVT, dl, Ch, Ptr, Node->getOperand(2));
6609     Hi = DAG.getVAArg(NVT, dl, Lo.getValue(1), Ptr, Node->getOperand(2));
6610
6611     // Remember that we legalized the chain.
6612     Hi = LegalizeOp(Hi);
6613     AddLegalizedOperand(Op.getValue(1), Hi.getValue(1));
6614     if (TLI.isBigEndian())
6615       std::swap(Lo, Hi);
6616     break;
6617   }
6618
6619   case ISD::LOAD: {
6620     LoadSDNode *LD = cast<LoadSDNode>(Node);
6621     SDValue Ch  = LD->getChain();    // Legalize the chain.
6622     SDValue Ptr = LD->getBasePtr();  // Legalize the pointer.
6623     ISD::LoadExtType ExtType = LD->getExtensionType();
6624     const Value *SV = LD->getSrcValue();
6625     int SVOffset = LD->getSrcValueOffset();
6626     unsigned Alignment = LD->getAlignment();
6627     bool isVolatile = LD->isVolatile();
6628
6629     if (ExtType == ISD::NON_EXTLOAD) {
6630       Lo = DAG.getLoad(NVT, dl, Ch, Ptr, SV, SVOffset,
6631                        isVolatile, Alignment);
6632       if (VT == MVT::f32 || VT == MVT::f64) {
6633         // f32->i32 or f64->i64 one to one expansion.
6634         // Remember that we legalized the chain.
6635         AddLegalizedOperand(SDValue(Node, 1), LegalizeOp(Lo.getValue(1)));
6636         // Recursively expand the new load.
6637         if (getTypeAction(NVT) == Expand)
6638           ExpandOp(Lo, Lo, Hi);
6639         break;
6640       }
6641
6642       // Increment the pointer to the other half.
6643       unsigned IncrementSize = Lo.getValueType().getSizeInBits()/8;
6644       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
6645                         DAG.getIntPtrConstant(IncrementSize));
6646       SVOffset += IncrementSize;
6647       Alignment = MinAlign(Alignment, IncrementSize);
6648       Hi = DAG.getLoad(NVT, dl, Ch, Ptr, SV, SVOffset,
6649                        isVolatile, Alignment);
6650
6651       // Build a factor node to remember that this load is independent of the
6652       // other one.
6653       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
6654                                Hi.getValue(1));
6655
6656       // Remember that we legalized the chain.
6657       AddLegalizedOperand(Op.getValue(1), LegalizeOp(TF));
6658       if (TLI.isBigEndian())
6659         std::swap(Lo, Hi);
6660     } else {
6661       MVT EVT = LD->getMemoryVT();
6662
6663       if ((VT == MVT::f64 && EVT == MVT::f32) ||
6664           (VT == MVT::ppcf128 && (EVT==MVT::f64 || EVT==MVT::f32))) {
6665         // f64 = EXTLOAD f32 should expand to LOAD, FP_EXTEND
6666         SDValue Load = DAG.getLoad(EVT, dl, Ch, Ptr, SV,
6667                                    SVOffset, isVolatile, Alignment);
6668         // Remember that we legalized the chain.
6669         AddLegalizedOperand(SDValue(Node, 1), LegalizeOp(Load.getValue(1)));
6670         ExpandOp(DAG.getNode(ISD::FP_EXTEND, dl, VT, Load), Lo, Hi);
6671         break;
6672       }
6673
6674       if (EVT == NVT)
6675         Lo = DAG.getLoad(NVT, dl, Ch, Ptr, SV,
6676                          SVOffset, isVolatile, Alignment);
6677       else
6678         Lo = DAG.getExtLoad(ExtType, dl, NVT, Ch, Ptr, SV,
6679                             SVOffset, EVT, isVolatile,
6680                             Alignment);
6681
6682       // Remember that we legalized the chain.
6683       AddLegalizedOperand(SDValue(Node, 1), LegalizeOp(Lo.getValue(1)));
6684
6685       if (ExtType == ISD::SEXTLOAD) {
6686         // The high part is obtained by SRA'ing all but one of the bits of the
6687         // lo part.
6688         unsigned LoSize = Lo.getValueType().getSizeInBits();
6689         Hi = DAG.getNode(ISD::SRA, dl, NVT, Lo,
6690                          DAG.getConstant(LoSize-1, TLI.getShiftAmountTy()));
6691       } else if (ExtType == ISD::ZEXTLOAD) {
6692         // The high part is just a zero.
6693         Hi = DAG.getConstant(0, NVT);
6694       } else /* if (ExtType == ISD::EXTLOAD) */ {
6695         // The high part is undefined.
6696         Hi = DAG.getUNDEF(NVT);
6697       }
6698     }
6699     break;
6700   }
6701   case ISD::AND:
6702   case ISD::OR:
6703   case ISD::XOR: {   // Simple logical operators -> two trivial pieces.
6704     SDValue LL, LH, RL, RH;
6705     ExpandOp(Node->getOperand(0), LL, LH);
6706     ExpandOp(Node->getOperand(1), RL, RH);
6707     Lo = DAG.getNode(Node->getOpcode(), dl, NVT, LL, RL);
6708     Hi = DAG.getNode(Node->getOpcode(), dl, NVT, LH, RH);
6709     break;
6710   }
6711   case ISD::SELECT: {
6712     SDValue LL, LH, RL, RH;
6713     ExpandOp(Node->getOperand(1), LL, LH);
6714     ExpandOp(Node->getOperand(2), RL, RH);
6715     if (getTypeAction(NVT) == Expand)
6716       NVT = TLI.getTypeToExpandTo(NVT);
6717     Lo = DAG.getNode(ISD::SELECT, dl, NVT, Node->getOperand(0), LL, RL);
6718     if (VT != MVT::f32)
6719       Hi = DAG.getNode(ISD::SELECT, dl, NVT, Node->getOperand(0), LH, RH);
6720     break;
6721   }
6722   case ISD::SELECT_CC: {
6723     SDValue TL, TH, FL, FH;
6724     ExpandOp(Node->getOperand(2), TL, TH);
6725     ExpandOp(Node->getOperand(3), FL, FH);
6726     if (getTypeAction(NVT) == Expand)
6727       NVT = TLI.getTypeToExpandTo(NVT);
6728     Lo = DAG.getNode(ISD::SELECT_CC, dl, NVT, Node->getOperand(0),
6729                      Node->getOperand(1), TL, FL, Node->getOperand(4));
6730     if (VT != MVT::f32)
6731       Hi = DAG.getNode(ISD::SELECT_CC, dl, NVT, Node->getOperand(0),
6732                        Node->getOperand(1), TH, FH, Node->getOperand(4));
6733     break;
6734   }
6735   case ISD::ANY_EXTEND:
6736     // The low part is any extension of the input (which degenerates to a copy).
6737     Lo = DAG.getNode(ISD::ANY_EXTEND, dl, NVT, Node->getOperand(0));
6738     // The high part is undefined.
6739     Hi = DAG.getUNDEF(NVT);
6740     break;
6741   case ISD::SIGN_EXTEND: {
6742     // The low part is just a sign extension of the input (which degenerates to
6743     // a copy).
6744     Lo = DAG.getNode(ISD::SIGN_EXTEND, dl, NVT, Node->getOperand(0));
6745
6746     // The high part is obtained by SRA'ing all but one of the bits of the lo
6747     // part.
6748     unsigned LoSize = Lo.getValueType().getSizeInBits();
6749     Hi = DAG.getNode(ISD::SRA, dl, NVT, Lo,
6750                      DAG.getConstant(LoSize-1, TLI.getShiftAmountTy()));
6751     break;
6752   }
6753   case ISD::ZERO_EXTEND:
6754     // The low part is just a zero extension of the input (which degenerates to
6755     // a copy).
6756     Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Node->getOperand(0));
6757
6758     // The high part is just a zero.
6759     Hi = DAG.getConstant(0, NVT);
6760     break;
6761
6762   case ISD::TRUNCATE: {
6763     // The input value must be larger than this value.  Expand *it*.
6764     SDValue NewLo;
6765     ExpandOp(Node->getOperand(0), NewLo, Hi);
6766
6767     // The low part is now either the right size, or it is closer.  If not the
6768     // right size, make an illegal truncate so we recursively expand it.
6769     if (NewLo.getValueType() != Node->getValueType(0))
6770       NewLo = DAG.getNode(ISD::TRUNCATE, dl, Node->getValueType(0), NewLo);
6771     ExpandOp(NewLo, Lo, Hi);
6772     break;
6773   }
6774
6775   case ISD::BIT_CONVERT: {
6776     SDValue Tmp;
6777     if (TLI.getOperationAction(ISD::BIT_CONVERT, VT) == TargetLowering::Custom){
6778       // If the target wants to, allow it to lower this itself.
6779       switch (getTypeAction(Node->getOperand(0).getValueType())) {
6780       case Expand: assert(0 && "cannot expand FP!");
6781       case Legal:   Tmp = LegalizeOp(Node->getOperand(0)); break;
6782       case Promote: Tmp = PromoteOp (Node->getOperand(0)); break;
6783       }
6784       Tmp = TLI.LowerOperation(DAG.getNode(ISD::BIT_CONVERT, dl, VT, Tmp), DAG);
6785     }
6786
6787     // f32 / f64 must be expanded to i32 / i64.
6788     if (VT == MVT::f32 || VT == MVT::f64) {
6789       Lo = DAG.getNode(ISD::BIT_CONVERT, dl, NVT, Node->getOperand(0));
6790       if (getTypeAction(NVT) == Expand)
6791         ExpandOp(Lo, Lo, Hi);
6792       break;
6793     }
6794
6795     // If source operand will be expanded to the same type as VT, i.e.
6796     // i64 <- f64, i32 <- f32, expand the source operand instead.
6797     MVT VT0 = Node->getOperand(0).getValueType();
6798     if (getTypeAction(VT0) == Expand && TLI.getTypeToTransformTo(VT0) == VT) {
6799       ExpandOp(Node->getOperand(0), Lo, Hi);
6800       break;
6801     }
6802
6803     // Turn this into a load/store pair by default.
6804     if (Tmp.getNode() == 0)
6805       Tmp = EmitStackConvert(Node->getOperand(0), VT, VT, dl);
6806
6807     ExpandOp(Tmp, Lo, Hi);
6808     break;
6809   }
6810
6811   case ISD::READCYCLECOUNTER: {
6812     assert(TLI.getOperationAction(ISD::READCYCLECOUNTER, VT) ==
6813                  TargetLowering::Custom &&
6814            "Must custom expand ReadCycleCounter");
6815     SDValue Tmp = TLI.LowerOperation(Op, DAG);
6816     assert(Tmp.getNode() && "Node must be custom expanded!");
6817     ExpandOp(Tmp.getValue(0), Lo, Hi);
6818     AddLegalizedOperand(SDValue(Node, 1), // Remember we legalized the chain.
6819                         LegalizeOp(Tmp.getValue(1)));
6820     break;
6821   }
6822
6823   case ISD::ATOMIC_CMP_SWAP: {
6824     // This operation does not need a loop.
6825     SDValue Tmp = TLI.LowerOperation(Op, DAG);
6826     assert(Tmp.getNode() && "Node must be custom expanded!");
6827     ExpandOp(Tmp.getValue(0), Lo, Hi);
6828     AddLegalizedOperand(SDValue(Node, 1), // Remember we legalized the chain.
6829                         LegalizeOp(Tmp.getValue(1)));
6830     break;
6831   }
6832
6833   case ISD::ATOMIC_LOAD_ADD:
6834   case ISD::ATOMIC_LOAD_SUB:
6835   case ISD::ATOMIC_LOAD_AND:
6836   case ISD::ATOMIC_LOAD_OR:
6837   case ISD::ATOMIC_LOAD_XOR:
6838   case ISD::ATOMIC_LOAD_NAND:
6839   case ISD::ATOMIC_SWAP: {
6840     // These operations require a loop to be generated.  We can't do that yet,
6841     // so substitute a target-dependent pseudo and expand that later.
6842     SDValue In2Lo, In2Hi, In2;
6843     ExpandOp(Op.getOperand(2), In2Lo, In2Hi);
6844     In2 = DAG.getNode(ISD::BUILD_PAIR, dl, VT, In2Lo, In2Hi);
6845     AtomicSDNode* Anode = cast<AtomicSDNode>(Node);
6846     SDValue Replace =
6847       DAG.getAtomic(Op.getOpcode(), dl, Anode->getMemoryVT(),
6848                     Op.getOperand(0), Op.getOperand(1), In2,
6849                     Anode->getSrcValue(), Anode->getAlignment());
6850     SDValue Result = TLI.LowerOperation(Replace, DAG);
6851     ExpandOp(Result.getValue(0), Lo, Hi);
6852     // Remember that we legalized the chain.
6853     AddLegalizedOperand(SDValue(Node, 1), LegalizeOp(Result.getValue(1)));
6854     break;
6855   }
6856
6857     // These operators cannot be expanded directly, emit them as calls to
6858     // library functions.
6859   case ISD::FP_TO_SINT: {
6860     if (TLI.getOperationAction(ISD::FP_TO_SINT, VT) == TargetLowering::Custom) {
6861       SDValue Op;
6862       switch (getTypeAction(Node->getOperand(0).getValueType())) {
6863       case Expand: assert(0 && "cannot expand FP!");
6864       case Legal:   Op = LegalizeOp(Node->getOperand(0)); break;
6865       case Promote: Op = PromoteOp (Node->getOperand(0)); break;
6866       }
6867
6868       Op = TLI.LowerOperation(DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op), DAG);
6869
6870       // Now that the custom expander is done, expand the result, which is still
6871       // VT.
6872       if (Op.getNode()) {
6873         ExpandOp(Op, Lo, Hi);
6874         break;
6875       }
6876     }
6877
6878     RTLIB::Libcall LC = RTLIB::getFPTOSINT(Node->getOperand(0).getValueType(),
6879                                            VT);
6880     assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unexpected uint-to-fp conversion!");
6881     Lo = ExpandLibCall(LC, Node, false/*sign irrelevant*/, Hi);
6882     break;
6883   }
6884
6885   case ISD::FP_TO_UINT: {
6886     if (TLI.getOperationAction(ISD::FP_TO_UINT, VT) == TargetLowering::Custom) {
6887       SDValue Op;
6888       switch (getTypeAction(Node->getOperand(0).getValueType())) {
6889         case Expand: assert(0 && "cannot expand FP!");
6890         case Legal:   Op = LegalizeOp(Node->getOperand(0)); break;
6891         case Promote: Op = PromoteOp (Node->getOperand(0)); break;
6892       }
6893
6894       Op = TLI.LowerOperation(DAG.getNode(ISD::FP_TO_UINT, dl, VT, Op), DAG);
6895
6896       // Now that the custom expander is done, expand the result.
6897       if (Op.getNode()) {
6898         ExpandOp(Op, Lo, Hi);
6899         break;
6900       }
6901     }
6902
6903     RTLIB::Libcall LC = RTLIB::getFPTOUINT(Node->getOperand(0).getValueType(),
6904                                            VT);
6905     assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unexpected fp-to-uint conversion!");
6906     Lo = ExpandLibCall(LC, Node, false/*sign irrelevant*/, Hi);
6907     break;
6908   }
6909
6910   case ISD::SHL: {
6911     // If the target wants custom lowering, do so.
6912     SDValue ShiftAmt = LegalizeOp(Node->getOperand(1));
6913     if (TLI.getOperationAction(ISD::SHL, VT) == TargetLowering::Custom) {
6914       SDValue Op = DAG.getNode(ISD::SHL, dl, VT, Node->getOperand(0), ShiftAmt);
6915       Op = TLI.LowerOperation(Op, DAG);
6916       if (Op.getNode()) {
6917         // Now that the custom expander is done, expand the result, which is
6918         // still VT.
6919         ExpandOp(Op, Lo, Hi);
6920         break;
6921       }
6922     }
6923
6924     // If ADDC/ADDE are supported and if the shift amount is a constant 1, emit
6925     // this X << 1 as X+X.
6926     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(ShiftAmt)) {
6927       if (ShAmt->getAPIntValue() == 1 &&
6928           TLI.isOperationLegalOrCustom(ISD::ADDC, NVT) &&
6929           TLI.isOperationLegalOrCustom(ISD::ADDE, NVT)) {
6930         SDValue LoOps[2], HiOps[3];
6931         ExpandOp(Node->getOperand(0), LoOps[0], HiOps[0]);
6932         SDVTList VTList = DAG.getVTList(LoOps[0].getValueType(), MVT::Flag);
6933         LoOps[1] = LoOps[0];
6934         Lo = DAG.getNode(ISD::ADDC, dl, VTList, LoOps, 2);
6935
6936         HiOps[1] = HiOps[0];
6937         HiOps[2] = Lo.getValue(1);
6938         Hi = DAG.getNode(ISD::ADDE, dl, VTList, HiOps, 3);
6939         break;
6940       }
6941     }
6942
6943     // If we can emit an efficient shift operation, do so now.
6944     if (ExpandShift(ISD::SHL, Node->getOperand(0), ShiftAmt, Lo, Hi, dl))
6945       break;
6946
6947     // If this target supports SHL_PARTS, use it.
6948     TargetLowering::LegalizeAction Action =
6949       TLI.getOperationAction(ISD::SHL_PARTS, NVT);
6950     if ((Action == TargetLowering::Legal && TLI.isTypeLegal(NVT)) ||
6951         Action == TargetLowering::Custom) {
6952       ExpandShiftParts(ISD::SHL_PARTS, Node->getOperand(0),
6953                        ShiftAmt, Lo, Hi, dl);
6954       break;
6955     }
6956
6957     // Otherwise, emit a libcall.
6958     Lo = ExpandLibCall(RTLIB::SHL_I64, Node, false/*left shift=unsigned*/, Hi);
6959     break;
6960   }
6961
6962   case ISD::SRA: {
6963     // If the target wants custom lowering, do so.
6964     SDValue ShiftAmt = LegalizeOp(Node->getOperand(1));
6965     if (TLI.getOperationAction(ISD::SRA, VT) == TargetLowering::Custom) {
6966       SDValue Op = DAG.getNode(ISD::SRA, dl, VT, Node->getOperand(0), ShiftAmt);
6967       Op = TLI.LowerOperation(Op, DAG);
6968       if (Op.getNode()) {
6969         // Now that the custom expander is done, expand the result, which is
6970         // still VT.
6971         ExpandOp(Op, Lo, Hi);
6972         break;
6973       }
6974     }
6975
6976     // If we can emit an efficient shift operation, do so now.
6977     if (ExpandShift(ISD::SRA,  Node->getOperand(0), ShiftAmt, Lo, Hi, dl))
6978       break;
6979
6980     // If this target supports SRA_PARTS, use it.
6981     TargetLowering::LegalizeAction Action =
6982       TLI.getOperationAction(ISD::SRA_PARTS, NVT);
6983     if ((Action == TargetLowering::Legal && TLI.isTypeLegal(NVT)) ||
6984         Action == TargetLowering::Custom) {
6985       ExpandShiftParts(ISD::SRA_PARTS, Node->getOperand(0),
6986                        ShiftAmt, Lo, Hi, dl);
6987       break;
6988     }
6989
6990     // Otherwise, emit a libcall.
6991     Lo = ExpandLibCall(RTLIB::SRA_I64, Node, true/*ashr is signed*/, Hi);
6992     break;
6993   }
6994
6995   case ISD::SRL: {
6996     // If the target wants custom lowering, do so.
6997     SDValue ShiftAmt = LegalizeOp(Node->getOperand(1));
6998     if (TLI.getOperationAction(ISD::SRL, VT) == TargetLowering::Custom) {
6999       SDValue Op = DAG.getNode(ISD::SRL, dl, VT, Node->getOperand(0), ShiftAmt);
7000       Op = TLI.LowerOperation(Op, DAG);
7001       if (Op.getNode()) {
7002         // Now that the custom expander is done, expand the result, which is
7003         // still VT.
7004         ExpandOp(Op, Lo, Hi);
7005         break;
7006       }
7007     }
7008
7009     // If we can emit an efficient shift operation, do so now.
7010     if (ExpandShift(ISD::SRL, Node->getOperand(0), ShiftAmt, Lo, Hi, dl))
7011       break;
7012
7013     // If this target supports SRL_PARTS, use it.
7014     TargetLowering::LegalizeAction Action =
7015       TLI.getOperationAction(ISD::SRL_PARTS, NVT);
7016     if ((Action == TargetLowering::Legal && TLI.isTypeLegal(NVT)) ||
7017         Action == TargetLowering::Custom) {
7018       ExpandShiftParts(ISD::SRL_PARTS,
7019                        Node->getOperand(0), ShiftAmt, Lo, Hi, dl);
7020       break;
7021     }
7022
7023     // Otherwise, emit a libcall.
7024     Lo = ExpandLibCall(RTLIB::SRL_I64, Node, false/*lshr is unsigned*/, Hi);
7025     break;
7026   }
7027
7028   case ISD::ADD:
7029   case ISD::SUB: {
7030     // If the target wants to custom expand this, let them.
7031     if (TLI.getOperationAction(Node->getOpcode(), VT) ==
7032             TargetLowering::Custom) {
7033       SDValue Result = TLI.LowerOperation(Op, DAG);
7034       if (Result.getNode()) {
7035         ExpandOp(Result, Lo, Hi);
7036         break;
7037       }
7038     }
7039     // Expand the subcomponents.
7040     SDValue LHSL, LHSH, RHSL, RHSH;
7041     ExpandOp(Node->getOperand(0), LHSL, LHSH);
7042     ExpandOp(Node->getOperand(1), RHSL, RHSH);
7043     SDValue LoOps[2], HiOps[3];
7044     LoOps[0] = LHSL;
7045     LoOps[1] = RHSL;
7046     HiOps[0] = LHSH;
7047     HiOps[1] = RHSH;
7048
7049     //cascaded check to see if any smaller size has a a carry flag.
7050     unsigned OpV = Node->getOpcode() == ISD::ADD ? ISD::ADDC : ISD::SUBC;
7051     bool hasCarry = false;
7052     for (unsigned BitSize = NVT.getSizeInBits(); BitSize != 0; BitSize /= 2) {
7053       MVT AVT = MVT::getIntegerVT(BitSize);
7054       if (TLI.isOperationLegalOrCustom(OpV, AVT)) {
7055         hasCarry = true;
7056         break;
7057       }
7058     }
7059
7060     if(hasCarry) {
7061       SDVTList VTList = DAG.getVTList(LHSL.getValueType(), MVT::Flag);
7062       if (Node->getOpcode() == ISD::ADD) {
7063         Lo = DAG.getNode(ISD::ADDC, dl, VTList, LoOps, 2);
7064         HiOps[2] = Lo.getValue(1);
7065         Hi = DAG.getNode(ISD::ADDE, dl, VTList, HiOps, 3);
7066       } else {
7067         Lo = DAG.getNode(ISD::SUBC, dl, VTList, LoOps, 2);
7068         HiOps[2] = Lo.getValue(1);
7069         Hi = DAG.getNode(ISD::SUBE, dl, VTList, HiOps, 3);
7070       }
7071       break;
7072     } else {
7073       if (Node->getOpcode() == ISD::ADD) {
7074         Lo = DAG.getNode(ISD::ADD, dl, NVT, LoOps, 2);
7075         Hi = DAG.getNode(ISD::ADD, dl, NVT, HiOps, 2);
7076         SDValue Cmp1 = DAG.getSetCC(dl, TLI.getSetCCResultType(NVT),
7077                                     Lo, LoOps[0], ISD::SETULT);
7078         SDValue Carry1 = DAG.getNode(ISD::SELECT, dl, NVT, Cmp1,
7079                                      DAG.getConstant(1, NVT),
7080                                      DAG.getConstant(0, NVT));
7081         SDValue Cmp2 = DAG.getSetCC(dl, TLI.getSetCCResultType(NVT),
7082                                     Lo, LoOps[1], ISD::SETULT);
7083         SDValue Carry2 = DAG.getNode(ISD::SELECT, dl, NVT, Cmp2,
7084                                     DAG.getConstant(1, NVT),
7085                                     Carry1);
7086         Hi = DAG.getNode(ISD::ADD, dl, NVT, Hi, Carry2);
7087       } else {
7088         Lo = DAG.getNode(ISD::SUB, dl, NVT, LoOps, 2);
7089         Hi = DAG.getNode(ISD::SUB, dl, NVT, HiOps, 2);
7090         SDValue Cmp = DAG.getSetCC(dl, NVT, LoOps[0], LoOps[1], ISD::SETULT);
7091         SDValue Borrow = DAG.getNode(ISD::SELECT, dl, NVT, Cmp,
7092                                      DAG.getConstant(1, NVT),
7093                                      DAG.getConstant(0, NVT));
7094         Hi = DAG.getNode(ISD::SUB, dl, NVT, Hi, Borrow);
7095       }
7096       break;
7097     }
7098   }
7099
7100   case ISD::ADDC:
7101   case ISD::SUBC: {
7102     // Expand the subcomponents.
7103     SDValue LHSL, LHSH, RHSL, RHSH;
7104     ExpandOp(Node->getOperand(0), LHSL, LHSH);
7105     ExpandOp(Node->getOperand(1), RHSL, RHSH);
7106     SDVTList VTList = DAG.getVTList(LHSL.getValueType(), MVT::Flag);
7107     SDValue LoOps[2] = { LHSL, RHSL };
7108     SDValue HiOps[3] = { LHSH, RHSH };
7109
7110     if (Node->getOpcode() == ISD::ADDC) {
7111       Lo = DAG.getNode(ISD::ADDC, dl, VTList, LoOps, 2);
7112       HiOps[2] = Lo.getValue(1);
7113       Hi = DAG.getNode(ISD::ADDE, dl, VTList, HiOps, 3);
7114     } else {
7115       Lo = DAG.getNode(ISD::SUBC, dl, VTList, LoOps, 2);
7116       HiOps[2] = Lo.getValue(1);
7117       Hi = DAG.getNode(ISD::SUBE, dl, VTList, HiOps, 3);
7118     }
7119     // Remember that we legalized the flag.
7120     AddLegalizedOperand(Op.getValue(1), LegalizeOp(Hi.getValue(1)));
7121     break;
7122   }
7123   case ISD::ADDE:
7124   case ISD::SUBE: {
7125     // Expand the subcomponents.
7126     SDValue LHSL, LHSH, RHSL, RHSH;
7127     ExpandOp(Node->getOperand(0), LHSL, LHSH);
7128     ExpandOp(Node->getOperand(1), RHSL, RHSH);
7129     SDVTList VTList = DAG.getVTList(LHSL.getValueType(), MVT::Flag);
7130     SDValue LoOps[3] = { LHSL, RHSL, Node->getOperand(2) };
7131     SDValue HiOps[3] = { LHSH, RHSH };
7132
7133     Lo = DAG.getNode(Node->getOpcode(), dl, VTList, LoOps, 3);
7134     HiOps[2] = Lo.getValue(1);
7135     Hi = DAG.getNode(Node->getOpcode(), dl, VTList, HiOps, 3);
7136
7137     // Remember that we legalized the flag.
7138     AddLegalizedOperand(Op.getValue(1), LegalizeOp(Hi.getValue(1)));
7139     break;
7140   }
7141   case ISD::MUL: {
7142     // If the target wants to custom expand this, let them.
7143     if (TLI.getOperationAction(ISD::MUL, VT) == TargetLowering::Custom) {
7144       SDValue New = TLI.LowerOperation(Op, DAG);
7145       if (New.getNode()) {
7146         ExpandOp(New, Lo, Hi);
7147         break;
7148       }
7149     }
7150
7151     bool HasMULHS = TLI.isOperationLegalOrCustom(ISD::MULHS, NVT);
7152     bool HasMULHU = TLI.isOperationLegalOrCustom(ISD::MULHU, NVT);
7153     bool HasSMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::SMUL_LOHI, NVT);
7154     bool HasUMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::UMUL_LOHI, NVT);
7155     if (HasMULHU || HasMULHS || HasUMUL_LOHI || HasSMUL_LOHI) {
7156       SDValue LL, LH, RL, RH;
7157       ExpandOp(Node->getOperand(0), LL, LH);
7158       ExpandOp(Node->getOperand(1), RL, RH);
7159       unsigned OuterBitSize = Op.getValueSizeInBits();
7160       unsigned InnerBitSize = RH.getValueSizeInBits();
7161       unsigned LHSSB = DAG.ComputeNumSignBits(Op.getOperand(0));
7162       unsigned RHSSB = DAG.ComputeNumSignBits(Op.getOperand(1));
7163       APInt HighMask = APInt::getHighBitsSet(OuterBitSize, InnerBitSize);
7164       if (DAG.MaskedValueIsZero(Node->getOperand(0), HighMask) &&
7165           DAG.MaskedValueIsZero(Node->getOperand(1), HighMask)) {
7166         // The inputs are both zero-extended.
7167         if (HasUMUL_LOHI) {
7168           // We can emit a umul_lohi.
7169           Lo = DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(NVT, NVT), LL, RL);
7170           Hi = SDValue(Lo.getNode(), 1);
7171           break;
7172         }
7173         if (HasMULHU) {
7174           // We can emit a mulhu+mul.
7175           Lo = DAG.getNode(ISD::MUL, dl, NVT, LL, RL);
7176           Hi = DAG.getNode(ISD::MULHU, dl, NVT, LL, RL);
7177           break;
7178         }
7179       }
7180       if (LHSSB > InnerBitSize && RHSSB > InnerBitSize) {
7181         // The input values are both sign-extended.
7182         if (HasSMUL_LOHI) {
7183           // We can emit a smul_lohi.
7184           Lo = DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(NVT, NVT), LL, RL);
7185           Hi = SDValue(Lo.getNode(), 1);
7186           break;
7187         }
7188         if (HasMULHS) {
7189           // We can emit a mulhs+mul.
7190           Lo = DAG.getNode(ISD::MUL, dl, NVT, LL, RL);
7191           Hi = DAG.getNode(ISD::MULHS, dl, NVT, LL, RL);
7192           break;
7193         }
7194       }
7195       if (HasUMUL_LOHI) {
7196         // Lo,Hi = umul LHS, RHS.
7197         SDValue UMulLOHI = DAG.getNode(ISD::UMUL_LOHI, dl,
7198                                          DAG.getVTList(NVT, NVT), LL, RL);
7199         Lo = UMulLOHI;
7200         Hi = UMulLOHI.getValue(1);
7201         RH = DAG.getNode(ISD::MUL, dl, NVT, LL, RH);
7202         LH = DAG.getNode(ISD::MUL, dl, NVT, LH, RL);
7203         Hi = DAG.getNode(ISD::ADD, dl, NVT, Hi, RH);
7204         Hi = DAG.getNode(ISD::ADD, dl, NVT, Hi, LH);
7205         break;
7206       }
7207       if (HasMULHU) {
7208         Lo = DAG.getNode(ISD::MUL, dl, NVT, LL, RL);
7209         Hi = DAG.getNode(ISD::MULHU, dl, NVT, LL, RL);
7210         RH = DAG.getNode(ISD::MUL, dl, NVT, LL, RH);
7211         LH = DAG.getNode(ISD::MUL, dl, NVT, LH, RL);
7212         Hi = DAG.getNode(ISD::ADD, dl, NVT, Hi, RH);
7213         Hi = DAG.getNode(ISD::ADD, dl, NVT, Hi, LH);
7214         break;
7215       }
7216     }
7217
7218     // If nothing else, we can make a libcall.
7219     Lo = ExpandLibCall(RTLIB::MUL_I64, Node, false/*sign irrelevant*/, Hi);
7220     break;
7221   }
7222   case ISD::SDIV:
7223     Lo = ExpandLibCall(RTLIB::SDIV_I64, Node, true, Hi);
7224     break;
7225   case ISD::UDIV:
7226     Lo = ExpandLibCall(RTLIB::UDIV_I64, Node, true, Hi);
7227     break;
7228   case ISD::SREM:
7229     Lo = ExpandLibCall(RTLIB::SREM_I64, Node, true, Hi);
7230     break;
7231   case ISD::UREM:
7232     Lo = ExpandLibCall(RTLIB::UREM_I64, Node, true, Hi);
7233     break;
7234
7235   case ISD::FADD:
7236     Lo = ExpandLibCall(GetFPLibCall(VT, RTLIB::ADD_F32,
7237                                         RTLIB::ADD_F64,
7238                                         RTLIB::ADD_F80,
7239                                         RTLIB::ADD_PPCF128),
7240                        Node, false, Hi);
7241     break;
7242   case ISD::FSUB:
7243     Lo = ExpandLibCall(GetFPLibCall(VT, RTLIB::SUB_F32,
7244                                         RTLIB::SUB_F64,
7245                                         RTLIB::SUB_F80,
7246                                         RTLIB::SUB_PPCF128),
7247                        Node, false, Hi);
7248     break;
7249   case ISD::FMUL:
7250     Lo = ExpandLibCall(GetFPLibCall(VT, RTLIB::MUL_F32,
7251                                         RTLIB::MUL_F64,
7252                                         RTLIB::MUL_F80,
7253                                         RTLIB::MUL_PPCF128),
7254                        Node, false, Hi);
7255     break;
7256   case ISD::FDIV:
7257     Lo = ExpandLibCall(GetFPLibCall(VT, RTLIB::DIV_F32,
7258                                         RTLIB::DIV_F64,
7259                                         RTLIB::DIV_F80,
7260                                         RTLIB::DIV_PPCF128),
7261                        Node, false, Hi);
7262     break;
7263   case ISD::FP_EXTEND: {
7264     if (VT == MVT::ppcf128) {
7265       assert(Node->getOperand(0).getValueType()==MVT::f32 ||
7266              Node->getOperand(0).getValueType()==MVT::f64);
7267       const uint64_t zero = 0;
7268       if (Node->getOperand(0).getValueType()==MVT::f32)
7269         Hi = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Node->getOperand(0));
7270       else
7271         Hi = Node->getOperand(0);
7272       Lo = DAG.getConstantFP(APFloat(APInt(64, 1, &zero)), MVT::f64);
7273       break;
7274     }
7275     RTLIB::Libcall LC = RTLIB::getFPEXT(Node->getOperand(0).getValueType(), VT);
7276     assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported FP_EXTEND!");
7277     Lo = ExpandLibCall(LC, Node, true, Hi);
7278     break;
7279   }
7280   case ISD::FP_ROUND: {
7281     RTLIB::Libcall LC = RTLIB::getFPROUND(Node->getOperand(0).getValueType(),
7282                                           VT);
7283     assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported FP_ROUND!");
7284     Lo = ExpandLibCall(LC, Node, true, Hi);
7285     break;
7286   }
7287   case ISD::FSQRT:
7288   case ISD::FSIN:
7289   case ISD::FCOS:
7290   case ISD::FLOG:
7291   case ISD::FLOG2:
7292   case ISD::FLOG10:
7293   case ISD::FEXP:
7294   case ISD::FEXP2:
7295   case ISD::FTRUNC:
7296   case ISD::FFLOOR:
7297   case ISD::FCEIL:
7298   case ISD::FRINT:
7299   case ISD::FNEARBYINT:
7300   case ISD::FPOW:
7301   case ISD::FPOWI: {
7302     RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
7303     switch(Node->getOpcode()) {
7304     case ISD::FSQRT:
7305       LC = GetFPLibCall(VT, RTLIB::SQRT_F32, RTLIB::SQRT_F64,
7306                         RTLIB::SQRT_F80, RTLIB::SQRT_PPCF128);
7307       break;
7308     case ISD::FSIN:
7309       LC = GetFPLibCall(VT, RTLIB::SIN_F32, RTLIB::SIN_F64,
7310                         RTLIB::SIN_F80, RTLIB::SIN_PPCF128);
7311       break;
7312     case ISD::FCOS:
7313       LC = GetFPLibCall(VT, RTLIB::COS_F32, RTLIB::COS_F64,
7314                         RTLIB::COS_F80, RTLIB::COS_PPCF128);
7315       break;
7316     case ISD::FLOG:
7317       LC = GetFPLibCall(VT, RTLIB::LOG_F32, RTLIB::LOG_F64,
7318                         RTLIB::LOG_F80, RTLIB::LOG_PPCF128);
7319       break;
7320     case ISD::FLOG2:
7321       LC = GetFPLibCall(VT, RTLIB::LOG2_F32, RTLIB::LOG2_F64,
7322                         RTLIB::LOG2_F80, RTLIB::LOG2_PPCF128);
7323       break;
7324     case ISD::FLOG10:
7325       LC = GetFPLibCall(VT, RTLIB::LOG10_F32, RTLIB::LOG10_F64,
7326                         RTLIB::LOG10_F80, RTLIB::LOG10_PPCF128);
7327       break;
7328     case ISD::FEXP:
7329       LC = GetFPLibCall(VT, RTLIB::EXP_F32, RTLIB::EXP_F64,
7330                         RTLIB::EXP_F80, RTLIB::EXP_PPCF128);
7331       break;
7332     case ISD::FEXP2:
7333       LC = GetFPLibCall(VT, RTLIB::EXP2_F32, RTLIB::EXP2_F64,
7334                         RTLIB::EXP2_F80, RTLIB::EXP2_PPCF128);
7335       break;
7336     case ISD::FTRUNC:
7337       LC = GetFPLibCall(VT, RTLIB::TRUNC_F32, RTLIB::TRUNC_F64,
7338                         RTLIB::TRUNC_F80, RTLIB::TRUNC_PPCF128);
7339       break;
7340     case ISD::FFLOOR:
7341       LC = GetFPLibCall(VT, RTLIB::FLOOR_F32, RTLIB::FLOOR_F64,
7342                         RTLIB::FLOOR_F80, RTLIB::FLOOR_PPCF128);
7343       break;
7344     case ISD::FCEIL:
7345       LC = GetFPLibCall(VT, RTLIB::CEIL_F32, RTLIB::CEIL_F64,
7346                         RTLIB::CEIL_F80, RTLIB::CEIL_PPCF128);
7347       break;
7348     case ISD::FRINT:
7349       LC = GetFPLibCall(VT, RTLIB::RINT_F32, RTLIB::RINT_F64,
7350                         RTLIB::RINT_F80, RTLIB::RINT_PPCF128);
7351       break;
7352     case ISD::FNEARBYINT:
7353       LC = GetFPLibCall(VT, RTLIB::NEARBYINT_F32, RTLIB::NEARBYINT_F64,
7354                         RTLIB::NEARBYINT_F80, RTLIB::NEARBYINT_PPCF128);
7355       break;
7356     case ISD::FPOW:
7357       LC = GetFPLibCall(VT, RTLIB::POW_F32, RTLIB::POW_F64, RTLIB::POW_F80,
7358                         RTLIB::POW_PPCF128);
7359       break;
7360     case ISD::FPOWI:
7361       LC = GetFPLibCall(VT, RTLIB::POWI_F32, RTLIB::POWI_F64, RTLIB::POWI_F80,
7362                         RTLIB::POWI_PPCF128);
7363       break;
7364     default: assert(0 && "Unreachable!");
7365     }
7366     Lo = ExpandLibCall(LC, Node, false, Hi);
7367     break;
7368   }
7369   case ISD::FABS: {
7370     if (VT == MVT::ppcf128) {
7371       SDValue Tmp;
7372       ExpandOp(Node->getOperand(0), Lo, Tmp);
7373       Hi = DAG.getNode(ISD::FABS, dl, NVT, Tmp);
7374       // lo = hi==fabs(hi) ? lo : -lo;
7375       Lo = DAG.getNode(ISD::SELECT_CC, dl, NVT, Hi, Tmp,
7376                        Lo, DAG.getNode(ISD::FNEG, dl, NVT, Lo),
7377                        DAG.getCondCode(ISD::SETEQ));
7378       break;
7379     }
7380     SDValue Mask = (VT == MVT::f64)
7381       ? DAG.getConstantFP(BitsToDouble(~(1ULL << 63)), VT)
7382       : DAG.getConstantFP(BitsToFloat(~(1U << 31)), VT);
7383     Mask = DAG.getNode(ISD::BIT_CONVERT, dl, NVT, Mask);
7384     Lo = DAG.getNode(ISD::BIT_CONVERT, dl, NVT, Node->getOperand(0));
7385     Lo = DAG.getNode(ISD::AND, dl, NVT, Lo, Mask);
7386     if (getTypeAction(NVT) == Expand)
7387       ExpandOp(Lo, Lo, Hi);
7388     break;
7389   }
7390   case ISD::FNEG: {
7391     if (VT == MVT::ppcf128) {
7392       ExpandOp(Node->getOperand(0), Lo, Hi);
7393       Lo = DAG.getNode(ISD::FNEG, dl, MVT::f64, Lo);
7394       Hi = DAG.getNode(ISD::FNEG, dl, MVT::f64, Hi);
7395       break;
7396     }
7397     SDValue Mask = (VT == MVT::f64)
7398       ? DAG.getConstantFP(BitsToDouble(1ULL << 63), VT)
7399       : DAG.getConstantFP(BitsToFloat(1U << 31), VT);
7400     Mask = DAG.getNode(ISD::BIT_CONVERT, dl, NVT, Mask);
7401     Lo = DAG.getNode(ISD::BIT_CONVERT, dl, NVT, Node->getOperand(0));
7402     Lo = DAG.getNode(ISD::XOR, dl, NVT, Lo, Mask);
7403     if (getTypeAction(NVT) == Expand)
7404       ExpandOp(Lo, Lo, Hi);
7405     break;
7406   }
7407   case ISD::FCOPYSIGN: {
7408     Lo = ExpandFCOPYSIGNToBitwiseOps(Node, NVT, DAG, TLI);
7409     if (getTypeAction(NVT) == Expand)
7410       ExpandOp(Lo, Lo, Hi);
7411     break;
7412   }
7413   case ISD::SINT_TO_FP:
7414   case ISD::UINT_TO_FP: {
7415     bool isSigned = Node->getOpcode() == ISD::SINT_TO_FP;
7416     MVT SrcVT = Node->getOperand(0).getValueType();
7417
7418     // Promote the operand if needed.  Do this before checking for
7419     // ppcf128 so conversions of i16 and i8 work.
7420     if (getTypeAction(SrcVT) == Promote) {
7421       SDValue Tmp = PromoteOp(Node->getOperand(0));
7422       Tmp = isSigned
7423         ? DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, Tmp.getValueType(), Tmp,
7424                       DAG.getValueType(SrcVT))
7425         : DAG.getZeroExtendInReg(Tmp, dl, SrcVT);
7426       Node = DAG.UpdateNodeOperands(Op, Tmp).getNode();
7427       SrcVT = Node->getOperand(0).getValueType();
7428     }
7429
7430     if (VT == MVT::ppcf128 && SrcVT == MVT::i32) {
7431       static const uint64_t zero = 0;
7432       if (isSigned) {
7433         Hi = LegalizeOp(DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f64,
7434                                     Node->getOperand(0)));
7435         Lo = DAG.getConstantFP(APFloat(APInt(64, 1, &zero)), MVT::f64);
7436       } else {
7437         static const uint64_t TwoE32[] = { 0x41f0000000000000LL, 0 };
7438         Hi = LegalizeOp(DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f64,
7439                                     Node->getOperand(0)));
7440         Lo = DAG.getConstantFP(APFloat(APInt(64, 1, &zero)), MVT::f64);
7441         Hi = DAG.getNode(ISD::BUILD_PAIR, dl, VT, Lo, Hi);
7442         // X>=0 ? {(f64)x, 0} : {(f64)x, 0} + 2^32
7443         ExpandOp(DAG.getNode(ISD::SELECT_CC, dl,
7444                              MVT::ppcf128, Node->getOperand(0),
7445                              DAG.getConstant(0, MVT::i32),
7446                              DAG.getNode(ISD::FADD, dl, MVT::ppcf128, Hi,
7447                                          DAG.getConstantFP
7448                                          (APFloat(APInt(128, 2, TwoE32)),
7449                                           MVT::ppcf128)),
7450                              Hi,
7451                              DAG.getCondCode(ISD::SETLT)),
7452                  Lo, Hi);
7453       }
7454       break;
7455     }
7456     if (VT == MVT::ppcf128 && SrcVT == MVT::i64 && !isSigned) {
7457       // si64->ppcf128 done by libcall, below
7458       static const uint64_t TwoE64[] = { 0x43f0000000000000LL, 0 };
7459       ExpandOp(DAG.getNode(ISD::SINT_TO_FP, dl, MVT::ppcf128,
7460                Node->getOperand(0)), Lo, Hi);
7461       Hi = DAG.getNode(ISD::BUILD_PAIR, dl, VT, Lo, Hi);
7462       // x>=0 ? (ppcf128)(i64)x : (ppcf128)(i64)x + 2^64
7463       ExpandOp(DAG.getNode(ISD::SELECT_CC, dl, MVT::ppcf128,
7464                            Node->getOperand(0),
7465                            DAG.getConstant(0, MVT::i64),
7466                            DAG.getNode(ISD::FADD, dl, MVT::ppcf128, Hi,
7467                                        DAG.getConstantFP
7468                                        (APFloat(APInt(128, 2, TwoE64)),
7469                                         MVT::ppcf128)),
7470                            Hi,
7471                            DAG.getCondCode(ISD::SETLT)),
7472                Lo, Hi);
7473       break;
7474     }
7475
7476     Lo = ExpandIntToFP(Node->getOpcode() == ISD::SINT_TO_FP, VT,
7477                        Node->getOperand(0), dl);
7478     if (getTypeAction(Lo.getValueType()) == Expand)
7479       // float to i32 etc. can be 'expanded' to a single node.
7480       ExpandOp(Lo, Lo, Hi);
7481     break;
7482   }
7483   }
7484
7485   // Make sure the resultant values have been legalized themselves, unless this
7486   // is a type that requires multi-step expansion.
7487   if (getTypeAction(NVT) != Expand && NVT != MVT::isVoid) {
7488     Lo = LegalizeOp(Lo);
7489     if (Hi.getNode())
7490       // Don't legalize the high part if it is expanded to a single node.
7491       Hi = LegalizeOp(Hi);
7492   }
7493
7494   // Remember in a map if the values will be reused later.
7495   bool isNew =
7496     ExpandedNodes.insert(std::make_pair(Op, std::make_pair(Lo, Hi))).second;
7497   assert(isNew && "Value already expanded?!?");
7498   isNew = isNew;
7499 }
7500
7501 /// SplitVectorOp - Given an operand of vector type, break it down into
7502 /// two smaller values, still of vector type.
7503 void SelectionDAGLegalize::SplitVectorOp(SDValue Op, SDValue &Lo,
7504                                          SDValue &Hi) {
7505   assert(Op.getValueType().isVector() && "Cannot split non-vector type!");
7506   SDNode *Node = Op.getNode();
7507   DebugLoc dl = Node->getDebugLoc();
7508   unsigned NumElements = Op.getValueType().getVectorNumElements();
7509   assert(NumElements > 1 && "Cannot split a single element vector!");
7510
7511   MVT NewEltVT = Op.getValueType().getVectorElementType();
7512
7513   unsigned NewNumElts_Lo = 1 << Log2_32(NumElements-1);
7514   unsigned NewNumElts_Hi = NumElements - NewNumElts_Lo;
7515
7516   MVT NewVT_Lo = MVT::getVectorVT(NewEltVT, NewNumElts_Lo);
7517   MVT NewVT_Hi = MVT::getVectorVT(NewEltVT, NewNumElts_Hi);
7518
7519   // See if we already split it.
7520   std::map<SDValue, std::pair<SDValue, SDValue> >::iterator I
7521     = SplitNodes.find(Op);
7522   if (I != SplitNodes.end()) {
7523     Lo = I->second.first;
7524     Hi = I->second.second;
7525     return;
7526   }
7527
7528   switch (Node->getOpcode()) {
7529   default:
7530 #ifndef NDEBUG
7531     Node->dump(&DAG);
7532 #endif
7533     assert(0 && "Unhandled operation in SplitVectorOp!");
7534   case ISD::UNDEF:
7535     Lo = DAG.getUNDEF(NewVT_Lo);
7536     Hi = DAG.getUNDEF(NewVT_Hi);
7537     break;
7538   case ISD::BUILD_PAIR:
7539     Lo = Node->getOperand(0);
7540     Hi = Node->getOperand(1);
7541     break;
7542   case ISD::INSERT_VECTOR_ELT: {
7543     if (ConstantSDNode *Idx = dyn_cast<ConstantSDNode>(Node->getOperand(2))) {
7544       SplitVectorOp(Node->getOperand(0), Lo, Hi);
7545       unsigned Index = Idx->getZExtValue();
7546       SDValue ScalarOp = Node->getOperand(1);
7547       if (Index < NewNumElts_Lo)
7548         Lo = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, NewVT_Lo, Lo, ScalarOp,
7549                          DAG.getIntPtrConstant(Index));
7550       else
7551         Hi = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, NewVT_Hi, Hi, ScalarOp,
7552                          DAG.getIntPtrConstant(Index - NewNumElts_Lo));
7553       break;
7554     }
7555     SDValue Tmp = PerformInsertVectorEltInMemory(Node->getOperand(0),
7556                                                  Node->getOperand(1),
7557                                                  Node->getOperand(2), dl);
7558     SplitVectorOp(Tmp, Lo, Hi);
7559     break;
7560   }
7561   case ISD::VECTOR_SHUFFLE: {
7562     // Build the low part.
7563     SDValue Mask = Node->getOperand(2);
7564     SmallVector<SDValue, 8> Ops;
7565     MVT PtrVT = TLI.getPointerTy();
7566
7567     // Insert all of the elements from the input that are needed.  We use
7568     // buildvector of extractelement here because the input vectors will have
7569     // to be legalized, so this makes the code simpler.
7570     for (unsigned i = 0; i != NewNumElts_Lo; ++i) {
7571       SDValue IdxNode = Mask.getOperand(i);
7572       if (IdxNode.getOpcode() == ISD::UNDEF) {
7573         Ops.push_back(DAG.getUNDEF(NewEltVT));
7574         continue;
7575       }
7576       unsigned Idx = cast<ConstantSDNode>(IdxNode)->getZExtValue();
7577       SDValue InVec = Node->getOperand(0);
7578       if (Idx >= NumElements) {
7579         InVec = Node->getOperand(1);
7580         Idx -= NumElements;
7581       }
7582       Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, NewEltVT, InVec,
7583                                 DAG.getConstant(Idx, PtrVT)));
7584     }
7585     Lo = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT_Lo, &Ops[0], Ops.size());
7586     Ops.clear();
7587
7588     for (unsigned i = NewNumElts_Lo; i != NumElements; ++i) {
7589       SDValue IdxNode = Mask.getOperand(i);
7590       if (IdxNode.getOpcode() == ISD::UNDEF) {
7591         Ops.push_back(DAG.getUNDEF(NewEltVT));
7592         continue;
7593       }
7594       unsigned Idx = cast<ConstantSDNode>(IdxNode)->getZExtValue();
7595       SDValue InVec = Node->getOperand(0);
7596       if (Idx >= NumElements) {
7597         InVec = Node->getOperand(1);
7598         Idx -= NumElements;
7599       }
7600       Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, NewEltVT, InVec,
7601                                 DAG.getConstant(Idx, PtrVT)));
7602     }
7603     Hi = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT_Hi, &Ops[0], Ops.size());
7604     break;
7605   }
7606   case ISD::BUILD_VECTOR: {
7607     SmallVector<SDValue, 8> LoOps(Node->op_begin(),
7608                                   Node->op_begin()+NewNumElts_Lo);
7609     Lo = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT_Lo, &LoOps[0], LoOps.size());
7610
7611     SmallVector<SDValue, 8> HiOps(Node->op_begin()+NewNumElts_Lo,
7612                                   Node->op_end());
7613     Hi = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT_Hi, &HiOps[0], HiOps.size());
7614     break;
7615   }
7616   case ISD::CONCAT_VECTORS: {
7617     // FIXME: Handle non-power-of-two vectors?
7618     unsigned NewNumSubvectors = Node->getNumOperands() / 2;
7619     if (NewNumSubvectors == 1) {
7620       Lo = Node->getOperand(0);
7621       Hi = Node->getOperand(1);
7622     } else {
7623       SmallVector<SDValue, 8> LoOps(Node->op_begin(),
7624                                     Node->op_begin()+NewNumSubvectors);
7625       Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewVT_Lo,
7626                        &LoOps[0], LoOps.size());
7627
7628       SmallVector<SDValue, 8> HiOps(Node->op_begin()+NewNumSubvectors,
7629                                     Node->op_end());
7630       Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewVT_Hi,
7631                        &HiOps[0], HiOps.size());
7632     }
7633     break;
7634   }
7635   case ISD::EXTRACT_SUBVECTOR: {
7636     SDValue Vec = Op.getOperand(0);
7637     SDValue Idx = Op.getOperand(1);
7638     MVT     IdxVT = Idx.getValueType();
7639
7640     Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NewVT_Lo, Vec, Idx);
7641     ConstantSDNode *CIdx = dyn_cast<ConstantSDNode>(Idx);
7642     if (CIdx) {
7643       Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NewVT_Hi, Vec,
7644                        DAG.getConstant(CIdx->getZExtValue() + NewNumElts_Lo,
7645                                        IdxVT));
7646     } else {
7647       Idx = DAG.getNode(ISD::ADD, dl, IdxVT, Idx,
7648                         DAG.getConstant(NewNumElts_Lo, IdxVT));
7649       Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NewVT_Hi, Vec, Idx);
7650     }
7651     break;
7652   }
7653   case ISD::SELECT: {
7654     SDValue Cond = Node->getOperand(0);
7655
7656     SDValue LL, LH, RL, RH;
7657     SplitVectorOp(Node->getOperand(1), LL, LH);
7658     SplitVectorOp(Node->getOperand(2), RL, RH);
7659
7660     if (Cond.getValueType().isVector()) {
7661       // Handle a vector merge.
7662       SDValue CL, CH;
7663       SplitVectorOp(Cond, CL, CH);
7664       Lo = DAG.getNode(Node->getOpcode(), dl, NewVT_Lo, CL, LL, RL);
7665       Hi = DAG.getNode(Node->getOpcode(), dl, NewVT_Hi, CH, LH, RH);
7666     } else {
7667       // Handle a simple select with vector operands.
7668       Lo = DAG.getNode(Node->getOpcode(), dl, NewVT_Lo, Cond, LL, RL);
7669       Hi = DAG.getNode(Node->getOpcode(), dl, NewVT_Hi, Cond, LH, RH);
7670     }
7671     break;
7672   }
7673   case ISD::SELECT_CC: {
7674     SDValue CondLHS = Node->getOperand(0);
7675     SDValue CondRHS = Node->getOperand(1);
7676     SDValue CondCode = Node->getOperand(4);
7677
7678     SDValue LL, LH, RL, RH;
7679     SplitVectorOp(Node->getOperand(2), LL, LH);
7680     SplitVectorOp(Node->getOperand(3), RL, RH);
7681
7682     // Handle a simple select with vector operands.
7683     Lo = DAG.getNode(ISD::SELECT_CC, dl, NewVT_Lo, CondLHS, CondRHS,
7684                      LL, RL, CondCode);
7685     Hi = DAG.getNode(ISD::SELECT_CC, dl, NewVT_Hi, CondLHS, CondRHS,
7686                      LH, RH, CondCode);
7687     break;
7688   }
7689   case ISD::VSETCC: {
7690     SDValue LL, LH, RL, RH;
7691     SplitVectorOp(Node->getOperand(0), LL, LH);
7692     SplitVectorOp(Node->getOperand(1), RL, RH);
7693     Lo = DAG.getNode(ISD::VSETCC, dl, NewVT_Lo, LL, RL, Node->getOperand(2));
7694     Hi = DAG.getNode(ISD::VSETCC, dl, NewVT_Hi, LH, RH, Node->getOperand(2));
7695     break;
7696   }
7697   case ISD::ADD:
7698   case ISD::SUB:
7699   case ISD::MUL:
7700   case ISD::FADD:
7701   case ISD::FSUB:
7702   case ISD::FMUL:
7703   case ISD::SDIV:
7704   case ISD::UDIV:
7705   case ISD::FDIV:
7706   case ISD::FPOW:
7707   case ISD::AND:
7708   case ISD::OR:
7709   case ISD::XOR:
7710   case ISD::UREM:
7711   case ISD::SREM:
7712   case ISD::FREM:
7713   case ISD::SHL:
7714   case ISD::SRA:
7715   case ISD::SRL: {
7716     SDValue LL, LH, RL, RH;
7717     SplitVectorOp(Node->getOperand(0), LL, LH);
7718     SplitVectorOp(Node->getOperand(1), RL, RH);
7719
7720     Lo = DAG.getNode(Node->getOpcode(), dl, NewVT_Lo, LL, RL);
7721     Hi = DAG.getNode(Node->getOpcode(), dl, NewVT_Hi, LH, RH);
7722     break;
7723   }
7724   case ISD::FP_ROUND:
7725   case ISD::FPOWI: {
7726     SDValue L, H;
7727     SplitVectorOp(Node->getOperand(0), L, H);
7728
7729     Lo = DAG.getNode(Node->getOpcode(), dl, NewVT_Lo, L, Node->getOperand(1));
7730     Hi = DAG.getNode(Node->getOpcode(), dl, NewVT_Hi, H, Node->getOperand(1));
7731     break;
7732   }
7733   case ISD::CTTZ:
7734   case ISD::CTLZ:
7735   case ISD::CTPOP:
7736   case ISD::FNEG:
7737   case ISD::FABS:
7738   case ISD::FSQRT:
7739   case ISD::FSIN:
7740   case ISD::FCOS:
7741   case ISD::FLOG:
7742   case ISD::FLOG2:
7743   case ISD::FLOG10:
7744   case ISD::FEXP:
7745   case ISD::FEXP2:
7746   case ISD::FP_TO_SINT:
7747   case ISD::FP_TO_UINT:
7748   case ISD::SINT_TO_FP:
7749   case ISD::UINT_TO_FP:
7750   case ISD::TRUNCATE:
7751   case ISD::ANY_EXTEND:
7752   case ISD::SIGN_EXTEND:
7753   case ISD::ZERO_EXTEND:
7754   case ISD::FP_EXTEND: {
7755     SDValue L, H;
7756     SplitVectorOp(Node->getOperand(0), L, H);
7757
7758     Lo = DAG.getNode(Node->getOpcode(), dl, NewVT_Lo, L);
7759     Hi = DAG.getNode(Node->getOpcode(), dl, NewVT_Hi, H);
7760     break;
7761   }
7762   case ISD::CONVERT_RNDSAT: {
7763     ISD::CvtCode CvtCode = cast<CvtRndSatSDNode>(Node)->getCvtCode();
7764     SDValue L, H;
7765     SplitVectorOp(Node->getOperand(0), L, H);
7766     SDValue DTyOpL = DAG.getValueType(NewVT_Lo);
7767     SDValue DTyOpH = DAG.getValueType(NewVT_Hi);
7768     SDValue STyOpL = DAG.getValueType(L.getValueType());
7769     SDValue STyOpH = DAG.getValueType(H.getValueType());
7770
7771     SDValue RndOp = Node->getOperand(3);
7772     SDValue SatOp = Node->getOperand(4);
7773
7774     Lo = DAG.getConvertRndSat(NewVT_Lo, dl, L, DTyOpL, STyOpL,
7775                               RndOp, SatOp, CvtCode);
7776     Hi = DAG.getConvertRndSat(NewVT_Hi, dl, H, DTyOpH, STyOpH,
7777                               RndOp, SatOp, CvtCode);
7778     break;
7779   }
7780   case ISD::LOAD: {
7781     LoadSDNode *LD = cast<LoadSDNode>(Node);
7782     SDValue Ch = LD->getChain();
7783     SDValue Ptr = LD->getBasePtr();
7784     ISD::LoadExtType ExtType = LD->getExtensionType();
7785     const Value *SV = LD->getSrcValue();
7786     int SVOffset = LD->getSrcValueOffset();
7787     MVT MemoryVT = LD->getMemoryVT();
7788     unsigned Alignment = LD->getAlignment();
7789     bool isVolatile = LD->isVolatile();
7790
7791     assert(LD->isUnindexed() && "Indexed vector loads are not supported yet!");
7792     SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
7793
7794     MVT MemNewEltVT = MemoryVT.getVectorElementType();
7795     MVT MemNewVT_Lo = MVT::getVectorVT(MemNewEltVT, NewNumElts_Lo);
7796     MVT MemNewVT_Hi = MVT::getVectorVT(MemNewEltVT, NewNumElts_Hi);
7797
7798     Lo = DAG.getLoad(ISD::UNINDEXED, dl, ExtType,
7799                      NewVT_Lo, Ch, Ptr, Offset,
7800                      SV, SVOffset, MemNewVT_Lo, isVolatile, Alignment);
7801     unsigned IncrementSize = NewNumElts_Lo * MemNewEltVT.getSizeInBits()/8;
7802     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
7803                       DAG.getIntPtrConstant(IncrementSize));
7804     SVOffset += IncrementSize;
7805     Alignment = MinAlign(Alignment, IncrementSize);
7806     Hi = DAG.getLoad(ISD::UNINDEXED, dl, ExtType,
7807                      NewVT_Hi, Ch, Ptr, Offset,
7808                      SV, SVOffset, MemNewVT_Hi, isVolatile, Alignment);
7809
7810     // Build a factor node to remember that this load is independent of the
7811     // other one.
7812     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
7813                              Hi.getValue(1));
7814
7815     // Remember that we legalized the chain.
7816     AddLegalizedOperand(Op.getValue(1), LegalizeOp(TF));
7817     break;
7818   }
7819   case ISD::BIT_CONVERT: {
7820     // We know the result is a vector.  The input may be either a vector or a
7821     // scalar value.
7822     SDValue InOp = Node->getOperand(0);
7823     if (!InOp.getValueType().isVector() ||
7824         InOp.getValueType().getVectorNumElements() == 1) {
7825       // The input is a scalar or single-element vector.
7826       // Lower to a store/load so that it can be split.
7827       // FIXME: this could be improved probably.
7828       unsigned LdAlign = TLI.getTargetData()->
7829         getPrefTypeAlignment(Op.getValueType().getTypeForMVT());
7830       SDValue Ptr = DAG.CreateStackTemporary(InOp.getValueType(), LdAlign);
7831       int FI = cast<FrameIndexSDNode>(Ptr.getNode())->getIndex();
7832
7833       SDValue St = DAG.getStore(DAG.getEntryNode(), dl,
7834                                 InOp, Ptr,
7835                                 PseudoSourceValue::getFixedStack(FI), 0);
7836       InOp = DAG.getLoad(Op.getValueType(), dl, St, Ptr,
7837                          PseudoSourceValue::getFixedStack(FI), 0);
7838     }
7839     // Split the vector and convert each of the pieces now.
7840     SplitVectorOp(InOp, Lo, Hi);
7841     Lo = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT_Lo, Lo);
7842     Hi = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT_Hi, Hi);
7843     break;
7844   }
7845   }
7846
7847   // Remember in a map if the values will be reused later.
7848   bool isNew =
7849     SplitNodes.insert(std::make_pair(Op, std::make_pair(Lo, Hi))).second;
7850   assert(isNew && "Value already split?!?");
7851   isNew = isNew;
7852 }
7853
7854
7855 /// ScalarizeVectorOp - Given an operand of single-element vector type
7856 /// (e.g. v1f32), convert it into the equivalent operation that returns a
7857 /// scalar (e.g. f32) value.
7858 SDValue SelectionDAGLegalize::ScalarizeVectorOp(SDValue Op) {
7859   assert(Op.getValueType().isVector() && "Bad ScalarizeVectorOp invocation!");
7860   SDNode *Node = Op.getNode();
7861   DebugLoc dl = Node->getDebugLoc();
7862   MVT NewVT = Op.getValueType().getVectorElementType();
7863   assert(Op.getValueType().getVectorNumElements() == 1);
7864
7865   // See if we already scalarized it.
7866   std::map<SDValue, SDValue>::iterator I = ScalarizedNodes.find(Op);
7867   if (I != ScalarizedNodes.end()) return I->second;
7868
7869   SDValue Result;
7870   switch (Node->getOpcode()) {
7871   default:
7872 #ifndef NDEBUG
7873     Node->dump(&DAG); cerr << "\n";
7874 #endif
7875     assert(0 && "Unknown vector operation in ScalarizeVectorOp!");
7876   case ISD::ADD:
7877   case ISD::FADD:
7878   case ISD::SUB:
7879   case ISD::FSUB:
7880   case ISD::MUL:
7881   case ISD::FMUL:
7882   case ISD::SDIV:
7883   case ISD::UDIV:
7884   case ISD::FDIV:
7885   case ISD::SREM:
7886   case ISD::UREM:
7887   case ISD::FREM:
7888   case ISD::FPOW:
7889   case ISD::AND:
7890   case ISD::OR:
7891   case ISD::XOR:
7892     Result = DAG.getNode(Node->getOpcode(), dl,
7893                          NewVT,
7894                          ScalarizeVectorOp(Node->getOperand(0)),
7895                          ScalarizeVectorOp(Node->getOperand(1)));
7896     break;
7897   case ISD::FNEG:
7898   case ISD::FABS:
7899   case ISD::FSQRT:
7900   case ISD::FSIN:
7901   case ISD::FCOS:
7902   case ISD::FLOG:
7903   case ISD::FLOG2:
7904   case ISD::FLOG10:
7905   case ISD::FEXP:
7906   case ISD::FEXP2:
7907   case ISD::FP_TO_SINT:
7908   case ISD::FP_TO_UINT:
7909   case ISD::SINT_TO_FP:
7910   case ISD::UINT_TO_FP:
7911   case ISD::SIGN_EXTEND:
7912   case ISD::ZERO_EXTEND:
7913   case ISD::ANY_EXTEND:
7914   case ISD::TRUNCATE:
7915   case ISD::FP_EXTEND:
7916     Result = DAG.getNode(Node->getOpcode(), dl,
7917                          NewVT,
7918                          ScalarizeVectorOp(Node->getOperand(0)));
7919     break;
7920   case ISD::CONVERT_RNDSAT: {
7921     SDValue Op0 = ScalarizeVectorOp(Node->getOperand(0));
7922     Result = DAG.getConvertRndSat(NewVT, dl, Op0,
7923                                   DAG.getValueType(NewVT),
7924                                   DAG.getValueType(Op0.getValueType()),
7925                                   Node->getOperand(3),
7926                                   Node->getOperand(4),
7927                                   cast<CvtRndSatSDNode>(Node)->getCvtCode());
7928     break;
7929   }
7930   case ISD::FPOWI:
7931   case ISD::FP_ROUND:
7932     Result = DAG.getNode(Node->getOpcode(), dl,
7933                          NewVT,
7934                          ScalarizeVectorOp(Node->getOperand(0)),
7935                          Node->getOperand(1));
7936     break;
7937   case ISD::LOAD: {
7938     LoadSDNode *LD = cast<LoadSDNode>(Node);
7939     SDValue Ch = LegalizeOp(LD->getChain());     // Legalize the chain.
7940     SDValue Ptr = LegalizeOp(LD->getBasePtr());  // Legalize the pointer.
7941     ISD::LoadExtType ExtType = LD->getExtensionType();
7942     const Value *SV = LD->getSrcValue();
7943     int SVOffset = LD->getSrcValueOffset();
7944     MVT MemoryVT = LD->getMemoryVT();
7945     unsigned Alignment = LD->getAlignment();
7946     bool isVolatile = LD->isVolatile();
7947
7948     assert(LD->isUnindexed() && "Indexed vector loads are not supported yet!");
7949     SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
7950
7951     Result = DAG.getLoad(ISD::UNINDEXED, dl, ExtType,
7952                          NewVT, Ch, Ptr, Offset, SV, SVOffset,
7953                          MemoryVT.getVectorElementType(),
7954                          isVolatile, Alignment);
7955
7956     // Remember that we legalized the chain.
7957     AddLegalizedOperand(Op.getValue(1), LegalizeOp(Result.getValue(1)));
7958     break;
7959   }
7960   case ISD::BUILD_VECTOR:
7961     Result = Node->getOperand(0);
7962     break;
7963   case ISD::INSERT_VECTOR_ELT:
7964     // Returning the inserted scalar element.
7965     Result = Node->getOperand(1);
7966     break;
7967   case ISD::CONCAT_VECTORS:
7968     assert(Node->getOperand(0).getValueType() == NewVT &&
7969            "Concat of non-legal vectors not yet supported!");
7970     Result = Node->getOperand(0);
7971     break;
7972   case ISD::VECTOR_SHUFFLE: {
7973     // Figure out if the scalar is the LHS or RHS and return it.
7974     SDValue EltNum = Node->getOperand(2).getOperand(0);
7975     if (cast<ConstantSDNode>(EltNum)->getZExtValue())
7976       Result = ScalarizeVectorOp(Node->getOperand(1));
7977     else
7978       Result = ScalarizeVectorOp(Node->getOperand(0));
7979     break;
7980   }
7981   case ISD::EXTRACT_SUBVECTOR:
7982     Result = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, NewVT,
7983                          Node->getOperand(0), Node->getOperand(1));
7984     break;
7985   case ISD::BIT_CONVERT: {
7986     SDValue Op0 = Op.getOperand(0);
7987     if (Op0.getValueType().isVector() &&
7988         Op0.getValueType().getVectorNumElements() == 1)
7989       Op0 = ScalarizeVectorOp(Op0);
7990     Result = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, Op0);
7991     break;
7992   }
7993   case ISD::SELECT:
7994     Result = DAG.getNode(ISD::SELECT, dl, NewVT, Op.getOperand(0),
7995                          ScalarizeVectorOp(Op.getOperand(1)),
7996                          ScalarizeVectorOp(Op.getOperand(2)));
7997     break;
7998   case ISD::SELECT_CC:
7999     Result = DAG.getNode(ISD::SELECT_CC, dl, NewVT, Node->getOperand(0),
8000                          Node->getOperand(1),
8001                          ScalarizeVectorOp(Op.getOperand(2)),
8002                          ScalarizeVectorOp(Op.getOperand(3)),
8003                          Node->getOperand(4));
8004     break;
8005   case ISD::VSETCC: {
8006     SDValue Op0 = ScalarizeVectorOp(Op.getOperand(0));
8007     SDValue Op1 = ScalarizeVectorOp(Op.getOperand(1));
8008     Result = DAG.getNode(ISD::SETCC, dl,
8009                          TLI.getSetCCResultType(Op0.getValueType()),
8010                          Op0, Op1, Op.getOperand(2));
8011     Result = DAG.getNode(ISD::SELECT, dl, NewVT, Result,
8012                          DAG.getConstant(-1ULL, NewVT),
8013                          DAG.getConstant(0ULL, NewVT));
8014     break;
8015   }
8016   }
8017
8018   if (TLI.isTypeLegal(NewVT))
8019     Result = LegalizeOp(Result);
8020   bool isNew = ScalarizedNodes.insert(std::make_pair(Op, Result)).second;
8021   assert(isNew && "Value already scalarized?");
8022   isNew = isNew;
8023   return Result;
8024 }
8025
8026
8027 SDValue SelectionDAGLegalize::WidenVectorOp(SDValue Op, MVT WidenVT) {
8028   std::map<SDValue, SDValue>::iterator I = WidenNodes.find(Op);
8029   if (I != WidenNodes.end()) return I->second;
8030
8031   MVT VT = Op.getValueType();
8032   assert(VT.isVector() && "Cannot widen non-vector type!");
8033
8034   SDValue Result;
8035   SDNode *Node = Op.getNode();
8036   DebugLoc dl = Node->getDebugLoc();
8037   MVT EVT = VT.getVectorElementType();
8038
8039   unsigned NumElts = VT.getVectorNumElements();
8040   unsigned NewNumElts = WidenVT.getVectorNumElements();
8041   assert(NewNumElts > NumElts  && "Cannot widen to smaller type!");
8042   assert(NewNumElts < 17);
8043
8044   // When widen is called, it is assumed that it is more efficient to use a
8045   // wide type.  The default action is to widen to operation to a wider legal
8046   // vector type and then do the operation if it is legal by calling LegalizeOp
8047   // again.  If there is no vector equivalent, we will unroll the operation, do
8048   // it, and rebuild the vector.  If most of the operations are vectorizible to
8049   // the legal type, the resulting code will be more efficient.  If this is not
8050   // the case, the resulting code will preform badly as we end up generating
8051   // code to pack/unpack the results. It is the function that calls widen
8052   // that is responsible for seeing this doesn't happen.
8053   switch (Node->getOpcode()) {
8054   default:
8055 #ifndef NDEBUG
8056       Node->dump(&DAG);
8057 #endif
8058       assert(0 && "Unexpected operation in WidenVectorOp!");
8059       break;
8060   case ISD::CopyFromReg:
8061     assert(0 && "CopyFromReg doesn't need widening!");
8062   case ISD::Constant:
8063   case ISD::ConstantFP:
8064     // To build a vector of these elements, clients should call BuildVector
8065     // and with each element instead of creating a node with a vector type
8066     assert(0 && "Unexpected operation in WidenVectorOp!");
8067   case ISD::VAARG:
8068     // Variable Arguments with vector types doesn't make any sense to me
8069     assert(0 && "Unexpected operation in WidenVectorOp!");
8070     break;
8071   case ISD::UNDEF:
8072     Result = DAG.getUNDEF(WidenVT);
8073     break;
8074   case ISD::BUILD_VECTOR: {
8075     // Build a vector with undefined for the new nodes
8076     SDValueVector NewOps(Node->op_begin(), Node->op_end());
8077     for (unsigned i = NumElts; i < NewNumElts; ++i) {
8078       NewOps.push_back(DAG.getUNDEF(EVT));
8079     }
8080     Result = DAG.getNode(ISD::BUILD_VECTOR, dl, WidenVT,
8081                          &NewOps[0], NewOps.size());
8082     break;
8083   }
8084   case ISD::INSERT_VECTOR_ELT: {
8085     SDValue Tmp1 = WidenVectorOp(Node->getOperand(0), WidenVT);
8086     Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, WidenVT, Tmp1,
8087                          Node->getOperand(1), Node->getOperand(2));
8088     break;
8089   }
8090   case ISD::VECTOR_SHUFFLE: {
8091     SDValue Tmp1 = WidenVectorOp(Node->getOperand(0), WidenVT);
8092     SDValue Tmp2 = WidenVectorOp(Node->getOperand(1), WidenVT);
8093     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Node);
8094     SmallVector<int, 8> NewMask;
8095     for (unsigned i = 0; i < NumElts; ++i) {
8096       int Idx = SVOp->getMaskElt(i);
8097       if (Idx < (int)NumElts)
8098         NewMask.push_back(Idx);
8099       else
8100         NewMask.push_back(Idx + NewNumElts - NumElts);
8101     }
8102     for (unsigned i = NumElts; i < NewNumElts; ++i)
8103       NewMask.push_back(-1);
8104     
8105     Result = DAG.getVectorShuffle(WidenVT, dl, Tmp1, Tmp2, &NewMask[0]);
8106     break;
8107   }
8108   case ISD::LOAD: {
8109     // If the load widen returns true, we can use a single load for the
8110     // vector.  Otherwise, it is returning a token factor for multiple
8111     // loads.
8112     SDValue TFOp;
8113     if (LoadWidenVectorOp(Result, TFOp, Op, WidenVT))
8114       AddLegalizedOperand(Op.getValue(1), LegalizeOp(TFOp.getValue(1)));
8115     else
8116       AddLegalizedOperand(Op.getValue(1), LegalizeOp(TFOp.getValue(0)));
8117     break;
8118   }
8119
8120   case ISD::BIT_CONVERT: {
8121     SDValue Tmp1 = Node->getOperand(0);
8122     // Converts between two different types so we need to determine
8123     // the correct widen type for the input operand.
8124     MVT InVT = Tmp1.getValueType();
8125     unsigned WidenSize = WidenVT.getSizeInBits();
8126     if (InVT.isVector()) {
8127       MVT InEltVT = InVT.getVectorElementType();
8128       unsigned InEltSize = InEltVT.getSizeInBits();
8129       assert(WidenSize % InEltSize == 0 &&
8130              "can not widen bit convert that are not multiple of element type");
8131       MVT NewInWidenVT = MVT::getVectorVT(InEltVT, WidenSize / InEltSize);
8132       Tmp1 = WidenVectorOp(Tmp1, NewInWidenVT);
8133       assert(Tmp1.getValueType().getSizeInBits() == WidenVT.getSizeInBits());
8134       Result = DAG.getNode(ISD::BIT_CONVERT, dl, WidenVT, Tmp1);
8135     } else {
8136       // If the result size is a multiple of the input size, widen the input
8137       // and then convert.
8138       unsigned InSize = InVT.getSizeInBits();
8139       assert(WidenSize % InSize == 0 &&
8140              "can not widen bit convert that are not multiple of element type");
8141       unsigned NewNumElts = WidenSize / InSize;
8142       SmallVector<SDValue, 16> Ops(NewNumElts);
8143       SDValue UndefVal = DAG.getUNDEF(InVT);
8144       Ops[0] = Tmp1;
8145       for (unsigned i = 1; i < NewNumElts; ++i)
8146         Ops[i] = UndefVal;
8147
8148       MVT NewInVT = MVT::getVectorVT(InVT, NewNumElts);
8149       Result = DAG.getNode(ISD::BUILD_VECTOR, dl, NewInVT, &Ops[0], NewNumElts);
8150       Result = DAG.getNode(ISD::BIT_CONVERT, dl, WidenVT, Result);
8151     }
8152     break;
8153   }
8154
8155   case ISD::SINT_TO_FP:
8156   case ISD::UINT_TO_FP:
8157   case ISD::FP_TO_SINT:
8158   case ISD::FP_TO_UINT:
8159   case ISD::FP_ROUND: {
8160     SDValue Tmp1 = Node->getOperand(0);
8161     // Converts between two different types so we need to determine
8162     // the correct widen type for the input operand.
8163     MVT TVT = Tmp1.getValueType();
8164     assert(TVT.isVector() && "can not widen non vector type");
8165     MVT TEVT = TVT.getVectorElementType();
8166     MVT TWidenVT =  MVT::getVectorVT(TEVT, NewNumElts);
8167     Tmp1 = WidenVectorOp(Tmp1, TWidenVT);
8168     assert(Tmp1.getValueType().getVectorNumElements() == NewNumElts);
8169     Result = DAG.getNode(Node->getOpcode(), dl, WidenVT, Tmp1);
8170     break;
8171   }
8172
8173   case ISD::FP_EXTEND:
8174     assert(0 && "Case not implemented.  Dynamically dead with 2 FP types!");
8175   case ISD::TRUNCATE:
8176   case ISD::SIGN_EXTEND:
8177   case ISD::ZERO_EXTEND:
8178   case ISD::ANY_EXTEND:
8179   case ISD::SIGN_EXTEND_INREG:
8180   case ISD::FABS:
8181   case ISD::FNEG:
8182   case ISD::FSQRT:
8183   case ISD::FSIN:
8184   case ISD::FCOS:
8185   case ISD::CTPOP:
8186   case ISD::CTTZ:
8187   case ISD::CTLZ: {
8188     // Unary op widening
8189     SDValue Tmp1;
8190     Tmp1 = WidenVectorOp(Node->getOperand(0), WidenVT);
8191     assert(Tmp1.getValueType() == WidenVT);
8192     Result = DAG.getNode(Node->getOpcode(), dl, WidenVT, Tmp1);
8193     break;
8194   }
8195   case ISD::CONVERT_RNDSAT: {
8196     SDValue RndOp = Node->getOperand(3);
8197     SDValue SatOp = Node->getOperand(4);
8198     SDValue SrcOp = Node->getOperand(0);
8199
8200     // Converts between two different types so we need to determine
8201     // the correct widen type for the input operand.
8202     MVT SVT = SrcOp.getValueType();
8203     assert(SVT.isVector() && "can not widen non vector type");
8204     MVT SEVT = SVT.getVectorElementType();
8205     MVT SWidenVT =  MVT::getVectorVT(SEVT, NewNumElts);
8206
8207     SrcOp = WidenVectorOp(SrcOp, SWidenVT);
8208     assert(SrcOp.getValueType() == WidenVT);
8209     SDValue DTyOp = DAG.getValueType(WidenVT);
8210     SDValue STyOp = DAG.getValueType(SrcOp.getValueType());
8211     ISD::CvtCode CvtCode = cast<CvtRndSatSDNode>(Node)->getCvtCode();
8212
8213     Result = DAG.getConvertRndSat(WidenVT, dl, SrcOp, DTyOp, STyOp,
8214                                   RndOp, SatOp, CvtCode);
8215     break;
8216   }
8217   case ISD::FPOW:
8218   case ISD::FPOWI:
8219   case ISD::ADD:
8220   case ISD::SUB:
8221   case ISD::MUL:
8222   case ISD::MULHS:
8223   case ISD::MULHU:
8224   case ISD::AND:
8225   case ISD::OR:
8226   case ISD::XOR:
8227   case ISD::FADD:
8228   case ISD::FSUB:
8229   case ISD::FMUL:
8230   case ISD::SDIV:
8231   case ISD::SREM:
8232   case ISD::FDIV:
8233   case ISD::FREM:
8234   case ISD::FCOPYSIGN:
8235   case ISD::UDIV:
8236   case ISD::UREM:
8237   case ISD::BSWAP: {
8238     // Binary op widening
8239     SDValue Tmp1 = WidenVectorOp(Node->getOperand(0), WidenVT);
8240     SDValue Tmp2 = WidenVectorOp(Node->getOperand(1), WidenVT);
8241     assert(Tmp1.getValueType() == WidenVT && Tmp2.getValueType() == WidenVT);
8242     Result = DAG.getNode(Node->getOpcode(), dl, WidenVT, Tmp1, Tmp2);
8243     break;
8244   }
8245
8246   case ISD::SHL:
8247   case ISD::SRA:
8248   case ISD::SRL: {
8249     SDValue Tmp1 = WidenVectorOp(Node->getOperand(0), WidenVT);
8250     assert(Tmp1.getValueType() == WidenVT);
8251     SDValue ShOp = Node->getOperand(1);
8252     MVT ShVT = ShOp.getValueType();
8253     MVT NewShVT = MVT::getVectorVT(ShVT.getVectorElementType(),
8254                                    WidenVT.getVectorNumElements());
8255     ShOp = WidenVectorOp(ShOp, NewShVT);
8256     assert(ShOp.getValueType() == NewShVT);
8257     Result = DAG.getNode(Node->getOpcode(), dl, WidenVT, Tmp1, ShOp);
8258     break;
8259   }
8260
8261   case ISD::EXTRACT_VECTOR_ELT: {
8262     SDValue Tmp1 = WidenVectorOp(Node->getOperand(0), WidenVT);
8263     assert(Tmp1.getValueType() == WidenVT);
8264     Result = DAG.getNode(Node->getOpcode(), dl, EVT, Tmp1, Node->getOperand(1));
8265     break;
8266   }
8267   case ISD::CONCAT_VECTORS: {
8268     // We concurrently support only widen on a multiple of the incoming vector.
8269     // We could widen on a multiple of the incoming operand if necessary.
8270     unsigned NumConcat = NewNumElts / NumElts;
8271     assert(NewNumElts % NumElts == 0 && "Can widen only a multiple of vector");
8272     SDValue UndefVal = DAG.getUNDEF(VT);
8273     SmallVector<SDValue, 8> MOps;
8274     MOps.push_back(Op);
8275     for (unsigned i = 1; i != NumConcat; ++i) {
8276       MOps.push_back(UndefVal);
8277     }
8278     Result = LegalizeOp(DAG.getNode(ISD::CONCAT_VECTORS, dl, WidenVT,
8279                                     &MOps[0], MOps.size()));
8280     break;
8281   }
8282   case ISD::EXTRACT_SUBVECTOR: {
8283     SDValue Tmp1 = Node->getOperand(0);
8284     SDValue Idx = Node->getOperand(1);
8285     ConstantSDNode *CIdx = dyn_cast<ConstantSDNode>(Idx);
8286     if (CIdx && CIdx->getZExtValue() == 0) {
8287       // Since we are access the start of the vector, the incoming
8288       // vector type might be the proper.
8289       MVT Tmp1VT = Tmp1.getValueType();
8290       if (Tmp1VT == WidenVT)
8291         return Tmp1;
8292       else {
8293         unsigned Tmp1VTNumElts = Tmp1VT.getVectorNumElements();
8294         if (Tmp1VTNumElts < NewNumElts)
8295           Result = WidenVectorOp(Tmp1, WidenVT);
8296         else
8297           Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, WidenVT, Tmp1, Idx);
8298       }
8299     } else if (NewNumElts % NumElts == 0) {
8300       // Widen the extracted subvector.
8301       unsigned NumConcat = NewNumElts / NumElts;
8302       SDValue UndefVal = DAG.getUNDEF(VT);
8303       SmallVector<SDValue, 8> MOps;
8304       MOps.push_back(Op);
8305       for (unsigned i = 1; i != NumConcat; ++i) {
8306         MOps.push_back(UndefVal);
8307       }
8308       Result = LegalizeOp(DAG.getNode(ISD::CONCAT_VECTORS, dl, WidenVT,
8309                                       &MOps[0], MOps.size()));
8310     } else {
8311       assert(0 && "can not widen extract subvector");
8312      // This could be implemented using insert and build vector but I would
8313      // like to see when this happens.
8314     }
8315     break;
8316   }
8317
8318   case ISD::SELECT: {
8319     // Determine new condition widen type and widen
8320     SDValue Cond1 = Node->getOperand(0);
8321     MVT CondVT = Cond1.getValueType();
8322     assert(CondVT.isVector() && "can not widen non vector type");
8323     MVT CondEVT = CondVT.getVectorElementType();
8324     MVT CondWidenVT =  MVT::getVectorVT(CondEVT, NewNumElts);
8325     Cond1 = WidenVectorOp(Cond1, CondWidenVT);
8326     assert(Cond1.getValueType() == CondWidenVT && "Condition not widen");
8327
8328     SDValue Tmp1 = WidenVectorOp(Node->getOperand(1), WidenVT);
8329     SDValue Tmp2 = WidenVectorOp(Node->getOperand(2), WidenVT);
8330     assert(Tmp1.getValueType() == WidenVT && Tmp2.getValueType() == WidenVT);
8331     Result = DAG.getNode(Node->getOpcode(), dl, WidenVT, Cond1, Tmp1, Tmp2);
8332     break;
8333   }
8334
8335   case ISD::SELECT_CC: {
8336     // Determine new condition widen type and widen
8337     SDValue Cond1 = Node->getOperand(0);
8338     SDValue Cond2 = Node->getOperand(1);
8339     MVT CondVT = Cond1.getValueType();
8340     assert(CondVT.isVector() && "can not widen non vector type");
8341     assert(CondVT == Cond2.getValueType() && "mismatch lhs/rhs");
8342     MVT CondEVT = CondVT.getVectorElementType();
8343     MVT CondWidenVT =  MVT::getVectorVT(CondEVT, NewNumElts);
8344     Cond1 = WidenVectorOp(Cond1, CondWidenVT);
8345     Cond2 = WidenVectorOp(Cond2, CondWidenVT);
8346     assert(Cond1.getValueType() == CondWidenVT &&
8347            Cond2.getValueType() == CondWidenVT && "condition not widen");
8348
8349     SDValue Tmp1 = WidenVectorOp(Node->getOperand(2), WidenVT);
8350     SDValue Tmp2 = WidenVectorOp(Node->getOperand(3), WidenVT);
8351     assert(Tmp1.getValueType() == WidenVT && Tmp2.getValueType() == WidenVT &&
8352            "operands not widen");
8353     Result = DAG.getNode(Node->getOpcode(), dl, WidenVT, Cond1, Cond2, Tmp1,
8354                          Tmp2, Node->getOperand(4));
8355     break;
8356   }
8357   case ISD::VSETCC: {
8358     // Determine widen for the operand
8359     SDValue Tmp1 = Node->getOperand(0);
8360     MVT TmpVT = Tmp1.getValueType();
8361     assert(TmpVT.isVector() && "can not widen non vector type");
8362     MVT TmpEVT = TmpVT.getVectorElementType();
8363     MVT TmpWidenVT =  MVT::getVectorVT(TmpEVT, NewNumElts);
8364     Tmp1 = WidenVectorOp(Tmp1, TmpWidenVT);
8365     SDValue Tmp2 = WidenVectorOp(Node->getOperand(1), TmpWidenVT);
8366     Result = DAG.getNode(Node->getOpcode(), dl, WidenVT, Tmp1, Tmp2,
8367                          Node->getOperand(2));
8368     break;
8369   }
8370   case ISD::ATOMIC_CMP_SWAP:
8371   case ISD::ATOMIC_LOAD_ADD:
8372   case ISD::ATOMIC_LOAD_SUB:
8373   case ISD::ATOMIC_LOAD_AND:
8374   case ISD::ATOMIC_LOAD_OR:
8375   case ISD::ATOMIC_LOAD_XOR:
8376   case ISD::ATOMIC_LOAD_NAND:
8377   case ISD::ATOMIC_LOAD_MIN:
8378   case ISD::ATOMIC_LOAD_MAX:
8379   case ISD::ATOMIC_LOAD_UMIN:
8380   case ISD::ATOMIC_LOAD_UMAX:
8381   case ISD::ATOMIC_SWAP: {
8382     // For now, we assume that using vectors for these operations don't make
8383     // much sense so we just split it.  We return an empty result
8384     SDValue X, Y;
8385     SplitVectorOp(Op, X, Y);
8386     return Result;
8387     break;
8388   }
8389
8390   } // end switch (Node->getOpcode())
8391
8392   assert(Result.getNode() && "Didn't set a result!");
8393   if (Result != Op)
8394     Result = LegalizeOp(Result);
8395
8396   AddWidenedOperand(Op, Result);
8397   return Result;
8398 }
8399
8400 // Utility function to find a legal vector type and its associated element
8401 // type from a preferred width and whose vector type must be the same size
8402 // as the VVT.
8403 //  TLI:   Target lowering used to determine legal types
8404 //  Width: Preferred width of element type
8405 //  VVT:   Vector value type whose size we must match.
8406 // Returns VecEVT and EVT - the vector type and its associated element type
8407 static void FindWidenVecType(const TargetLowering &TLI, unsigned Width, MVT VVT,
8408                              MVT& EVT, MVT& VecEVT) {
8409   // We start with the preferred width, make it a power of 2 and see if
8410   // we can find a vector type of that width. If not, we reduce it by
8411   // another power of 2.  If we have widen the type, a vector of bytes should
8412   // always be legal.
8413   assert(TLI.isTypeLegal(VVT));
8414   unsigned EWidth = Width + 1;
8415   do {
8416     assert(EWidth > 0);
8417     EWidth =  (1 << Log2_32(EWidth-1));
8418     EVT = MVT::getIntegerVT(EWidth);
8419     unsigned NumEVT = VVT.getSizeInBits()/EWidth;
8420     VecEVT = MVT::getVectorVT(EVT, NumEVT);
8421   } while (!TLI.isTypeLegal(VecEVT) ||
8422            VVT.getSizeInBits() != VecEVT.getSizeInBits());
8423 }
8424
8425 SDValue SelectionDAGLegalize::genWidenVectorLoads(SDValueVector& LdChain,
8426                                                     SDValue   Chain,
8427                                                     SDValue   BasePtr,
8428                                                     const Value *SV,
8429                                                     int         SVOffset,
8430                                                     unsigned    Alignment,
8431                                                     bool        isVolatile,
8432                                                     unsigned    LdWidth,
8433                                                     MVT         ResType,
8434                                                     DebugLoc    dl) {
8435   // We assume that we have good rules to handle loading power of two loads so
8436   // we break down the operations to power of 2 loads.  The strategy is to
8437   // load the largest power of 2 that we can easily transform to a legal vector
8438   // and then insert into that vector, and the cast the result into the legal
8439   // vector that we want.  This avoids unnecessary stack converts.
8440   // TODO: If the Ldwidth is legal, alignment is the same as the LdWidth, and
8441   //       the load is nonvolatile, we an use a wider load for the value.
8442   // Find a vector length we can load a large chunk
8443   MVT EVT, VecEVT;
8444   unsigned EVTWidth;
8445   FindWidenVecType(TLI, LdWidth, ResType, EVT, VecEVT);
8446   EVTWidth = EVT.getSizeInBits();
8447
8448   SDValue LdOp = DAG.getLoad(EVT, dl, Chain, BasePtr, SV, SVOffset,
8449                              isVolatile, Alignment);
8450   SDValue VecOp = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecEVT, LdOp);
8451   LdChain.push_back(LdOp.getValue(1));
8452
8453   // Check if we can load the element with one instruction
8454   if (LdWidth == EVTWidth) {
8455     return DAG.getNode(ISD::BIT_CONVERT, dl, ResType, VecOp);
8456   }
8457
8458   // The vector element order is endianness dependent.
8459   unsigned Idx = 1;
8460   LdWidth -= EVTWidth;
8461   unsigned Offset = 0;
8462
8463   while (LdWidth > 0) {
8464     unsigned Increment = EVTWidth / 8;
8465     Offset += Increment;
8466     BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
8467                           DAG.getIntPtrConstant(Increment));
8468
8469     if (LdWidth < EVTWidth) {
8470       // Our current type we are using is too large, use a smaller size by
8471       // using a smaller power of 2
8472       unsigned oEVTWidth = EVTWidth;
8473       FindWidenVecType(TLI, LdWidth, ResType, EVT, VecEVT);
8474       EVTWidth = EVT.getSizeInBits();
8475       // Readjust position and vector position based on new load type
8476       Idx = Idx * (oEVTWidth/EVTWidth);
8477       VecOp = DAG.getNode(ISD::BIT_CONVERT, dl, VecEVT, VecOp);
8478     }
8479
8480     SDValue LdOp = DAG.getLoad(EVT, dl, Chain, BasePtr, SV,
8481                                SVOffset+Offset, isVolatile,
8482                                MinAlign(Alignment, Offset));
8483     LdChain.push_back(LdOp.getValue(1));
8484     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecEVT, VecOp, LdOp,
8485                         DAG.getIntPtrConstant(Idx++));
8486
8487     LdWidth -= EVTWidth;
8488   }
8489
8490   return DAG.getNode(ISD::BIT_CONVERT, dl, ResType, VecOp);
8491 }
8492
8493 bool SelectionDAGLegalize::LoadWidenVectorOp(SDValue& Result,
8494                                              SDValue& TFOp,
8495                                              SDValue Op,
8496                                              MVT NVT) {
8497   // TODO: Add support for ConcatVec and the ability to load many vector
8498   //       types (e.g., v4i8).  This will not work when a vector register
8499   //       to memory mapping is strange (e.g., vector elements are not
8500   //       stored in some sequential order).
8501
8502   // It must be true that the widen vector type is bigger than where
8503   // we need to load from.
8504   LoadSDNode *LD = cast<LoadSDNode>(Op.getNode());
8505   MVT LdVT = LD->getMemoryVT();
8506   DebugLoc dl = LD->getDebugLoc();
8507   assert(LdVT.isVector() && NVT.isVector());
8508   assert(LdVT.getVectorElementType() == NVT.getVectorElementType());
8509
8510   // Load information
8511   SDValue Chain = LD->getChain();
8512   SDValue BasePtr = LD->getBasePtr();
8513   int       SVOffset = LD->getSrcValueOffset();
8514   unsigned  Alignment = LD->getAlignment();
8515   bool      isVolatile = LD->isVolatile();
8516   const Value *SV = LD->getSrcValue();
8517   unsigned int LdWidth = LdVT.getSizeInBits();
8518
8519   // Load value as a large register
8520   SDValueVector LdChain;
8521   Result = genWidenVectorLoads(LdChain, Chain, BasePtr, SV, SVOffset,
8522                                Alignment, isVolatile, LdWidth, NVT, dl);
8523
8524   if (LdChain.size() == 1) {
8525     TFOp = LdChain[0];
8526     return true;
8527   }
8528   else {
8529     TFOp=DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
8530                      &LdChain[0], LdChain.size());
8531     return false;
8532   }
8533 }
8534
8535
8536 void SelectionDAGLegalize::genWidenVectorStores(SDValueVector& StChain,
8537                                                 SDValue   Chain,
8538                                                 SDValue   BasePtr,
8539                                                 const Value *SV,
8540                                                 int         SVOffset,
8541                                                 unsigned    Alignment,
8542                                                 bool        isVolatile,
8543                                                 SDValue     ValOp,
8544                                                 unsigned    StWidth,
8545                                                 DebugLoc    dl) {
8546   // Breaks the stores into a series of power of 2 width stores.  For any
8547   // width, we convert the vector to the vector of element size that we
8548   // want to store.  This avoids requiring a stack convert.
8549
8550   // Find a width of the element type we can store with
8551   MVT VVT = ValOp.getValueType();
8552   MVT EVT, VecEVT;
8553   unsigned EVTWidth;
8554   FindWidenVecType(TLI, StWidth, VVT, EVT, VecEVT);
8555   EVTWidth = EVT.getSizeInBits();
8556
8557   SDValue VecOp = DAG.getNode(ISD::BIT_CONVERT, dl, VecEVT, ValOp);
8558   SDValue EOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EVT, VecOp,
8559                             DAG.getIntPtrConstant(0));
8560   SDValue StOp = DAG.getStore(Chain, dl, EOp, BasePtr, SV, SVOffset,
8561                               isVolatile, Alignment);
8562   StChain.push_back(StOp);
8563
8564   // Check if we are done
8565   if (StWidth == EVTWidth) {
8566     return;
8567   }
8568
8569   unsigned Idx = 1;
8570   StWidth -= EVTWidth;
8571   unsigned Offset = 0;
8572
8573   while (StWidth > 0) {
8574     unsigned Increment = EVTWidth / 8;
8575     Offset += Increment;
8576     BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
8577                           DAG.getIntPtrConstant(Increment));
8578
8579     if (StWidth < EVTWidth) {
8580       // Our current type we are using is too large, use a smaller size by
8581       // using a smaller power of 2
8582       unsigned oEVTWidth = EVTWidth;
8583       FindWidenVecType(TLI, StWidth, VVT, EVT, VecEVT);
8584       EVTWidth = EVT.getSizeInBits();
8585       // Readjust position and vector position based on new load type
8586       Idx = Idx * (oEVTWidth/EVTWidth);
8587       VecOp = DAG.getNode(ISD::BIT_CONVERT, dl, VecEVT, VecOp);
8588     }
8589
8590     EOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EVT, VecOp,
8591                       DAG.getIntPtrConstant(Idx++));
8592     StChain.push_back(DAG.getStore(Chain, dl, EOp, BasePtr, SV,
8593                                    SVOffset + Offset, isVolatile,
8594                                    MinAlign(Alignment, Offset)));
8595     StWidth -= EVTWidth;
8596   }
8597 }
8598
8599
8600 SDValue SelectionDAGLegalize::StoreWidenVectorOp(StoreSDNode *ST,
8601                                                  SDValue Chain,
8602                                                  SDValue BasePtr) {
8603   // TODO: It might be cleaner if we can use SplitVector and have more legal
8604   //        vector types that can be stored into memory (e.g., v4xi8 can
8605   //        be stored as a word). This will not work when a vector register
8606   //        to memory mapping is strange (e.g., vector elements are not
8607   //        stored in some sequential order).
8608
8609   MVT StVT = ST->getMemoryVT();
8610   SDValue ValOp = ST->getValue();
8611   DebugLoc dl = ST->getDebugLoc();
8612
8613   // Check if we have widen this node with another value
8614   std::map<SDValue, SDValue>::iterator I = WidenNodes.find(ValOp);
8615   if (I != WidenNodes.end())
8616     ValOp = I->second;
8617
8618   MVT VVT = ValOp.getValueType();
8619
8620   // It must be true that we the widen vector type is bigger than where
8621   // we need to store.
8622   assert(StVT.isVector() && VVT.isVector());
8623   assert(StVT.bitsLT(VVT));
8624   assert(StVT.getVectorElementType() == VVT.getVectorElementType());
8625
8626   // Store value
8627   SDValueVector StChain;
8628   genWidenVectorStores(StChain, Chain, BasePtr, ST->getSrcValue(),
8629                        ST->getSrcValueOffset(), ST->getAlignment(),
8630                        ST->isVolatile(), ValOp, StVT.getSizeInBits(), dl);
8631   if (StChain.size() == 1)
8632     return StChain[0];
8633   else
8634     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
8635                        &StChain[0], StChain.size());
8636 }
8637
8638
8639 // SelectionDAG::Legalize - This is the entry point for the file.
8640 //
8641 void SelectionDAG::Legalize(bool TypesNeedLegalizing,
8642                             CodeGenOpt::Level OptLevel) {
8643   /// run - This is the main entry point to this class.
8644   ///
8645   SelectionDAGLegalize(*this, TypesNeedLegalizing, OptLevel).LegalizeDAG();
8646 }
8647