LegalizeDAG.cpp revision bc7d448f242b1bbc1031fb87cd69c285ff9aaffa
18383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner//===-- LegalizeDAG.cpp - Implement SelectionDAG::Legalize ----------------===//
28383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner//
38383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner//                     The LLVM Compiler Infrastructure
48383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner//
58383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner// This file is distributed under the University of Illinois Open Source
68383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner// License. See LICENSE.TXT for details.
78383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner//
88383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner//===----------------------------------------------------------------------===//
98383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner//
10177480b7ede0441135572d641a2497df25a7d95fChris Lattner// This file implements the SelectionDAG::Legalize method.
118383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner//
128383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner//===----------------------------------------------------------------------===//
138383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner
148383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner#include "llvm/Analysis/DebugInfo.h"
158383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner#include "llvm/CodeGen/Analysis.h"
16177480b7ede0441135572d641a2497df25a7d95fChris Lattner#include "llvm/CodeGen/MachineFunction.h"
171ff50b380e6f5549f5ddd9e6c390dcb00332e3e9Owen Anderson#include "llvm/CodeGen/MachineJumpTableInfo.h"
188383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner#include "llvm/CodeGen/SelectionDAG.h"
199819ef7742cc2e3af92a0b760fa33e30218ff7bbChris Lattner#include "llvm/Target/TargetFrameLowering.h"
202cc675180b06d0a2173365a4015606933f1a285dChris Lattner#include "llvm/Target/TargetLowering.h"
21bd3401fa98b578080e227afce940bca80137dea6Chris Lattner#include "llvm/Target/TargetData.h"
22433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner#include "llvm/Target/TargetMachine.h"
23ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner#include "llvm/CallingConv.h"
24fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump#include "llvm/Constants.h"
25fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump#include "llvm/DerivedTypes.h"
26fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump#include "llvm/LLVMContext.h"
27fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump#include "llvm/Support/Debug.h"
28fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump#include "llvm/Support/ErrorHandling.h"
298383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner#include "llvm/Support/MathExtras.h"
30177480b7ede0441135572d641a2497df25a7d95fChris Lattner#include "llvm/Support/raw_ostream.h"
3193b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar#include "llvm/ADT/DenseMap.h"
328383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner#include "llvm/ADT/SmallVector.h"
338383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner#include "llvm/ADT/SmallPtrSet.h"
34bd3401fa98b578080e227afce940bca80137dea6Chris Lattnerusing namespace llvm;
35bd3401fa98b578080e227afce940bca80137dea6Chris Lattner
3678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner//===----------------------------------------------------------------------===//
378383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner/// SelectionDAGLegalize - This takes an arbitrary SelectionDAG as input and
38177480b7ede0441135572d641a2497df25a7d95fChris Lattner/// hacks on it until the target machine can handle it.  This involves
39177480b7ede0441135572d641a2497df25a7d95fChris Lattner/// eliminating value sizes the machine cannot handle (promoting small sizes to
40177480b7ede0441135572d641a2497df25a7d95fChris Lattner/// large sizes or splitting up large values into small values) as well as
41177480b7ede0441135572d641a2497df25a7d95fChris Lattner/// eliminating operations the machine cannot handle.
42177480b7ede0441135572d641a2497df25a7d95fChris Lattner///
438383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner/// This code also does a small amount of optimization and recognition of idioms
4494019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner/// as part of its processing.  For example, if a target does not support a
4594019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner/// 'setcc' instruction efficiently, but does support 'brcc' instruction, this
4694019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner/// will attempt merge setcc and brc instructions into brcc's.
4794019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner///
4894019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattnernamespace {
4994019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattnerclass SelectionDAGLegalize : public SelectionDAG::DAGUpdateListener {
5094019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner  const TargetMachine &TM;
5194019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner  const TargetLowering &TLI;
5294019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner  SelectionDAG &DAG;
5394019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner
5494019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner  /// LegalizePosition - The iterator for walking through the node list.
5594019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner  SelectionDAG::allnodes_iterator LegalizePosition;
5694019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner
5794019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner  /// LegalizedNodes - The set of nodes which have already been legalized.
5894019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner  SmallPtrSet<SDNode *, 16> LegalizedNodes;
5994019f8e064bf84085b44c35ab0c1efb76fb94f7Chris Lattner
603e8b6631e67e01e4960a7ba4668a50c596607473Chris Lattner  // Libcall insertion helpers.
61ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner
62fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stumppublic:
63fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  explicit SelectionDAGLegalize(SelectionDAG &DAG);
64fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump
65fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  void LegalizeDAG();
66fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump
678383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattnerprivate:
688383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner  /// LegalizeOp - Legalizes the given operation.
69ae73dc1448d25b02cabc7c64c86c64371453dda8Dan Gohman  void LegalizeOp(SDNode *Node);
708383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner
718383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner  SDValue OptimizeFloatStore(StoreSDNode *ST);
72fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump
73fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  /// PerformInsertVectorEltInMemory - Some target cannot handle a variable
74c7bcbf6903a741e5252d6003916fb3624be937e5Chris Lattner  /// insertion index for the INSERT_VECTOR_ELT instruction.  In this case, it
755729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  /// is necessary to spill the vector being inserted into to memory, perform
765729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  /// the insert there, and then read the result back.
7778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  SDValue PerformInsertVectorEltInMemory(SDValue Vec, SDValue Val,
7878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner                                         SDValue Idx, DebugLoc dl);
795729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  SDValue ExpandINSERT_VECTOR_ELT(SDValue Vec, SDValue Val,
805729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                                  SDValue Idx, DebugLoc dl);
815729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
825729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  /// ShuffleWithNarrowerEltType - Return a vector shuffle operation which
835729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  /// performs the same shuffe in terms of order or result bytes, but on a type
845729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  /// whose vector element type is narrower than the original shuffle type.
855729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  /// e.g. <v4i32> <0, 1, 0, 1> -> v8i16 <0, 1, 2, 3, 0, 1, 2, 3>
865729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  SDValue ShuffleWithNarrowerEltType(EVT NVT, EVT VT, DebugLoc dl,
875729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                                     SDValue N1, SDValue N2,
88421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner                                     ArrayRef<int> Mask) const;
893cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner
906bf77500c655520a04ea8640af6dccbcf995a754Chris Lattner  void LegalizeSetCCCondCode(EVT VT, SDValue &LHS, SDValue &RHS, SDValue &CC,
91d38c14e6ed0136624a18cf8338c82f1709d804aaChris Lattner                             DebugLoc dl);
9269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
9369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  SDValue ExpandLibCall(RTLIB::Libcall LC, SDNode *Node, bool isSigned);
948383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner  SDValue ExpandLibCall(RTLIB::Libcall LC, EVT RetVT, const SDValue *Ops,
958383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner                        unsigned NumOps, bool isSigned, DebugLoc dl);
968383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner
97844731a7f1909f55935e3514c9e713a62d67662eDan Gohman  std::pair<SDValue, SDValue> ExpandChainLibCall(RTLIB::Libcall LC,
98844731a7f1909f55935e3514c9e713a62d67662eDan Gohman                                                 SDNode *Node, bool isSigned);
99844731a7f1909f55935e3514c9e713a62d67662eDan Gohman  SDValue ExpandFPLibCall(SDNode *Node, RTLIB::Libcall Call_F32,
100844731a7f1909f55935e3514c9e713a62d67662eDan Gohman                          RTLIB::Libcall Call_F64, RTLIB::Libcall Call_F80,
1018383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner                          RTLIB::Libcall Call_PPCF128);
1028383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner  SDValue ExpandIntLibCall(SDNode *Node, bool isSigned,
1038383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner                           RTLIB::Libcall Call_I8,
1048383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner                           RTLIB::Libcall Call_I16,
1058383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner                           RTLIB::Libcall Call_I32,
1068383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner                           RTLIB::Libcall Call_I64,
10793b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar                           RTLIB::Libcall Call_I128);
10802a436c48ecff9e34d50ce0a2f861e5acdd9bf3fDan Gohman  void ExpandDivRemLibCall(SDNode *Node, SmallVectorImpl<SDValue> &Results);
109bd3401fa98b578080e227afce940bca80137dea6Chris Lattner
110fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  SDValue EmitStackConvert(SDValue SrcOp, EVT SlotVT, EVT DestVT, DebugLoc dl);
111fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  SDValue ExpandBUILD_VECTOR(SDNode *Node);
112bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  SDValue ExpandSCALAR_TO_VECTOR(SDNode *Node);
113bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  void ExpandDYNAMIC_STACKALLOC(SDNode *Node,
114bd3401fa98b578080e227afce940bca80137dea6Chris Lattner                                SmallVectorImpl<SDValue> &Results);
115bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  SDValue ExpandFCOPYSIGN(SDNode *Node);
116421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  SDValue ExpandLegalINT_TO_FP(bool isSigned, SDValue LegalOp, EVT DestVT,
117421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner                               DebugLoc dl);
118f3183f6da6321c6496daa107ea5d6d48b99d9330Chris Lattner  SDValue PromoteLegalINT_TO_FP(SDValue LegalOp, EVT DestVT, bool isSigned,
119421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner                                DebugLoc dl);
120bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  SDValue PromoteLegalFP_TO_INT(SDValue LegalOp, EVT DestVT, bool isSigned,
121421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner                                DebugLoc dl);
122421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner
123421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  SDValue ExpandBSWAP(SDValue Op, DebugLoc dl);
124421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  SDValue ExpandBitCount(unsigned Opc, SDValue Op, DebugLoc dl);
125421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner
126421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  SDValue ExpandExtractFromVectorThroughStack(SDValue Op);
12720fa76ef6f7c2d3073e0960cf347af8db64708fcChris Lattner  SDValue ExpandInsertToVectorThroughStack(SDValue Op);
12893b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar  SDValue ExpandVectorBuildThroughStack(SDNode* Node);
12978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
130fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  SDValue ExpandConstantFP(ConstantFPSDNode *CFP, bool UseCP);
131421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner
132421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  std::pair<SDValue, SDValue> ExpandAtomic(SDNode *Node);
133f3183f6da6321c6496daa107ea5d6d48b99d9330Chris Lattner
134f3183f6da6321c6496daa107ea5d6d48b99d9330Chris Lattner  void ExpandNode(SDNode *Node);
135f3183f6da6321c6496daa107ea5d6d48b99d9330Chris Lattner  void PromoteNode(SDNode *Node);
136f3183f6da6321c6496daa107ea5d6d48b99d9330Chris Lattner
137f3183f6da6321c6496daa107ea5d6d48b99d9330Chris Lattner  void ForgetNode(SDNode *N) {
138f3183f6da6321c6496daa107ea5d6d48b99d9330Chris Lattner    LegalizedNodes.erase(N);
139f3183f6da6321c6496daa107ea5d6d48b99d9330Chris Lattner    if (LegalizePosition == SelectionDAG::allnodes_iterator(N))
140f3183f6da6321c6496daa107ea5d6d48b99d9330Chris Lattner      ++LegalizePosition;
141f3183f6da6321c6496daa107ea5d6d48b99d9330Chris Lattner  }
142f3183f6da6321c6496daa107ea5d6d48b99d9330Chris Lattner
143f3183f6da6321c6496daa107ea5d6d48b99d9330Chris Lattnerpublic:
144f3183f6da6321c6496daa107ea5d6d48b99d9330Chris Lattner  // DAGUpdateListener implementation.
1456f84a5feee5c7322a5145992bd4704225987909cChris Lattner  virtual void NodeDeleted(SDNode *N, SDNode *E) {
1466f84a5feee5c7322a5145992bd4704225987909cChris Lattner    ForgetNode(N);
1476f84a5feee5c7322a5145992bd4704225987909cChris Lattner  }
1486f84a5feee5c7322a5145992bd4704225987909cChris Lattner  virtual void NodeUpdated(SDNode *N) {}
149f3183f6da6321c6496daa107ea5d6d48b99d9330Chris Lattner
150f3183f6da6321c6496daa107ea5d6d48b99d9330Chris Lattner  // Node replacement helpers
151f3183f6da6321c6496daa107ea5d6d48b99d9330Chris Lattner  void ReplacedNode(SDNode *N) {
1526f84a5feee5c7322a5145992bd4704225987909cChris Lattner    if (N->use_empty()) {
153f3183f6da6321c6496daa107ea5d6d48b99d9330Chris Lattner      DAG.RemoveDeadNode(N);
154f3183f6da6321c6496daa107ea5d6d48b99d9330Chris Lattner    } else {
155f3183f6da6321c6496daa107ea5d6d48b99d9330Chris Lattner      ForgetNode(N);
156421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    }
157421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  }
158bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  void ReplaceNode(SDNode *Old, SDNode *New) {
159bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    DAG.ReplaceAllUsesWith(Old, New);
160bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    ReplacedNode(Old);
161fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  }
162fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  void ReplaceNode(SDValue Old, SDValue New) {
163bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    DAG.ReplaceAllUsesWith(Old, New);
1648383a7b7a6acdae478d4b4c2520915153b73f676Chris Lattner    ReplacedNode(Old.getNode());
165177480b7ede0441135572d641a2497df25a7d95fChris Lattner  }
16678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  void ReplaceNode(SDNode *Old, const SDValue *New) {
16778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    DAG.ReplaceAllUsesWith(Old, New);
16878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    ReplacedNode(Old);
16978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  }
17078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner};
17178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner}
17278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
17378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner/// ShuffleWithNarrowerEltType - Return a vector shuffle operation which
17478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner/// performs the same shuffe in terms of order or result bytes, but on a type
17578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner/// whose vector element type is narrower than the original shuffle type.
17678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner/// e.g. <v4i32> <0, 1, 0, 1> -> v8i16 <0, 1, 2, 3, 0, 1, 2, 3>
17778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris LattnerSDValue
17878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris LattnerSelectionDAGLegalize::ShuffleWithNarrowerEltType(EVT NVT, EVT VT,  DebugLoc dl,
17978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner                                                 SDValue N1, SDValue N2,
18078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner                                                 ArrayRef<int> Mask) const {
18178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  unsigned NumMaskElts = VT.getVectorNumElements();
18278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  unsigned NumDestElts = NVT.getVectorNumElements();
18378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  unsigned NumEltsGrowth = NumDestElts / NumMaskElts;
18478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
18578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  assert(NumEltsGrowth && "Cannot promote to vector type with fewer elts!");
18678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
18778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  if (NumEltsGrowth == 1)
18878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    return DAG.getVectorShuffle(NVT, dl, N1, N2, &Mask[0]);
18978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
19078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  SmallVector<int, 8> NewMask;
19178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  for (unsigned i = 0; i != NumMaskElts; ++i) {
19278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    int Idx = Mask[i];
19378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    for (unsigned j = 0; j != NumEltsGrowth; ++j) {
19478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner      if (Idx < 0)
19578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner        NewMask.push_back(-1);
19678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner      else
19778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner        NewMask.push_back(Idx * NumEltsGrowth + j);
19878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    }
19978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  }
20078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  assert(NewMask.size() == NumDestElts && "Non-integer NumEltsGrowth?");
20178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  assert(TLI.isShuffleMaskLegal(NewMask, NVT) && "Shuffle not legal?");
20278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  return DAG.getVectorShuffle(NVT, dl, N1, N2, &NewMask[0]);
20378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner}
20478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
20578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris LattnerSelectionDAGLegalize::SelectionDAGLegalize(SelectionDAG &dag)
20678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  : SelectionDAG::DAGUpdateListener(dag),
207c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner    TM(dag.getTarget()), TLI(dag.getTargetLoweringInfo()),
208c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner    DAG(dag) {
209fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner}
210fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner
211fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattnervoid SelectionDAGLegalize::LegalizeDAG() {
212fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner  DAG.AssignTopologicalOrder();
213fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner
214fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner  // Visit all the nodes. We start in topological order, so that we see
215fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner  // nodes with their original operands intact. Legalization can produce
216fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner  // new nodes which may themselves need to be legalized. Iterate until all
217fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner  // nodes have been legalized.
218fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner  for (;;) {
219fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner    bool AnyLegalized = false;
220fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner    for (LegalizePosition = DAG.allnodes_end();
221fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner         LegalizePosition != DAG.allnodes_begin(); ) {
222fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner      --LegalizePosition;
223fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner
224fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner      SDNode *N = LegalizePosition;
225fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner      if (LegalizedNodes.insert(N)) {
226fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner        AnyLegalized = true;
227fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner        LegalizeOp(N);
228fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner      }
229fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner    }
230fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner    if (!AnyLegalized)
231fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner      break;
232fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner
233fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner  }
234fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner
235fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner  // Remove dead nodes now.
236fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner  DAG.RemoveDeadNodes();
237fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner}
238fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner
239fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner/// ExpandConstantFP - Expands the ConstantFP node to an integer constant or
240fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner/// a load from the constant pool.
241fddcf47a249fe3a1102257deddc996ee327a85cbChris LattnerSDValue
242fddcf47a249fe3a1102257deddc996ee327a85cbChris LattnerSelectionDAGLegalize::ExpandConstantFP(ConstantFPSDNode *CFP, bool UseCP) {
243c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner  bool Extend = false;
244c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner  DebugLoc dl = CFP->getDebugLoc();
245c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner
246c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner  // If a FP immediate is precise when represented as a float and if the
247c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner  // target can do an extending load from float to double, we put it into
248c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner  // the constant pool as a float, even if it's is statically typed as a
249c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner  // double.  This shrinks FP constants and canonicalizes them for targets where
250c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner  // an FP extending load is the same cost as a normal load (such as on the x87
251c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner  // fp stack or PPC FP unit).
252c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner  EVT VT = CFP->getValueType(0);
253c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner  ConstantFP *LLVMC = const_cast<ConstantFP*>(CFP->getConstantFPValue());
254c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner  if (!UseCP) {
255c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner    assert((VT == MVT::f64 || VT == MVT::f32) && "Invalid type expansion");
256c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner    return DAG.getConstant(LLVMC->getValueAPF().bitcastToAPInt(),
257c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner                           (VT == MVT::f64) ? MVT::i64 : MVT::i32);
258c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner  }
259c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner
260c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner  EVT OrigVT = VT;
261c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner  EVT SVT = VT;
262c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner  while (SVT != MVT::f32) {
263c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner    SVT = (MVT::SimpleValueType)(SVT.getSimpleVT().SimpleTy - 1);
264c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner    if (ConstantFPSDNode::isValueValidForType(SVT, CFP->getValueAPF()) &&
265c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner        // Only do this if the target has a native EXTLOAD instruction from
266c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner        // smaller type.
267c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner        TLI.isLoadExtLegal(ISD::EXTLOAD, SVT) &&
268c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner        TLI.ShouldShrinkFPConstant(OrigVT)) {
269c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner      Type *SType = SVT.getTypeForEVT(*DAG.getContext());
270c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner      LLVMC = cast<ConstantFP>(ConstantExpr::getFPTrunc(LLVMC, SType));
271c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner      VT = SVT;
272c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner      Extend = true;
273fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner    }
274fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner  }
275c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner
276c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner  SDValue CPIdx = DAG.getConstantPool(LLVMC, TLI.getPointerTy());
277fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner  unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
278c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner  if (Extend) {
279c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner    SDValue Result =
280c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner      DAG.getExtLoad(ISD::EXTLOAD, dl, OrigVT,
281c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner                     DAG.getEntryNode(),
282c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner                     CPIdx, MachinePointerInfo::getConstantPool(),
283c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner                     VT, false, false, Alignment);
284c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner    return Result;
285c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner  }
286c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner  SDValue Result =
287c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner    DAG.getLoad(OrigVT, dl, DAG.getEntryNode(), CPIdx,
28878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner                MachinePointerInfo::getConstantPool(), false, false, false,
289fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump                Alignment);
290fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  return Result;
291fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump}
292fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump
293fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump/// ExpandUnalignedStore - Expands an unaligned store to 2 half-size stores.
294fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stumpstatic void ExpandUnalignedStore(StoreSDNode *ST, SelectionDAG &DAG,
295fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump                                 const TargetLowering &TLI,
296fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump                                 SelectionDAGLegalize *DAGLegalize) {
297fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  assert(ST->getAddressingMode() == ISD::UNINDEXED &&
298fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump         "unaligned indexed stores not implemented!");
299fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  SDValue Chain = ST->getChain();
300fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  SDValue Ptr = ST->getBasePtr();
301fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  SDValue Val = ST->getValue();
302fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  EVT VT = Val.getValueType();
303fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  int Alignment = ST->getAlignment();
304fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  DebugLoc dl = ST->getDebugLoc();
305fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump  if (ST->getMemoryVT().isFloatingPoint() ||
306fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump      ST->getMemoryVT().isVector()) {
307fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump    EVT intVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
308fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump    if (TLI.isTypeLegal(intVT)) {
309fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump      // Expand to a bitconvert of the value to the integer type of the
310fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump      // same size, then a (misaligned) int store.
311fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump      // FIXME: Does not handle truncating floating point stores!
3125729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      SDValue Result = DAG.getNode(ISD::BITCAST, dl, intVT, Val);
3135729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      Result = DAG.getStore(Chain, dl, Result, Ptr, ST->getPointerInfo(),
314e7e63fe9650fc01043c96e2bf8a1ecc19e49c5b7Chris Lattner                           ST->isVolatile(), ST->isNonTemporal(), Alignment);
3155729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      DAGLegalize->ReplaceNode(SDValue(ST, 0), Result);
3165729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      return;
3175729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    }
3185729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    // Do a (aligned) store to a stack slot, then copy from the stack slot
3195729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    // to the final destination using (unaligned) integer loads and stores.
3205729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    EVT StoredVT = ST->getMemoryVT();
321785672534d32d196d04ad022c111fde3864e0d28Chris Lattner    EVT RegVT =
3225729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      TLI.getRegisterType(*DAG.getContext(),
3235729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                          EVT::getIntegerVT(*DAG.getContext(),
3245729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                                            StoredVT.getSizeInBits()));
3255729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    unsigned StoredBytes = StoredVT.getSizeInBits() / 8;
3265729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    unsigned RegBytes = RegVT.getSizeInBits() / 8;
3275729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    unsigned NumRegs = (StoredBytes + RegBytes - 1) / RegBytes;
3285729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
3295729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    // Make sure the stack slot is also aligned for the register type.
3305729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    SDValue StackPtr = DAG.CreateStackTemporary(StoredVT, RegVT);
3315729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
3325729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    // Perform the original store, only redirected to the stack slot.
3335729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    SDValue Store = DAG.getTruncStore(Chain, dl,
3345729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                                      Val, StackPtr, MachinePointerInfo(),
3355729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                                      StoredVT, false, false, 0);
3365729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    SDValue Increment = DAG.getConstant(RegBytes, TLI.getPointerTy());
3375729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    SmallVector<SDValue, 8> Stores;
3385729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    unsigned Offset = 0;
3395729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
3405729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    // Do all but one copies using the full register width.
3415729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    for (unsigned i = 1; i < NumRegs; i++) {
3425729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      // Load one integer register's worth from the stack slot.
3435729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      SDValue Load = DAG.getLoad(RegVT, dl, Store, StackPtr,
3445729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                                 MachinePointerInfo(),
3455729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                                 false, false, false, 0);
3465729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      // Store it to the final location.  Remember the store.
3475729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, Ptr,
3485729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                                  ST->getPointerInfo().getWithOffset(Offset),
3495729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                                    ST->isVolatile(), ST->isNonTemporal(),
3505729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                                    MinAlign(ST->getAlignment(), Offset)));
3515729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      // Increment the pointers.
3525729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      Offset += RegBytes;
3535729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      StackPtr = DAG.getNode(ISD::ADD, dl, StackPtr.getValueType(), StackPtr,
3545729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                             Increment);
3555729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
3565729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    }
3575729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
3585729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    // The last store may be partial.  Do a truncating store.  On big-endian
3595729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    // machines this requires an extending load from the stack slot to ensure
3605729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    // that the bits are in the right place.
3615729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    EVT MemVT = EVT::getIntegerVT(*DAG.getContext(),
3625729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                                  8 * (StoredBytes - Offset));
3635729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
3645729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    // Load from the stack slot.
3655729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Store, StackPtr,
3665729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                                  MachinePointerInfo(),
3675729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                                  MemVT, false, false, 0);
3685729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
3695729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    Stores.push_back(DAG.getTruncStore(Load.getValue(1), dl, Load, Ptr,
3705729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                                       ST->getPointerInfo()
3715729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                                         .getWithOffset(Offset),
3725729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                                       MemVT, ST->isVolatile(),
3735729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                                       ST->isNonTemporal(),
3745729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                                       MinAlign(ST->getAlignment(), Offset)));
3755729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    // The order of the stores doesn't matter - say it with a TokenFactor.
3765729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    SDValue Result =
3775729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Stores[0],
3785729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                  Stores.size());
3795729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    DAGLegalize->ReplaceNode(SDValue(ST, 0), Result);
3805729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    return;
3815729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  }
3825729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  assert(ST->getMemoryVT().isInteger() &&
3835729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner         !ST->getMemoryVT().isVector() &&
384785672534d32d196d04ad022c111fde3864e0d28Chris Lattner         "Unaligned store of unknown type.");
3855729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // Get the half-size VT
3865729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  EVT NewStoredVT = ST->getMemoryVT().getHalfSizedIntegerVT(*DAG.getContext());
3875729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  int NumBits = NewStoredVT.getSizeInBits();
38812d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel  int IncrementSize = NumBits / 8;
3895729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
3905729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // Divide the stored value in two parts.
3915729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  SDValue ShiftAmount = DAG.getConstant(NumBits,
3925729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                                      TLI.getShiftAmountTy(Val.getValueType()));
3935729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  SDValue Lo = Val;
3945729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  SDValue Hi = DAG.getNode(ISD::SRL, dl, VT, Val, ShiftAmount);
3955729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
3965729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // Store the two parts
3975729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  SDValue Store1, Store2;
3985729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  Store1 = DAG.getTruncStore(Chain, dl, TLI.isLittleEndian()?Lo:Hi, Ptr,
3995729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                             ST->getPointerInfo(), NewStoredVT,
4009dbb42944c4d7caddab21016b24cca31019a3fafChris Lattner                             ST->isVolatile(), ST->isNonTemporal(), Alignment);
4015729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
4025729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                    DAG.getConstant(IncrementSize, TLI.getPointerTy()));
4035729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  Alignment = MinAlign(Alignment, IncrementSize);
4045729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  Store2 = DAG.getTruncStore(Chain, dl, TLI.isLittleEndian()?Hi:Lo, Ptr,
4055729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                             ST->getPointerInfo().getWithOffset(IncrementSize),
4065729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                             NewStoredVT, ST->isVolatile(), ST->isNonTemporal(),
4075729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                             Alignment);
4085729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
4095729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  SDValue Result =
4105729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2);
4115729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  DAGLegalize->ReplaceNode(SDValue(ST, 0), Result);
4125729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner}
4135729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
4145729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner/// ExpandUnalignedLoad - Expands an unaligned load to 2 half-size loads.
4155729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattnerstatic void
4165729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris LattnerExpandUnalignedLoad(LoadSDNode *LD, SelectionDAG &DAG,
4175729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                    const TargetLowering &TLI,
4185729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                    SDValue &ValResult, SDValue &ChainResult) {
4196bf77500c655520a04ea8640af6dccbcf995a754Chris Lattner  assert(LD->getAddressingMode() == ISD::UNINDEXED &&
420e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner         "unaligned indexed loads not implemented!");
421e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner  SDValue Chain = LD->getChain();
422e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner  SDValue Ptr = LD->getBasePtr();
423e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner  EVT VT = LD->getValueType(0);
424e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner  EVT LoadedVT = LD->getMemoryVT();
425e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner  DebugLoc dl = LD->getDebugLoc();
426e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner  if (VT.isFloatingPoint() || VT.isVector()) {
427e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner    EVT intVT = EVT::getIntegerVT(*DAG.getContext(), LoadedVT.getSizeInBits());
428e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner    if (TLI.isTypeLegal(intVT)) {
429e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner      // Expand to a (misaligned) integer load of the same size,
430e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner      // then bitconvert to floating point or vector.
431e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner      SDValue newLoad = DAG.getLoad(intVT, dl, Chain, Ptr, LD->getPointerInfo(),
432e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner                                    LD->isVolatile(),
433e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner                                    LD->isNonTemporal(),
434e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner                                    LD->isInvariant(), LD->getAlignment());
435e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner      SDValue Result = DAG.getNode(ISD::BITCAST, dl, LoadedVT, newLoad);
436e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner      if (VT.isFloatingPoint() && LoadedVT != VT)
437e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner        Result = DAG.getNode(ISD::FP_EXTEND, dl, VT, Result);
438e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner
439e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner      ValResult = Result;
440e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner      ChainResult = Chain;
441e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner      return;
442c7bcbf6903a741e5252d6003916fb3624be937e5Chris Lattner    }
443177480b7ede0441135572d641a2497df25a7d95fChris Lattner
444c7bcbf6903a741e5252d6003916fb3624be937e5Chris Lattner    // Copy the value to a (aligned) stack slot using (unaligned) integer
44569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    // loads and stores, then do a (aligned) load from the stack slot.
44669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    EVT RegVT = TLI.getRegisterType(*DAG.getContext(), intVT);
44769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    unsigned LoadedBytes = LoadedVT.getSizeInBits() / 8;
44869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    unsigned RegBytes = RegVT.getSizeInBits() / 8;
4495729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    unsigned NumRegs = (LoadedBytes + RegBytes - 1) / RegBytes;
450f5102a0f088e7c96f7028bf7ca1c24975c314fffChris Lattner
451f5102a0f088e7c96f7028bf7ca1c24975c314fffChris Lattner    // Make sure the stack slot is also aligned for the register type.
452fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump    SDValue StackBase = DAG.CreateStackTemporary(LoadedVT, RegVT);
453fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump
454fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump    SDValue Increment = DAG.getConstant(RegBytes, TLI.getPointerTy());
455fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump    SmallVector<SDValue, 8> Stores;
4563d86d242c69a26ba2e6102f32b00b04884c4c9b1Chris Lattner    SDValue StackPtr = StackBase;
4573d86d242c69a26ba2e6102f32b00b04884c4c9b1Chris Lattner    unsigned Offset = 0;
4583d86d242c69a26ba2e6102f32b00b04884c4c9b1Chris Lattner
45969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    // Do all but one copies using the full register width.
4603d86d242c69a26ba2e6102f32b00b04884c4c9b1Chris Lattner    for (unsigned i = 1; i < NumRegs; i++) {
4613d86d242c69a26ba2e6102f32b00b04884c4c9b1Chris Lattner      // Load one integer register's worth from the original location.
4623d86d242c69a26ba2e6102f32b00b04884c4c9b1Chris Lattner      SDValue Load = DAG.getLoad(RegVT, dl, Chain, Ptr,
46369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner                                 LD->getPointerInfo().getWithOffset(Offset),
46469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner                                 LD->isVolatile(), LD->isNonTemporal(),
4655729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                                 LD->isInvariant(),
4665729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                                 MinAlign(LD->getAlignment(), Offset));
4675729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      // Follow the load with a store to the stack slot.  Remember the store.
4685729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, StackPtr,
469177480b7ede0441135572d641a2497df25a7d95fChris Lattner                                    MachinePointerInfo(), false, false, 0));
470bd3401fa98b578080e227afce940bca80137dea6Chris Lattner      // Increment the pointers.
471bd3401fa98b578080e227afce940bca80137dea6Chris Lattner      Offset += RegBytes;
472bd3401fa98b578080e227afce940bca80137dea6Chris Lattner      Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
473177480b7ede0441135572d641a2497df25a7d95fChris Lattner      StackPtr = DAG.getNode(ISD::ADD, dl, StackPtr.getValueType(), StackPtr,
474bd3401fa98b578080e227afce940bca80137dea6Chris Lattner                             Increment);
475177480b7ede0441135572d641a2497df25a7d95fChris Lattner    }
476177480b7ede0441135572d641a2497df25a7d95fChris Lattner
477177480b7ede0441135572d641a2497df25a7d95fChris Lattner    // The last copy may be partial.  Do an extending load.
478bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    EVT MemVT = EVT::getIntegerVT(*DAG.getContext(),
479bd3401fa98b578080e227afce940bca80137dea6Chris Lattner                                  8 * (LoadedBytes - Offset));
480037c781de797242ba652db775f1f2c5d2d4eb19bChris Lattner    SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Chain, Ptr,
481bd3401fa98b578080e227afce940bca80137dea6Chris Lattner                                  LD->getPointerInfo().getWithOffset(Offset),
482bd3401fa98b578080e227afce940bca80137dea6Chris Lattner                                  MemVT, LD->isVolatile(),
48393b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar                                  LD->isNonTemporal(),
48478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner                                  MinAlign(LD->getAlignment(), Offset));
485bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    // Follow the load with a store to the stack slot.  Remember the store.
486bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    // On big-endian machines this requires a truncating store to ensure
487bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    // that the bits end up in the right place.
488bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    Stores.push_back(DAG.getTruncStore(Load.getValue(1), dl, Load, StackPtr,
489bd3401fa98b578080e227afce940bca80137dea6Chris Lattner                                       MachinePointerInfo(), MemVT,
490421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner                                       false, false, 0));
491e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner
492421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    // The order of the stores doesn't matter - say it with a TokenFactor.
493e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner    SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Stores[0],
494421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner                             Stores.size());
495421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner
496e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner    // Finally, perform the original load only redirected to the stack slot.
497421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    Load = DAG.getExtLoad(LD->getExtensionType(), dl, VT, TF, StackBase,
498e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner                          MachinePointerInfo(), LoadedVT, false, false, 0);
499c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner
500421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    // Callers expect a MERGE_VALUES node.
501421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    ValResult = Load;
50293b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar    ChainResult = TF;
50378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    return;
504e33583b7c2b4d715a24e4d668bf446af9c836e54Chris Lattner  }
505421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  assert(LoadedVT.isInteger() && !LoadedVT.isVector() &&
506421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner         "Unaligned load of unsupported type.");
507421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner
508421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  // Compute the new VT that is half the size of the old one.  This is an
509421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  // integer MVT.
510421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  unsigned NumBits = LoadedVT.getSizeInBits();
511421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  EVT NewLoadedVT;
512421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  NewLoadedVT = EVT::getIntegerVT(*DAG.getContext(), NumBits/2);
513421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  NumBits >>= 1;
514421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner
515421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  unsigned Alignment = LD->getAlignment();
516421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  unsigned IncrementSize = NumBits / 8;
517421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  ISD::LoadExtType HiExtType = LD->getExtensionType();
518421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner
519421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD.
520421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  if (HiExtType == ISD::NON_EXTLOAD)
521421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    HiExtType = ISD::ZEXTLOAD;
522421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner
523421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  // Load the value in two parts
524421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  SDValue Lo, Hi;
5253cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner  if (TLI.isLittleEndian()) {
5263cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner    Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, LD->getPointerInfo(),
5273cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner                        NewLoadedVT, LD->isVolatile(),
5283cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner                        LD->isNonTemporal(), Alignment);
5293cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner    Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
5303cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner                      DAG.getConstant(IncrementSize, TLI.getPointerTy()));
5313cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner    Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr,
532421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner                        LD->getPointerInfo().getWithOffset(IncrementSize),
533421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner                        NewLoadedVT, LD->isVolatile(),
534421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner                        LD->isNonTemporal(), MinAlign(Alignment,IncrementSize));
535421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  } else {
536421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, LD->getPointerInfo(),
537421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner                        NewLoadedVT, LD->isVolatile(),
538421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner                        LD->isNonTemporal(), Alignment);
539177480b7ede0441135572d641a2497df25a7d95fChris Lattner    Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
540421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner                      DAG.getConstant(IncrementSize, TLI.getPointerTy()));
541421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr,
542421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner                        LD->getPointerInfo().getWithOffset(IncrementSize),
543177480b7ede0441135572d641a2497df25a7d95fChris Lattner                        NewLoadedVT, LD->isVolatile(),
5449683f181746c2312c8828c79b6e25a07fb441d57Nick Lewycky                        LD->isNonTemporal(), MinAlign(Alignment,IncrementSize));
5455729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  }
5465729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
5475729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // aggregate the two parts
5485729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  SDValue ShiftAmount = DAG.getConstant(NumBits,
5495729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                                       TLI.getShiftAmountTy(Hi.getValueType()));
5505729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  SDValue Result = DAG.getNode(ISD::SHL, dl, VT, Hi, ShiftAmount);
5515729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  Result = DAG.getNode(ISD::OR, dl, VT, Result, Lo);
5525729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
5535729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
5545729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                             Hi.getValue(1));
5555729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
5565729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  ValResult = Result;
5575729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  ChainResult = TF;
5585729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner}
5595729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
5605729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner/// PerformInsertVectorEltInMemory - Some target cannot handle a variable
56179c740ff479dde322aceafe15887b162c19ea195Chris Lattner/// insertion index for the INSERT_VECTOR_ELT instruction.  In this case, it
56279c740ff479dde322aceafe15887b162c19ea195Chris Lattner/// is necessary to spill the vector being inserted into to memory, perform
5635729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner/// the insert there, and then read the result back.
5649683f181746c2312c8828c79b6e25a07fb441d57Nick LewyckySDValue SelectionDAGLegalize::
56569e067fdd86d34cb81ccdffb82415b4f89144218Chris LattnerPerformInsertVectorEltInMemory(SDValue Vec, SDValue Val, SDValue Idx,
56669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner                               DebugLoc dl) {
56769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  SDValue Tmp1 = Vec;
56869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  SDValue Tmp2 = Val;
56969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  SDValue Tmp3 = Idx;
57069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
57169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // If the target doesn't support this, we have to spill the input vector
57269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // to a temporary stack slot, update the element, then reload it.  This is
573421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  // badness.  We could also load the value into a vector register (either
57469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // with a "move to register" or "extload into register" instruction, then
57569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // permute it into place, if the idx is a constant and if the idx is
57669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  // supported by the target.
57769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  EVT VT    = Tmp1.getValueType();
57869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  EVT EltVT = VT.getVectorElementType();
57969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  EVT IdxVT = Tmp3.getValueType();
58069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  EVT PtrVT = TLI.getPointerTy();
58169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  SDValue StackPtr = DAG.CreateStackTemporary(VT);
5825729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
5835729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
5845729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
5855729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // Store the vector.
5865729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, Tmp1, StackPtr,
5875729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                            MachinePointerInfo::getFixedStack(SPFI),
5885729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                            false, false, 0);
589e7e63fe9650fc01043c96e2bf8a1ecc19e49c5b7Chris Lattner
5905729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // Truncate or zero extend offset to target pointer type.
5915729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  unsigned CastOpc = IdxVT.bitsGT(PtrVT) ? ISD::TRUNCATE : ISD::ZERO_EXTEND;
5925729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  Tmp3 = DAG.getNode(CastOpc, dl, PtrVT, Tmp3);
5935729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  // Add the offset to the index.
5945729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  unsigned EltSize = EltVT.getSizeInBits()/8;
59569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  Tmp3 = DAG.getNode(ISD::MUL, dl, IdxVT, Tmp3,DAG.getConstant(EltSize, IdxVT));
59669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  SDValue StackPtr2 = DAG.getNode(ISD::ADD, dl, IdxVT, Tmp3, StackPtr);
597a5ddb59a1319ccd23844c74809a64bc4d88f59d1Chris Lattner  // Store the scalar value.
598d38c14e6ed0136624a18cf8338c82f1709d804aaChris Lattner  Ch = DAG.getTruncStore(Ch, dl, Tmp2, StackPtr2, MachinePointerInfo(), EltVT,
599d38c14e6ed0136624a18cf8338c82f1709d804aaChris Lattner                         false, false, 0);
600d38c14e6ed0136624a18cf8338c82f1709d804aaChris Lattner  // Load the updated vector.
601421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  return DAG.getLoad(VT, dl, Ch, StackPtr,
602421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner                     MachinePointerInfo::getFixedStack(SPFI), false, false,
603421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner                     false, 0);
604421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner}
605421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner
606421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner
607421fa9e32e445c972df4a981c60fbec4e21ac187Chris LattnerSDValue SelectionDAGLegalize::
608421fa9e32e445c972df4a981c60fbec4e21ac187Chris LattnerExpandINSERT_VECTOR_ELT(SDValue Vec, SDValue Val, SDValue Idx, DebugLoc dl) {
609421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  if (ConstantSDNode *InsertPos = dyn_cast<ConstantSDNode>(Idx)) {
610421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    // SCALAR_TO_VECTOR requires that the type of the value being inserted
611421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    // match the element type of the vector being created, except for
612421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    // integers in which case the inserted value can be over width.
613421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    EVT EltVT = Vec.getValueType().getVectorElementType();
614421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    if (Val.getValueType() == EltVT ||
615421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner        (EltVT.isInteger() && Val.getValueType().bitsGE(EltVT))) {
616421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner      SDValue ScVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
617421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner                                  Vec.getValueType(), Val);
618421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner
619421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner      unsigned NumElts = Vec.getValueType().getVectorNumElements();
620421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner      // We generate a shuffle of InVec and ScVec, so the shuffle mask
621421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner      // should be 0,1,2,3,4,5... with the appropriate element replaced with
622421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner      // elt 0 of the RHS.
623421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner      SmallVector<int, 8> ShufOps;
62493b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar      for (unsigned i = 0; i != NumElts; ++i)
62578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner        ShufOps.push_back(i != InsertPos->getZExtValue() ? i : NumElts);
626421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner
627421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner      return DAG.getVectorShuffle(Vec.getValueType(), dl, Vec, ScVec,
628421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner                                  &ShufOps[0]);
629421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    }
630421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  }
631421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  return PerformInsertVectorEltInMemory(Vec, Val, Idx, dl);
632421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner}
633421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner
634421fa9e32e445c972df4a981c60fbec4e21ac187Chris LattnerSDValue SelectionDAGLegalize::OptimizeFloatStore(StoreSDNode* ST) {
635421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
63693b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar  // FIXME: We shouldn't do this for TargetConstantFP's.
63793b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar  // FIXME: move this to the DAG Combiner!  Note that we can't regress due
63878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // to phase ordering between legalized code and the dag combiner.  This
639421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  // probably means that we need to integrate dag combiner and legalizer
6405a06cf644f35b873686c8694968192ad3385e36aChris Lattner  // together.
6411d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson  // We generally can't do this one for long doubles.
6421d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson  SDValue Tmp1 = ST->getChain();
643421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  SDValue Tmp2 = ST->getBasePtr();
6445a06cf644f35b873686c8694968192ad3385e36aChris Lattner  SDValue Tmp3;
645421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  unsigned Alignment = ST->getAlignment();
646421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  bool isVolatile = ST->isVolatile();
647bdbf1a177de085927c375efa986c52af2057fb7aChris Lattner  bool isNonTemporal = ST->isNonTemporal();
648421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  DebugLoc dl = ST->getDebugLoc();
649421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner  if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(ST->getValue())) {
650421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    if (CFP->getValueType(0) == MVT::f32 &&
651421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner        TLI.isTypeLegal(MVT::i32)) {
6525729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      Tmp3 = DAG.getConstant(CFP->getValueAPF().
6535729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                                      bitcastToAPInt().zextOrTrunc(32),
6545729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                              MVT::i32);
655fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump      return DAG.getStore(Tmp1, dl, Tmp3, Tmp2, ST->getPointerInfo(),
6565729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                          isVolatile, isNonTemporal, Alignment);
657421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner    }
658421fa9e32e445c972df4a981c60fbec4e21ac187Chris Lattner
6593cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner    if (CFP->getValueType(0) == MVT::f64) {
6603cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      // If this target supports 64-bit registers, do a single 64-bit store.
6613cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      if (TLI.isTypeLegal(MVT::i64)) {
6623cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner        Tmp3 = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
6633cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner                                  zextOrTrunc(64), MVT::i64);
6643cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner        return DAG.getStore(Tmp1, dl, Tmp3, Tmp2, ST->getPointerInfo(),
6653cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner                            isVolatile, isNonTemporal, Alignment);
6663cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      }
6673cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner
6683cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      if (TLI.isTypeLegal(MVT::i32) && !ST->isVolatile()) {
6693cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner        // Otherwise, if the target supports 32-bit registers, use 2 32-bit
6703cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner        // stores.  If the target supports neither 32- nor 64-bits, this
6712c7ed11d93239dacf81540e2307f0db456bb9122Chris Lattner        // xform is certainly not worth it.
6722c7ed11d93239dacf81540e2307f0db456bb9122Chris Lattner        const APInt &IntVal =CFP->getValueAPF().bitcastToAPInt();
6732c7ed11d93239dacf81540e2307f0db456bb9122Chris Lattner        SDValue Lo = DAG.getConstant(IntVal.trunc(32), MVT::i32);
6742c7ed11d93239dacf81540e2307f0db456bb9122Chris Lattner        SDValue Hi = DAG.getConstant(IntVal.lshr(32).trunc(32), MVT::i32);
6753cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner        if (TLI.isBigEndian()) std::swap(Lo, Hi);
6763cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner
6773cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner        Lo = DAG.getStore(Tmp1, dl, Lo, Tmp2, ST->getPointerInfo(), isVolatile,
6783cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner                          isNonTemporal, Alignment);
6793cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner        Tmp2 = DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
6803cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner                            DAG.getIntPtrConstant(4));
6813cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner        Hi = DAG.getStore(Tmp1, dl, Hi, Tmp2,
6823cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner                          ST->getPointerInfo().getWithOffset(4),
6836b233395025069f63156ea2b524cdb708a14731fDale Johannesen                          isVolatile, isNonTemporal, MinAlign(Alignment, 4U));
6846b233395025069f63156ea2b524cdb708a14731fDale Johannesen
6856b233395025069f63156ea2b524cdb708a14731fDale Johannesen        return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi);
6866b233395025069f63156ea2b524cdb708a14731fDale Johannesen      }
6873cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner    }
6883cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner  }
6896b233395025069f63156ea2b524cdb708a14731fDale Johannesen  return SDValue(0, 0);
6903cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner}
6913cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner
6923cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner/// LegalizeOp - Return a legal replacement for the given operation, with
6933cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner/// all legal operands.
6943cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattnervoid SelectionDAGLegalize::LegalizeOp(SDNode *Node) {
6953cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner  if (Node->getOpcode() == ISD::TargetConstant) // Allow illegal target nodes.
6963cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner    return;
6973cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner
6983cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner  DebugLoc dl = Node->getDebugLoc();
6993cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner
7003cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner  for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
7013cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner    assert(TLI.getTypeAction(*DAG.getContext(), Node->getValueType(i)) ==
7023cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner             TargetLowering::TypeLegal &&
7033cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner           "Unexpected illegal type!");
7043cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner
7053cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner  for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
7063cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner    assert((TLI.getTypeAction(*DAG.getContext(),
7073cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner                              Node->getOperand(i).getValueType()) ==
7083cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner              TargetLowering::TypeLegal ||
7093cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner            Node->getOperand(i).getOpcode() == ISD::TargetConstant) &&
71093b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar           "Unexpected illegal type!");
71193b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar
7123cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner  SDValue Tmp1, Tmp2, Tmp3, Tmp4;
7133cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner  bool isCustom = false;
7143cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner
7153cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner  // Figure out the correct action; the way to query this varies by opcode
7163cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner  TargetLowering::LegalizeAction Action = TargetLowering::Legal;
7173cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner  bool SimpleFinishLegalizing = true;
7183cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner  switch (Node->getOpcode()) {
7193cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner  case ISD::INTRINSIC_W_CHAIN:
7203cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner  case ISD::INTRINSIC_WO_CHAIN:
7213cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner  case ISD::INTRINSIC_VOID:
7223cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner  case ISD::STACKSAVE:
7233cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner    Action = TLI.getOperationAction(Node->getOpcode(), MVT::Other);
7243cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner    break;
7253cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner  case ISD::VAARG:
7263cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner    Action = TLI.getOperationAction(Node->getOpcode(),
7273cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner                                    Node->getValueType(0));
7283cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner    if (Action != TargetLowering::Promote)
7293cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner      Action = TLI.getOperationAction(Node->getOpcode(), MVT::Other);
7303cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner    break;
7313cda3cdab118fd2b185b3e6e05e2b19a4a70c1adChris Lattner  case ISD::SINT_TO_FP:
73269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  case ISD::UINT_TO_FP:
73369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  case ISD::EXTRACT_VECTOR_ELT:
73469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    Action = TLI.getOperationAction(Node->getOpcode(),
73569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner                                    Node->getOperand(0).getValueType());
73669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    break;
73769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  case ISD::FP_ROUND_INREG:
73869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  case ISD::SIGN_EXTEND_INREG: {
73969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    EVT InnerType = cast<VTSDNode>(Node->getOperand(1))->getVT();
74069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    Action = TLI.getOperationAction(Node->getOpcode(), InnerType);
74169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    break;
74269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  }
74369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  case ISD::ATOMIC_STORE: {
74469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    Action = TLI.getOperationAction(Node->getOpcode(),
74569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner                                    Node->getOperand(2).getValueType());
74669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    break;
74769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  }
74869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  case ISD::SELECT_CC:
74969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  case ISD::SETCC:
75069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  case ISD::BR_CC: {
75169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    unsigned CCOperand = Node->getOpcode() == ISD::SELECT_CC ? 4 :
75269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner                         Node->getOpcode() == ISD::SETCC ? 2 : 1;
75369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    unsigned CompareOperand = Node->getOpcode() == ISD::BR_CC ? 2 : 0;
75469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    EVT OpVT = Node->getOperand(CompareOperand).getValueType();
75569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    ISD::CondCode CCCode =
75669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner        cast<CondCodeSDNode>(Node->getOperand(CCOperand))->get();
75769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    Action = TLI.getCondCodeAction(CCCode, OpVT);
75852c95856b4a40ccae6c4b0e13b2a04101e1f79c9Chris Lattner    if (Action == TargetLowering::Legal) {
75952c95856b4a40ccae6c4b0e13b2a04101e1f79c9Chris Lattner      if (Node->getOpcode() == ISD::SELECT_CC)
76069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner        Action = TLI.getOperationAction(Node->getOpcode(),
76169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner                                        Node->getValueType(0));
76269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      else
7632a99b482a62e3f1ac3fd716fba430ac32fedade4Chris Lattner        Action = TLI.getOperationAction(Node->getOpcode(), OpVT);
7642a99b482a62e3f1ac3fd716fba430ac32fedade4Chris Lattner    }
7652a99b482a62e3f1ac3fd716fba430ac32fedade4Chris Lattner    break;
7669e9a0d5fc26878e51a58a8b57900fcbf952c2691Owen Anderson  }
76769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  case ISD::LOAD:
76869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  case ISD::STORE:
76969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    // FIXME: Model these properly.  LOAD and STORE are complicated, and
77069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    // STORE expects the unlegalized operand in some cases.
77169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    SimpleFinishLegalizing = false;
77269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    break;
77369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  case ISD::CALLSEQ_START:
77469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  case ISD::CALLSEQ_END:
77569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    // FIXME: This shouldn't be necessary.  These nodes have special properties
77669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    // dealing with the recursive nature of legalization.  Removing this
77769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    // special case should be done as part of making LegalizeDAG non-recursive.
77869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    SimpleFinishLegalizing = false;
77969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    break;
78069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  case ISD::EXTRACT_ELEMENT:
78169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  case ISD::FLT_ROUNDS_:
78269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  case ISD::SADDO:
78369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  case ISD::SSUBO:
78469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  case ISD::UADDO:
78569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  case ISD::USUBO:
78669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  case ISD::SMULO:
78769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  case ISD::UMULO:
78869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  case ISD::FPOWI:
78969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  case ISD::MERGE_VALUES:
79069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  case ISD::EH_RETURN:
79169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  case ISD::FRAME_TO_ARGS_OFFSET:
79269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  case ISD::EH_SJLJ_SETJMP:
79369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  case ISD::EH_SJLJ_LONGJMP:
79469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    // These operations lie about being legal: when they claim to be legal,
79569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    // they should actually be expanded.
79652c95856b4a40ccae6c4b0e13b2a04101e1f79c9Chris Lattner    Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
79769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    if (Action == TargetLowering::Legal)
79869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      Action = TargetLowering::Expand;
79969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    break;
80069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  case ISD::INIT_TRAMPOLINE:
80169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  case ISD::ADJUST_TRAMPOLINE:
80269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  case ISD::FRAMEADDR:
80369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  case ISD::RETURNADDR:
80469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    // These operations lie about being legal: when they claim to be legal,
80569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    // they should actually be custom-lowered.
80669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
80769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    if (Action == TargetLowering::Legal)
80869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      Action = TargetLowering::Custom;
80969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    break;
81069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  default:
81169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    if (Node->getOpcode() >= ISD::BUILTIN_OP_END) {
81269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      Action = TargetLowering::Legal;
81369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    } else {
81469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
81569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    }
81669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    break;
81769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  }
81869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
81969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner  if (SimpleFinishLegalizing) {
82069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    SmallVector<SDValue, 8> Ops;
82169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
82269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      Ops.push_back(Node->getOperand(i));
82369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    switch (Node->getOpcode()) {
82469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    default: break;
82569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    case ISD::SHL:
82669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    case ISD::SRL:
82769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    case ISD::SRA:
82869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    case ISD::ROTL:
82969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    case ISD::ROTR:
83069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      // Legalizing shifts/rotates requires adjusting the shift amount
83169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      // to the appropriate width.
83269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      if (!Ops[1].getValueType().isVector()) {
83369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner        SDValue SAO = DAG.getShiftAmountOperand(Ops[0].getValueType(), Ops[1]);
83469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner        HandleSDNode Handle(SAO);
83569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner        LegalizeOp(SAO.getNode());
83669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner        Ops[1] = Handle.getValue();
83769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      }
83869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      break;
83969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    case ISD::SRL_PARTS:
84069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    case ISD::SRA_PARTS:
84169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    case ISD::SHL_PARTS:
84269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      // Legalizing shifts/rotates requires adjusting the shift amount
84369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      // to the appropriate width.
84469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      if (!Ops[2].getValueType().isVector()) {
84569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner        SDValue SAO = DAG.getShiftAmountOperand(Ops[0].getValueType(), Ops[2]);
84669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner        HandleSDNode Handle(SAO);
84769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner        LegalizeOp(SAO.getNode());
84869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner        Ops[2] = Handle.getValue();
84969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      }
85069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      break;
85169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    }
85269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
85369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    SDNode *NewNode = DAG.UpdateNodeOperands(Node, Ops.data(), Ops.size());
85469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    if (NewNode != Node) {
85569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      DAG.ReplaceAllUsesWith(Node, NewNode);
85669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
85769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner        DAG.TransferDbgValues(SDValue(Node, i), SDValue(NewNode, i));
858a3522000ab9c821f48856d0c25ada8297c1c2914Chris Lattner      ReplacedNode(Node);
85969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      Node = NewNode;
86069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    }
86169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    switch (Action) {
86269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    case TargetLowering::Legal:
86369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      return;
86469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner    case TargetLowering::Custom:
86569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      // FIXME: The handling for custom lowering with multiple results is
86669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      // a complete mess.
86769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      Tmp1 = TLI.LowerOperation(SDValue(Node, 0), DAG);
86869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      if (Tmp1.getNode()) {
86969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner        SmallVector<SDValue, 8> ResultVals;
87069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner        for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i) {
87169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner          if (e == 1)
87269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner            ResultVals.push_back(Tmp1);
87369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner          else
87469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner            ResultVals.push_back(Tmp1.getValue(i));
87569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner        }
87669e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner        if (Tmp1.getNode() != Node || Tmp1.getResNo() != 0) {
87769e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner          DAG.ReplaceAllUsesWith(Node, ResultVals.data());
87869e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner          for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
87969e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner            DAG.TransferDbgValues(SDValue(Node, i), ResultVals[i]);
88069e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner          ReplacedNode(Node);
88169e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner        }
88269e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner        return;
88369e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      }
88469e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner
88569e067fdd86d34cb81ccdffb82415b4f89144218Chris Lattner      // FALL THROUGH
8865729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    case TargetLowering::Expand:
8875729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      ExpandNode(Node);
8885729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      return;
8895729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    case TargetLowering::Promote:
8905729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      PromoteNode(Node);
8915729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      return;
8925729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    }
8935729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  }
894785672534d32d196d04ad022c111fde3864e0d28Chris Lattner
8955729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  switch (Node->getOpcode()) {
8965729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  default:
8975729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner#ifndef NDEBUG
8985729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    dbgs() << "NODE: ";
8995729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    Node->dump( &DAG);
9005729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    dbgs() << "\n";
9015729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner#endif
9025729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    llvm_unreachable("Do not know how to legalize this operator!");
903785672534d32d196d04ad022c111fde3864e0d28Chris Lattner
9045729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  case ISD::CALLSEQ_START:
9055729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  case ISD::CALLSEQ_END:
9065729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    break;
9075729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner  case ISD::LOAD: {
9085729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    LoadSDNode *LD = cast<LoadSDNode>(Node);
90978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    Tmp1 = LD->getChain();   // Legalize the chain.
9105729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    Tmp2 = LD->getBasePtr(); // Legalize the base pointer.
9115729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
9125729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    ISD::LoadExtType ExtType = LD->getExtensionType();
9135729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    if (ExtType == ISD::NON_EXTLOAD) {
9145729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      EVT VT = Node->getValueType(0);
9155729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      Tmp3 = SDValue(Node, 0);
9165729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      Tmp4 = SDValue(Node, 1);
9175729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
9185729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
9195729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      default: llvm_unreachable("This action is not supported yet!");
9205729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      case TargetLowering::Legal:
9215729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        // If this is an unaligned load and the target doesn't support it,
9225729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        // expand it.
9235729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        if (!TLI.allowsUnalignedMemoryAccesses(LD->getMemoryVT())) {
92478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          Type *Ty = LD->getMemoryVT().getTypeForEVT(*DAG.getContext());
9255729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner          unsigned ABIAlignment = TLI.getTargetData()->getABITypeAlignment(Ty);
9265729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner          if (LD->getAlignment() < ABIAlignment){
9275729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner            ExpandUnalignedLoad(cast<LoadSDNode>(Node),
9285729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                                DAG, TLI, Tmp3, Tmp4);
9295729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner          }
9305729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        }
9315729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        break;
9325729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      case TargetLowering::Custom:
9335729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        Tmp1 = TLI.LowerOperation(Tmp3, DAG);
9345729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        if (Tmp1.getNode()) {
93512d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel          Tmp3 = Tmp1;
9365729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner          Tmp4 = Tmp1.getValue(1);
9375729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        }
9385729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        break;
9395729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      case TargetLowering::Promote: {
9405729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        // Only promote a load of vector type to another.
94112d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel        assert(VT.isVector() && "Cannot promote this load!");
94212d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel        // Change base type to a different vector type.
94312d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel        EVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), VT);
94412d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel
9455729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        Tmp1 = DAG.getLoad(NVT, dl, Tmp1, Tmp2, LD->getPointerInfo(),
9465729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                           LD->isVolatile(), LD->isNonTemporal(),
9475729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                           LD->isInvariant(), LD->getAlignment());
9485729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        Tmp3 = DAG.getNode(ISD::BITCAST, dl, VT, Tmp1);
9495729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        Tmp4 = Tmp1.getValue(1);
9505729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        break;
9515729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      }
9525729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      }
9535729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      if (Tmp4.getNode() != Node) {
95412d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel        assert(Tmp3.getNode() != Node && "Load must be completely replaced");
95512d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel        DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 0), Tmp3);
9565729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), Tmp4);
9575729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        ReplacedNode(Node);
95812d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel      }
9595729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      return;
9605729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    }
9615729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
9625729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    EVT SrcVT = LD->getMemoryVT();
9635729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    unsigned SrcWidth = SrcVT.getSizeInBits();
9645729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    unsigned Alignment = LD->getAlignment();
9655729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    bool isVolatile = LD->isVolatile();
9665729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    bool isNonTemporal = LD->isNonTemporal();
9675729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
9685729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner    if (SrcWidth != SrcVT.getStoreSizeInBits() &&
9695729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        // Some targets pretend to have an i1 loading operation, and actually
9705729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        // load an i8.  This trick is correct for ZEXTLOAD because the top 7
9715729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        // bits are guaranteed to be zero; it helps the optimizers understand
97212d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel        // that these bits are zero.  It is also useful for EXTLOAD, since it
9735729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        // tells the optimizers that those bits are undefined.  It would be
9745729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        // nice to have an effective generic way of getting these benefits...
9755729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        // Until such a way is found, don't insist on promoting i1 here.
976e7e63fe9650fc01043c96e2bf8a1ecc19e49c5b7Chris Lattner        (SrcVT != MVT::i1 ||
9775729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner         TLI.getLoadExtAction(ExtType, MVT::i1) == TargetLowering::Promote)) {
9785729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      // Promote to a byte-sized load if not loading an integral number of
9795729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      // bytes.  For example, promote EXTLOAD:i20 -> EXTLOAD:i24.
9805729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      unsigned NewWidth = SrcVT.getStoreSizeInBits();
9815729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      EVT NVT = EVT::getIntegerVT(*DAG.getContext(), NewWidth);
9825729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      SDValue Ch;
9835729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
9845729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      // The extra bits are guaranteed to be zero, since we stored them that
9855729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      // way.  A zext load from NVT thus automatically gives zext from SrcVT.
9865729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
98712d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel      ISD::LoadExtType NewExtType =
9885729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        ExtType == ISD::ZEXTLOAD ? ISD::ZEXTLOAD : ISD::EXTLOAD;
9895729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
9905729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      SDValue Result =
99112d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel        DAG.getExtLoad(NewExtType, dl, Node->getValueType(0),
99212d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel                       Tmp1, Tmp2, LD->getPointerInfo(),
9935729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                       NVT, isVolatile, isNonTemporal, Alignment);
9945729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
9955729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      Ch = Result.getValue(1); // The chain.
9965729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
9975729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      if (ExtType == ISD::SEXTLOAD)
9985729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        // Having the top bits zero doesn't help when sign extending.
9995729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl,
10005729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                             Result.getValueType(),
10015729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                             Result, DAG.getValueType(SrcVT));
10025729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      else if (ExtType == ISD::ZEXTLOAD || NVT == Result.getValueType())
100312d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel        // All the top bits are guaranteed to be zero - inform the optimizers.
10045729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        Result = DAG.getNode(ISD::AssertZext, dl,
10055729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                             Result.getValueType(), Result,
10065729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                             DAG.getValueType(SrcVT));
10075729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
10085729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      Tmp1 = Result;
10095729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      Tmp2 = Ch;
101012d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel    } else if (SrcWidth & (SrcWidth - 1)) {
10115729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      // If not loading a power-of-2 number of bits, expand as two loads.
101212d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel      assert(!SrcVT.isVector() && "Unsupported extload!");
101312d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel      unsigned RoundWidth = 1 << Log2_32(SrcWidth);
10145729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      assert(RoundWidth < SrcWidth);
10155729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      unsigned ExtraWidth = SrcWidth - RoundWidth;
101612d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel      assert(ExtraWidth < RoundWidth);
101712d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel      assert(!(RoundWidth % 8) && !(ExtraWidth % 8) &&
10185729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner             "Load size not an integral number of bytes!");
10195729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      EVT RoundVT = EVT::getIntegerVT(*DAG.getContext(), RoundWidth);
10205729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      EVT ExtraVT = EVT::getIntegerVT(*DAG.getContext(), ExtraWidth);
10215729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      SDValue Lo, Hi, Ch;
10225729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      unsigned IncrementSize;
102312d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel
10245729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      if (TLI.isLittleEndian()) {
10255729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        // EXTLOAD:i24 -> ZEXTLOAD:i16 | (shl EXTLOAD@+2:i8, 16)
102612d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel        // Load the bottom RoundWidth bits.
10275729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, Node->getValueType(0),
10285729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                            Tmp1, Tmp2,
10295729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                            LD->getPointerInfo(), RoundVT, isVolatile,
10305729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                            isNonTemporal, Alignment);
10315729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
10325729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        // Load the remaining ExtraWidth bits.
10335729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        IncrementSize = RoundWidth / 8;
10345729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        Tmp2 = DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
10355729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                           DAG.getIntPtrConstant(IncrementSize));
10365729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        Hi = DAG.getExtLoad(ExtType, dl, Node->getValueType(0), Tmp1, Tmp2,
10375729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                            LD->getPointerInfo().getWithOffset(IncrementSize),
10385729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                            ExtraVT, isVolatile, isNonTemporal,
10395729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                            MinAlign(Alignment, IncrementSize));
10405729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
10415729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        // Build a factor node to remember that this load is independent of
10425729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        // the other one.
10435729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
10445729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                         Hi.getValue(1));
10455729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
10465729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        // Move the top bits to the right place.
10475729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        Hi = DAG.getNode(ISD::SHL, dl, Hi.getValueType(), Hi,
10485729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                         DAG.getConstant(RoundWidth,
104912d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel                                      TLI.getShiftAmountTy(Hi.getValueType())));
10505729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
10515729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        // Join the hi and lo parts.
10525729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        Tmp1 = DAG.getNode(ISD::OR, dl, Node->getValueType(0), Lo, Hi);
10535729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner      } else {
10545729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        // Big endian - avoid unaligned loads.
10555729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        // EXTLOAD:i24 -> (shl EXTLOAD:i16, 8) | ZEXTLOAD@+2:i8
10565729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        // Load the top RoundWidth bits.
10575729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        Hi = DAG.getExtLoad(ExtType, dl, Node->getValueType(0), Tmp1, Tmp2,
10585729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                            LD->getPointerInfo(), RoundVT, isVolatile,
10595729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                            isNonTemporal, Alignment);
10605729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
10615729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        // Load the remaining ExtraWidth bits.
10625729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        IncrementSize = RoundWidth / 8;
10635729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        Tmp2 = DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
10645729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                           DAG.getIntPtrConstant(IncrementSize));
10655729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        Lo = DAG.getExtLoad(ISD::ZEXTLOAD,
10665729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                            dl, Node->getValueType(0), Tmp1, Tmp2,
10675729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                            LD->getPointerInfo().getWithOffset(IncrementSize),
10685729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                            ExtraVT, isVolatile, isNonTemporal,
10695729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                            MinAlign(Alignment, IncrementSize));
10705729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
10715729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        // Build a factor node to remember that this load is independent of
10725729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        // the other one.
10735729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
10745729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                         Hi.getValue(1));
10755729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
10765729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        // Move the top bits to the right place.
10775729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        Hi = DAG.getNode(ISD::SHL, dl, Hi.getValueType(), Hi,
10785729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                         DAG.getConstant(ExtraWidth,
10795729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                                      TLI.getShiftAmountTy(Hi.getValueType())));
10805729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
108112d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel        // Join the hi and lo parts.
108212d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel        Tmp1 = DAG.getNode(ISD::OR, dl, Node->getValueType(0), Lo, Hi);
108312d53dba36905d20b02cf7c4cdae057ae4a5a5e1Devang Patel      }
108478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
108578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner      Tmp2 = Ch;
108678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    } else {
108778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner      switch (TLI.getLoadExtAction(ExtType, SrcVT)) {
108878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner      default: llvm_unreachable("This action is not supported yet!");
108978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner      case TargetLowering::Custom:
109078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner        isCustom = true;
109178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner        // FALLTHROUGH
109278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner      case TargetLowering::Legal:
109378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner        Tmp1 = SDValue(Node, 0);
109478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner        Tmp2 = SDValue(Node, 1);
109578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
1096bdbf1a177de085927c375efa986c52af2057fb7aChris Lattner        if (isCustom) {
109778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          Tmp3 = TLI.LowerOperation(SDValue(Node, 0), DAG);
109878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          if (Tmp3.getNode()) {
109978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner            Tmp1 = Tmp3;
110078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner            Tmp2 = Tmp3.getValue(1);
110178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          }
1102bdbf1a177de085927c375efa986c52af2057fb7aChris Lattner        } else {
110378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          // If this is an unaligned load and the target doesn't support it,
110478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          // expand it.
1105bdbf1a177de085927c375efa986c52af2057fb7aChris Lattner          if (!TLI.allowsUnalignedMemoryAccesses(LD->getMemoryVT())) {
1106fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump            Type *Ty =
1107fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump              LD->getMemoryVT().getTypeForEVT(*DAG.getContext());
11085729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner            unsigned ABIAlignment =
11095729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner              TLI.getTargetData()->getABITypeAlignment(Ty);
11105729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner            if (LD->getAlignment() < ABIAlignment){
11115729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner              ExpandUnalignedLoad(cast<LoadSDNode>(Node),
11125729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner                                  DAG, TLI, Tmp1, Tmp2);
1113bdbf1a177de085927c375efa986c52af2057fb7aChris Lattner            }
1114eede65ce6cb29c8f3a701be8606e95c9a213efffChris Lattner          }
1115eede65ce6cb29c8f3a701be8606e95c9a213efffChris Lattner        }
111693b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar        break;
111793b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar      case TargetLowering::Expand:
1118eede65ce6cb29c8f3a701be8606e95c9a213efffChris Lattner        if (!TLI.isLoadExtLegal(ISD::EXTLOAD, SrcVT) && TLI.isTypeLegal(SrcVT)) {
1119eede65ce6cb29c8f3a701be8606e95c9a213efffChris Lattner          SDValue Load = DAG.getLoad(SrcVT, dl, Tmp1, Tmp2,
1120eede65ce6cb29c8f3a701be8606e95c9a213efffChris Lattner                                     LD->getPointerInfo(),
1121fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump                                     LD->isVolatile(), LD->isNonTemporal(),
1122fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump                                     LD->isInvariant(), LD->getAlignment());
1123fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump          unsigned ExtendOp;
11245729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner          switch (ExtType) {
112593b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar          case ISD::EXTLOAD:
112693b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar            ExtendOp = (SrcVT.isFloatingPoint() ?
1127fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump                        ISD::FP_EXTEND : ISD::ANY_EXTEND);
1128fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump            break;
1129fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump          case ISD::SEXTLOAD: ExtendOp = ISD::SIGN_EXTEND; break;
113078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          case ISD::ZEXTLOAD: ExtendOp = ISD::ZERO_EXTEND; break;
113178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          default: llvm_unreachable("Unexpected extend load type!");
113278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          }
113378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          Tmp1 = DAG.getNode(ExtendOp, dl, Node->getValueType(0), Load);
113478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          Tmp2 = Load.getValue(1);
113578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          break;
113678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner        }
11375729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
11385729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        assert(!SrcVT.isVector() &&
11395729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner               "Vector Loads are handled in LegalizeVectorOps");
11405729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner
11415729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        // FIXME: This does not work for vectors on most targets.  Sign- and
11425729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        // zero-extend operations are currently folded into extending loads,
11435729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        // whether they are legal or not, and then we end up here without any
11445729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        // support for legalizing them.
11455729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        assert(ExtType != ISD::EXTLOAD &&
11465729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner               "EXTLOAD should always be supported!");
11475729d38c81bc2e3b21a2bb7a80a8cde384fc7b7bChris Lattner        // Turn the unsupported load into an EXTLOAD followed by an explicit
1148a5ddb59a1319ccd23844c74809a64bc4d88f59d1Chris Lattner        // zero/sign extend inreg.
114993b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar        SDValue Result = DAG.getExtLoad(ISD::EXTLOAD, dl, Node->getValueType(0),
1150460f656475738d1a95a6be95346908ce1597df25Daniel Dunbar                                        Tmp1, Tmp2, LD->getPointerInfo(), SrcVT,
115193b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar                                        LD->isVolatile(), LD->isNonTemporal(),
115293b67e40de356569493c285b86b138a3f11b5035Daniel Dunbar                                        LD->getAlignment());
1153a5ddb59a1319ccd23844c74809a64bc4d88f59d1Chris Lattner        SDValue ValRes;
1154bd3401fa98b578080e227afce940bca80137dea6Chris Lattner        if (ExtType == ISD::SEXTLOAD)
1155bd3401fa98b578080e227afce940bca80137dea6Chris Lattner          ValRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl,
1156bd3401fa98b578080e227afce940bca80137dea6Chris Lattner                               Result.getValueType(),
1157bd3401fa98b578080e227afce940bca80137dea6Chris Lattner                               Result, DAG.getValueType(SrcVT));
1158bd3401fa98b578080e227afce940bca80137dea6Chris Lattner        else
11591d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson          ValRes = DAG.getZeroExtendInReg(Result, dl, SrcVT.getScalarType());
11601d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson        Tmp1 = ValRes;
11611d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson        Tmp2 = Result.getValue(1);
1162bd3401fa98b578080e227afce940bca80137dea6Chris Lattner        break;
1163bd3401fa98b578080e227afce940bca80137dea6Chris Lattner      }
1164bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    }
1165bd3401fa98b578080e227afce940bca80137dea6Chris Lattner
1166bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    // Since loads produce two values, make sure to remember that we legalized
1167bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    // both of them.
1168bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    if (Tmp2.getNode() != Node) {
1169bd3401fa98b578080e227afce940bca80137dea6Chris Lattner      assert(Tmp1.getNode() != Node && "Load must be completely replaced");
1170bd3401fa98b578080e227afce940bca80137dea6Chris Lattner      DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 0), Tmp1);
11716776064d190701c5bae4d5403939eed2e480d1cdNick Lewycky      DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), Tmp2);
1172460f656475738d1a95a6be95346908ce1597df25Daniel Dunbar      ReplacedNode(Node);
1173bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    }
1174bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    break;
1175bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  }
1176bd3401fa98b578080e227afce940bca80137dea6Chris Lattner  case ISD::STORE: {
1177bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    StoreSDNode *ST = cast<StoreSDNode>(Node);
1178f530c92cd55f35f64904e42e38b3a2bc92b347cbDan Gohman    Tmp1 = ST->getChain();
1179f530c92cd55f35f64904e42e38b3a2bc92b347cbDan Gohman    Tmp2 = ST->getBasePtr();
1180f530c92cd55f35f64904e42e38b3a2bc92b347cbDan Gohman    unsigned Alignment = ST->getAlignment();
1181f530c92cd55f35f64904e42e38b3a2bc92b347cbDan Gohman    bool isVolatile = ST->isVolatile();
1182f530c92cd55f35f64904e42e38b3a2bc92b347cbDan Gohman    bool isNonTemporal = ST->isNonTemporal();
1183bd3401fa98b578080e227afce940bca80137dea6Chris Lattner
1184bd3401fa98b578080e227afce940bca80137dea6Chris Lattner    if (!ST->isTruncatingStore()) {
1185bd3401fa98b578080e227afce940bca80137dea6Chris Lattner      if (SDNode *OptStore = OptimizeFloatStore(ST).getNode()) {
1186bd3401fa98b578080e227afce940bca80137dea6Chris Lattner        ReplaceNode(ST, OptStore);
1187bd3401fa98b578080e227afce940bca80137dea6Chris Lattner        break;
1188bd3401fa98b578080e227afce940bca80137dea6Chris Lattner      }
1189bd3401fa98b578080e227afce940bca80137dea6Chris Lattner
1190bd3401fa98b578080e227afce940bca80137dea6Chris Lattner      {
119178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner        Tmp3 = ST->getValue();
1192177480b7ede0441135572d641a2497df25a7d95fChris Lattner        EVT VT = Tmp3.getValueType();
1193433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner        switch (TLI.getOperationAction(ISD::STORE, VT)) {
1194433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner        default: llvm_unreachable("This action is not supported yet!");
1195433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner        case TargetLowering::Legal:
1196433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner          // If this is an unaligned store and the target doesn't support it,
1197433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner          // expand it.
1198433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner          if (!TLI.allowsUnalignedMemoryAccesses(ST->getMemoryVT())) {
1199433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner            Type *Ty = ST->getMemoryVT().getTypeForEVT(*DAG.getContext());
1200433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner            unsigned ABIAlignment= TLI.getTargetData()->getABITypeAlignment(Ty);
1201433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner            if (ST->getAlignment() < ABIAlignment)
1202433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner              ExpandUnalignedStore(cast<StoreSDNode>(Node),
1203433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner                                   DAG, TLI, this);
1204433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner          }
1205433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner          break;
1206433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner        case TargetLowering::Custom:
1207433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner          Tmp1 = TLI.LowerOperation(SDValue(Node, 0), DAG);
1208433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner          if (Tmp1.getNode())
1209433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner            ReplaceNode(SDValue(Node, 0), Tmp1);
1210433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner          break;
1211433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner        case TargetLowering::Promote: {
1212433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner          assert(VT.isVector() && "Unknown legal promote case!");
1213433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner          Tmp3 = DAG.getNode(ISD::BITCAST, dl,
1214433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner                             TLI.getTypeToPromoteTo(ISD::STORE, VT), Tmp3);
1215433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner          SDValue Result =
1216433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner            DAG.getStore(Tmp1, dl, Tmp3, Tmp2,
1217433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner                         ST->getPointerInfo(), isVolatile,
1218433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner                         isNonTemporal, Alignment);
1219433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner          ReplaceNode(SDValue(Node, 0), Result);
1220433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner          break;
1221433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner        }
1222433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner        }
1223433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner        break;
1224433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner      }
1225433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner    } else {
1226433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner      Tmp3 = ST->getValue();
1227433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner
1228433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner      EVT StVT = ST->getMemoryVT();
1229433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner      unsigned StWidth = StVT.getSizeInBits();
1230433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner
1231433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner      if (StWidth != StVT.getStoreSizeInBits()) {
1232433a0dbb262b16b42d75715a4dad618a475ba91bChris Lattner        // Promote to a byte-sized store with upper bits zero if not
1233ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner        // storing an integral number of bytes.  For example, promote
1234bd3401fa98b578080e227afce940bca80137dea6Chris Lattner        // TRUNCSTORE:i1 X -> TRUNCSTORE:i8 (and X, 1)
1235bd3401fa98b578080e227afce940bca80137dea6Chris Lattner        EVT NVT = EVT::getIntegerVT(*DAG.getContext(),
1236bd3401fa98b578080e227afce940bca80137dea6Chris Lattner                                    StVT.getStoreSizeInBits());
1237bd3401fa98b578080e227afce940bca80137dea6Chris Lattner        Tmp3 = DAG.getZeroExtendInReg(Tmp3, dl, StVT);
1238bd3401fa98b578080e227afce940bca80137dea6Chris Lattner        SDValue Result =
1239c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner          DAG.getTruncStore(Tmp1, dl, Tmp3, Tmp2, ST->getPointerInfo(),
1240bd3401fa98b578080e227afce940bca80137dea6Chris Lattner                            NVT, isVolatile, isNonTemporal, Alignment);
1241bd3401fa98b578080e227afce940bca80137dea6Chris Lattner        ReplaceNode(SDValue(Node, 0), Result);
1242ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner      } else if (StWidth & (StWidth - 1)) {
1243ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner        // If not storing a power-of-2 number of bits, expand as two stores.
1244ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner        assert(!StVT.isVector() && "Unsupported truncstore!");
1245ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner        unsigned RoundWidth = 1 << Log2_32(StWidth);
1246ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner        assert(RoundWidth < StWidth);
1247ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner        unsigned ExtraWidth = StWidth - RoundWidth;
1248ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner        assert(ExtraWidth < RoundWidth);
1249fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner        assert(!(RoundWidth % 8) && !(ExtraWidth % 8) &&
1250e34537856a544c83513e390ac9552a8bc3823346Chris Lattner               "Store size not an integral number of bytes!");
1251fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner        EVT RoundVT = EVT::getIntegerVT(*DAG.getContext(), RoundWidth);
1252fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner        EVT ExtraVT = EVT::getIntegerVT(*DAG.getContext(), ExtraWidth);
1253fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner        SDValue Lo, Hi;
1254fddcf47a249fe3a1102257deddc996ee327a85cbChris Lattner        unsigned IncrementSize;
1255ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner
1256ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner        if (TLI.isLittleEndian()) {
1257ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner          // TRUNCSTORE:i24 X -> TRUNCSTORE:i16 X, TRUNCSTORE@+2:i8 (srl X, 16)
1258ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner          // Store the bottom RoundWidth bits.
1259ef0c6744d5050ad724e1ae90e6ac2b932ce01e13Chris Lattner          Lo = DAG.getTruncStore(Tmp1, dl, Tmp3, Tmp2, ST->getPointerInfo(),
1260fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump                                 RoundVT,
1261fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump                                 isVolatile, isNonTemporal, Alignment);
1262fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump
1263fe095f39e7009c51d1c86769792ccbcad8cdd2ecMike Stump          // Store the remaining ExtraWidth bits.
1264177480b7ede0441135572d641a2497df25a7d95fChris Lattner          IncrementSize = RoundWidth / 8;
126578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          Tmp2 = DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
126678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner                             DAG.getIntPtrConstant(IncrementSize));
126778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          Hi = DAG.getNode(ISD::SRL, dl, Tmp3.getValueType(), Tmp3,
126878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner                           DAG.getConstant(RoundWidth,
126978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner                                    TLI.getShiftAmountTy(Tmp3.getValueType())));
127078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          Hi = DAG.getTruncStore(Tmp1, dl, Hi, Tmp2,
127178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner                             ST->getPointerInfo().getWithOffset(IncrementSize),
127278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner                                 ExtraVT, isVolatile, isNonTemporal,
127378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner                                 MinAlign(Alignment, IncrementSize));
127478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner        } else {
127578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          // Big endian - avoid unaligned stores.
127678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          // TRUNCSTORE:i24 X -> TRUNCSTORE:i16 (srl X, 8), TRUNCSTORE@+2:i8 X
127778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          // Store the top RoundWidth bits.
127878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          Hi = DAG.getNode(ISD::SRL, dl, Tmp3.getValueType(), Tmp3,
127978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner                           DAG.getConstant(ExtraWidth,
128078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner                                    TLI.getShiftAmountTy(Tmp3.getValueType())));
128178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          Hi = DAG.getTruncStore(Tmp1, dl, Hi, Tmp2, ST->getPointerInfo(),
128278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner                                 RoundVT, isVolatile, isNonTemporal, Alignment);
128378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
128478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          // Store the remaining ExtraWidth bits.
128578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          IncrementSize = RoundWidth / 8;
128678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          Tmp2 = DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
128778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner                             DAG.getIntPtrConstant(IncrementSize));
128878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          Lo = DAG.getTruncStore(Tmp1, dl, Tmp3, Tmp2,
128978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner                              ST->getPointerInfo().getWithOffset(IncrementSize),
129078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner                                 ExtraVT, isVolatile, isNonTemporal,
129178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner                                 MinAlign(Alignment, IncrementSize));
129278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner        }
129378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
129478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner        // The order of the stores doesn't matter.
129578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner        SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi);
129678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner        ReplaceNode(SDValue(Node, 0), Result);
129778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner      } else {
129878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner        switch (TLI.getTruncStoreAction(ST->getValue().getValueType(), StVT)) {
129978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner        default: llvm_unreachable("This action is not supported yet!");
130078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner        case TargetLowering::Legal:
130178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          // If this is an unaligned store and the target doesn't support it,
130278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          // expand it.
130378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          if (!TLI.allowsUnalignedMemoryAccesses(ST->getMemoryVT())) {
130478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner            Type *Ty = ST->getMemoryVT().getTypeForEVT(*DAG.getContext());
130578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner            unsigned ABIAlignment= TLI.getTargetData()->getABITypeAlignment(Ty);
130678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner            if (ST->getAlignment() < ABIAlignment)
130778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner              ExpandUnalignedStore(cast<StoreSDNode>(Node), DAG, TLI, this);
130878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          }
130978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          break;
131078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner        case TargetLowering::Custom:
131178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          ReplaceNode(SDValue(Node, 0),
131278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner                      TLI.LowerOperation(SDValue(Node, 0), DAG));
131378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          break;
131478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner        case TargetLowering::Expand:
131578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          assert(!StVT.isVector() &&
131678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner                 "Vector Stores are handled in LegalizeVectorOps");
131778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
131878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          // TRUNCSTORE:i16 i32 -> STORE i16
131978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          assert(TLI.isTypeLegal(StVT) && "Do not know how to expand this store!");
132078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          Tmp3 = DAG.getNode(ISD::TRUNCATE, dl, StVT, Tmp3);
132178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          SDValue Result =
132278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner            DAG.getStore(Tmp1, dl, Tmp3, Tmp2, ST->getPointerInfo(),
132378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner                         isVolatile, isNonTemporal, Alignment);
132478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          ReplaceNode(SDValue(Node, 0), Result);
132578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner          break;
132678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner        }
132778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner      }
132878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    }
132978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    break;
133078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  }
133178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  }
133278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner}
133378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
133478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris LattnerSDValue SelectionDAGLegalize::ExpandExtractFromVectorThroughStack(SDValue Op) {
133578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  SDValue Vec = Op.getOperand(0);
133678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  SDValue Idx = Op.getOperand(1);
133778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  DebugLoc dl = Op.getDebugLoc();
133878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // Store the value to a temporary stack slot, then LOAD the returned part.
133978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  SDValue StackPtr = DAG.CreateStackTemporary(Vec.getValueType());
134078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, Vec, StackPtr,
134178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner                            MachinePointerInfo(), false, false, 0);
134278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
134378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // Add the offset to the index.
134478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  unsigned EltSize =
134578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner      Vec.getValueType().getVectorElementType().getSizeInBits()/8;
134678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  Idx = DAG.getNode(ISD::MUL, dl, Idx.getValueType(), Idx,
134778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner                    DAG.getConstant(EltSize, Idx.getValueType()));
134878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
134978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  if (Idx.getValueType().bitsGT(TLI.getPointerTy()))
135078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    Idx = DAG.getNode(ISD::TRUNCATE, dl, TLI.getPointerTy(), Idx);
135178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  else
135278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    Idx = DAG.getNode(ISD::ZERO_EXTEND, dl, TLI.getPointerTy(), Idx);
135378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
135478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  StackPtr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(), Idx, StackPtr);
135578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
135678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  if (Op.getValueType().isVector())
135778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner    return DAG.getLoad(Op.getValueType(), dl, Ch, StackPtr,MachinePointerInfo(),
135878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner                       false, false, false, 0);
135978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  return DAG.getExtLoad(ISD::EXTLOAD, dl, Op.getValueType(), Ch, StackPtr,
136078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner                        MachinePointerInfo(),
136178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner                        Vec.getValueType().getVectorElementType(),
136278c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner                        false, false, 0);
136378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner}
136478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
136578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris LattnerSDValue SelectionDAGLegalize::ExpandInsertToVectorThroughStack(SDValue Op) {
136678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  assert(Op.getValueType().isVector() && "Non-vector insert subvector!");
136778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
136878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  SDValue Vec  = Op.getOperand(0);
136978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  SDValue Part = Op.getOperand(1);
137078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  SDValue Idx  = Op.getOperand(2);
137178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  DebugLoc dl  = Op.getDebugLoc();
1372c2c23d03df415d064c7789349cd82e438f9d44bbChris Lattner
137378c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // Store the value to a temporary stack slot, then LOAD the returned part.
137478c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
137578c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  SDValue StackPtr = DAG.CreateStackTemporary(Vec.getValueType());
137678c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  int FI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
137778c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(FI);
137878c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner
137978c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  // First store the whole vector.
138078c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner  SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, Vec, StackPtr, PtrInfo,
138178c552ef309eb8c47d12aac2c0b3af7849c27ce9Chris Lattner                            false, false, 0);
1382
1383  // Then store the inserted part.
1384
1385  // Add the offset to the index.
1386  unsigned EltSize =
1387      Vec.getValueType().getVectorElementType().getSizeInBits()/8;
1388
1389  Idx = DAG.getNode(ISD::MUL, dl, Idx.getValueType(), Idx,
1390                    DAG.getConstant(EltSize, Idx.getValueType()));
1391
1392  if (Idx.getValueType().bitsGT(TLI.getPointerTy()))
1393    Idx = DAG.getNode(ISD::TRUNCATE, dl, TLI.getPointerTy(), Idx);
1394  else
1395    Idx = DAG.getNode(ISD::ZERO_EXTEND, dl, TLI.getPointerTy(), Idx);
1396
1397  SDValue SubStackPtr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(), Idx,
1398                                    StackPtr);
1399
1400  // Store the subvector.
1401  Ch = DAG.getStore(DAG.getEntryNode(), dl, Part, SubStackPtr,
1402                    MachinePointerInfo(), false, false, 0);
1403
1404  // Finally, load the updated vector.
1405  return DAG.getLoad(Op.getValueType(), dl, Ch, StackPtr, PtrInfo,
1406                     false, false, false, 0);
1407}
1408
1409SDValue SelectionDAGLegalize::ExpandVectorBuildThroughStack(SDNode* Node) {
1410  // We can't handle this case efficiently.  Allocate a sufficiently
1411  // aligned object on the stack, store each element into it, then load
1412  // the result as a vector.
1413  // Create the stack frame object.
1414  EVT VT = Node->getValueType(0);
1415  EVT EltVT = VT.getVectorElementType();
1416  DebugLoc dl = Node->getDebugLoc();
1417  SDValue FIPtr = DAG.CreateStackTemporary(VT);
1418  int FI = cast<FrameIndexSDNode>(FIPtr.getNode())->getIndex();
1419  MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(FI);
1420
1421  // Emit a store of each element to the stack slot.
1422  SmallVector<SDValue, 8> Stores;
1423  unsigned TypeByteSize = EltVT.getSizeInBits() / 8;
1424  // Store (in the right endianness) the elements to memory.
1425  for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
1426    // Ignore undef elements.
1427    if (Node->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1428
1429    unsigned Offset = TypeByteSize*i;
1430
1431    SDValue Idx = DAG.getConstant(Offset, FIPtr.getValueType());
1432    Idx = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, Idx);
1433
1434    // If the destination vector element type is narrower than the source
1435    // element type, only store the bits necessary.
1436    if (EltVT.bitsLT(Node->getOperand(i).getValueType().getScalarType())) {
1437      Stores.push_back(DAG.getTruncStore(DAG.getEntryNode(), dl,
1438                                         Node->getOperand(i), Idx,
1439                                         PtrInfo.getWithOffset(Offset),
1440                                         EltVT, false, false, 0));
1441    } else
1442      Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl,
1443                                    Node->getOperand(i), Idx,
1444                                    PtrInfo.getWithOffset(Offset),
1445                                    false, false, 0));
1446  }
1447
1448  SDValue StoreChain;
1449  if (!Stores.empty())    // Not all undef elements?
1450    StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1451                             &Stores[0], Stores.size());
1452  else
1453    StoreChain = DAG.getEntryNode();
1454
1455  // Result is a load from the stack slot.
1456  return DAG.getLoad(VT, dl, StoreChain, FIPtr, PtrInfo,
1457                     false, false, false, 0);
1458}
1459
1460SDValue SelectionDAGLegalize::ExpandFCOPYSIGN(SDNode* Node) {
1461  DebugLoc dl = Node->getDebugLoc();
1462  SDValue Tmp1 = Node->getOperand(0);
1463  SDValue Tmp2 = Node->getOperand(1);
1464
1465  // Get the sign bit of the RHS.  First obtain a value that has the same
1466  // sign as the sign bit, i.e. negative if and only if the sign bit is 1.
1467  SDValue SignBit;
1468  EVT FloatVT = Tmp2.getValueType();
1469  EVT IVT = EVT::getIntegerVT(*DAG.getContext(), FloatVT.getSizeInBits());
1470  if (TLI.isTypeLegal(IVT)) {
1471    // Convert to an integer with the same sign bit.
1472    SignBit = DAG.getNode(ISD::BITCAST, dl, IVT, Tmp2);
1473  } else {
1474    // Store the float to memory, then load the sign part out as an integer.
1475    MVT LoadTy = TLI.getPointerTy();
1476    // First create a temporary that is aligned for both the load and store.
1477    SDValue StackPtr = DAG.CreateStackTemporary(FloatVT, LoadTy);
1478    // Then store the float to it.
1479    SDValue Ch =
1480      DAG.getStore(DAG.getEntryNode(), dl, Tmp2, StackPtr, MachinePointerInfo(),
1481                   false, false, 0);
1482    if (TLI.isBigEndian()) {
1483      assert(FloatVT.isByteSized() && "Unsupported floating point type!");
1484      // Load out a legal integer with the same sign bit as the float.
1485      SignBit = DAG.getLoad(LoadTy, dl, Ch, StackPtr, MachinePointerInfo(),
1486                            false, false, false, 0);
1487    } else { // Little endian
1488      SDValue LoadPtr = StackPtr;
1489      // The float may be wider than the integer we are going to load.  Advance
1490      // the pointer so that the loaded integer will contain the sign bit.
1491      unsigned Strides = (FloatVT.getSizeInBits()-1)/LoadTy.getSizeInBits();
1492      unsigned ByteOffset = (Strides * LoadTy.getSizeInBits()) / 8;
1493      LoadPtr = DAG.getNode(ISD::ADD, dl, LoadPtr.getValueType(),
1494                            LoadPtr, DAG.getIntPtrConstant(ByteOffset));
1495      // Load a legal integer containing the sign bit.
1496      SignBit = DAG.getLoad(LoadTy, dl, Ch, LoadPtr, MachinePointerInfo(),
1497                            false, false, false, 0);
1498      // Move the sign bit to the top bit of the loaded integer.
1499      unsigned BitShift = LoadTy.getSizeInBits() -
1500        (FloatVT.getSizeInBits() - 8 * ByteOffset);
1501      assert(BitShift < LoadTy.getSizeInBits() && "Pointer advanced wrong?");
1502      if (BitShift)
1503        SignBit = DAG.getNode(ISD::SHL, dl, LoadTy, SignBit,
1504                              DAG.getConstant(BitShift,
1505                                 TLI.getShiftAmountTy(SignBit.getValueType())));
1506    }
1507  }
1508  // Now get the sign bit proper, by seeing whether the value is negative.
1509  SignBit = DAG.getSetCC(dl, TLI.getSetCCResultType(SignBit.getValueType()),
1510                         SignBit, DAG.getConstant(0, SignBit.getValueType()),
1511                         ISD::SETLT);
1512  // Get the absolute value of the result.
1513  SDValue AbsVal = DAG.getNode(ISD::FABS, dl, Tmp1.getValueType(), Tmp1);
1514  // Select between the nabs and abs value based on the sign bit of
1515  // the input.
1516  return DAG.getNode(ISD::SELECT, dl, AbsVal.getValueType(), SignBit,
1517                     DAG.getNode(ISD::FNEG, dl, AbsVal.getValueType(), AbsVal),
1518                     AbsVal);
1519}
1520
1521void SelectionDAGLegalize::ExpandDYNAMIC_STACKALLOC(SDNode* Node,
1522                                           SmallVectorImpl<SDValue> &Results) {
1523  unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
1524  assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
1525          " not tell us which reg is the stack pointer!");
1526  DebugLoc dl = Node->getDebugLoc();
1527  EVT VT = Node->getValueType(0);
1528  SDValue Tmp1 = SDValue(Node, 0);
1529  SDValue Tmp2 = SDValue(Node, 1);
1530  SDValue Tmp3 = Node->getOperand(2);
1531  SDValue Chain = Tmp1.getOperand(0);
1532
1533  // Chain the dynamic stack allocation so that it doesn't modify the stack
1534  // pointer when other instructions are using the stack.
1535  Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true));
1536
1537  SDValue Size  = Tmp2.getOperand(1);
1538  SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
1539  Chain = SP.getValue(1);
1540  unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
1541  unsigned StackAlign = TM.getFrameLowering()->getStackAlignment();
1542  if (Align > StackAlign)
1543    SP = DAG.getNode(ISD::AND, dl, VT, SP,
1544                      DAG.getConstant(-(uint64_t)Align, VT));
1545  Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size);       // Value
1546  Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1);     // Output chain
1547
1548  Tmp2 = DAG.getCALLSEQ_END(Chain,  DAG.getIntPtrConstant(0, true),
1549                            DAG.getIntPtrConstant(0, true), SDValue());
1550
1551  Results.push_back(Tmp1);
1552  Results.push_back(Tmp2);
1553}
1554
1555/// LegalizeSetCCCondCode - Legalize a SETCC with given LHS and RHS and
1556/// condition code CC on the current target. This routine expands SETCC with
1557/// illegal condition code into AND / OR of multiple SETCC values.
1558void SelectionDAGLegalize::LegalizeSetCCCondCode(EVT VT,
1559                                                 SDValue &LHS, SDValue &RHS,
1560                                                 SDValue &CC,
1561                                                 DebugLoc dl) {
1562  EVT OpVT = LHS.getValueType();
1563  ISD::CondCode CCCode = cast<CondCodeSDNode>(CC)->get();
1564  switch (TLI.getCondCodeAction(CCCode, OpVT)) {
1565  default: llvm_unreachable("Unknown condition code action!");
1566  case TargetLowering::Legal:
1567    // Nothing to do.
1568    break;
1569  case TargetLowering::Expand: {
1570    ISD::CondCode CC1 = ISD::SETCC_INVALID, CC2 = ISD::SETCC_INVALID;
1571    unsigned Opc = 0;
1572    switch (CCCode) {
1573    default: llvm_unreachable("Don't know how to expand this condition!");
1574    case ISD::SETOEQ: CC1 = ISD::SETEQ; CC2 = ISD::SETO;  Opc = ISD::AND; break;
1575    case ISD::SETOGT: CC1 = ISD::SETGT; CC2 = ISD::SETO;  Opc = ISD::AND; break;
1576    case ISD::SETOGE: CC1 = ISD::SETGE; CC2 = ISD::SETO;  Opc = ISD::AND; break;
1577    case ISD::SETOLT: CC1 = ISD::SETLT; CC2 = ISD::SETO;  Opc = ISD::AND; break;
1578    case ISD::SETOLE: CC1 = ISD::SETLE; CC2 = ISD::SETO;  Opc = ISD::AND; break;
1579    case ISD::SETONE: CC1 = ISD::SETNE; CC2 = ISD::SETO;  Opc = ISD::AND; break;
1580    case ISD::SETUEQ: CC1 = ISD::SETEQ; CC2 = ISD::SETUO; Opc = ISD::OR;  break;
1581    case ISD::SETUGT: CC1 = ISD::SETGT; CC2 = ISD::SETUO; Opc = ISD::OR;  break;
1582    case ISD::SETUGE: CC1 = ISD::SETGE; CC2 = ISD::SETUO; Opc = ISD::OR;  break;
1583    case ISD::SETULT: CC1 = ISD::SETLT; CC2 = ISD::SETUO; Opc = ISD::OR;  break;
1584    case ISD::SETULE: CC1 = ISD::SETLE; CC2 = ISD::SETUO; Opc = ISD::OR;  break;
1585    case ISD::SETUNE: CC1 = ISD::SETNE; CC2 = ISD::SETUO; Opc = ISD::OR;  break;
1586    // FIXME: Implement more expansions.
1587    }
1588
1589    SDValue SetCC1 = DAG.getSetCC(dl, VT, LHS, RHS, CC1);
1590    SDValue SetCC2 = DAG.getSetCC(dl, VT, LHS, RHS, CC2);
1591    LHS = DAG.getNode(Opc, dl, VT, SetCC1, SetCC2);
1592    RHS = SDValue();
1593    CC  = SDValue();
1594    break;
1595  }
1596  }
1597}
1598
1599/// EmitStackConvert - Emit a store/load combination to the stack.  This stores
1600/// SrcOp to a stack slot of type SlotVT, truncating it if needed.  It then does
1601/// a load from the stack slot to DestVT, extending it if needed.
1602/// The resultant code need not be legal.
1603SDValue SelectionDAGLegalize::EmitStackConvert(SDValue SrcOp,
1604                                               EVT SlotVT,
1605                                               EVT DestVT,
1606                                               DebugLoc dl) {
1607  // Create the stack frame object.
1608  unsigned SrcAlign =
1609    TLI.getTargetData()->getPrefTypeAlignment(SrcOp.getValueType().
1610                                              getTypeForEVT(*DAG.getContext()));
1611  SDValue FIPtr = DAG.CreateStackTemporary(SlotVT, SrcAlign);
1612
1613  FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(FIPtr);
1614  int SPFI = StackPtrFI->getIndex();
1615  MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(SPFI);
1616
1617  unsigned SrcSize = SrcOp.getValueType().getSizeInBits();
1618  unsigned SlotSize = SlotVT.getSizeInBits();
1619  unsigned DestSize = DestVT.getSizeInBits();
1620  Type *DestType = DestVT.getTypeForEVT(*DAG.getContext());
1621  unsigned DestAlign = TLI.getTargetData()->getPrefTypeAlignment(DestType);
1622
1623  // Emit a store to the stack slot.  Use a truncstore if the input value is
1624  // later than DestVT.
1625  SDValue Store;
1626
1627  if (SrcSize > SlotSize)
1628    Store = DAG.getTruncStore(DAG.getEntryNode(), dl, SrcOp, FIPtr,
1629                              PtrInfo, SlotVT, false, false, SrcAlign);
1630  else {
1631    assert(SrcSize == SlotSize && "Invalid store");
1632    Store = DAG.getStore(DAG.getEntryNode(), dl, SrcOp, FIPtr,
1633                         PtrInfo, false, false, SrcAlign);
1634  }
1635
1636  // Result is a load from the stack slot.
1637  if (SlotSize == DestSize)
1638    return DAG.getLoad(DestVT, dl, Store, FIPtr, PtrInfo,
1639                       false, false, false, DestAlign);
1640
1641  assert(SlotSize < DestSize && "Unknown extension!");
1642  return DAG.getExtLoad(ISD::EXTLOAD, dl, DestVT, Store, FIPtr,
1643                        PtrInfo, SlotVT, false, false, DestAlign);
1644}
1645
1646SDValue SelectionDAGLegalize::ExpandSCALAR_TO_VECTOR(SDNode *Node) {
1647  DebugLoc dl = Node->getDebugLoc();
1648  // Create a vector sized/aligned stack slot, store the value to element #0,
1649  // then load the whole vector back out.
1650  SDValue StackPtr = DAG.CreateStackTemporary(Node->getValueType(0));
1651
1652  FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(StackPtr);
1653  int SPFI = StackPtrFI->getIndex();
1654
1655  SDValue Ch = DAG.getTruncStore(DAG.getEntryNode(), dl, Node->getOperand(0),
1656                                 StackPtr,
1657                                 MachinePointerInfo::getFixedStack(SPFI),
1658                                 Node->getValueType(0).getVectorElementType(),
1659                                 false, false, 0);
1660  return DAG.getLoad(Node->getValueType(0), dl, Ch, StackPtr,
1661                     MachinePointerInfo::getFixedStack(SPFI),
1662                     false, false, false, 0);
1663}
1664
1665
1666/// ExpandBUILD_VECTOR - Expand a BUILD_VECTOR node on targets that don't
1667/// support the operation, but do support the resultant vector type.
1668SDValue SelectionDAGLegalize::ExpandBUILD_VECTOR(SDNode *Node) {
1669  unsigned NumElems = Node->getNumOperands();
1670  SDValue Value1, Value2;
1671  DebugLoc dl = Node->getDebugLoc();
1672  EVT VT = Node->getValueType(0);
1673  EVT OpVT = Node->getOperand(0).getValueType();
1674  EVT EltVT = VT.getVectorElementType();
1675
1676  // If the only non-undef value is the low element, turn this into a
1677  // SCALAR_TO_VECTOR node.  If this is { X, X, X, X }, determine X.
1678  bool isOnlyLowElement = true;
1679  bool MoreThanTwoValues = false;
1680  bool isConstant = true;
1681  for (unsigned i = 0; i < NumElems; ++i) {
1682    SDValue V = Node->getOperand(i);
1683    if (V.getOpcode() == ISD::UNDEF)
1684      continue;
1685    if (i > 0)
1686      isOnlyLowElement = false;
1687    if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
1688      isConstant = false;
1689
1690    if (!Value1.getNode()) {
1691      Value1 = V;
1692    } else if (!Value2.getNode()) {
1693      if (V != Value1)
1694        Value2 = V;
1695    } else if (V != Value1 && V != Value2) {
1696      MoreThanTwoValues = true;
1697    }
1698  }
1699
1700  if (!Value1.getNode())
1701    return DAG.getUNDEF(VT);
1702
1703  if (isOnlyLowElement)
1704    return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Node->getOperand(0));
1705
1706  // If all elements are constants, create a load from the constant pool.
1707  if (isConstant) {
1708    SmallVector<Constant*, 16> CV;
1709    for (unsigned i = 0, e = NumElems; i != e; ++i) {
1710      if (ConstantFPSDNode *V =
1711          dyn_cast<ConstantFPSDNode>(Node->getOperand(i))) {
1712        CV.push_back(const_cast<ConstantFP *>(V->getConstantFPValue()));
1713      } else if (ConstantSDNode *V =
1714                 dyn_cast<ConstantSDNode>(Node->getOperand(i))) {
1715        if (OpVT==EltVT)
1716          CV.push_back(const_cast<ConstantInt *>(V->getConstantIntValue()));
1717        else {
1718          // If OpVT and EltVT don't match, EltVT is not legal and the
1719          // element values have been promoted/truncated earlier.  Undo this;
1720          // we don't want a v16i8 to become a v16i32 for example.
1721          const ConstantInt *CI = V->getConstantIntValue();
1722          CV.push_back(ConstantInt::get(EltVT.getTypeForEVT(*DAG.getContext()),
1723                                        CI->getZExtValue()));
1724        }
1725      } else {
1726        assert(Node->getOperand(i).getOpcode() == ISD::UNDEF);
1727        Type *OpNTy = EltVT.getTypeForEVT(*DAG.getContext());
1728        CV.push_back(UndefValue::get(OpNTy));
1729      }
1730    }
1731    Constant *CP = ConstantVector::get(CV);
1732    SDValue CPIdx = DAG.getConstantPool(CP, TLI.getPointerTy());
1733    unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
1734    return DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
1735                       MachinePointerInfo::getConstantPool(),
1736                       false, false, false, Alignment);
1737  }
1738
1739  if (!MoreThanTwoValues) {
1740    SmallVector<int, 8> ShuffleVec(NumElems, -1);
1741    for (unsigned i = 0; i < NumElems; ++i) {
1742      SDValue V = Node->getOperand(i);
1743      if (V.getOpcode() == ISD::UNDEF)
1744        continue;
1745      ShuffleVec[i] = V == Value1 ? 0 : NumElems;
1746    }
1747    if (TLI.isShuffleMaskLegal(ShuffleVec, Node->getValueType(0))) {
1748      // Get the splatted value into the low element of a vector register.
1749      SDValue Vec1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value1);
1750      SDValue Vec2;
1751      if (Value2.getNode())
1752        Vec2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value2);
1753      else
1754        Vec2 = DAG.getUNDEF(VT);
1755
1756      // Return shuffle(LowValVec, undef, <0,0,0,0>)
1757      return DAG.getVectorShuffle(VT, dl, Vec1, Vec2, ShuffleVec.data());
1758    }
1759  }
1760
1761  // Otherwise, we can't handle this case efficiently.
1762  return ExpandVectorBuildThroughStack(Node);
1763}
1764
1765// ExpandLibCall - Expand a node into a call to a libcall.  If the result value
1766// does not fit into a register, return the lo part and set the hi part to the
1767// by-reg argument.  If it does fit into a single register, return the result
1768// and leave the Hi part unset.
1769SDValue SelectionDAGLegalize::ExpandLibCall(RTLIB::Libcall LC, SDNode *Node,
1770                                            bool isSigned) {
1771  TargetLowering::ArgListTy Args;
1772  TargetLowering::ArgListEntry Entry;
1773  for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
1774    EVT ArgVT = Node->getOperand(i).getValueType();
1775    Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
1776    Entry.Node = Node->getOperand(i); Entry.Ty = ArgTy;
1777    Entry.isSExt = isSigned;
1778    Entry.isZExt = !isSigned;
1779    Args.push_back(Entry);
1780  }
1781  SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
1782                                         TLI.getPointerTy());
1783
1784  Type *RetTy = Node->getValueType(0).getTypeForEVT(*DAG.getContext());
1785
1786  // By default, the input chain to this libcall is the entry node of the
1787  // function. If the libcall is going to be emitted as a tail call then
1788  // TLI.isUsedByReturnOnly will change it to the right chain if the return
1789  // node which is being folded has a non-entry input chain.
1790  SDValue InChain = DAG.getEntryNode();
1791
1792  // isTailCall may be true since the callee does not reference caller stack
1793  // frame. Check if it's in the right position.
1794  SDValue TCChain = InChain;
1795  bool isTailCall = isInTailCallPosition(DAG, Node, TCChain, TLI);
1796  if (isTailCall)
1797    InChain = TCChain;
1798
1799  std::pair<SDValue, SDValue> CallInfo =
1800    TLI.LowerCallTo(InChain, RetTy, isSigned, !isSigned, false, false,
1801                    0, TLI.getLibcallCallingConv(LC), isTailCall,
1802                    /*doesNotReturn=*/false, /*isReturnValueUsed=*/true,
1803                    Callee, Args, DAG, Node->getDebugLoc());
1804
1805  if (!CallInfo.second.getNode())
1806    // It's a tailcall, return the chain (which is the DAG root).
1807    return DAG.getRoot();
1808
1809  return CallInfo.first;
1810}
1811
1812/// ExpandLibCall - Generate a libcall taking the given operands as arguments
1813/// and returning a result of type RetVT.
1814SDValue SelectionDAGLegalize::ExpandLibCall(RTLIB::Libcall LC, EVT RetVT,
1815                                            const SDValue *Ops, unsigned NumOps,
1816                                            bool isSigned, DebugLoc dl) {
1817  TargetLowering::ArgListTy Args;
1818  Args.reserve(NumOps);
1819
1820  TargetLowering::ArgListEntry Entry;
1821  for (unsigned i = 0; i != NumOps; ++i) {
1822    Entry.Node = Ops[i];
1823    Entry.Ty = Entry.Node.getValueType().getTypeForEVT(*DAG.getContext());
1824    Entry.isSExt = isSigned;
1825    Entry.isZExt = !isSigned;
1826    Args.push_back(Entry);
1827  }
1828  SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
1829                                         TLI.getPointerTy());
1830
1831  Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
1832  std::pair<SDValue,SDValue> CallInfo =
1833  TLI.LowerCallTo(DAG.getEntryNode(), RetTy, isSigned, !isSigned, false,
1834                  false, 0, TLI.getLibcallCallingConv(LC), /*isTailCall=*/false,
1835                  /*doesNotReturn=*/false, /*isReturnValueUsed=*/true,
1836                  Callee, Args, DAG, dl);
1837
1838  return CallInfo.first;
1839}
1840
1841// ExpandChainLibCall - Expand a node into a call to a libcall. Similar to
1842// ExpandLibCall except that the first operand is the in-chain.
1843std::pair<SDValue, SDValue>
1844SelectionDAGLegalize::ExpandChainLibCall(RTLIB::Libcall LC,
1845                                         SDNode *Node,
1846                                         bool isSigned) {
1847  SDValue InChain = Node->getOperand(0);
1848
1849  TargetLowering::ArgListTy Args;
1850  TargetLowering::ArgListEntry Entry;
1851  for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i) {
1852    EVT ArgVT = Node->getOperand(i).getValueType();
1853    Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
1854    Entry.Node = Node->getOperand(i);
1855    Entry.Ty = ArgTy;
1856    Entry.isSExt = isSigned;
1857    Entry.isZExt = !isSigned;
1858    Args.push_back(Entry);
1859  }
1860  SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
1861                                         TLI.getPointerTy());
1862
1863  Type *RetTy = Node->getValueType(0).getTypeForEVT(*DAG.getContext());
1864  std::pair<SDValue, SDValue> CallInfo =
1865    TLI.LowerCallTo(InChain, RetTy, isSigned, !isSigned, false, false,
1866                    0, TLI.getLibcallCallingConv(LC), /*isTailCall=*/false,
1867                    /*doesNotReturn=*/false, /*isReturnValueUsed=*/true,
1868                    Callee, Args, DAG, Node->getDebugLoc());
1869
1870  return CallInfo;
1871}
1872
1873SDValue SelectionDAGLegalize::ExpandFPLibCall(SDNode* Node,
1874                                              RTLIB::Libcall Call_F32,
1875                                              RTLIB::Libcall Call_F64,
1876                                              RTLIB::Libcall Call_F80,
1877                                              RTLIB::Libcall Call_PPCF128) {
1878  RTLIB::Libcall LC;
1879  switch (Node->getValueType(0).getSimpleVT().SimpleTy) {
1880  default: llvm_unreachable("Unexpected request for libcall!");
1881  case MVT::f32: LC = Call_F32; break;
1882  case MVT::f64: LC = Call_F64; break;
1883  case MVT::f80: LC = Call_F80; break;
1884  case MVT::ppcf128: LC = Call_PPCF128; break;
1885  }
1886  return ExpandLibCall(LC, Node, false);
1887}
1888
1889SDValue SelectionDAGLegalize::ExpandIntLibCall(SDNode* Node, bool isSigned,
1890                                               RTLIB::Libcall Call_I8,
1891                                               RTLIB::Libcall Call_I16,
1892                                               RTLIB::Libcall Call_I32,
1893                                               RTLIB::Libcall Call_I64,
1894                                               RTLIB::Libcall Call_I128) {
1895  RTLIB::Libcall LC;
1896  switch (Node->getValueType(0).getSimpleVT().SimpleTy) {
1897  default: llvm_unreachable("Unexpected request for libcall!");
1898  case MVT::i8:   LC = Call_I8; break;
1899  case MVT::i16:  LC = Call_I16; break;
1900  case MVT::i32:  LC = Call_I32; break;
1901  case MVT::i64:  LC = Call_I64; break;
1902  case MVT::i128: LC = Call_I128; break;
1903  }
1904  return ExpandLibCall(LC, Node, isSigned);
1905}
1906
1907/// isDivRemLibcallAvailable - Return true if divmod libcall is available.
1908static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned,
1909                                     const TargetLowering &TLI) {
1910  RTLIB::Libcall LC;
1911  switch (Node->getValueType(0).getSimpleVT().SimpleTy) {
1912  default: llvm_unreachable("Unexpected request for libcall!");
1913  case MVT::i8:   LC= isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
1914  case MVT::i16:  LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
1915  case MVT::i32:  LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
1916  case MVT::i64:  LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
1917  case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
1918  }
1919
1920  return TLI.getLibcallName(LC) != 0;
1921}
1922
1923/// UseDivRem - Only issue divrem libcall if both quotient and remainder are
1924/// needed.
1925static bool UseDivRem(SDNode *Node, bool isSigned, bool isDIV) {
1926  unsigned OtherOpcode = 0;
1927  if (isSigned)
1928    OtherOpcode = isDIV ? ISD::SREM : ISD::SDIV;
1929  else
1930    OtherOpcode = isDIV ? ISD::UREM : ISD::UDIV;
1931
1932  SDValue Op0 = Node->getOperand(0);
1933  SDValue Op1 = Node->getOperand(1);
1934  for (SDNode::use_iterator UI = Op0.getNode()->use_begin(),
1935         UE = Op0.getNode()->use_end(); UI != UE; ++UI) {
1936    SDNode *User = *UI;
1937    if (User == Node)
1938      continue;
1939    if (User->getOpcode() == OtherOpcode &&
1940        User->getOperand(0) == Op0 &&
1941        User->getOperand(1) == Op1)
1942      return true;
1943  }
1944  return false;
1945}
1946
1947/// ExpandDivRemLibCall - Issue libcalls to __{u}divmod to compute div / rem
1948/// pairs.
1949void
1950SelectionDAGLegalize::ExpandDivRemLibCall(SDNode *Node,
1951                                          SmallVectorImpl<SDValue> &Results) {
1952  unsigned Opcode = Node->getOpcode();
1953  bool isSigned = Opcode == ISD::SDIVREM;
1954
1955  RTLIB::Libcall LC;
1956  switch (Node->getValueType(0).getSimpleVT().SimpleTy) {
1957  default: llvm_unreachable("Unexpected request for libcall!");
1958  case MVT::i8:   LC= isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
1959  case MVT::i16:  LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
1960  case MVT::i32:  LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
1961  case MVT::i64:  LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
1962  case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
1963  }
1964
1965  // The input chain to this libcall is the entry node of the function.
1966  // Legalizing the call will automatically add the previous call to the
1967  // dependence.
1968  SDValue InChain = DAG.getEntryNode();
1969
1970  EVT RetVT = Node->getValueType(0);
1971  Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
1972
1973  TargetLowering::ArgListTy Args;
1974  TargetLowering::ArgListEntry Entry;
1975  for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
1976    EVT ArgVT = Node->getOperand(i).getValueType();
1977    Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
1978    Entry.Node = Node->getOperand(i); Entry.Ty = ArgTy;
1979    Entry.isSExt = isSigned;
1980    Entry.isZExt = !isSigned;
1981    Args.push_back(Entry);
1982  }
1983
1984  // Also pass the return address of the remainder.
1985  SDValue FIPtr = DAG.CreateStackTemporary(RetVT);
1986  Entry.Node = FIPtr;
1987  Entry.Ty = RetTy->getPointerTo();
1988  Entry.isSExt = isSigned;
1989  Entry.isZExt = !isSigned;
1990  Args.push_back(Entry);
1991
1992  SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
1993                                         TLI.getPointerTy());
1994
1995  DebugLoc dl = Node->getDebugLoc();
1996  std::pair<SDValue, SDValue> CallInfo =
1997    TLI.LowerCallTo(InChain, RetTy, isSigned, !isSigned, false, false,
1998                    0, TLI.getLibcallCallingConv(LC), /*isTailCall=*/false,
1999                    /*doesNotReturn=*/false, /*isReturnValueUsed=*/true,
2000                    Callee, Args, DAG, dl);
2001
2002  // Remainder is loaded back from the stack frame.
2003  SDValue Rem = DAG.getLoad(RetVT, dl, CallInfo.second, FIPtr,
2004                            MachinePointerInfo(), false, false, false, 0);
2005  Results.push_back(CallInfo.first);
2006  Results.push_back(Rem);
2007}
2008
2009/// ExpandLegalINT_TO_FP - This function is responsible for legalizing a
2010/// INT_TO_FP operation of the specified operand when the target requests that
2011/// we expand it.  At this point, we know that the result and operand types are
2012/// legal for the target.
2013SDValue SelectionDAGLegalize::ExpandLegalINT_TO_FP(bool isSigned,
2014                                                   SDValue Op0,
2015                                                   EVT DestVT,
2016                                                   DebugLoc dl) {
2017  if (Op0.getValueType() == MVT::i32) {
2018    // simple 32-bit [signed|unsigned] integer to float/double expansion
2019
2020    // Get the stack frame index of a 8 byte buffer.
2021    SDValue StackSlot = DAG.CreateStackTemporary(MVT::f64);
2022
2023    // word offset constant for Hi/Lo address computation
2024    SDValue WordOff = DAG.getConstant(sizeof(int), TLI.getPointerTy());
2025    // set up Hi and Lo (into buffer) address based on endian
2026    SDValue Hi = StackSlot;
2027    SDValue Lo = DAG.getNode(ISD::ADD, dl,
2028                             TLI.getPointerTy(), StackSlot, WordOff);
2029    if (TLI.isLittleEndian())
2030      std::swap(Hi, Lo);
2031
2032    // if signed map to unsigned space
2033    SDValue Op0Mapped;
2034    if (isSigned) {
2035      // constant used to invert sign bit (signed to unsigned mapping)
2036      SDValue SignBit = DAG.getConstant(0x80000000u, MVT::i32);
2037      Op0Mapped = DAG.getNode(ISD::XOR, dl, MVT::i32, Op0, SignBit);
2038    } else {
2039      Op0Mapped = Op0;
2040    }
2041    // store the lo of the constructed double - based on integer input
2042    SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl,
2043                                  Op0Mapped, Lo, MachinePointerInfo(),
2044                                  false, false, 0);
2045    // initial hi portion of constructed double
2046    SDValue InitialHi = DAG.getConstant(0x43300000u, MVT::i32);
2047    // store the hi of the constructed double - biased exponent
2048    SDValue Store2 = DAG.getStore(Store1, dl, InitialHi, Hi,
2049                                  MachinePointerInfo(),
2050                                  false, false, 0);
2051    // load the constructed double
2052    SDValue Load = DAG.getLoad(MVT::f64, dl, Store2, StackSlot,
2053                               MachinePointerInfo(), false, false, false, 0);
2054    // FP constant to bias correct the final result
2055    SDValue Bias = DAG.getConstantFP(isSigned ?
2056                                     BitsToDouble(0x4330000080000000ULL) :
2057                                     BitsToDouble(0x4330000000000000ULL),
2058                                     MVT::f64);
2059    // subtract the bias
2060    SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Load, Bias);
2061    // final result
2062    SDValue Result;
2063    // handle final rounding
2064    if (DestVT == MVT::f64) {
2065      // do nothing
2066      Result = Sub;
2067    } else if (DestVT.bitsLT(MVT::f64)) {
2068      Result = DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
2069                           DAG.getIntPtrConstant(0));
2070    } else if (DestVT.bitsGT(MVT::f64)) {
2071      Result = DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
2072    }
2073    return Result;
2074  }
2075  assert(!isSigned && "Legalize cannot Expand SINT_TO_FP for i64 yet");
2076  // Code below here assumes !isSigned without checking again.
2077
2078  // Implementation of unsigned i64 to f64 following the algorithm in
2079  // __floatundidf in compiler_rt. This implementation has the advantage
2080  // of performing rounding correctly, both in the default rounding mode
2081  // and in all alternate rounding modes.
2082  // TODO: Generalize this for use with other types.
2083  if (Op0.getValueType() == MVT::i64 && DestVT == MVT::f64) {
2084    SDValue TwoP52 =
2085      DAG.getConstant(UINT64_C(0x4330000000000000), MVT::i64);
2086    SDValue TwoP84PlusTwoP52 =
2087      DAG.getConstantFP(BitsToDouble(UINT64_C(0x4530000000100000)), MVT::f64);
2088    SDValue TwoP84 =
2089      DAG.getConstant(UINT64_C(0x4530000000000000), MVT::i64);
2090
2091    SDValue Lo = DAG.getZeroExtendInReg(Op0, dl, MVT::i32);
2092    SDValue Hi = DAG.getNode(ISD::SRL, dl, MVT::i64, Op0,
2093                             DAG.getConstant(32, MVT::i64));
2094    SDValue LoOr = DAG.getNode(ISD::OR, dl, MVT::i64, Lo, TwoP52);
2095    SDValue HiOr = DAG.getNode(ISD::OR, dl, MVT::i64, Hi, TwoP84);
2096    SDValue LoFlt = DAG.getNode(ISD::BITCAST, dl, MVT::f64, LoOr);
2097    SDValue HiFlt = DAG.getNode(ISD::BITCAST, dl, MVT::f64, HiOr);
2098    SDValue HiSub = DAG.getNode(ISD::FSUB, dl, MVT::f64, HiFlt,
2099                                TwoP84PlusTwoP52);
2100    return DAG.getNode(ISD::FADD, dl, MVT::f64, LoFlt, HiSub);
2101  }
2102
2103  // Implementation of unsigned i64 to f32.
2104  // TODO: Generalize this for use with other types.
2105  if (Op0.getValueType() == MVT::i64 && DestVT == MVT::f32) {
2106    // For unsigned conversions, convert them to signed conversions using the
2107    // algorithm from the x86_64 __floatundidf in compiler_rt.
2108    if (!isSigned) {
2109      SDValue Fast = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, Op0);
2110
2111      SDValue ShiftConst =
2112          DAG.getConstant(1, TLI.getShiftAmountTy(Op0.getValueType()));
2113      SDValue Shr = DAG.getNode(ISD::SRL, dl, MVT::i64, Op0, ShiftConst);
2114      SDValue AndConst = DAG.getConstant(1, MVT::i64);
2115      SDValue And = DAG.getNode(ISD::AND, dl, MVT::i64, Op0, AndConst);
2116      SDValue Or = DAG.getNode(ISD::OR, dl, MVT::i64, And, Shr);
2117
2118      SDValue SignCvt = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, Or);
2119      SDValue Slow = DAG.getNode(ISD::FADD, dl, MVT::f32, SignCvt, SignCvt);
2120
2121      // TODO: This really should be implemented using a branch rather than a
2122      // select.  We happen to get lucky and machinesink does the right
2123      // thing most of the time.  This would be a good candidate for a
2124      //pseudo-op, or, even better, for whole-function isel.
2125      SDValue SignBitTest = DAG.getSetCC(dl, TLI.getSetCCResultType(MVT::i64),
2126        Op0, DAG.getConstant(0, MVT::i64), ISD::SETLT);
2127      return DAG.getNode(ISD::SELECT, dl, MVT::f32, SignBitTest, Slow, Fast);
2128    }
2129
2130    // Otherwise, implement the fully general conversion.
2131
2132    SDValue And = DAG.getNode(ISD::AND, dl, MVT::i64, Op0,
2133         DAG.getConstant(UINT64_C(0xfffffffffffff800), MVT::i64));
2134    SDValue Or = DAG.getNode(ISD::OR, dl, MVT::i64, And,
2135         DAG.getConstant(UINT64_C(0x800), MVT::i64));
2136    SDValue And2 = DAG.getNode(ISD::AND, dl, MVT::i64, Op0,
2137         DAG.getConstant(UINT64_C(0x7ff), MVT::i64));
2138    SDValue Ne = DAG.getSetCC(dl, TLI.getSetCCResultType(MVT::i64),
2139                   And2, DAG.getConstant(UINT64_C(0), MVT::i64), ISD::SETNE);
2140    SDValue Sel = DAG.getNode(ISD::SELECT, dl, MVT::i64, Ne, Or, Op0);
2141    SDValue Ge = DAG.getSetCC(dl, TLI.getSetCCResultType(MVT::i64),
2142                   Op0, DAG.getConstant(UINT64_C(0x0020000000000000), MVT::i64),
2143                   ISD::SETUGE);
2144    SDValue Sel2 = DAG.getNode(ISD::SELECT, dl, MVT::i64, Ge, Sel, Op0);
2145    EVT SHVT = TLI.getShiftAmountTy(Sel2.getValueType());
2146
2147    SDValue Sh = DAG.getNode(ISD::SRL, dl, MVT::i64, Sel2,
2148                             DAG.getConstant(32, SHVT));
2149    SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Sh);
2150    SDValue Fcvt = DAG.getNode(ISD::UINT_TO_FP, dl, MVT::f64, Trunc);
2151    SDValue TwoP32 =
2152      DAG.getConstantFP(BitsToDouble(UINT64_C(0x41f0000000000000)), MVT::f64);
2153    SDValue Fmul = DAG.getNode(ISD::FMUL, dl, MVT::f64, TwoP32, Fcvt);
2154    SDValue Lo = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Sel2);
2155    SDValue Fcvt2 = DAG.getNode(ISD::UINT_TO_FP, dl, MVT::f64, Lo);
2156    SDValue Fadd = DAG.getNode(ISD::FADD, dl, MVT::f64, Fmul, Fcvt2);
2157    return DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, Fadd,
2158                       DAG.getIntPtrConstant(0));
2159  }
2160
2161  SDValue Tmp1 = DAG.getNode(ISD::SINT_TO_FP, dl, DestVT, Op0);
2162
2163  SDValue SignSet = DAG.getSetCC(dl, TLI.getSetCCResultType(Op0.getValueType()),
2164                                 Op0, DAG.getConstant(0, Op0.getValueType()),
2165                                 ISD::SETLT);
2166  SDValue Zero = DAG.getIntPtrConstant(0), Four = DAG.getIntPtrConstant(4);
2167  SDValue CstOffset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(),
2168                                    SignSet, Four, Zero);
2169
2170  // If the sign bit of the integer is set, the large number will be treated
2171  // as a negative number.  To counteract this, the dynamic code adds an
2172  // offset depending on the data type.
2173  uint64_t FF;
2174  switch (Op0.getValueType().getSimpleVT().SimpleTy) {
2175  default: llvm_unreachable("Unsupported integer type!");
2176  case MVT::i8 : FF = 0x43800000ULL; break;  // 2^8  (as a float)
2177  case MVT::i16: FF = 0x47800000ULL; break;  // 2^16 (as a float)
2178  case MVT::i32: FF = 0x4F800000ULL; break;  // 2^32 (as a float)
2179  case MVT::i64: FF = 0x5F800000ULL; break;  // 2^64 (as a float)
2180  }
2181  if (TLI.isLittleEndian()) FF <<= 32;
2182  Constant *FudgeFactor = ConstantInt::get(
2183                                       Type::getInt64Ty(*DAG.getContext()), FF);
2184
2185  SDValue CPIdx = DAG.getConstantPool(FudgeFactor, TLI.getPointerTy());
2186  unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
2187  CPIdx = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(), CPIdx, CstOffset);
2188  Alignment = std::min(Alignment, 4u);
2189  SDValue FudgeInReg;
2190  if (DestVT == MVT::f32)
2191    FudgeInReg = DAG.getLoad(MVT::f32, dl, DAG.getEntryNode(), CPIdx,
2192                             MachinePointerInfo::getConstantPool(),
2193                             false, false, false, Alignment);
2194  else {
2195    SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, DestVT,
2196                                  DAG.getEntryNode(), CPIdx,
2197                                  MachinePointerInfo::getConstantPool(),
2198                                  MVT::f32, false, false, Alignment);
2199    HandleSDNode Handle(Load);
2200    LegalizeOp(Load.getNode());
2201    FudgeInReg = Handle.getValue();
2202  }
2203
2204  return DAG.getNode(ISD::FADD, dl, DestVT, Tmp1, FudgeInReg);
2205}
2206
2207/// PromoteLegalINT_TO_FP - This function is responsible for legalizing a
2208/// *INT_TO_FP operation of the specified operand when the target requests that
2209/// we promote it.  At this point, we know that the result and operand types are
2210/// legal for the target, and that there is a legal UINT_TO_FP or SINT_TO_FP
2211/// operation that takes a larger input.
2212SDValue SelectionDAGLegalize::PromoteLegalINT_TO_FP(SDValue LegalOp,
2213                                                    EVT DestVT,
2214                                                    bool isSigned,
2215                                                    DebugLoc dl) {
2216  // First step, figure out the appropriate *INT_TO_FP operation to use.
2217  EVT NewInTy = LegalOp.getValueType();
2218
2219  unsigned OpToUse = 0;
2220
2221  // Scan for the appropriate larger type to use.
2222  while (1) {
2223    NewInTy = (MVT::SimpleValueType)(NewInTy.getSimpleVT().SimpleTy+1);
2224    assert(NewInTy.isInteger() && "Ran out of possibilities!");
2225
2226    // If the target supports SINT_TO_FP of this type, use it.
2227    if (TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, NewInTy)) {
2228      OpToUse = ISD::SINT_TO_FP;
2229      break;
2230    }
2231    if (isSigned) continue;
2232
2233    // If the target supports UINT_TO_FP of this type, use it.
2234    if (TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, NewInTy)) {
2235      OpToUse = ISD::UINT_TO_FP;
2236      break;
2237    }
2238
2239    // Otherwise, try a larger type.
2240  }
2241
2242  // Okay, we found the operation and type to use.  Zero extend our input to the
2243  // desired type then run the operation on it.
2244  return DAG.getNode(OpToUse, dl, DestVT,
2245                     DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
2246                                 dl, NewInTy, LegalOp));
2247}
2248
2249/// PromoteLegalFP_TO_INT - This function is responsible for legalizing a
2250/// FP_TO_*INT operation of the specified operand when the target requests that
2251/// we promote it.  At this point, we know that the result and operand types are
2252/// legal for the target, and that there is a legal FP_TO_UINT or FP_TO_SINT
2253/// operation that returns a larger result.
2254SDValue SelectionDAGLegalize::PromoteLegalFP_TO_INT(SDValue LegalOp,
2255                                                    EVT DestVT,
2256                                                    bool isSigned,
2257                                                    DebugLoc dl) {
2258  // First step, figure out the appropriate FP_TO*INT operation to use.
2259  EVT NewOutTy = DestVT;
2260
2261  unsigned OpToUse = 0;
2262
2263  // Scan for the appropriate larger type to use.
2264  while (1) {
2265    NewOutTy = (MVT::SimpleValueType)(NewOutTy.getSimpleVT().SimpleTy+1);
2266    assert(NewOutTy.isInteger() && "Ran out of possibilities!");
2267
2268    if (TLI.isOperationLegalOrCustom(ISD::FP_TO_SINT, NewOutTy)) {
2269      OpToUse = ISD::FP_TO_SINT;
2270      break;
2271    }
2272
2273    if (TLI.isOperationLegalOrCustom(ISD::FP_TO_UINT, NewOutTy)) {
2274      OpToUse = ISD::FP_TO_UINT;
2275      break;
2276    }
2277
2278    // Otherwise, try a larger type.
2279  }
2280
2281
2282  // Okay, we found the operation and type to use.
2283  SDValue Operation = DAG.getNode(OpToUse, dl, NewOutTy, LegalOp);
2284
2285  // Truncate the result of the extended FP_TO_*INT operation to the desired
2286  // size.
2287  return DAG.getNode(ISD::TRUNCATE, dl, DestVT, Operation);
2288}
2289
2290/// ExpandBSWAP - Open code the operations for BSWAP of the specified operation.
2291///
2292SDValue SelectionDAGLegalize::ExpandBSWAP(SDValue Op, DebugLoc dl) {
2293  EVT VT = Op.getValueType();
2294  EVT SHVT = TLI.getShiftAmountTy(VT);
2295  SDValue Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8;
2296  switch (VT.getSimpleVT().SimpleTy) {
2297  default: llvm_unreachable("Unhandled Expand type in BSWAP!");
2298  case MVT::i16:
2299    Tmp2 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, SHVT));
2300    Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, SHVT));
2301    return DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
2302  case MVT::i32:
2303    Tmp4 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, SHVT));
2304    Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, SHVT));
2305    Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, SHVT));
2306    Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, SHVT));
2307    Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3, DAG.getConstant(0xFF0000, VT));
2308    Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(0xFF00, VT));
2309    Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
2310    Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
2311    return DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
2312  case MVT::i64:
2313    Tmp8 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(56, SHVT));
2314    Tmp7 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(40, SHVT));
2315    Tmp6 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, SHVT));
2316    Tmp5 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, SHVT));
2317    Tmp4 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, SHVT));
2318    Tmp3 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, SHVT));
2319    Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(40, SHVT));
2320    Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(56, SHVT));
2321    Tmp7 = DAG.getNode(ISD::AND, dl, VT, Tmp7, DAG.getConstant(255ULL<<48, VT));
2322    Tmp6 = DAG.getNode(ISD::AND, dl, VT, Tmp6, DAG.getConstant(255ULL<<40, VT));
2323    Tmp5 = DAG.getNode(ISD::AND, dl, VT, Tmp5, DAG.getConstant(255ULL<<32, VT));
2324    Tmp4 = DAG.getNode(ISD::AND, dl, VT, Tmp4, DAG.getConstant(255ULL<<24, VT));
2325    Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3, DAG.getConstant(255ULL<<16, VT));
2326    Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(255ULL<<8 , VT));
2327    Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp7);
2328    Tmp6 = DAG.getNode(ISD::OR, dl, VT, Tmp6, Tmp5);
2329    Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
2330    Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
2331    Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp6);
2332    Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
2333    return DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp4);
2334  }
2335}
2336
2337/// SplatByte - Distribute ByteVal over NumBits bits.
2338// FIXME: Move this helper to a common place.
2339static APInt SplatByte(unsigned NumBits, uint8_t ByteVal) {
2340  APInt Val = APInt(NumBits, ByteVal);
2341  unsigned Shift = 8;
2342  for (unsigned i = NumBits; i > 8; i >>= 1) {
2343    Val = (Val << Shift) | Val;
2344    Shift <<= 1;
2345  }
2346  return Val;
2347}
2348
2349/// ExpandBitCount - Expand the specified bitcount instruction into operations.
2350///
2351SDValue SelectionDAGLegalize::ExpandBitCount(unsigned Opc, SDValue Op,
2352                                             DebugLoc dl) {
2353  switch (Opc) {
2354  default: llvm_unreachable("Cannot expand this yet!");
2355  case ISD::CTPOP: {
2356    EVT VT = Op.getValueType();
2357    EVT ShVT = TLI.getShiftAmountTy(VT);
2358    unsigned Len = VT.getSizeInBits();
2359
2360    assert(VT.isInteger() && Len <= 128 && Len % 8 == 0 &&
2361           "CTPOP not implemented for this type.");
2362
2363    // This is the "best" algorithm from
2364    // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
2365
2366    SDValue Mask55 = DAG.getConstant(SplatByte(Len, 0x55), VT);
2367    SDValue Mask33 = DAG.getConstant(SplatByte(Len, 0x33), VT);
2368    SDValue Mask0F = DAG.getConstant(SplatByte(Len, 0x0F), VT);
2369    SDValue Mask01 = DAG.getConstant(SplatByte(Len, 0x01), VT);
2370
2371    // v = v - ((v >> 1) & 0x55555555...)
2372    Op = DAG.getNode(ISD::SUB, dl, VT, Op,
2373                     DAG.getNode(ISD::AND, dl, VT,
2374                                 DAG.getNode(ISD::SRL, dl, VT, Op,
2375                                             DAG.getConstant(1, ShVT)),
2376                                 Mask55));
2377    // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
2378    Op = DAG.getNode(ISD::ADD, dl, VT,
2379                     DAG.getNode(ISD::AND, dl, VT, Op, Mask33),
2380                     DAG.getNode(ISD::AND, dl, VT,
2381                                 DAG.getNode(ISD::SRL, dl, VT, Op,
2382                                             DAG.getConstant(2, ShVT)),
2383                                 Mask33));
2384    // v = (v + (v >> 4)) & 0x0F0F0F0F...
2385    Op = DAG.getNode(ISD::AND, dl, VT,
2386                     DAG.getNode(ISD::ADD, dl, VT, Op,
2387                                 DAG.getNode(ISD::SRL, dl, VT, Op,
2388                                             DAG.getConstant(4, ShVT))),
2389                     Mask0F);
2390    // v = (v * 0x01010101...) >> (Len - 8)
2391    Op = DAG.getNode(ISD::SRL, dl, VT,
2392                     DAG.getNode(ISD::MUL, dl, VT, Op, Mask01),
2393                     DAG.getConstant(Len - 8, ShVT));
2394
2395    return Op;
2396  }
2397  case ISD::CTLZ_ZERO_UNDEF:
2398    // This trivially expands to CTLZ.
2399    return DAG.getNode(ISD::CTLZ, dl, Op.getValueType(), Op);
2400  case ISD::CTLZ: {
2401    // for now, we do this:
2402    // x = x | (x >> 1);
2403    // x = x | (x >> 2);
2404    // ...
2405    // x = x | (x >>16);
2406    // x = x | (x >>32); // for 64-bit input
2407    // return popcount(~x);
2408    //
2409    // but see also: http://www.hackersdelight.org/HDcode/nlz.cc
2410    EVT VT = Op.getValueType();
2411    EVT ShVT = TLI.getShiftAmountTy(VT);
2412    unsigned len = VT.getSizeInBits();
2413    for (unsigned i = 0; (1U << i) <= (len / 2); ++i) {
2414      SDValue Tmp3 = DAG.getConstant(1ULL << i, ShVT);
2415      Op = DAG.getNode(ISD::OR, dl, VT, Op,
2416                       DAG.getNode(ISD::SRL, dl, VT, Op, Tmp3));
2417    }
2418    Op = DAG.getNOT(dl, Op, VT);
2419    return DAG.getNode(ISD::CTPOP, dl, VT, Op);
2420  }
2421  case ISD::CTTZ_ZERO_UNDEF:
2422    // This trivially expands to CTTZ.
2423    return DAG.getNode(ISD::CTTZ, dl, Op.getValueType(), Op);
2424  case ISD::CTTZ: {
2425    // for now, we use: { return popcount(~x & (x - 1)); }
2426    // unless the target has ctlz but not ctpop, in which case we use:
2427    // { return 32 - nlz(~x & (x-1)); }
2428    // see also http://www.hackersdelight.org/HDcode/ntz.cc
2429    EVT VT = Op.getValueType();
2430    SDValue Tmp3 = DAG.getNode(ISD::AND, dl, VT,
2431                               DAG.getNOT(dl, Op, VT),
2432                               DAG.getNode(ISD::SUB, dl, VT, Op,
2433                                           DAG.getConstant(1, VT)));
2434    // If ISD::CTLZ is legal and CTPOP isn't, then do that instead.
2435    if (!TLI.isOperationLegalOrCustom(ISD::CTPOP, VT) &&
2436        TLI.isOperationLegalOrCustom(ISD::CTLZ, VT))
2437      return DAG.getNode(ISD::SUB, dl, VT,
2438                         DAG.getConstant(VT.getSizeInBits(), VT),
2439                         DAG.getNode(ISD::CTLZ, dl, VT, Tmp3));
2440    return DAG.getNode(ISD::CTPOP, dl, VT, Tmp3);
2441  }
2442  }
2443}
2444
2445std::pair <SDValue, SDValue> SelectionDAGLegalize::ExpandAtomic(SDNode *Node) {
2446  unsigned Opc = Node->getOpcode();
2447  MVT VT = cast<AtomicSDNode>(Node)->getMemoryVT().getSimpleVT();
2448  RTLIB::Libcall LC;
2449
2450  switch (Opc) {
2451  default:
2452    llvm_unreachable("Unhandled atomic intrinsic Expand!");
2453  case ISD::ATOMIC_SWAP:
2454    switch (VT.SimpleTy) {
2455    default: llvm_unreachable("Unexpected value type for atomic!");
2456    case MVT::i8:  LC = RTLIB::SYNC_LOCK_TEST_AND_SET_1; break;
2457    case MVT::i16: LC = RTLIB::SYNC_LOCK_TEST_AND_SET_2; break;
2458    case MVT::i32: LC = RTLIB::SYNC_LOCK_TEST_AND_SET_4; break;
2459    case MVT::i64: LC = RTLIB::SYNC_LOCK_TEST_AND_SET_8; break;
2460    }
2461    break;
2462  case ISD::ATOMIC_CMP_SWAP:
2463    switch (VT.SimpleTy) {
2464    default: llvm_unreachable("Unexpected value type for atomic!");
2465    case MVT::i8:  LC = RTLIB::SYNC_VAL_COMPARE_AND_SWAP_1; break;
2466    case MVT::i16: LC = RTLIB::SYNC_VAL_COMPARE_AND_SWAP_2; break;
2467    case MVT::i32: LC = RTLIB::SYNC_VAL_COMPARE_AND_SWAP_4; break;
2468    case MVT::i64: LC = RTLIB::SYNC_VAL_COMPARE_AND_SWAP_8; break;
2469    }
2470    break;
2471  case ISD::ATOMIC_LOAD_ADD:
2472    switch (VT.SimpleTy) {
2473    default: llvm_unreachable("Unexpected value type for atomic!");
2474    case MVT::i8:  LC = RTLIB::SYNC_FETCH_AND_ADD_1; break;
2475    case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_ADD_2; break;
2476    case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_ADD_4; break;
2477    case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_ADD_8; break;
2478    }
2479    break;
2480  case ISD::ATOMIC_LOAD_SUB:
2481    switch (VT.SimpleTy) {
2482    default: llvm_unreachable("Unexpected value type for atomic!");
2483    case MVT::i8:  LC = RTLIB::SYNC_FETCH_AND_SUB_1; break;
2484    case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_SUB_2; break;
2485    case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_SUB_4; break;
2486    case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_SUB_8; break;
2487    }
2488    break;
2489  case ISD::ATOMIC_LOAD_AND:
2490    switch (VT.SimpleTy) {
2491    default: llvm_unreachable("Unexpected value type for atomic!");
2492    case MVT::i8:  LC = RTLIB::SYNC_FETCH_AND_AND_1; break;
2493    case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_AND_2; break;
2494    case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_AND_4; break;
2495    case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_AND_8; break;
2496    }
2497    break;
2498  case ISD::ATOMIC_LOAD_OR:
2499    switch (VT.SimpleTy) {
2500    default: llvm_unreachable("Unexpected value type for atomic!");
2501    case MVT::i8:  LC = RTLIB::SYNC_FETCH_AND_OR_1; break;
2502    case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_OR_2; break;
2503    case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_OR_4; break;
2504    case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_OR_8; break;
2505    }
2506    break;
2507  case ISD::ATOMIC_LOAD_XOR:
2508    switch (VT.SimpleTy) {
2509    default: llvm_unreachable("Unexpected value type for atomic!");
2510    case MVT::i8:  LC = RTLIB::SYNC_FETCH_AND_XOR_1; break;
2511    case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_XOR_2; break;
2512    case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_XOR_4; break;
2513    case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_XOR_8; break;
2514    }
2515    break;
2516  case ISD::ATOMIC_LOAD_NAND:
2517    switch (VT.SimpleTy) {
2518    default: llvm_unreachable("Unexpected value type for atomic!");
2519    case MVT::i8:  LC = RTLIB::SYNC_FETCH_AND_NAND_1; break;
2520    case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_NAND_2; break;
2521    case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_NAND_4; break;
2522    case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_NAND_8; break;
2523    }
2524    break;
2525  }
2526
2527  return ExpandChainLibCall(LC, Node, false);
2528}
2529
2530void SelectionDAGLegalize::ExpandNode(SDNode *Node) {
2531  SmallVector<SDValue, 8> Results;
2532  DebugLoc dl = Node->getDebugLoc();
2533  SDValue Tmp1, Tmp2, Tmp3, Tmp4;
2534  switch (Node->getOpcode()) {
2535  case ISD::CTPOP:
2536  case ISD::CTLZ:
2537  case ISD::CTLZ_ZERO_UNDEF:
2538  case ISD::CTTZ:
2539  case ISD::CTTZ_ZERO_UNDEF:
2540    Tmp1 = ExpandBitCount(Node->getOpcode(), Node->getOperand(0), dl);
2541    Results.push_back(Tmp1);
2542    break;
2543  case ISD::BSWAP:
2544    Results.push_back(ExpandBSWAP(Node->getOperand(0), dl));
2545    break;
2546  case ISD::FRAMEADDR:
2547  case ISD::RETURNADDR:
2548  case ISD::FRAME_TO_ARGS_OFFSET:
2549    Results.push_back(DAG.getConstant(0, Node->getValueType(0)));
2550    break;
2551  case ISD::FLT_ROUNDS_:
2552    Results.push_back(DAG.getConstant(1, Node->getValueType(0)));
2553    break;
2554  case ISD::EH_RETURN:
2555  case ISD::EH_LABEL:
2556  case ISD::PREFETCH:
2557  case ISD::VAEND:
2558  case ISD::EH_SJLJ_LONGJMP:
2559    // If the target didn't expand these, there's nothing to do, so just
2560    // preserve the chain and be done.
2561    Results.push_back(Node->getOperand(0));
2562    break;
2563  case ISD::EH_SJLJ_SETJMP:
2564    // If the target didn't expand this, just return 'zero' and preserve the
2565    // chain.
2566    Results.push_back(DAG.getConstant(0, MVT::i32));
2567    Results.push_back(Node->getOperand(0));
2568    break;
2569  case ISD::ATOMIC_FENCE:
2570  case ISD::MEMBARRIER: {
2571    // If the target didn't lower this, lower it to '__sync_synchronize()' call
2572    // FIXME: handle "fence singlethread" more efficiently.
2573    TargetLowering::ArgListTy Args;
2574    std::pair<SDValue, SDValue> CallResult =
2575      TLI.LowerCallTo(Node->getOperand(0), Type::getVoidTy(*DAG.getContext()),
2576                      false, false, false, false, 0, CallingConv::C,
2577                      /*isTailCall=*/false,
2578                      /*doesNotReturn=*/false, /*isReturnValueUsed=*/true,
2579                      DAG.getExternalSymbol("__sync_synchronize",
2580                                            TLI.getPointerTy()),
2581                      Args, DAG, dl);
2582    Results.push_back(CallResult.second);
2583    break;
2584  }
2585  case ISD::ATOMIC_LOAD: {
2586    // There is no libcall for atomic load; fake it with ATOMIC_CMP_SWAP.
2587    SDValue Zero = DAG.getConstant(0, Node->getValueType(0));
2588    SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl,
2589                                 cast<AtomicSDNode>(Node)->getMemoryVT(),
2590                                 Node->getOperand(0),
2591                                 Node->getOperand(1), Zero, Zero,
2592                                 cast<AtomicSDNode>(Node)->getMemOperand(),
2593                                 cast<AtomicSDNode>(Node)->getOrdering(),
2594                                 cast<AtomicSDNode>(Node)->getSynchScope());
2595    Results.push_back(Swap.getValue(0));
2596    Results.push_back(Swap.getValue(1));
2597    break;
2598  }
2599  case ISD::ATOMIC_STORE: {
2600    // There is no libcall for atomic store; fake it with ATOMIC_SWAP.
2601    SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
2602                                 cast<AtomicSDNode>(Node)->getMemoryVT(),
2603                                 Node->getOperand(0),
2604                                 Node->getOperand(1), Node->getOperand(2),
2605                                 cast<AtomicSDNode>(Node)->getMemOperand(),
2606                                 cast<AtomicSDNode>(Node)->getOrdering(),
2607                                 cast<AtomicSDNode>(Node)->getSynchScope());
2608    Results.push_back(Swap.getValue(1));
2609    break;
2610  }
2611  // By default, atomic intrinsics are marked Legal and lowered. Targets
2612  // which don't support them directly, however, may want libcalls, in which
2613  // case they mark them Expand, and we get here.
2614  case ISD::ATOMIC_SWAP:
2615  case ISD::ATOMIC_LOAD_ADD:
2616  case ISD::ATOMIC_LOAD_SUB:
2617  case ISD::ATOMIC_LOAD_AND:
2618  case ISD::ATOMIC_LOAD_OR:
2619  case ISD::ATOMIC_LOAD_XOR:
2620  case ISD::ATOMIC_LOAD_NAND:
2621  case ISD::ATOMIC_LOAD_MIN:
2622  case ISD::ATOMIC_LOAD_MAX:
2623  case ISD::ATOMIC_LOAD_UMIN:
2624  case ISD::ATOMIC_LOAD_UMAX:
2625  case ISD::ATOMIC_CMP_SWAP: {
2626    std::pair<SDValue, SDValue> Tmp = ExpandAtomic(Node);
2627    Results.push_back(Tmp.first);
2628    Results.push_back(Tmp.second);
2629    break;
2630  }
2631  case ISD::DYNAMIC_STACKALLOC:
2632    ExpandDYNAMIC_STACKALLOC(Node, Results);
2633    break;
2634  case ISD::MERGE_VALUES:
2635    for (unsigned i = 0; i < Node->getNumValues(); i++)
2636      Results.push_back(Node->getOperand(i));
2637    break;
2638  case ISD::UNDEF: {
2639    EVT VT = Node->getValueType(0);
2640    if (VT.isInteger())
2641      Results.push_back(DAG.getConstant(0, VT));
2642    else {
2643      assert(VT.isFloatingPoint() && "Unknown value type!");
2644      Results.push_back(DAG.getConstantFP(0, VT));
2645    }
2646    break;
2647  }
2648  case ISD::TRAP: {
2649    // If this operation is not supported, lower it to 'abort()' call
2650    TargetLowering::ArgListTy Args;
2651    std::pair<SDValue, SDValue> CallResult =
2652      TLI.LowerCallTo(Node->getOperand(0), Type::getVoidTy(*DAG.getContext()),
2653                      false, false, false, false, 0, CallingConv::C,
2654                      /*isTailCall=*/false,
2655                      /*doesNotReturn=*/false, /*isReturnValueUsed=*/true,
2656                      DAG.getExternalSymbol("abort", TLI.getPointerTy()),
2657                      Args, DAG, dl);
2658    Results.push_back(CallResult.second);
2659    break;
2660  }
2661  case ISD::FP_ROUND:
2662  case ISD::BITCAST:
2663    Tmp1 = EmitStackConvert(Node->getOperand(0), Node->getValueType(0),
2664                            Node->getValueType(0), dl);
2665    Results.push_back(Tmp1);
2666    break;
2667  case ISD::FP_EXTEND:
2668    Tmp1 = EmitStackConvert(Node->getOperand(0),
2669                            Node->getOperand(0).getValueType(),
2670                            Node->getValueType(0), dl);
2671    Results.push_back(Tmp1);
2672    break;
2673  case ISD::SIGN_EXTEND_INREG: {
2674    // NOTE: we could fall back on load/store here too for targets without
2675    // SAR.  However, it is doubtful that any exist.
2676    EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
2677    EVT VT = Node->getValueType(0);
2678    EVT ShiftAmountTy = TLI.getShiftAmountTy(VT);
2679    if (VT.isVector())
2680      ShiftAmountTy = VT;
2681    unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
2682                        ExtraVT.getScalarType().getSizeInBits();
2683    SDValue ShiftCst = DAG.getConstant(BitsDiff, ShiftAmountTy);
2684    Tmp1 = DAG.getNode(ISD::SHL, dl, Node->getValueType(0),
2685                       Node->getOperand(0), ShiftCst);
2686    Tmp1 = DAG.getNode(ISD::SRA, dl, Node->getValueType(0), Tmp1, ShiftCst);
2687    Results.push_back(Tmp1);
2688    break;
2689  }
2690  case ISD::FP_ROUND_INREG: {
2691    // The only way we can lower this is to turn it into a TRUNCSTORE,
2692    // EXTLOAD pair, targeting a temporary location (a stack slot).
2693
2694    // NOTE: there is a choice here between constantly creating new stack
2695    // slots and always reusing the same one.  We currently always create
2696    // new ones, as reuse may inhibit scheduling.
2697    EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
2698    Tmp1 = EmitStackConvert(Node->getOperand(0), ExtraVT,
2699                            Node->getValueType(0), dl);
2700    Results.push_back(Tmp1);
2701    break;
2702  }
2703  case ISD::SINT_TO_FP:
2704  case ISD::UINT_TO_FP:
2705    Tmp1 = ExpandLegalINT_TO_FP(Node->getOpcode() == ISD::SINT_TO_FP,
2706                                Node->getOperand(0), Node->getValueType(0), dl);
2707    Results.push_back(Tmp1);
2708    break;
2709  case ISD::FP_TO_UINT: {
2710    SDValue True, False;
2711    EVT VT =  Node->getOperand(0).getValueType();
2712    EVT NVT = Node->getValueType(0);
2713    APFloat apf(APInt::getNullValue(VT.getSizeInBits()));
2714    APInt x = APInt::getSignBit(NVT.getSizeInBits());
2715    (void)apf.convertFromAPInt(x, false, APFloat::rmNearestTiesToEven);
2716    Tmp1 = DAG.getConstantFP(apf, VT);
2717    Tmp2 = DAG.getSetCC(dl, TLI.getSetCCResultType(VT),
2718                        Node->getOperand(0),
2719                        Tmp1, ISD::SETLT);
2720    True = DAG.getNode(ISD::FP_TO_SINT, dl, NVT, Node->getOperand(0));
2721    False = DAG.getNode(ISD::FP_TO_SINT, dl, NVT,
2722                        DAG.getNode(ISD::FSUB, dl, VT,
2723                                    Node->getOperand(0), Tmp1));
2724    False = DAG.getNode(ISD::XOR, dl, NVT, False,
2725                        DAG.getConstant(x, NVT));
2726    Tmp1 = DAG.getNode(ISD::SELECT, dl, NVT, Tmp2, True, False);
2727    Results.push_back(Tmp1);
2728    break;
2729  }
2730  case ISD::VAARG: {
2731    const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2732    EVT VT = Node->getValueType(0);
2733    Tmp1 = Node->getOperand(0);
2734    Tmp2 = Node->getOperand(1);
2735    unsigned Align = Node->getConstantOperandVal(3);
2736
2737    SDValue VAListLoad = DAG.getLoad(TLI.getPointerTy(), dl, Tmp1, Tmp2,
2738                                     MachinePointerInfo(V),
2739                                     false, false, false, 0);
2740    SDValue VAList = VAListLoad;
2741
2742    if (Align > TLI.getMinStackArgumentAlignment()) {
2743      assert(((Align & (Align-1)) == 0) && "Expected Align to be a power of 2");
2744
2745      VAList = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(), VAList,
2746                           DAG.getConstant(Align - 1,
2747                                           TLI.getPointerTy()));
2748
2749      VAList = DAG.getNode(ISD::AND, dl, TLI.getPointerTy(), VAList,
2750                           DAG.getConstant(-(int64_t)Align,
2751                                           TLI.getPointerTy()));
2752    }
2753
2754    // Increment the pointer, VAList, to the next vaarg
2755    Tmp3 = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(), VAList,
2756                       DAG.getConstant(TLI.getTargetData()->
2757                          getTypeAllocSize(VT.getTypeForEVT(*DAG.getContext())),
2758                                       TLI.getPointerTy()));
2759    // Store the incremented VAList to the legalized pointer
2760    Tmp3 = DAG.getStore(VAListLoad.getValue(1), dl, Tmp3, Tmp2,
2761                        MachinePointerInfo(V), false, false, 0);
2762    // Load the actual argument out of the pointer VAList
2763    Results.push_back(DAG.getLoad(VT, dl, Tmp3, VAList, MachinePointerInfo(),
2764                                  false, false, false, 0));
2765    Results.push_back(Results[0].getValue(1));
2766    break;
2767  }
2768  case ISD::VACOPY: {
2769    // This defaults to loading a pointer from the input and storing it to the
2770    // output, returning the chain.
2771    const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
2772    const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
2773    Tmp1 = DAG.getLoad(TLI.getPointerTy(), dl, Node->getOperand(0),
2774                       Node->getOperand(2), MachinePointerInfo(VS),
2775                       false, false, false, 0);
2776    Tmp1 = DAG.getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
2777                        MachinePointerInfo(VD), false, false, 0);
2778    Results.push_back(Tmp1);
2779    break;
2780  }
2781  case ISD::EXTRACT_VECTOR_ELT:
2782    if (Node->getOperand(0).getValueType().getVectorNumElements() == 1)
2783      // This must be an access of the only element.  Return it.
2784      Tmp1 = DAG.getNode(ISD::BITCAST, dl, Node->getValueType(0),
2785                         Node->getOperand(0));
2786    else
2787      Tmp1 = ExpandExtractFromVectorThroughStack(SDValue(Node, 0));
2788    Results.push_back(Tmp1);
2789    break;
2790  case ISD::EXTRACT_SUBVECTOR:
2791    Results.push_back(ExpandExtractFromVectorThroughStack(SDValue(Node, 0)));
2792    break;
2793  case ISD::INSERT_SUBVECTOR:
2794    Results.push_back(ExpandInsertToVectorThroughStack(SDValue(Node, 0)));
2795    break;
2796  case ISD::CONCAT_VECTORS: {
2797    Results.push_back(ExpandVectorBuildThroughStack(Node));
2798    break;
2799  }
2800  case ISD::SCALAR_TO_VECTOR:
2801    Results.push_back(ExpandSCALAR_TO_VECTOR(Node));
2802    break;
2803  case ISD::INSERT_VECTOR_ELT:
2804    Results.push_back(ExpandINSERT_VECTOR_ELT(Node->getOperand(0),
2805                                              Node->getOperand(1),
2806                                              Node->getOperand(2), dl));
2807    break;
2808  case ISD::VECTOR_SHUFFLE: {
2809    SmallVector<int, 32> NewMask;
2810    ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Node)->getMask();
2811
2812    EVT VT = Node->getValueType(0);
2813    EVT EltVT = VT.getVectorElementType();
2814    SDValue Op0 = Node->getOperand(0);
2815    SDValue Op1 = Node->getOperand(1);
2816    if (!TLI.isTypeLegal(EltVT)) {
2817
2818      EVT NewEltVT = TLI.getTypeToTransformTo(*DAG.getContext(), EltVT);
2819
2820      // BUILD_VECTOR operands are allowed to be wider than the element type.
2821      // But if NewEltVT is smaller that EltVT the BUILD_VECTOR does not accept it
2822      if (NewEltVT.bitsLT(EltVT)) {
2823
2824        // Convert shuffle node.
2825        // If original node was v4i64 and the new EltVT is i32,
2826        // cast operands to v8i32 and re-build the mask.
2827
2828        // Calculate new VT, the size of the new VT should be equal to original.
2829        EVT NewVT = EVT::getVectorVT(*DAG.getContext(), NewEltVT,
2830                                      VT.getSizeInBits()/NewEltVT.getSizeInBits());
2831        assert(NewVT.bitsEq(VT));
2832
2833        // cast operands to new VT
2834        Op0 = DAG.getNode(ISD::BITCAST, dl, NewVT, Op0);
2835        Op1 = DAG.getNode(ISD::BITCAST, dl, NewVT, Op1);
2836
2837        // Convert the shuffle mask
2838        unsigned int factor = NewVT.getVectorNumElements()/VT.getVectorNumElements();
2839
2840        // EltVT gets smaller
2841        assert(factor > 0);
2842
2843        for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
2844          if (Mask[i] < 0) {
2845            for (unsigned fi = 0; fi < factor; ++fi)
2846              NewMask.push_back(Mask[i]);
2847          }
2848          else {
2849            for (unsigned fi = 0; fi < factor; ++fi)
2850              NewMask.push_back(Mask[i]*factor+fi);
2851          }
2852        }
2853        Mask = NewMask;
2854        VT = NewVT;
2855      }
2856      EltVT = NewEltVT;
2857    }
2858    unsigned NumElems = VT.getVectorNumElements();
2859    SmallVector<SDValue, 16> Ops;
2860    for (unsigned i = 0; i != NumElems; ++i) {
2861      if (Mask[i] < 0) {
2862        Ops.push_back(DAG.getUNDEF(EltVT));
2863        continue;
2864      }
2865      unsigned Idx = Mask[i];
2866      if (Idx < NumElems)
2867        Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
2868                                  Op0,
2869                                  DAG.getIntPtrConstant(Idx)));
2870      else
2871        Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
2872                                  Op1,
2873                                  DAG.getIntPtrConstant(Idx - NumElems)));
2874    }
2875
2876    Tmp1 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Ops[0], Ops.size());
2877    // We may have changed the BUILD_VECTOR type. Cast it back to the Node type.
2878    Tmp1 = DAG.getNode(ISD::BITCAST, dl, Node->getValueType(0), Tmp1);
2879    Results.push_back(Tmp1);
2880    break;
2881  }
2882  case ISD::EXTRACT_ELEMENT: {
2883    EVT OpTy = Node->getOperand(0).getValueType();
2884    if (cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue()) {
2885      // 1 -> Hi
2886      Tmp1 = DAG.getNode(ISD::SRL, dl, OpTy, Node->getOperand(0),
2887                         DAG.getConstant(OpTy.getSizeInBits()/2,
2888                    TLI.getShiftAmountTy(Node->getOperand(0).getValueType())));
2889      Tmp1 = DAG.getNode(ISD::TRUNCATE, dl, Node->getValueType(0), Tmp1);
2890    } else {
2891      // 0 -> Lo
2892      Tmp1 = DAG.getNode(ISD::TRUNCATE, dl, Node->getValueType(0),
2893                         Node->getOperand(0));
2894    }
2895    Results.push_back(Tmp1);
2896    break;
2897  }
2898  case ISD::STACKSAVE:
2899    // Expand to CopyFromReg if the target set
2900    // StackPointerRegisterToSaveRestore.
2901    if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) {
2902      Results.push_back(DAG.getCopyFromReg(Node->getOperand(0), dl, SP,
2903                                           Node->getValueType(0)));
2904      Results.push_back(Results[0].getValue(1));
2905    } else {
2906      Results.push_back(DAG.getUNDEF(Node->getValueType(0)));
2907      Results.push_back(Node->getOperand(0));
2908    }
2909    break;
2910  case ISD::STACKRESTORE:
2911    // Expand to CopyToReg if the target set
2912    // StackPointerRegisterToSaveRestore.
2913    if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) {
2914      Results.push_back(DAG.getCopyToReg(Node->getOperand(0), dl, SP,
2915                                         Node->getOperand(1)));
2916    } else {
2917      Results.push_back(Node->getOperand(0));
2918    }
2919    break;
2920  case ISD::FCOPYSIGN:
2921    Results.push_back(ExpandFCOPYSIGN(Node));
2922    break;
2923  case ISD::FNEG:
2924    // Expand Y = FNEG(X) ->  Y = SUB -0.0, X
2925    Tmp1 = DAG.getConstantFP(-0.0, Node->getValueType(0));
2926    Tmp1 = DAG.getNode(ISD::FSUB, dl, Node->getValueType(0), Tmp1,
2927                       Node->getOperand(0));
2928    Results.push_back(Tmp1);
2929    break;
2930  case ISD::FABS: {
2931    // Expand Y = FABS(X) -> Y = (X >u 0.0) ? X : fneg(X).
2932    EVT VT = Node->getValueType(0);
2933    Tmp1 = Node->getOperand(0);
2934    Tmp2 = DAG.getConstantFP(0.0, VT);
2935    Tmp2 = DAG.getSetCC(dl, TLI.getSetCCResultType(Tmp1.getValueType()),
2936                        Tmp1, Tmp2, ISD::SETUGT);
2937    Tmp3 = DAG.getNode(ISD::FNEG, dl, VT, Tmp1);
2938    Tmp1 = DAG.getNode(ISD::SELECT, dl, VT, Tmp2, Tmp1, Tmp3);
2939    Results.push_back(Tmp1);
2940    break;
2941  }
2942  case ISD::FSQRT:
2943    Results.push_back(ExpandFPLibCall(Node, RTLIB::SQRT_F32, RTLIB::SQRT_F64,
2944                                      RTLIB::SQRT_F80, RTLIB::SQRT_PPCF128));
2945    break;
2946  case ISD::FSIN:
2947    Results.push_back(ExpandFPLibCall(Node, RTLIB::SIN_F32, RTLIB::SIN_F64,
2948                                      RTLIB::SIN_F80, RTLIB::SIN_PPCF128));
2949    break;
2950  case ISD::FCOS:
2951    Results.push_back(ExpandFPLibCall(Node, RTLIB::COS_F32, RTLIB::COS_F64,
2952                                      RTLIB::COS_F80, RTLIB::COS_PPCF128));
2953    break;
2954  case ISD::FLOG:
2955    Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG_F32, RTLIB::LOG_F64,
2956                                      RTLIB::LOG_F80, RTLIB::LOG_PPCF128));
2957    break;
2958  case ISD::FLOG2:
2959    Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG2_F32, RTLIB::LOG2_F64,
2960                                      RTLIB::LOG2_F80, RTLIB::LOG2_PPCF128));
2961    break;
2962  case ISD::FLOG10:
2963    Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG10_F32, RTLIB::LOG10_F64,
2964                                      RTLIB::LOG10_F80, RTLIB::LOG10_PPCF128));
2965    break;
2966  case ISD::FEXP:
2967    Results.push_back(ExpandFPLibCall(Node, RTLIB::EXP_F32, RTLIB::EXP_F64,
2968                                      RTLIB::EXP_F80, RTLIB::EXP_PPCF128));
2969    break;
2970  case ISD::FEXP2:
2971    Results.push_back(ExpandFPLibCall(Node, RTLIB::EXP2_F32, RTLIB::EXP2_F64,
2972                                      RTLIB::EXP2_F80, RTLIB::EXP2_PPCF128));
2973    break;
2974  case ISD::FTRUNC:
2975    Results.push_back(ExpandFPLibCall(Node, RTLIB::TRUNC_F32, RTLIB::TRUNC_F64,
2976                                      RTLIB::TRUNC_F80, RTLIB::TRUNC_PPCF128));
2977    break;
2978  case ISD::FFLOOR:
2979    Results.push_back(ExpandFPLibCall(Node, RTLIB::FLOOR_F32, RTLIB::FLOOR_F64,
2980                                      RTLIB::FLOOR_F80, RTLIB::FLOOR_PPCF128));
2981    break;
2982  case ISD::FCEIL:
2983    Results.push_back(ExpandFPLibCall(Node, RTLIB::CEIL_F32, RTLIB::CEIL_F64,
2984                                      RTLIB::CEIL_F80, RTLIB::CEIL_PPCF128));
2985    break;
2986  case ISD::FRINT:
2987    Results.push_back(ExpandFPLibCall(Node, RTLIB::RINT_F32, RTLIB::RINT_F64,
2988                                      RTLIB::RINT_F80, RTLIB::RINT_PPCF128));
2989    break;
2990  case ISD::FNEARBYINT:
2991    Results.push_back(ExpandFPLibCall(Node, RTLIB::NEARBYINT_F32,
2992                                      RTLIB::NEARBYINT_F64,
2993                                      RTLIB::NEARBYINT_F80,
2994                                      RTLIB::NEARBYINT_PPCF128));
2995    break;
2996  case ISD::FPOWI:
2997    Results.push_back(ExpandFPLibCall(Node, RTLIB::POWI_F32, RTLIB::POWI_F64,
2998                                      RTLIB::POWI_F80, RTLIB::POWI_PPCF128));
2999    break;
3000  case ISD::FPOW:
3001    Results.push_back(ExpandFPLibCall(Node, RTLIB::POW_F32, RTLIB::POW_F64,
3002                                      RTLIB::POW_F80, RTLIB::POW_PPCF128));
3003    break;
3004  case ISD::FDIV:
3005    Results.push_back(ExpandFPLibCall(Node, RTLIB::DIV_F32, RTLIB::DIV_F64,
3006                                      RTLIB::DIV_F80, RTLIB::DIV_PPCF128));
3007    break;
3008  case ISD::FREM:
3009    Results.push_back(ExpandFPLibCall(Node, RTLIB::REM_F32, RTLIB::REM_F64,
3010                                      RTLIB::REM_F80, RTLIB::REM_PPCF128));
3011    break;
3012  case ISD::FMA:
3013    Results.push_back(ExpandFPLibCall(Node, RTLIB::FMA_F32, RTLIB::FMA_F64,
3014                                      RTLIB::FMA_F80, RTLIB::FMA_PPCF128));
3015    break;
3016  case ISD::FP16_TO_FP32:
3017    Results.push_back(ExpandLibCall(RTLIB::FPEXT_F16_F32, Node, false));
3018    break;
3019  case ISD::FP32_TO_FP16:
3020    Results.push_back(ExpandLibCall(RTLIB::FPROUND_F32_F16, Node, false));
3021    break;
3022  case ISD::ConstantFP: {
3023    ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Node);
3024    // Check to see if this FP immediate is already legal.
3025    // If this is a legal constant, turn it into a TargetConstantFP node.
3026    if (!TLI.isFPImmLegal(CFP->getValueAPF(), Node->getValueType(0)))
3027      Results.push_back(ExpandConstantFP(CFP, true));
3028    break;
3029  }
3030  case ISD::EHSELECTION: {
3031    unsigned Reg = TLI.getExceptionSelectorRegister();
3032    assert(Reg && "Can't expand to unknown register!");
3033    Results.push_back(DAG.getCopyFromReg(Node->getOperand(1), dl, Reg,
3034                                         Node->getValueType(0)));
3035    Results.push_back(Results[0].getValue(1));
3036    break;
3037  }
3038  case ISD::EXCEPTIONADDR: {
3039    unsigned Reg = TLI.getExceptionPointerRegister();
3040    assert(Reg && "Can't expand to unknown register!");
3041    Results.push_back(DAG.getCopyFromReg(Node->getOperand(0), dl, Reg,
3042                                         Node->getValueType(0)));
3043    Results.push_back(Results[0].getValue(1));
3044    break;
3045  }
3046  case ISD::FSUB: {
3047    EVT VT = Node->getValueType(0);
3048    assert(TLI.isOperationLegalOrCustom(ISD::FADD, VT) &&
3049           TLI.isOperationLegalOrCustom(ISD::FNEG, VT) &&
3050           "Don't know how to expand this FP subtraction!");
3051    Tmp1 = DAG.getNode(ISD::FNEG, dl, VT, Node->getOperand(1));
3052    Tmp1 = DAG.getNode(ISD::FADD, dl, VT, Node->getOperand(0), Tmp1);
3053    Results.push_back(Tmp1);
3054    break;
3055  }
3056  case ISD::SUB: {
3057    EVT VT = Node->getValueType(0);
3058    assert(TLI.isOperationLegalOrCustom(ISD::ADD, VT) &&
3059           TLI.isOperationLegalOrCustom(ISD::XOR, VT) &&
3060           "Don't know how to expand this subtraction!");
3061    Tmp1 = DAG.getNode(ISD::XOR, dl, VT, Node->getOperand(1),
3062               DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT));
3063    Tmp1 = DAG.getNode(ISD::ADD, dl, VT, Tmp2, DAG.getConstant(1, VT));
3064    Results.push_back(DAG.getNode(ISD::ADD, dl, VT, Node->getOperand(0), Tmp1));
3065    break;
3066  }
3067  case ISD::UREM:
3068  case ISD::SREM: {
3069    EVT VT = Node->getValueType(0);
3070    SDVTList VTs = DAG.getVTList(VT, VT);
3071    bool isSigned = Node->getOpcode() == ISD::SREM;
3072    unsigned DivOpc = isSigned ? ISD::SDIV : ISD::UDIV;
3073    unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
3074    Tmp2 = Node->getOperand(0);
3075    Tmp3 = Node->getOperand(1);
3076    if (TLI.isOperationLegalOrCustom(DivRemOpc, VT) ||
3077        (isDivRemLibcallAvailable(Node, isSigned, TLI) &&
3078         UseDivRem(Node, isSigned, false))) {
3079      Tmp1 = DAG.getNode(DivRemOpc, dl, VTs, Tmp2, Tmp3).getValue(1);
3080    } else if (TLI.isOperationLegalOrCustom(DivOpc, VT)) {
3081      // X % Y -> X-X/Y*Y
3082      Tmp1 = DAG.getNode(DivOpc, dl, VT, Tmp2, Tmp3);
3083      Tmp1 = DAG.getNode(ISD::MUL, dl, VT, Tmp1, Tmp3);
3084      Tmp1 = DAG.getNode(ISD::SUB, dl, VT, Tmp2, Tmp1);
3085    } else if (isSigned)
3086      Tmp1 = ExpandIntLibCall(Node, true,
3087                              RTLIB::SREM_I8,
3088                              RTLIB::SREM_I16, RTLIB::SREM_I32,
3089                              RTLIB::SREM_I64, RTLIB::SREM_I128);
3090    else
3091      Tmp1 = ExpandIntLibCall(Node, false,
3092                              RTLIB::UREM_I8,
3093                              RTLIB::UREM_I16, RTLIB::UREM_I32,
3094                              RTLIB::UREM_I64, RTLIB::UREM_I128);
3095    Results.push_back(Tmp1);
3096    break;
3097  }
3098  case ISD::UDIV:
3099  case ISD::SDIV: {
3100    bool isSigned = Node->getOpcode() == ISD::SDIV;
3101    unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
3102    EVT VT = Node->getValueType(0);
3103    SDVTList VTs = DAG.getVTList(VT, VT);
3104    if (TLI.isOperationLegalOrCustom(DivRemOpc, VT) ||
3105        (isDivRemLibcallAvailable(Node, isSigned, TLI) &&
3106         UseDivRem(Node, isSigned, true)))
3107      Tmp1 = DAG.getNode(DivRemOpc, dl, VTs, Node->getOperand(0),
3108                         Node->getOperand(1));
3109    else if (isSigned)
3110      Tmp1 = ExpandIntLibCall(Node, true,
3111                              RTLIB::SDIV_I8,
3112                              RTLIB::SDIV_I16, RTLIB::SDIV_I32,
3113                              RTLIB::SDIV_I64, RTLIB::SDIV_I128);
3114    else
3115      Tmp1 = ExpandIntLibCall(Node, false,
3116                              RTLIB::UDIV_I8,
3117                              RTLIB::UDIV_I16, RTLIB::UDIV_I32,
3118                              RTLIB::UDIV_I64, RTLIB::UDIV_I128);
3119    Results.push_back(Tmp1);
3120    break;
3121  }
3122  case ISD::MULHU:
3123  case ISD::MULHS: {
3124    unsigned ExpandOpcode = Node->getOpcode() == ISD::MULHU ? ISD::UMUL_LOHI :
3125                                                              ISD::SMUL_LOHI;
3126    EVT VT = Node->getValueType(0);
3127    SDVTList VTs = DAG.getVTList(VT, VT);
3128    assert(TLI.isOperationLegalOrCustom(ExpandOpcode, VT) &&
3129           "If this wasn't legal, it shouldn't have been created!");
3130    Tmp1 = DAG.getNode(ExpandOpcode, dl, VTs, Node->getOperand(0),
3131                       Node->getOperand(1));
3132    Results.push_back(Tmp1.getValue(1));
3133    break;
3134  }
3135  case ISD::SDIVREM:
3136  case ISD::UDIVREM:
3137    // Expand into divrem libcall
3138    ExpandDivRemLibCall(Node, Results);
3139    break;
3140  case ISD::MUL: {
3141    EVT VT = Node->getValueType(0);
3142    SDVTList VTs = DAG.getVTList(VT, VT);
3143    // See if multiply or divide can be lowered using two-result operations.
3144    // We just need the low half of the multiply; try both the signed
3145    // and unsigned forms. If the target supports both SMUL_LOHI and
3146    // UMUL_LOHI, form a preference by checking which forms of plain
3147    // MULH it supports.
3148    bool HasSMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::SMUL_LOHI, VT);
3149    bool HasUMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::UMUL_LOHI, VT);
3150    bool HasMULHS = TLI.isOperationLegalOrCustom(ISD::MULHS, VT);
3151    bool HasMULHU = TLI.isOperationLegalOrCustom(ISD::MULHU, VT);
3152    unsigned OpToUse = 0;
3153    if (HasSMUL_LOHI && !HasMULHS) {
3154      OpToUse = ISD::SMUL_LOHI;
3155    } else if (HasUMUL_LOHI && !HasMULHU) {
3156      OpToUse = ISD::UMUL_LOHI;
3157    } else if (HasSMUL_LOHI) {
3158      OpToUse = ISD::SMUL_LOHI;
3159    } else if (HasUMUL_LOHI) {
3160      OpToUse = ISD::UMUL_LOHI;
3161    }
3162    if (OpToUse) {
3163      Results.push_back(DAG.getNode(OpToUse, dl, VTs, Node->getOperand(0),
3164                                    Node->getOperand(1)));
3165      break;
3166    }
3167    Tmp1 = ExpandIntLibCall(Node, false,
3168                            RTLIB::MUL_I8,
3169                            RTLIB::MUL_I16, RTLIB::MUL_I32,
3170                            RTLIB::MUL_I64, RTLIB::MUL_I128);
3171    Results.push_back(Tmp1);
3172    break;
3173  }
3174  case ISD::SADDO:
3175  case ISD::SSUBO: {
3176    SDValue LHS = Node->getOperand(0);
3177    SDValue RHS = Node->getOperand(1);
3178    SDValue Sum = DAG.getNode(Node->getOpcode() == ISD::SADDO ?
3179                              ISD::ADD : ISD::SUB, dl, LHS.getValueType(),
3180                              LHS, RHS);
3181    Results.push_back(Sum);
3182    EVT OType = Node->getValueType(1);
3183
3184    SDValue Zero = DAG.getConstant(0, LHS.getValueType());
3185
3186    //   LHSSign -> LHS >= 0
3187    //   RHSSign -> RHS >= 0
3188    //   SumSign -> Sum >= 0
3189    //
3190    //   Add:
3191    //   Overflow -> (LHSSign == RHSSign) && (LHSSign != SumSign)
3192    //   Sub:
3193    //   Overflow -> (LHSSign != RHSSign) && (LHSSign != SumSign)
3194    //
3195    SDValue LHSSign = DAG.getSetCC(dl, OType, LHS, Zero, ISD::SETGE);
3196    SDValue RHSSign = DAG.getSetCC(dl, OType, RHS, Zero, ISD::SETGE);
3197    SDValue SignsMatch = DAG.getSetCC(dl, OType, LHSSign, RHSSign,
3198                                      Node->getOpcode() == ISD::SADDO ?
3199                                      ISD::SETEQ : ISD::SETNE);
3200
3201    SDValue SumSign = DAG.getSetCC(dl, OType, Sum, Zero, ISD::SETGE);
3202    SDValue SumSignNE = DAG.getSetCC(dl, OType, LHSSign, SumSign, ISD::SETNE);
3203
3204    SDValue Cmp = DAG.getNode(ISD::AND, dl, OType, SignsMatch, SumSignNE);
3205    Results.push_back(Cmp);
3206    break;
3207  }
3208  case ISD::UADDO:
3209  case ISD::USUBO: {
3210    SDValue LHS = Node->getOperand(0);
3211    SDValue RHS = Node->getOperand(1);
3212    SDValue Sum = DAG.getNode(Node->getOpcode() == ISD::UADDO ?
3213                              ISD::ADD : ISD::SUB, dl, LHS.getValueType(),
3214                              LHS, RHS);
3215    Results.push_back(Sum);
3216    Results.push_back(DAG.getSetCC(dl, Node->getValueType(1), Sum, LHS,
3217                                   Node->getOpcode () == ISD::UADDO ?
3218                                   ISD::SETULT : ISD::SETUGT));
3219    break;
3220  }
3221  case ISD::UMULO:
3222  case ISD::SMULO: {
3223    EVT VT = Node->getValueType(0);
3224    EVT WideVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits() * 2);
3225    SDValue LHS = Node->getOperand(0);
3226    SDValue RHS = Node->getOperand(1);
3227    SDValue BottomHalf;
3228    SDValue TopHalf;
3229    static const unsigned Ops[2][3] =
3230        { { ISD::MULHU, ISD::UMUL_LOHI, ISD::ZERO_EXTEND },
3231          { ISD::MULHS, ISD::SMUL_LOHI, ISD::SIGN_EXTEND }};
3232    bool isSigned = Node->getOpcode() == ISD::SMULO;
3233    if (TLI.isOperationLegalOrCustom(Ops[isSigned][0], VT)) {
3234      BottomHalf = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
3235      TopHalf = DAG.getNode(Ops[isSigned][0], dl, VT, LHS, RHS);
3236    } else if (TLI.isOperationLegalOrCustom(Ops[isSigned][1], VT)) {
3237      BottomHalf = DAG.getNode(Ops[isSigned][1], dl, DAG.getVTList(VT, VT), LHS,
3238                               RHS);
3239      TopHalf = BottomHalf.getValue(1);
3240    } else if (TLI.isTypeLegal(EVT::getIntegerVT(*DAG.getContext(),
3241                                                 VT.getSizeInBits() * 2))) {
3242      LHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, LHS);
3243      RHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, RHS);
3244      Tmp1 = DAG.getNode(ISD::MUL, dl, WideVT, LHS, RHS);
3245      BottomHalf = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VT, Tmp1,
3246                               DAG.getIntPtrConstant(0));
3247      TopHalf = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VT, Tmp1,
3248                            DAG.getIntPtrConstant(1));
3249    } else {
3250      // We can fall back to a libcall with an illegal type for the MUL if we
3251      // have a libcall big enough.
3252      // Also, we can fall back to a division in some cases, but that's a big
3253      // performance hit in the general case.
3254      RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
3255      if (WideVT == MVT::i16)
3256        LC = RTLIB::MUL_I16;
3257      else if (WideVT == MVT::i32)
3258        LC = RTLIB::MUL_I32;
3259      else if (WideVT == MVT::i64)
3260        LC = RTLIB::MUL_I64;
3261      else if (WideVT == MVT::i128)
3262        LC = RTLIB::MUL_I128;
3263      assert(LC != RTLIB::UNKNOWN_LIBCALL && "Cannot expand this operation!");
3264
3265      // The high part is obtained by SRA'ing all but one of the bits of low
3266      // part.
3267      unsigned LoSize = VT.getSizeInBits();
3268      SDValue HiLHS = DAG.getNode(ISD::SRA, dl, VT, RHS,
3269                                DAG.getConstant(LoSize-1, TLI.getPointerTy()));
3270      SDValue HiRHS = DAG.getNode(ISD::SRA, dl, VT, LHS,
3271                                DAG.getConstant(LoSize-1, TLI.getPointerTy()));
3272
3273      // Here we're passing the 2 arguments explicitly as 4 arguments that are
3274      // pre-lowered to the correct types. This all depends upon WideVT not
3275      // being a legal type for the architecture and thus has to be split to
3276      // two arguments.
3277      SDValue Args[] = { LHS, HiLHS, RHS, HiRHS };
3278      SDValue Ret = ExpandLibCall(LC, WideVT, Args, 4, isSigned, dl);
3279      BottomHalf = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VT, Ret,
3280                               DAG.getIntPtrConstant(0));
3281      TopHalf = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VT, Ret,
3282                            DAG.getIntPtrConstant(1));
3283      // Ret is a node with an illegal type. Because such things are not
3284      // generally permitted during this phase of legalization, delete the
3285      // node. The above EXTRACT_ELEMENT nodes should have been folded.
3286      DAG.DeleteNode(Ret.getNode());
3287    }
3288
3289    if (isSigned) {
3290      Tmp1 = DAG.getConstant(VT.getSizeInBits() - 1,
3291                             TLI.getShiftAmountTy(BottomHalf.getValueType()));
3292      Tmp1 = DAG.getNode(ISD::SRA, dl, VT, BottomHalf, Tmp1);
3293      TopHalf = DAG.getSetCC(dl, TLI.getSetCCResultType(VT), TopHalf, Tmp1,
3294                             ISD::SETNE);
3295    } else {
3296      TopHalf = DAG.getSetCC(dl, TLI.getSetCCResultType(VT), TopHalf,
3297                             DAG.getConstant(0, VT), ISD::SETNE);
3298    }
3299    Results.push_back(BottomHalf);
3300    Results.push_back(TopHalf);
3301    break;
3302  }
3303  case ISD::BUILD_PAIR: {
3304    EVT PairTy = Node->getValueType(0);
3305    Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, PairTy, Node->getOperand(0));
3306    Tmp2 = DAG.getNode(ISD::ANY_EXTEND, dl, PairTy, Node->getOperand(1));
3307    Tmp2 = DAG.getNode(ISD::SHL, dl, PairTy, Tmp2,
3308                       DAG.getConstant(PairTy.getSizeInBits()/2,
3309                                       TLI.getShiftAmountTy(PairTy)));
3310    Results.push_back(DAG.getNode(ISD::OR, dl, PairTy, Tmp1, Tmp2));
3311    break;
3312  }
3313  case ISD::SELECT:
3314    Tmp1 = Node->getOperand(0);
3315    Tmp2 = Node->getOperand(1);
3316    Tmp3 = Node->getOperand(2);
3317    if (Tmp1.getOpcode() == ISD::SETCC) {
3318      Tmp1 = DAG.getSelectCC(dl, Tmp1.getOperand(0), Tmp1.getOperand(1),
3319                             Tmp2, Tmp3,
3320                             cast<CondCodeSDNode>(Tmp1.getOperand(2))->get());
3321    } else {
3322      Tmp1 = DAG.getSelectCC(dl, Tmp1,
3323                             DAG.getConstant(0, Tmp1.getValueType()),
3324                             Tmp2, Tmp3, ISD::SETNE);
3325    }
3326    Results.push_back(Tmp1);
3327    break;
3328  case ISD::BR_JT: {
3329    SDValue Chain = Node->getOperand(0);
3330    SDValue Table = Node->getOperand(1);
3331    SDValue Index = Node->getOperand(2);
3332
3333    EVT PTy = TLI.getPointerTy();
3334
3335    const TargetData &TD = *TLI.getTargetData();
3336    unsigned EntrySize =
3337      DAG.getMachineFunction().getJumpTableInfo()->getEntrySize(TD);
3338
3339    Index = DAG.getNode(ISD::MUL, dl, PTy,
3340                        Index, DAG.getConstant(EntrySize, PTy));
3341    SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3342
3343    EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), EntrySize * 8);
3344    SDValue LD = DAG.getExtLoad(ISD::SEXTLOAD, dl, PTy, Chain, Addr,
3345                                MachinePointerInfo::getJumpTable(), MemVT,
3346                                false, false, 0);
3347    Addr = LD;
3348    if (TM.getRelocationModel() == Reloc::PIC_) {
3349      // For PIC, the sequence is:
3350      // BRIND(load(Jumptable + index) + RelocBase)
3351      // RelocBase can be JumpTable, GOT or some sort of global base.
3352      Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr,
3353                          TLI.getPICJumpTableRelocBase(Table, DAG));
3354    }
3355    Tmp1 = DAG.getNode(ISD::BRIND, dl, MVT::Other, LD.getValue(1), Addr);
3356    Results.push_back(Tmp1);
3357    break;
3358  }
3359  case ISD::BRCOND:
3360    // Expand brcond's setcc into its constituent parts and create a BR_CC
3361    // Node.
3362    Tmp1 = Node->getOperand(0);
3363    Tmp2 = Node->getOperand(1);
3364    if (Tmp2.getOpcode() == ISD::SETCC) {
3365      Tmp1 = DAG.getNode(ISD::BR_CC, dl, MVT::Other,
3366                         Tmp1, Tmp2.getOperand(2),
3367                         Tmp2.getOperand(0), Tmp2.getOperand(1),
3368                         Node->getOperand(2));
3369    } else {
3370      // We test only the i1 bit.  Skip the AND if UNDEF.
3371      Tmp3 = (Tmp2.getOpcode() == ISD::UNDEF) ? Tmp2 :
3372        DAG.getNode(ISD::AND, dl, Tmp2.getValueType(), Tmp2,
3373                    DAG.getConstant(1, Tmp2.getValueType()));
3374      Tmp1 = DAG.getNode(ISD::BR_CC, dl, MVT::Other, Tmp1,
3375                         DAG.getCondCode(ISD::SETNE), Tmp3,
3376                         DAG.getConstant(0, Tmp3.getValueType()),
3377                         Node->getOperand(2));
3378    }
3379    Results.push_back(Tmp1);
3380    break;
3381  case ISD::SETCC: {
3382    Tmp1 = Node->getOperand(0);
3383    Tmp2 = Node->getOperand(1);
3384    Tmp3 = Node->getOperand(2);
3385    LegalizeSetCCCondCode(Node->getValueType(0), Tmp1, Tmp2, Tmp3, dl);
3386
3387    // If we expanded the SETCC into an AND/OR, return the new node
3388    if (Tmp2.getNode() == 0) {
3389      Results.push_back(Tmp1);
3390      break;
3391    }
3392
3393    // Otherwise, SETCC for the given comparison type must be completely
3394    // illegal; expand it into a SELECT_CC.
3395    EVT VT = Node->getValueType(0);
3396    Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, VT, Tmp1, Tmp2,
3397                       DAG.getConstant(1, VT), DAG.getConstant(0, VT), Tmp3);
3398    Results.push_back(Tmp1);
3399    break;
3400  }
3401  case ISD::SELECT_CC: {
3402    Tmp1 = Node->getOperand(0);   // LHS
3403    Tmp2 = Node->getOperand(1);   // RHS
3404    Tmp3 = Node->getOperand(2);   // True
3405    Tmp4 = Node->getOperand(3);   // False
3406    SDValue CC = Node->getOperand(4);
3407
3408    LegalizeSetCCCondCode(TLI.getSetCCResultType(Tmp1.getValueType()),
3409                          Tmp1, Tmp2, CC, dl);
3410
3411    assert(!Tmp2.getNode() && "Can't legalize SELECT_CC with legal condition!");
3412    Tmp2 = DAG.getConstant(0, Tmp1.getValueType());
3413    CC = DAG.getCondCode(ISD::SETNE);
3414    Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, Node->getValueType(0), Tmp1, Tmp2,
3415                       Tmp3, Tmp4, CC);
3416    Results.push_back(Tmp1);
3417    break;
3418  }
3419  case ISD::BR_CC: {
3420    Tmp1 = Node->getOperand(0);              // Chain
3421    Tmp2 = Node->getOperand(2);              // LHS
3422    Tmp3 = Node->getOperand(3);              // RHS
3423    Tmp4 = Node->getOperand(1);              // CC
3424
3425    LegalizeSetCCCondCode(TLI.getSetCCResultType(Tmp2.getValueType()),
3426                          Tmp2, Tmp3, Tmp4, dl);
3427
3428    assert(!Tmp3.getNode() && "Can't legalize BR_CC with legal condition!");
3429    Tmp3 = DAG.getConstant(0, Tmp2.getValueType());
3430    Tmp4 = DAG.getCondCode(ISD::SETNE);
3431    Tmp1 = DAG.getNode(ISD::BR_CC, dl, Node->getValueType(0), Tmp1, Tmp4, Tmp2,
3432                       Tmp3, Node->getOperand(4));
3433    Results.push_back(Tmp1);
3434    break;
3435  }
3436  case ISD::BUILD_VECTOR:
3437    Results.push_back(ExpandBUILD_VECTOR(Node));
3438    break;
3439  case ISD::SRA:
3440  case ISD::SRL:
3441  case ISD::SHL: {
3442    // Scalarize vector SRA/SRL/SHL.
3443    EVT VT = Node->getValueType(0);
3444    assert(VT.isVector() && "Unable to legalize non-vector shift");
3445    assert(TLI.isTypeLegal(VT.getScalarType())&& "Element type must be legal");
3446    unsigned NumElem = VT.getVectorNumElements();
3447
3448    SmallVector<SDValue, 8> Scalars;
3449    for (unsigned Idx = 0; Idx < NumElem; Idx++) {
3450      SDValue Ex = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
3451                               VT.getScalarType(),
3452                               Node->getOperand(0), DAG.getIntPtrConstant(Idx));
3453      SDValue Sh = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
3454                               VT.getScalarType(),
3455                               Node->getOperand(1), DAG.getIntPtrConstant(Idx));
3456      Scalars.push_back(DAG.getNode(Node->getOpcode(), dl,
3457                                    VT.getScalarType(), Ex, Sh));
3458    }
3459    SDValue Result =
3460      DAG.getNode(ISD::BUILD_VECTOR, dl, Node->getValueType(0),
3461                  &Scalars[0], Scalars.size());
3462    ReplaceNode(SDValue(Node, 0), Result);
3463    break;
3464  }
3465  case ISD::GLOBAL_OFFSET_TABLE:
3466  case ISD::GlobalAddress:
3467  case ISD::GlobalTLSAddress:
3468  case ISD::ExternalSymbol:
3469  case ISD::ConstantPool:
3470  case ISD::JumpTable:
3471  case ISD::INTRINSIC_W_CHAIN:
3472  case ISD::INTRINSIC_WO_CHAIN:
3473  case ISD::INTRINSIC_VOID:
3474    // FIXME: Custom lowering for these operations shouldn't return null!
3475    break;
3476  }
3477
3478  // Replace the original node with the legalized result.
3479  if (!Results.empty())
3480    ReplaceNode(Node, Results.data());
3481}
3482
3483void SelectionDAGLegalize::PromoteNode(SDNode *Node) {
3484  SmallVector<SDValue, 8> Results;
3485  EVT OVT = Node->getValueType(0);
3486  if (Node->getOpcode() == ISD::UINT_TO_FP ||
3487      Node->getOpcode() == ISD::SINT_TO_FP ||
3488      Node->getOpcode() == ISD::SETCC) {
3489    OVT = Node->getOperand(0).getValueType();
3490  }
3491  EVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
3492  DebugLoc dl = Node->getDebugLoc();
3493  SDValue Tmp1, Tmp2, Tmp3;
3494  switch (Node->getOpcode()) {
3495  case ISD::CTTZ:
3496  case ISD::CTTZ_ZERO_UNDEF:
3497  case ISD::CTLZ:
3498  case ISD::CTLZ_ZERO_UNDEF:
3499  case ISD::CTPOP:
3500    // Zero extend the argument.
3501    Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Node->getOperand(0));
3502    // Perform the larger operation. For CTPOP and CTTZ_ZERO_UNDEF, this is
3503    // already the correct result.
3504    Tmp1 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1);
3505    if (Node->getOpcode() == ISD::CTTZ) {
3506      // FIXME: This should set a bit in the zero extended value instead.
3507      Tmp2 = DAG.getSetCC(dl, TLI.getSetCCResultType(NVT),
3508                          Tmp1, DAG.getConstant(NVT.getSizeInBits(), NVT),
3509                          ISD::SETEQ);
3510      Tmp1 = DAG.getNode(ISD::SELECT, dl, NVT, Tmp2,
3511                          DAG.getConstant(OVT.getSizeInBits(), NVT), Tmp1);
3512    } else if (Node->getOpcode() == ISD::CTLZ ||
3513               Node->getOpcode() == ISD::CTLZ_ZERO_UNDEF) {
3514      // Tmp1 = Tmp1 - (sizeinbits(NVT) - sizeinbits(Old VT))
3515      Tmp1 = DAG.getNode(ISD::SUB, dl, NVT, Tmp1,
3516                          DAG.getConstant(NVT.getSizeInBits() -
3517                                          OVT.getSizeInBits(), NVT));
3518    }
3519    Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp1));
3520    break;
3521  case ISD::BSWAP: {
3522    unsigned DiffBits = NVT.getSizeInBits() - OVT.getSizeInBits();
3523    Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Node->getOperand(0));
3524    Tmp1 = DAG.getNode(ISD::BSWAP, dl, NVT, Tmp1);
3525    Tmp1 = DAG.getNode(ISD::SRL, dl, NVT, Tmp1,
3526                          DAG.getConstant(DiffBits, TLI.getShiftAmountTy(NVT)));
3527    Results.push_back(Tmp1);
3528    break;
3529  }
3530  case ISD::FP_TO_UINT:
3531  case ISD::FP_TO_SINT:
3532    Tmp1 = PromoteLegalFP_TO_INT(Node->getOperand(0), Node->getValueType(0),
3533                                 Node->getOpcode() == ISD::FP_TO_SINT, dl);
3534    Results.push_back(Tmp1);
3535    break;
3536  case ISD::UINT_TO_FP:
3537  case ISD::SINT_TO_FP:
3538    Tmp1 = PromoteLegalINT_TO_FP(Node->getOperand(0), Node->getValueType(0),
3539                                 Node->getOpcode() == ISD::SINT_TO_FP, dl);
3540    Results.push_back(Tmp1);
3541    break;
3542  case ISD::VAARG: {
3543    SDValue Chain = Node->getOperand(0); // Get the chain.
3544    SDValue Ptr = Node->getOperand(1); // Get the pointer.
3545
3546    unsigned TruncOp;
3547    if (OVT.isVector()) {
3548      TruncOp = ISD::BITCAST;
3549    } else {
3550      assert(OVT.isInteger()
3551        && "VAARG promotion is supported only for vectors or integer types");
3552      TruncOp = ISD::TRUNCATE;
3553    }
3554
3555    // Perform the larger operation, then convert back
3556    Tmp1 = DAG.getVAArg(NVT, dl, Chain, Ptr, Node->getOperand(2),
3557             Node->getConstantOperandVal(3));
3558    Chain = Tmp1.getValue(1);
3559
3560    Tmp2 = DAG.getNode(TruncOp, dl, OVT, Tmp1);
3561
3562    // Modified the chain result - switch anything that used the old chain to
3563    // use the new one.
3564    DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 0), Tmp2);
3565    DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), Chain);
3566    ReplacedNode(Node);
3567    break;
3568  }
3569  case ISD::AND:
3570  case ISD::OR:
3571  case ISD::XOR: {
3572    unsigned ExtOp, TruncOp;
3573    if (OVT.isVector()) {
3574      ExtOp   = ISD::BITCAST;
3575      TruncOp = ISD::BITCAST;
3576    } else {
3577      assert(OVT.isInteger() && "Cannot promote logic operation");
3578      ExtOp   = ISD::ANY_EXTEND;
3579      TruncOp = ISD::TRUNCATE;
3580    }
3581    // Promote each of the values to the new type.
3582    Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(0));
3583    Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
3584    // Perform the larger operation, then convert back
3585    Tmp1 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2);
3586    Results.push_back(DAG.getNode(TruncOp, dl, OVT, Tmp1));
3587    break;
3588  }
3589  case ISD::SELECT: {
3590    unsigned ExtOp, TruncOp;
3591    if (Node->getValueType(0).isVector()) {
3592      ExtOp   = ISD::BITCAST;
3593      TruncOp = ISD::BITCAST;
3594    } else if (Node->getValueType(0).isInteger()) {
3595      ExtOp   = ISD::ANY_EXTEND;
3596      TruncOp = ISD::TRUNCATE;
3597    } else {
3598      ExtOp   = ISD::FP_EXTEND;
3599      TruncOp = ISD::FP_ROUND;
3600    }
3601    Tmp1 = Node->getOperand(0);
3602    // Promote each of the values to the new type.
3603    Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
3604    Tmp3 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(2));
3605    // Perform the larger operation, then round down.
3606    Tmp1 = DAG.getNode(ISD::SELECT, dl, NVT, Tmp1, Tmp2, Tmp3);
3607    if (TruncOp != ISD::FP_ROUND)
3608      Tmp1 = DAG.getNode(TruncOp, dl, Node->getValueType(0), Tmp1);
3609    else
3610      Tmp1 = DAG.getNode(TruncOp, dl, Node->getValueType(0), Tmp1,
3611                         DAG.getIntPtrConstant(0));
3612    Results.push_back(Tmp1);
3613    break;
3614  }
3615  case ISD::VECTOR_SHUFFLE: {
3616    ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Node)->getMask();
3617
3618    // Cast the two input vectors.
3619    Tmp1 = DAG.getNode(ISD::BITCAST, dl, NVT, Node->getOperand(0));
3620    Tmp2 = DAG.getNode(ISD::BITCAST, dl, NVT, Node->getOperand(1));
3621
3622    // Convert the shuffle mask to the right # elements.
3623    Tmp1 = ShuffleWithNarrowerEltType(NVT, OVT, dl, Tmp1, Tmp2, Mask);
3624    Tmp1 = DAG.getNode(ISD::BITCAST, dl, OVT, Tmp1);
3625    Results.push_back(Tmp1);
3626    break;
3627  }
3628  case ISD::SETCC: {
3629    unsigned ExtOp = ISD::FP_EXTEND;
3630    if (NVT.isInteger()) {
3631      ISD::CondCode CCCode =
3632        cast<CondCodeSDNode>(Node->getOperand(2))->get();
3633      ExtOp = isSignedIntSetCC(CCCode) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
3634    }
3635    Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(0));
3636    Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
3637    Results.push_back(DAG.getNode(ISD::SETCC, dl, Node->getValueType(0),
3638                                  Tmp1, Tmp2, Node->getOperand(2)));
3639    break;
3640  }
3641  case ISD::FDIV:
3642  case ISD::FREM:
3643  case ISD::FPOW: {
3644    Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0));
3645    Tmp2 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(1));
3646    Tmp3 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2);
3647    Results.push_back(DAG.getNode(ISD::FP_ROUND, dl, OVT,
3648                                  Tmp3, DAG.getIntPtrConstant(0)));
3649    break;
3650  }
3651  case ISD::FLOG2:
3652  case ISD::FEXP2:
3653  case ISD::FLOG:
3654  case ISD::FEXP: {
3655    Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0));
3656    Tmp2 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1);
3657    Results.push_back(DAG.getNode(ISD::FP_ROUND, dl, OVT,
3658                                  Tmp2, DAG.getIntPtrConstant(0)));
3659    break;
3660  }
3661  }
3662
3663  // Replace the original node with the legalized result.
3664  if (!Results.empty())
3665    ReplaceNode(Node, Results.data());
3666}
3667
3668// SelectionDAG::Legalize - This is the entry point for the file.
3669//
3670void SelectionDAG::Legalize() {
3671  /// run - This is the main entry point to this class.
3672  ///
3673  SelectionDAGLegalize(*this).LegalizeDAG();
3674}
3675