blob: ab07954a6f1640a9b18c0067c43719f1fb021fa9 [file] [log] [blame]
Nate Begeman2504fe22005-09-01 23:24:04 +00001//===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
Nate Begeman21158fc2005-09-01 00:19:25 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Nate Begeman21158fc2005-09-01 00:19:25 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This pass combines dag nodes to form fewer, simpler DAG nodes. It can be run
11// both before and after the DAG is legalized.
Scott Michelcf0da6c2009-02-17 22:15:04 +000012//
Dan Gohman45399872009-04-25 17:09:45 +000013// This pass is not a substitute for the LLVM IR instcombine pass. This pass is
14// primarily intended to handle simplification opportunities that are implicit
15// in the LLVM IR and exposed by the various codegen lowering phases.
16//
Nate Begeman21158fc2005-09-01 00:19:25 +000017//===----------------------------------------------------------------------===//
18
Nate Begeman21158fc2005-09-01 00:19:25 +000019#include "llvm/CodeGen/SelectionDAG.h"
Chris Lattner48fb92f2007-05-16 06:37:59 +000020#include "llvm/ADT/SmallPtrSet.h"
21#include "llvm/ADT/Statistic.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000022#include "llvm/Analysis/AliasAnalysis.h"
23#include "llvm/CodeGen/MachineFrameInfo.h"
24#include "llvm/CodeGen/MachineFunction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000025#include "llvm/IR/DataLayout.h"
26#include "llvm/IR/DerivedTypes.h"
27#include "llvm/IR/Function.h"
28#include "llvm/IR/LLVMContext.h"
Jim Laskey5d19d592006-09-21 16:28:59 +000029#include "llvm/Support/CommandLine.h"
Chris Lattner48fb92f2007-05-16 06:37:59 +000030#include "llvm/Support/Debug.h"
Torok Edwinccb29cd2009-07-11 13:10:19 +000031#include "llvm/Support/ErrorHandling.h"
Chris Lattner48fb92f2007-05-16 06:37:59 +000032#include "llvm/Support/MathExtras.h"
Chris Lattner4dc3edd2009-08-23 06:35:02 +000033#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000034#include "llvm/Target/TargetLowering.h"
35#include "llvm/Target/TargetMachine.h"
36#include "llvm/Target/TargetOptions.h"
Quentin Colombetde0e0622013-10-11 18:29:42 +000037#include "llvm/Target/TargetRegisterInfo.h"
Hal Finkel5ef4dcc2013-08-29 03:29:55 +000038#include "llvm/Target/TargetSubtargetInfo.h"
Chris Lattnerbd39c1a2005-09-09 23:53:39 +000039#include <algorithm>
Nate Begeman21158fc2005-09-01 00:19:25 +000040using namespace llvm;
41
Chandler Carruth1b9dde02014-04-22 02:02:50 +000042#define DEBUG_TYPE "dagcombine"
43
Chris Lattneraee775a2006-12-19 22:41:21 +000044STATISTIC(NodesCombined , "Number of dag nodes combined");
45STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
46STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
Evan Chenga9cda8a2009-05-28 00:35:15 +000047STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
Evan Chengd42641c2011-02-02 01:06:55 +000048STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int");
Quentin Colombetde0e0622013-10-11 18:29:42 +000049STATISTIC(SlicedLoads, "Number of load sliced");
Chris Lattneraee775a2006-12-19 22:41:21 +000050
Nate Begeman21158fc2005-09-01 00:19:25 +000051namespace {
Jim Laskey0463e082006-10-07 23:37:56 +000052 static cl::opt<bool>
Owen Anderson7b8d2ae2010-09-19 21:01:26 +000053 CombinerAA("combiner-alias-analysis", cl::Hidden,
Hal Finkel5fb07342014-01-25 17:32:37 +000054 cl::desc("Enable DAG combiner alias-analysis heuristics"));
Jim Laskeydf2ccc32006-10-12 15:22:24 +000055
Jim Laskey55e4dca2006-10-18 19:08:31 +000056 static cl::opt<bool>
57 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
Hal Finkel5fb07342014-01-25 17:32:37 +000058 cl::desc("Enable DAG combiner's use of IR alias analysis"));
Jim Laskey55e4dca2006-10-18 19:08:31 +000059
Hal Finkeldbebb522014-01-25 19:24:54 +000060 static cl::opt<bool>
Hal Finkel3b48d082014-04-12 01:26:00 +000061 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
Hal Finkeldbebb522014-01-25 19:24:54 +000062 cl::desc("Enable DAG combiner's use of TBAA"));
63
Hal Finkel9b2617a2014-01-25 17:32:39 +000064#ifndef NDEBUG
65 static cl::opt<std::string>
66 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
67 cl::desc("Only use DAG-combiner alias analysis in this"
68 " function"));
69#endif
70
Quentin Colombetde0e0622013-10-11 18:29:42 +000071 /// Hidden option to stress test load slicing, i.e., when this option
72 /// is enabled, load slicing bypasses most of its profitability guards.
73 static cl::opt<bool>
74 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
75 cl::desc("Bypass the profitability model of load "
76 "slicing"),
77 cl::init(false));
78
Jim Laskey6549d222006-10-05 15:07:25 +000079//------------------------------ DAGCombiner ---------------------------------//
80
Nick Lewycky02d5f772009-10-25 06:33:48 +000081 class DAGCombiner {
Nate Begeman21158fc2005-09-01 00:19:25 +000082 SelectionDAG &DAG;
Dan Gohman619ef482009-01-15 19:20:50 +000083 const TargetLowering &TLI;
Duncan Sandsdc2dac12008-11-24 14:53:14 +000084 CombineLevel Level;
Bill Wendling026e5d72009-04-29 23:29:43 +000085 CodeGenOpt::Level OptLevel;
Duncan Sandsdc2dac12008-11-24 14:53:14 +000086 bool LegalOperations;
87 bool LegalTypes;
Quentin Colombetde0e0622013-10-11 18:29:42 +000088 bool ForCodeSize;
Nate Begeman21158fc2005-09-01 00:19:25 +000089
90 // Worklist of all of the nodes that need to be simplified.
James Molloy67b6b112012-02-16 09:17:04 +000091 //
92 // This has the semantics that when adding to the worklist,
93 // the item added must be next to be processed. It should
94 // also only appear once. The naive approach to this takes
95 // linear time.
96 //
97 // To reduce the insert/remove time to logarithmic, we use
98 // a set and a vector to maintain our worklist.
99 //
100 // The set contains the items on the worklist, but does not
101 // maintain the order they should be visited.
102 //
103 // The vector maintains the order nodes should be visited, but may
104 // contain duplicate or removed nodes. When choosing a node to
105 // visit, we pop off the order stack until we find an item that is
106 // also in the contents set. All operations are O(log N).
107 SmallPtrSet<SDNode*, 64> WorkListContents;
Benjamin Kramere1e549d2012-03-10 00:23:58 +0000108 SmallVector<SDNode*, 64> WorkListOrder;
Nate Begeman21158fc2005-09-01 00:19:25 +0000109
Jim Laskeydcb2b832006-10-16 20:52:31 +0000110 // AA - Used for DAG load/store alias analysis.
111 AliasAnalysis &AA;
112
Nate Begeman21158fc2005-09-01 00:19:25 +0000113 /// AddUsersToWorkList - When an instruction is simplified, add all users of
114 /// the instruction to the work lists because they might get more simplified
115 /// now.
116 ///
117 void AddUsersToWorkList(SDNode *N) {
Jim Grosbache8160032014-04-11 01:13:13 +0000118 for (SDNode *Node : N->uses())
119 AddToWorkList(Node);
Nate Begeman21158fc2005-09-01 00:19:25 +0000120 }
121
Dan Gohman5c6d0c32007-10-08 17:57:15 +0000122 /// visit - call the node-specific routine that knows how to fold each
123 /// particular type of node.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000124 SDValue visit(SDNode *N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +0000125
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000126 public:
James Molloy920ae8c2012-02-16 09:48:07 +0000127 /// AddToWorkList - Add to the work list making sure its instance is at the
James Molloy67b6b112012-02-16 09:17:04 +0000128 /// back (next to be processed.)
Chris Lattnerfbcd62d2006-03-01 04:03:14 +0000129 void AddToWorkList(SDNode *N) {
James Molloy67b6b112012-02-16 09:17:04 +0000130 WorkListContents.insert(N);
131 WorkListOrder.push_back(N);
Chris Lattnerfbcd62d2006-03-01 04:03:14 +0000132 }
Jim Laskey708d0db2006-10-04 16:53:27 +0000133
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000134 /// removeFromWorkList - remove all instances of N from the worklist.
135 ///
136 void removeFromWorkList(SDNode *N) {
James Molloy67b6b112012-02-16 09:17:04 +0000137 WorkListContents.erase(N);
Chris Lattnere260ed82005-10-10 22:04:48 +0000138 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000139
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000140 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
Evan Chengfd81c732009-03-28 05:57:29 +0000141 bool AddTo = true);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000142
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000143 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
Jim Laskeydcf983c2006-10-13 23:32:28 +0000144 return CombineTo(N, &Res, 1, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000145 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000146
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000147 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
Evan Chengfd81c732009-03-28 05:57:29 +0000148 bool AddTo = true) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000149 SDValue To[] = { Res0, Res1 };
Jim Laskeydcf983c2006-10-13 23:32:28 +0000150 return CombineTo(N, To, 2, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000151 }
Dan Gohmane58ab792009-01-29 01:59:02 +0000152
153 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000154
155 private:
156
Chris Lattner375e1a72006-02-17 21:58:01 +0000157 /// SimplifyDemandedBits - Check the specified integer node value to see if
Chris Lattner232024e2006-03-01 19:55:35 +0000158 /// it can be simplified or if things it uses can be simplified by bit
Chris Lattner375e1a72006-02-17 21:58:01 +0000159 /// propagation. If so, return true.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000160 bool SimplifyDemandedBits(SDValue Op) {
Dan Gohman1d459e42009-12-11 21:31:27 +0000161 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
162 APInt Demanded = APInt::getAllOnesValue(BitWidth);
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000163 return SimplifyDemandedBits(Op, Demanded);
164 }
165
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000166 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
Chris Lattner04c73702005-10-10 22:31:19 +0000167
Chris Lattnerffad2162006-11-11 00:39:41 +0000168 bool CombineToPreIndexedLoadStore(SDNode *N);
169 bool CombineToPostIndexedLoadStore(SDNode *N);
Quentin Colombetde0e0622013-10-11 18:29:42 +0000170 bool SliceUpLoad(SDNode *N);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000171
Michael J. Spencerf375d802014-05-29 01:42:45 +0000172 /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
173 /// load.
174 ///
175 /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
176 /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
177 /// \param EltNo index of the vector element to load.
178 /// \param OriginalLoad load that EVE came from to be replaced.
179 /// \returns EVE on success SDValue() on failure.
180 SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
181 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000182 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
183 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
184 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
185 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
Evan Chengaf56fac2010-04-16 06:14:10 +0000186 SDValue PromoteIntBinOp(SDValue Op);
Evan Chengf1223bd2010-04-22 20:19:46 +0000187 SDValue PromoteIntShiftOp(SDValue Op);
Evan Chenge19aa5c2010-04-19 19:29:22 +0000188 SDValue PromoteExtend(SDValue Op);
189 bool PromoteLoad(SDValue Op);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000190
Craig Toppere0b71182013-07-13 07:43:40 +0000191 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
Andrew Trickef9de2a2013-05-25 02:42:55 +0000192 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
Nick Lewycky6d677cf2011-06-16 01:15:49 +0000193 ISD::NodeType ExtType);
194
Dan Gohman5c6d0c32007-10-08 17:57:15 +0000195 /// combine - call the node-specific routine that knows how to fold each
196 /// particular type of node. If that doesn't do anything, try the
197 /// target-specific DAG combines.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000198 SDValue combine(SDNode *N);
Nate Begeman21158fc2005-09-01 00:19:25 +0000199
200 // Visitation implementation - Implement dag node combining for different
201 // node types. The semantics are as follows:
202 // Return Value:
Evan Cheng5e7658c2008-08-29 22:21:44 +0000203 // SDValue.getNode() == 0 - No change was made
204 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
205 // otherwise - N should be replaced by the returned Operand.
Nate Begeman21158fc2005-09-01 00:19:25 +0000206 //
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000207 SDValue visitTokenFactor(SDNode *N);
208 SDValue visitMERGE_VALUES(SDNode *N);
209 SDValue visitADD(SDNode *N);
210 SDValue visitSUB(SDNode *N);
211 SDValue visitADDC(SDNode *N);
Craig Topper43a1bd62012-01-07 09:06:39 +0000212 SDValue visitSUBC(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000213 SDValue visitADDE(SDNode *N);
Craig Topper43a1bd62012-01-07 09:06:39 +0000214 SDValue visitSUBE(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000215 SDValue visitMUL(SDNode *N);
216 SDValue visitSDIV(SDNode *N);
217 SDValue visitUDIV(SDNode *N);
218 SDValue visitSREM(SDNode *N);
219 SDValue visitUREM(SDNode *N);
220 SDValue visitMULHU(SDNode *N);
221 SDValue visitMULHS(SDNode *N);
222 SDValue visitSMUL_LOHI(SDNode *N);
223 SDValue visitUMUL_LOHI(SDNode *N);
Benjamin Kramer2fd48f22011-05-21 18:31:55 +0000224 SDValue visitSMULO(SDNode *N);
225 SDValue visitUMULO(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000226 SDValue visitSDIVREM(SDNode *N);
227 SDValue visitUDIVREM(SDNode *N);
228 SDValue visitAND(SDNode *N);
229 SDValue visitOR(SDNode *N);
230 SDValue visitXOR(SDNode *N);
231 SDValue SimplifyVBinOp(SDNode *N);
Craig Topper82384612012-09-11 01:45:21 +0000232 SDValue SimplifyVUnaryOp(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000233 SDValue visitSHL(SDNode *N);
234 SDValue visitSRA(SDNode *N);
235 SDValue visitSRL(SDNode *N);
Adam Nemet7f928f12014-03-07 23:56:30 +0000236 SDValue visitRotate(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000237 SDValue visitCTLZ(SDNode *N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +0000238 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000239 SDValue visitCTTZ(SDNode *N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +0000240 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000241 SDValue visitCTPOP(SDNode *N);
242 SDValue visitSELECT(SDNode *N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +0000243 SDValue visitVSELECT(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000244 SDValue visitSELECT_CC(SDNode *N);
245 SDValue visitSETCC(SDNode *N);
246 SDValue visitSIGN_EXTEND(SDNode *N);
247 SDValue visitZERO_EXTEND(SDNode *N);
248 SDValue visitANY_EXTEND(SDNode *N);
249 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
250 SDValue visitTRUNCATE(SDNode *N);
Wesley Peck527da1b2010-11-23 03:31:01 +0000251 SDValue visitBITCAST(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000252 SDValue visitBUILD_PAIR(SDNode *N);
253 SDValue visitFADD(SDNode *N);
254 SDValue visitFSUB(SDNode *N);
255 SDValue visitFMUL(SDNode *N);
Owen Anderson41b06652012-05-02 22:17:40 +0000256 SDValue visitFMA(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000257 SDValue visitFDIV(SDNode *N);
258 SDValue visitFREM(SDNode *N);
259 SDValue visitFCOPYSIGN(SDNode *N);
260 SDValue visitSINT_TO_FP(SDNode *N);
261 SDValue visitUINT_TO_FP(SDNode *N);
262 SDValue visitFP_TO_SINT(SDNode *N);
263 SDValue visitFP_TO_UINT(SDNode *N);
264 SDValue visitFP_ROUND(SDNode *N);
265 SDValue visitFP_ROUND_INREG(SDNode *N);
266 SDValue visitFP_EXTEND(SDNode *N);
267 SDValue visitFNEG(SDNode *N);
268 SDValue visitFABS(SDNode *N);
Owen Andersona40319b2012-08-13 23:32:49 +0000269 SDValue visitFCEIL(SDNode *N);
270 SDValue visitFTRUNC(SDNode *N);
271 SDValue visitFFLOOR(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000272 SDValue visitBRCOND(SDNode *N);
273 SDValue visitBR_CC(SDNode *N);
274 SDValue visitLOAD(SDNode *N);
275 SDValue visitSTORE(SDNode *N);
276 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
277 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
278 SDValue visitBUILD_VECTOR(SDNode *N);
279 SDValue visitCONCAT_VECTORS(SDNode *N);
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +0000280 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000281 SDValue visitVECTOR_SHUFFLE(SDNode *N);
Manman Ren413a6cb2014-01-31 01:10:35 +0000282 SDValue visitINSERT_SUBVECTOR(SDNode *N);
Chris Lattnere260ed82005-10-10 22:04:48 +0000283
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000284 SDValue XformToShuffleWithZero(SDNode *N);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000285 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000286
Matt Arsenault985b9de2014-03-17 18:58:01 +0000287 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
Chris Lattner7c709a52007-12-06 07:33:36 +0000288
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000289 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
290 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000291 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
292 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
Scott Michelcf0da6c2009-02-17 22:15:04 +0000293 SDValue N3, ISD::CondCode CC,
Bill Wendling31b50992009-01-30 23:59:18 +0000294 bool NotExtCompare = false);
Owen Anderson53aa7a92009-08-10 22:56:29 +0000295 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
Andrew Trickef9de2a2013-05-25 02:42:55 +0000296 SDLoc DL, bool foldBooleans = true);
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000297
298 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
299 SDValue &CC) const;
300 bool isOneUseSetCC(SDValue N) const;
301
Scott Michelcf0da6c2009-02-17 22:15:04 +0000302 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
Chris Lattner31e9edc2008-01-26 01:09:19 +0000303 unsigned HiOp);
Owen Anderson53aa7a92009-08-10 22:56:29 +0000304 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
Wesley Peck527da1b2010-11-23 03:31:01 +0000305 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000306 SDValue BuildSDIV(SDNode *N);
307 SDValue BuildUDIV(SDNode *N);
Evan Cheng4c0bd962011-06-21 06:01:08 +0000308 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
309 bool DemandHighBits = true);
310 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
Richard Sandiford95c864d2014-01-08 15:40:47 +0000311 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
312 SDValue InnerPos, SDValue InnerNeg,
313 unsigned PosOpcode, unsigned NegOpcode,
314 SDLoc DL);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000315 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000316 SDValue ReduceLoadWidth(SDNode *N);
Evan Chenga9cda8a2009-05-28 00:35:15 +0000317 SDValue ReduceLoadOpStoreWidth(SDNode *N);
Evan Chengd42641c2011-02-02 01:06:55 +0000318 SDValue TransformFPLoadStorePair(SDNode *N);
Michael Liao6d106b72012-10-23 23:06:52 +0000319 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
Michael Liao59229792012-10-24 04:14:18 +0000320 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000321
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000322 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000323
Jim Laskey708d0db2006-10-04 16:53:27 +0000324 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
325 /// looking for aliasing nodes and adding them to the Aliases vector.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000326 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
Craig Topperb94011f2013-07-14 04:42:23 +0000327 SmallVectorImpl<SDValue> &Aliases);
Jim Laskey708d0db2006-10-04 16:53:27 +0000328
Jim Laskeya15b0eb2006-10-18 12:29:57 +0000329 /// isAlias - Return true if there is any possibility that the two addresses
330 /// overlap.
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000331 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000332
Jim Laskeyd07be232006-09-25 16:29:54 +0000333 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
Jim Laskey708d0db2006-10-04 16:53:27 +0000334 /// looking for a better chain (aliasing node.)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000335 SDValue FindBetterChain(SDNode *N, SDValue Chain);
Duncan Sands41826032009-01-31 15:50:11 +0000336
Nadav Rotem7cbc12a2012-10-03 16:11:15 +0000337 /// Merge consecutive store operations into a wide store.
338 /// This optimization uses wide integers or vectors when possible.
339 /// \return True if some memory operations were changed.
340 bool MergeConsecutiveStores(StoreSDNode *N);
341
Adam Nemet67483892014-03-04 23:28:31 +0000342 /// \brief Try to transform a truncation where C is a constant:
343 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
344 ///
345 /// \p N needs to be a truncation and its first operand an AND. Other
346 /// requirements are checked by the function (e.g. that trunc is
347 /// single-use) and if missed an empty SDValue is returned.
348 SDValue distributeTruncateThroughAnd(SDNode *N);
349
Chris Lattner4041ab62010-04-15 04:48:01 +0000350 public:
Bill Wendling026e5d72009-04-29 23:29:43 +0000351 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
Quentin Colombetde0e0622013-10-11 18:29:42 +0000352 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
353 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
354 AttributeSet FnAttrs =
355 DAG.getMachineFunction().getFunction()->getAttributes();
356 ForCodeSize =
357 FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
358 Attribute::OptimizeForSize) ||
359 FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
360 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000361
Nate Begeman21158fc2005-09-01 00:19:25 +0000362 /// Run - runs the dag combiner on all nodes in the work list
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000363 void Run(CombineLevel AtLevel);
Wesley Peck527da1b2010-11-23 03:31:01 +0000364
Chris Lattner4041ab62010-04-15 04:48:01 +0000365 SelectionDAG &getDAG() const { return DAG; }
Wesley Peck527da1b2010-11-23 03:31:01 +0000366
Chris Lattner4041ab62010-04-15 04:48:01 +0000367 /// getShiftAmountTy - Returns a type large enough to hold any valid
368 /// shift amount - before type legalization these can be huge.
Owen Andersonb2c80da2011-02-25 21:41:48 +0000369 EVT getShiftAmountTy(EVT LHSTy) {
Elena Demikhovsky6769c502013-06-26 10:55:03 +0000370 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
371 if (LHSTy.isVector())
372 return LHSTy;
Jack Carterd4e96152013-10-17 01:34:33 +0000373 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
374 : TLI.getPointerTy();
Chris Lattner4041ab62010-04-15 04:48:01 +0000375 }
Wesley Peck527da1b2010-11-23 03:31:01 +0000376
Chris Lattner4041ab62010-04-15 04:48:01 +0000377 /// isTypeLegal - This method returns true if we are running before type
378 /// legalization or if the specified VT is legal.
379 bool isTypeLegal(const EVT &VT) {
380 if (!LegalTypes) return true;
381 return TLI.isTypeLegal(VT);
382 }
Matt Arsenault758659232013-05-18 00:21:46 +0000383
384 /// getSetCCResultType - Convenience wrapper around
385 /// TargetLowering::getSetCCResultType
386 EVT getSetCCResultType(EVT VT) const {
387 return TLI.getSetCCResultType(*DAG.getContext(), VT);
388 }
Nate Begeman21158fc2005-09-01 00:19:25 +0000389 };
390}
391
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000392
393namespace {
394/// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
395/// nodes from the worklist.
Nick Lewycky02d5f772009-10-25 06:33:48 +0000396class WorkListRemover : public SelectionDAG::DAGUpdateListener {
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000397 DAGCombiner &DC;
398public:
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000399 explicit WorkListRemover(DAGCombiner &dc)
400 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
Scott Michelcf0da6c2009-02-17 22:15:04 +0000401
Craig Topper7b883b32014-03-08 06:31:39 +0000402 void NodeDeleted(SDNode *N, SDNode *E) override {
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000403 DC.removeFromWorkList(N);
404 }
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000405};
406}
407
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000408//===----------------------------------------------------------------------===//
409// TargetLowering::DAGCombinerInfo implementation
410//===----------------------------------------------------------------------===//
411
412void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
413 ((DAGCombiner*)DC)->AddToWorkList(N);
414}
415
Cameron Zwarich8c7bbc02011-04-02 02:40:26 +0000416void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
417 ((DAGCombiner*)DC)->removeFromWorkList(N);
418}
419
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000420SDValue TargetLowering::DAGCombinerInfo::
Evan Chengfd81c732009-03-28 05:57:29 +0000421CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
422 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000423}
424
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000425SDValue TargetLowering::DAGCombinerInfo::
Evan Chengfd81c732009-03-28 05:57:29 +0000426CombineTo(SDNode *N, SDValue Res, bool AddTo) {
427 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000428}
429
430
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000431SDValue TargetLowering::DAGCombinerInfo::
Evan Chengfd81c732009-03-28 05:57:29 +0000432CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
433 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000434}
435
Dan Gohmane58ab792009-01-29 01:59:02 +0000436void TargetLowering::DAGCombinerInfo::
437CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
438 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
439}
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000440
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000441//===----------------------------------------------------------------------===//
Chris Lattnere49c9742007-05-14 22:04:50 +0000442// Helper Functions
443//===----------------------------------------------------------------------===//
444
445/// isNegatibleForFree - Return 1 if we can compute the negated form of the
446/// specified expression for the same cost as the expression itself, or 2 if we
447/// can compute the negated form more cheaply than the expression itself.
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000448static char isNegatibleForFree(SDValue Op, bool LegalOperations,
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000449 const TargetLowering &TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000450 const TargetOptions *Options,
Chris Lattnere7c14012008-02-26 07:04:54 +0000451 unsigned Depth = 0) {
Chris Lattnere49c9742007-05-14 22:04:50 +0000452 // fneg is removable even if it has multiple uses.
453 if (Op.getOpcode() == ISD::FNEG) return 2;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000454
Chris Lattnere49c9742007-05-14 22:04:50 +0000455 // Don't allow anything with multiple uses.
456 if (!Op.hasOneUse()) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000457
Chris Lattner46980832007-05-25 02:19:06 +0000458 // Don't recurse exponentially.
459 if (Depth > 6) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000460
Chris Lattnere49c9742007-05-14 22:04:50 +0000461 switch (Op.getOpcode()) {
462 default: return false;
463 case ISD::ConstantFP:
Chris Lattnere7c14012008-02-26 07:04:54 +0000464 // Don't invert constant FP values after legalize. The negated constant
465 // isn't necessarily legal.
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000466 return LegalOperations ? 0 : 1;
Chris Lattnere49c9742007-05-14 22:04:50 +0000467 case ISD::FADD:
468 // FIXME: determine better conditions for this xform.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000469 if (!Options->UnsafeFPMath) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000470
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000471 // After operation legalization, it might not be legal to create new FSUBs.
472 if (LegalOperations &&
473 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
474 return 0;
475
Craig Topper03f39772012-09-09 22:58:45 +0000476 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000477 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
478 Options, Depth + 1))
Chris Lattnere49c9742007-05-14 22:04:50 +0000479 return V;
Bill Wendling6fbf5492009-01-30 23:10:18 +0000480 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000481 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000482 Depth + 1);
Chris Lattnere49c9742007-05-14 22:04:50 +0000483 case ISD::FSUB:
Scott Michelcf0da6c2009-02-17 22:15:04 +0000484 // We can't turn -(A-B) into B-A when we honor signed zeros.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000485 if (!Options->UnsafeFPMath) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000486
Bill Wendling6fbf5492009-01-30 23:10:18 +0000487 // fold (fneg (fsub A, B)) -> (fsub B, A)
Chris Lattnere49c9742007-05-14 22:04:50 +0000488 return 1;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000489
Chris Lattnere49c9742007-05-14 22:04:50 +0000490 case ISD::FMUL:
491 case ISD::FDIV:
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000492 if (Options->HonorSignDependentRoundingFPMath()) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000493
Bill Wendling6fbf5492009-01-30 23:10:18 +0000494 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000495 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
496 Options, Depth + 1))
Chris Lattnere49c9742007-05-14 22:04:50 +0000497 return V;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000498
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000499 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000500 Depth + 1);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000501
Chris Lattnere49c9742007-05-14 22:04:50 +0000502 case ISD::FP_EXTEND:
503 case ISD::FP_ROUND:
504 case ISD::FSIN:
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000505 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000506 Depth + 1);
Chris Lattnere49c9742007-05-14 22:04:50 +0000507 }
508}
509
510/// GetNegatedExpression - If isNegatibleForFree returns true, this function
511/// returns the newly negated expression.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000512static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000513 bool LegalOperations, unsigned Depth = 0) {
Chris Lattnere49c9742007-05-14 22:04:50 +0000514 // fneg is removable even if it has multiple uses.
515 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000516
Chris Lattnere49c9742007-05-14 22:04:50 +0000517 // Don't allow anything with multiple uses.
518 assert(Op.hasOneUse() && "Unknown reuse!");
Scott Michelcf0da6c2009-02-17 22:15:04 +0000519
Chris Lattner46980832007-05-25 02:19:06 +0000520 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
Chris Lattnere49c9742007-05-14 22:04:50 +0000521 switch (Op.getOpcode()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000522 default: llvm_unreachable("Unknown code");
Dale Johannesen446b9002007-08-31 23:34:27 +0000523 case ISD::ConstantFP: {
524 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
525 V.changeSign();
526 return DAG.getConstantFP(V, Op.getValueType());
527 }
Chris Lattnere49c9742007-05-14 22:04:50 +0000528 case ISD::FADD:
529 // FIXME: determine better conditions for this xform.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000530 assert(DAG.getTarget().Options.UnsafeFPMath);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000531
Bill Wendling6fbf5492009-01-30 23:10:18 +0000532 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000533 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000534 DAG.getTargetLoweringInfo(),
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000535 &DAG.getTarget().Options, Depth+1))
Andrew Trickef9de2a2013-05-25 02:42:55 +0000536 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000537 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000538 LegalOperations, Depth+1),
Chris Lattnere49c9742007-05-14 22:04:50 +0000539 Op.getOperand(1));
Bill Wendling6fbf5492009-01-30 23:10:18 +0000540 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
Andrew Trickef9de2a2013-05-25 02:42:55 +0000541 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000542 GetNegatedExpression(Op.getOperand(1), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000543 LegalOperations, Depth+1),
Chris Lattnere49c9742007-05-14 22:04:50 +0000544 Op.getOperand(0));
545 case ISD::FSUB:
Scott Michelcf0da6c2009-02-17 22:15:04 +0000546 // We can't turn -(A-B) into B-A when we honor signed zeros.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000547 assert(DAG.getTarget().Options.UnsafeFPMath);
Dan Gohman9a708232007-07-02 15:48:56 +0000548
Bill Wendling6fbf5492009-01-30 23:10:18 +0000549 // fold (fneg (fsub 0, B)) -> B
Dan Gohman9a708232007-07-02 15:48:56 +0000550 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
Dale Johannesen446b9002007-08-31 23:34:27 +0000551 if (N0CFP->getValueAPF().isZero())
Dan Gohman9a708232007-07-02 15:48:56 +0000552 return Op.getOperand(1);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000553
Bill Wendling6fbf5492009-01-30 23:10:18 +0000554 // fold (fneg (fsub A, B)) -> (fsub B, A)
Andrew Trickef9de2a2013-05-25 02:42:55 +0000555 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000556 Op.getOperand(1), Op.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +0000557
Chris Lattnere49c9742007-05-14 22:04:50 +0000558 case ISD::FMUL:
559 case ISD::FDIV:
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000560 assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000561
Bill Wendling6fbf5492009-01-30 23:10:18 +0000562 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000563 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000564 DAG.getTargetLoweringInfo(),
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000565 &DAG.getTarget().Options, Depth+1))
Andrew Trickef9de2a2013-05-25 02:42:55 +0000566 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000567 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000568 LegalOperations, Depth+1),
Chris Lattnere49c9742007-05-14 22:04:50 +0000569 Op.getOperand(1));
Scott Michelcf0da6c2009-02-17 22:15:04 +0000570
Bill Wendling6fbf5492009-01-30 23:10:18 +0000571 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
Andrew Trickef9de2a2013-05-25 02:42:55 +0000572 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Chris Lattnere49c9742007-05-14 22:04:50 +0000573 Op.getOperand(0),
Chris Lattnere7c14012008-02-26 07:04:54 +0000574 GetNegatedExpression(Op.getOperand(1), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000575 LegalOperations, Depth+1));
Scott Michelcf0da6c2009-02-17 22:15:04 +0000576
Chris Lattnere49c9742007-05-14 22:04:50 +0000577 case ISD::FP_EXTEND:
Chris Lattnere49c9742007-05-14 22:04:50 +0000578 case ISD::FSIN:
Andrew Trickef9de2a2013-05-25 02:42:55 +0000579 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000580 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000581 LegalOperations, Depth+1));
Chris Lattner72733e52008-01-17 07:00:52 +0000582 case ISD::FP_ROUND:
Andrew Trickef9de2a2013-05-25 02:42:55 +0000583 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000584 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000585 LegalOperations, Depth+1),
Chris Lattner72733e52008-01-17 07:00:52 +0000586 Op.getOperand(1));
Chris Lattnere49c9742007-05-14 22:04:50 +0000587 }
588}
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000589
Nate Begeman2504fe22005-09-01 23:24:04 +0000590// isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000591// that selects between the target values used for true and false, making it
592// equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
593// the appropriate nodes based on the type of node we are checking. This
594// simplifies life a bit for the callers.
595bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
596 SDValue &CC) const {
Nate Begeman7cea6ef2005-09-02 21:18:40 +0000597 if (N.getOpcode() == ISD::SETCC) {
598 LHS = N.getOperand(0);
599 RHS = N.getOperand(1);
600 CC = N.getOperand(2);
Nate Begeman2504fe22005-09-01 23:24:04 +0000601 return true;
Nate Begeman7cea6ef2005-09-02 21:18:40 +0000602 }
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000603
604 if (N.getOpcode() != ISD::SELECT_CC ||
605 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
606 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
607 return false;
608
609 LHS = N.getOperand(0);
610 RHS = N.getOperand(1);
611 CC = N.getOperand(4);
612 return true;
Nate Begeman21158fc2005-09-01 00:19:25 +0000613}
614
Nate Begeman2cc2c9a2005-09-07 23:25:52 +0000615// isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
616// one use. If this is true, it allows the users to invert the operation for
617// free when it is profitable to do so.
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000618bool DAGCombiner::isOneUseSetCC(SDValue N) const {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000619 SDValue N0, N1, N2;
Gabor Greiff304a7a2008-08-28 21:40:38 +0000620 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
Nate Begeman2504fe22005-09-01 23:24:04 +0000621 return true;
622 return false;
623}
624
Matt Arsenault985b9de2014-03-17 18:58:01 +0000625/// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose
626/// elements are all the same constant or undefined.
627static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
628 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
629 if (!C)
630 return false;
631
632 APInt SplatUndef;
633 unsigned SplatBitSize;
634 bool HasAnyUndefs;
635 EVT EltVT = N->getValueType(0).getVectorElementType();
636 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
637 HasAnyUndefs) &&
638 EltVT.getSizeInBits() >= SplatBitSize);
639}
640
641// \brief Returns the SDNode if it is a constant BuildVector or constant.
Juergen Ributzka68402822014-01-13 21:49:25 +0000642static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
643 if (isa<ConstantSDNode>(N))
644 return N.getNode();
645 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
646 if(BV && BV->isConstant())
647 return BV;
Craig Topperc0196b12014-04-14 00:51:57 +0000648 return nullptr;
Juergen Ributzka68402822014-01-13 21:49:25 +0000649}
650
Matt Arsenault985b9de2014-03-17 18:58:01 +0000651// \brief Returns the SDNode if it is a constant splat BuildVector or constant
652// int.
653static ConstantSDNode *isConstOrConstSplat(SDValue N) {
654 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
655 return CN;
656
Chandler Carruthbeeacac2014-07-07 19:03:32 +0000657 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
Chandler Carruthf0a33b72014-07-09 00:41:34 +0000658 BitVector UndefElements;
659 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
Chandler Carruthbeeacac2014-07-07 19:03:32 +0000660
661 // BuildVectors can truncate their operands. Ignore that case here.
Chandler Carruthb844e722014-07-08 07:19:55 +0000662 // FIXME: We blindly ignore splats which include undef which is overly
663 // pessimistic.
Chandler Carruthf0a33b72014-07-09 00:41:34 +0000664 if (CN && UndefElements.none() &&
Chandler Carruthb844e722014-07-08 07:19:55 +0000665 CN->getValueType(0) == N.getValueType().getScalarType())
Chandler Carruthbeeacac2014-07-07 19:03:32 +0000666 return CN;
667 }
Matt Arsenault985b9de2014-03-17 18:58:01 +0000668
669 return nullptr;
670}
671
Andrew Trickef9de2a2013-05-25 02:42:55 +0000672SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000673 SDValue N0, SDValue N1) {
Owen Anderson53aa7a92009-08-10 22:56:29 +0000674 EVT VT = N0.getValueType();
Juergen Ributzka68402822014-01-13 21:49:25 +0000675 if (N0.getOpcode() == Opc) {
676 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
677 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
678 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
679 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
680 if (!OpNode.getNode())
681 return SDValue();
682 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
Juergen Ributzka73844052014-01-13 20:51:35 +0000683 }
Juergen Ributzka68402822014-01-13 21:49:25 +0000684 if (N0.hasOneUse()) {
685 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
686 // use
687 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
688 if (!OpNode.getNode())
689 return SDValue();
690 AddToWorkList(OpNode.getNode());
691 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
Juergen Ributzka73844052014-01-13 20:51:35 +0000692 }
693 }
Nate Begeman22e251a2006-02-03 06:46:56 +0000694 }
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000695
Juergen Ributzka68402822014-01-13 21:49:25 +0000696 if (N1.getOpcode() == Opc) {
697 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
698 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
699 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
700 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
701 if (!OpNode.getNode())
702 return SDValue();
703 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
704 }
705 if (N1.hasOneUse()) {
706 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
707 // use
708 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
709 if (!OpNode.getNode())
710 return SDValue();
711 AddToWorkList(OpNode.getNode());
712 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
713 }
Nate Begeman22e251a2006-02-03 06:46:56 +0000714 }
715 }
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000716
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000717 return SDValue();
Nate Begeman22e251a2006-02-03 06:46:56 +0000718}
719
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000720SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
721 bool AddTo) {
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000722 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
723 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +0000724 DEBUG(dbgs() << "\nReplacing.1 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000725 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000726 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000727 To[0].getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000728 dbgs() << " and " << NumTo-1 << " other values\n";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000729 for (unsigned i = 0, e = NumTo; i != e; ++i)
Jakob Stoklund Olesen32042f92009-12-03 05:15:35 +0000730 assert((!To[i].getNode() ||
731 N->getValueType(i) == To[i].getValueType()) &&
Dan Gohman7e6b9322009-01-21 15:17:51 +0000732 "Cannot combine value to value of different type!"));
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000733 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000734 DAG.ReplaceAllUsesWith(N, To);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000735 if (AddTo) {
736 // Push the new nodes and any users onto the worklist
737 for (unsigned i = 0, e = NumTo; i != e; ++i) {
Chris Lattner4147f082009-03-12 06:52:53 +0000738 if (To[i].getNode()) {
739 AddToWorkList(To[i].getNode());
740 AddUsersToWorkList(To[i].getNode());
741 }
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000742 }
743 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000744
Dan Gohmancd0b1bf2009-01-19 21:44:21 +0000745 // Finally, if the node is now dead, remove it from the graph. The node
746 // may not be dead if the replacement process recursively simplified to
747 // something else needing this node.
748 if (N->use_empty()) {
749 // Nodes can be reintroduced into the worklist. Make sure we do not
750 // process a node that has been replaced.
751 removeFromWorkList(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000752
Dan Gohmancd0b1bf2009-01-19 21:44:21 +0000753 // Finally, since the node is now dead, remove it from the graph.
754 DAG.DeleteNode(N);
755 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000756 return SDValue(N, 0);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000757}
758
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000759void DAGCombiner::
760CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
Scott Michelcf0da6c2009-02-17 22:15:04 +0000761 // Replace all uses. If any nodes become isomorphic to other nodes and
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000762 // are deleted, make sure to remove them from our worklist.
763 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000764 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
Dan Gohmane58ab792009-01-29 01:59:02 +0000765
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000766 // Push the new node and any (possibly new) users onto the worklist.
Gabor Greiff304a7a2008-08-28 21:40:38 +0000767 AddToWorkList(TLO.New.getNode());
768 AddUsersToWorkList(TLO.New.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000769
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000770 // Finally, if the node is now dead, remove it from the graph. The node
771 // may not be dead if the replacement process recursively simplified to
772 // something else needing this node.
Gabor Greiff304a7a2008-08-28 21:40:38 +0000773 if (TLO.Old.getNode()->use_empty()) {
774 removeFromWorkList(TLO.Old.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000775
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000776 // If the operands of this node are only used by the node, they will now
777 // be dead. Make sure to visit them first to delete dead nodes early.
Hal Finkel2c77fe52014-05-28 15:33:19 +0000778 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
779 if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
780 AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
781
Gabor Greiff304a7a2008-08-28 21:40:38 +0000782 DAG.DeleteNode(TLO.Old.getNode());
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000783 }
Dan Gohmane58ab792009-01-29 01:59:02 +0000784}
785
786/// SimplifyDemandedBits - Check the specified integer node value to see if
787/// it can be simplified or if things it uses can be simplified by bit
788/// propagation. If so, return true.
789bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000790 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
Dan Gohmane58ab792009-01-29 01:59:02 +0000791 APInt KnownZero, KnownOne;
792 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
793 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000794
Dan Gohmane58ab792009-01-29 01:59:02 +0000795 // Revisit the node.
796 AddToWorkList(Op.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000797
Dan Gohmane58ab792009-01-29 01:59:02 +0000798 // Replace the old value with the new one.
799 ++NodesCombined;
Wesley Peck527da1b2010-11-23 03:31:01 +0000800 DEBUG(dbgs() << "\nReplacing.2 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000801 TLO.Old.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000802 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000803 TLO.New.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000804 dbgs() << '\n');
Scott Michelcf0da6c2009-02-17 22:15:04 +0000805
Dan Gohmane58ab792009-01-29 01:59:02 +0000806 CommitTargetLoweringOpt(TLO);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000807 return true;
808}
809
Evan Cheng0abb54d2010-04-24 04:43:44 +0000810void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
Andrew Trickef9de2a2013-05-25 02:42:55 +0000811 SDLoc dl(Load);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000812 EVT VT = Load->getValueType(0);
813 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
Evan Chenge19aa5c2010-04-19 19:29:22 +0000814
Evan Cheng0abb54d2010-04-24 04:43:44 +0000815 DEBUG(dbgs() << "\nReplacing.9 ";
816 Load->dump(&DAG);
817 dbgs() << "\nWith: ";
818 Trunc.getNode()->dump(&DAG);
819 dbgs() << '\n');
820 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000821 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
822 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
Evan Cheng0abb54d2010-04-24 04:43:44 +0000823 removeFromWorkList(Load);
824 DAG.DeleteNode(Load);
Evan Chenge8136902010-04-27 19:48:13 +0000825 AddToWorkList(Trunc.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000826}
827
828SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
829 Replace = false;
Andrew Trickef9de2a2013-05-25 02:42:55 +0000830 SDLoc dl(Op);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000831 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
Evan Chenge8136902010-04-27 19:48:13 +0000832 EVT MemVT = LD->getMemoryVT();
833 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
Owen Andersonb2c80da2011-02-25 21:41:48 +0000834 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
Eric Christopherd9e8eac2010-12-09 04:48:06 +0000835 : ISD::EXTLOAD)
Evan Chenge8136902010-04-27 19:48:13 +0000836 : LD->getExtensionType();
Evan Cheng0abb54d2010-04-24 04:43:44 +0000837 Replace = true;
Stuart Hastings81c43062011-02-16 16:23:55 +0000838 return DAG.getExtLoad(ExtType, dl, PVT,
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000839 LD->getChain(), LD->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +0000840 MemVT, LD->getMemOperand());
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000841 }
842
Evan Chenge19aa5c2010-04-19 19:29:22 +0000843 unsigned Opc = Op.getOpcode();
Evan Chengb9ff1302010-04-23 19:10:30 +0000844 switch (Opc) {
845 default: break;
846 case ISD::AssertSext:
Evan Chenge19aa5c2010-04-19 19:29:22 +0000847 return DAG.getNode(ISD::AssertSext, dl, PVT,
Evan Cheng0abb54d2010-04-24 04:43:44 +0000848 SExtPromoteOperand(Op.getOperand(0), PVT),
Evan Chenge19aa5c2010-04-19 19:29:22 +0000849 Op.getOperand(1));
Evan Chengb9ff1302010-04-23 19:10:30 +0000850 case ISD::AssertZext:
Evan Chenge19aa5c2010-04-19 19:29:22 +0000851 return DAG.getNode(ISD::AssertZext, dl, PVT,
Evan Cheng0abb54d2010-04-24 04:43:44 +0000852 ZExtPromoteOperand(Op.getOperand(0), PVT),
Evan Chenge19aa5c2010-04-19 19:29:22 +0000853 Op.getOperand(1));
Evan Chengb9ff1302010-04-23 19:10:30 +0000854 case ISD::Constant: {
855 unsigned ExtOpc =
Evan Chenge19aa5c2010-04-19 19:29:22 +0000856 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
Evan Chengb9ff1302010-04-23 19:10:30 +0000857 return DAG.getNode(ExtOpc, dl, PVT, Op);
Wesley Peck527da1b2010-11-23 03:31:01 +0000858 }
Evan Chengb9ff1302010-04-23 19:10:30 +0000859 }
860
861 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000862 return SDValue();
Evan Chengb9ff1302010-04-23 19:10:30 +0000863 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
Evan Chengaf56fac2010-04-16 06:14:10 +0000864}
865
Evan Cheng0abb54d2010-04-24 04:43:44 +0000866SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000867 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
868 return SDValue();
869 EVT OldVT = Op.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +0000870 SDLoc dl(Op);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000871 bool Replace = false;
872 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
Craig Topperc0196b12014-04-14 00:51:57 +0000873 if (!NewOp.getNode())
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000874 return SDValue();
Evan Chenge8136902010-04-27 19:48:13 +0000875 AddToWorkList(NewOp.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000876
877 if (Replace)
878 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
879 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000880 DAG.getValueType(OldVT));
881}
882
Evan Cheng0abb54d2010-04-24 04:43:44 +0000883SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000884 EVT OldVT = Op.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +0000885 SDLoc dl(Op);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000886 bool Replace = false;
887 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
Craig Topperc0196b12014-04-14 00:51:57 +0000888 if (!NewOp.getNode())
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000889 return SDValue();
Evan Chenge8136902010-04-27 19:48:13 +0000890 AddToWorkList(NewOp.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000891
892 if (Replace)
893 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
894 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000895}
896
Evan Chengaf56fac2010-04-16 06:14:10 +0000897/// PromoteIntBinOp - Promote the specified integer binary operation if the
898/// target indicates it is beneficial. e.g. On x86, it's usually better to
899/// promote i16 operations to i32 since i16 instructions are longer.
900SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
901 if (!LegalOperations)
902 return SDValue();
903
904 EVT VT = Op.getValueType();
905 if (VT.isVector() || !VT.isInteger())
906 return SDValue();
907
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000908 // If operation type is 'undesirable', e.g. i16 on x86, consider
909 // promoting it.
910 unsigned Opc = Op.getOpcode();
911 if (TLI.isTypeDesirableForOp(Opc, VT))
912 return SDValue();
913
Evan Chengaf56fac2010-04-16 06:14:10 +0000914 EVT PVT = VT;
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000915 // Consult target whether it is a good idea to promote this operation and
916 // what's the right type to promote it to.
917 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
Evan Chengaf56fac2010-04-16 06:14:10 +0000918 assert(PVT != VT && "Don't know what type to promote to!");
919
Evan Cheng0abb54d2010-04-24 04:43:44 +0000920 bool Replace0 = false;
921 SDValue N0 = Op.getOperand(0);
922 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
Craig Topperc0196b12014-04-14 00:51:57 +0000923 if (!NN0.getNode())
Evan Chengf1223bd2010-04-22 20:19:46 +0000924 return SDValue();
925
Evan Cheng0abb54d2010-04-24 04:43:44 +0000926 bool Replace1 = false;
927 SDValue N1 = Op.getOperand(1);
Evan Cheng02947a42010-05-10 19:03:57 +0000928 SDValue NN1;
929 if (N0 == N1)
930 NN1 = NN0;
931 else {
932 NN1 = PromoteOperand(N1, PVT, Replace1);
Craig Topperc0196b12014-04-14 00:51:57 +0000933 if (!NN1.getNode())
Evan Cheng02947a42010-05-10 19:03:57 +0000934 return SDValue();
935 }
Evan Chengf1223bd2010-04-22 20:19:46 +0000936
Evan Cheng0abb54d2010-04-24 04:43:44 +0000937 AddToWorkList(NN0.getNode());
Evan Cheng02947a42010-05-10 19:03:57 +0000938 if (NN1.getNode())
939 AddToWorkList(NN1.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000940
941 if (Replace0)
942 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
943 if (Replace1)
944 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
Evan Chengf1223bd2010-04-22 20:19:46 +0000945
Evan Chenge8136902010-04-27 19:48:13 +0000946 DEBUG(dbgs() << "\nPromoting ";
947 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +0000948 SDLoc dl(Op);
Evan Chengf1223bd2010-04-22 20:19:46 +0000949 return DAG.getNode(ISD::TRUNCATE, dl, VT,
Evan Cheng0abb54d2010-04-24 04:43:44 +0000950 DAG.getNode(Opc, dl, PVT, NN0, NN1));
Evan Chengf1223bd2010-04-22 20:19:46 +0000951 }
952 return SDValue();
953}
954
955/// PromoteIntShiftOp - Promote the specified integer shift operation if the
956/// target indicates it is beneficial. e.g. On x86, it's usually better to
957/// promote i16 operations to i32 since i16 instructions are longer.
958SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
959 if (!LegalOperations)
960 return SDValue();
961
962 EVT VT = Op.getValueType();
963 if (VT.isVector() || !VT.isInteger())
964 return SDValue();
965
966 // If operation type is 'undesirable', e.g. i16 on x86, consider
967 // promoting it.
968 unsigned Opc = Op.getOpcode();
969 if (TLI.isTypeDesirableForOp(Opc, VT))
970 return SDValue();
971
972 EVT PVT = VT;
973 // Consult target whether it is a good idea to promote this operation and
974 // what's the right type to promote it to.
975 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
976 assert(PVT != VT && "Don't know what type to promote to!");
977
Evan Cheng0abb54d2010-04-24 04:43:44 +0000978 bool Replace = false;
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000979 SDValue N0 = Op.getOperand(0);
980 if (Opc == ISD::SRA)
Evan Cheng0abb54d2010-04-24 04:43:44 +0000981 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000982 else if (Opc == ISD::SRL)
Evan Cheng0abb54d2010-04-24 04:43:44 +0000983 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000984 else
Evan Cheng0abb54d2010-04-24 04:43:44 +0000985 N0 = PromoteOperand(N0, PVT, Replace);
Craig Topperc0196b12014-04-14 00:51:57 +0000986 if (!N0.getNode())
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000987 return SDValue();
Evan Cheng0abb54d2010-04-24 04:43:44 +0000988
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000989 AddToWorkList(N0.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000990 if (Replace)
991 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
Evan Chengaf56fac2010-04-16 06:14:10 +0000992
Evan Chenge8136902010-04-27 19:48:13 +0000993 DEBUG(dbgs() << "\nPromoting ";
994 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +0000995 SDLoc dl(Op);
Evan Chengaf56fac2010-04-16 06:14:10 +0000996 return DAG.getNode(ISD::TRUNCATE, dl, VT,
Evan Chengf1223bd2010-04-22 20:19:46 +0000997 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
Evan Chengaf56fac2010-04-16 06:14:10 +0000998 }
999 return SDValue();
1000}
1001
Evan Chenge19aa5c2010-04-19 19:29:22 +00001002SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1003 if (!LegalOperations)
1004 return SDValue();
1005
1006 EVT VT = Op.getValueType();
1007 if (VT.isVector() || !VT.isInteger())
1008 return SDValue();
1009
1010 // If operation type is 'undesirable', e.g. i16 on x86, consider
1011 // promoting it.
1012 unsigned Opc = Op.getOpcode();
1013 if (TLI.isTypeDesirableForOp(Opc, VT))
1014 return SDValue();
1015
1016 EVT PVT = VT;
1017 // Consult target whether it is a good idea to promote this operation and
1018 // what's the right type to promote it to.
1019 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1020 assert(PVT != VT && "Don't know what type to promote to!");
1021 // fold (aext (aext x)) -> (aext x)
1022 // fold (aext (zext x)) -> (zext x)
1023 // fold (aext (sext x)) -> (sext x)
Evan Chenge8136902010-04-27 19:48:13 +00001024 DEBUG(dbgs() << "\nPromoting ";
1025 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +00001026 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
Evan Chenge19aa5c2010-04-19 19:29:22 +00001027 }
1028 return SDValue();
1029}
1030
1031bool DAGCombiner::PromoteLoad(SDValue Op) {
1032 if (!LegalOperations)
1033 return false;
1034
1035 EVT VT = Op.getValueType();
1036 if (VT.isVector() || !VT.isInteger())
1037 return false;
1038
1039 // If operation type is 'undesirable', e.g. i16 on x86, consider
1040 // promoting it.
1041 unsigned Opc = Op.getOpcode();
1042 if (TLI.isTypeDesirableForOp(Opc, VT))
1043 return false;
1044
1045 EVT PVT = VT;
1046 // Consult target whether it is a good idea to promote this operation and
1047 // what's the right type to promote it to.
1048 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1049 assert(PVT != VT && "Don't know what type to promote to!");
1050
Andrew Trickef9de2a2013-05-25 02:42:55 +00001051 SDLoc dl(Op);
Evan Chenge19aa5c2010-04-19 19:29:22 +00001052 SDNode *N = Op.getNode();
1053 LoadSDNode *LD = cast<LoadSDNode>(N);
Evan Chenge8136902010-04-27 19:48:13 +00001054 EVT MemVT = LD->getMemoryVT();
1055 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
Owen Andersonb2c80da2011-02-25 21:41:48 +00001056 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
Eric Christopherd9e8eac2010-12-09 04:48:06 +00001057 : ISD::EXTLOAD)
Evan Chenge8136902010-04-27 19:48:13 +00001058 : LD->getExtensionType();
Stuart Hastings81c43062011-02-16 16:23:55 +00001059 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
Evan Chenge19aa5c2010-04-19 19:29:22 +00001060 LD->getChain(), LD->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00001061 MemVT, LD->getMemOperand());
Evan Chenge19aa5c2010-04-19 19:29:22 +00001062 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1063
Evan Cheng0abb54d2010-04-24 04:43:44 +00001064 DEBUG(dbgs() << "\nPromoting ";
Evan Chenge19aa5c2010-04-19 19:29:22 +00001065 N->dump(&DAG);
Evan Cheng0abb54d2010-04-24 04:43:44 +00001066 dbgs() << "\nTo: ";
Evan Chenge19aa5c2010-04-19 19:29:22 +00001067 Result.getNode()->dump(&DAG);
1068 dbgs() << '\n');
1069 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001070 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1071 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
Evan Chenge19aa5c2010-04-19 19:29:22 +00001072 removeFromWorkList(N);
1073 DAG.DeleteNode(N);
Evan Chenge8136902010-04-27 19:48:13 +00001074 AddToWorkList(Result.getNode());
Evan Chenge19aa5c2010-04-19 19:29:22 +00001075 return true;
1076 }
1077 return false;
1078}
1079
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001080
Chris Lattnere49c9742007-05-14 22:04:50 +00001081//===----------------------------------------------------------------------===//
1082// Main DAG Combiner implementation
1083//===----------------------------------------------------------------------===//
1084
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001085void DAGCombiner::Run(CombineLevel AtLevel) {
1086 // set the instance variables, so that the various visit routines may use it.
1087 Level = AtLevel;
Eli Friedman9d448e42011-11-12 00:35:34 +00001088 LegalOperations = Level >= AfterLegalizeVectorOps;
1089 LegalTypes = Level >= AfterLegalizeTypes;
Nate Begeman2504fe22005-09-01 23:24:04 +00001090
Evan Cheng5e7658c2008-08-29 22:21:44 +00001091 // Add all the dag nodes to the worklist.
Evan Cheng5e7658c2008-08-29 22:21:44 +00001092 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1093 E = DAG.allnodes_end(); I != E; ++I)
James Molloy67b6b112012-02-16 09:17:04 +00001094 AddToWorkList(I);
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001095
Evan Cheng5e7658c2008-08-29 22:21:44 +00001096 // Create a dummy node (which is not added to allnodes), that adds a reference
1097 // to the root node, preventing it from being deleted, and tracking any
1098 // changes of the root.
1099 HandleSDNode Dummy(DAG.getRoot());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001100
Jim Laskeye7d2c242006-10-17 19:33:52 +00001101 // The root of the dag may dangle to deleted nodes until the dag combiner is
1102 // done. Set it to null to avoid confusion.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001103 DAG.setRoot(SDValue());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001104
James Molloy67b6b112012-02-16 09:17:04 +00001105 // while the worklist isn't empty, find a node and
Evan Cheng5e7658c2008-08-29 22:21:44 +00001106 // try and combine it.
James Molloy67b6b112012-02-16 09:17:04 +00001107 while (!WorkListContents.empty()) {
1108 SDNode *N;
Jack Carterd4e96152013-10-17 01:34:33 +00001109 // The WorkListOrder holds the SDNodes in order, but it may contain
1110 // duplicates.
James Molloy67b6b112012-02-16 09:17:04 +00001111 // In order to avoid a linear scan, we use a set (O(log N)) to hold what the
1112 // worklist *should* contain, and check the node we want to visit is should
1113 // actually be visited.
1114 do {
Benjamin Kramere1e549d2012-03-10 00:23:58 +00001115 N = WorkListOrder.pop_back_val();
James Molloy67b6b112012-02-16 09:17:04 +00001116 } while (!WorkListContents.erase(N));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001117
Evan Cheng5e7658c2008-08-29 22:21:44 +00001118 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1119 // N is deleted from the DAG, since they too may now be dead or may have a
1120 // reduced number of uses, allowing other xforms.
1121 if (N->use_empty() && N != &Dummy) {
1122 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1123 AddToWorkList(N->getOperand(i).getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001124
Evan Cheng5e7658c2008-08-29 22:21:44 +00001125 DAG.DeleteNode(N);
1126 continue;
Nate Begeman21158fc2005-09-01 00:19:25 +00001127 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001128
Evan Cheng5e7658c2008-08-29 22:21:44 +00001129 SDValue RV = combine(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001130
Craig Topperc0196b12014-04-14 00:51:57 +00001131 if (!RV.getNode())
Evan Cheng5e7658c2008-08-29 22:21:44 +00001132 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001133
Evan Cheng5e7658c2008-08-29 22:21:44 +00001134 ++NodesCombined;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001135
Evan Cheng5e7658c2008-08-29 22:21:44 +00001136 // If we get back the same node we passed in, rather than a new node or
1137 // zero, we know that the node must have defined multiple values and
Scott Michelcf0da6c2009-02-17 22:15:04 +00001138 // CombineTo was used. Since CombineTo takes care of the worklist
Evan Cheng5e7658c2008-08-29 22:21:44 +00001139 // mechanics for us, we have no work to do in this case.
1140 if (RV.getNode() == N)
1141 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001142
Evan Cheng5e7658c2008-08-29 22:21:44 +00001143 assert(N->getOpcode() != ISD::DELETED_NODE &&
1144 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1145 "Node was deleted but visit returned new node!");
Chris Lattner8f872d22006-05-27 00:43:02 +00001146
Wesley Peck527da1b2010-11-23 03:31:01 +00001147 DEBUG(dbgs() << "\nReplacing.3 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00001148 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00001149 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00001150 RV.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00001151 dbgs() << '\n');
Eric Christopherd6300d22011-07-14 01:12:15 +00001152
Devang Patelefec7712011-05-23 22:04:42 +00001153 // Transfer debug value.
1154 DAG.TransferDbgValues(SDValue(N, 0), RV);
Evan Cheng5e7658c2008-08-29 22:21:44 +00001155 WorkListRemover DeadNodes(*this);
1156 if (N->getNumValues() == RV.getNode()->getNumValues())
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001157 DAG.ReplaceAllUsesWith(N, RV.getNode());
Evan Cheng5e7658c2008-08-29 22:21:44 +00001158 else {
1159 assert(N->getValueType(0) == RV.getValueType() &&
1160 N->getNumValues() == 1 && "Type mismatch");
1161 SDValue OpV = RV;
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001162 DAG.ReplaceAllUsesWith(N, &OpV);
Evan Cheng5e7658c2008-08-29 22:21:44 +00001163 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001164
Evan Cheng5e7658c2008-08-29 22:21:44 +00001165 // Push the new node and any users onto the worklist
1166 AddToWorkList(RV.getNode());
1167 AddUsersToWorkList(RV.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001168
Evan Cheng5e7658c2008-08-29 22:21:44 +00001169 // Add any uses of the old node to the worklist in case this node is the
1170 // last one that uses them. They may become dead after this node is
1171 // deleted.
1172 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1173 AddToWorkList(N->getOperand(i).getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001174
Dan Gohmancd0b1bf2009-01-19 21:44:21 +00001175 // Finally, if the node is now dead, remove it from the graph. The node
1176 // may not be dead if the replacement process recursively simplified to
1177 // something else needing this node.
1178 if (N->use_empty()) {
1179 // Nodes can be reintroduced into the worklist. Make sure we do not
1180 // process a node that has been replaced.
1181 removeFromWorkList(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001182
Dan Gohmancd0b1bf2009-01-19 21:44:21 +00001183 // Finally, since the node is now dead, remove it from the graph.
1184 DAG.DeleteNode(N);
1185 }
Evan Cheng5e7658c2008-08-29 22:21:44 +00001186 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001187
Chris Lattner06f1d0f2005-10-05 06:35:28 +00001188 // If the root changed (e.g. it was a dead load, update the root).
1189 DAG.setRoot(Dummy.getValue());
Hal Finkele0cf6392012-04-16 03:33:22 +00001190 DAG.RemoveDeadNodes();
Nate Begeman21158fc2005-09-01 00:19:25 +00001191}
1192
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001193SDValue DAGCombiner::visit(SDNode *N) {
Evan Chengf1005572010-04-28 07:10:39 +00001194 switch (N->getOpcode()) {
Nate Begeman21158fc2005-09-01 00:19:25 +00001195 default: break;
Nate Begemane8f78d12005-09-01 00:33:32 +00001196 case ISD::TokenFactor: return visitTokenFactor(N);
Chris Lattneree322b42008-02-13 07:25:05 +00001197 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001198 case ISD::ADD: return visitADD(N);
1199 case ISD::SUB: return visitSUB(N);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001200 case ISD::ADDC: return visitADDC(N);
Craig Topper43a1bd62012-01-07 09:06:39 +00001201 case ISD::SUBC: return visitSUBC(N);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001202 case ISD::ADDE: return visitADDE(N);
Craig Topper43a1bd62012-01-07 09:06:39 +00001203 case ISD::SUBE: return visitSUBE(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001204 case ISD::MUL: return visitMUL(N);
1205 case ISD::SDIV: return visitSDIV(N);
1206 case ISD::UDIV: return visitUDIV(N);
1207 case ISD::SREM: return visitSREM(N);
1208 case ISD::UREM: return visitUREM(N);
1209 case ISD::MULHU: return visitMULHU(N);
1210 case ISD::MULHS: return visitMULHS(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001211 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1212 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00001213 case ISD::SMULO: return visitSMULO(N);
1214 case ISD::UMULO: return visitUMULO(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001215 case ISD::SDIVREM: return visitSDIVREM(N);
1216 case ISD::UDIVREM: return visitUDIVREM(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001217 case ISD::AND: return visitAND(N);
1218 case ISD::OR: return visitOR(N);
1219 case ISD::XOR: return visitXOR(N);
1220 case ISD::SHL: return visitSHL(N);
1221 case ISD::SRA: return visitSRA(N);
1222 case ISD::SRL: return visitSRL(N);
Adam Nemet7f928f12014-03-07 23:56:30 +00001223 case ISD::ROTR:
1224 case ISD::ROTL: return visitRotate(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001225 case ISD::CTLZ: return visitCTLZ(N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00001226 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001227 case ISD::CTTZ: return visitCTTZ(N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00001228 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001229 case ISD::CTPOP: return visitCTPOP(N);
Nate Begeman24a7eca2005-09-16 00:54:12 +00001230 case ISD::SELECT: return visitSELECT(N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00001231 case ISD::VSELECT: return visitVSELECT(N);
Nate Begeman24a7eca2005-09-16 00:54:12 +00001232 case ISD::SELECT_CC: return visitSELECT_CC(N);
1233 case ISD::SETCC: return visitSETCC(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001234 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1235 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
Chris Lattner812646a2006-05-05 05:58:59 +00001236 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001237 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1238 case ISD::TRUNCATE: return visitTRUNCATE(N);
Wesley Peck527da1b2010-11-23 03:31:01 +00001239 case ISD::BITCAST: return visitBITCAST(N);
Evan Chengb980f6f2008-05-12 23:04:07 +00001240 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
Chris Lattner6f3b5772005-09-28 22:28:18 +00001241 case ISD::FADD: return visitFADD(N);
1242 case ISD::FSUB: return visitFSUB(N);
1243 case ISD::FMUL: return visitFMUL(N);
Owen Anderson41b06652012-05-02 22:17:40 +00001244 case ISD::FMA: return visitFMA(N);
Chris Lattner6f3b5772005-09-28 22:28:18 +00001245 case ISD::FDIV: return visitFDIV(N);
1246 case ISD::FREM: return visitFREM(N);
Chris Lattner3bc40502006-03-05 05:30:57 +00001247 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001248 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1249 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1250 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1251 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1252 case ISD::FP_ROUND: return visitFP_ROUND(N);
1253 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1254 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1255 case ISD::FNEG: return visitFNEG(N);
1256 case ISD::FABS: return visitFABS(N);
Owen Andersona40319b2012-08-13 23:32:49 +00001257 case ISD::FFLOOR: return visitFFLOOR(N);
1258 case ISD::FCEIL: return visitFCEIL(N);
1259 case ISD::FTRUNC: return visitFTRUNC(N);
Nate Begemanc760f802005-09-19 22:34:01 +00001260 case ISD::BRCOND: return visitBRCOND(N);
Nate Begemanc760f802005-09-19 22:34:01 +00001261 case ISD::BR_CC: return visitBR_CC(N);
Chris Lattnere260ed82005-10-10 22:04:48 +00001262 case ISD::LOAD: return visitLOAD(N);
Chris Lattner04c73702005-10-10 22:31:19 +00001263 case ISD::STORE: return visitSTORE(N);
Chris Lattner5336a592006-03-19 01:27:56 +00001264 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
Evan Cheng0de312d2007-10-06 08:19:55 +00001265 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
Dan Gohmana8665142007-06-25 16:23:39 +00001266 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1267 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +00001268 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
Chris Lattnera46dfe82006-03-28 22:11:53 +00001269 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
Manman Ren413a6cb2014-01-31 01:10:35 +00001270 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
Nate Begeman21158fc2005-09-01 00:19:25 +00001271 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001272 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001273}
1274
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001275SDValue DAGCombiner::combine(SDNode *N) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001276 SDValue RV = visit(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001277
1278 // If nothing happened, try a target-specific DAG combine.
Craig Topperc0196b12014-04-14 00:51:57 +00001279 if (!RV.getNode()) {
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001280 assert(N->getOpcode() != ISD::DELETED_NODE &&
1281 "Node was deleted but visit returned NULL!");
1282
1283 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1284 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1285
1286 // Expose the DAG combiner to the target combiner impls.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001287 TargetLowering::DAGCombinerInfo
Nadav Rotemb1dd5242012-12-27 06:47:41 +00001288 DagCombineInfo(DAG, Level, false, this);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001289
1290 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1291 }
1292 }
1293
Evan Chengf1005572010-04-28 07:10:39 +00001294 // If nothing happened still, try promoting the operation.
Craig Topperc0196b12014-04-14 00:51:57 +00001295 if (!RV.getNode()) {
Evan Chengf1005572010-04-28 07:10:39 +00001296 switch (N->getOpcode()) {
1297 default: break;
1298 case ISD::ADD:
1299 case ISD::SUB:
1300 case ISD::MUL:
1301 case ISD::AND:
1302 case ISD::OR:
1303 case ISD::XOR:
1304 RV = PromoteIntBinOp(SDValue(N, 0));
1305 break;
1306 case ISD::SHL:
1307 case ISD::SRA:
1308 case ISD::SRL:
1309 RV = PromoteIntShiftOp(SDValue(N, 0));
1310 break;
1311 case ISD::SIGN_EXTEND:
1312 case ISD::ZERO_EXTEND:
1313 case ISD::ANY_EXTEND:
1314 RV = PromoteExtend(SDValue(N, 0));
1315 break;
1316 case ISD::LOAD:
1317 if (PromoteLoad(SDValue(N, 0)))
1318 RV = SDValue(N, 0);
1319 break;
1320 }
1321 }
1322
Scott Michelcf0da6c2009-02-17 22:15:04 +00001323 // If N is a commutative binary node, try commuting it to enable more
Evan Cheng31604a62008-03-22 01:55:50 +00001324 // sdisel CSE.
Craig Topperc0196b12014-04-14 00:51:57 +00001325 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
Evan Cheng31604a62008-03-22 01:55:50 +00001326 N->getNumValues() == 1) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001327 SDValue N0 = N->getOperand(0);
1328 SDValue N1 = N->getOperand(1);
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001329
Evan Cheng31604a62008-03-22 01:55:50 +00001330 // Constant operands are canonicalized to RHS.
1331 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
Andrea Di Biagio4db1abe2014-06-09 12:32:53 +00001332 SDValue Ops[] = {N1, N0};
1333 SDNode *CSENode;
1334 if (const BinaryWithFlagsSDNode *BinNode =
1335 dyn_cast<BinaryWithFlagsSDNode>(N)) {
1336 CSENode = DAG.getNodeIfExists(
1337 N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1338 BinNode->hasNoSignedWrap(), BinNode->isExact());
1339 } else {
1340 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1341 }
Evan Chengfe7610f2008-03-24 23:55:16 +00001342 if (CSENode)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001343 return SDValue(CSENode, 0);
Evan Cheng31604a62008-03-22 01:55:50 +00001344 }
1345 }
1346
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001347 return RV;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001348}
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001349
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001350/// getInputChainForNode - Given a node, return its input chain if it has one,
1351/// otherwise return a null sd operand.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001352static SDValue getInputChainForNode(SDNode *N) {
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001353 if (unsigned NumOps = N->getNumOperands()) {
Owen Anderson9f944592009-08-11 20:47:22 +00001354 if (N->getOperand(0).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001355 return N->getOperand(0);
Stephen Lin8e8424e2013-07-09 00:44:49 +00001356 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001357 return N->getOperand(NumOps-1);
1358 for (unsigned i = 1; i < NumOps-1; ++i)
Owen Anderson9f944592009-08-11 20:47:22 +00001359 if (N->getOperand(i).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001360 return N->getOperand(i);
1361 }
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001362 return SDValue();
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001363}
1364
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001365SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001366 // If N has two operands, where one has an input chain equal to the other,
1367 // the 'other' chain is redundant.
1368 if (N->getNumOperands() == 2) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00001369 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001370 return N->getOperand(0);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001371 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001372 return N->getOperand(1);
1373 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001374
Chris Lattner48fb92f2007-05-16 06:37:59 +00001375 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001376 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001377 SmallPtrSet<SDNode*, 16> SeenOps;
Chris Lattner48fb92f2007-05-16 06:37:59 +00001378 bool Changed = false; // If we should replace this token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001379
Jim Laskey708d0db2006-10-04 16:53:27 +00001380 // Start out with this token factor.
Jim Laskeyd07be232006-09-25 16:29:54 +00001381 TFs.push_back(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001382
Jim Laskey0463e082006-10-07 23:37:56 +00001383 // Iterate through token factors. The TFs grows when new token factors are
Jim Laskey6549d222006-10-05 15:07:25 +00001384 // encountered.
1385 for (unsigned i = 0; i < TFs.size(); ++i) {
1386 SDNode *TF = TFs[i];
Scott Michelcf0da6c2009-02-17 22:15:04 +00001387
Jim Laskey708d0db2006-10-04 16:53:27 +00001388 // Check each of the operands.
1389 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001390 SDValue Op = TF->getOperand(i);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001391
Jim Laskey708d0db2006-10-04 16:53:27 +00001392 switch (Op.getOpcode()) {
1393 case ISD::EntryToken:
Jim Laskey6549d222006-10-05 15:07:25 +00001394 // Entry tokens don't need to be added to the list. They are
1395 // rededundant.
1396 Changed = true;
Jim Laskey708d0db2006-10-04 16:53:27 +00001397 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001398
Jim Laskey708d0db2006-10-04 16:53:27 +00001399 case ISD::TokenFactor:
Nate Begeman879d8f12009-09-15 00:18:30 +00001400 if (Op.hasOneUse() &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00001401 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
Jim Laskey708d0db2006-10-04 16:53:27 +00001402 // Queue up for processing.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001403 TFs.push_back(Op.getNode());
Jim Laskey708d0db2006-10-04 16:53:27 +00001404 // Clean up in case the token factor is removed.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001405 AddToWorkList(Op.getNode());
Jim Laskey708d0db2006-10-04 16:53:27 +00001406 Changed = true;
1407 break;
Jim Laskeyd07be232006-09-25 16:29:54 +00001408 }
Jim Laskey708d0db2006-10-04 16:53:27 +00001409 // Fall thru
Scott Michelcf0da6c2009-02-17 22:15:04 +00001410
Jim Laskey708d0db2006-10-04 16:53:27 +00001411 default:
Chris Lattner48fb92f2007-05-16 06:37:59 +00001412 // Only add if it isn't already in the list.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001413 if (SeenOps.insert(Op.getNode()))
Jim Laskey6549d222006-10-05 15:07:25 +00001414 Ops.push_back(Op);
Chris Lattner48fb92f2007-05-16 06:37:59 +00001415 else
1416 Changed = true;
Jim Laskey708d0db2006-10-04 16:53:27 +00001417 break;
Jim Laskeyd07be232006-09-25 16:29:54 +00001418 }
1419 }
Jim Laskey708d0db2006-10-04 16:53:27 +00001420 }
Wesley Peck527da1b2010-11-23 03:31:01 +00001421
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001422 SDValue Result;
Jim Laskey708d0db2006-10-04 16:53:27 +00001423
1424 // If we've change things around then replace token factor.
1425 if (Changed) {
Dan Gohman70de4cb2008-01-29 13:02:09 +00001426 if (Ops.empty()) {
Jim Laskey708d0db2006-10-04 16:53:27 +00001427 // The entry token is the only possible outcome.
1428 Result = DAG.getEntryNode();
1429 } else {
1430 // New and improved token factor.
Craig Topper48d114b2014-04-26 18:35:24 +00001431 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
Nate Begeman02b23c62005-10-13 03:11:28 +00001432 }
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001433
Jim Laskeydcf983c2006-10-13 23:32:28 +00001434 // Don't add users to work list.
1435 return CombineTo(N, Result, false);
Nate Begeman02b23c62005-10-13 03:11:28 +00001436 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001437
Jim Laskey708d0db2006-10-04 16:53:27 +00001438 return Result;
Nate Begeman21158fc2005-09-01 00:19:25 +00001439}
1440
Chris Lattneree322b42008-02-13 07:25:05 +00001441/// MERGE_VALUES can always be eliminated.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001442SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
Chris Lattneree322b42008-02-13 07:25:05 +00001443 WorkListRemover DeadNodes(*this);
Dan Gohman9d26c852009-08-10 23:43:19 +00001444 // Replacing results may cause a different MERGE_VALUES to suddenly
1445 // be CSE'd with N, and carry its uses with it. Iterate until no
1446 // uses remain, to ensure that the node can be safely deleted.
Pete Cooperfe5b84b2012-06-20 19:35:43 +00001447 // First add the users of this node to the work list so that they
1448 // can be tried again once they have new operands.
1449 AddUsersToWorkList(N);
Dan Gohman9d26c852009-08-10 23:43:19 +00001450 do {
1451 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001452 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
Dan Gohman9d26c852009-08-10 23:43:19 +00001453 } while (!N->use_empty());
Chris Lattneree322b42008-02-13 07:25:05 +00001454 removeFromWorkList(N);
1455 DAG.DeleteNode(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001456 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattneree322b42008-02-13 07:25:05 +00001457}
1458
Evan Cheng92011002007-01-19 17:51:44 +00001459static
Andrew Trickef9de2a2013-05-25 02:42:55 +00001460SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
Bill Wendlingcdd96132009-01-30 02:23:43 +00001461 SelectionDAG &DAG) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00001462 EVT VT = N0.getValueType();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001463 SDValue N00 = N0.getOperand(0);
1464 SDValue N01 = N0.getOperand(1);
Evan Cheng92011002007-01-19 17:51:44 +00001465 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
Bill Wendlingcdd96132009-01-30 02:23:43 +00001466
Gabor Greiff304a7a2008-08-28 21:40:38 +00001467 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
Evan Cheng92011002007-01-19 17:51:44 +00001468 isa<ConstantSDNode>(N00.getOperand(1))) {
Bill Wendlingcdd96132009-01-30 02:23:43 +00001469 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
Andrew Trickef9de2a2013-05-25 02:42:55 +00001470 N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1471 DAG.getNode(ISD::SHL, SDLoc(N00), VT,
Bill Wendlingcdd96132009-01-30 02:23:43 +00001472 N00.getOperand(0), N01),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001473 DAG.getNode(ISD::SHL, SDLoc(N01), VT,
Bill Wendlingcdd96132009-01-30 02:23:43 +00001474 N00.getOperand(1), N01));
1475 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
Evan Cheng92011002007-01-19 17:51:44 +00001476 }
Bill Wendlingcdd96132009-01-30 02:23:43 +00001477
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001478 return SDValue();
Evan Cheng92011002007-01-19 17:51:44 +00001479}
1480
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001481SDValue DAGCombiner::visitADD(SDNode *N) {
1482 SDValue N0 = N->getOperand(0);
1483 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001484 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1485 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001486 EVT VT = N0.getValueType();
Dan Gohmana8665142007-06-25 16:23:39 +00001487
1488 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00001489 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001490 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001491 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topperd8005db2012-12-10 08:12:29 +00001492
1493 // fold (add x, 0) -> x, vector edition
1494 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1495 return N0;
1496 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1497 return N1;
Dan Gohman80f9f072007-07-13 20:03:40 +00001498 }
Bill Wendling0864a752008-12-10 22:36:00 +00001499
Dan Gohman06563a82007-07-03 14:03:57 +00001500 // fold (add x, undef) -> undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00001501 if (N0.getOpcode() == ISD::UNDEF)
1502 return N0;
1503 if (N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00001504 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00001505 // fold (add c1, c2) -> c1+c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001506 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00001507 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00001508 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00001509 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001510 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001511 // fold (add x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001512 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00001513 return N0;
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001514 // fold (add Sym, c) -> Sym+c
1515 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001516 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001517 GA->getOpcode() == ISD::GlobalAddress)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001518 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001519 GA->getOffset() +
1520 (uint64_t)N1C->getSExtValue());
Chris Lattner3470b5d2006-01-12 20:22:43 +00001521 // fold ((c1-A)+c2) -> (c1+c2)-A
1522 if (N1C && N0.getOpcode() == ISD::SUB)
1523 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001524 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Dan Gohmanb72127a2008-03-13 22:13:53 +00001525 DAG.getConstant(N1C->getAPIntValue()+
1526 N0C->getAPIntValue(), VT),
Chris Lattner3470b5d2006-01-12 20:22:43 +00001527 N0.getOperand(1));
Nate Begeman22e251a2006-02-03 06:46:56 +00001528 // reassociate add
Andrew Trickef9de2a2013-05-25 02:42:55 +00001529 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00001530 if (RADD.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00001531 return RADD;
Nate Begeman21158fc2005-09-01 00:19:25 +00001532 // fold ((0-A) + B) -> B-A
1533 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1534 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001535 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
Nate Begeman21158fc2005-09-01 00:19:25 +00001536 // fold (A + (0-B)) -> A-B
1537 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1538 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001539 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
Chris Lattner6f3b5772005-09-28 22:28:18 +00001540 // fold (A+(B-A)) -> B
1541 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
Nate Begemand23739d2005-09-06 04:43:02 +00001542 return N1.getOperand(0);
Dale Johannesen73bc0ba2008-11-27 00:43:21 +00001543 // fold ((B-A)+A) -> B
1544 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1545 return N0.getOperand(0);
Dale Johannesen8c766702008-12-02 01:30:54 +00001546 // fold (A+(B-(A+C))) to (B-C)
1547 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001548 N0 == N1.getOperand(1).getOperand(0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001549 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
Dale Johannesen8c766702008-12-02 01:30:54 +00001550 N1.getOperand(1).getOperand(1));
Dale Johannesen8c766702008-12-02 01:30:54 +00001551 // fold (A+(B-(C+A))) to (B-C)
1552 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001553 N0 == N1.getOperand(1).getOperand(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001554 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
Dale Johannesen8c766702008-12-02 01:30:54 +00001555 N1.getOperand(1).getOperand(0));
Dale Johannesenee573fc2008-12-23 23:47:22 +00001556 // fold (A+((B-A)+or-C)) to (B+or-C)
Dale Johannesen54bdec22008-12-02 18:40:40 +00001557 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1558 N1.getOperand(0).getOpcode() == ISD::SUB &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001559 N0 == N1.getOperand(0).getOperand(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001560 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
Bill Wendlingc4423482009-01-30 02:31:17 +00001561 N1.getOperand(0).getOperand(0), N1.getOperand(1));
Dale Johannesen54bdec22008-12-02 18:40:40 +00001562
Dale Johannesen8c766702008-12-02 01:30:54 +00001563 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1564 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1565 SDValue N00 = N0.getOperand(0);
1566 SDValue N01 = N0.getOperand(1);
1567 SDValue N10 = N1.getOperand(0);
1568 SDValue N11 = N1.getOperand(1);
Bill Wendlingc4423482009-01-30 02:31:17 +00001569
1570 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001571 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1572 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1573 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
Dale Johannesen8c766702008-12-02 01:30:54 +00001574 }
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001575
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001576 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1577 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001578
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001579 // fold (a+b) -> (a|b) iff a and b share no bits.
Duncan Sands13237ac2008-06-06 12:08:01 +00001580 if (VT.isInteger() && !VT.isVector()) {
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001581 APInt LHSZero, LHSOne;
1582 APInt RHSZero, RHSOne;
Jay Foada0653a32014-05-14 21:14:37 +00001583 DAG.computeKnownBits(N0, LHSZero, LHSOne);
Bill Wendlingc4423482009-01-30 02:31:17 +00001584
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001585 if (LHSZero.getBoolValue()) {
Jay Foada0653a32014-05-14 21:14:37 +00001586 DAG.computeKnownBits(N1, RHSZero, RHSOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001587
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001588 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1589 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
Owen Anderson60a46782014-01-31 00:51:43 +00001590 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1591 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1592 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1593 }
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001594 }
1595 }
Evan Chengeb99bd72006-11-06 08:14:30 +00001596
Evan Cheng92011002007-01-19 17:51:44 +00001597 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
Gabor Greiff304a7a2008-08-28 21:40:38 +00001598 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001599 SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001600 if (Result.getNode()) return Result;
Evan Cheng92011002007-01-19 17:51:44 +00001601 }
Gabor Greiff304a7a2008-08-28 21:40:38 +00001602 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001603 SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001604 if (Result.getNode()) return Result;
Evan Cheng92011002007-01-19 17:51:44 +00001605 }
1606
Dan Gohman954f4902010-01-19 23:30:49 +00001607 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1608 if (N1.getOpcode() == ISD::SHL &&
1609 N1.getOperand(0).getOpcode() == ISD::SUB)
1610 if (ConstantSDNode *C =
1611 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1612 if (C->getAPIntValue() == 0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001613 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1614 DAG.getNode(ISD::SHL, SDLoc(N), VT,
Dan Gohman954f4902010-01-19 23:30:49 +00001615 N1.getOperand(0).getOperand(1),
1616 N1.getOperand(1)));
1617 if (N0.getOpcode() == ISD::SHL &&
1618 N0.getOperand(0).getOpcode() == ISD::SUB)
1619 if (ConstantSDNode *C =
1620 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1621 if (C->getAPIntValue() == 0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001622 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1623 DAG.getNode(ISD::SHL, SDLoc(N), VT,
Dan Gohman954f4902010-01-19 23:30:49 +00001624 N0.getOperand(0).getOperand(1),
1625 N0.getOperand(1)));
1626
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001627 if (N1.getOpcode() == ISD::AND) {
1628 SDValue AndOp0 = N1.getOperand(0);
Wesley Peck527da1b2010-11-23 03:31:01 +00001629 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001630 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1631 unsigned DestBits = VT.getScalarType().getSizeInBits();
Wesley Peck527da1b2010-11-23 03:31:01 +00001632
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001633 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1634 // and similar xforms where the inner op is either ~0 or 0.
1635 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001636 SDLoc DL(N);
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001637 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1638 }
1639 }
1640
Benjamin Kramer1f4dfbb2010-12-22 23:17:45 +00001641 // add (sext i1), X -> sub X, (zext i1)
1642 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1643 N0.getOperand(0).getValueType() == MVT::i1 &&
1644 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001645 SDLoc DL(N);
Benjamin Kramer1f4dfbb2010-12-22 23:17:45 +00001646 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1647 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1648 }
1649
Evan Chengf1005572010-04-28 07:10:39 +00001650 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001651}
1652
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001653SDValue DAGCombiner::visitADDC(SDNode *N) {
1654 SDValue N0 = N->getOperand(0);
1655 SDValue N1 = N->getOperand(1);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001656 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1657 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001658 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001659
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001660 // If the flag result is dead, turn this into an ADD.
Craig Topper0515cd42012-01-07 18:31:09 +00001661 if (!N->hasAnyUseOfValue(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001662 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
Dale Johannesen5234d372009-06-02 03:12:52 +00001663 DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001664 SDLoc(N), MVT::Glue));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001665
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001666 // canonicalize constant to RHS.
Dan Gohmanb4e26372008-06-23 15:29:14 +00001667 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001668 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001669
Chris Lattner47206662007-03-04 20:40:38 +00001670 // fold (addc x, 0) -> x + no carry out
1671 if (N1C && N1C->isNullValue())
Dale Johannesen5234d372009-06-02 03:12:52 +00001672 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001673 SDLoc(N), MVT::Glue));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001674
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001675 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001676 APInt LHSZero, LHSOne;
1677 APInt RHSZero, RHSOne;
Jay Foada0653a32014-05-14 21:14:37 +00001678 DAG.computeKnownBits(N0, LHSZero, LHSOne);
Bill Wendling61277572009-01-30 02:38:00 +00001679
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001680 if (LHSZero.getBoolValue()) {
Jay Foada0653a32014-05-14 21:14:37 +00001681 DAG.computeKnownBits(N1, RHSZero, RHSOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001682
Chris Lattner47206662007-03-04 20:40:38 +00001683 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1684 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001685 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001686 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
Dale Johannesen5234d372009-06-02 03:12:52 +00001687 DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001688 SDLoc(N), MVT::Glue));
Chris Lattner47206662007-03-04 20:40:38 +00001689 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001690
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001691 return SDValue();
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001692}
1693
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001694SDValue DAGCombiner::visitADDE(SDNode *N) {
1695 SDValue N0 = N->getOperand(0);
1696 SDValue N1 = N->getOperand(1);
1697 SDValue CarryIn = N->getOperand(2);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001698 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1699 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001700
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001701 // canonicalize constant to RHS
Dan Gohmanb4e26372008-06-23 15:29:14 +00001702 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001703 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
Bill Wendling61277572009-01-30 02:38:00 +00001704 N1, N0, CarryIn);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001705
Chris Lattner47206662007-03-04 20:40:38 +00001706 // fold (adde x, y, false) -> (addc x, y)
Dale Johannesen5234d372009-06-02 03:12:52 +00001707 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001708 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001709
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001710 return SDValue();
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001711}
1712
Eric Christophere5ca1e02011-02-16 04:50:12 +00001713// Since it may not be valid to emit a fold to zero for vector initializers
1714// check if we can before folding.
Andrew Trickef9de2a2013-05-25 02:42:55 +00001715static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
Hal Finkel6c29bd92013-07-09 17:02:45 +00001716 SelectionDAG &DAG,
1717 bool LegalOperations, bool LegalTypes) {
Stephen Lin8e8424e2013-07-09 00:44:49 +00001718 if (!VT.isVector())
Eric Christophere5ca1e02011-02-16 04:50:12 +00001719 return DAG.getConstant(0, VT);
Daniel Sandersb021c6f2013-11-25 11:14:43 +00001720 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1721 return DAG.getConstant(0, VT);
Eric Christophere5ca1e02011-02-16 04:50:12 +00001722 return SDValue();
1723}
1724
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001725SDValue DAGCombiner::visitSUB(SDNode *N) {
1726 SDValue N0 = N->getOperand(0);
1727 SDValue N1 = N->getOperand(1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001728 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1729 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
Craig Topperc0196b12014-04-14 00:51:57 +00001730 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
Eric Christopherd6300d22011-07-14 01:12:15 +00001731 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
Owen Anderson53aa7a92009-08-10 22:56:29 +00001732 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001733
Dan Gohmana8665142007-06-25 16:23:39 +00001734 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00001735 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001736 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001737 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topperd8005db2012-12-10 08:12:29 +00001738
1739 // fold (sub x, 0) -> x, vector edition
1740 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1741 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00001742 }
Bill Wendling0864a752008-12-10 22:36:00 +00001743
Chris Lattnereeb2bda2005-10-17 01:07:11 +00001744 // fold (sub x, x) -> 0
Eric Christopheref721412011-02-16 01:10:03 +00001745 // FIXME: Refactor this and xor and other similar operations together.
Eric Christophere5ca1e02011-02-16 04:50:12 +00001746 if (N0 == N1)
Hal Finkel6c29bd92013-07-09 17:02:45 +00001747 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
Nate Begeman21158fc2005-09-01 00:19:25 +00001748 // fold (sub c1, c2) -> c1-c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001749 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00001750 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
Chris Lattnerc38fb8e2005-10-11 06:07:15 +00001751 // fold (sub x, c) -> (add x, -c)
1752 if (N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001753 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
Dan Gohmanb72127a2008-03-13 22:13:53 +00001754 DAG.getConstant(-N1C->getAPIntValue(), VT));
Evan Cheng88b65bc2010-01-18 21:38:44 +00001755 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1756 if (N0C && N0C->isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001757 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
Benjamin Kramer65bb14d2011-01-29 12:34:05 +00001758 // fold A-(A-B) -> B
1759 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1760 return N1.getOperand(1);
Nate Begeman21158fc2005-09-01 00:19:25 +00001761 // fold (A+B)-A -> B
Chris Lattner6f3b5772005-09-28 22:28:18 +00001762 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
Nate Begemand23739d2005-09-06 04:43:02 +00001763 return N0.getOperand(1);
Nate Begeman21158fc2005-09-01 00:19:25 +00001764 // fold (A+B)-B -> A
Chris Lattner6f3b5772005-09-28 22:28:18 +00001765 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
Scott Michelcf0da6c2009-02-17 22:15:04 +00001766 return N0.getOperand(0);
Eric Christopherd6300d22011-07-14 01:12:15 +00001767 // fold C2-(A+C1) -> (C2-C1)-A
1768 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
Nadav Rotem841c9a82012-09-20 08:53:31 +00001769 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1770 VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00001771 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
Bill Wendlingd1634052012-07-19 00:04:14 +00001772 N1.getOperand(0));
Eric Christopherd6300d22011-07-14 01:12:15 +00001773 }
Dale Johannesenee573fc2008-12-23 23:47:22 +00001774 // fold ((A+(B+or-C))-B) -> A+or-C
Dale Johannesenf51dcef2008-12-16 22:13:49 +00001775 if (N0.getOpcode() == ISD::ADD &&
Dale Johannesenacc84e52008-12-23 23:01:27 +00001776 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1777 N0.getOperand(1).getOpcode() == ISD::ADD) &&
Dale Johannesenf51dcef2008-12-16 22:13:49 +00001778 N0.getOperand(1).getOperand(0) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001779 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001780 N0.getOperand(0), N0.getOperand(1).getOperand(1));
Dale Johannesenacc84e52008-12-23 23:01:27 +00001781 // fold ((A+(C+B))-B) -> A+C
1782 if (N0.getOpcode() == ISD::ADD &&
1783 N0.getOperand(1).getOpcode() == ISD::ADD &&
1784 N0.getOperand(1).getOperand(1) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001785 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001786 N0.getOperand(0), N0.getOperand(1).getOperand(0));
Dale Johannesend2a46852008-12-23 01:59:54 +00001787 // fold ((A-(B-C))-C) -> A-B
1788 if (N0.getOpcode() == ISD::SUB &&
1789 N0.getOperand(1).getOpcode() == ISD::SUB &&
1790 N0.getOperand(1).getOperand(1) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001791 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001792 N0.getOperand(0), N0.getOperand(1).getOperand(0));
Bill Wendling48ff08e2009-01-30 02:42:10 +00001793
Dan Gohman06563a82007-07-03 14:03:57 +00001794 // If either operand of a sub is undef, the result is undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00001795 if (N0.getOpcode() == ISD::UNDEF)
1796 return N0;
1797 if (N1.getOpcode() == ISD::UNDEF)
1798 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00001799
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001800 // If the relocation model supports it, consider symbol offsets.
1801 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001802 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001803 // fold (sub Sym, c) -> Sym-c
1804 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001805 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001806 GA->getOffset() -
1807 (uint64_t)N1C->getSExtValue());
1808 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1809 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1810 if (GA->getGlobal() == GB->getGlobal())
1811 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1812 VT);
1813 }
1814
Evan Chengf1005572010-04-28 07:10:39 +00001815 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001816}
1817
Craig Topper43a1bd62012-01-07 09:06:39 +00001818SDValue DAGCombiner::visitSUBC(SDNode *N) {
1819 SDValue N0 = N->getOperand(0);
1820 SDValue N1 = N->getOperand(1);
1821 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1822 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1823 EVT VT = N0.getValueType();
1824
1825 // If the flag result is dead, turn this into an SUB.
Craig Topper0515cd42012-01-07 18:31:09 +00001826 if (!N->hasAnyUseOfValue(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001827 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1828 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001829 MVT::Glue));
1830
1831 // fold (subc x, x) -> 0 + no borrow
1832 if (N0 == N1)
1833 return CombineTo(N, DAG.getConstant(0, VT),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001834 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001835 MVT::Glue));
1836
1837 // fold (subc x, 0) -> x + no borrow
1838 if (N1C && N1C->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001839 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001840 MVT::Glue));
1841
1842 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1843 if (N0C && N0C->isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001844 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1845 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001846 MVT::Glue));
1847
1848 return SDValue();
1849}
1850
1851SDValue DAGCombiner::visitSUBE(SDNode *N) {
1852 SDValue N0 = N->getOperand(0);
1853 SDValue N1 = N->getOperand(1);
1854 SDValue CarryIn = N->getOperand(2);
1855
1856 // fold (sube x, y, false) -> (subc x, y)
1857 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001858 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
Craig Topper43a1bd62012-01-07 09:06:39 +00001859
1860 return SDValue();
1861}
1862
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001863SDValue DAGCombiner::visitMUL(SDNode *N) {
1864 SDValue N0 = N->getOperand(0);
1865 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001866 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001867
Dan Gohman06563a82007-07-03 14:03:57 +00001868 // fold (mul x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00001869 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00001870 return DAG.getConstant(0, VT);
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001871
1872 bool N0IsConst = false;
1873 bool N1IsConst = false;
1874 APInt ConstValue0, ConstValue1;
1875 // fold vector ops
1876 if (VT.isVector()) {
1877 SDValue FoldedVOp = SimplifyVBinOp(N);
1878 if (FoldedVOp.getNode()) return FoldedVOp;
1879
1880 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1881 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1882 } else {
Craig Topperc0196b12014-04-14 00:51:57 +00001883 N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
Jack Carterd4e96152013-10-17 01:34:33 +00001884 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1885 : APInt();
Craig Topperc0196b12014-04-14 00:51:57 +00001886 N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
Jack Carterd4e96152013-10-17 01:34:33 +00001887 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1888 : APInt();
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001889 }
1890
Nate Begeman21158fc2005-09-01 00:19:25 +00001891 // fold (mul c1, c2) -> c1*c2
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001892 if (N0IsConst && N1IsConst)
1893 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1894
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00001895 // canonicalize constant to RHS
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001896 if (N0IsConst && !N1IsConst)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001897 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001898 // fold (mul x, 0) -> 0
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001899 if (N1IsConst && ConstValue1 == 0)
Nate Begemand23739d2005-09-06 04:43:02 +00001900 return N1;
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001901 // We require a splat of the entire scalar bit width for non-contiguous
1902 // bit patterns.
1903 bool IsFullSplat =
1904 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001905 // fold (mul x, 1) -> x
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001906 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001907 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00001908 // fold (mul x, -1) -> 0-x
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001909 if (N1IsConst && ConstValue1.isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001910 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001911 DAG.getConstant(0, VT), N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001912 // fold (mul x, (1 << c)) -> x << c
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001913 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001914 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001915 DAG.getConstant(ConstValue1.logBase2(),
Owen Andersonb2c80da2011-02-25 21:41:48 +00001916 getShiftAmountTy(N0.getValueType())));
Chris Lattnera70878d2005-10-30 06:41:49 +00001917 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001918 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001919 unsigned Log2Val = (-ConstValue1).logBase2();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001920 // FIXME: If the input is something that is easily negated (e.g. a
Chris Lattnera70878d2005-10-30 06:41:49 +00001921 // single-use add), we should put the negate there.
Andrew Trickef9de2a2013-05-25 02:42:55 +00001922 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001923 DAG.getConstant(0, VT),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001924 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
Owen Andersonb2c80da2011-02-25 21:41:48 +00001925 DAG.getConstant(Log2Val,
1926 getShiftAmountTy(N0.getValueType()))));
Chris Lattner4249b9a2009-03-09 20:22:18 +00001927 }
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001928
1929 APInt Val;
Chris Lattner324871e2006-03-01 03:44:24 +00001930 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
Stephen Lincfe7f352013-07-08 00:37:03 +00001931 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001932 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1933 isa<ConstantSDNode>(N0.getOperand(1)))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001934 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001935 N1, N0.getOperand(1));
Gabor Greiff304a7a2008-08-28 21:40:38 +00001936 AddToWorkList(C3.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00001937 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001938 N0.getOperand(0), C3);
Chris Lattner324871e2006-03-01 03:44:24 +00001939 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001940
Chris Lattner324871e2006-03-01 03:44:24 +00001941 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1942 // use.
1943 {
Craig Topperc0196b12014-04-14 00:51:57 +00001944 SDValue Sh(nullptr,0), Y(nullptr,0);
Chris Lattner324871e2006-03-01 03:44:24 +00001945 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
Stephen Lincfe7f352013-07-08 00:37:03 +00001946 if (N0.getOpcode() == ISD::SHL &&
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001947 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1948 isa<ConstantSDNode>(N0.getOperand(1))) &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00001949 N0.getNode()->hasOneUse()) {
Chris Lattner324871e2006-03-01 03:44:24 +00001950 Sh = N0; Y = N1;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001951 } else if (N1.getOpcode() == ISD::SHL &&
Gabor Greife12264b2008-08-30 19:29:20 +00001952 isa<ConstantSDNode>(N1.getOperand(1)) &&
1953 N1.getNode()->hasOneUse()) {
Chris Lattner324871e2006-03-01 03:44:24 +00001954 Sh = N1; Y = N0;
1955 }
Bill Wendlingb48dcf62009-01-30 02:49:26 +00001956
Gabor Greiff304a7a2008-08-28 21:40:38 +00001957 if (Sh.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001958 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001959 Sh.getOperand(0), Y);
Andrew Trickef9de2a2013-05-25 02:42:55 +00001960 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001961 Mul, Sh.getOperand(1));
Chris Lattner324871e2006-03-01 03:44:24 +00001962 }
1963 }
Bill Wendlingb48dcf62009-01-30 02:49:26 +00001964
Chris Lattnerf29f5202006-03-04 23:33:26 +00001965 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001966 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1967 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1968 isa<ConstantSDNode>(N0.getOperand(1))))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001969 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1970 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001971 N0.getOperand(0), N1),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001972 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001973 N0.getOperand(1), N1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001974
Nate Begeman22e251a2006-02-03 06:46:56 +00001975 // reassociate mul
Andrew Trickef9de2a2013-05-25 02:42:55 +00001976 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00001977 if (RMUL.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00001978 return RMUL;
Dan Gohmana8665142007-06-25 16:23:39 +00001979
Evan Chengf1005572010-04-28 07:10:39 +00001980 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001981}
1982
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001983SDValue DAGCombiner::visitSDIV(SDNode *N) {
1984 SDValue N0 = N->getOperand(0);
1985 SDValue N1 = N->getOperand(1);
Benjamin Kramerda4841b2014-04-26 23:09:49 +00001986 ConstantSDNode *N0C = isConstOrConstSplat(N0);
1987 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001988 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001989
Dan Gohmana8665142007-06-25 16:23:39 +00001990 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00001991 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001992 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001993 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00001994 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001995
Nate Begeman21158fc2005-09-01 00:19:25 +00001996 // fold (sdiv c1, c2) -> c1/c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001997 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00001998 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
Nate Begeman4dd38312005-10-21 00:02:42 +00001999 // fold (sdiv X, 1) -> X
Eli Friedmane9e356a2011-10-27 02:06:39 +00002000 if (N1C && N1C->getAPIntValue() == 1LL)
Nate Begeman4dd38312005-10-21 00:02:42 +00002001 return N0;
2002 // fold (sdiv X, -1) -> 0-X
2003 if (N1C && N1C->isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00002004 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling5b663e72009-01-30 02:52:17 +00002005 DAG.getConstant(0, VT), N0);
Chris Lattner5bcd0dd82005-10-07 06:10:46 +00002006 // If we know the sign bits of both operands are zero, strength reduce to a
2007 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
Duncan Sands13237ac2008-06-06 12:08:01 +00002008 if (!VT.isVector()) {
Dan Gohman1f372ed2008-02-25 21:11:39 +00002009 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002010 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
Bill Wendling5b663e72009-01-30 02:52:17 +00002011 N0, N1);
Chris Lattner2ee91f42008-01-27 23:32:17 +00002012 }
Benjamin Kramerad016872014-04-26 13:00:53 +00002013
Nate Begeman57b35672006-02-17 07:26:20 +00002014 // fold (sdiv X, pow2) -> simple ops after legalize
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002015 if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2016 (-N1C->getAPIntValue()).isPowerOf2())) {
Nate Begeman4dd38312005-10-21 00:02:42 +00002017 // If dividing by powers of two is cheap, then don't perform the following
2018 // fold.
2019 if (TLI.isPow2DivCheap())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002020 return SDValue();
Bill Wendling5b663e72009-01-30 02:52:17 +00002021
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002022 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
Bill Wendling5b663e72009-01-30 02:52:17 +00002023
Chris Lattner471627c2006-02-16 08:02:36 +00002024 // Splat the sign bit into the register
Benjamin Kramerad016872014-04-26 13:00:53 +00002025 SDValue SGN =
2026 DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2027 DAG.getConstant(VT.getScalarSizeInBits() - 1,
2028 getShiftAmountTy(N0.getValueType())));
Gabor Greiff304a7a2008-08-28 21:40:38 +00002029 AddToWorkList(SGN.getNode());
Bill Wendling5b663e72009-01-30 02:52:17 +00002030
Chris Lattner471627c2006-02-16 08:02:36 +00002031 // Add (N0 < 0) ? abs2 - 1 : 0;
Benjamin Kramerad016872014-04-26 13:00:53 +00002032 SDValue SRL =
2033 DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2034 DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2035 getShiftAmountTy(SGN.getValueType())));
Andrew Trickef9de2a2013-05-25 02:42:55 +00002036 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002037 AddToWorkList(SRL.getNode());
2038 AddToWorkList(ADD.getNode()); // Divide by pow2
Andrew Trickef9de2a2013-05-25 02:42:55 +00002039 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002040 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
Bill Wendling5b663e72009-01-30 02:52:17 +00002041
Nate Begeman4dd38312005-10-21 00:02:42 +00002042 // If we're dividing by a positive value, we're done. Otherwise, we must
2043 // negate the result.
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002044 if (N1C->getAPIntValue().isNonNegative())
Nate Begeman4dd38312005-10-21 00:02:42 +00002045 return SRA;
Bill Wendling5b663e72009-01-30 02:52:17 +00002046
Gabor Greiff304a7a2008-08-28 21:40:38 +00002047 AddToWorkList(SRA.getNode());
Benjamin Kramerad016872014-04-26 13:00:53 +00002048 return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
Nate Begeman4dd38312005-10-21 00:02:42 +00002049 }
Bill Wendling5b663e72009-01-30 02:52:17 +00002050
Nate Begemanc6f067a2005-10-20 02:15:44 +00002051 // if integer divide is expensive and we satisfy the requirements, emit an
2052 // alternate sequence.
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002053 if (N1C && !TLI.isIntDivCheap()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002054 SDValue Op = BuildSDIV(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002055 if (Op.getNode()) return Op;
Nate Begemanc6f067a2005-10-20 02:15:44 +00002056 }
Dan Gohmana8665142007-06-25 16:23:39 +00002057
Dan Gohman06563a82007-07-03 14:03:57 +00002058 // undef / X -> 0
2059 if (N0.getOpcode() == ISD::UNDEF)
2060 return DAG.getConstant(0, VT);
2061 // X / undef -> undef
2062 if (N1.getOpcode() == ISD::UNDEF)
2063 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002064
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002065 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002066}
2067
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002068SDValue DAGCombiner::visitUDIV(SDNode *N) {
2069 SDValue N0 = N->getOperand(0);
2070 SDValue N1 = N->getOperand(1);
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002071 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2072 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002073 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002074
Dan Gohmana8665142007-06-25 16:23:39 +00002075 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00002076 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002077 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002078 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00002079 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002080
Nate Begeman21158fc2005-09-01 00:19:25 +00002081 // fold (udiv c1, c2) -> c1/c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002082 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002083 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00002084 // fold (udiv x, (1 << c)) -> x >>u c
Dan Gohmanb72127a2008-03-13 22:13:53 +00002085 if (N1C && N1C->getAPIntValue().isPowerOf2())
Andrew Trickef9de2a2013-05-25 02:42:55 +00002086 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
Dan Gohmanb72127a2008-03-13 22:13:53 +00002087 DAG.getConstant(N1C->getAPIntValue().logBase2(),
Owen Andersonb2c80da2011-02-25 21:41:48 +00002088 getShiftAmountTy(N0.getValueType())));
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002089 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
Nate Begeman25d178b2006-02-05 07:20:23 +00002090 if (N1.getOpcode() == ISD::SHL) {
2091 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
Dan Gohmanb72127a2008-03-13 22:13:53 +00002092 if (SHC->getAPIntValue().isPowerOf2()) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00002093 EVT ADDVT = N1.getOperand(1).getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00002094 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
Bill Wendlingaff3e032009-01-30 02:55:25 +00002095 N1.getOperand(1),
2096 DAG.getConstant(SHC->getAPIntValue()
2097 .logBase2(),
2098 ADDVT));
Gabor Greiff304a7a2008-08-28 21:40:38 +00002099 AddToWorkList(Add.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002100 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
Nate Begeman25d178b2006-02-05 07:20:23 +00002101 }
2102 }
2103 }
Nate Begemanc6f067a2005-10-20 02:15:44 +00002104 // fold (udiv x, c) -> alternate
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002105 if (N1C && !TLI.isIntDivCheap()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002106 SDValue Op = BuildUDIV(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002107 if (Op.getNode()) return Op;
Chris Lattner9faa5b72005-10-22 18:50:15 +00002108 }
Dan Gohmana8665142007-06-25 16:23:39 +00002109
Dan Gohman06563a82007-07-03 14:03:57 +00002110 // undef / X -> 0
2111 if (N0.getOpcode() == ISD::UNDEF)
2112 return DAG.getConstant(0, VT);
2113 // X / undef -> undef
2114 if (N1.getOpcode() == ISD::UNDEF)
2115 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002116
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002117 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002118}
2119
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002120SDValue DAGCombiner::visitSREM(SDNode *N) {
2121 SDValue N0 = N->getOperand(0);
2122 SDValue N1 = N->getOperand(1);
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002123 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2124 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002125 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002126
Nate Begeman21158fc2005-09-01 00:19:25 +00002127 // fold (srem c1, c2) -> c1%c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002128 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002129 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
Nate Begeman6828ed92005-10-10 21:26:48 +00002130 // If we know the sign bits of both operands are zero, strength reduce to a
2131 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
Duncan Sands13237ac2008-06-06 12:08:01 +00002132 if (!VT.isVector()) {
Dan Gohman1f372ed2008-02-25 21:11:39 +00002133 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002134 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
Chris Lattnerd0496d02008-01-27 23:21:58 +00002135 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002136
Dan Gohman9a693412007-11-26 23:46:11 +00002137 // If X/C can be simplified by the division-by-constant logic, lower
2138 // X%C to the equivalent of X-X/C*C.
Chris Lattnerd0620d22006-10-12 20:58:32 +00002139 if (N1C && !N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002140 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002141 AddToWorkList(Div.getNode());
2142 SDValue OptimizedDiv = combine(Div.getNode());
2143 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002144 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendlingd033af02009-01-30 02:57:00 +00002145 OptimizedDiv, N1);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002146 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002147 AddToWorkList(Mul.getNode());
Dan Gohman9a693412007-11-26 23:46:11 +00002148 return Sub;
2149 }
Chris Lattnerd0620d22006-10-12 20:58:32 +00002150 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002151
Dan Gohman06563a82007-07-03 14:03:57 +00002152 // undef % X -> 0
2153 if (N0.getOpcode() == ISD::UNDEF)
2154 return DAG.getConstant(0, VT);
2155 // X % undef -> undef
2156 if (N1.getOpcode() == ISD::UNDEF)
2157 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002158
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002159 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002160}
2161
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002162SDValue DAGCombiner::visitUREM(SDNode *N) {
2163 SDValue N0 = N->getOperand(0);
2164 SDValue N1 = N->getOperand(1);
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002165 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2166 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002167 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002168
Nate Begeman21158fc2005-09-01 00:19:25 +00002169 // fold (urem c1, c2) -> c1%c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002170 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002171 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
Nate Begeman6828ed92005-10-10 21:26:48 +00002172 // fold (urem x, pow2) -> (and x, pow2-1)
Dan Gohmanb72127a2008-03-13 22:13:53 +00002173 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
Andrew Trickef9de2a2013-05-25 02:42:55 +00002174 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
Dan Gohmanb72127a2008-03-13 22:13:53 +00002175 DAG.getConstant(N1C->getAPIntValue()-1,VT));
Nate Begemanc89fdf12006-02-05 07:36:48 +00002176 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2177 if (N1.getOpcode() == ISD::SHL) {
2178 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
Dan Gohmanb72127a2008-03-13 22:13:53 +00002179 if (SHC->getAPIntValue().isPowerOf2()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002180 SDValue Add =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002181 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
Duncan Sands13237ac2008-06-06 12:08:01 +00002182 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
Dan Gohmanb72127a2008-03-13 22:13:53 +00002183 VT));
Gabor Greiff304a7a2008-08-28 21:40:38 +00002184 AddToWorkList(Add.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002185 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
Nate Begemanc89fdf12006-02-05 07:36:48 +00002186 }
2187 }
2188 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002189
Dan Gohman9a693412007-11-26 23:46:11 +00002190 // If X/C can be simplified by the division-by-constant logic, lower
2191 // X%C to the equivalent of X-X/C*C.
Chris Lattnerd0620d22006-10-12 20:58:32 +00002192 if (N1C && !N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002193 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
Dan Gohman1df80f62008-09-08 16:59:01 +00002194 AddToWorkList(Div.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002195 SDValue OptimizedDiv = combine(Div.getNode());
2196 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002197 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendlingd033af02009-01-30 02:57:00 +00002198 OptimizedDiv, N1);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002199 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002200 AddToWorkList(Mul.getNode());
Dan Gohman9a693412007-11-26 23:46:11 +00002201 return Sub;
2202 }
Chris Lattnerd0620d22006-10-12 20:58:32 +00002203 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002204
Dan Gohman06563a82007-07-03 14:03:57 +00002205 // undef % X -> 0
2206 if (N0.getOpcode() == ISD::UNDEF)
2207 return DAG.getConstant(0, VT);
2208 // X % undef -> undef
2209 if (N1.getOpcode() == ISD::UNDEF)
2210 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002211
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002212 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002213}
2214
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002215SDValue DAGCombiner::visitMULHS(SDNode *N) {
2216 SDValue N0 = N->getOperand(0);
2217 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002218 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002219 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002220 SDLoc DL(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002221
Nate Begeman21158fc2005-09-01 00:19:25 +00002222 // fold (mulhs x, 0) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002223 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002224 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00002225 // fold (mulhs x, 1) -> (sra x, size(x)-1)
Dan Gohmanb72127a2008-03-13 22:13:53 +00002226 if (N1C && N1C->getAPIntValue() == 1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002227 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
Bill Wendlingfaed0652009-01-30 03:00:18 +00002228 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002229 getShiftAmountTy(N0.getValueType())));
Dan Gohman06563a82007-07-03 14:03:57 +00002230 // fold (mulhs x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002231 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00002232 return DAG.getConstant(0, VT);
Dan Gohmana8665142007-06-25 16:23:39 +00002233
Chris Lattner10bd29f2010-12-13 08:39:01 +00002234 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2235 // plus a shift.
2236 if (VT.isSimple() && !VT.isVector()) {
2237 MVT Simple = VT.getSimpleVT();
2238 unsigned SimpleSize = Simple.getSizeInBits();
2239 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2240 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2241 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2242 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2243 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
Chris Lattnerb86dcee2010-12-15 05:51:39 +00002244 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002245 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
Chris Lattner10bd29f2010-12-13 08:39:01 +00002246 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2247 }
2248 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002249
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002250 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002251}
2252
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002253SDValue DAGCombiner::visitMULHU(SDNode *N) {
2254 SDValue N0 = N->getOperand(0);
2255 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002256 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002257 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002258 SDLoc DL(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002259
Nate Begeman21158fc2005-09-01 00:19:25 +00002260 // fold (mulhu x, 0) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002261 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002262 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00002263 // fold (mulhu x, 1) -> 0
Dan Gohmanb72127a2008-03-13 22:13:53 +00002264 if (N1C && N1C->getAPIntValue() == 1)
Nate Begemand23739d2005-09-06 04:43:02 +00002265 return DAG.getConstant(0, N0.getValueType());
Dan Gohman06563a82007-07-03 14:03:57 +00002266 // fold (mulhu x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002267 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00002268 return DAG.getConstant(0, VT);
Dan Gohmana8665142007-06-25 16:23:39 +00002269
Chris Lattner10bd29f2010-12-13 08:39:01 +00002270 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2271 // plus a shift.
2272 if (VT.isSimple() && !VT.isVector()) {
2273 MVT Simple = VT.getSimpleVT();
2274 unsigned SimpleSize = Simple.getSizeInBits();
2275 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2276 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2277 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2278 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2279 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2280 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002281 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
Chris Lattner10bd29f2010-12-13 08:39:01 +00002282 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2283 }
2284 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002285
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002286 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002287}
2288
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002289/// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2290/// compute two values. LoOp and HiOp give the opcodes for the two computations
2291/// that are being performed. Return true if a simplification was made.
2292///
Scott Michelcf0da6c2009-02-17 22:15:04 +00002293SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002294 unsigned HiOp) {
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002295 // If the high half is not needed, just compute the low half.
Evan Chengece4c682007-11-08 09:25:29 +00002296 bool HiExists = N->hasAnyUseOfValue(1);
2297 if (!HiExists &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002298 (!LegalOperations ||
Owen Andersonfb00d5b2014-01-20 18:41:34 +00002299 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002300 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
Craig Topperdd5e16d2014-04-27 19:21:06 +00002301 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
Chris Lattner31e9edc2008-01-26 01:09:19 +00002302 return CombineTo(N, Res, Res);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002303 }
2304
2305 // If the low half is not needed, just compute the high half.
Evan Chengece4c682007-11-08 09:25:29 +00002306 bool LoExists = N->hasAnyUseOfValue(0);
2307 if (!LoExists &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002308 (!LegalOperations ||
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002309 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002310 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
Craig Topperdd5e16d2014-04-27 19:21:06 +00002311 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
Chris Lattner31e9edc2008-01-26 01:09:19 +00002312 return CombineTo(N, Res, Res);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002313 }
2314
Evan Chengece4c682007-11-08 09:25:29 +00002315 // If both halves are used, return as it is.
2316 if (LoExists && HiExists)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002317 return SDValue();
Evan Chengece4c682007-11-08 09:25:29 +00002318
2319 // If the two computed results can be simplified separately, separate them.
Evan Chengece4c682007-11-08 09:25:29 +00002320 if (LoExists) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002321 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
Craig Topperdd5e16d2014-04-27 19:21:06 +00002322 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
Gabor Greiff304a7a2008-08-28 21:40:38 +00002323 AddToWorkList(Lo.getNode());
2324 SDValue LoOpt = combine(Lo.getNode());
2325 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002326 (!LegalOperations ||
Duncan Sands8651e9c2008-06-13 19:07:40 +00002327 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
Chris Lattner31e9edc2008-01-26 01:09:19 +00002328 return CombineTo(N, LoOpt, LoOpt);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002329 }
2330
Evan Chengece4c682007-11-08 09:25:29 +00002331 if (HiExists) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002332 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
Craig Topperdd5e16d2014-04-27 19:21:06 +00002333 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
Gabor Greiff304a7a2008-08-28 21:40:38 +00002334 AddToWorkList(Hi.getNode());
2335 SDValue HiOpt = combine(Hi.getNode());
2336 if (HiOpt.getNode() && HiOpt != Hi &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002337 (!LegalOperations ||
Duncan Sands8651e9c2008-06-13 19:07:40 +00002338 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
Chris Lattner31e9edc2008-01-26 01:09:19 +00002339 return CombineTo(N, HiOpt, HiOpt);
Evan Chengece4c682007-11-08 09:25:29 +00002340 }
Bill Wendling9b3407e2009-01-30 03:08:40 +00002341
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002342 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002343}
2344
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002345SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2346 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002347 if (Res.getNode()) return Res;
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002348
Chris Lattner15090e12010-12-15 06:04:19 +00002349 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002350 SDLoc DL(N);
Chris Lattner15090e12010-12-15 06:04:19 +00002351
2352 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2353 // plus a shift.
2354 if (VT.isSimple() && !VT.isVector()) {
2355 MVT Simple = VT.getSimpleVT();
2356 unsigned SimpleSize = Simple.getSizeInBits();
2357 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2358 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2359 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2360 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2361 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2362 // Compute the high part as N1.
2363 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002364 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
Chris Lattner15090e12010-12-15 06:04:19 +00002365 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2366 // Compute the low part as N0.
2367 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2368 return CombineTo(N, Lo, Hi);
2369 }
2370 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002371
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002372 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002373}
2374
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002375SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2376 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002377 if (Res.getNode()) return Res;
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002378
Chris Lattner15090e12010-12-15 06:04:19 +00002379 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002380 SDLoc DL(N);
Owen Andersonb2c80da2011-02-25 21:41:48 +00002381
Chris Lattner15090e12010-12-15 06:04:19 +00002382 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2383 // plus a shift.
2384 if (VT.isSimple() && !VT.isVector()) {
2385 MVT Simple = VT.getSimpleVT();
2386 unsigned SimpleSize = Simple.getSizeInBits();
2387 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2388 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2389 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2390 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2391 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2392 // Compute the high part as N1.
2393 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002394 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
Chris Lattner15090e12010-12-15 06:04:19 +00002395 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2396 // Compute the low part as N0.
2397 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2398 return CombineTo(N, Lo, Hi);
2399 }
2400 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002401
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002402 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002403}
2404
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002405SDValue DAGCombiner::visitSMULO(SDNode *N) {
2406 // (smulo x, 2) -> (saddo x, x)
2407 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2408 if (C2->getAPIntValue() == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002409 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002410 N->getOperand(0), N->getOperand(0));
2411
2412 return SDValue();
2413}
2414
2415SDValue DAGCombiner::visitUMULO(SDNode *N) {
2416 // (umulo x, 2) -> (uaddo x, x)
2417 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2418 if (C2->getAPIntValue() == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002419 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002420 N->getOperand(0), N->getOperand(0));
2421
2422 return SDValue();
2423}
2424
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002425SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2426 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002427 if (Res.getNode()) return Res;
Scott Michelcf0da6c2009-02-17 22:15:04 +00002428
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002429 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002430}
2431
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002432SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2433 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002434 if (Res.getNode()) return Res;
Scott Michelcf0da6c2009-02-17 22:15:04 +00002435
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002436 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002437}
2438
Chris Lattner8d6fc202006-05-05 05:51:50 +00002439/// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2440/// two operands of the same opcode, try to simplify it.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002441SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2442 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002443 EVT VT = N0.getValueType();
Chris Lattner8d6fc202006-05-05 05:51:50 +00002444 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
Scott Michelcf0da6c2009-02-17 22:15:04 +00002445
Dan Gohmandd5286d2010-01-14 03:08:49 +00002446 // Bail early if none of these transforms apply.
2447 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2448
Chris Lattner002ee912006-05-05 06:31:05 +00002449 // For each of OP in AND/OR/XOR:
2450 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2451 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2452 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
Dan Gohman600f62b2010-06-24 14:30:44 +00002453 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
Nate Begeman9655f842009-12-03 07:11:29 +00002454 //
2455 // do not sink logical op inside of a vector extend, since it may combine
2456 // into a vsetcc.
Evan Cheng166a4e62010-01-06 19:38:29 +00002457 EVT Op0VT = N0.getOperand(0).getValueType();
2458 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
Dan Gohmanad3e5492009-04-08 00:15:30 +00002459 N0.getOpcode() == ISD::SIGN_EXTEND ||
Evan Chengf1bd5fc2010-04-17 06:13:15 +00002460 // Avoid infinite looping with PromoteIntBinOp.
2461 (N0.getOpcode() == ISD::ANY_EXTEND &&
2462 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
Dan Gohman600f62b2010-06-24 14:30:44 +00002463 (N0.getOpcode() == ISD::TRUNCATE &&
2464 (!TLI.isZExtFree(VT, Op0VT) ||
2465 !TLI.isTruncateFree(Op0VT, VT)) &&
2466 TLI.isTypeLegal(Op0VT))) &&
Nate Begeman9655f842009-12-03 07:11:29 +00002467 !VT.isVector() &&
Evan Cheng166a4e62010-01-06 19:38:29 +00002468 Op0VT == N1.getOperand(0).getValueType() &&
2469 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002470 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
Bill Wendling781db7a2009-01-30 19:25:47 +00002471 N0.getOperand(0).getValueType(),
2472 N0.getOperand(0), N1.getOperand(0));
Gabor Greiff304a7a2008-08-28 21:40:38 +00002473 AddToWorkList(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002474 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
Chris Lattner8d6fc202006-05-05 05:51:50 +00002475 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002476
Chris Lattner5ac42932006-05-05 06:10:43 +00002477 // For each of OP in SHL/SRL/SRA/AND...
2478 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2479 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2480 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
Chris Lattner8d6fc202006-05-05 05:51:50 +00002481 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
Chris Lattner5ac42932006-05-05 06:10:43 +00002482 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
Chris Lattner8d6fc202006-05-05 05:51:50 +00002483 N0.getOperand(1) == N1.getOperand(1)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002484 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
Bill Wendling781db7a2009-01-30 19:25:47 +00002485 N0.getOperand(0).getValueType(),
2486 N0.getOperand(0), N1.getOperand(0));
Gabor Greiff304a7a2008-08-28 21:40:38 +00002487 AddToWorkList(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002488 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Bill Wendling781db7a2009-01-30 19:25:47 +00002489 ORNode, N0.getOperand(1));
Chris Lattner8d6fc202006-05-05 05:51:50 +00002490 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002491
Nadav Rotemb0783502012-04-01 19:31:22 +00002492 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2493 // Only perform this optimization after type legalization and before
2494 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2495 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2496 // we don't want to undo this promotion.
2497 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2498 // on scalars.
Nadav Rotem841c9a82012-09-20 08:53:31 +00002499 if ((N0.getOpcode() == ISD::BITCAST ||
2500 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2501 Level == AfterLegalizeTypes) {
Nadav Rotemb0783502012-04-01 19:31:22 +00002502 SDValue In0 = N0.getOperand(0);
2503 SDValue In1 = N1.getOperand(0);
2504 EVT In0Ty = In0.getValueType();
2505 EVT In1Ty = In1.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00002506 SDLoc DL(N);
Nadav Rotem841c9a82012-09-20 08:53:31 +00002507 // If both incoming values are integers, and the original types are the
2508 // same.
Nadav Rotemb0783502012-04-01 19:31:22 +00002509 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
Nadav Rotem841c9a82012-09-20 08:53:31 +00002510 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2511 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
Nadav Rotemb0783502012-04-01 19:31:22 +00002512 AddToWorkList(Op.getNode());
2513 return BC;
2514 }
2515 }
2516
2517 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2518 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2519 // If both shuffles use the same mask, and both shuffle within a single
2520 // vector, then it is worthwhile to move the swizzle after the operation.
2521 // The type-legalizer generates this pattern when loading illegal
2522 // vector types from memory. In many cases this allows additional shuffle
2523 // optimizations.
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002524 // There are other cases where moving the shuffle after the xor/and/or
2525 // is profitable even if shuffles don't perform a swizzle.
2526 // If both shuffles use the same mask, and both shuffles have the same first
2527 // or second operand, then it might still be profitable to move the shuffle
2528 // after the xor/and/or operation.
2529 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
Nadav Rotemb0783502012-04-01 19:31:22 +00002530 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2531 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
Craig Topper9c3da312012-04-09 07:19:09 +00002532
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002533 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
Craig Topper9c3da312012-04-09 07:19:09 +00002534 "Inputs to shuffles are not the same type");
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00002535
Nadav Rotemb0783502012-04-01 19:31:22 +00002536 // Check that both shuffles use the same mask. The masks are known to be of
2537 // the same length because the result vector type is the same.
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002538 // Check also that shuffles have only one use to avoid introducing extra
2539 // instructions.
2540 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2541 SVN0->getMask().equals(SVN1->getMask())) {
2542 SDValue ShOp = N0->getOperand(1);
Nadav Rotemb0783502012-04-01 19:31:22 +00002543
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002544 // Don't try to fold this node if it requires introducing a
2545 // build vector of all zeros that might be illegal at this stage.
2546 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2547 if (!LegalTypes)
2548 ShOp = DAG.getConstant(0, VT);
2549 else
2550 ShOp = SDValue();
2551 }
2552
2553 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2554 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2555 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2556 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2557 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2558 N0->getOperand(0), N1->getOperand(0));
2559 AddToWorkList(NewNode.getNode());
2560 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2561 &SVN0->getMask()[0]);
2562 }
2563
2564 // Don't try to fold this node if it requires introducing a
2565 // build vector of all zeros that might be illegal at this stage.
2566 ShOp = N0->getOperand(0);
2567 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2568 if (!LegalTypes)
2569 ShOp = DAG.getConstant(0, VT);
2570 else
2571 ShOp = SDValue();
2572 }
2573
2574 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2575 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2576 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2577 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2578 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2579 N0->getOperand(1), N1->getOperand(1));
2580 AddToWorkList(NewNode.getNode());
2581 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2582 &SVN0->getMask()[0]);
2583 }
Nadav Rotemb0783502012-04-01 19:31:22 +00002584 }
2585 }
Craig Topper9c3da312012-04-09 07:19:09 +00002586
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002587 return SDValue();
Chris Lattner8d6fc202006-05-05 05:51:50 +00002588}
2589
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002590SDValue DAGCombiner::visitAND(SDNode *N) {
2591 SDValue N0 = N->getOperand(0);
2592 SDValue N1 = N->getOperand(1);
2593 SDValue LL, LR, RL, RR, CC0, CC1;
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002594 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2595 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002596 EVT VT = N1.getValueType();
Dan Gohmane14c4082010-03-04 00:23:16 +00002597 unsigned BitWidth = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00002598
Dan Gohmana8665142007-06-25 16:23:39 +00002599 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00002600 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002601 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002602 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00002603
2604 // fold (and x, 0) -> 0, vector edition
2605 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2606 return N0;
2607 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2608 return N1;
2609
2610 // fold (and x, -1) -> x, vector edition
2611 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2612 return N1;
2613 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2614 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00002615 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002616
Dan Gohman06563a82007-07-03 14:03:57 +00002617 // fold (and x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002618 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00002619 return DAG.getConstant(0, VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00002620 // fold (and c1, c2) -> c1&c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002621 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00002622 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00002623 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00002624 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002625 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00002626 // fold (and x, -1) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002627 if (N1C && N1C->isAllOnesValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002628 return N0;
2629 // if (and x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002630 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1f372ed2008-02-25 21:11:39 +00002631 APInt::getAllOnesValue(BitWidth)))
Nate Begemand23739d2005-09-06 04:43:02 +00002632 return DAG.getConstant(0, VT);
Nate Begeman22e251a2006-02-03 06:46:56 +00002633 // reassociate and
Andrew Trickef9de2a2013-05-25 02:42:55 +00002634 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00002635 if (RAND.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00002636 return RAND;
Bill Wendlingaf13d822010-03-03 00:35:56 +00002637 // fold (and (or x, C), D) -> D if (C & D) == D
Nate Begemanee065282005-11-02 18:42:59 +00002638 if (N1C && N0.getOpcode() == ISD::OR)
Nate Begeman21158fc2005-09-01 00:19:25 +00002639 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
Dan Gohmanb72127a2008-03-13 22:13:53 +00002640 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002641 return N1;
Chris Lattner49beaf42006-02-02 07:17:31 +00002642 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2643 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002644 SDValue N0Op0 = N0.getOperand(0);
Dan Gohman1f372ed2008-02-25 21:11:39 +00002645 APInt Mask = ~N1C->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00002646 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
Dan Gohman1f372ed2008-02-25 21:11:39 +00002647 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002648 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
Bill Wendling86171912009-01-30 20:43:18 +00002649 N0.getValueType(), N0Op0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002650
Chris Lattner0db2f2c2006-03-01 21:47:21 +00002651 // Replace uses of the AND with uses of the Zero extend node.
2652 CombineTo(N, Zext);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002653
Chris Lattner49beaf42006-02-02 07:17:31 +00002654 // We actually want to replace all uses of the any_extend with the
2655 // zero_extend, to avoid duplicating things. This will later cause this
2656 // AND to be folded.
Gabor Greiff304a7a2008-08-28 21:40:38 +00002657 CombineTo(N0.getNode(), Zext);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002658 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattner49beaf42006-02-02 07:17:31 +00002659 }
2660 }
Stephen Lincfe7f352013-07-08 00:37:03 +00002661 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
James Molloy862fe492012-02-20 12:02:38 +00002662 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2663 // already be zero by virtue of the width of the base type of the load.
2664 //
2665 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2666 // more cases.
2667 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2668 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2669 N0.getOpcode() == ISD::LOAD) {
2670 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2671 N0 : N0.getOperand(0) );
2672
2673 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2674 // This can be a pure constant or a vector splat, in which case we treat the
2675 // vector as a scalar and use the splat value.
2676 APInt Constant = APInt::getNullValue(1);
2677 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2678 Constant = C->getAPIntValue();
2679 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2680 APInt SplatValue, SplatUndef;
2681 unsigned SplatBitSize;
2682 bool HasAnyUndefs;
2683 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2684 SplatBitSize, HasAnyUndefs);
2685 if (IsSplat) {
2686 // Undef bits can contribute to a possible optimisation if set, so
2687 // set them.
2688 SplatValue |= SplatUndef;
2689
2690 // The splat value may be something like "0x00FFFFFF", which means 0 for
2691 // the first vector value and FF for the rest, repeating. We need a mask
2692 // that will apply equally to all members of the vector, so AND all the
2693 // lanes of the constant together.
2694 EVT VT = Vector->getValueType(0);
2695 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
Silviu Baranga3f40d872012-09-05 08:57:21 +00002696
2697 // If the splat value has been compressed to a bitlength lower
2698 // than the size of the vector lane, we need to re-expand it to
2699 // the lane size.
2700 if (BitWidth > SplatBitSize)
2701 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2702 SplatBitSize < BitWidth;
2703 SplatBitSize = SplatBitSize * 2)
2704 SplatValue |= SplatValue.shl(SplatBitSize);
2705
James Molloy862fe492012-02-20 12:02:38 +00002706 Constant = APInt::getAllOnesValue(BitWidth);
Silviu Baranga3f40d872012-09-05 08:57:21 +00002707 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
James Molloy862fe492012-02-20 12:02:38 +00002708 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2709 }
2710 }
2711
2712 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2713 // actually legal and isn't going to get expanded, else this is a false
2714 // optimisation.
2715 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2716 Load->getMemoryVT());
2717
2718 // Resize the constant to the same size as the original memory access before
2719 // extension. If it is still the AllOnesValue then this AND is completely
2720 // unneeded.
2721 Constant =
2722 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2723
2724 bool B;
2725 switch (Load->getExtensionType()) {
2726 default: B = false; break;
2727 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2728 case ISD::ZEXTLOAD:
2729 case ISD::NON_EXTLOAD: B = true; break;
2730 }
2731
2732 if (B && Constant.isAllOnesValue()) {
2733 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2734 // preserve semantics once we get rid of the AND.
2735 SDValue NewLoad(Load, 0);
2736 if (Load->getExtensionType() == ISD::EXTLOAD) {
2737 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
Andrew Trickef9de2a2013-05-25 02:42:55 +00002738 Load->getValueType(0), SDLoc(Load),
James Molloy862fe492012-02-20 12:02:38 +00002739 Load->getChain(), Load->getBasePtr(),
2740 Load->getOffset(), Load->getMemoryVT(),
2741 Load->getMemOperand());
2742 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
Hal Finkel8a311382012-06-20 15:42:48 +00002743 if (Load->getNumValues() == 3) {
2744 // PRE/POST_INC loads have 3 values.
2745 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2746 NewLoad.getValue(2) };
2747 CombineTo(Load, To, 3, true);
2748 } else {
2749 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2750 }
James Molloy862fe492012-02-20 12:02:38 +00002751 }
2752
2753 // Fold the AND away, taking care not to fold to the old load node if we
2754 // replaced it.
2755 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2756
2757 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2758 }
2759 }
Nate Begeman049b7482005-09-09 19:49:52 +00002760 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2761 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2762 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2763 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
Scott Michelcf0da6c2009-02-17 22:15:04 +00002764
Tom Stellard7783b0a2014-06-12 16:04:47 +00002765 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
Duncan Sands13237ac2008-06-06 12:08:01 +00002766 LL.getValueType().isInteger()) {
Bill Wendling86171912009-01-30 20:43:18 +00002767 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
Tom Stellard7783b0a2014-06-12 16:04:47 +00002768 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002769 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
Bill Wendling86171912009-01-30 20:43:18 +00002770 LR.getValueType(), LL, RL);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002771 AddToWorkList(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002772 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00002773 }
Bill Wendling86171912009-01-30 20:43:18 +00002774 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
Tom Stellard7783b0a2014-06-12 16:04:47 +00002775 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002776 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
Bill Wendling86171912009-01-30 20:43:18 +00002777 LR.getValueType(), LL, RL);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002778 AddToWorkList(ANDNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002779 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00002780 }
Bill Wendling86171912009-01-30 20:43:18 +00002781 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
Tom Stellard7783b0a2014-06-12 16:04:47 +00002782 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002783 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
Bill Wendling86171912009-01-30 20:43:18 +00002784 LR.getValueType(), LL, RL);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002785 AddToWorkList(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002786 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00002787 }
2788 }
Jim Grosbach327ccc72013-08-13 21:30:58 +00002789 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2790 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2791 Op0 == Op1 && LL.getValueType().isInteger() &&
2792 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2793 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2794 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2795 cast<ConstantSDNode>(RR)->isNullValue()))) {
2796 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2797 LL, DAG.getConstant(1, LL.getValueType()));
2798 AddToWorkList(ADDNode.getNode());
2799 return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2800 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2801 }
Nate Begeman049b7482005-09-09 19:49:52 +00002802 // canonicalize equivalent to ll == rl
2803 if (LL == RR && LR == RL) {
2804 Op1 = ISD::getSetCCSwappedOperands(Op1);
2805 std::swap(RL, RR);
2806 }
2807 if (LL == RL && LR == RR) {
Duncan Sands13237ac2008-06-06 12:08:01 +00002808 bool isInteger = LL.getValueType().isInteger();
Nate Begeman049b7482005-09-09 19:49:52 +00002809 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
Chris Lattner5fa10402008-10-28 07:11:07 +00002810 if (Result != ISD::SETCC_INVALID &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00002811 (!LegalOperations ||
Owen Andersoncc068992013-02-14 09:07:33 +00002812 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2813 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault758659232013-05-18 00:21:46 +00002814 getSetCCResultType(N0.getSimpleValueType())))))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002815 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
Bill Wendling86171912009-01-30 20:43:18 +00002816 LL, LR, Result);
Nate Begeman049b7482005-09-09 19:49:52 +00002817 }
2818 }
Chris Lattner8d6fc202006-05-05 05:51:50 +00002819
Bill Wendling86171912009-01-30 20:43:18 +00002820 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
Chris Lattner8d6fc202006-05-05 05:51:50 +00002821 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002822 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002823 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00002824 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002825
Nate Begemandc7bba92006-02-03 22:24:05 +00002826 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2827 // fold (and (sra)) -> (and (srl)) when possible.
Duncan Sands13237ac2008-06-06 12:08:01 +00002828 if (!VT.isVector() &&
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002829 SimplifyDemandedBits(SDValue(N, 0)))
2830 return SDValue(N, 0);
Evan Cheng166a4e62010-01-06 19:38:29 +00002831
Nate Begeman02b23c62005-10-13 03:11:28 +00002832 // fold (zext_inreg (extload x)) -> (zextload x)
Gabor Greiff304a7a2008-08-28 21:40:38 +00002833 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00002834 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00002835 EVT MemVT = LN0->getMemoryVT();
Nate Begeman8e022b32005-10-13 18:34:58 +00002836 // If we zero all the possible extended bits, then we can turn this into
2837 // a zextload if we are running before legalize or the operation is legal.
Dan Gohmane14c4082010-03-04 00:23:16 +00002838 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
Dan Gohman1f372ed2008-02-25 21:11:39 +00002839 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
Dan Gohmane14c4082010-03-04 00:23:16 +00002840 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002841 ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00002842 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002843 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
Bill Wendling86171912009-01-30 20:43:18 +00002844 LN0->getChain(), LN0->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002845 MemVT, LN0->getMemOperand());
Chris Lattnerfbcd62d2006-03-01 04:03:14 +00002846 AddToWorkList(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002847 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002848 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00002849 }
2850 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002851 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
Gabor Greiff304a7a2008-08-28 21:40:38 +00002852 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Cheng8a1d09d2007-03-07 08:07:03 +00002853 N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00002854 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00002855 EVT MemVT = LN0->getMemoryVT();
Nate Begeman8e022b32005-10-13 18:34:58 +00002856 // If we zero all the possible extended bits, then we can turn this into
2857 // a zextload if we are running before legalize or the operation is legal.
Dan Gohmane14c4082010-03-04 00:23:16 +00002858 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
Dan Gohman1f372ed2008-02-25 21:11:39 +00002859 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
Dan Gohmane14c4082010-03-04 00:23:16 +00002860 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002861 ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00002862 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002863 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002864 LN0->getChain(), LN0->getBasePtr(),
2865 MemVT, LN0->getMemOperand());
Chris Lattnerfbcd62d2006-03-01 04:03:14 +00002866 AddToWorkList(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002867 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002868 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00002869 }
2870 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002871
Chris Lattnerf0032b32006-02-28 06:49:37 +00002872 // fold (and (load x), 255) -> (zextload x, i8)
2873 // fold (and (extload x, i16), 255) -> (zextload x, i8)
Evan Cheng166a4e62010-01-06 19:38:29 +00002874 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2875 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2876 (N0.getOpcode() == ISD::ANY_EXTEND &&
2877 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2878 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2879 LoadSDNode *LN0 = HasAnyExt
2880 ? cast<LoadSDNode>(N0.getOperand(0))
2881 : cast<LoadSDNode>(N0);
Evan Chenge71fe34d2006-10-09 20:57:25 +00002882 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
Tim Northover68239002013-07-02 09:58:53 +00002883 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
Duncan Sands93b66092008-06-09 11:32:28 +00002884 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
Evan Cheng166a4e62010-01-06 19:38:29 +00002885 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2886 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2887 EVT LoadedVT = LN0->getMemoryVT();
Duncan Sands93b66092008-06-09 11:32:28 +00002888
Evan Cheng166a4e62010-01-06 19:38:29 +00002889 if (ExtVT == LoadedVT &&
2890 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
Chris Lattner88de3842010-01-07 21:53:27 +00002891 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
Wesley Peck527da1b2010-11-23 03:31:01 +00002892
2893 SDValue NewLoad =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002894 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002895 LN0->getChain(), LN0->getBasePtr(), ExtVT,
2896 LN0->getMemOperand());
Chris Lattner88de3842010-01-07 21:53:27 +00002897 AddToWorkList(N);
2898 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2899 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2900 }
Wesley Peck527da1b2010-11-23 03:31:01 +00002901
Chris Lattner88de3842010-01-07 21:53:27 +00002902 // Do not change the width of a volatile load.
2903 // Do not generate loads of non-round integer types since these can
2904 // be expensive (and would be wrong if the type is not byte sized).
2905 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2906 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2907 EVT PtrType = LN0->getOperand(1).getValueType();
Bill Wendling86171912009-01-30 20:43:18 +00002908
Chris Lattner88de3842010-01-07 21:53:27 +00002909 unsigned Alignment = LN0->getAlignment();
2910 SDValue NewPtr = LN0->getBasePtr();
2911
2912 // For big endian targets, we need to add an offset to the pointer
2913 // to load the correct bytes. For little endian systems, we merely
2914 // need to read fewer bytes from the same pointer.
2915 if (TLI.isBigEndian()) {
Evan Cheng166a4e62010-01-06 19:38:29 +00002916 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2917 unsigned EVTStoreBytes = ExtVT.getStoreSize();
2918 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
Andrew Trickef9de2a2013-05-25 02:42:55 +00002919 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
Chris Lattner88de3842010-01-07 21:53:27 +00002920 NewPtr, DAG.getConstant(PtrOff, PtrType));
2921 Alignment = MinAlign(Alignment, PtrOff);
Evan Cheng166a4e62010-01-06 19:38:29 +00002922 }
Chris Lattner88de3842010-01-07 21:53:27 +00002923
2924 AddToWorkList(NewPtr.getNode());
Wesley Peck527da1b2010-11-23 03:31:01 +00002925
Chris Lattner88de3842010-01-07 21:53:27 +00002926 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2927 SDValue Load =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002928 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
Chris Lattner88de3842010-01-07 21:53:27 +00002929 LN0->getChain(), NewPtr,
Chris Lattner3d178ed2010-09-21 17:04:51 +00002930 LN0->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +00002931 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002932 Alignment, LN0->getTBAAInfo());
Chris Lattner88de3842010-01-07 21:53:27 +00002933 AddToWorkList(N);
2934 CombineTo(LN0, Load, Load.getValue(1));
2935 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Duncan Sands1826ded2007-10-28 12:59:45 +00002936 }
Evan Chenge71fe34d2006-10-09 20:57:25 +00002937 }
Chris Lattnerbdbc4472006-02-28 06:35:35 +00002938 }
2939 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002940
Evan Chenge6a3b032012-07-17 18:54:11 +00002941 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2942 VT.getSizeInBits() <= 64) {
2943 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2944 APInt ADDC = ADDI->getAPIntValue();
2945 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2946 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2947 // immediate for an add, but it is legal if its top c2 bits are set,
2948 // transform the ADD so the immediate doesn't need to be materialized
2949 // in a register.
2950 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2951 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2952 SRLI->getZExtValue());
2953 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2954 ADDC |= Mask;
2955 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2956 SDValue NewAdd =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002957 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
Evan Chenge6a3b032012-07-17 18:54:11 +00002958 N0.getOperand(0), DAG.getConstant(ADDC, VT));
2959 CombineTo(N0.getNode(), NewAdd);
2960 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2961 }
2962 }
2963 }
2964 }
2965 }
2966 }
Evan Chenge6a3b032012-07-17 18:54:11 +00002967
Tim Northover819bfb52013-08-27 13:46:45 +00002968 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
2969 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
2970 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
2971 N0.getOperand(1), false);
2972 if (BSwap.getNode())
2973 return BSwap;
2974 }
2975
Evan Chengf1005572010-04-28 07:10:39 +00002976 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002977}
2978
Evan Cheng4c0bd962011-06-21 06:01:08 +00002979/// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2980///
2981SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2982 bool DemandHighBits) {
2983 if (!LegalOperations)
2984 return SDValue();
2985
2986 EVT VT = N->getValueType(0);
2987 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2988 return SDValue();
2989 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2990 return SDValue();
2991
2992 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2993 bool LookPassAnd0 = false;
2994 bool LookPassAnd1 = false;
2995 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2996 std::swap(N0, N1);
2997 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2998 std::swap(N0, N1);
2999 if (N0.getOpcode() == ISD::AND) {
3000 if (!N0.getNode()->hasOneUse())
3001 return SDValue();
3002 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3003 if (!N01C || N01C->getZExtValue() != 0xFF00)
3004 return SDValue();
3005 N0 = N0.getOperand(0);
3006 LookPassAnd0 = true;
3007 }
3008
3009 if (N1.getOpcode() == ISD::AND) {
3010 if (!N1.getNode()->hasOneUse())
3011 return SDValue();
3012 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3013 if (!N11C || N11C->getZExtValue() != 0xFF)
3014 return SDValue();
3015 N1 = N1.getOperand(0);
3016 LookPassAnd1 = true;
3017 }
3018
3019 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3020 std::swap(N0, N1);
3021 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3022 return SDValue();
3023 if (!N0.getNode()->hasOneUse() ||
3024 !N1.getNode()->hasOneUse())
3025 return SDValue();
3026
3027 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3028 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3029 if (!N01C || !N11C)
3030 return SDValue();
3031 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3032 return SDValue();
3033
3034 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3035 SDValue N00 = N0->getOperand(0);
3036 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3037 if (!N00.getNode()->hasOneUse())
3038 return SDValue();
3039 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3040 if (!N001C || N001C->getZExtValue() != 0xFF)
3041 return SDValue();
3042 N00 = N00.getOperand(0);
3043 LookPassAnd0 = true;
3044 }
3045
3046 SDValue N10 = N1->getOperand(0);
3047 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3048 if (!N10.getNode()->hasOneUse())
3049 return SDValue();
3050 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3051 if (!N101C || N101C->getZExtValue() != 0xFF00)
3052 return SDValue();
3053 N10 = N10.getOperand(0);
3054 LookPassAnd1 = true;
3055 }
3056
3057 if (N00 != N10)
3058 return SDValue();
3059
Tim Northover819bfb52013-08-27 13:46:45 +00003060 // Make sure everything beyond the low halfword gets set to zero since the SRL
3061 // 16 will clear the top bits.
Evan Cheng4c0bd962011-06-21 06:01:08 +00003062 unsigned OpSizeInBits = VT.getSizeInBits();
Tim Northover819bfb52013-08-27 13:46:45 +00003063 if (DemandHighBits && OpSizeInBits > 16) {
3064 // If the left-shift isn't masked out then the only way this is a bswap is
3065 // if all bits beyond the low 8 are 0. In that case the entire pattern
3066 // reduces to a left shift anyway: leave it for other parts of the combiner.
3067 if (!LookPassAnd0)
3068 return SDValue();
3069
3070 // However, if the right shift isn't masked out then it might be because
3071 // it's not needed. See if we can spot that too.
3072 if (!LookPassAnd1 &&
3073 !DAG.MaskedValueIsZero(
3074 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3075 return SDValue();
3076 }
Eric Christopherd6300d22011-07-14 01:12:15 +00003077
Andrew Trickef9de2a2013-05-25 02:42:55 +00003078 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
Evan Cheng4c0bd962011-06-21 06:01:08 +00003079 if (OpSizeInBits > 16)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003080 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
Evan Cheng4c0bd962011-06-21 06:01:08 +00003081 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3082 return Res;
3083}
3084
3085/// isBSwapHWordElement - Return true if the specified node is an element
3086/// that makes up a 32-bit packed halfword byteswap. i.e.
3087/// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
Craig Topperb94011f2013-07-14 04:42:23 +00003088static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
Evan Cheng4c0bd962011-06-21 06:01:08 +00003089 if (!N.getNode()->hasOneUse())
3090 return false;
3091
3092 unsigned Opc = N.getOpcode();
3093 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3094 return false;
3095
3096 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3097 if (!N1C)
3098 return false;
3099
3100 unsigned Num;
3101 switch (N1C->getZExtValue()) {
3102 default:
3103 return false;
3104 case 0xFF: Num = 0; break;
3105 case 0xFF00: Num = 1; break;
3106 case 0xFF0000: Num = 2; break;
3107 case 0xFF000000: Num = 3; break;
3108 }
3109
3110 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3111 SDValue N0 = N.getOperand(0);
3112 if (Opc == ISD::AND) {
3113 if (Num == 0 || Num == 2) {
3114 // (x >> 8) & 0xff
3115 // (x >> 8) & 0xff0000
3116 if (N0.getOpcode() != ISD::SRL)
3117 return false;
3118 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3119 if (!C || C->getZExtValue() != 8)
3120 return false;
3121 } else {
3122 // (x << 8) & 0xff00
3123 // (x << 8) & 0xff000000
3124 if (N0.getOpcode() != ISD::SHL)
3125 return false;
3126 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3127 if (!C || C->getZExtValue() != 8)
3128 return false;
3129 }
3130 } else if (Opc == ISD::SHL) {
3131 // (x & 0xff) << 8
3132 // (x & 0xff0000) << 8
3133 if (Num != 0 && Num != 2)
3134 return false;
3135 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3136 if (!C || C->getZExtValue() != 8)
3137 return false;
3138 } else { // Opc == ISD::SRL
3139 // (x & 0xff00) >> 8
3140 // (x & 0xff000000) >> 8
3141 if (Num != 1 && Num != 3)
3142 return false;
3143 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3144 if (!C || C->getZExtValue() != 8)
3145 return false;
3146 }
3147
3148 if (Parts[Num])
3149 return false;
3150
3151 Parts[Num] = N0.getOperand(0).getNode();
3152 return true;
3153}
3154
3155/// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3156/// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3157/// => (rotl (bswap x), 16)
3158SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3159 if (!LegalOperations)
3160 return SDValue();
3161
3162 EVT VT = N->getValueType(0);
3163 if (VT != MVT::i32)
3164 return SDValue();
3165 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3166 return SDValue();
3167
Craig Topperc0196b12014-04-14 00:51:57 +00003168 SmallVector<SDNode*,4> Parts(4, (SDNode*)nullptr);
Evan Cheng4c0bd962011-06-21 06:01:08 +00003169 // Look for either
3170 // (or (or (and), (and)), (or (and), (and)))
3171 // (or (or (or (and), (and)), (and)), (and))
3172 if (N0.getOpcode() != ISD::OR)
3173 return SDValue();
3174 SDValue N00 = N0.getOperand(0);
3175 SDValue N01 = N0.getOperand(1);
3176
Evan Chengbf0baa92012-12-13 01:34:32 +00003177 if (N1.getOpcode() == ISD::OR &&
3178 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
Evan Cheng4c0bd962011-06-21 06:01:08 +00003179 // (or (or (and), (and)), (or (and), (and)))
3180 SDValue N000 = N00.getOperand(0);
3181 if (!isBSwapHWordElement(N000, Parts))
3182 return SDValue();
3183
3184 SDValue N001 = N00.getOperand(1);
3185 if (!isBSwapHWordElement(N001, Parts))
3186 return SDValue();
3187 SDValue N010 = N01.getOperand(0);
3188 if (!isBSwapHWordElement(N010, Parts))
3189 return SDValue();
3190 SDValue N011 = N01.getOperand(1);
3191 if (!isBSwapHWordElement(N011, Parts))
3192 return SDValue();
3193 } else {
3194 // (or (or (or (and), (and)), (and)), (and))
3195 if (!isBSwapHWordElement(N1, Parts))
3196 return SDValue();
3197 if (!isBSwapHWordElement(N01, Parts))
3198 return SDValue();
3199 if (N00.getOpcode() != ISD::OR)
3200 return SDValue();
3201 SDValue N000 = N00.getOperand(0);
3202 if (!isBSwapHWordElement(N000, Parts))
3203 return SDValue();
3204 SDValue N001 = N00.getOperand(1);
3205 if (!isBSwapHWordElement(N001, Parts))
3206 return SDValue();
3207 }
3208
3209 // Make sure the parts are all coming from the same node.
3210 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3211 return SDValue();
3212
Andrew Trickef9de2a2013-05-25 02:42:55 +00003213 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
Evan Cheng4c0bd962011-06-21 06:01:08 +00003214 SDValue(Parts[0],0));
3215
Kay Tiong Khoo9195a5b2013-09-23 18:43:51 +00003216 // Result of the bswap should be rotated by 16. If it's not legal, then
Evan Cheng4c0bd962011-06-21 06:01:08 +00003217 // do (x << 16) | (x >> 16).
3218 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3219 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003220 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
Craig Topper5f9791f2012-09-29 07:18:53 +00003221 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003222 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3223 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3224 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3225 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
Evan Cheng4c0bd962011-06-21 06:01:08 +00003226}
3227
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003228SDValue DAGCombiner::visitOR(SDNode *N) {
3229 SDValue N0 = N->getOperand(0);
3230 SDValue N1 = N->getOperand(1);
3231 SDValue LL, LR, RL, RR, CC0, CC1;
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003232 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3233 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00003234 EVT VT = N1.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003235
Dan Gohmana8665142007-06-25 16:23:39 +00003236 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00003237 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003238 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003239 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00003240
3241 // fold (or x, 0) -> x, vector edition
3242 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3243 return N1;
3244 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3245 return N0;
3246
3247 // fold (or x, -1) -> -1, vector edition
3248 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3249 return N0;
3250 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3251 return N1;
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003252
3253 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3254 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3255 // Do this only if the resulting shuffle is legal.
3256 if (isa<ShuffleVectorSDNode>(N0) &&
3257 isa<ShuffleVectorSDNode>(N1) &&
3258 N0->getOperand(1) == N1->getOperand(1) &&
3259 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3260 bool CanFold = true;
3261 unsigned NumElts = VT.getVectorNumElements();
3262 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3263 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3264 // We construct two shuffle masks:
3265 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3266 // and N1 as the second operand.
3267 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3268 // and N0 as the second operand.
3269 // We do this because OR is commutable and therefore there might be
3270 // two ways to fold this node into a shuffle.
3271 SmallVector<int,4> Mask1;
3272 SmallVector<int,4> Mask2;
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00003273
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003274 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3275 int M0 = SV0->getMaskElt(i);
3276 int M1 = SV1->getMaskElt(i);
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00003277
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003278 // Both shuffle indexes are undef. Propagate Undef.
3279 if (M0 < 0 && M1 < 0) {
3280 Mask1.push_back(M0);
3281 Mask2.push_back(M0);
3282 continue;
3283 }
3284
3285 if (M0 < 0 || M1 < 0 ||
3286 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3287 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3288 CanFold = false;
3289 break;
3290 }
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00003291
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003292 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3293 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3294 }
3295
3296 if (CanFold) {
3297 // Fold this sequence only if the resulting shuffle is 'legal'.
3298 if (TLI.isShuffleMaskLegal(Mask1, VT))
3299 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3300 N1->getOperand(0), &Mask1[0]);
3301 if (TLI.isShuffleMaskLegal(Mask2, VT))
3302 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3303 N0->getOperand(0), &Mask2[0]);
3304 }
3305 }
Dan Gohman80f9f072007-07-13 20:03:40 +00003306 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003307
Dan Gohman06563a82007-07-03 14:03:57 +00003308 // fold (or x, undef) -> -1
Bob Wilson269a89f2010-06-28 23:40:25 +00003309 if (!LegalOperations &&
3310 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
Nate Begeman9655f842009-12-03 07:11:29 +00003311 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3312 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3313 }
Nate Begeman21158fc2005-09-01 00:19:25 +00003314 // fold (or c1, c2) -> c1|c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003315 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00003316 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003317 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00003318 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003319 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00003320 // fold (or x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003321 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003322 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00003323 // fold (or x, -1) -> -1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003324 if (N1C && N1C->isAllOnesValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003325 return N1;
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003326 // fold (or x, c) -> c iff (x & ~c) == 0
Dan Gohman1f372ed2008-02-25 21:11:39 +00003327 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
Nate Begemand23739d2005-09-06 04:43:02 +00003328 return N1;
Evan Cheng4c0bd962011-06-21 06:01:08 +00003329
3330 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3331 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003332 if (BSwap.getNode())
Evan Cheng4c0bd962011-06-21 06:01:08 +00003333 return BSwap;
3334 BSwap = MatchBSwapHWordLow(N, N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003335 if (BSwap.getNode())
Evan Cheng4c0bd962011-06-21 06:01:08 +00003336 return BSwap;
3337
Nate Begeman22e251a2006-02-03 06:46:56 +00003338 // reassociate or
Andrew Trickef9de2a2013-05-25 02:42:55 +00003339 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003340 if (ROR.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00003341 return ROR;
3342 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003343 // iff (c1 & c2) == 0.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003344 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
Chris Lattnerd8c5c062005-10-27 05:06:38 +00003345 isa<ConstantSDNode>(N0.getOperand(1))) {
Chris Lattnerd8c5c062005-10-27 05:06:38 +00003346 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
Juergen Ributzkaf26beda2014-01-25 02:02:55 +00003347 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3348 SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3349 if (!COR.getNode())
3350 return SDValue();
Andrew Trickef9de2a2013-05-25 02:42:55 +00003351 return DAG.getNode(ISD::AND, SDLoc(N), VT,
3352 DAG.getNode(ISD::OR, SDLoc(N0), VT,
Juergen Ributzkaf26beda2014-01-25 02:02:55 +00003353 N0.getOperand(0), N1), COR);
3354 }
Nate Begeman85c1cc42005-09-08 20:18:10 +00003355 }
Nate Begeman049b7482005-09-09 19:49:52 +00003356 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3357 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3358 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3359 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003360
Nate Begeman049b7482005-09-09 19:49:52 +00003361 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
Duncan Sands13237ac2008-06-06 12:08:01 +00003362 LL.getValueType().isInteger()) {
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003363 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3364 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
Scott Michelcf0da6c2009-02-17 22:15:04 +00003365 if (cast<ConstantSDNode>(LR)->isNullValue() &&
Nate Begeman049b7482005-09-09 19:49:52 +00003366 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003367 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003368 LR.getValueType(), LL, RL);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003369 AddToWorkList(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003370 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00003371 }
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003372 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3373 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
Scott Michelcf0da6c2009-02-17 22:15:04 +00003374 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
Nate Begeman049b7482005-09-09 19:49:52 +00003375 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003376 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003377 LR.getValueType(), LL, RL);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003378 AddToWorkList(ANDNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003379 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00003380 }
3381 }
3382 // canonicalize equivalent to ll == rl
3383 if (LL == RR && LR == RL) {
3384 Op1 = ISD::getSetCCSwappedOperands(Op1);
3385 std::swap(RL, RR);
3386 }
3387 if (LL == RL && LR == RR) {
Duncan Sands13237ac2008-06-06 12:08:01 +00003388 bool isInteger = LL.getValueType().isInteger();
Nate Begeman049b7482005-09-09 19:49:52 +00003389 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
Chris Lattner5fa10402008-10-28 07:11:07 +00003390 if (Result != ISD::SETCC_INVALID &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00003391 (!LegalOperations ||
Owen Andersoncc068992013-02-14 09:07:33 +00003392 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3393 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault758659232013-05-18 00:21:46 +00003394 getSetCCResultType(N0.getValueType())))))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003395 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003396 LL, LR, Result);
Nate Begeman049b7482005-09-09 19:49:52 +00003397 }
3398 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003399
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003400 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
Chris Lattner8d6fc202006-05-05 05:51:50 +00003401 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003402 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003403 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00003404 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003405
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003406 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
Chris Lattner46d710e2006-09-14 21:11:37 +00003407 if (N0.getOpcode() == ISD::AND &&
3408 N1.getOpcode() == ISD::AND &&
3409 N0.getOperand(1).getOpcode() == ISD::Constant &&
3410 N1.getOperand(1).getOpcode() == ISD::Constant &&
3411 // Don't increase # computations.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003412 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
Chris Lattner46d710e2006-09-14 21:11:37 +00003413 // We can only do this xform if we know that bits from X that are set in C2
3414 // but not in C1 are already zero. Likewise for Y.
Dan Gohman1f372ed2008-02-25 21:11:39 +00003415 const APInt &LHSMask =
3416 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3417 const APInt &RHSMask =
3418 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003419
Dan Gohman309d3d52007-06-22 14:59:07 +00003420 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3421 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003422 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003423 N0.getOperand(0), N1.getOperand(0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00003424 return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003425 DAG.getConstant(LHSMask | RHSMask, VT));
Chris Lattner46d710e2006-09-14 21:11:37 +00003426 }
3427 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003428
Chris Lattner97614c82006-09-14 20:50:57 +00003429 // See if this is some rotate idiom.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003430 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003431 return SDValue(Rot, 0);
Chris Lattner8d6fc202006-05-05 05:51:50 +00003432
Dan Gohman600f62b2010-06-24 14:30:44 +00003433 // Simplify the operands using demanded-bits information.
3434 if (!VT.isVector() &&
3435 SimplifyDemandedBits(SDValue(N, 0)))
3436 return SDValue(N, 0);
3437
Evan Chengf1005572010-04-28 07:10:39 +00003438 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00003439}
3440
Chris Lattner97614c82006-09-14 20:50:57 +00003441/// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003442static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
Chris Lattner97614c82006-09-14 20:50:57 +00003443 if (Op.getOpcode() == ISD::AND) {
Reid Spencerde46e482006-11-02 20:25:50 +00003444 if (isa<ConstantSDNode>(Op.getOperand(1))) {
Chris Lattner97614c82006-09-14 20:50:57 +00003445 Mask = Op.getOperand(1);
3446 Op = Op.getOperand(0);
3447 } else {
3448 return false;
3449 }
3450 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003451
Chris Lattner97614c82006-09-14 20:50:57 +00003452 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3453 Shift = Op;
3454 return true;
3455 }
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003456
Scott Michelcf0da6c2009-02-17 22:15:04 +00003457 return false;
Chris Lattner97614c82006-09-14 20:50:57 +00003458}
3459
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003460// Return true if we can prove that, whenever Neg and Pos are both in the
3461// range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
Richard Sandiford0f264db2014-01-09 10:49:40 +00003462// for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3463//
3464// (or (shift1 X, Neg), (shift2 X, Pos))
3465//
Adam Nemetc6553a82014-03-07 23:56:24 +00003466// reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3467// in direction shift1 by Neg. The range [0, OpSize) means that we only need
3468// to consider shift amounts with defined behavior.
Richard Sandiford0f264db2014-01-09 10:49:40 +00003469static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003470 // If OpSize is a power of 2 then:
3471 //
3472 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3473 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3474 //
3475 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3476 // for the stronger condition:
3477 //
3478 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3479 //
3480 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3481 // we can just replace Neg with Neg' for the rest of the function.
3482 //
3483 // In other cases we check for the even stronger condition:
3484 //
3485 // Neg == OpSize - Pos [B]
3486 //
3487 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3488 // behavior if Pos == 0 (and consequently Neg == OpSize).
Adam Nemetc6553a82014-03-07 23:56:24 +00003489 //
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003490 // We could actually use [A] whenever OpSize is a power of 2, but the
3491 // only extra cases that it would match are those uninteresting ones
3492 // where Neg and Pos are never in range at the same time. E.g. for
3493 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3494 // as well as (sub 32, Pos), but:
3495 //
3496 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3497 //
3498 // always invokes undefined behavior for 32-bit X.
3499 //
3500 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
Adam Nemetc6553a82014-03-07 23:56:24 +00003501 unsigned MaskLoBits = 0;
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003502 if (Neg.getOpcode() == ISD::AND &&
3503 isPowerOf2_64(OpSize) &&
3504 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3505 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3506 Neg = Neg.getOperand(0);
Adam Nemetc6553a82014-03-07 23:56:24 +00003507 MaskLoBits = Log2_64(OpSize);
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003508 }
3509
Richard Sandiford0f264db2014-01-09 10:49:40 +00003510 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3511 if (Neg.getOpcode() != ISD::SUB)
3512 return 0;
3513 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3514 if (!NegC)
3515 return 0;
3516 SDValue NegOp1 = Neg.getOperand(1);
3517
Adam Nemet5117f5d2014-03-07 23:56:28 +00003518 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3519 // Pos'. The truncation is redundant for the purpose of the equality.
3520 if (MaskLoBits &&
3521 Pos.getOpcode() == ISD::AND &&
3522 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3523 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3524 Pos = Pos.getOperand(0);
3525
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003526 // The condition we need is now:
3527 //
3528 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3529 //
3530 // If NegOp1 == Pos then we need:
3531 //
3532 // OpSize & Mask == NegC & Mask
3533 //
3534 // (because "x & Mask" is a truncation and distributes through subtraction).
3535 APInt Width;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003536 if (Pos == NegOp1)
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003537 Width = NegC->getAPIntValue();
Richard Sandiford0f264db2014-01-09 10:49:40 +00003538 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3539 // Then the condition we want to prove becomes:
Richard Sandiford0f264db2014-01-09 10:49:40 +00003540 //
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003541 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3542 //
3543 // which, again because "x & Mask" is a truncation, becomes:
3544 //
3545 // NegC & Mask == (OpSize - PosC) & Mask
3546 // OpSize & Mask == (NegC + PosC) & Mask
3547 else if (Pos.getOpcode() == ISD::ADD &&
3548 Pos.getOperand(0) == NegOp1 &&
3549 Pos.getOperand(1).getOpcode() == ISD::Constant)
3550 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3551 NegC->getAPIntValue());
3552 else
3553 return false;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003554
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003555 // Now we just need to check that OpSize & Mask == Width & Mask.
Adam Nemetc6553a82014-03-07 23:56:24 +00003556 if (MaskLoBits)
3557 // Opsize & Mask is 0 since Mask is Opsize - 1.
3558 return Width.getLoBits(MaskLoBits) == 0;
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003559 return Width == OpSize;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003560}
3561
Richard Sandiford95c864d2014-01-08 15:40:47 +00003562// A subroutine of MatchRotate used once we have found an OR of two opposite
3563// shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3564// to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3565// former being preferred if supported. InnerPos and InnerNeg are Pos and
3566// Neg with outer conversions stripped away.
3567SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3568 SDValue Neg, SDValue InnerPos,
3569 SDValue InnerNeg, unsigned PosOpcode,
3570 unsigned NegOpcode, SDLoc DL) {
Richard Sandiford95c864d2014-01-08 15:40:47 +00003571 // fold (or (shl x, (*ext y)),
3572 // (srl x, (*ext (sub 32, y)))) ->
3573 // (rotl x, y) or (rotr x, (sub 32, y))
3574 //
3575 // fold (or (shl x, (*ext (sub 32, y))),
3576 // (srl x, (*ext y))) ->
3577 // (rotr x, y) or (rotl x, (sub 32, y))
3578 EVT VT = Shifted.getValueType();
Richard Sandiford0f264db2014-01-09 10:49:40 +00003579 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
Richard Sandiford95c864d2014-01-08 15:40:47 +00003580 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3581 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3582 HasPos ? Pos : Neg).getNode();
3583 }
3584
Craig Topperc0196b12014-04-14 00:51:57 +00003585 return nullptr;
Richard Sandiford95c864d2014-01-08 15:40:47 +00003586}
3587
Chris Lattner97614c82006-09-14 20:50:57 +00003588// MatchRotate - Handle an 'or' of two operands. If this is one of the many
3589// idioms for rotate, and if the target supports rotation instructions, generate
3590// a rot[lr].
Andrew Trickef9de2a2013-05-25 02:42:55 +00003591SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
Duncan Sands8651e9c2008-06-13 19:07:40 +00003592 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
Owen Anderson53aa7a92009-08-10 22:56:29 +00003593 EVT VT = LHS.getValueType();
Craig Topperc0196b12014-04-14 00:51:57 +00003594 if (!TLI.isTypeLegal(VT)) return nullptr;
Chris Lattner97614c82006-09-14 20:50:57 +00003595
3596 // The target must have at least one rotate flavor.
Dan Gohman4aa18462009-01-28 17:46:25 +00003597 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3598 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
Craig Topperc0196b12014-04-14 00:51:57 +00003599 if (!HasROTL && !HasROTR) return nullptr;
Duncan Sands8651e9c2008-06-13 19:07:40 +00003600
Chris Lattner97614c82006-09-14 20:50:57 +00003601 // Match "(X shl/srl V1) & V2" where V2 may not be present.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003602 SDValue LHSShift; // The shift.
3603 SDValue LHSMask; // AND value if any.
Chris Lattner97614c82006-09-14 20:50:57 +00003604 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
Craig Topperc0196b12014-04-14 00:51:57 +00003605 return nullptr; // Not part of a rotate.
Chris Lattner97614c82006-09-14 20:50:57 +00003606
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003607 SDValue RHSShift; // The shift.
3608 SDValue RHSMask; // AND value if any.
Chris Lattner97614c82006-09-14 20:50:57 +00003609 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
Craig Topperc0196b12014-04-14 00:51:57 +00003610 return nullptr; // Not part of a rotate.
Scott Michelcf0da6c2009-02-17 22:15:04 +00003611
Chris Lattner97614c82006-09-14 20:50:57 +00003612 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
Craig Topperc0196b12014-04-14 00:51:57 +00003613 return nullptr; // Not shifting the same value.
Chris Lattner97614c82006-09-14 20:50:57 +00003614
3615 if (LHSShift.getOpcode() == RHSShift.getOpcode())
Craig Topperc0196b12014-04-14 00:51:57 +00003616 return nullptr; // Shifts must disagree.
Scott Michelcf0da6c2009-02-17 22:15:04 +00003617
Chris Lattner97614c82006-09-14 20:50:57 +00003618 // Canonicalize shl to left side in a shl/srl pair.
3619 if (RHSShift.getOpcode() == ISD::SHL) {
3620 std::swap(LHS, RHS);
3621 std::swap(LHSShift, RHSShift);
3622 std::swap(LHSMask , RHSMask );
3623 }
3624
Duncan Sands13237ac2008-06-06 12:08:01 +00003625 unsigned OpSizeInBits = VT.getSizeInBits();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003626 SDValue LHSShiftArg = LHSShift.getOperand(0);
3627 SDValue LHSShiftAmt = LHSShift.getOperand(1);
Kai Nacked09bb462013-09-19 23:00:28 +00003628 SDValue RHSShiftArg = RHSShift.getOperand(0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003629 SDValue RHSShiftAmt = RHSShift.getOperand(1);
Chris Lattner97614c82006-09-14 20:50:57 +00003630
3631 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3632 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
Scott Michel16627a52007-04-02 21:36:32 +00003633 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3634 RHSShiftAmt.getOpcode() == ISD::Constant) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00003635 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3636 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
Chris Lattner97614c82006-09-14 20:50:57 +00003637 if ((LShVal + RShVal) != OpSizeInBits)
Craig Topperc0196b12014-04-14 00:51:57 +00003638 return nullptr;
Chris Lattner97614c82006-09-14 20:50:57 +00003639
Craig Topper65161fa2012-09-29 06:54:22 +00003640 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3641 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003642
Chris Lattner97614c82006-09-14 20:50:57 +00003643 // If there is an AND of either shifted operand, apply it to the result.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003644 if (LHSMask.getNode() || RHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003645 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003646
Gabor Greiff304a7a2008-08-28 21:40:38 +00003647 if (LHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003648 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3649 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
Chris Lattner97614c82006-09-14 20:50:57 +00003650 }
Gabor Greiff304a7a2008-08-28 21:40:38 +00003651 if (RHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003652 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3653 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
Chris Lattner97614c82006-09-14 20:50:57 +00003654 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003655
Bill Wendling35972a92009-01-30 21:14:50 +00003656 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
Chris Lattner97614c82006-09-14 20:50:57 +00003657 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003658
Gabor Greiff304a7a2008-08-28 21:40:38 +00003659 return Rot.getNode();
Chris Lattner97614c82006-09-14 20:50:57 +00003660 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003661
Chris Lattner97614c82006-09-14 20:50:57 +00003662 // If there is a mask here, and we have a variable shift, we can't be sure
3663 // that we're masking out the right stuff.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003664 if (LHSMask.getNode() || RHSMask.getNode())
Craig Topperc0196b12014-04-14 00:51:57 +00003665 return nullptr;
Scott Michelcf0da6c2009-02-17 22:15:04 +00003666
Benjamin Kramer64bdb292013-09-24 14:21:28 +00003667 // If the shift amount is sign/zext/any-extended just peel it off.
3668 SDValue LExtOp0 = LHSShiftAmt;
3669 SDValue RExtOp0 = RHSShiftAmt;
Craig Topper5f9791f2012-09-29 07:18:53 +00003670 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3671 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3672 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3673 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3674 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3675 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3676 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3677 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
Benjamin Kramer64bdb292013-09-24 14:21:28 +00003678 LExtOp0 = LHSShiftAmt.getOperand(0);
3679 RExtOp0 = RHSShiftAmt.getOperand(0);
3680 }
3681
Richard Sandiford95c864d2014-01-08 15:40:47 +00003682 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3683 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3684 if (TryL)
3685 return TryL;
3686
3687 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3688 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3689 if (TryR)
3690 return TryR;
Scott Michelcf0da6c2009-02-17 22:15:04 +00003691
Craig Topperc0196b12014-04-14 00:51:57 +00003692 return nullptr;
Chris Lattner97614c82006-09-14 20:50:57 +00003693}
3694
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003695SDValue DAGCombiner::visitXOR(SDNode *N) {
3696 SDValue N0 = N->getOperand(0);
3697 SDValue N1 = N->getOperand(1);
3698 SDValue LHS, RHS, CC;
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003699 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3700 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00003701 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003702
Dan Gohmana8665142007-06-25 16:23:39 +00003703 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00003704 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003705 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003706 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00003707
3708 // fold (xor x, 0) -> x, vector edition
3709 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3710 return N1;
3711 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3712 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00003713 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003714
Evan Chengdf1690d2008-03-25 20:08:07 +00003715 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3716 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3717 return DAG.getConstant(0, VT);
Dan Gohman06563a82007-07-03 14:03:57 +00003718 // fold (xor x, undef) -> undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00003719 if (N0.getOpcode() == ISD::UNDEF)
3720 return N0;
3721 if (N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00003722 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00003723 // fold (xor c1, c2) -> c1^c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003724 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00003725 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003726 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00003727 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003728 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00003729 // fold (xor x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003730 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003731 return N0;
Nate Begeman22e251a2006-02-03 06:46:56 +00003732 // reassociate xor
Andrew Trickef9de2a2013-05-25 02:42:55 +00003733 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003734 if (RXOR.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00003735 return RXOR;
Bill Wendling49a5ce82008-11-11 08:25:46 +00003736
Nate Begeman21158fc2005-09-01 00:19:25 +00003737 // fold !(x cc y) -> (x !cc y)
Dan Gohmanb72127a2008-03-13 22:13:53 +00003738 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
Duncan Sands13237ac2008-06-06 12:08:01 +00003739 bool isInt = LHS.getValueType().isInteger();
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003740 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3741 isInt);
Bill Wendling49a5ce82008-11-11 08:25:46 +00003742
Patrik Hagglundffd057a2012-12-19 10:19:55 +00003743 if (!LegalOperations ||
3744 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
Bill Wendling49a5ce82008-11-11 08:25:46 +00003745 switch (N0.getOpcode()) {
3746 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +00003747 llvm_unreachable("Unhandled SetCC Equivalent!");
Bill Wendling49a5ce82008-11-11 08:25:46 +00003748 case ISD::SETCC:
Andrew Trickef9de2a2013-05-25 02:42:55 +00003749 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
Bill Wendling49a5ce82008-11-11 08:25:46 +00003750 case ISD::SELECT_CC:
Andrew Trickef9de2a2013-05-25 02:42:55 +00003751 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
Bill Wendling49a5ce82008-11-11 08:25:46 +00003752 N0.getOperand(3), NotCC);
3753 }
3754 }
Nate Begeman21158fc2005-09-01 00:19:25 +00003755 }
Bill Wendling49a5ce82008-11-11 08:25:46 +00003756
Chris Lattner58c227b2007-09-10 21:39:07 +00003757 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
Dan Gohmanb72127a2008-03-13 22:13:53 +00003758 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
Gabor Greife12264b2008-08-30 19:29:20 +00003759 N0.getNode()->hasOneUse() &&
3760 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003761 SDValue V = N0.getOperand(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003762 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
Duncan Sands56ab90d2007-10-10 09:54:50 +00003763 DAG.getConstant(1, V.getValueType()));
Gabor Greiff304a7a2008-08-28 21:40:38 +00003764 AddToWorkList(V.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003765 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
Chris Lattner58c227b2007-09-10 21:39:07 +00003766 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003767
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003768 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
Owen Anderson9f944592009-08-11 20:47:22 +00003769 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003770 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003771 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003772 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3773 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
Andrew Trickef9de2a2013-05-25 02:42:55 +00003774 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3775 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
Gabor Greiff304a7a2008-08-28 21:40:38 +00003776 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003777 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
Nate Begeman21158fc2005-09-01 00:19:25 +00003778 }
3779 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003780 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
Scott Michelcf0da6c2009-02-17 22:15:04 +00003781 if (N1C && N1C->isAllOnesValue() &&
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003782 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003783 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003784 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3785 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
Andrew Trickef9de2a2013-05-25 02:42:55 +00003786 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3787 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
Gabor Greiff304a7a2008-08-28 21:40:38 +00003788 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003789 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
Nate Begeman21158fc2005-09-01 00:19:25 +00003790 }
3791 }
David Majnemer386ab7f2013-05-08 06:44:42 +00003792 // fold (xor (and x, y), y) -> (and (not x), y)
3793 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
Benjamin Kramerbb1dd732013-11-17 10:40:03 +00003794 N0->getOperand(1) == N1) {
David Majnemer386ab7f2013-05-08 06:44:42 +00003795 SDValue X = N0->getOperand(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003796 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
David Majnemer386ab7f2013-05-08 06:44:42 +00003797 AddToWorkList(NotX.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003798 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
David Majnemer386ab7f2013-05-08 06:44:42 +00003799 }
Bill Wendling35972a92009-01-30 21:14:50 +00003800 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
Nate Begeman85c1cc42005-09-08 20:18:10 +00003801 if (N1C && N0.getOpcode() == ISD::XOR) {
3802 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3803 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3804 if (N00C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003805 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
Bill Wendling35972a92009-01-30 21:14:50 +00003806 DAG.getConstant(N1C->getAPIntValue() ^
Dan Gohmanb72127a2008-03-13 22:13:53 +00003807 N00C->getAPIntValue(), VT));
Nate Begeman85c1cc42005-09-08 20:18:10 +00003808 if (N01C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003809 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
Bill Wendling35972a92009-01-30 21:14:50 +00003810 DAG.getConstant(N1C->getAPIntValue() ^
Dan Gohmanb72127a2008-03-13 22:13:53 +00003811 N01C->getAPIntValue(), VT));
Nate Begeman85c1cc42005-09-08 20:18:10 +00003812 }
3813 // fold (xor x, x) -> 0
Eric Christophere5ca1e02011-02-16 04:50:12 +00003814 if (N0 == N1)
Hal Finkel6c29bd92013-07-09 17:02:45 +00003815 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003816
Chris Lattner8d6fc202006-05-05 05:51:50 +00003817 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3818 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003819 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003820 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00003821 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003822
Chris Lattner098c01e2006-04-08 04:15:24 +00003823 // Simplify the expression using non-local knowledge.
Duncan Sands13237ac2008-06-06 12:08:01 +00003824 if (!VT.isVector() &&
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003825 SimplifyDemandedBits(SDValue(N, 0)))
3826 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003827
Evan Chengf1005572010-04-28 07:10:39 +00003828 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00003829}
3830
Chris Lattner7c709a52007-12-06 07:33:36 +00003831/// visitShiftByConstant - Handle transforms common to the three shifts, when
3832/// the shift amount is a constant.
Matt Arsenault985b9de2014-03-17 18:58:01 +00003833SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003834 // We can't and shouldn't fold opaque constants.
Matt Arsenault985b9de2014-03-17 18:58:01 +00003835 if (Amt->isOpaque())
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003836 return SDValue();
3837
Gabor Greiff304a7a2008-08-28 21:40:38 +00003838 SDNode *LHS = N->getOperand(0).getNode();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003839 if (!LHS->hasOneUse()) return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003840
Chris Lattner7c709a52007-12-06 07:33:36 +00003841 // We want to pull some binops through shifts, so that we have (and (shift))
3842 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3843 // thing happens with address calculations, so it's important to canonicalize
3844 // it.
3845 bool HighBitSet = false; // Can we transform this if the high bit is set?
Scott Michelcf0da6c2009-02-17 22:15:04 +00003846
Chris Lattner7c709a52007-12-06 07:33:36 +00003847 switch (LHS->getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003848 default: return SDValue();
Chris Lattner7c709a52007-12-06 07:33:36 +00003849 case ISD::OR:
3850 case ISD::XOR:
3851 HighBitSet = false; // We can only transform sra if the high bit is clear.
3852 break;
3853 case ISD::AND:
3854 HighBitSet = true; // We can only transform sra if the high bit is set.
3855 break;
3856 case ISD::ADD:
Scott Michelcf0da6c2009-02-17 22:15:04 +00003857 if (N->getOpcode() != ISD::SHL)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003858 return SDValue(); // only shl(add) not sr[al](add).
Chris Lattner7c709a52007-12-06 07:33:36 +00003859 HighBitSet = false; // We can only transform sra if the high bit is clear.
3860 break;
3861 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003862
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003863 // We require the RHS of the binop to be a constant and not opaque as well.
Chris Lattner7c709a52007-12-06 07:33:36 +00003864 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003865 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003866
3867 // FIXME: disable this unless the input to the binop is a shift by a constant.
3868 // If it is not a shift, it pessimizes some common cases like:
Chris Lattnereedaf922007-12-06 07:47:55 +00003869 //
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003870 // void foo(int *X, int i) { X[i & 1235] = 1; }
3871 // int bar(int *X, int i) { return X[i & 255]; }
Gabor Greiff304a7a2008-08-28 21:40:38 +00003872 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003873 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
Chris Lattnereedaf922007-12-06 07:47:55 +00003874 BinOpLHSVal->getOpcode() != ISD::SRA &&
3875 BinOpLHSVal->getOpcode() != ISD::SRL) ||
3876 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003877 return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003878
Owen Anderson53aa7a92009-08-10 22:56:29 +00003879 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003880
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003881 // If this is a signed shift right, and the high bit is modified by the
3882 // logical operation, do not perform the transformation. The highBitSet
3883 // boolean indicates the value of the high bit of the constant which would
3884 // cause it to be modified for this operation.
Chris Lattner7c709a52007-12-06 07:33:36 +00003885 if (N->getOpcode() == ISD::SRA) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003886 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3887 if (BinOpRHSSignSet != HighBitSet)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003888 return SDValue();
Chris Lattner7c709a52007-12-06 07:33:36 +00003889 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003890
Weiming Zhao7f6daf12014-04-30 21:07:24 +00003891 if (!TLI.isDesirableToCommuteWithShift(LHS))
3892 return SDValue();
3893
Chris Lattner7c709a52007-12-06 07:33:36 +00003894 // Fold the constants, shifting the binop RHS by the shift amount.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003895 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003896 N->getValueType(0),
3897 LHS->getOperand(1), N->getOperand(1));
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003898 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
Chris Lattner7c709a52007-12-06 07:33:36 +00003899
3900 // Create the new shift.
Eric Christopherd9e8eac2010-12-09 04:48:06 +00003901 SDValue NewShift = DAG.getNode(N->getOpcode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00003902 SDLoc(LHS->getOperand(0)),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003903 VT, LHS->getOperand(0), N->getOperand(1));
Chris Lattner7c709a52007-12-06 07:33:36 +00003904
3905 // Create the new binop.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003906 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
Chris Lattner7c709a52007-12-06 07:33:36 +00003907}
3908
Adam Nemet67483892014-03-04 23:28:31 +00003909SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3910 assert(N->getOpcode() == ISD::TRUNCATE);
3911 assert(N->getOperand(0).getOpcode() == ISD::AND);
3912
3913 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3914 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3915 SDValue N01 = N->getOperand(0).getOperand(1);
3916
Matt Arsenault985b9de2014-03-17 18:58:01 +00003917 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
Adam Nemet67483892014-03-04 23:28:31 +00003918 EVT TruncVT = N->getValueType(0);
3919 SDValue N00 = N->getOperand(0).getOperand(0);
3920 APInt TruncC = N01C->getAPIntValue();
Matt Arsenault985b9de2014-03-17 18:58:01 +00003921 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
Adam Nemet67483892014-03-04 23:28:31 +00003922
3923 return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3924 DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
3925 DAG.getConstant(TruncC, TruncVT));
3926 }
3927 }
3928
3929 return SDValue();
3930}
Adam Nemet7f928f12014-03-07 23:56:30 +00003931
3932SDValue DAGCombiner::visitRotate(SDNode *N) {
3933 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
3934 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
3935 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
3936 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
3937 if (NewOp1.getNode())
3938 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
3939 N->getOperand(0), NewOp1);
3940 }
3941 return SDValue();
3942}
3943
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003944SDValue DAGCombiner::visitSHL(SDNode *N) {
3945 SDValue N0 = N->getOperand(0);
3946 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003947 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3948 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00003949 EVT VT = N0.getValueType();
Matt Arsenault985b9de2014-03-17 18:58:01 +00003950 unsigned OpSizeInBits = VT.getScalarSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003951
Daniel Sandersa1840d22013-11-11 17:23:41 +00003952 // fold vector ops
3953 if (VT.isVector()) {
3954 SDValue FoldedVOp = SimplifyVBinOp(N);
3955 if (FoldedVOp.getNode()) return FoldedVOp;
Quentin Colombet4db08df2014-02-21 23:42:41 +00003956
3957 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
3958 // If setcc produces all-one true value then:
3959 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
Matt Arsenault985b9de2014-03-17 18:58:01 +00003960 if (N1CV && N1CV->isConstant()) {
3961 if (N0.getOpcode() == ISD::AND &&
3962 TLI.getBooleanContents(true) ==
3963 TargetLowering::ZeroOrNegativeOneBooleanContent) {
3964 SDValue N00 = N0->getOperand(0);
3965 SDValue N01 = N0->getOperand(1);
3966 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
Quentin Colombet4db08df2014-02-21 23:42:41 +00003967
Matt Arsenault985b9de2014-03-17 18:58:01 +00003968 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC) {
3969 SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
3970 if (C.getNode())
3971 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
3972 }
3973 } else {
3974 N1C = isConstOrConstSplat(N1);
Quentin Colombet4db08df2014-02-21 23:42:41 +00003975 }
3976 }
Daniel Sandersa1840d22013-11-11 17:23:41 +00003977 }
3978
Nate Begeman21158fc2005-09-01 00:19:25 +00003979 // fold (shl c1, c2) -> c1<<c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003980 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00003981 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00003982 // fold (shl 0, x) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003983 if (N0C && N0C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003984 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00003985 // fold (shl x, c >= size(x)) -> undef
Dan Gohmaneffb8942008-09-12 16:56:44 +00003986 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00003987 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00003988 // fold (shl x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003989 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003990 return N0;
Chad Rosier818e1162011-06-14 22:29:10 +00003991 // fold (shl undef, x) -> 0
3992 if (N0.getOpcode() == ISD::UNDEF)
3993 return DAG.getConstant(0, VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00003994 // if (shl x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003995 if (DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1d459e42009-12-11 21:31:27 +00003996 APInt::getAllOnesValue(OpSizeInBits)))
Nate Begemand23739d2005-09-06 04:43:02 +00003997 return DAG.getConstant(0, VT);
Duncan Sands3ed76882009-02-01 18:06:53 +00003998 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00003999 if (N1.getOpcode() == ISD::TRUNCATE &&
Adam Nemet67483892014-03-04 23:28:31 +00004000 N1.getOperand(0).getOpcode() == ISD::AND) {
4001 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4002 if (NewOp1.getNode())
4003 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004004 }
4005
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004006 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4007 return SDValue(N, 0);
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004008
4009 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
Matt Arsenault985b9de2014-03-17 18:58:01 +00004010 if (N1C && N0.getOpcode() == ISD::SHL) {
4011 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4012 uint64_t c1 = N0C1->getZExtValue();
4013 uint64_t c2 = N1C->getZExtValue();
4014 if (c1 + c2 >= OpSizeInBits)
4015 return DAG.getConstant(0, VT);
4016 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4017 DAG.getConstant(c1 + c2, N1.getValueType()));
4018 }
Nate Begeman21158fc2005-09-01 00:19:25 +00004019 }
Dale Johannesena94e36b2010-12-21 21:55:50 +00004020
4021 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4022 // For this to be valid, the second form must not preserve any of the bits
4023 // that are shifted out by the inner shift in the first form. This means
4024 // the outer shift size must be >= the number of bits added by the ext.
4025 // As a corollary, we don't care what kind of ext it is.
4026 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4027 N0.getOpcode() == ISD::ANY_EXTEND ||
4028 N0.getOpcode() == ISD::SIGN_EXTEND) &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004029 N0.getOperand(0).getOpcode() == ISD::SHL) {
4030 SDValue N0Op0 = N0.getOperand(0);
4031 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4032 uint64_t c1 = N0Op0C1->getZExtValue();
4033 uint64_t c2 = N1C->getZExtValue();
4034 EVT InnerShiftVT = N0Op0.getValueType();
4035 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4036 if (c2 >= OpSizeInBits - InnerShiftSize) {
4037 if (c1 + c2 >= OpSizeInBits)
4038 return DAG.getConstant(0, VT);
4039 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4040 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4041 N0Op0->getOperand(0)),
4042 DAG.getConstant(c1 + c2, N1.getValueType()));
4043 }
Dale Johannesena94e36b2010-12-21 21:55:50 +00004044 }
4045 }
4046
Andrea Di Biagio56ce9c42013-09-27 11:37:05 +00004047 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4048 // Only fold this if the inner zext has no other uses to avoid increasing
4049 // the total number of instructions.
4050 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004051 N0.getOperand(0).getOpcode() == ISD::SRL) {
4052 SDValue N0Op0 = N0.getOperand(0);
4053 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4054 uint64_t c1 = N0Op0C1->getZExtValue();
4055 if (c1 < VT.getScalarSizeInBits()) {
4056 uint64_t c2 = N1C->getZExtValue();
4057 if (c1 == c2) {
4058 SDValue NewOp0 = N0.getOperand(0);
4059 EVT CountVT = NewOp0.getOperand(1).getValueType();
4060 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4061 NewOp0, DAG.getConstant(c2, CountVT));
4062 AddToWorkList(NewSHL.getNode());
4063 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4064 }
Andrea Di Biagio56ce9c42013-09-27 11:37:05 +00004065 }
4066 }
4067 }
4068
Eli Friedman1877ac92011-06-09 22:14:44 +00004069 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4070 // (and (srl x, (sub c1, c2), MASK)
Chandler Carruthe041a302012-01-05 11:05:55 +00004071 // Only fold this if the inner shift has no other uses -- if it does, folding
4072 // this will increase the total number of instructions.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004073 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4074 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4075 uint64_t c1 = N0C1->getZExtValue();
4076 if (c1 < OpSizeInBits) {
4077 uint64_t c2 = N1C->getZExtValue();
4078 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4079 SDValue Shift;
4080 if (c2 > c1) {
4081 Mask = Mask.shl(c2 - c1);
4082 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4083 DAG.getConstant(c2 - c1, N1.getValueType()));
4084 } else {
4085 Mask = Mask.lshr(c1 - c2);
4086 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4087 DAG.getConstant(c1 - c2, N1.getValueType()));
4088 }
4089 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4090 DAG.getConstant(Mask, VT));
Eli Friedman1877ac92011-06-09 22:14:44 +00004091 }
Evan Chenga7bb55e2009-07-21 05:40:15 +00004092 }
Nate Begeman21158fc2005-09-01 00:19:25 +00004093 }
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004094 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
Dan Gohman5758e1e2009-08-06 09:18:59 +00004095 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004096 unsigned BitSize = VT.getScalarSizeInBits();
Dan Gohman5758e1e2009-08-06 09:18:59 +00004097 SDValue HiBitsMask =
Matt Arsenault985b9de2014-03-17 18:58:01 +00004098 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4099 BitSize - N1C->getZExtValue()), VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004100 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
Dan Gohman5758e1e2009-08-06 09:18:59 +00004101 HiBitsMask);
4102 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004103
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004104 if (N1C) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004105 SDValue NewSHL = visitShiftByConstant(N, N1C);
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004106 if (NewSHL.getNode())
4107 return NewSHL;
4108 }
4109
Evan Chengf1005572010-04-28 07:10:39 +00004110 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004111}
4112
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004113SDValue DAGCombiner::visitSRA(SDNode *N) {
4114 SDValue N0 = N->getOperand(0);
4115 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004116 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4117 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004118 EVT VT = N0.getValueType();
Dan Gohman1d459e42009-12-11 21:31:27 +00004119 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004120
Daniel Sandersa1840d22013-11-11 17:23:41 +00004121 // fold vector ops
4122 if (VT.isVector()) {
4123 SDValue FoldedVOp = SimplifyVBinOp(N);
4124 if (FoldedVOp.getNode()) return FoldedVOp;
Matt Arsenault985b9de2014-03-17 18:58:01 +00004125
4126 N1C = isConstOrConstSplat(N1);
Daniel Sandersa1840d22013-11-11 17:23:41 +00004127 }
4128
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004129 // fold (sra c1, c2) -> (sra c1, c2)
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004130 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00004131 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00004132 // fold (sra 0, x) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004133 if (N0C && N0C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004134 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004135 // fold (sra -1, x) -> -1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004136 if (N0C && N0C->isAllOnesValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004137 return N0;
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004138 // fold (sra x, (setge c, size(x))) -> undef
Dan Gohman1d459e42009-12-11 21:31:27 +00004139 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00004140 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004141 // fold (sra x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004142 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004143 return N0;
Nate Begemanfb5dbad2006-02-17 19:54:08 +00004144 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4145 // sext_inreg.
4146 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
Dan Gohman1d459e42009-12-11 21:31:27 +00004147 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004148 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4149 if (VT.isVector())
4150 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4151 ExtVT, VT.getVectorNumElements());
4152 if ((!LegalOperations ||
4153 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004154 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004155 N0.getOperand(0), DAG.getValueType(ExtVT));
Nate Begemanfb5dbad2006-02-17 19:54:08 +00004156 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00004157
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004158 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
Chris Lattner0f8a7272006-02-28 06:23:04 +00004159 if (N1C && N0.getOpcode() == ISD::SRA) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004160 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00004161 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
Matt Arsenault985b9de2014-03-17 18:58:01 +00004162 if (Sum >= OpSizeInBits)
4163 Sum = OpSizeInBits - 1;
Andrew Trickef9de2a2013-05-25 02:42:55 +00004164 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
Matt Arsenault985b9de2014-03-17 18:58:01 +00004165 DAG.getConstant(Sum, N1.getValueType()));
Chris Lattner0f8a7272006-02-28 06:23:04 +00004166 }
4167 }
Christopher Lamb8fe91092008-03-19 08:30:06 +00004168
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004169 // fold (sra (shl X, m), (sub result_size, n))
4170 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
Scott Michelcf0da6c2009-02-17 22:15:04 +00004171 // result_size - n != m.
4172 // If truncate is free for the target sext(shl) is likely to result in better
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004173 // code.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004174 if (N0.getOpcode() == ISD::SHL && N1C) {
Christopher Lamb8fe91092008-03-19 08:30:06 +00004175 // Get the two constanst of the shifts, CN0 = m, CN = n.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004176 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4177 if (N01C) {
4178 LLVMContext &Ctx = *DAG.getContext();
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004179 // Determine what the truncate's result bitsize and type would be.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004180 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4181
4182 if (VT.isVector())
4183 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4184
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004185 // Determine the residual right-shift amount.
Torok Edwinbe6a9a12009-05-23 17:29:48 +00004186 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
Duncan Sands8651e9c2008-06-13 19:07:40 +00004187
Scott Michelcf0da6c2009-02-17 22:15:04 +00004188 // If the shift is not a no-op (in which case this should be just a sign
4189 // extend already), the truncated to type is legal, sign_extend is legal
Dan Gohman4a618822010-02-10 16:03:48 +00004190 // on that type, and the truncate to that type is both legal and free,
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004191 // perform the transform.
Torok Edwinbe6a9a12009-05-23 17:29:48 +00004192 if ((ShiftAmt > 0) &&
Dan Gohman4aa18462009-01-28 17:46:25 +00004193 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4194 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
Evan Cheng7a3e7502008-03-20 02:18:41 +00004195 TLI.isTruncateFree(VT, TruncVT)) {
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004196
Owen Andersonb2c80da2011-02-25 21:41:48 +00004197 SDValue Amt = DAG.getConstant(ShiftAmt,
4198 getShiftAmountTy(N0.getOperand(0).getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004199 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004200 N0.getOperand(0), Amt);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004201 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004202 Shift);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004203 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004204 N->getValueType(0), Trunc);
Christopher Lamb8fe91092008-03-19 08:30:06 +00004205 }
4206 }
4207 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004208
Duncan Sands3ed76882009-02-01 18:06:53 +00004209 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004210 if (N1.getOpcode() == ISD::TRUNCATE &&
Adam Nemet67483892014-03-04 23:28:31 +00004211 N1.getOperand(0).getOpcode() == ISD::AND) {
4212 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4213 if (NewOp1.getNode())
4214 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004215 }
4216
Matt Arsenault985b9de2014-03-17 18:58:01 +00004217 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
Benjamin Kramer946e1522011-01-30 16:38:43 +00004218 // if c1 is equal to the number of bits the trunc removes
4219 if (N0.getOpcode() == ISD::TRUNCATE &&
4220 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4221 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4222 N0.getOperand(0).hasOneUse() &&
4223 N0.getOperand(0).getOperand(1).hasOneUse() &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004224 N1C) {
4225 SDValue N0Op0 = N0.getOperand(0);
4226 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4227 unsigned LargeShiftVal = LargeShift->getZExtValue();
4228 EVT LargeVT = N0Op0.getValueType();
Benjamin Kramer946e1522011-01-30 16:38:43 +00004229
Matt Arsenault985b9de2014-03-17 18:58:01 +00004230 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4231 SDValue Amt =
4232 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4233 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4234 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4235 N0Op0.getOperand(0), Amt);
4236 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4237 }
Benjamin Kramer946e1522011-01-30 16:38:43 +00004238 }
4239 }
4240
Scott Michelcf0da6c2009-02-17 22:15:04 +00004241 // Simplify, based on bits shifted out of the LHS.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004242 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4243 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004244
4245
Nate Begeman21158fc2005-09-01 00:19:25 +00004246 // If the sign bit is known to be zero, switch this to a SRL.
Dan Gohman1f372ed2008-02-25 21:11:39 +00004247 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004248 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
Chris Lattner7c709a52007-12-06 07:33:36 +00004249
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004250 if (N1C) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004251 SDValue NewSRA = visitShiftByConstant(N, N1C);
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004252 if (NewSRA.getNode())
4253 return NewSRA;
4254 }
4255
Evan Chengf1005572010-04-28 07:10:39 +00004256 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004257}
4258
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004259SDValue DAGCombiner::visitSRL(SDNode *N) {
4260 SDValue N0 = N->getOperand(0);
4261 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004262 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4263 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004264 EVT VT = N0.getValueType();
Dan Gohman1d459e42009-12-11 21:31:27 +00004265 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004266
Daniel Sandersa1840d22013-11-11 17:23:41 +00004267 // fold vector ops
4268 if (VT.isVector()) {
4269 SDValue FoldedVOp = SimplifyVBinOp(N);
4270 if (FoldedVOp.getNode()) return FoldedVOp;
Matt Arsenault985b9de2014-03-17 18:58:01 +00004271
4272 N1C = isConstOrConstSplat(N1);
Daniel Sandersa1840d22013-11-11 17:23:41 +00004273 }
4274
Nate Begeman21158fc2005-09-01 00:19:25 +00004275 // fold (srl c1, c2) -> c1 >>u c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004276 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00004277 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00004278 // fold (srl 0, x) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004279 if (N0C && N0C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004280 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004281 // fold (srl x, c >= size(x)) -> undef
Dan Gohmaneffb8942008-09-12 16:56:44 +00004282 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00004283 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004284 // fold (srl x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004285 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004286 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004287 // if (srl x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004288 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1f372ed2008-02-25 21:11:39 +00004289 APInt::getAllOnesValue(OpSizeInBits)))
Nate Begemand23739d2005-09-06 04:43:02 +00004290 return DAG.getConstant(0, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004291
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004292 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
Matt Arsenault985b9de2014-03-17 18:58:01 +00004293 if (N1C && N0.getOpcode() == ISD::SRL) {
4294 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4295 uint64_t c1 = N01C->getZExtValue();
4296 uint64_t c2 = N1C->getZExtValue();
4297 if (c1 + c2 >= OpSizeInBits)
4298 return DAG.getConstant(0, VT);
4299 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4300 DAG.getConstant(c1 + c2, N1.getValueType()));
4301 }
Nate Begeman21158fc2005-09-01 00:19:25 +00004302 }
Wesley Peck527da1b2010-11-23 03:31:01 +00004303
Dale Johannesencd538af2010-12-17 21:45:49 +00004304 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
Dale Johannesencd538af2010-12-17 21:45:49 +00004305 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4306 N0.getOperand(0).getOpcode() == ISD::SRL &&
Dale Johannesen0a291a32010-12-20 20:10:50 +00004307 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
Owen Andersonb2c80da2011-02-25 21:41:48 +00004308 uint64_t c1 =
Dale Johannesencd538af2010-12-17 21:45:49 +00004309 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4310 uint64_t c2 = N1C->getZExtValue();
Dale Johannesena94e36b2010-12-21 21:55:50 +00004311 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4312 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
Dale Johannesencd538af2010-12-17 21:45:49 +00004313 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
Dale Johannesen0a291a32010-12-20 20:10:50 +00004314 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
Dale Johannesencd538af2010-12-17 21:45:49 +00004315 if (c1 + OpSizeInBits == InnerShiftSize) {
4316 if (c1 + c2 >= InnerShiftSize)
4317 return DAG.getConstant(0, VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004318 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4319 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
Dale Johannesencd538af2010-12-17 21:45:49 +00004320 N0.getOperand(0)->getOperand(0),
Dale Johannesena94e36b2010-12-21 21:55:50 +00004321 DAG.getConstant(c1 + c2, ShiftCountVT)));
Dale Johannesencd538af2010-12-17 21:45:49 +00004322 }
4323 }
4324
Chris Lattnerf9b2e3c2010-04-15 05:28:43 +00004325 // fold (srl (shl x, c), c) -> (and x, cst2)
Matt Arsenault985b9de2014-03-17 18:58:01 +00004326 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4327 unsigned BitSize = N0.getScalarValueSizeInBits();
4328 if (BitSize <= 64) {
4329 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4330 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4331 DAG.getConstant(~0ULL >> ShAmt, VT));
4332 }
Chris Lattnerf9b2e3c2010-04-15 05:28:43 +00004333 }
Wesley Peck527da1b2010-11-23 03:31:01 +00004334
Michael Liao62ebfd82013-06-21 18:45:27 +00004335 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004336 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4337 // Shifting in all undef bits?
Owen Anderson53aa7a92009-08-10 22:56:29 +00004338 EVT SmallVT = N0.getOperand(0).getValueType();
Matt Arsenault985b9de2014-03-17 18:58:01 +00004339 unsigned BitSize = SmallVT.getScalarSizeInBits();
4340 if (N1C->getZExtValue() >= BitSize)
Dale Johannesen84935752009-02-06 23:05:02 +00004341 return DAG.getUNDEF(VT);
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004342
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004343 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
Owen Andersona5192842011-04-14 17:30:49 +00004344 uint64_t ShiftAmt = N1C->getZExtValue();
Andrew Trickef9de2a2013-05-25 02:42:55 +00004345 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
Owen Andersona5192842011-04-14 17:30:49 +00004346 N0.getOperand(0),
4347 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004348 AddToWorkList(SmallShift.getNode());
Matt Arsenault985b9de2014-03-17 18:58:01 +00004349 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
Michael Liao62ebfd82013-06-21 18:45:27 +00004350 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4351 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4352 DAG.getConstant(Mask, VT));
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004353 }
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004354 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004355
Chris Lattner2e33fb42006-10-12 20:23:19 +00004356 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4357 // bit, which is unmodified by sra.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004358 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
Chris Lattner2e33fb42006-10-12 20:23:19 +00004359 if (N0.getOpcode() == ISD::SRA)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004360 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
Chris Lattner2e33fb42006-10-12 20:23:19 +00004361 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004362
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00004363 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
Scott Michelcf0da6c2009-02-17 22:15:04 +00004364 if (N1C && N0.getOpcode() == ISD::CTLZ &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004365 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004366 APInt KnownZero, KnownOne;
Jay Foada0653a32014-05-14 21:14:37 +00004367 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004368
Chris Lattner49932492006-04-02 06:11:11 +00004369 // If any of the input bits are KnownOne, then the input couldn't be all
4370 // zeros, thus the result of the srl will always be zero.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004371 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004372
Chris Lattner49932492006-04-02 06:11:11 +00004373 // If all of the bits input the to ctlz node are known to be zero, then
4374 // the result of the ctlz is "32" and the result of the shift is one.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00004375 APInt UnknownBits = ~KnownZero;
Chris Lattner49932492006-04-02 06:11:11 +00004376 if (UnknownBits == 0) return DAG.getConstant(1, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004377
Chris Lattner49932492006-04-02 06:11:11 +00004378 // Otherwise, check to see if there is exactly one bit input to the ctlz.
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004379 if ((UnknownBits & (UnknownBits - 1)) == 0) {
Chris Lattner49932492006-04-02 06:11:11 +00004380 // Okay, we know that only that the single bit specified by UnknownBits
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004381 // could be set on input to the CTLZ node. If this bit is set, the SRL
4382 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4383 // to an SRL/XOR pair, which is likely to simplify more.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004384 unsigned ShAmt = UnknownBits.countTrailingZeros();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004385 SDValue Op = N0.getOperand(0);
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004386
Chris Lattner49932492006-04-02 06:11:11 +00004387 if (ShAmt) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004388 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
Owen Andersonb2c80da2011-02-25 21:41:48 +00004389 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
Gabor Greiff304a7a2008-08-28 21:40:38 +00004390 AddToWorkList(Op.getNode());
Chris Lattner49932492006-04-02 06:11:11 +00004391 }
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004392
Andrew Trickef9de2a2013-05-25 02:42:55 +00004393 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004394 Op, DAG.getConstant(1, VT));
Chris Lattner49932492006-04-02 06:11:11 +00004395 }
4396 }
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004397
Duncan Sands3ed76882009-02-01 18:06:53 +00004398 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004399 if (N1.getOpcode() == ISD::TRUNCATE &&
Adam Nemet67483892014-03-04 23:28:31 +00004400 N1.getOperand(0).getOpcode() == ISD::AND) {
4401 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4402 if (NewOp1.getNode())
4403 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004404 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004405
Chris Lattnerf03c90b2007-04-18 03:06:49 +00004406 // fold operands of srl based on knowledge that the low bits are not
4407 // demanded.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004408 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4409 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004410
Evan Chengb175de62009-12-18 21:31:31 +00004411 if (N1C) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004412 SDValue NewSRL = visitShiftByConstant(N, N1C);
Evan Chengb175de62009-12-18 21:31:31 +00004413 if (NewSRL.getNode())
4414 return NewSRL;
4415 }
4416
Dan Gohman600f62b2010-06-24 14:30:44 +00004417 // Attempt to convert a srl of a load into a narrower zero-extending load.
4418 SDValue NarrowLoad = ReduceLoadWidth(N);
4419 if (NarrowLoad.getNode())
4420 return NarrowLoad;
4421
Evan Chengb175de62009-12-18 21:31:31 +00004422 // Here is a common situation. We want to optimize:
4423 //
4424 // %a = ...
4425 // %b = and i32 %a, 2
4426 // %c = srl i32 %b, 1
4427 // brcond i32 %c ...
4428 //
4429 // into
Wesley Peck527da1b2010-11-23 03:31:01 +00004430 //
Evan Chengb175de62009-12-18 21:31:31 +00004431 // %a = ...
4432 // %b = and %a, 2
4433 // %c = setcc eq %b, 0
4434 // brcond %c ...
4435 //
4436 // However when after the source operand of SRL is optimized into AND, the SRL
4437 // itself may not be optimized further. Look for it and add the BRCOND into
4438 // the worklist.
Evan Cheng166a4e62010-01-06 19:38:29 +00004439 if (N->hasOneUse()) {
4440 SDNode *Use = *N->use_begin();
4441 if (Use->getOpcode() == ISD::BRCOND)
4442 AddToWorkList(Use);
4443 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4444 // Also look pass the truncate.
4445 Use = *Use->use_begin();
4446 if (Use->getOpcode() == ISD::BRCOND)
4447 AddToWorkList(Use);
4448 }
4449 }
Evan Chengb175de62009-12-18 21:31:31 +00004450
Evan Chengf1005572010-04-28 07:10:39 +00004451 return SDValue();
Evan Chenge19aa5c2010-04-19 19:29:22 +00004452}
4453
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004454SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4455 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004456 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00004457
4458 // fold (ctlz c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004459 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004460 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004461 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004462}
4463
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004464SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4465 SDValue N0 = N->getOperand(0);
4466 EVT VT = N->getValueType(0);
4467
4468 // fold (ctlz_zero_undef c1) -> c2
4469 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004470 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004471 return SDValue();
4472}
4473
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004474SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4475 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004476 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004477
Nate Begeman21158fc2005-09-01 00:19:25 +00004478 // fold (cttz c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004479 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004480 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004481 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004482}
4483
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004484SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4485 SDValue N0 = N->getOperand(0);
4486 EVT VT = N->getValueType(0);
4487
4488 // fold (cttz_zero_undef c1) -> c2
4489 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004490 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004491 return SDValue();
4492}
4493
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004494SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4495 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004496 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004497
Nate Begeman21158fc2005-09-01 00:19:25 +00004498 // fold (ctpop c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004499 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004500 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004501 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004502}
4503
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004504SDValue DAGCombiner::visitSELECT(SDNode *N) {
4505 SDValue N0 = N->getOperand(0);
4506 SDValue N1 = N->getOperand(1);
4507 SDValue N2 = N->getOperand(2);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004508 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4509 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4510 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004511 EVT VT = N->getValueType(0);
4512 EVT VT0 = N0.getValueType();
Nate Begemanc760f802005-09-19 22:34:01 +00004513
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004514 // fold (select C, X, X) -> X
Nate Begeman24a7eca2005-09-16 00:54:12 +00004515 if (N1 == N2)
4516 return N1;
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004517 // fold (select true, X, Y) -> X
Nate Begeman24a7eca2005-09-16 00:54:12 +00004518 if (N0C && !N0C->isNullValue())
4519 return N1;
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004520 // fold (select false, X, Y) -> Y
Nate Begeman24a7eca2005-09-16 00:54:12 +00004521 if (N0C && N0C->isNullValue())
4522 return N2;
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004523 // fold (select C, 1, X) -> (or C, X)
Owen Anderson9f944592009-08-11 20:47:22 +00004524 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004525 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004526 // fold (select C, 0, 1) -> (xor C, 1)
Bob Wilsonc2dc7ee2009-01-22 22:05:48 +00004527 if (VT.isInteger() &&
Owen Anderson9f944592009-08-11 20:47:22 +00004528 (VT0 == MVT::i1 ||
Bob Wilsonc2dc7ee2009-01-22 22:05:48 +00004529 (VT0.isInteger() &&
Nadav Rotem841c9a82012-09-20 08:53:31 +00004530 TLI.getBooleanContents(false) ==
4531 TargetLowering::ZeroOrOneBooleanContent)) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00004532 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004533 SDValue XORNode;
Evan Chengf5a23ab2007-08-18 05:57:05 +00004534 if (VT == VT0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004535 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004536 N0, DAG.getConstant(1, VT0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004537 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004538 N0, DAG.getConstant(1, VT0));
Gabor Greiff304a7a2008-08-28 21:40:38 +00004539 AddToWorkList(XORNode.getNode());
Duncan Sands11dd4242008-06-08 20:54:56 +00004540 if (VT.bitsGT(VT0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004541 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4542 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
Evan Chengf5a23ab2007-08-18 05:57:05 +00004543 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004544 // fold (select C, 0, X) -> (and (not C), X)
Owen Anderson9f944592009-08-11 20:47:22 +00004545 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004546 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
Bob Wilsonc5890052009-01-22 17:39:32 +00004547 AddToWorkList(NOTNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004548 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004549 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004550 // fold (select C, X, 1) -> (or (not C), X)
Owen Anderson9f944592009-08-11 20:47:22 +00004551 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004552 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
Bob Wilsonc5890052009-01-22 17:39:32 +00004553 AddToWorkList(NOTNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004554 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004555 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004556 // fold (select C, X, 0) -> (and C, X)
Owen Anderson9f944592009-08-11 20:47:22 +00004557 if (VT == MVT::i1 && N2C && N2C->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00004558 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004559 // fold (select X, X, Y) -> (or X, Y)
4560 // fold (select X, 1, Y) -> (or X, Y)
Owen Anderson9f944592009-08-11 20:47:22 +00004561 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004562 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004563 // fold (select X, Y, X) -> (and X, Y)
4564 // fold (select X, Y, 0) -> (and X, Y)
Owen Anderson9f944592009-08-11 20:47:22 +00004565 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004566 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004567
Chris Lattner6c14c352005-10-18 06:04:22 +00004568 // If we can fold this based on the true/false value, do so.
4569 if (SimplifySelectOps(N, N1, N2))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004570 return SDValue(N, 0); // Don't revisit N.
Duncan Sands8651e9c2008-06-13 19:07:40 +00004571
Nate Begemanc760f802005-09-19 22:34:01 +00004572 // fold selects based on a setcc into other things, such as min/max/abs
Anton Korobeynikov035eaac2008-02-20 11:10:28 +00004573 if (N0.getOpcode() == ISD::SETCC) {
Tom Stellard3787b122014-06-10 16:01:29 +00004574 if ((!LegalOperations &&
4575 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4576 TLI.isOperationLegal(ISD::SELECT_CC, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004577 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004578 N0.getOperand(0), N0.getOperand(1),
Nate Begeman7e7f4392006-02-01 07:19:44 +00004579 N1, N2, N0.getOperand(2));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004580 return SimplifySelect(SDLoc(N), N0, N1, N2);
Anton Korobeynikov035eaac2008-02-20 11:10:28 +00004581 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004582
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004583 return SDValue();
Nate Begeman24a7eca2005-09-16 00:54:12 +00004584}
4585
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004586static
4587std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4588 SDLoc DL(N);
4589 EVT LoVT, HiVT;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +00004590 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004591
4592 // Split the inputs.
4593 SDValue Lo, Hi, LL, LH, RL, RH;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +00004594 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4595 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004596
4597 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4598 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4599
4600 return std::make_pair(Lo, Hi);
4601}
4602
Filipe Cabecinhas82111f12014-05-30 23:03:11 +00004603// This function assumes all the vselect's arguments are CONCAT_VECTOR
4604// nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4605static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4606 SDLoc dl(N);
4607 SDValue Cond = N->getOperand(0);
4608 SDValue LHS = N->getOperand(1);
4609 SDValue RHS = N->getOperand(2);
4610 MVT VT = N->getSimpleValueType(0);
4611 int NumElems = VT.getVectorNumElements();
4612 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4613 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4614 Cond.getOpcode() == ISD::BUILD_VECTOR);
4615
4616 // We're sure we have an even number of elements due to the
4617 // concat_vectors we have as arguments to vselect.
4618 // Skip BV elements until we find one that's not an UNDEF
4619 // After we find an UNDEF element, keep looping until we get to half the
4620 // length of the BV and see if all the non-undef nodes are the same.
4621 ConstantSDNode *BottomHalf = nullptr;
4622 for (int i = 0; i < NumElems / 2; ++i) {
4623 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4624 continue;
4625
4626 if (BottomHalf == nullptr)
4627 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4628 else if (Cond->getOperand(i).getNode() != BottomHalf)
4629 return SDValue();
4630 }
4631
4632 // Do the same for the second half of the BuildVector
4633 ConstantSDNode *TopHalf = nullptr;
4634 for (int i = NumElems / 2; i < NumElems; ++i) {
4635 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4636 continue;
4637
4638 if (TopHalf == nullptr)
4639 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4640 else if (Cond->getOperand(i).getNode() != TopHalf)
4641 return SDValue();
4642 }
4643
4644 assert(TopHalf && BottomHalf &&
4645 "One half of the selector was all UNDEFs and the other was all the "
4646 "same value. This should have been addressed before this function.");
4647 return DAG.getNode(
4648 ISD::CONCAT_VECTORS, dl, VT,
4649 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4650 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4651}
4652
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00004653SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4654 SDValue N0 = N->getOperand(0);
4655 SDValue N1 = N->getOperand(1);
4656 SDValue N2 = N->getOperand(2);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004657 SDLoc DL(N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00004658
4659 // Canonicalize integer abs.
4660 // vselect (setg[te] X, 0), X, -X ->
4661 // vselect (setgt X, -1), X, -X ->
4662 // vselect (setl[te] X, 0), -X, X ->
4663 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4664 if (N0.getOpcode() == ISD::SETCC) {
4665 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4666 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4667 bool isAbs = false;
4668 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4669
4670 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4671 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4672 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4673 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4674 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4675 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4676 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4677
4678 if (isAbs) {
4679 EVT VT = LHS.getValueType();
4680 SDValue Shift = DAG.getNode(
4681 ISD::SRA, DL, VT, LHS,
4682 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4683 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4684 AddToWorkList(Shift.getNode());
4685 AddToWorkList(Add.getNode());
4686 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4687 }
4688 }
4689
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004690 // If the VSELECT result requires splitting and the mask is provided by a
4691 // SETCC, then split both nodes and its operands before legalization. This
4692 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4693 // and enables future optimizations (e.g. min/max pattern matching on X86).
4694 if (N0.getOpcode() == ISD::SETCC) {
4695 EVT VT = N->getValueType(0);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004696
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004697 // Check if any splitting is required.
4698 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4699 TargetLowering::TypeSplitVector)
4700 return SDValue();
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004701
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004702 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +00004703 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4704 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4705 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004706
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004707 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4708 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004709
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004710 // Add the new VSELECT nodes to the work list in case they need to be split
4711 // again.
4712 AddToWorkList(Lo.getNode());
4713 AddToWorkList(Hi.getNode());
4714
4715 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004716 }
4717
Andrea Di Biagio23df4e42014-01-08 18:33:04 +00004718 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4719 if (ISD::isBuildVectorAllOnes(N0.getNode()))
4720 return N1;
4721 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4722 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4723 return N2;
4724
Filipe Cabecinhas82111f12014-05-30 23:03:11 +00004725 // The ConvertSelectToConcatVector function is assuming both the above
4726 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
4727 // and addressed.
4728 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
4729 N2.getOpcode() == ISD::CONCAT_VECTORS &&
4730 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
4731 SDValue CV = ConvertSelectToConcatVector(N, DAG);
4732 if (CV.getNode())
4733 return CV;
4734 }
4735
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00004736 return SDValue();
4737}
4738
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004739SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4740 SDValue N0 = N->getOperand(0);
4741 SDValue N1 = N->getOperand(1);
4742 SDValue N2 = N->getOperand(2);
4743 SDValue N3 = N->getOperand(3);
4744 SDValue N4 = N->getOperand(4);
Nate Begemanc760f802005-09-19 22:34:01 +00004745 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004746
Nate Begemanc760f802005-09-19 22:34:01 +00004747 // fold select_cc lhs, rhs, x, x, cc -> x
4748 if (N2 == N3)
4749 return N2;
Scott Michelcf0da6c2009-02-17 22:15:04 +00004750
Chris Lattner8b68dec2006-09-20 06:19:26 +00004751 // Determine if the condition we're dealing with is constant
Matt Arsenault758659232013-05-18 00:21:46 +00004752 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00004753 N0, N1, CC, SDLoc(N), false);
Stephen Lin605207f2013-06-15 04:03:33 +00004754 if (SCC.getNode()) {
4755 AddToWorkList(SCC.getNode());
Chris Lattner8b68dec2006-09-20 06:19:26 +00004756
Stephen Lin605207f2013-06-15 04:03:33 +00004757 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4758 if (!SCCC->isNullValue())
4759 return N2; // cond always true -> true val
4760 else
4761 return N3; // cond always false -> false val
4762 }
4763
4764 // Fold to a simpler select_cc
4765 if (SCC.getOpcode() == ISD::SETCC)
4766 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4767 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4768 SCC.getOperand(2));
Chris Lattner8b68dec2006-09-20 06:19:26 +00004769 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004770
Chris Lattner6c14c352005-10-18 06:04:22 +00004771 // If we can fold this based on the true/false value, do so.
4772 if (SimplifySelectOps(N, N2, N3))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004773 return SDValue(N, 0); // Don't revisit N.
Scott Michelcf0da6c2009-02-17 22:15:04 +00004774
Nate Begemanc760f802005-09-19 22:34:01 +00004775 // fold select_cc into other things, such as min/max/abs
Andrew Trickef9de2a2013-05-25 02:42:55 +00004776 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004777}
4778
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004779SDValue DAGCombiner::visitSETCC(SDNode *N) {
Nate Begeman24a7eca2005-09-16 00:54:12 +00004780 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
Dale Johannesenf1163e92009-02-03 00:47:48 +00004781 cast<CondCodeSDNode>(N->getOperand(2))->get(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00004782 SDLoc(N));
Nate Begeman24a7eca2005-09-16 00:54:12 +00004783}
4784
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004785// tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4786// dag node into a ConstantSDNode or a build_vector of constants.
4787// This function is called by the DAGCombiner when visiting sext/zext/aext
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00004788// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004789// Vector extends are not folded if operations are legal; this is to
4790// avoid introducing illegal build_vector dag nodes.
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004791static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4792 SelectionDAG &DAG, bool LegalTypes,
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004793 bool LegalOperations) {
4794 unsigned Opcode = N->getOpcode();
4795 SDValue N0 = N->getOperand(0);
4796 EVT VT = N->getValueType(0);
4797
4798 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4799 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4800
4801 // fold (sext c1) -> c1
4802 // fold (zext c1) -> c1
4803 // fold (aext c1) -> c1
4804 if (isa<ConstantSDNode>(N0))
4805 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4806
4807 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4808 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4809 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004810 EVT SVT = VT.getScalarType();
4811 if (!(VT.isVector() &&
4812 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004813 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
Craig Topperc0196b12014-04-14 00:51:57 +00004814 return nullptr;
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00004815
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004816 // We can fold this node into a build_vector.
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004817 unsigned VTBits = SVT.getSizeInBits();
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004818 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4819 unsigned ShAmt = VTBits - EVTBits;
4820 SmallVector<SDValue, 8> Elts;
4821 unsigned NumElts = N0->getNumOperands();
4822 SDLoc DL(N);
4823
4824 for (unsigned i=0; i != NumElts; ++i) {
4825 SDValue Op = N0->getOperand(i);
4826 if (Op->getOpcode() == ISD::UNDEF) {
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004827 Elts.push_back(DAG.getUNDEF(SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004828 continue;
4829 }
4830
4831 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4832 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4833 if (Opcode == ISD::SIGN_EXTEND)
4834 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004835 SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004836 else
4837 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004838 SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004839 }
4840
Craig Topper48d114b2014-04-26 18:35:24 +00004841 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004842}
4843
Evan Chenge106e2f2007-10-29 19:58:20 +00004844// ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
Dan Gohman0e8d1992009-04-09 03:51:29 +00004845// "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
Evan Chenge106e2f2007-10-29 19:58:20 +00004846// transformation. Returns true if extension are possible and the above
Scott Michelcf0da6c2009-02-17 22:15:04 +00004847// mentioned transformation is profitable.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004848static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
Evan Chenge106e2f2007-10-29 19:58:20 +00004849 unsigned ExtOpc,
Craig Topperb94011f2013-07-14 04:42:23 +00004850 SmallVectorImpl<SDNode *> &ExtendNodes,
Dan Gohman619ef482009-01-15 19:20:50 +00004851 const TargetLowering &TLI) {
Evan Chenge106e2f2007-10-29 19:58:20 +00004852 bool HasCopyToRegUses = false;
4853 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
Gabor Greife12264b2008-08-30 19:29:20 +00004854 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4855 UE = N0.getNode()->use_end();
Evan Chenge106e2f2007-10-29 19:58:20 +00004856 UI != UE; ++UI) {
Dan Gohman91e5dcb2008-07-27 20:43:25 +00004857 SDNode *User = *UI;
Evan Chenge106e2f2007-10-29 19:58:20 +00004858 if (User == N)
4859 continue;
Dan Gohman0e8d1992009-04-09 03:51:29 +00004860 if (UI.getUse().getResNo() != N0.getResNo())
4861 continue;
Evan Chenge106e2f2007-10-29 19:58:20 +00004862 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
Dan Gohman0e8d1992009-04-09 03:51:29 +00004863 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
Evan Chenge106e2f2007-10-29 19:58:20 +00004864 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4865 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4866 // Sign bits will be lost after a zext.
4867 return false;
4868 bool Add = false;
4869 for (unsigned i = 0; i != 2; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004870 SDValue UseOp = User->getOperand(i);
Evan Chenge106e2f2007-10-29 19:58:20 +00004871 if (UseOp == N0)
4872 continue;
4873 if (!isa<ConstantSDNode>(UseOp))
4874 return false;
4875 Add = true;
4876 }
4877 if (Add)
4878 ExtendNodes.push_back(User);
Dan Gohman0e8d1992009-04-09 03:51:29 +00004879 continue;
Evan Chenge106e2f2007-10-29 19:58:20 +00004880 }
Dan Gohman0e8d1992009-04-09 03:51:29 +00004881 // If truncates aren't free and there are users we can't
4882 // extend, it isn't worthwhile.
4883 if (!isTruncFree)
4884 return false;
4885 // Remember if this value is live-out.
4886 if (User->getOpcode() == ISD::CopyToReg)
4887 HasCopyToRegUses = true;
Evan Chenge106e2f2007-10-29 19:58:20 +00004888 }
4889
4890 if (HasCopyToRegUses) {
4891 bool BothLiveOut = false;
4892 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4893 UI != UE; ++UI) {
Dan Gohman0e8d1992009-04-09 03:51:29 +00004894 SDUse &Use = UI.getUse();
4895 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4896 BothLiveOut = true;
4897 break;
Evan Chenge106e2f2007-10-29 19:58:20 +00004898 }
4899 }
4900 if (BothLiveOut)
4901 // Both unextended and extended values are live out. There had better be
Bob Wilsonf9b96c42010-11-28 06:51:19 +00004902 // a good reason for the transformation.
Evan Chenge106e2f2007-10-29 19:58:20 +00004903 return ExtendNodes.size();
4904 }
4905 return true;
4906}
4907
Craig Toppere0b71182013-07-13 07:43:40 +00004908void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
Andrew Trickef9de2a2013-05-25 02:42:55 +00004909 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004910 ISD::NodeType ExtType) {
4911 // Extend SetCC uses if necessary.
4912 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4913 SDNode *SetCC = SetCCs[i];
4914 SmallVector<SDValue, 4> Ops;
4915
4916 for (unsigned j = 0; j != 2; ++j) {
4917 SDValue SOp = SetCC->getOperand(j);
4918 if (SOp == Trunc)
4919 Ops.push_back(ExtLoad);
4920 else
4921 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4922 }
4923
4924 Ops.push_back(SetCC->getOperand(2));
Craig Topper48d114b2014-04-26 18:35:24 +00004925 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004926 }
4927}
4928
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004929SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4930 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004931 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00004932
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004933 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
4934 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004935 return SDValue(Res, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004936
Nadav Rotem9450fcf2013-01-20 08:35:56 +00004937 // fold (sext (sext x)) -> (sext x)
4938 // fold (sext (aext x)) -> (sext x)
4939 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004940 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
Nadav Rotem9450fcf2013-01-20 08:35:56 +00004941 N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00004942
Chris Lattnerfce448f2007-02-26 03:13:59 +00004943 if (N0.getOpcode() == ISD::TRUNCATE) {
Dan Gohmanc1a4e212008-05-20 20:56:33 +00004944 // fold (sext (truncate (load x))) -> (sext (smaller load x))
4945 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00004946 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4947 if (NarrowLoad.getNode()) {
Dale Johannesenff384ad2010-05-25 17:50:03 +00004948 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4949 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00004950 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesenff384ad2010-05-25 17:50:03 +00004951 // CombineTo deleted the truncate, if needed, but not what's under it.
4952 AddToWorkList(oye);
4953 }
Dan Gohmanbe36f5c2009-04-27 02:00:55 +00004954 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00004955 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00004956
Dan Gohmanc1a4e212008-05-20 20:56:33 +00004957 // See if the value being truncated is already sign extended. If so, just
4958 // eliminate the trunc/sext pair.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004959 SDValue Op = N0.getOperand(0);
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004960 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
4961 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
4962 unsigned DestBits = VT.getScalarType().getSizeInBits();
Dan Gohman309d3d52007-06-22 14:59:07 +00004963 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004964
Chris Lattnerfce448f2007-02-26 03:13:59 +00004965 if (OpBits == DestBits) {
4966 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
4967 // bits, it is already ready.
4968 if (NumSignBits > DestBits-MidBits)
4969 return Op;
4970 } else if (OpBits < DestBits) {
4971 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
4972 // bits, just sext from i32.
4973 if (NumSignBits > OpBits-MidBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004974 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
Chris Lattnerfce448f2007-02-26 03:13:59 +00004975 } else {
4976 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
4977 // bits, just truncate to i32.
4978 if (NumSignBits > OpBits-MidBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004979 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chris Lattnera31f0a62006-09-21 06:00:20 +00004980 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004981
Chris Lattnerfce448f2007-02-26 03:13:59 +00004982 // fold (sext (truncate x)) -> (sextinreg x).
Duncan Sandsdc2dac12008-11-24 14:53:14 +00004983 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4984 N0.getValueType())) {
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004985 if (OpBits < DestBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004986 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004987 else if (OpBits > DestBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004988 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
4989 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004990 DAG.getValueType(N0.getValueType()));
Chris Lattnerfce448f2007-02-26 03:13:59 +00004991 }
Chris Lattnera31f0a62006-09-21 06:00:20 +00004992 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004993
Evan Chengbce7c472005-12-14 02:19:23 +00004994 // fold (sext (load x)) -> (sext (truncate (sextload x)))
Nadav Rotem502f1b92011-02-24 21:01:34 +00004995 // None of the supported targets knows how to perform load and sign extend
Nadav Rotemb0091302011-02-27 07:40:43 +00004996 // on vectors in one instruction. We only perform this transformation on
4997 // scalars.
Nadav Rotem502f1b92011-02-24 21:01:34 +00004998 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Quentin Colombet0b1a5582014-04-09 20:03:05 +00004999 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005000 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005001 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
Evan Chenge106e2f2007-10-29 19:58:20 +00005002 bool DoXform = true;
5003 SmallVector<SDNode*, 4> SetCCs;
5004 if (!N0.hasOneUse())
5005 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5006 if (DoXform) {
5007 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005008 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Dan Gohman0e8d1992009-04-09 03:51:29 +00005009 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005010 LN0->getBasePtr(), N0.getValueType(),
5011 LN0->getMemOperand());
Evan Chenge106e2f2007-10-29 19:58:20 +00005012 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005013 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00005014 N0.getValueType(), ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005015 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005016 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005017 ISD::SIGN_EXTEND);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005018 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenge106e2f2007-10-29 19:58:20 +00005019 }
Nate Begeman8caf81d2005-10-12 20:40:40 +00005020 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005021
5022 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5023 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00005024 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5025 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005026 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00005027 EVT MemVT = LN0->getMemoryVT();
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005028 if ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00005029 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005030 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005031 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005032 LN0->getBasePtr(), MemVT,
5033 LN0->getMemOperand());
Jim Laskey26df19a2006-12-15 21:38:30 +00005034 CombineTo(N, ExtLoad);
Gabor Greife12264b2008-08-30 19:29:20 +00005035 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005036 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00005037 N0.getValueType(), ExtLoad),
Jim Laskey26df19a2006-12-15 21:38:30 +00005038 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005039 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Jim Laskey26df19a2006-12-15 21:38:30 +00005040 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005041 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005042
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005043 // fold (sext (and/or/xor (load x), cst)) ->
5044 // (and/or/xor (sextload x), (sext cst))
5045 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5046 N0.getOpcode() == ISD::XOR) &&
5047 isa<LoadSDNode>(N0.getOperand(0)) &&
5048 N0.getOperand(1).getOpcode() == ISD::Constant &&
5049 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
5050 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5051 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005052 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005053 bool DoXform = true;
5054 SmallVector<SDNode*, 4> SetCCs;
5055 if (!N0.hasOneUse())
5056 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5057 SetCCs, TLI);
5058 if (DoXform) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005059 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005060 LN0->getChain(), LN0->getBasePtr(),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005061 LN0->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005062 LN0->getMemOperand());
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005063 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5064 Mask = Mask.sext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005065 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005066 ExtLoad, DAG.getConstant(Mask, VT));
5067 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00005068 SDLoc(N0.getOperand(0)),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005069 N0.getOperand(0).getValueType(), ExtLoad);
5070 CombineTo(N, And);
5071 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005072 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005073 ISD::SIGN_EXTEND);
5074 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5075 }
5076 }
5077 }
5078
Chris Lattner65786b02007-04-11 05:32:27 +00005079 if (N0.getOpcode() == ISD::SETCC) {
Chris Lattner4ac60732009-07-08 00:31:33 +00005080 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
Dan Gohmane82c25e2010-04-30 17:19:19 +00005081 // Only do this before legalize for now.
Owen Anderson2d4cca32013-04-23 18:09:28 +00005082 if (VT.isVector() && !LegalOperations &&
Stephen Lincfe7f352013-07-08 00:37:03 +00005083 TLI.getBooleanContents(true) ==
Owen Anderson2d4cca32013-04-23 18:09:28 +00005084 TargetLowering::ZeroOrNegativeOneBooleanContent) {
Dan Gohmane82c25e2010-04-30 17:19:19 +00005085 EVT N0VT = N0.getOperand(0).getValueType();
Nadav Rotem9d376b62012-04-11 08:26:11 +00005086 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5087 // of the same size as the compared operands. Only optimize sext(setcc())
5088 // if this is the case.
Matt Arsenault758659232013-05-18 00:21:46 +00005089 EVT SVT = getSetCCResultType(N0VT);
Nadav Rotem9d376b62012-04-11 08:26:11 +00005090
5091 // We know that the # elements of the results is the same as the
5092 // # elements of the compare (and the # elements of the compare result
5093 // for that matter). Check to see that they are the same size. If so,
5094 // we know that the element size of the sext'd result matches the
5095 // element size of the compare operands.
5096 if (VT.getSizeInBits() == SVT.getSizeInBits())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005097 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005098 N0.getOperand(1),
5099 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Matt Arsenault04126232013-05-17 21:43:43 +00005100
Dan Gohmane82c25e2010-04-30 17:19:19 +00005101 // If the desired elements are smaller or larger than the source
5102 // elements we can use a matching integer vector type and then
5103 // truncate/sign extend
Matt Arsenault04126232013-05-17 21:43:43 +00005104 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
Craig Topper5f9791f2012-09-29 07:18:53 +00005105 if (SVT == MatchingVectorType) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005106 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
Craig Topper5f9791f2012-09-29 07:18:53 +00005107 N0.getOperand(0), N0.getOperand(1),
5108 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005109 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
Dan Gohmane82c25e2010-04-30 17:19:19 +00005110 }
Chris Lattner4ac60732009-07-08 00:31:33 +00005111 }
Dan Gohmane82c25e2010-04-30 17:19:19 +00005112
Matt Arsenault5f2a92a2014-01-27 21:41:54 +00005113 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
Dan Gohman5544b0c2010-04-24 01:17:30 +00005114 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
Dan Gohman5758e1e2009-08-06 09:18:59 +00005115 SDValue NegOne =
Dan Gohman5544b0c2010-04-24 01:17:30 +00005116 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005117 SDValue SCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005118 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Dan Gohman5758e1e2009-08-06 09:18:59 +00005119 NegOne, DAG.getConstant(0, VT),
Chris Lattnera083ffc2007-04-11 06:50:51 +00005120 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005121 if (SCC.getNode()) return SCC;
Matt Arsenault5f2a92a2014-01-27 21:41:54 +00005122
5123 if (!VT.isVector()) {
5124 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5125 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5126 SDLoc DL(N);
5127 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5128 SDValue SetCC = DAG.getSetCC(DL,
5129 SetCCVT,
5130 N0.getOperand(0), N0.getOperand(1), CC);
5131 EVT SelectVT = getSetCCResultType(VT);
5132 return DAG.getSelect(DL, VT,
5133 DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
5134 NegOne, DAG.getConstant(0, VT));
5135
5136 }
Matt Arsenaultd2f03322013-06-14 22:04:37 +00005137 }
Wesley Peck527da1b2010-11-23 03:31:01 +00005138 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005139
Dan Gohman3eb10f72008-04-28 16:58:24 +00005140 // fold (sext x) -> (zext x) if the sign bit is known zero.
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005141 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
Dan Gohmanc968c1f2008-04-28 18:47:17 +00005142 DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005143 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005144
Evan Chengf1005572010-04-28 07:10:39 +00005145 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00005146}
5147
Rafael Espindola8f62b322012-04-09 16:06:03 +00005148// isTruncateOf - If N is a truncate of some other value, return true, record
5149// the value being truncated in Op and which of Op's bits are zero in KnownZero.
5150// This function computes KnownZero to avoid a duplicated call to
Jay Foada0653a32014-05-14 21:14:37 +00005151// computeKnownBits in the caller.
Rafael Espindola8f62b322012-04-09 16:06:03 +00005152static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5153 APInt &KnownZero) {
5154 APInt KnownOne;
5155 if (N->getOpcode() == ISD::TRUNCATE) {
5156 Op = N->getOperand(0);
Jay Foada0653a32014-05-14 21:14:37 +00005157 DAG.computeKnownBits(Op, KnownZero, KnownOne);
Rafael Espindola8f62b322012-04-09 16:06:03 +00005158 return true;
5159 }
5160
5161 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5162 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5163 return false;
5164
5165 SDValue Op0 = N->getOperand(0);
5166 SDValue Op1 = N->getOperand(1);
5167 assert(Op0.getValueType() == Op1.getValueType());
5168
5169 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5170 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
Rafael Espindola1d9672b2012-04-10 00:16:22 +00005171 if (COp0 && COp0->isNullValue())
Rafael Espindola8f62b322012-04-09 16:06:03 +00005172 Op = Op1;
Rafael Espindola1d9672b2012-04-10 00:16:22 +00005173 else if (COp1 && COp1->isNullValue())
Rafael Espindola8f62b322012-04-09 16:06:03 +00005174 Op = Op0;
5175 else
5176 return false;
5177
Jay Foada0653a32014-05-14 21:14:37 +00005178 DAG.computeKnownBits(Op, KnownZero, KnownOne);
Rafael Espindola8f62b322012-04-09 16:06:03 +00005179
5180 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5181 return false;
5182
5183 return true;
5184}
5185
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005186SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5187 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005188 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00005189
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005190 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5191 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005192 return SDValue(Res, 0);
5193
Nate Begeman21158fc2005-09-01 00:19:25 +00005194 // fold (zext (zext x)) -> (zext x)
Chris Lattner7e7bcf32006-05-06 23:06:26 +00005195 // fold (zext (aext x)) -> (zext x)
5196 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005197 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005198 N0.getOperand(0));
Chris Lattnera31f0a62006-09-21 06:00:20 +00005199
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005200 // fold (zext (truncate x)) -> (zext x) or
5201 // (zext (truncate x)) -> (truncate x)
5202 // This is valid when the truncated bits of x are already zero.
5203 // FIXME: We should extend this to work for vectors too.
Rafael Espindola8f62b322012-04-09 16:06:03 +00005204 SDValue Op;
5205 APInt KnownZero;
5206 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5207 APInt TruncatedBits =
5208 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5209 APInt(Op.getValueSizeInBits(), 0) :
5210 APInt::getBitsSet(Op.getValueSizeInBits(),
5211 N0.getValueSizeInBits(),
5212 std::min(Op.getValueSizeInBits(),
5213 VT.getSizeInBits()));
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00005214 if (TruncatedBits == (KnownZero & TruncatedBits)) {
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005215 if (VT.bitsGT(Op.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005216 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005217 if (VT.bitsLT(Op.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005218 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005219
5220 return Op;
5221 }
5222 }
5223
Evan Cheng464dc9b2007-03-22 01:54:19 +00005224 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5225 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
Dale Johannesen4bbd2ee2007-03-30 21:38:07 +00005226 if (N0.getOpcode() == ISD::TRUNCATE) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005227 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5228 if (NarrowLoad.getNode()) {
Dale Johannesenff384ad2010-05-25 17:50:03 +00005229 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5230 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005231 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesenff384ad2010-05-25 17:50:03 +00005232 // CombineTo deleted the truncate, if needed, but not what's under it.
5233 AddToWorkList(oye);
5234 }
Eli Friedman55b0acd2011-04-16 23:25:34 +00005235 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00005236 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005237 }
5238
Chris Lattnera31f0a62006-09-21 06:00:20 +00005239 // fold (zext (truncate x)) -> (and x, mask)
5240 if (N0.getOpcode() == ISD::TRUNCATE &&
Dan Gohman600f62b2010-06-24 14:30:44 +00005241 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
Dan Gohman68fb0042010-11-03 01:47:46 +00005242
5243 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5244 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5245 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5246 if (NarrowLoad.getNode()) {
5247 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5248 if (NarrowLoad.getNode() != N0.getNode()) {
5249 CombineTo(N0.getNode(), NarrowLoad);
5250 // CombineTo deleted the truncate, if needed, but not what's under it.
5251 AddToWorkList(oye);
5252 }
5253 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5254 }
5255
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005256 SDValue Op = N0.getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00005257 if (Op.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005258 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
Elena Demikhovsky8d7e56c2012-04-22 09:39:03 +00005259 AddToWorkList(Op.getNode());
Duncan Sands11dd4242008-06-08 20:54:56 +00005260 } else if (Op.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005261 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Elena Demikhovsky8d7e56c2012-04-22 09:39:03 +00005262 AddToWorkList(Op.getNode());
Chris Lattnera31f0a62006-09-21 06:00:20 +00005263 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00005264 return DAG.getZeroExtendInReg(Op, SDLoc(N),
Dan Gohman1d459e42009-12-11 21:31:27 +00005265 N0.getValueType().getScalarType());
Chris Lattnera31f0a62006-09-21 06:00:20 +00005266 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005267
Dan Gohmanad3e5492009-04-08 00:15:30 +00005268 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5269 // if either of the casts is not free.
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00005270 if (N0.getOpcode() == ISD::AND &&
5271 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
Dan Gohmanad3e5492009-04-08 00:15:30 +00005272 N0.getOperand(1).getOpcode() == ISD::Constant &&
5273 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5274 N0.getValueType()) ||
5275 !TLI.isZExtFree(N0.getValueType(), VT))) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005276 SDValue X = N0.getOperand(0).getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00005277 if (X.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005278 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
Duncan Sands11dd4242008-06-08 20:54:56 +00005279 } else if (X.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005280 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00005281 }
Dan Gohmane1c4f992008-03-03 23:51:38 +00005282 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00005283 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005284 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005285 X, DAG.getConstant(Mask, VT));
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00005286 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005287
Evan Chengbce7c472005-12-14 02:19:23 +00005288 // fold (zext (load x)) -> (zext (truncate (zextload x)))
Nadav Rotem25f2ac92011-02-20 12:37:50 +00005289 // None of the supported targets knows how to perform load and vector_zext
Nadav Rotemb0091302011-02-27 07:40:43 +00005290 // on vectors in one instruction. We only perform this transformation on
5291 // scalars.
Nadav Rotem25f2ac92011-02-20 12:37:50 +00005292 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005293 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005294 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005295 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
Evan Chenge106e2f2007-10-29 19:58:20 +00005296 bool DoXform = true;
5297 SmallVector<SDNode*, 4> SetCCs;
5298 if (!N0.hasOneUse())
5299 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5300 if (DoXform) {
5301 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005302 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005303 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005304 LN0->getBasePtr(), N0.getValueType(),
5305 LN0->getMemOperand());
Evan Chenge106e2f2007-10-29 19:58:20 +00005306 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005307 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00005308 N0.getValueType(), ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005309 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Bill Wendlingc4093182009-01-30 22:23:15 +00005310
Andrew Trickef9de2a2013-05-25 02:42:55 +00005311 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005312 ISD::ZERO_EXTEND);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005313 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenge106e2f2007-10-29 19:58:20 +00005314 }
Evan Chengbce7c472005-12-14 02:19:23 +00005315 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005316
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005317 // fold (zext (and/or/xor (load x), cst)) ->
5318 // (and/or/xor (zextload x), (zext cst))
5319 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5320 N0.getOpcode() == ISD::XOR) &&
5321 isa<LoadSDNode>(N0.getOperand(0)) &&
5322 N0.getOperand(1).getOpcode() == ISD::Constant &&
5323 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5324 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5325 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005326 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005327 bool DoXform = true;
5328 SmallVector<SDNode*, 4> SetCCs;
5329 if (!N0.hasOneUse())
5330 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5331 SetCCs, TLI);
5332 if (DoXform) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005333 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005334 LN0->getChain(), LN0->getBasePtr(),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005335 LN0->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005336 LN0->getMemOperand());
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005337 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5338 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005339 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005340 ExtLoad, DAG.getConstant(Mask, VT));
5341 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00005342 SDLoc(N0.getOperand(0)),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005343 N0.getOperand(0).getValueType(), ExtLoad);
5344 CombineTo(N, And);
5345 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005346 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005347 ISD::ZERO_EXTEND);
5348 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5349 }
5350 }
5351 }
5352
Chris Lattner7dac1082005-12-14 19:05:06 +00005353 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5354 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00005355 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5356 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005357 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00005358 EVT MemVT = LN0->getMemoryVT();
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005359 if ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00005360 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005361 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005362 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005363 LN0->getBasePtr(), MemVT,
5364 LN0->getMemOperand());
Duncan Sands8651e9c2008-06-13 19:07:40 +00005365 CombineTo(N, ExtLoad);
Gabor Greife12264b2008-08-30 19:29:20 +00005366 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005367 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
Bill Wendlingc4093182009-01-30 22:23:15 +00005368 ExtLoad),
Duncan Sands8651e9c2008-06-13 19:07:40 +00005369 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005370 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Duncan Sands8651e9c2008-06-13 19:07:40 +00005371 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005372 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005373
Chris Lattner65786b02007-04-11 05:32:27 +00005374 if (N0.getOpcode() == ISD::SETCC) {
Kevin Qinede9ce12013-12-30 02:05:13 +00005375 if (!LegalOperations && VT.isVector() &&
5376 N0.getValueType().getVectorElementType() == MVT::i1) {
Elena Demikhovsky9d56f1e2014-01-22 12:26:19 +00005377 EVT N0VT = N0.getOperand(0).getValueType();
5378 if (getSetCCResultType(N0VT) == N0.getValueType())
5379 return SDValue();
5380
Evan Chengabd0ad52010-05-19 01:08:17 +00005381 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5382 // Only do this before legalize for now.
Evan Chengabd0ad52010-05-19 01:08:17 +00005383 EVT EltVT = VT.getVectorElementType();
5384 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5385 DAG.getConstant(1, EltVT));
Dan Gohman4298df62011-05-17 22:20:36 +00005386 if (VT.getSizeInBits() == N0VT.getSizeInBits())
Evan Chengabd0ad52010-05-19 01:08:17 +00005387 // We know that the # elements of the results is the same as the
5388 // # elements of the compare (and the # elements of the compare result
5389 // for that matter). Check to see that they are the same size. If so,
5390 // we know that the element size of the sext'd result matches the
5391 // element size of the compare operands.
Andrew Trickef9de2a2013-05-25 02:42:55 +00005392 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5393 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Evan Chengabd0ad52010-05-19 01:08:17 +00005394 N0.getOperand(1),
5395 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005396 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
Craig Topper48d114b2014-04-26 18:35:24 +00005397 OneOps));
Dan Gohman4298df62011-05-17 22:20:36 +00005398
5399 // If the desired elements are smaller or larger than the source
5400 // elements we can use a matching integer vector type and then
5401 // truncate/sign extend
5402 EVT MatchingElementType =
5403 EVT::getIntegerVT(*DAG.getContext(),
5404 N0VT.getScalarType().getSizeInBits());
5405 EVT MatchingVectorType =
5406 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5407 N0VT.getVectorNumElements());
5408 SDValue VsetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005409 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
Dan Gohman4298df62011-05-17 22:20:36 +00005410 N0.getOperand(1),
5411 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005412 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5413 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
Craig Topper48d114b2014-04-26 18:35:24 +00005414 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
Evan Chengabd0ad52010-05-19 01:08:17 +00005415 }
5416
5417 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
Scott Michelcf0da6c2009-02-17 22:15:04 +00005418 SDValue SCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005419 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Chris Lattner65786b02007-04-11 05:32:27 +00005420 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
Chris Lattnera083ffc2007-04-11 06:50:51 +00005421 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005422 if (SCC.getNode()) return SCC;
Chris Lattner65786b02007-04-11 05:32:27 +00005423 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005424
Evan Cheng852c4862009-12-15 03:00:32 +00005425 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
Evan Chengca7c6902009-12-15 00:41:36 +00005426 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
Evan Cheng852c4862009-12-15 03:00:32 +00005427 isa<ConstantSDNode>(N0.getOperand(1)) &&
Evan Chengca7c6902009-12-15 00:41:36 +00005428 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5429 N0.hasOneUse()) {
Chris Lattnere95d1952011-02-13 19:09:16 +00005430 SDValue ShAmt = N0.getOperand(1);
5431 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
Evan Cheng852c4862009-12-15 03:00:32 +00005432 if (N0.getOpcode() == ISD::SHL) {
Chris Lattnere95d1952011-02-13 19:09:16 +00005433 SDValue InnerZExt = N0.getOperand(0);
Evan Cheng852c4862009-12-15 03:00:32 +00005434 // If the original shl may be shifting out bits, do not perform this
5435 // transformation.
Chris Lattnere95d1952011-02-13 19:09:16 +00005436 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5437 InnerZExt.getOperand(0).getValueType().getSizeInBits();
5438 if (ShAmtVal > KnownZeroBits)
Evan Cheng852c4862009-12-15 03:00:32 +00005439 return SDValue();
5440 }
Chris Lattnere95d1952011-02-13 19:09:16 +00005441
Andrew Trickef9de2a2013-05-25 02:42:55 +00005442 SDLoc DL(N);
Owen Andersonb2c80da2011-02-25 21:41:48 +00005443
5444 // Ensure that the shift amount is wide enough for the shifted value.
Chris Lattnere95d1952011-02-13 19:09:16 +00005445 if (VT.getSizeInBits() >= 256)
5446 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
Owen Andersonb2c80da2011-02-25 21:41:48 +00005447
Chris Lattnere95d1952011-02-13 19:09:16 +00005448 return DAG.getNode(N0.getOpcode(), DL, VT,
5449 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5450 ShAmt);
Evan Chengca7c6902009-12-15 00:41:36 +00005451 }
5452
Evan Chengf1005572010-04-28 07:10:39 +00005453 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00005454}
5455
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005456SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5457 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005458 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005459
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005460 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5461 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005462 return SDValue(Res, 0);
5463
Chris Lattner812646a2006-05-05 05:58:59 +00005464 // fold (aext (aext x)) -> (aext x)
5465 // fold (aext (zext x)) -> (zext x)
5466 // fold (aext (sext x)) -> (sext x)
5467 if (N0.getOpcode() == ISD::ANY_EXTEND ||
5468 N0.getOpcode() == ISD::ZERO_EXTEND ||
5469 N0.getOpcode() == ISD::SIGN_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005470 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00005471
Evan Cheng464dc9b2007-03-22 01:54:19 +00005472 // fold (aext (truncate (load x))) -> (aext (smaller load x))
5473 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5474 if (N0.getOpcode() == ISD::TRUNCATE) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005475 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5476 if (NarrowLoad.getNode()) {
Dale Johannesen60fe2cd2010-05-25 18:47:23 +00005477 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5478 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005479 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesen60fe2cd2010-05-25 18:47:23 +00005480 // CombineTo deleted the truncate, if needed, but not what's under it.
5481 AddToWorkList(oye);
5482 }
Eli Friedman55b0acd2011-04-16 23:25:34 +00005483 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00005484 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005485 }
5486
Chris Lattner8746e2c2006-09-20 06:29:17 +00005487 // fold (aext (truncate x))
5488 if (N0.getOpcode() == ISD::TRUNCATE) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005489 SDValue TruncOp = N0.getOperand(0);
Chris Lattner8746e2c2006-09-20 06:29:17 +00005490 if (TruncOp.getValueType() == VT)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005491 return TruncOp; // x iff x size == zext size.
Duncan Sands11dd4242008-06-08 20:54:56 +00005492 if (TruncOp.getValueType().bitsGT(VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005493 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5494 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
Chris Lattner8746e2c2006-09-20 06:29:17 +00005495 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005496
Dan Gohmanad3e5492009-04-08 00:15:30 +00005497 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5498 // if the trunc is not free.
Chris Lattner082db3f2006-09-21 06:40:43 +00005499 if (N0.getOpcode() == ISD::AND &&
5500 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
Dan Gohmanad3e5492009-04-08 00:15:30 +00005501 N0.getOperand(1).getOpcode() == ISD::Constant &&
5502 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5503 N0.getValueType())) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005504 SDValue X = N0.getOperand(0).getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00005505 if (X.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005506 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
Duncan Sands11dd4242008-06-08 20:54:56 +00005507 } else if (X.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005508 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
Chris Lattner082db3f2006-09-21 06:40:43 +00005509 }
Dan Gohmane1c4f992008-03-03 23:51:38 +00005510 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00005511 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005512 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendling9b3dc8d2009-01-30 22:27:33 +00005513 X, DAG.getConstant(Mask, VT));
Chris Lattner082db3f2006-09-21 06:40:43 +00005514 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005515
Chris Lattner812646a2006-05-05 05:58:59 +00005516 // fold (aext (load x)) -> (aext (truncate (extload x)))
Nadav Rotem502f1b92011-02-24 21:01:34 +00005517 // None of the supported targets knows how to perform load and any_ext
Nadav Rotemb0091302011-02-27 07:40:43 +00005518 // on vectors in one instruction. We only perform this transformation on
5519 // scalars.
Nadav Rotem502f1b92011-02-24 21:01:34 +00005520 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005521 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005522 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005523 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
Dan Gohman0e8d1992009-04-09 03:51:29 +00005524 bool DoXform = true;
5525 SmallVector<SDNode*, 4> SetCCs;
5526 if (!N0.hasOneUse())
5527 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5528 if (DoXform) {
5529 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005530 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
Dan Gohman0e8d1992009-04-09 03:51:29 +00005531 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005532 LN0->getBasePtr(), N0.getValueType(),
5533 LN0->getMemOperand());
Dan Gohman0e8d1992009-04-09 03:51:29 +00005534 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005535 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Dan Gohman0e8d1992009-04-09 03:51:29 +00005536 N0.getValueType(), ExtLoad);
5537 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005538 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005539 ISD::ANY_EXTEND);
Dan Gohman0e8d1992009-04-09 03:51:29 +00005540 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5541 }
Chris Lattner812646a2006-05-05 05:58:59 +00005542 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005543
Chris Lattner812646a2006-05-05 05:58:59 +00005544 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5545 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5546 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
Evan Cheng8a1d09d2007-03-07 08:07:03 +00005547 if (N0.getOpcode() == ISD::LOAD &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00005548 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Chenge71fe34d2006-10-09 20:57:25 +00005549 N0.hasOneUse()) {
5550 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Matt Arsenaultaaf96232014-04-08 21:40:37 +00005551 ISD::LoadExtType ExtType = LN0->getExtensionType();
Dan Gohman08c0a952009-09-23 21:02:20 +00005552 EVT MemVT = LN0->getMemoryVT();
Matt Arsenaultaaf96232014-04-08 21:40:37 +00005553 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5554 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5555 VT, LN0->getChain(), LN0->getBasePtr(),
5556 MemVT, LN0->getMemOperand());
5557 CombineTo(N, ExtLoad);
5558 CombineTo(N0.getNode(),
5559 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5560 N0.getValueType(), ExtLoad),
5561 ExtLoad.getValue(1));
5562 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5563 }
Chris Lattner812646a2006-05-05 05:58:59 +00005564 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005565
Chris Lattner65786b02007-04-11 05:32:27 +00005566 if (N0.getOpcode() == ISD::SETCC) {
Hao Liuc636d152014-04-22 09:57:06 +00005567 // For vectors:
5568 // aext(setcc) -> vsetcc
5569 // aext(setcc) -> truncate(vsetcc)
5570 // aext(setcc) -> aext(vsetcc)
Evan Chengabd0ad52010-05-19 01:08:17 +00005571 // Only do this before legalize for now.
5572 if (VT.isVector() && !LegalOperations) {
5573 EVT N0VT = N0.getOperand(0).getValueType();
5574 // We know that the # elements of the results is the same as the
5575 // # elements of the compare (and the # elements of the compare result
5576 // for that matter). Check to see that they are the same size. If so,
5577 // we know that the element size of the sext'd result matches the
5578 // element size of the compare operands.
5579 if (VT.getSizeInBits() == N0VT.getSizeInBits())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005580 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005581 N0.getOperand(1),
5582 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Evan Chengabd0ad52010-05-19 01:08:17 +00005583 // If the desired elements are smaller or larger than the source
5584 // elements we can use a matching integer vector type and then
Hao Liuc636d152014-04-22 09:57:06 +00005585 // truncate/any extend
Evan Chengabd0ad52010-05-19 01:08:17 +00005586 else {
Hao Liuc636d152014-04-22 09:57:06 +00005587 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005588 SDValue VsetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005589 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005590 N0.getOperand(1),
5591 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Hao Liuc636d152014-04-22 09:57:06 +00005592 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
Evan Chengabd0ad52010-05-19 01:08:17 +00005593 }
5594 }
5595
5596 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
Scott Michelcf0da6c2009-02-17 22:15:04 +00005597 SDValue SCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005598 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Chris Lattnera083ffc2007-04-11 06:50:51 +00005599 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
Chris Lattner18e4ac42007-04-11 16:51:53 +00005600 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005601 if (SCC.getNode())
Chris Lattnerc5f85d32007-04-11 06:43:25 +00005602 return SCC;
Chris Lattner65786b02007-04-11 05:32:27 +00005603 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005604
Evan Chengf1005572010-04-28 07:10:39 +00005605 return SDValue();
Chris Lattner812646a2006-05-05 05:58:59 +00005606}
5607
Chris Lattner5e6fe052007-10-13 06:35:54 +00005608/// GetDemandedBits - See if the specified operand can be simplified with the
5609/// knowledge that only the bits specified by Mask are used. If so, return the
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005610/// simpler operand, otherwise return a null SDValue.
5611SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
Chris Lattner5e6fe052007-10-13 06:35:54 +00005612 switch (V.getOpcode()) {
5613 default: break;
Lang Hamesb85fcd02011-11-08 18:56:23 +00005614 case ISD::Constant: {
5615 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
Craig Topperc0196b12014-04-14 00:51:57 +00005616 assert(CV && "Const value should be ConstSDNode.");
Lang Hamesb85fcd02011-11-08 18:56:23 +00005617 const APInt &CVal = CV->getAPIntValue();
5618 APInt NewVal = CVal & Mask;
Stephen Lin8e8424e2013-07-09 00:44:49 +00005619 if (NewVal != CVal)
Lang Hamesb85fcd02011-11-08 18:56:23 +00005620 return DAG.getConstant(NewVal, V.getValueType());
Lang Hamesb85fcd02011-11-08 18:56:23 +00005621 break;
5622 }
Chris Lattner5e6fe052007-10-13 06:35:54 +00005623 case ISD::OR:
5624 case ISD::XOR:
5625 // If the LHS or RHS don't contribute bits to the or, drop them.
5626 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5627 return V.getOperand(1);
5628 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5629 return V.getOperand(0);
5630 break;
Chris Lattnerf47e3062007-10-13 06:58:48 +00005631 case ISD::SRL:
5632 // Only look at single-use SRLs.
Gabor Greiff304a7a2008-08-28 21:40:38 +00005633 if (!V.getNode()->hasOneUse())
Chris Lattnerf47e3062007-10-13 06:58:48 +00005634 break;
5635 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5636 // See if we can recursively simplify the LHS.
Dan Gohmaneffb8942008-09-12 16:56:44 +00005637 unsigned Amt = RHSC->getZExtValue();
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005638
Dan Gohmanb9fa1d22009-01-03 19:22:06 +00005639 // Watch out for shift count overflow though.
5640 if (Amt >= Mask.getBitWidth()) break;
Dan Gohman1f372ed2008-02-25 21:11:39 +00005641 APInt NewMask = Mask << Amt;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005642 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005643 if (SimplifyLHS.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005644 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
Chris Lattnerf47e3062007-10-13 06:58:48 +00005645 SimplifyLHS, V.getOperand(1));
Chris Lattnerf47e3062007-10-13 06:58:48 +00005646 }
Chris Lattner5e6fe052007-10-13 06:35:54 +00005647 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005648 return SDValue();
Chris Lattner5e6fe052007-10-13 06:35:54 +00005649}
5650
Evan Cheng464dc9b2007-03-22 01:54:19 +00005651/// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5652/// bits and then truncated to a narrower type and where N is a multiple
5653/// of number of bits of the narrower type, transform it to a narrower load
5654/// from address + N / num of bits of new type. If the result is to be
5655/// extended, also fold the extension to form a extending load.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005656SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
Evan Cheng464dc9b2007-03-22 01:54:19 +00005657 unsigned Opc = N->getOpcode();
Dan Gohman600f62b2010-06-24 14:30:44 +00005658
Evan Cheng464dc9b2007-03-22 01:54:19 +00005659 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005660 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005661 EVT VT = N->getValueType(0);
5662 EVT ExtVT = VT;
Evan Cheng464dc9b2007-03-22 01:54:19 +00005663
Dan Gohman550c9af2008-08-14 20:04:46 +00005664 // This transformation isn't valid for vector loads.
5665 if (VT.isVector())
5666 return SDValue();
5667
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005668 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
Evan Chenga883b582007-03-23 22:13:36 +00005669 // extended to VT.
Evan Cheng464dc9b2007-03-22 01:54:19 +00005670 if (Opc == ISD::SIGN_EXTEND_INREG) {
5671 ExtType = ISD::SEXTLOAD;
Owen Anderson53aa7a92009-08-10 22:56:29 +00005672 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
Dan Gohman600f62b2010-06-24 14:30:44 +00005673 } else if (Opc == ISD::SRL) {
Chris Lattner2a7ff992010-12-21 18:05:22 +00005674 // Another special-case: SRL is basically zero-extending a narrower value.
Dan Gohman600f62b2010-06-24 14:30:44 +00005675 ExtType = ISD::ZEXTLOAD;
5676 N0 = SDValue(N, 0);
5677 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5678 if (!N01) return SDValue();
5679 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5680 VT.getSizeInBits() - N01->getZExtValue());
Evan Cheng464dc9b2007-03-22 01:54:19 +00005681 }
Richard Osborne272e0842011-01-31 17:41:44 +00005682 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5683 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005684
Owen Anderson53aa7a92009-08-10 22:56:29 +00005685 unsigned EVTBits = ExtVT.getSizeInBits();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005686
Chris Lattner9a499e92010-12-22 08:01:44 +00005687 // Do not generate loads of non-round integer types since these can
5688 // be expensive (and would be wrong if the type is not byte sized).
5689 if (!ExtVT.isRound())
5690 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005691
Evan Cheng464dc9b2007-03-22 01:54:19 +00005692 unsigned ShAmt = 0;
Chris Lattner9a499e92010-12-22 08:01:44 +00005693 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
Evan Cheng464dc9b2007-03-22 01:54:19 +00005694 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00005695 ShAmt = N01->getZExtValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005696 // Is the shift amount a multiple of size of VT?
5697 if ((ShAmt & (EVTBits-1)) == 0) {
5698 N0 = N0.getOperand(0);
Eli Friedman1e008c12009-08-19 08:46:10 +00005699 // Is the load width a multiple of size of VT?
5700 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005701 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005702 }
Wesley Peck527da1b2010-11-23 03:31:01 +00005703
Chris Lattnercafc1e62010-12-22 08:02:57 +00005704 // At this point, we must have a load or else we can't do the transform.
5705 if (!isa<LoadSDNode>(N0)) return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005706
Chandler Carruthb27041c2012-12-11 00:36:57 +00005707 // Because a SRL must be assumed to *need* to zero-extend the high bits
5708 // (as opposed to anyext the high bits), we can't combine the zextload
5709 // lowering of SRL and an sextload.
5710 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5711 return SDValue();
5712
Chris Lattnera2050552010-10-01 05:36:09 +00005713 // If the shift amount is larger than the input type then we're not
5714 // accessing any of the loaded bytes. If the load was a zextload/extload
5715 // then the result of the shift+trunc is zero/undef (handled elsewhere).
Chris Lattnercafc1e62010-12-22 08:02:57 +00005716 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
Chris Lattnera2050552010-10-01 05:36:09 +00005717 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005718 }
5719 }
5720
Dan Gohman68fb0042010-11-03 01:47:46 +00005721 // If the load is shifted left (and the result isn't shifted back right),
5722 // we can fold the truncate through the shift.
5723 unsigned ShLeftAmt = 0;
5724 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
Chris Lattner222374d2010-12-22 07:36:50 +00005725 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
Dan Gohman68fb0042010-11-03 01:47:46 +00005726 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5727 ShLeftAmt = N01->getZExtValue();
5728 N0 = N0.getOperand(0);
5729 }
5730 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00005731
Chris Lattner222374d2010-12-22 07:36:50 +00005732 // If we haven't found a load, we can't narrow it. Don't transform one with
5733 // multiple uses, this would require adding a new load.
Bill Schmidtd006c692013-01-14 22:04:38 +00005734 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5735 return SDValue();
5736
5737 // Don't change the width of a volatile load.
5738 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5739 if (LN0->isVolatile())
Chris Lattner222374d2010-12-22 07:36:50 +00005740 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005741
Chris Lattner9a499e92010-12-22 08:01:44 +00005742 // Verify that we are actually reducing a load width here.
Bill Schmidtd006c692013-01-14 22:04:38 +00005743 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
Chris Lattner222374d2010-12-22 07:36:50 +00005744 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005745
Bill Schmidtd006c692013-01-14 22:04:38 +00005746 // For the transform to be legal, the load must produce only two values
5747 // (the value loaded and the chain). Don't transform a pre-increment
Stephen Lincfe7f352013-07-08 00:37:03 +00005748 // load, for example, which produces an extra value. Otherwise the
Bill Schmidtd006c692013-01-14 22:04:38 +00005749 // transformation is not equivalent, and the downstream logic to replace
5750 // uses gets things wrong.
5751 if (LN0->getNumValues() > 2)
5752 return SDValue();
5753
Benjamin Kramerc7332b22013-07-06 14:05:09 +00005754 // If the load that we're shrinking is an extload and we're not just
5755 // discarding the extension we can't simply shrink the load. Bail.
5756 // TODO: It would be possible to merge the extensions in some cases.
5757 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5758 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5759 return SDValue();
5760
Chris Lattner222374d2010-12-22 07:36:50 +00005761 EVT PtrType = N0.getOperand(1).getValueType();
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005762
Evan Cheng4c6f9172012-06-26 01:19:33 +00005763 if (PtrType == MVT::Untyped || PtrType.isExtended())
5764 // It's not possible to generate a constant of extended or untyped type.
5765 return SDValue();
5766
Chris Lattner222374d2010-12-22 07:36:50 +00005767 // For big endian targets, we need to adjust the offset to the pointer to
5768 // load the correct bytes.
5769 if (TLI.isBigEndian()) {
5770 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5771 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5772 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
Evan Cheng464dc9b2007-03-22 01:54:19 +00005773 }
5774
Chris Lattner222374d2010-12-22 07:36:50 +00005775 uint64_t PtrOff = ShAmt / 8;
5776 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005777 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
Chris Lattner222374d2010-12-22 07:36:50 +00005778 PtrType, LN0->getBasePtr(),
5779 DAG.getConstant(PtrOff, PtrType));
5780 AddToWorkList(NewPtr.getNode());
5781
Chris Lattner9a499e92010-12-22 08:01:44 +00005782 SDValue Load;
5783 if (ExtType == ISD::NON_EXTLOAD)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005784 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
Chris Lattner9a499e92010-12-22 08:01:44 +00005785 LN0->getPointerInfo().getWithOffset(PtrOff),
Pete Cooper82cd9e82011-11-08 18:42:53 +00005786 LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005787 LN0->isInvariant(), NewAlign, LN0->getTBAAInfo());
Chris Lattner9a499e92010-12-22 08:01:44 +00005788 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00005789 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
Chris Lattner9a499e92010-12-22 08:01:44 +00005790 LN0->getPointerInfo().getWithOffset(PtrOff),
5791 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005792 NewAlign, LN0->getTBAAInfo());
Chris Lattner222374d2010-12-22 07:36:50 +00005793
5794 // Replace the old load's chain with the new load's chain.
5795 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00005796 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
Chris Lattner222374d2010-12-22 07:36:50 +00005797
5798 // Shift the result left, if we've swallowed a left shift.
5799 SDValue Result = Load;
5800 if (ShLeftAmt != 0) {
Owen Andersonb2c80da2011-02-25 21:41:48 +00005801 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
Chris Lattner222374d2010-12-22 07:36:50 +00005802 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5803 ShImmTy = VT;
Paul Redmond288604e2013-02-12 15:21:21 +00005804 // If the shift amount is as large as the result size (but, presumably,
5805 // no larger than the source) then the useful bits of the result are
5806 // zero; we can't simply return the shortened shift, because the result
5807 // of that operation is undefined.
5808 if (ShLeftAmt >= VT.getSizeInBits())
5809 Result = DAG.getConstant(0, VT);
5810 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00005811 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
Paul Redmond288604e2013-02-12 15:21:21 +00005812 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
Chris Lattner222374d2010-12-22 07:36:50 +00005813 }
5814
5815 // Return the new loaded value.
5816 return Result;
Evan Cheng464dc9b2007-03-22 01:54:19 +00005817}
5818
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005819SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5820 SDValue N0 = N->getOperand(0);
5821 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005822 EVT VT = N->getValueType(0);
5823 EVT EVT = cast<VTSDNode>(N1)->getVT();
Dan Gohman1d459e42009-12-11 21:31:27 +00005824 unsigned VTBits = VT.getScalarType().getSizeInBits();
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005825 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00005826
Nate Begeman21158fc2005-09-01 00:19:25 +00005827 // fold (sext_in_reg c1) -> c1
Chris Lattner29062da2006-05-08 20:59:41 +00005828 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005829 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005830
Chris Lattner2a4d7b82006-05-06 22:43:44 +00005831 // If the input is already sign extended, just drop the extension.
Dan Gohman1d459e42009-12-11 21:31:27 +00005832 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
Chris Lattner1ecb2a22006-05-06 09:30:03 +00005833 return N0;
Scott Michelcf0da6c2009-02-17 22:15:04 +00005834
Nate Begeman7cea6ef2005-09-02 21:18:40 +00005835 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5836 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00005837 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005838 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005839 N0.getOperand(0), N1);
Chris Lattner446e1ef2006-05-08 21:18:59 +00005840
Dan Gohman345d63c2008-07-31 00:50:31 +00005841 // fold (sext_in_reg (sext x)) -> (sext x)
5842 // fold (sext_in_reg (aext x)) -> (sext x)
5843 // if x is small enough.
5844 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5845 SDValue N00 = N0.getOperand(0);
Evan Chengf037f872010-04-16 22:26:19 +00005846 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5847 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005848 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
Dan Gohman345d63c2008-07-31 00:50:31 +00005849 }
5850
Chris Lattner9ad59152007-04-17 19:03:21 +00005851 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
Dan Gohman1f372ed2008-02-25 21:11:39 +00005852 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005853 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005854
Chris Lattner9ad59152007-04-17 19:03:21 +00005855 // fold operands of sext_in_reg based on knowledge that the top bits are not
5856 // demanded.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005857 if (SimplifyDemandedBits(SDValue(N, 0)))
5858 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005859
Evan Cheng464dc9b2007-03-22 01:54:19 +00005860 // fold (sext_in_reg (load x)) -> (smaller sextload x)
5861 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005862 SDValue NarrowLoad = ReduceLoadWidth(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005863 if (NarrowLoad.getNode())
Evan Cheng464dc9b2007-03-22 01:54:19 +00005864 return NarrowLoad;
5865
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005866 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005867 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
Chris Lattner446e1ef2006-05-08 21:18:59 +00005868 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5869 if (N0.getOpcode() == ISD::SRL) {
5870 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
Dan Gohman1d459e42009-12-11 21:31:27 +00005871 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005872 // We can turn this into an SRA iff the input to the SRL is already sign
Chris Lattner446e1ef2006-05-08 21:18:59 +00005873 // extended enough.
Dan Gohman309d3d52007-06-22 14:59:07 +00005874 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
Dan Gohman1d459e42009-12-11 21:31:27 +00005875 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005876 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005877 N0.getOperand(0), N0.getOperand(1));
Chris Lattner446e1ef2006-05-08 21:18:59 +00005878 }
5879 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005880
Nate Begeman02b23c62005-10-13 03:11:28 +00005881 // fold (sext_inreg (extload x)) -> (sextload x)
Scott Michelcf0da6c2009-02-17 22:15:04 +00005882 if (ISD::isEXTLoad(N0.getNode()) &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00005883 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Dan Gohman47a7d6f2008-01-30 00:15:11 +00005884 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005885 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005886 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005887 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005888 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005889 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005890 LN0->getBasePtr(), EVT,
5891 LN0->getMemOperand());
Chris Lattnerd39c60f2005-12-14 19:25:30 +00005892 CombineTo(N, ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005893 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Elena Demikhovsky14a4af02012-12-19 07:50:20 +00005894 AddToWorkList(ExtLoad.getNode());
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005895 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00005896 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005897 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
Gabor Greiff304a7a2008-08-28 21:40:38 +00005898 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Cheng8a1d09d2007-03-07 08:07:03 +00005899 N0.hasOneUse() &&
Dan Gohman47a7d6f2008-01-30 00:15:11 +00005900 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005901 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005902 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005903 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005904 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005905 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005906 LN0->getBasePtr(), EVT,
5907 LN0->getMemOperand());
Chris Lattnerd39c60f2005-12-14 19:25:30 +00005908 CombineTo(N, ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005909 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005910 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00005911 }
Evan Cheng4c0bd962011-06-21 06:01:08 +00005912
5913 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5914 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5915 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5916 N0.getOperand(1), false);
Craig Topperc0196b12014-04-14 00:51:57 +00005917 if (BSwap.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005918 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Evan Cheng4c0bd962011-06-21 06:01:08 +00005919 BSwap, N1);
5920 }
5921
Andrea Di Biagio46dcddb2013-12-27 20:20:28 +00005922 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
5923 // into a build_vector.
5924 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5925 SmallVector<SDValue, 8> Elts;
5926 unsigned NumElts = N0->getNumOperands();
5927 unsigned ShAmt = VTBits - EVTBits;
5928
5929 for (unsigned i = 0; i != NumElts; ++i) {
5930 SDValue Op = N0->getOperand(i);
5931 if (Op->getOpcode() == ISD::UNDEF) {
5932 Elts.push_back(Op);
5933 continue;
5934 }
5935
5936 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
Kevin Qin5cd73c92014-01-06 02:26:10 +00005937 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5938 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
Andrea Di Biagio46dcddb2013-12-27 20:20:28 +00005939 Op.getValueType()));
5940 }
5941
Craig Topper48d114b2014-04-26 18:35:24 +00005942 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
Andrea Di Biagio46dcddb2013-12-27 20:20:28 +00005943 }
5944
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005945 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00005946}
5947
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005948SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5949 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005950 EVT VT = N->getValueType(0);
Nadav Rotem5399f4d2012-02-03 13:18:25 +00005951 bool isLE = TLI.isLittleEndian();
Nate Begeman21158fc2005-09-01 00:19:25 +00005952
5953 // noop truncate
5954 if (N0.getValueType() == N->getValueType(0))
Nate Begemand23739d2005-09-06 04:43:02 +00005955 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00005956 // fold (truncate c1) -> c1
Chris Lattner7e7bcf32006-05-06 23:06:26 +00005957 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005958 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00005959 // fold (truncate (truncate x)) -> (truncate x)
5960 if (N0.getOpcode() == ISD::TRUNCATE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005961 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
Nate Begeman21158fc2005-09-01 00:19:25 +00005962 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
Chris Lattner6855d622010-04-07 18:13:33 +00005963 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5964 N0.getOpcode() == ISD::SIGN_EXTEND ||
Chris Lattner907e3922006-05-05 22:56:26 +00005965 N0.getOpcode() == ISD::ANY_EXTEND) {
Duncan Sands11dd4242008-06-08 20:54:56 +00005966 if (N0.getOperand(0).getValueType().bitsLT(VT))
Nate Begeman21158fc2005-09-01 00:19:25 +00005967 // if the source is smaller than the dest, we still need an extend
Andrew Trickef9de2a2013-05-25 02:42:55 +00005968 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00005969 N0.getOperand(0));
Craig Topper5f9791f2012-09-29 07:18:53 +00005970 if (N0.getOperand(0).getValueType().bitsGT(VT))
Nate Begeman21158fc2005-09-01 00:19:25 +00005971 // if the source is larger than the dest, than we just need the truncate
Andrew Trickef9de2a2013-05-25 02:42:55 +00005972 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
Craig Topper5f9791f2012-09-29 07:18:53 +00005973 // if the source and dest are the same type, we can drop both the extend
5974 // and the truncate.
5975 return N0.getOperand(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00005976 }
Evan Chengd63baea2007-03-21 20:14:05 +00005977
Nadav Rotem4f4546b2012-02-05 11:39:23 +00005978 // Fold extract-and-trunc into a narrow extract. For example:
5979 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5980 // i32 y = TRUNCATE(i64 x)
5981 // -- becomes --
5982 // v16i8 b = BITCAST (v2i64 val)
5983 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5984 //
5985 // Note: We only run this optimization after type legalization (which often
Nadav Rotem5399f4d2012-02-03 13:18:25 +00005986 // creates this pattern) and before operation legalization after which
5987 // we need to be more careful about the vector instructions that we generate.
5988 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
Hal Finkelab51ecd2014-02-28 00:26:45 +00005989 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
Nadav Rotem5399f4d2012-02-03 13:18:25 +00005990
5991 EVT VecTy = N0.getOperand(0).getValueType();
5992 EVT ExTy = N0.getValueType();
5993 EVT TrTy = N->getValueType(0);
5994
5995 unsigned NumElem = VecTy.getVectorNumElements();
5996 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5997
5998 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5999 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6000
6001 SDValue EltNo = N0->getOperand(1);
6002 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6003 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Tom Stellardd42c5942013-08-05 22:22:01 +00006004 EVT IndexTy = TLI.getVectorIdxTy();
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006005 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6006
Andrew Trickef9de2a2013-05-25 02:42:55 +00006007 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006008 NVT, N0.getOperand(0));
6009
6010 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
Andrew Trickef9de2a2013-05-25 02:42:55 +00006011 SDLoc(N), TrTy, V,
Jim Grosbach92f6adc2012-05-08 20:56:07 +00006012 DAG.getConstant(Index, IndexTy));
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006013 }
6014 }
6015
Matt Arsenault658c5572014-07-09 19:12:07 +00006016 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6017 if (N0.getOpcode() == ISD::SELECT) {
6018 EVT SrcVT = N0.getValueType();
6019 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6020 TLI.isTruncateFree(SrcVT, VT)) {
6021 SDLoc SL(N0);
6022 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6023 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6024 EVT SetCCVT = getSetCCResultType(VT);
6025 SDValue Cond = DAG.getSExtOrTrunc(N0.getOperand(0), SL, SetCCVT);
6026 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6027 }
6028 }
6029
Arnold Schwaighofer3f9568e2013-02-20 21:33:32 +00006030 // Fold a series of buildvector, bitcast, and truncate if possible.
6031 // For example fold
6032 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6033 // (2xi32 (buildvector x, y)).
6034 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6035 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6036 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6037 N0.getOperand(0).hasOneUse()) {
6038
6039 SDValue BuildVect = N0.getOperand(0);
6040 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6041 EVT TruncVecEltTy = VT.getVectorElementType();
6042
6043 // Check that the element types match.
6044 if (BuildVectEltTy == TruncVecEltTy) {
6045 // Now we only need to compute the offset of the truncated elements.
6046 unsigned BuildVecNumElts = BuildVect.getNumOperands();
6047 unsigned TruncVecNumElts = VT.getVectorNumElements();
6048 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6049
6050 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6051 "Invalid number of elements");
6052
6053 SmallVector<SDValue, 8> Opnds;
6054 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6055 Opnds.push_back(BuildVect.getOperand(i));
6056
Craig Topper48d114b2014-04-26 18:35:24 +00006057 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
Arnold Schwaighofer3f9568e2013-02-20 21:33:32 +00006058 }
6059 }
6060
Chris Lattner5e6fe052007-10-13 06:35:54 +00006061 // See if we can simplify the input to this truncate through knowledge that
Nadav Rotem502f1b92011-02-24 21:01:34 +00006062 // only the low bits are being used.
6063 // For example "trunc (or (shl x, 8), y)" // -> trunc y
Nadav Rotemb0091302011-02-27 07:40:43 +00006064 // Currently we only perform this optimization on scalars because vectors
Nadav Rotem502f1b92011-02-24 21:01:34 +00006065 // may have different active low bits.
6066 if (!VT.isVector()) {
6067 SDValue Shorter =
6068 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6069 VT.getSizeInBits()));
6070 if (Shorter.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006071 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
Nadav Rotem502f1b92011-02-24 21:01:34 +00006072 }
Nate Begeman8caf81d2005-10-12 20:40:40 +00006073 // fold (truncate (load x)) -> (smaller load x)
Evan Chengd63baea2007-03-21 20:14:05 +00006074 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
Dan Gohman600f62b2010-06-24 14:30:44 +00006075 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6076 SDValue Reduced = ReduceLoadWidth(N);
6077 if (Reduced.getNode())
6078 return Reduced;
Richard Sandifordd1093632013-12-11 11:37:27 +00006079 // Handle the case where the load remains an extending load even
6080 // after truncation.
6081 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6082 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6083 if (!LN0->isVolatile() &&
6084 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6085 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6086 VT, LN0->getChain(), LN0->getBasePtr(),
6087 LN0->getMemoryVT(),
6088 LN0->getMemOperand());
6089 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6090 return NewLoad;
6091 }
6092 }
Dan Gohman600f62b2010-06-24 14:30:44 +00006093 }
Michael Liao3ac82012012-10-17 23:45:54 +00006094 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6095 // where ... are all 'undef'.
6096 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6097 SmallVector<EVT, 8> VTs;
6098 SDValue V;
6099 unsigned Idx = 0;
6100 unsigned NumDefs = 0;
6101
6102 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6103 SDValue X = N0.getOperand(i);
6104 if (X.getOpcode() != ISD::UNDEF) {
6105 V = X;
6106 Idx = i;
6107 NumDefs++;
6108 }
6109 // Stop if more than one members are non-undef.
6110 if (NumDefs > 1)
6111 break;
6112 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6113 VT.getVectorElementType(),
6114 X.getValueType().getVectorNumElements()));
6115 }
6116
6117 if (NumDefs == 0)
6118 return DAG.getUNDEF(VT);
6119
6120 if (NumDefs == 1) {
6121 assert(V.getNode() && "The single defined operand is empty!");
6122 SmallVector<SDValue, 8> Opnds;
6123 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6124 if (i != Idx) {
6125 Opnds.push_back(DAG.getUNDEF(VTs[i]));
6126 continue;
6127 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00006128 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
Michael Liao3ac82012012-10-17 23:45:54 +00006129 AddToWorkList(NV.getNode());
6130 Opnds.push_back(NV);
6131 }
Craig Topper48d114b2014-04-26 18:35:24 +00006132 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
Michael Liao3ac82012012-10-17 23:45:54 +00006133 }
6134 }
Dan Gohman600f62b2010-06-24 14:30:44 +00006135
6136 // Simplify the operands using demanded-bits information.
6137 if (!VT.isVector() &&
6138 SimplifyDemandedBits(SDValue(N, 0)))
6139 return SDValue(N, 0);
6140
Evan Chengf1bd5fc2010-04-17 06:13:15 +00006141 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00006142}
6143
Evan Chengb980f6f2008-05-12 23:04:07 +00006144static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006145 SDValue Elt = N->getOperand(i);
Evan Chengb980f6f2008-05-12 23:04:07 +00006146 if (Elt.getOpcode() != ISD::MERGE_VALUES)
Gabor Greiff304a7a2008-08-28 21:40:38 +00006147 return Elt.getNode();
6148 return Elt.getOperand(Elt.getResNo()).getNode();
Evan Chengb980f6f2008-05-12 23:04:07 +00006149}
6150
6151/// CombineConsecutiveLoads - build_pair (load, load) -> load
Scott Michelcf0da6c2009-02-17 22:15:04 +00006152/// if load locations are consecutive.
Owen Anderson53aa7a92009-08-10 22:56:29 +00006153SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
Evan Chengb980f6f2008-05-12 23:04:07 +00006154 assert(N->getOpcode() == ISD::BUILD_PAIR);
6155
Nate Begeman624690c2009-06-05 21:37:30 +00006156 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6157 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
Chris Lattnerf72c3c02010-09-21 16:08:50 +00006158 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
Matt Arsenault58a76392014-02-24 21:01:15 +00006159 LD1->getAddressSpace() != LD2->getAddressSpace())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006160 return SDValue();
Owen Anderson53aa7a92009-08-10 22:56:29 +00006161 EVT LD1VT = LD1->getValueType(0);
Bill Wendling4e0a6152009-01-30 22:44:24 +00006162
Evan Chengb980f6f2008-05-12 23:04:07 +00006163 if (ISD::isNON_EXTLoad(LD2) &&
6164 LD2->hasOneUse() &&
Duncan Sands8651e9c2008-06-13 19:07:40 +00006165 // If both are volatile this would reduce the number of volatile loads.
6166 // If one is volatile it might be ok, but play conservative and bail out.
Nate Begeman624690c2009-06-05 21:37:30 +00006167 !LD1->isVolatile() &&
6168 !LD2->isVolatile() &&
Evan Chengf5938d52009-12-09 01:36:00 +00006169 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
Nate Begeman624690c2009-06-05 21:37:30 +00006170 unsigned Align = LD1->getAlignment();
Micah Villmowcdfe20b2012-10-08 16:38:25 +00006171 unsigned NewAlign = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +00006172 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
Bill Wendling4e0a6152009-01-30 22:44:24 +00006173
Duncan Sands8651e9c2008-06-13 19:07:40 +00006174 if (NewAlign <= Align &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006175 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006176 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
Chris Lattnerf72c3c02010-09-21 16:08:50 +00006177 LD1->getBasePtr(), LD1->getPointerInfo(),
Pete Cooper82cd9e82011-11-08 18:42:53 +00006178 false, false, false, Align);
Evan Chengb980f6f2008-05-12 23:04:07 +00006179 }
Bill Wendling4e0a6152009-01-30 22:44:24 +00006180
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006181 return SDValue();
Evan Chengb980f6f2008-05-12 23:04:07 +00006182}
6183
Wesley Peck527da1b2010-11-23 03:31:01 +00006184SDValue DAGCombiner::visitBITCAST(SDNode *N) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006185 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006186 EVT VT = N->getValueType(0);
Chris Lattnera1874602005-12-23 05:30:37 +00006187
Dan Gohmana8665142007-06-25 16:23:39 +00006188 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6189 // Only do this before legalize, since afterward the target may be depending
6190 // on the bitconvert.
6191 // First check to see if this is all constant.
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006192 if (!LegalTypes &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00006193 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
Duncan Sands13237ac2008-06-06 12:08:01 +00006194 VT.isVector()) {
Juergen Ributzka73844052014-01-13 20:51:35 +00006195 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006196
Owen Anderson53aa7a92009-08-10 22:56:29 +00006197 EVT DestEltVT = N->getValueType(0).getVectorElementType();
Duncan Sands13237ac2008-06-06 12:08:01 +00006198 assert(!DestEltVT.isVector() &&
Dan Gohmana8665142007-06-25 16:23:39 +00006199 "Element type of vector ValueType must not be vector!");
Bill Wendling4e0a6152009-01-30 22:44:24 +00006200 if (isSimple)
Wesley Peck527da1b2010-11-23 03:31:01 +00006201 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
Dan Gohmana8665142007-06-25 16:23:39 +00006202 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006203
Dan Gohman921ddd62008-09-05 01:58:21 +00006204 // If the input is a constant, let getNode fold it.
Chris Lattnera1874602005-12-23 05:30:37 +00006205 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006206 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
Dan Gohman733a64d2009-08-10 23:15:10 +00006207 if (Res.getNode() != N) {
6208 if (!LegalOperations ||
6209 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6210 return Res;
6211
6212 // Folding it resulted in an illegal node, and it's too late to
6213 // do that. Clean up the old node and forego the transformation.
6214 // Ideally this won't happen very often, because instcombine
6215 // and the earlier dagcombine runs (where illegal nodes are
6216 // permitted) should have folded most of them already.
6217 DAG.DeleteNode(Res.getNode());
6218 }
Chris Lattnera1874602005-12-23 05:30:37 +00006219 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006220
Bill Wendling4e0a6152009-01-30 22:44:24 +00006221 // (conv (conv x, t1), t2) -> (conv x, t2)
Wesley Peck527da1b2010-11-23 03:31:01 +00006222 if (N0.getOpcode() == ISD::BITCAST)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006223 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006224 N0.getOperand(0));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006225
Chris Lattner54560f62005-12-23 05:44:41 +00006226 // fold (conv (load x)) -> (load (conv*)x)
Evan Cheng0de312d2007-10-06 08:19:55 +00006227 // If the resultant load doesn't need a higher alignment than the original!
Gabor Greiff304a7a2008-08-28 21:40:38 +00006228 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Duncan Sands8651e9c2008-06-13 19:07:40 +00006229 // Do not change the width of a volatile load.
6230 !cast<LoadSDNode>(N0)->isVolatile() &&
Ulrich Weigandf236bb12014-07-03 15:06:47 +00006231 // Do not remove the cast if the types differ in endian layout.
6232 TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6233 TLI.hasBigEndianPartOrdering(VT) &&
Matt Arsenaultc5559bb2013-11-15 04:42:23 +00006234 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6235 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00006236 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Micah Villmowcdfe20b2012-10-08 16:38:25 +00006237 unsigned Align = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +00006238 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
Evan Chenga4cf58a2007-05-07 21:27:48 +00006239 unsigned OrigAlign = LN0->getAlignment();
Bill Wendling4e0a6152009-01-30 22:44:24 +00006240
Evan Chenga4cf58a2007-05-07 21:27:48 +00006241 if (Align <= OrigAlign) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006242 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
Chris Lattnerf72c3c02010-09-21 16:08:50 +00006243 LN0->getBasePtr(), LN0->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +00006244 LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00006245 LN0->isInvariant(), OrigAlign,
6246 LN0->getTBAAInfo());
Evan Chenga4cf58a2007-05-07 21:27:48 +00006247 AddToWorkList(N);
Gabor Greife12264b2008-08-30 19:29:20 +00006248 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00006249 DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006250 N0.getValueType(), Load),
Evan Chenga4cf58a2007-05-07 21:27:48 +00006251 Load.getValue(1));
6252 return Load;
6253 }
Chris Lattner54560f62005-12-23 05:44:41 +00006254 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00006255
Bill Wendling4e0a6152009-01-30 22:44:24 +00006256 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6257 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
Chris Lattner888560d2008-01-27 17:42:27 +00006258 // This often reduces constant pool loads.
Tom Stellardc54731a2013-07-23 23:55:03 +00006259 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6260 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
Nadav Rotem24a822a2012-09-13 14:54:28 +00006261 N0.getNode()->hasOneUse() && VT.isInteger() &&
6262 !VT.isVector() && !N0.getValueType().isVector()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006263 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006264 N0.getOperand(0));
Gabor Greiff304a7a2008-08-28 21:40:38 +00006265 AddToWorkList(NewConv.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +00006266
Duncan Sands13237ac2008-06-06 12:08:01 +00006267 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
Chris Lattner888560d2008-01-27 17:42:27 +00006268 if (N0.getOpcode() == ISD::FNEG)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006269 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006270 NewConv, DAG.getConstant(SignBit, VT));
Chris Lattner888560d2008-01-27 17:42:27 +00006271 assert(N0.getOpcode() == ISD::FABS);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006272 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006273 NewConv, DAG.getConstant(~SignBit, VT));
Chris Lattner888560d2008-01-27 17:42:27 +00006274 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006275
Bill Wendling4e0a6152009-01-30 22:44:24 +00006276 // fold (bitconvert (fcopysign cst, x)) ->
6277 // (or (and (bitconvert x), sign), (and cst, (not sign)))
6278 // Note that we don't handle (copysign x, cst) because this can always be
6279 // folded to an fneg or fabs.
Gabor Greiff304a7a2008-08-28 21:40:38 +00006280 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
Chris Lattner2ee91f42008-01-27 23:32:17 +00006281 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
Duncan Sands13237ac2008-06-06 12:08:01 +00006282 VT.isInteger() && !VT.isVector()) {
6283 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
Owen Anderson117c9e82009-08-12 00:36:31 +00006284 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
Chris Lattner4041ab62010-04-15 04:48:01 +00006285 if (isTypeLegal(IntXVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006286 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006287 IntXVT, N0.getOperand(1));
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006288 AddToWorkList(X.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00006289
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006290 // If X has a different width than the result/lhs, sext it or truncate it.
6291 unsigned VTWidth = VT.getSizeInBits();
6292 if (OrigXWidth < VTWidth) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006293 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006294 AddToWorkList(X.getNode());
6295 } else if (OrigXWidth > VTWidth) {
6296 // To get the sign bit in the right place, we have to shift it right
6297 // before truncating.
Andrew Trickef9de2a2013-05-25 02:42:55 +00006298 X = DAG.getNode(ISD::SRL, SDLoc(X),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006299 X.getValueType(), X,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006300 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6301 AddToWorkList(X.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00006302 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006303 AddToWorkList(X.getNode());
6304 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006305
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006306 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00006307 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006308 X, DAG.getConstant(SignBit, VT));
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006309 AddToWorkList(X.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00006310
Andrew Trickef9de2a2013-05-25 02:42:55 +00006311 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006312 VT, N0.getOperand(0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006313 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006314 Cst, DAG.getConstant(~SignBit, VT));
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006315 AddToWorkList(Cst.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00006316
Andrew Trickef9de2a2013-05-25 02:42:55 +00006317 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006318 }
Chris Lattner888560d2008-01-27 17:42:27 +00006319 }
Evan Chengb980f6f2008-05-12 23:04:07 +00006320
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00006321 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
Evan Chengb980f6f2008-05-12 23:04:07 +00006322 if (N0.getOpcode() == ISD::BUILD_PAIR) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00006323 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6324 if (CombineLD.getNode())
Evan Chengb980f6f2008-05-12 23:04:07 +00006325 return CombineLD;
6326 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006327
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006328 return SDValue();
Chris Lattnera1874602005-12-23 05:30:37 +00006329}
6330
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006331SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00006332 EVT VT = N->getValueType(0);
Evan Chengb980f6f2008-05-12 23:04:07 +00006333 return CombineConsecutiveLoads(N, VT);
6334}
6335
Wesley Peck527da1b2010-11-23 03:31:01 +00006336/// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
Scott Michelcf0da6c2009-02-17 22:15:04 +00006337/// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
Chris Lattnere4e64b62006-04-02 02:53:43 +00006338/// destination element value type.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006339SDValue DAGCombiner::
Wesley Peck527da1b2010-11-23 03:31:01 +00006340ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00006341 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006342
Chris Lattnere4e64b62006-04-02 02:53:43 +00006343 // If this is already the right type, we're done.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006344 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006345
Duncan Sands13237ac2008-06-06 12:08:01 +00006346 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6347 unsigned DstBitSize = DstEltVT.getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006348
Chris Lattnere4e64b62006-04-02 02:53:43 +00006349 // If this is a conversion of N elements of one type to N elements of another
6350 // type, convert each element. This handles FP<->INT cases.
6351 if (SrcBitSize == DstBitSize) {
Nate Begeman317b9692010-07-27 18:02:18 +00006352 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6353 BV->getValueType(0).getVectorNumElements());
6354
6355 // Due to the FP element handling below calling this routine recursively,
6356 // we can end up with a scalar-to-vector node here.
6357 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006358 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6359 DAG.getNode(ISD::BITCAST, SDLoc(BV),
Nate Begeman317b9692010-07-27 18:02:18 +00006360 DstEltVT, BV->getOperand(0)));
Wesley Peck527da1b2010-11-23 03:31:01 +00006361
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006362 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +00006363 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
Bob Wilson59dbbb22009-04-13 22:05:19 +00006364 SDValue Op = BV->getOperand(i);
6365 // If the vector element type is not legal, the BUILD_VECTOR operands
6366 // are promoted and implicitly truncated. Make that explicit here.
Bob Wilsonda188eb2009-04-20 17:27:09 +00006367 if (Op.getValueType() != SrcEltVT)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006368 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6369 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
Bob Wilson59dbbb22009-04-13 22:05:19 +00006370 DstEltVT, Op));
Gabor Greiff304a7a2008-08-28 21:40:38 +00006371 AddToWorkList(Ops.back().getNode());
Chris Lattner098c01e2006-04-08 04:15:24 +00006372 }
Craig Topper48d114b2014-04-26 18:35:24 +00006373 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006374 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006375
Chris Lattnere4e64b62006-04-02 02:53:43 +00006376 // Otherwise, we're growing or shrinking the elements. To avoid having to
6377 // handle annoying details of growing/shrinking FP values, we convert them to
6378 // int first.
Duncan Sands13237ac2008-06-06 12:08:01 +00006379 if (SrcEltVT.isFloatingPoint()) {
Chris Lattnere4e64b62006-04-02 02:53:43 +00006380 // Convert the input float vector to a int vector where the elements are the
6381 // same sizes.
Owen Anderson9f944592009-08-11 20:47:22 +00006382 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
Owen Anderson117c9e82009-08-12 00:36:31 +00006383 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
Wesley Peck527da1b2010-11-23 03:31:01 +00006384 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
Chris Lattnere4e64b62006-04-02 02:53:43 +00006385 SrcEltVT = IntVT;
6386 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006387
Chris Lattnere4e64b62006-04-02 02:53:43 +00006388 // Now we know the input is an integer vector. If the output is a FP type,
6389 // convert to integer first, then to FP of the right size.
Duncan Sands13237ac2008-06-06 12:08:01 +00006390 if (DstEltVT.isFloatingPoint()) {
Owen Anderson9f944592009-08-11 20:47:22 +00006391 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
Owen Anderson117c9e82009-08-12 00:36:31 +00006392 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
Wesley Peck527da1b2010-11-23 03:31:01 +00006393 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006394
Chris Lattnere4e64b62006-04-02 02:53:43 +00006395 // Next, convert to FP elements of the same size.
Wesley Peck527da1b2010-11-23 03:31:01 +00006396 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006397 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006398
Chris Lattnere4e64b62006-04-02 02:53:43 +00006399 // Okay, we know the src/dst types are both integers of differing types.
6400 // Handling growing first.
Duncan Sands13237ac2008-06-06 12:08:01 +00006401 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
Chris Lattnere4e64b62006-04-02 02:53:43 +00006402 if (SrcBitSize < DstBitSize) {
6403 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
Scott Michelcf0da6c2009-02-17 22:15:04 +00006404
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006405 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +00006406 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
Chris Lattnere4e64b62006-04-02 02:53:43 +00006407 i += NumInputsPerOutput) {
6408 bool isLE = TLI.isLittleEndian();
Dan Gohmane1c4f992008-03-03 23:51:38 +00006409 APInt NewBits = APInt(DstBitSize, 0);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006410 bool EltIsUndef = true;
6411 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6412 // Shift the previously computed bits over.
6413 NewBits <<= SrcBitSize;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006414 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006415 if (Op.getOpcode() == ISD::UNDEF) continue;
6416 EltIsUndef = false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00006417
Jay Foad583abbc2010-12-07 08:25:19 +00006418 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
Dan Gohmanecd40a32010-04-12 02:24:01 +00006419 zextOrTrunc(SrcBitSize).zext(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006420 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006421
Chris Lattnere4e64b62006-04-02 02:53:43 +00006422 if (EltIsUndef)
Dale Johannesen84935752009-02-06 23:05:02 +00006423 Ops.push_back(DAG.getUNDEF(DstEltVT));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006424 else
6425 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6426 }
6427
Owen Anderson117c9e82009-08-12 00:36:31 +00006428 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
Craig Topper48d114b2014-04-26 18:35:24 +00006429 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006430 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006431
Chris Lattnere4e64b62006-04-02 02:53:43 +00006432 // Finally, this must be the case where we are shrinking elements: each input
6433 // turns into multiple outputs.
Evan Cheng6200c222008-02-18 23:04:32 +00006434 bool isS2V = ISD::isScalarToVector(BV);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006435 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
Owen Anderson117c9e82009-08-12 00:36:31 +00006436 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6437 NumOutputsPerInput*BV->getNumOperands());
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006438 SmallVector<SDValue, 8> Ops;
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006439
Dan Gohmana8665142007-06-25 16:23:39 +00006440 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
Chris Lattnere4e64b62006-04-02 02:53:43 +00006441 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6442 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
Dale Johannesen84935752009-02-06 23:05:02 +00006443 Ops.push_back(DAG.getUNDEF(DstEltVT));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006444 continue;
6445 }
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006446
Jay Foad583abbc2010-12-07 08:25:19 +00006447 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6448 getAPIntValue().zextOrTrunc(SrcBitSize);
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006449
Chris Lattnere4e64b62006-04-02 02:53:43 +00006450 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
Jay Foad583abbc2010-12-07 08:25:19 +00006451 APInt ThisVal = OpVal.trunc(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006452 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
Jay Foad583abbc2010-12-07 08:25:19 +00006453 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
Evan Cheng6200c222008-02-18 23:04:32 +00006454 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
Andrew Trickef9de2a2013-05-25 02:42:55 +00006455 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006456 Ops[0]);
Dan Gohmane1c4f992008-03-03 23:51:38 +00006457 OpVal = OpVal.lshr(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006458 }
6459
6460 // For big endian targets, swap the order of the pieces of each element.
Duncan Sands7377f5f2008-02-11 10:37:04 +00006461 if (TLI.isBigEndian())
Chris Lattnere4e64b62006-04-02 02:53:43 +00006462 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6463 }
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006464
Craig Topper48d114b2014-04-26 18:35:24 +00006465 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006466}
6467
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006468SDValue DAGCombiner::visitFADD(SDNode *N) {
6469 SDValue N0 = N->getOperand(0);
6470 SDValue N1 = N->getOperand(1);
Nate Begeman418c6e42005-10-18 00:28:13 +00006471 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6472 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006473 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006474
Dan Gohmana8665142007-06-25 16:23:39 +00006475 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006476 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006477 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006478 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006479 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006480
Lang Hamesa33db652012-06-14 20:37:15 +00006481 // fold (fadd c1, c2) -> c1 + c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006482 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006483 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
Nate Begeman418c6e42005-10-18 00:28:13 +00006484 // canonicalize constant to RHS
6485 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006486 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006487 // fold (fadd A, 0) -> A
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006488 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6489 N1CFP->getValueAPF().isZero())
Dan Gohman1f3411d2009-01-22 21:58:43 +00006490 return N0;
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006491 // fold (fadd A, (fneg B)) -> (fsub A, B)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006492 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
Nadav Rotem841c9a82012-09-20 08:53:31 +00006493 isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006494 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006495 GetNegatedExpression(N1, DAG, LegalOperations));
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006496 // fold (fadd (fneg A), B) -> (fsub B, A)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006497 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
Nadav Rotem841c9a82012-09-20 08:53:31 +00006498 isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006499 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006500 GetNegatedExpression(N0, DAG, LegalOperations));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006501
Chris Lattner0199fd62007-01-08 23:04:05 +00006502 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006503 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6504 N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6505 isa<ConstantFPSDNode>(N0.getOperand(1)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006506 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6507 DAG.getNode(ISD::FADD, SDLoc(N), VT,
Bill Wendlinga6c75ff2009-02-01 11:19:36 +00006508 N0.getOperand(1), N1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006509
Shuxin Yang93b1f122013-03-25 22:52:29 +00006510 // No FP constant should be created after legalization as Instruction
6511 // Selection pass has hard time in dealing with FP constant.
6512 //
6513 // We don't need test this condition for transformation like following, as
6514 // the DAG being transformed implies it is legal to take FP constant as
6515 // operand.
Stephen Lincfe7f352013-07-08 00:37:03 +00006516 //
Shuxin Yang93b1f122013-03-25 22:52:29 +00006517 // (fadd (fmul c, x), x) -> (fmul c+1, x)
Stephen Lincfe7f352013-07-08 00:37:03 +00006518 //
Shuxin Yang93b1f122013-03-25 22:52:29 +00006519 bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6520
Owen Andersonb351c8d2012-11-01 02:00:53 +00006521 // If allow, fold (fadd (fneg x), x) -> 0.0
Shuxin Yang93b1f122013-03-25 22:52:29 +00006522 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006523 N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
Owen Andersonb351c8d2012-11-01 02:00:53 +00006524 return DAG.getConstantFP(0.0, VT);
Owen Andersonb351c8d2012-11-01 02:00:53 +00006525
6526 // If allow, fold (fadd x, (fneg x)) -> 0.0
Shuxin Yang93b1f122013-03-25 22:52:29 +00006527 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006528 N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
Owen Andersonb351c8d2012-11-01 02:00:53 +00006529 return DAG.getConstantFP(0.0, VT);
Owen Andersonb351c8d2012-11-01 02:00:53 +00006530
Owen Andersoncc61f872012-08-30 23:35:16 +00006531 // In unsafe math mode, we can fold chains of FADD's of the same value
6532 // into multiplications. This transform is not safe in general because
6533 // we are reducing the number of rounding steps.
6534 if (DAG.getTarget().Options.UnsafeFPMath &&
6535 TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6536 !N0CFP && !N1CFP) {
6537 if (N0.getOpcode() == ISD::FMUL) {
6538 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6539 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6540
Stephen Line31f2d22013-06-14 18:17:35 +00006541 // (fadd (fmul c, x), x) -> (fmul x, c+1)
Owen Andersoncc61f872012-08-30 23:35:16 +00006542 if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006543 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006544 SDValue(CFP00, 0),
6545 DAG.getConstantFP(1.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006546 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006547 N1, NewCFP);
6548 }
6549
Stephen Line31f2d22013-06-14 18:17:35 +00006550 // (fadd (fmul x, c), x) -> (fmul x, c+1)
Owen Andersoncc61f872012-08-30 23:35:16 +00006551 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006552 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006553 SDValue(CFP01, 0),
6554 DAG.getConstantFP(1.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006555 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006556 N1, NewCFP);
6557 }
6558
Stephen Line31f2d22013-06-14 18:17:35 +00006559 // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
Owen Andersoncc61f872012-08-30 23:35:16 +00006560 if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6561 N1.getOperand(0) == N1.getOperand(1) &&
6562 N0.getOperand(1) == N1.getOperand(0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006563 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006564 SDValue(CFP00, 0),
6565 DAG.getConstantFP(2.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006566 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006567 N0.getOperand(1), NewCFP);
6568 }
6569
Stephen Line31f2d22013-06-14 18:17:35 +00006570 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
Owen Andersoncc61f872012-08-30 23:35:16 +00006571 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6572 N1.getOperand(0) == N1.getOperand(1) &&
6573 N0.getOperand(0) == N1.getOperand(0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006574 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006575 SDValue(CFP01, 0),
6576 DAG.getConstantFP(2.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006577 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006578 N0.getOperand(0), NewCFP);
6579 }
6580 }
6581
6582 if (N1.getOpcode() == ISD::FMUL) {
6583 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6584 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6585
Stephen Line31f2d22013-06-14 18:17:35 +00006586 // (fadd x, (fmul c, x)) -> (fmul x, c+1)
Owen Andersoncc61f872012-08-30 23:35:16 +00006587 if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006588 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006589 SDValue(CFP10, 0),
6590 DAG.getConstantFP(1.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006591 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006592 N0, NewCFP);
6593 }
6594
Stephen Line31f2d22013-06-14 18:17:35 +00006595 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
Owen Andersoncc61f872012-08-30 23:35:16 +00006596 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006597 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006598 SDValue(CFP11, 0),
6599 DAG.getConstantFP(1.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006600 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006601 N0, NewCFP);
6602 }
6603
Owen Andersoncc61f872012-08-30 23:35:16 +00006604
Stephen Line31f2d22013-06-14 18:17:35 +00006605 // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6606 if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6607 N0.getOperand(0) == N0.getOperand(1) &&
6608 N1.getOperand(1) == N0.getOperand(0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006609 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006610 SDValue(CFP10, 0),
6611 DAG.getConstantFP(2.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006612 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Stephen Line31f2d22013-06-14 18:17:35 +00006613 N1.getOperand(1), NewCFP);
Owen Andersoncc61f872012-08-30 23:35:16 +00006614 }
6615
Stephen Line31f2d22013-06-14 18:17:35 +00006616 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6617 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6618 N0.getOperand(0) == N0.getOperand(1) &&
6619 N1.getOperand(0) == N0.getOperand(0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006620 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006621 SDValue(CFP11, 0),
6622 DAG.getConstantFP(2.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006623 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Stephen Line31f2d22013-06-14 18:17:35 +00006624 N1.getOperand(0), NewCFP);
Owen Andersoncc61f872012-08-30 23:35:16 +00006625 }
6626 }
6627
Shuxin Yang93b1f122013-03-25 22:52:29 +00006628 if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006629 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
Stephen Lin4e69d012013-06-14 21:33:58 +00006630 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006631 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006632 (N0.getOperand(0) == N1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006633 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006634 N1, DAG.getConstantFP(3.0, VT));
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006635 }
6636
Shuxin Yang93b1f122013-03-25 22:52:29 +00006637 if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006638 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
Stephen Lin4e69d012013-06-14 21:33:58 +00006639 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006640 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006641 N1.getOperand(0) == N0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006642 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006643 N0, DAG.getConstantFP(3.0, VT));
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006644 }
6645
Stephen Lin4e69d012013-06-14 21:33:58 +00006646 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
Shuxin Yang93b1f122013-03-25 22:52:29 +00006647 if (AllowNewFpConst &&
6648 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
Owen Andersoncc61f872012-08-30 23:35:16 +00006649 N0.getOperand(0) == N0.getOperand(1) &&
6650 N1.getOperand(0) == N1.getOperand(1) &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006651 N0.getOperand(0) == N1.getOperand(0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006652 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006653 N0.getOperand(0),
6654 DAG.getConstantFP(4.0, VT));
Owen Andersoncc61f872012-08-30 23:35:16 +00006655 }
6656
Lang Hames39fb1d02012-06-19 22:51:23 +00006657 // FADD -> FMA combines:
Lang Hamesb8650f12012-06-22 01:09:09 +00006658 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
Lang Hames39fb1d02012-06-19 22:51:23 +00006659 DAG.getTarget().Options.UnsafeFPMath) &&
Stephen Lin73de7bf2013-07-09 18:16:56 +00006660 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6661 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
Lang Hames39fb1d02012-06-19 22:51:23 +00006662
6663 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
Stephen Lin8e8424e2013-07-09 00:44:49 +00006664 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006665 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006666 N0.getOperand(0), N0.getOperand(1), N1);
Owen Andersoncc61f872012-08-30 23:35:16 +00006667
Michael Liaoec3850122012-09-01 04:09:16 +00006668 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
Lang Hames39fb1d02012-06-19 22:51:23 +00006669 // Note: Commutes FADD operands.
Stephen Lin8e8424e2013-07-09 00:44:49 +00006670 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006671 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006672 N1.getOperand(0), N1.getOperand(1), N0);
Lang Hames39fb1d02012-06-19 22:51:23 +00006673 }
6674
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006675 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006676}
6677
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006678SDValue DAGCombiner::visitFSUB(SDNode *N) {
6679 SDValue N0 = N->getOperand(0);
6680 SDValue N1 = N->getOperand(1);
Nate Begeman418c6e42005-10-18 00:28:13 +00006681 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6682 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006683 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006684 SDLoc dl(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006685
Dan Gohmana8665142007-06-25 16:23:39 +00006686 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006687 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006688 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006689 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006690 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006691
Nate Begeman418c6e42005-10-18 00:28:13 +00006692 // fold (fsub c1, c2) -> c1-c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006693 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006694 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006695 // fold (fsub A, 0) -> A
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006696 if (DAG.getTarget().Options.UnsafeFPMath &&
6697 N1CFP && N1CFP->getValueAPF().isZero())
Dan Gohman1275e282009-01-23 19:10:37 +00006698 return N0;
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006699 // fold (fsub 0, B) -> -B
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006700 if (DAG.getTarget().Options.UnsafeFPMath &&
6701 N0CFP && N0CFP->getValueAPF().isZero()) {
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006702 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006703 return GetNegatedExpression(N1, DAG, LegalOperations);
Dan Gohman1f3411d2009-01-22 21:58:43 +00006704 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006705 return DAG.getNode(ISD::FNEG, dl, VT, N1);
Dan Gohman9a708232007-07-02 15:48:56 +00006706 }
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006707 // fold (fsub A, (fneg B)) -> (fadd A, B)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006708 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006709 return DAG.getNode(ISD::FADD, dl, VT, N0,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006710 GetNegatedExpression(N1, DAG, LegalOperations));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006711
Bill Wendlingdf170db2012-03-15 05:12:00 +00006712 // If 'unsafe math' is enabled, fold
Owen Andersonab63d842012-05-07 20:51:25 +00006713 // (fsub x, x) -> 0.0 &
Bill Wendlingdf170db2012-03-15 05:12:00 +00006714 // (fsub x, (fadd x, y)) -> (fneg y) &
6715 // (fsub x, (fadd y, x)) -> (fneg y)
6716 if (DAG.getTarget().Options.UnsafeFPMath) {
Owen Andersonab63d842012-05-07 20:51:25 +00006717 if (N0 == N1)
6718 return DAG.getConstantFP(0.0f, VT);
6719
Bill Wendlingdf170db2012-03-15 05:12:00 +00006720 if (N1.getOpcode() == ISD::FADD) {
6721 SDValue N10 = N1->getOperand(0);
6722 SDValue N11 = N1->getOperand(1);
6723
6724 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6725 &DAG.getTarget().Options))
6726 return GetNegatedExpression(N11, DAG, LegalOperations);
Stephen Lin10947502013-07-10 20:47:39 +00006727
Stephen Lin8e8424e2013-07-09 00:44:49 +00006728 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6729 &DAG.getTarget().Options))
Bill Wendlingdf170db2012-03-15 05:12:00 +00006730 return GetNegatedExpression(N10, DAG, LegalOperations);
6731 }
6732 }
6733
Lang Hames39fb1d02012-06-19 22:51:23 +00006734 // FSUB -> FMA combines:
Lang Hamesb8650f12012-06-22 01:09:09 +00006735 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
Lang Hames39fb1d02012-06-19 22:51:23 +00006736 DAG.getTarget().Options.UnsafeFPMath) &&
Stephen Lin73de7bf2013-07-09 18:16:56 +00006737 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6738 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
Lang Hames39fb1d02012-06-19 22:51:23 +00006739
6740 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
Stephen Lin8e8424e2013-07-09 00:44:49 +00006741 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006742 return DAG.getNode(ISD::FMA, dl, VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006743 N0.getOperand(0), N0.getOperand(1),
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006744 DAG.getNode(ISD::FNEG, dl, VT, N1));
Lang Hames39fb1d02012-06-19 22:51:23 +00006745
6746 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6747 // Note: Commutes FSUB operands.
Stephen Lin10947502013-07-10 20:47:39 +00006748 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006749 return DAG.getNode(ISD::FMA, dl, VT,
6750 DAG.getNode(ISD::FNEG, dl, VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006751 N1.getOperand(0)),
6752 N1.getOperand(1), N0);
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006753
Stephen Lin8e8424e2013-07-09 00:44:49 +00006754 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
Stephen Lincfe7f352013-07-08 00:37:03 +00006755 if (N0.getOpcode() == ISD::FNEG &&
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006756 N0.getOperand(0).getOpcode() == ISD::FMUL &&
6757 N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6758 SDValue N00 = N0.getOperand(0).getOperand(0);
6759 SDValue N01 = N0.getOperand(0).getOperand(1);
6760 return DAG.getNode(ISD::FMA, dl, VT,
6761 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6762 DAG.getNode(ISD::FNEG, dl, VT, N1));
6763 }
Lang Hames39fb1d02012-06-19 22:51:23 +00006764 }
6765
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006766 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006767}
6768
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006769SDValue DAGCombiner::visitFMUL(SDNode *N) {
6770 SDValue N0 = N->getOperand(0);
6771 SDValue N1 = N->getOperand(1);
Nate Begemanec48a1b2005-10-17 20:40:11 +00006772 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6773 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006774 EVT VT = N->getValueType(0);
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006775 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006776
Dan Gohmana8665142007-06-25 16:23:39 +00006777 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006778 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006779 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006780 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006781 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006782
Nate Begemanec48a1b2005-10-17 20:40:11 +00006783 // fold (fmul c1, c2) -> c1*c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006784 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006785 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
Nate Begemanec48a1b2005-10-17 20:40:11 +00006786 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00006787 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006788 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
Bill Wendling3dc5d242009-01-30 22:57:07 +00006789 // fold (fmul A, 0) -> 0
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006790 if (DAG.getTarget().Options.UnsafeFPMath &&
6791 N1CFP && N1CFP->getValueAPF().isZero())
Dan Gohman1f3411d2009-01-22 21:58:43 +00006792 return N1;
Dan Gohman7b6b5dd2009-06-04 17:12:12 +00006793 // fold (fmul A, 0) -> 0, vector edition.
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006794 if (DAG.getTarget().Options.UnsafeFPMath &&
6795 ISD::isBuildVectorAllZeros(N1.getNode()))
Dan Gohman7b6b5dd2009-06-04 17:12:12 +00006796 return N1;
Owen Andersonb5f167c2012-05-02 21:32:35 +00006797 // fold (fmul A, 1.0) -> A
6798 if (N1CFP && N1CFP->isExactlyValue(1.0))
6799 return N0;
Nate Begemanec48a1b2005-10-17 20:40:11 +00006800 // fold (fmul X, 2.0) -> (fadd X, X)
6801 if (N1CFP && N1CFP->isExactlyValue(+2.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006802 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
Dan Gohmanb7170912009-08-10 16:50:32 +00006803 // fold (fmul X, -1.0) -> (fneg X)
Chris Lattnere49c9742007-05-14 22:04:50 +00006804 if (N1CFP && N1CFP->isExactlyValue(-1.0))
Dan Gohman1f3411d2009-01-22 21:58:43 +00006805 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006806 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006807
Bill Wendling3dc5d242009-01-30 22:57:07 +00006808 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006809 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006810 &DAG.getTarget().Options)) {
Stephen Lincfe7f352013-07-08 00:37:03 +00006811 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006812 &DAG.getTarget().Options)) {
Chris Lattnere49c9742007-05-14 22:04:50 +00006813 // Both can be negated for free, check to see if at least one is cheaper
6814 // negated.
6815 if (LHSNeg == 2 || RHSNeg == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006816 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006817 GetNegatedExpression(N0, DAG, LegalOperations),
6818 GetNegatedExpression(N1, DAG, LegalOperations));
Chris Lattnere49c9742007-05-14 22:04:50 +00006819 }
6820 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006821
Chris Lattner0199fd62007-01-08 23:04:05 +00006822 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006823 if (DAG.getTarget().Options.UnsafeFPMath &&
6824 N1CFP && N0.getOpcode() == ISD::FMUL &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00006825 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006826 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6827 DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Dale Johannesen400dc2e2009-02-06 21:50:26 +00006828 N0.getOperand(1), N1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006829
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006830 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006831}
6832
Owen Anderson41b06652012-05-02 22:17:40 +00006833SDValue DAGCombiner::visitFMA(SDNode *N) {
6834 SDValue N0 = N->getOperand(0);
6835 SDValue N1 = N->getOperand(1);
6836 SDValue N2 = N->getOperand(2);
6837 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6838 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6839 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006840 SDLoc dl(N);
Owen Anderson41b06652012-05-02 22:17:40 +00006841
Owen Andersonb351c8d2012-11-01 02:00:53 +00006842 if (DAG.getTarget().Options.UnsafeFPMath) {
6843 if (N0CFP && N0CFP->isZero())
6844 return N2;
6845 if (N1CFP && N1CFP->isZero())
6846 return N2;
6847 }
Owen Anderson41b06652012-05-02 22:17:40 +00006848 if (N0CFP && N0CFP->isExactlyValue(1.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006849 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
Owen Anderson41b06652012-05-02 22:17:40 +00006850 if (N1CFP && N1CFP->isExactlyValue(1.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006851 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
Owen Anderson41b06652012-05-02 22:17:40 +00006852
Owen Andersonc7aaf522012-05-30 18:50:39 +00006853 // Canonicalize (fma c, x, y) -> (fma x, c, y)
Owen Anderson0eda3e12012-05-30 18:54:50 +00006854 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006855 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
Owen Andersonc7aaf522012-05-30 18:50:39 +00006856
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006857 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6858 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6859 N2.getOpcode() == ISD::FMUL &&
6860 N0 == N2.getOperand(0) &&
6861 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6862 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6863 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6864 }
6865
6866
6867 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6868 if (DAG.getTarget().Options.UnsafeFPMath &&
6869 N0.getOpcode() == ISD::FMUL && N1CFP &&
6870 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6871 return DAG.getNode(ISD::FMA, dl, VT,
6872 N0.getOperand(0),
6873 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6874 N2);
6875 }
6876
6877 // (fma x, 1, y) -> (fadd x, y)
6878 // (fma x, -1, y) -> (fadd (fneg x), y)
6879 if (N1CFP) {
6880 if (N1CFP->isExactlyValue(1.0))
6881 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6882
6883 if (N1CFP->isExactlyValue(-1.0) &&
6884 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6885 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6886 AddToWorkList(RHSNeg.getNode());
6887 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6888 }
6889 }
6890
6891 // (fma x, c, x) -> (fmul x, (c+1))
Stephen Lin8e8424e2013-07-09 00:44:49 +00006892 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6893 return DAG.getNode(ISD::FMUL, dl, VT, N0,
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006894 DAG.getNode(ISD::FADD, dl, VT,
6895 N1, DAG.getConstantFP(1.0, VT)));
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006896
6897 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6898 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006899 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6900 return DAG.getNode(ISD::FMUL, dl, VT, N0,
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006901 DAG.getNode(ISD::FADD, dl, VT,
6902 N1, DAG.getConstantFP(-1.0, VT)));
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006903
6904
Owen Anderson41b06652012-05-02 22:17:40 +00006905 return SDValue();
6906}
6907
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006908SDValue DAGCombiner::visitFDIV(SDNode *N) {
6909 SDValue N0 = N->getOperand(0);
6910 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00006911 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6912 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006913 EVT VT = N->getValueType(0);
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006914 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006915
Dan Gohmana8665142007-06-25 16:23:39 +00006916 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006917 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006918 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006919 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006920 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006921
Nate Begeman569c4392006-01-18 22:35:16 +00006922 // fold (fdiv c1, c2) -> c1/c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006923 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006924 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006925
Duncan Sands2f1dc382012-04-08 18:08:12 +00006926 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006927 if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
Duncan Sands5f8397a2012-04-07 20:04:00 +00006928 // Compute the reciprocal 1.0 / c2.
6929 APFloat N1APF = N1CFP->getValueAPF();
6930 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6931 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
Duncan Sands4f530742012-04-10 20:35:27 +00006932 // Only do the transform if the reciprocal is a legal fp immediate that
6933 // isn't too nasty (eg NaN, denormal, ...).
6934 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
Anton Korobeynikov4d1220d2012-04-10 13:22:49 +00006935 (!LegalOperations ||
6936 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6937 // backend)... we should handle this gracefully after Legalize.
6938 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6939 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6940 TLI.isFPImmLegal(Recip, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006941 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
Duncan Sands5f8397a2012-04-07 20:04:00 +00006942 DAG.getConstantFP(Recip, VT));
6943 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006944
Bill Wendling3dc5d242009-01-30 22:57:07 +00006945 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006946 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006947 &DAG.getTarget().Options)) {
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006948 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006949 &DAG.getTarget().Options)) {
Chris Lattnere49c9742007-05-14 22:04:50 +00006950 // Both can be negated for free, check to see if at least one is cheaper
6951 // negated.
6952 if (LHSNeg == 2 || RHSNeg == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006953 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006954 GetNegatedExpression(N0, DAG, LegalOperations),
6955 GetNegatedExpression(N1, DAG, LegalOperations));
Chris Lattnere49c9742007-05-14 22:04:50 +00006956 }
6957 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006958
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006959 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006960}
6961
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006962SDValue DAGCombiner::visitFREM(SDNode *N) {
6963 SDValue N0 = N->getOperand(0);
6964 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00006965 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6966 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006967 EVT VT = N->getValueType(0);
Chris Lattner6f3b5772005-09-28 22:28:18 +00006968
Nate Begeman569c4392006-01-18 22:35:16 +00006969 // fold (frem c1, c2) -> fmod(c1,c2)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006970 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006971 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
Dan Gohmana8665142007-06-25 16:23:39 +00006972
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006973 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006974}
6975
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006976SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6977 SDValue N0 = N->getOperand(0);
6978 SDValue N1 = N->getOperand(1);
Chris Lattner3bc40502006-03-05 05:30:57 +00006979 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6980 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006981 EVT VT = N->getValueType(0);
Chris Lattner3bc40502006-03-05 05:30:57 +00006982
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006983 if (N0CFP && N1CFP) // Constant fold
Andrew Trickef9de2a2013-05-25 02:42:55 +00006984 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006985
Chris Lattner3bc40502006-03-05 05:30:57 +00006986 if (N1CFP) {
Dale Johannesenb6d2bec2007-08-26 01:18:27 +00006987 const APFloat& V = N1CFP->getValueAPF();
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00006988 // copysign(x, c1) -> fabs(x) iff ispos(c1)
6989 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
Dan Gohman1f3411d2009-01-22 21:58:43 +00006990 if (!V.isNegative()) {
6991 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006992 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Dan Gohman1f3411d2009-01-22 21:58:43 +00006993 } else {
6994 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006995 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6996 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
Dan Gohman1f3411d2009-01-22 21:58:43 +00006997 }
Chris Lattner3bc40502006-03-05 05:30:57 +00006998 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006999
Chris Lattner3bc40502006-03-05 05:30:57 +00007000 // copysign(fabs(x), y) -> copysign(x, y)
7001 // copysign(fneg(x), y) -> copysign(x, y)
7002 // copysign(copysign(x,z), y) -> copysign(x, y)
7003 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7004 N0.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007005 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007006 N0.getOperand(0), N1);
Chris Lattner3bc40502006-03-05 05:30:57 +00007007
7008 // copysign(x, abs(y)) -> abs(x)
7009 if (N1.getOpcode() == ISD::FABS)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007010 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007011
Chris Lattner3bc40502006-03-05 05:30:57 +00007012 // copysign(x, copysign(y,z)) -> copysign(x, z)
7013 if (N1.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007014 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007015 N0, N1.getOperand(1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00007016
Chris Lattner3bc40502006-03-05 05:30:57 +00007017 // copysign(x, fp_extend(y)) -> copysign(x, y)
7018 // copysign(x, fp_round(y)) -> copysign(x, y)
7019 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007020 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007021 N0, N1.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00007022
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007023 return SDValue();
Chris Lattner3bc40502006-03-05 05:30:57 +00007024}
7025
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007026SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7027 SDValue N0 = N->getOperand(0);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00007028 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007029 EVT VT = N->getValueType(0);
7030 EVT OpVT = N0.getValueType();
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007031
Nate Begeman21158fc2005-09-01 00:19:25 +00007032 // fold (sint_to_fp c1) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007033 if (N0C &&
Stuart Hastings6b4007d2011-03-02 19:36:30 +00007034 // ...but only if the target supports immediate floating-point values
Eli Friedman9d448e42011-11-12 00:35:34 +00007035 (!LegalOperations ||
Evan Cheng4c0bd962011-06-21 06:01:08 +00007036 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007037 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007038
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007039 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7040 // but UINT_TO_FP is legal on this target, try to convert.
Dan Gohman4aa18462009-01-28 17:46:25 +00007041 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7042 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
Scott Michelcf0da6c2009-02-17 22:15:04 +00007043 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007044 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007045 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007046 }
Bill Wendling0bd29742009-01-30 23:15:49 +00007047
Alp Tokercb402912014-01-24 17:20:08 +00007048 // The next optimizations are desirable only if SELECT_CC can be lowered.
Tom Stellard3787b122014-06-10 16:01:29 +00007049 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
Nadav Rotem90560762012-07-23 07:59:50 +00007050 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7051 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7052 !VT.isVector() &&
7053 (!LegalOperations ||
7054 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7055 SDValue Ops[] =
7056 { N0.getOperand(0), N0.getOperand(1),
7057 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7058 N0.getOperand(2) };
Craig Topper48d114b2014-04-26 18:35:24 +00007059 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
Nadav Rotem90560762012-07-23 07:59:50 +00007060 }
Owen Andersond4b841f2012-07-09 20:31:12 +00007061
Nadav Rotem90560762012-07-23 07:59:50 +00007062 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7063 // (select_cc x, y, 1.0, 0.0,, cc)
7064 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7065 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7066 (!LegalOperations ||
7067 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7068 SDValue Ops[] =
7069 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7070 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7071 N0.getOperand(0).getOperand(2) };
Craig Topper48d114b2014-04-26 18:35:24 +00007072 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
Nadav Rotem90560762012-07-23 07:59:50 +00007073 }
Owen Andersond4b841f2012-07-09 20:31:12 +00007074 }
7075
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007076 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007077}
7078
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007079SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7080 SDValue N0 = N->getOperand(0);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00007081 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007082 EVT VT = N->getValueType(0);
7083 EVT OpVT = N0.getValueType();
Nate Begeman569c4392006-01-18 22:35:16 +00007084
Nate Begeman21158fc2005-09-01 00:19:25 +00007085 // fold (uint_to_fp c1) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007086 if (N0C &&
Stuart Hastings6b4007d2011-03-02 19:36:30 +00007087 // ...but only if the target supports immediate floating-point values
Eli Friedman9d448e42011-11-12 00:35:34 +00007088 (!LegalOperations ||
Evan Cheng4c0bd962011-06-21 06:01:08 +00007089 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007090 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007091
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007092 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7093 // but SINT_TO_FP is legal on this target, try to convert.
Dan Gohman4aa18462009-01-28 17:46:25 +00007094 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7095 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
Scott Michelcf0da6c2009-02-17 22:15:04 +00007096 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007097 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007098 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007099 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007100
Alp Tokercb402912014-01-24 17:20:08 +00007101 // The next optimizations are desirable only if SELECT_CC can be lowered.
Tom Stellard3787b122014-06-10 16:01:29 +00007102 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
Nadav Rotem90560762012-07-23 07:59:50 +00007103 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
Owen Andersond4b841f2012-07-09 20:31:12 +00007104
Nadav Rotem90560762012-07-23 07:59:50 +00007105 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7106 (!LegalOperations ||
7107 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7108 SDValue Ops[] =
7109 { N0.getOperand(0), N0.getOperand(1),
7110 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
7111 N0.getOperand(2) };
Craig Topper48d114b2014-04-26 18:35:24 +00007112 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
Nadav Rotem90560762012-07-23 07:59:50 +00007113 }
7114 }
Owen Andersond4b841f2012-07-09 20:31:12 +00007115
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007116 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007117}
7118
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007119SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7120 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007121 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007122 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007123
Nate Begeman21158fc2005-09-01 00:19:25 +00007124 // fold (fp_to_sint c1fp) -> c1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00007125 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007126 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
Bill Wendling0bd29742009-01-30 23:15:49 +00007127
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007128 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007129}
7130
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007131SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7132 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007133 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007134 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007135
Nate Begeman21158fc2005-09-01 00:19:25 +00007136 // fold (fp_to_uint c1fp) -> c1
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007137 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007138 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
Bill Wendling0bd29742009-01-30 23:15:49 +00007139
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007140 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007141}
7142
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007143SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7144 SDValue N0 = N->getOperand(0);
7145 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00007146 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007147 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007148
Nate Begeman21158fc2005-09-01 00:19:25 +00007149 // fold (fp_round c1fp) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007150 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007151 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007152
Chris Lattner8bb6cb72006-03-13 06:26:26 +00007153 // fold (fp_round (fp_extend x)) -> x
7154 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7155 return N0.getOperand(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007156
Chris Lattner0feb1b02008-01-24 06:45:35 +00007157 // fold (fp_round (fp_round x)) -> (fp_round x)
7158 if (N0.getOpcode() == ISD::FP_ROUND) {
7159 // This is a value preserving truncation if both round's are.
7160 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00007161 N0.getNode()->getConstantOperandVal(1) == 1;
Andrew Trickef9de2a2013-05-25 02:42:55 +00007162 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
Chris Lattner0feb1b02008-01-24 06:45:35 +00007163 DAG.getIntPtrConstant(IsTrunc));
7164 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007165
Chris Lattner8bb6cb72006-03-13 06:26:26 +00007166 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
Gabor Greiff304a7a2008-08-28 21:40:38 +00007167 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007168 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007169 N0.getOperand(0), N1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00007170 AddToWorkList(Tmp.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00007171 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007172 Tmp, N0.getOperand(1));
Chris Lattner8bb6cb72006-03-13 06:26:26 +00007173 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007174
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007175 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007176}
7177
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007178SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7179 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007180 EVT VT = N->getValueType(0);
7181 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
Nate Begeman7cea6ef2005-09-02 21:18:40 +00007182 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007183
Nate Begeman21158fc2005-09-01 00:19:25 +00007184 // fold (fp_round_inreg c1fp) -> c1fp
Chris Lattner4041ab62010-04-15 04:48:01 +00007185 if (N0CFP && isTypeLegal(EVT)) {
Dan Gohmanec270fb2008-09-12 18:08:03 +00007186 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007187 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
Nate Begeman21158fc2005-09-01 00:19:25 +00007188 }
Bill Wendling0bd29742009-01-30 23:15:49 +00007189
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007190 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007191}
7192
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007193SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7194 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007195 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007196 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007197
Chris Lattner5919b482007-12-29 06:55:23 +00007198 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
Scott Michelcf0da6c2009-02-17 22:15:04 +00007199 if (N->hasOneUse() &&
Dan Gohman8e4ac9b2009-01-26 04:35:06 +00007200 N->use_begin()->getOpcode() == ISD::FP_ROUND)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007201 return SDValue();
Chris Lattner72733e52008-01-17 07:00:52 +00007202
Nate Begeman21158fc2005-09-01 00:19:25 +00007203 // fold (fp_extend c1fp) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007204 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007205 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
Chris Lattner72733e52008-01-17 07:00:52 +00007206
7207 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7208 // value of X.
Gabor Greife12264b2008-08-30 19:29:20 +00007209 if (N0.getOpcode() == ISD::FP_ROUND
7210 && N0.getNode()->getConstantOperandVal(1) == 1) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007211 SDValue In = N0.getOperand(0);
Chris Lattner72733e52008-01-17 07:00:52 +00007212 if (In.getValueType() == VT) return In;
Duncan Sands11dd4242008-06-08 20:54:56 +00007213 if (VT.bitsLT(In.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007214 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007215 In, N0.getOperand(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00007216 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
Chris Lattner72733e52008-01-17 07:00:52 +00007217 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007218
Chris Lattner72733e52008-01-17 07:00:52 +00007219 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
Hal Finkeldbc7a8a2013-10-04 22:18:12 +00007220 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007221 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00007222 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00007223 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007224 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007225 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00007226 LN0->getBasePtr(), N0.getValueType(),
7227 LN0->getMemOperand());
Chris Lattner3d265772006-05-05 21:34:35 +00007228 CombineTo(N, ExtLoad);
Bill Wendling0bd29742009-01-30 23:15:49 +00007229 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00007230 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
Bill Wendling0bd29742009-01-30 23:15:49 +00007231 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
Chris Lattner3d265772006-05-05 21:34:35 +00007232 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007233 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattner3d265772006-05-05 21:34:35 +00007234 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00007235
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007236 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007237}
7238
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007239SDValue DAGCombiner::visitFNEG(SDNode *N) {
7240 SDValue N0 = N->getOperand(0);
Anton Korobeynikova6faf602009-10-20 21:37:45 +00007241 EVT VT = N->getValueType(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007242
Craig Topper82384612012-09-11 01:45:21 +00007243 if (VT.isVector()) {
7244 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7245 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topper03f39772012-09-09 22:58:45 +00007246 }
7247
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00007248 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7249 &DAG.getTarget().Options))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007250 return GetNegatedExpression(N0, DAG, LegalOperations);
Dan Gohman9a708232007-07-02 15:48:56 +00007251
Chris Lattner888560d2008-01-27 17:42:27 +00007252 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
7253 // constant pool values.
Owen Anderson98f2c0c2012-04-02 22:10:29 +00007254 if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
Anton Korobeynikova6faf602009-10-20 21:37:45 +00007255 !VT.isVector() &&
7256 N0.getNode()->hasOneUse() &&
7257 N0.getOperand(0).getValueType().isInteger()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007258 SDValue Int = N0.getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007259 EVT IntVT = Int.getValueType();
Duncan Sands13237ac2008-06-06 12:08:01 +00007260 if (IntVT.isInteger() && !IntVT.isVector()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007261 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
Duncan Sands3ed76882009-02-01 18:06:53 +00007262 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
Gabor Greiff304a7a2008-08-28 21:40:38 +00007263 AddToWorkList(Int.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00007264 return DAG.getNode(ISD::BITCAST, SDLoc(N),
Anton Korobeynikova6faf602009-10-20 21:37:45 +00007265 VT, Int);
Chris Lattner888560d2008-01-27 17:42:27 +00007266 }
7267 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007268
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007269 // (fneg (fmul c, x)) -> (fmul -c, x)
7270 if (N0.getOpcode() == ISD::FMUL) {
7271 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
Tim Northover820e0412014-05-02 17:25:02 +00007272 if (CFP1) {
7273 APFloat CVal = CFP1->getValueAPF();
7274 CVal.changeSign();
7275 if (Level >= AfterLegalizeDAG &&
7276 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
7277 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
7278 return DAG.getNode(
7279 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
7280 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
7281 }
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007282 }
7283
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007284 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007285}
7286
Owen Andersona40319b2012-08-13 23:32:49 +00007287SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7288 SDValue N0 = N->getOperand(0);
7289 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7290 EVT VT = N->getValueType(0);
7291
7292 // fold (fceil c1) -> fceil(c1)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007293 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007294 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
Owen Andersona40319b2012-08-13 23:32:49 +00007295
7296 return SDValue();
7297}
7298
7299SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7300 SDValue N0 = N->getOperand(0);
7301 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7302 EVT VT = N->getValueType(0);
7303
7304 // fold (ftrunc c1) -> ftrunc(c1)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007305 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007306 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
Owen Andersona40319b2012-08-13 23:32:49 +00007307
7308 return SDValue();
7309}
7310
7311SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7312 SDValue N0 = N->getOperand(0);
7313 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7314 EVT VT = N->getValueType(0);
7315
7316 // fold (ffloor c1) -> ffloor(c1)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007317 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007318 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
Owen Andersona40319b2012-08-13 23:32:49 +00007319
7320 return SDValue();
7321}
7322
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007323SDValue DAGCombiner::visitFABS(SDNode *N) {
7324 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007325 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007326 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007327
Craig Topper82384612012-09-11 01:45:21 +00007328 if (VT.isVector()) {
7329 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7330 if (FoldedVOp.getNode()) return FoldedVOp;
7331 }
7332
Nate Begeman21158fc2005-09-01 00:19:25 +00007333 // fold (fabs c1) -> fabs(c1)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007334 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007335 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00007336 // fold (fabs (fabs x)) -> (fabs x)
Chris Lattner3bc40502006-03-05 05:30:57 +00007337 if (N0.getOpcode() == ISD::FABS)
Nate Begemand23739d2005-09-06 04:43:02 +00007338 return N->getOperand(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00007339 // fold (fabs (fneg x)) -> (fabs x)
Chris Lattner3bc40502006-03-05 05:30:57 +00007340 // fold (fabs (fcopysign x, y)) -> (fabs x)
7341 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007342 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00007343
Chris Lattner888560d2008-01-27 17:42:27 +00007344 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
7345 // constant pool values.
Stephen Lincfe7f352013-07-08 00:37:03 +00007346 if (!TLI.isFAbsFree(VT) &&
Owen Anderson98f2c0c2012-04-02 22:10:29 +00007347 N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
Duncan Sands13237ac2008-06-06 12:08:01 +00007348 N0.getOperand(0).getValueType().isInteger() &&
7349 !N0.getOperand(0).getValueType().isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007350 SDValue Int = N0.getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007351 EVT IntVT = Int.getValueType();
Duncan Sands13237ac2008-06-06 12:08:01 +00007352 if (IntVT.isInteger() && !IntVT.isVector()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007353 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
Duncan Sands3ed76882009-02-01 18:06:53 +00007354 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
Gabor Greiff304a7a2008-08-28 21:40:38 +00007355 AddToWorkList(Int.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00007356 return DAG.getNode(ISD::BITCAST, SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007357 N->getValueType(0), Int);
Chris Lattner888560d2008-01-27 17:42:27 +00007358 }
7359 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007360
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007361 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007362}
7363
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007364SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7365 SDValue Chain = N->getOperand(0);
7366 SDValue N1 = N->getOperand(1);
7367 SDValue N2 = N->getOperand(2);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007368
Dan Gohman82e80012009-11-17 00:47:23 +00007369 // If N is a constant we could fold this into a fallthrough or unconditional
7370 // branch. However that doesn't happen very often in normal code, because
7371 // Instcombine/SimplifyCFG should have handled the available opportunities.
7372 // If we did this folding here, it would be necessary to update the
7373 // MachineBasicBlock CFG, which is awkward.
7374
Nate Begeman7e7f4392006-02-01 07:19:44 +00007375 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7376 // on the target.
Scott Michelcf0da6c2009-02-17 22:15:04 +00007377 if (N1.getOpcode() == ISD::SETCC &&
Tom Stellardb1588fc2013-03-08 15:36:57 +00007378 TLI.isOperationLegalOrCustom(ISD::BR_CC,
7379 N1.getOperand(0).getValueType())) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007380 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
Bill Wendling306bfc22009-01-30 23:27:35 +00007381 Chain, N1.getOperand(2),
Nate Begeman7e7f4392006-02-01 07:19:44 +00007382 N1.getOperand(0), N1.getOperand(1), N2);
7383 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007384
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007385 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7386 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7387 (N1.getOperand(0).hasOneUse() &&
7388 N1.getOperand(0).getOpcode() == ISD::SRL))) {
Craig Topperc0196b12014-04-14 00:51:57 +00007389 SDNode *Trunc = nullptr;
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007390 if (N1.getOpcode() == ISD::TRUNCATE) {
7391 // Look pass the truncate.
7392 Trunc = N1.getNode();
7393 N1 = N1.getOperand(0);
7394 }
Evan Cheng166a4e62010-01-06 19:38:29 +00007395
Bill Wendlingaa28be62009-03-26 06:14:09 +00007396 // Match this pattern so that we can generate simpler code:
7397 //
7398 // %a = ...
7399 // %b = and i32 %a, 2
7400 // %c = srl i32 %b, 1
7401 // brcond i32 %c ...
7402 //
7403 // into
Wesley Peck527da1b2010-11-23 03:31:01 +00007404 //
Bill Wendlingaa28be62009-03-26 06:14:09 +00007405 // %a = ...
Evan Cheng166a4e62010-01-06 19:38:29 +00007406 // %b = and i32 %a, 2
Bill Wendlingaa28be62009-03-26 06:14:09 +00007407 // %c = setcc eq %b, 0
7408 // brcond %c ...
7409 //
7410 // This applies only when the AND constant value has one bit set and the
7411 // SRL constant is equal to the log2 of the AND constant. The back-end is
7412 // smart enough to convert the result into a TEST/JMP sequence.
7413 SDValue Op0 = N1.getOperand(0);
7414 SDValue Op1 = N1.getOperand(1);
7415
7416 if (Op0.getOpcode() == ISD::AND &&
Bill Wendlingaa28be62009-03-26 06:14:09 +00007417 Op1.getOpcode() == ISD::Constant) {
Bill Wendlingaa28be62009-03-26 06:14:09 +00007418 SDValue AndOp1 = Op0.getOperand(1);
7419
7420 if (AndOp1.getOpcode() == ISD::Constant) {
7421 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7422
7423 if (AndConst.isPowerOf2() &&
7424 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7425 SDValue SetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00007426 DAG.getSetCC(SDLoc(N),
Matt Arsenault758659232013-05-18 00:21:46 +00007427 getSetCCResultType(Op0.getValueType()),
Bill Wendlingaa28be62009-03-26 06:14:09 +00007428 Op0, DAG.getConstant(0, Op0.getValueType()),
7429 ISD::SETNE);
7430
Andrew Trickef9de2a2013-05-25 02:42:55 +00007431 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng166a4e62010-01-06 19:38:29 +00007432 MVT::Other, Chain, SetCC, N2);
7433 // Don't add the new BRCond into the worklist or else SimplifySelectCC
7434 // will convert it back to (X & C1) >> C2.
7435 CombineTo(N, NewBRCond, false);
7436 // Truncate is dead.
7437 if (Trunc) {
7438 removeFromWorkList(Trunc);
7439 DAG.DeleteNode(Trunc);
7440 }
Bill Wendlingaa28be62009-03-26 06:14:09 +00007441 // Replace the uses of SRL with SETCC
Evan Cheng228c31f2010-02-27 07:36:59 +00007442 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007443 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
Bill Wendlingaa28be62009-03-26 06:14:09 +00007444 removeFromWorkList(N1.getNode());
7445 DAG.DeleteNode(N1.getNode());
Evan Cheng166a4e62010-01-06 19:38:29 +00007446 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Bill Wendlingaa28be62009-03-26 06:14:09 +00007447 }
7448 }
7449 }
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007450
7451 if (Trunc)
7452 // Restore N1 if the above transformation doesn't match.
7453 N1 = N->getOperand(1);
Bill Wendlingaa28be62009-03-26 06:14:09 +00007454 }
Wesley Peck527da1b2010-11-23 03:31:01 +00007455
Evan Cheng228c31f2010-02-27 07:36:59 +00007456 // Transform br(xor(x, y)) -> br(x != y)
7457 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7458 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7459 SDNode *TheXor = N1.getNode();
7460 SDValue Op0 = TheXor->getOperand(0);
7461 SDValue Op1 = TheXor->getOperand(1);
7462 if (Op0.getOpcode() == Op1.getOpcode()) {
7463 // Avoid missing important xor optimizations.
7464 SDValue Tmp = visitXOR(TheXor);
Evan Cheng5652a8d2013-01-09 20:56:40 +00007465 if (Tmp.getNode()) {
7466 if (Tmp.getNode() != TheXor) {
7467 DEBUG(dbgs() << "\nReplacing.8 ";
7468 TheXor->dump(&DAG);
7469 dbgs() << "\nWith: ";
7470 Tmp.getNode()->dump(&DAG);
7471 dbgs() << '\n');
7472 WorkListRemover DeadNodes(*this);
7473 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7474 removeFromWorkList(TheXor);
7475 DAG.DeleteNode(TheXor);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007476 return DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng5652a8d2013-01-09 20:56:40 +00007477 MVT::Other, Chain, Tmp, N2);
7478 }
7479
Benjamin Kramer93354432013-03-30 21:28:18 +00007480 // visitXOR has changed XOR's operands or replaced the XOR completely,
7481 // bail out.
7482 return SDValue(N, 0);
Evan Cheng228c31f2010-02-27 07:36:59 +00007483 }
7484 }
7485
7486 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7487 bool Equal = false;
7488 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7489 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7490 Op0.getOpcode() == ISD::XOR) {
7491 TheXor = Op0.getNode();
7492 Equal = true;
7493 }
7494
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007495 EVT SetCCVT = N1.getValueType();
Evan Cheng228c31f2010-02-27 07:36:59 +00007496 if (LegalTypes)
Matt Arsenault758659232013-05-18 00:21:46 +00007497 SetCCVT = getSetCCResultType(SetCCVT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007498 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
Evan Cheng228c31f2010-02-27 07:36:59 +00007499 SetCCVT,
7500 Op0, Op1,
7501 Equal ? ISD::SETEQ : ISD::SETNE);
7502 // Replace the uses of XOR with SETCC
7503 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007504 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007505 removeFromWorkList(N1.getNode());
7506 DAG.DeleteNode(N1.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00007507 return DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng228c31f2010-02-27 07:36:59 +00007508 MVT::Other, Chain, SetCC, N2);
7509 }
7510 }
Bill Wendlingaa28be62009-03-26 06:14:09 +00007511
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007512 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +00007513}
7514
Chris Lattnera49e16f2005-10-05 06:47:48 +00007515// Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7516//
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007517SDValue DAGCombiner::visitBR_CC(SDNode *N) {
Chris Lattnera49e16f2005-10-05 06:47:48 +00007518 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007519 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007520
Dan Gohman82e80012009-11-17 00:47:23 +00007521 // If N is a constant we could fold this into a fallthrough or unconditional
7522 // branch. However that doesn't happen very often in normal code, because
7523 // Instcombine/SimplifyCFG should have handled the available opportunities.
7524 // If we did this folding here, it would be necessary to update the
7525 // MachineBasicBlock CFG, which is awkward.
7526
Duncan Sands93b66092008-06-09 11:32:28 +00007527 // Use SimplifySetCC to simplify SETCC's.
Matt Arsenault758659232013-05-18 00:21:46 +00007528 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00007529 CondLHS, CondRHS, CC->get(), SDLoc(N),
Dale Johannesenf1163e92009-02-03 00:47:48 +00007530 false);
Gabor Greiff304a7a2008-08-28 21:40:38 +00007531 if (Simp.getNode()) AddToWorkList(Simp.getNode());
Chris Lattner6a1b2de2006-10-14 03:52:46 +00007532
Nate Begemanbd7df032005-10-05 21:43:42 +00007533 // fold to a simpler setcc
Gabor Greiff304a7a2008-08-28 21:40:38 +00007534 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007535 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
Bill Wendling306bfc22009-01-30 23:27:35 +00007536 N->getOperand(0), Simp.getOperand(2),
7537 Simp.getOperand(0), Simp.getOperand(1),
7538 N->getOperand(4));
7539
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007540 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +00007541}
7542
Evan Chengfa832632012-01-13 01:37:24 +00007543/// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7544/// uses N as its base pointer and that N may be folded in the load / store
Evan Cheng80893ce2012-03-06 23:33:32 +00007545/// addressing mode.
Evan Chengfa832632012-01-13 01:37:24 +00007546static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7547 SelectionDAG &DAG,
7548 const TargetLowering &TLI) {
7549 EVT VT;
7550 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
7551 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7552 return false;
7553 VT = Use->getValueType(0);
7554 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
7555 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7556 return false;
7557 VT = ST->getValue().getValueType();
7558 } else
7559 return false;
7560
Chandler Carruth95f83e02013-01-07 15:14:13 +00007561 TargetLowering::AddrMode AM;
Evan Chengfa832632012-01-13 01:37:24 +00007562 if (N->getOpcode() == ISD::ADD) {
7563 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7564 if (Offset)
Evan Cheng80893ce2012-03-06 23:33:32 +00007565 // [reg +/- imm]
Evan Chengfa832632012-01-13 01:37:24 +00007566 AM.BaseOffs = Offset->getSExtValue();
7567 else
Evan Cheng80893ce2012-03-06 23:33:32 +00007568 // [reg +/- reg]
7569 AM.Scale = 1;
Evan Chengfa832632012-01-13 01:37:24 +00007570 } else if (N->getOpcode() == ISD::SUB) {
7571 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7572 if (Offset)
Evan Cheng80893ce2012-03-06 23:33:32 +00007573 // [reg +/- imm]
Evan Chengfa832632012-01-13 01:37:24 +00007574 AM.BaseOffs = -Offset->getSExtValue();
7575 else
Evan Cheng80893ce2012-03-06 23:33:32 +00007576 // [reg +/- reg]
7577 AM.Scale = 1;
Evan Chengfa832632012-01-13 01:37:24 +00007578 } else
7579 return false;
7580
7581 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7582}
7583
Duncan Sands075293f2008-06-15 20:12:31 +00007584/// CombineToPreIndexedLoadStore - Try turning a load / store into a
7585/// pre-indexed load / store when the base pointer is an add or subtract
Chris Lattnerffad2162006-11-11 00:39:41 +00007586/// and it has other uses besides the load / store. After the
7587/// transformation, the new indexed load / store has effectively folded
7588/// the add / subtract in and all of its other uses are redirected to the
7589/// new load / store.
7590bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
Eli Friedman9d448e42011-11-12 00:35:34 +00007591 if (Level < AfterLegalizeDAG)
Chris Lattnerffad2162006-11-11 00:39:41 +00007592 return false;
7593
7594 bool isLoad = true;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007595 SDValue Ptr;
Owen Anderson53aa7a92009-08-10 22:56:29 +00007596 EVT VT;
Chris Lattnerffad2162006-11-11 00:39:41 +00007597 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007598 if (LD->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007599 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007600 VT = LD->getMemoryVT();
Evan Cheng8a1d09d2007-03-07 08:07:03 +00007601 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
Chris Lattnerffad2162006-11-11 00:39:41 +00007602 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7603 return false;
7604 Ptr = LD->getBasePtr();
7605 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007606 if (ST->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007607 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007608 VT = ST->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00007609 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7610 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7611 return false;
7612 Ptr = ST->getBasePtr();
7613 isLoad = false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007614 } else {
Chris Lattnerffad2162006-11-11 00:39:41 +00007615 return false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007616 }
Chris Lattnerffad2162006-11-11 00:39:41 +00007617
Chris Lattnereabc15c2006-11-11 00:56:29 +00007618 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7619 // out. There is no reason to make this a preinc/predec.
7620 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
Gabor Greiff304a7a2008-08-28 21:40:38 +00007621 Ptr.getNode()->hasOneUse())
Chris Lattnereabc15c2006-11-11 00:56:29 +00007622 return false;
Chris Lattnerffad2162006-11-11 00:39:41 +00007623
Chris Lattnereabc15c2006-11-11 00:56:29 +00007624 // Ask the target to do addressing mode selection.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007625 SDValue BasePtr;
7626 SDValue Offset;
Chris Lattnereabc15c2006-11-11 00:56:29 +00007627 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7628 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7629 return false;
Hal Finkel25819052013-02-08 21:35:47 +00007630
7631 // Backends without true r+i pre-indexed forms may need to pass a
7632 // constant base with a variable offset so that constant coercion
7633 // will work with the patterns in canonical form.
7634 bool Swapped = false;
7635 if (isa<ConstantSDNode>(BasePtr)) {
7636 std::swap(BasePtr, Offset);
7637 Swapped = true;
7638 }
7639
Evan Cheng044a0a82007-05-03 23:52:19 +00007640 // Don't create a indexed load / store with zero offset.
7641 if (isa<ConstantSDNode>(Offset) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00007642 cast<ConstantSDNode>(Offset)->isNullValue())
Evan Cheng044a0a82007-05-03 23:52:19 +00007643 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007644
Chris Lattnera0a80032006-11-11 01:00:15 +00007645 // Try turning it into a pre-indexed load / store except when:
Evan Chenga4d187b2007-05-24 02:35:39 +00007646 // 1) The new base ptr is a frame index.
7647 // 2) If N is a store and the new base ptr is either the same as or is a
Chris Lattnereabc15c2006-11-11 00:56:29 +00007648 // predecessor of the value being stored.
Evan Chenga4d187b2007-05-24 02:35:39 +00007649 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
Chris Lattnereabc15c2006-11-11 00:56:29 +00007650 // that would create a cycle.
Evan Chenga4d187b2007-05-24 02:35:39 +00007651 // 4) All uses are load / store ops that use it as old base ptr.
Chris Lattnerffad2162006-11-11 00:39:41 +00007652
Chris Lattnera0a80032006-11-11 01:00:15 +00007653 // Check #1. Preinc'ing a frame index would require copying the stack pointer
7654 // (plus the implicit offset) to a register to preinc anyway.
Evan Chengcfc05132009-05-06 18:25:01 +00007655 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
Chris Lattnera0a80032006-11-11 01:00:15 +00007656 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007657
Chris Lattnera0a80032006-11-11 01:00:15 +00007658 // Check #2.
Chris Lattnereabc15c2006-11-11 00:56:29 +00007659 if (!isLoad) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007660 SDValue Val = cast<StoreSDNode>(N)->getValue();
Gabor Greiff304a7a2008-08-28 21:40:38 +00007661 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
Chris Lattnereabc15c2006-11-11 00:56:29 +00007662 return false;
Chris Lattnerffad2162006-11-11 00:39:41 +00007663 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00007664
Hal Finkel25819052013-02-08 21:35:47 +00007665 // If the offset is a constant, there may be other adds of constants that
7666 // can be folded with this one. We should do this to avoid having to keep
7667 // a copy of the original base pointer.
7668 SmallVector<SDNode *, 16> OtherUses;
7669 if (isa<ConstantSDNode>(Offset))
Jim Grosbache8160032014-04-11 01:13:13 +00007670 for (SDNode *Use : BasePtr.getNode()->uses()) {
Hal Finkel25819052013-02-08 21:35:47 +00007671 if (Use == Ptr.getNode())
7672 continue;
7673
7674 if (Use->isPredecessorOf(N))
7675 continue;
7676
7677 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7678 OtherUses.clear();
7679 break;
7680 }
7681
7682 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7683 if (Op1.getNode() == BasePtr.getNode())
7684 std::swap(Op0, Op1);
7685 assert(Op0.getNode() == BasePtr.getNode() &&
7686 "Use of ADD/SUB but not an operand");
7687
7688 if (!isa<ConstantSDNode>(Op1)) {
7689 OtherUses.clear();
7690 break;
7691 }
7692
7693 // FIXME: In some cases, we can be smarter about this.
7694 if (Op1.getValueType() != Offset.getValueType()) {
7695 OtherUses.clear();
7696 break;
7697 }
7698
7699 OtherUses.push_back(Use);
7700 }
7701
7702 if (Swapped)
7703 std::swap(BasePtr, Offset);
7704
Evan Chenga4d187b2007-05-24 02:35:39 +00007705 // Now check for #3 and #4.
Chris Lattnereabc15c2006-11-11 00:56:29 +00007706 bool RealUse = false;
Lang Hames5a004992011-07-07 04:31:51 +00007707
7708 // Caches for hasPredecessorHelper
7709 SmallPtrSet<const SDNode *, 32> Visited;
7710 SmallVector<const SDNode *, 16> Worklist;
7711
Jim Grosbache8160032014-04-11 01:13:13 +00007712 for (SDNode *Use : Ptr.getNode()->uses()) {
Chris Lattnereabc15c2006-11-11 00:56:29 +00007713 if (Use == N)
7714 continue;
Lang Hames5a004992011-07-07 04:31:51 +00007715 if (N->hasPredecessorHelper(Use, Visited, Worklist))
Chris Lattnereabc15c2006-11-11 00:56:29 +00007716 return false;
7717
Evan Chengfa832632012-01-13 01:37:24 +00007718 // If Ptr may be folded in addressing mode of other use, then it's
7719 // not profitable to do this transformation.
7720 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
Chris Lattnereabc15c2006-11-11 00:56:29 +00007721 RealUse = true;
7722 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007723
Chris Lattnereabc15c2006-11-11 00:56:29 +00007724 if (!RealUse)
7725 return false;
7726
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007727 SDValue Result;
Chris Lattnereabc15c2006-11-11 00:56:29 +00007728 if (isLoad)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007729 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007730 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007731 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00007732 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007733 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007734 ++PreIndexedNodes;
7735 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +00007736 DEBUG(dbgs() << "\nReplacing.4 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007737 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007738 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007739 Result.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007740 dbgs() << '\n');
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +00007741 WorkListRemover DeadNodes(*this);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007742 if (isLoad) {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007743 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7744 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
Chris Lattnereabc15c2006-11-11 00:56:29 +00007745 } else {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007746 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
Chris Lattnereabc15c2006-11-11 00:56:29 +00007747 }
7748
Chris Lattnereabc15c2006-11-11 00:56:29 +00007749 // Finally, since the node is now dead, remove it from the graph.
7750 DAG.DeleteNode(N);
7751
Hal Finkel25819052013-02-08 21:35:47 +00007752 if (Swapped)
7753 std::swap(BasePtr, Offset);
7754
7755 // Replace other uses of BasePtr that can be updated to use Ptr
7756 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7757 unsigned OffsetIdx = 1;
7758 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7759 OffsetIdx = 0;
7760 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7761 BasePtr.getNode() && "Expected BasePtr operand");
7762
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007763 // We need to replace ptr0 in the following expression:
7764 // x0 * offset0 + y0 * ptr0 = t0
7765 // knowing that
7766 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
Stephen Lincfe7f352013-07-08 00:37:03 +00007767 //
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007768 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7769 // indexed load/store and the expresion that needs to be re-written.
7770 //
7771 // Therefore, we have:
7772 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
Hal Finkel25819052013-02-08 21:35:47 +00007773
7774 ConstantSDNode *CN =
7775 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007776 int X0, X1, Y0, Y1;
7777 APInt Offset0 = CN->getAPIntValue();
7778 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
Hal Finkel25819052013-02-08 21:35:47 +00007779
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007780 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7781 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7782 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7783 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
Hal Finkel25819052013-02-08 21:35:47 +00007784
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007785 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7786
7787 APInt CNV = Offset0;
7788 if (X0 < 0) CNV = -CNV;
7789 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7790 else CNV = CNV - Offset1;
7791
7792 // We can now generate the new expression.
7793 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7794 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7795
7796 SDValue NewUse = DAG.getNode(Opcode,
Andrew Trickef9de2a2013-05-25 02:42:55 +00007797 SDLoc(OtherUses[i]),
Hal Finkel25819052013-02-08 21:35:47 +00007798 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7799 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7800 removeFromWorkList(OtherUses[i]);
7801 DAG.DeleteNode(OtherUses[i]);
7802 }
7803
Chris Lattnereabc15c2006-11-11 00:56:29 +00007804 // Replace the uses of Ptr with uses of the updated base value.
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007805 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
Gabor Greiff304a7a2008-08-28 21:40:38 +00007806 removeFromWorkList(Ptr.getNode());
7807 DAG.DeleteNode(Ptr.getNode());
Chris Lattnereabc15c2006-11-11 00:56:29 +00007808
7809 return true;
Chris Lattnerffad2162006-11-11 00:39:41 +00007810}
7811
Duncan Sands075293f2008-06-15 20:12:31 +00007812/// CombineToPostIndexedLoadStore - Try to combine a load / store with a
Chris Lattnerffad2162006-11-11 00:39:41 +00007813/// add / sub of the base pointer node into a post-indexed load / store.
7814/// The transformation folded the add / subtract into the new indexed
7815/// load / store effectively and all of its uses are redirected to the
7816/// new load / store.
7817bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
Eli Friedman9d448e42011-11-12 00:35:34 +00007818 if (Level < AfterLegalizeDAG)
Chris Lattnerffad2162006-11-11 00:39:41 +00007819 return false;
7820
7821 bool isLoad = true;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007822 SDValue Ptr;
Owen Anderson53aa7a92009-08-10 22:56:29 +00007823 EVT VT;
Chris Lattnerffad2162006-11-11 00:39:41 +00007824 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007825 if (LD->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007826 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007827 VT = LD->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00007828 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7829 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7830 return false;
7831 Ptr = LD->getBasePtr();
7832 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007833 if (ST->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007834 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007835 VT = ST->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00007836 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7837 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7838 return false;
7839 Ptr = ST->getBasePtr();
7840 isLoad = false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007841 } else {
Chris Lattnerffad2162006-11-11 00:39:41 +00007842 return false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007843 }
Chris Lattnerffad2162006-11-11 00:39:41 +00007844
Gabor Greiff304a7a2008-08-28 21:40:38 +00007845 if (Ptr.getNode()->hasOneUse())
Chris Lattnereabc15c2006-11-11 00:56:29 +00007846 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007847
Jim Grosbache8160032014-04-11 01:13:13 +00007848 for (SDNode *Op : Ptr.getNode()->uses()) {
Chris Lattnereabc15c2006-11-11 00:56:29 +00007849 if (Op == N ||
7850 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7851 continue;
7852
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007853 SDValue BasePtr;
7854 SDValue Offset;
Chris Lattnereabc15c2006-11-11 00:56:29 +00007855 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7856 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
Evan Cheng044a0a82007-05-03 23:52:19 +00007857 // Don't create a indexed load / store with zero offset.
7858 if (isa<ConstantSDNode>(Offset) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00007859 cast<ConstantSDNode>(Offset)->isNullValue())
Evan Cheng044a0a82007-05-03 23:52:19 +00007860 continue;
Chris Lattnerffad2162006-11-11 00:39:41 +00007861
Chris Lattnereabc15c2006-11-11 00:56:29 +00007862 // Try turning it into a post-indexed load / store except when
Evan Chengfa832632012-01-13 01:37:24 +00007863 // 1) All uses are load / store ops that use it as base ptr (and
7864 // it may be folded as addressing mmode).
Chris Lattnereabc15c2006-11-11 00:56:29 +00007865 // 2) Op must be independent of N, i.e. Op is neither a predecessor
7866 // nor a successor of N. Otherwise, if Op is folded that would
7867 // create a cycle.
7868
Evan Chengcfc05132009-05-06 18:25:01 +00007869 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7870 continue;
7871
Chris Lattnereabc15c2006-11-11 00:56:29 +00007872 // Check for #1.
7873 bool TryNext = false;
Jim Grosbache8160032014-04-11 01:13:13 +00007874 for (SDNode *Use : BasePtr.getNode()->uses()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00007875 if (Use == Ptr.getNode())
Chris Lattnerffad2162006-11-11 00:39:41 +00007876 continue;
7877
Chris Lattnereabc15c2006-11-11 00:56:29 +00007878 // If all the uses are load / store addresses, then don't do the
7879 // transformation.
7880 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7881 bool RealUse = false;
Jim Grosbache8160032014-04-11 01:13:13 +00007882 for (SDNode *UseUse : Use->uses()) {
Stephen Lincfe7f352013-07-08 00:37:03 +00007883 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
Chris Lattnereabc15c2006-11-11 00:56:29 +00007884 RealUse = true;
7885 }
Chris Lattnerffad2162006-11-11 00:39:41 +00007886
Chris Lattnereabc15c2006-11-11 00:56:29 +00007887 if (!RealUse) {
7888 TryNext = true;
7889 break;
Chris Lattnerffad2162006-11-11 00:39:41 +00007890 }
7891 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00007892 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007893
Chris Lattnereabc15c2006-11-11 00:56:29 +00007894 if (TryNext)
7895 continue;
Chris Lattnerffad2162006-11-11 00:39:41 +00007896
Chris Lattnereabc15c2006-11-11 00:56:29 +00007897 // Check for #2
Evan Cheng567d2e52008-03-04 00:41:45 +00007898 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007899 SDValue Result = isLoad
Andrew Trickef9de2a2013-05-25 02:42:55 +00007900 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007901 BasePtr, Offset, AM)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007902 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007903 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007904 ++PostIndexedNodes;
7905 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +00007906 DEBUG(dbgs() << "\nReplacing.5 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007907 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007908 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007909 Result.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007910 dbgs() << '\n');
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +00007911 WorkListRemover DeadNodes(*this);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007912 if (isLoad) {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007913 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7914 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
Chris Lattnereabc15c2006-11-11 00:56:29 +00007915 } else {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007916 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
Chris Lattnerffad2162006-11-11 00:39:41 +00007917 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00007918
Chris Lattnereabc15c2006-11-11 00:56:29 +00007919 // Finally, since the node is now dead, remove it from the graph.
7920 DAG.DeleteNode(N);
7921
7922 // Replace the uses of Use with uses of the updated base value.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007923 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007924 Result.getValue(isLoad ? 1 : 0));
Chris Lattnereabc15c2006-11-11 00:56:29 +00007925 removeFromWorkList(Op);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007926 DAG.DeleteNode(Op);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007927 return true;
Chris Lattnerffad2162006-11-11 00:39:41 +00007928 }
7929 }
7930 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007931
Chris Lattnerffad2162006-11-11 00:39:41 +00007932 return false;
7933}
7934
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007935SDValue DAGCombiner::visitLOAD(SDNode *N) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00007936 LoadSDNode *LD = cast<LoadSDNode>(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007937 SDValue Chain = LD->getChain();
7938 SDValue Ptr = LD->getBasePtr();
Scott Michelcf0da6c2009-02-17 22:15:04 +00007939
Evan Chenga684cd22007-05-01 00:38:21 +00007940 // If load is not volatile and there are no uses of the loaded value (and
7941 // the updated indexed value in case of indexed loads), change uses of the
7942 // chain value into uses of the chain input (i.e. delete the dead load).
7943 if (!LD->isVolatile()) {
Owen Anderson9f944592009-08-11 20:47:22 +00007944 if (N->getValueType(1) == MVT::Other) {
Evan Chengb68343c2007-05-01 08:53:39 +00007945 // Unindexed loads.
Craig Topper0515cd42012-01-07 18:31:09 +00007946 if (!N->hasAnyUseOfValue(0)) {
Evan Cheng7be15282008-01-16 23:11:54 +00007947 // It's not safe to use the two value CombineTo variant here. e.g.
7948 // v1, chain2 = load chain1, loc
7949 // v2, chain3 = load chain2, loc
7950 // v3 = add v2, c
Chris Lattnere97fa8c2008-01-24 07:57:06 +00007951 // Now we replace use of chain2 with chain1. This makes the second load
7952 // isomorphic to the one we are deleting, and thus makes this load live.
David Greenefe5c3522010-01-05 01:25:00 +00007953 DEBUG(dbgs() << "\nReplacing.6 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007954 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007955 dbgs() << "\nWith chain: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007956 Chain.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007957 dbgs() << "\n");
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +00007958 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007959 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
Bill Wendling306bfc22009-01-30 23:27:35 +00007960
Chris Lattnere97fa8c2008-01-24 07:57:06 +00007961 if (N->use_empty()) {
7962 removeFromWorkList(N);
7963 DAG.DeleteNode(N);
7964 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007965
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007966 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Cheng7be15282008-01-16 23:11:54 +00007967 }
Evan Chengb68343c2007-05-01 08:53:39 +00007968 } else {
7969 // Indexed loads.
Owen Anderson9f944592009-08-11 20:47:22 +00007970 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
Hal Finkel2c77fe52014-05-28 15:33:19 +00007971 if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
Dale Johannesen84935752009-02-06 23:05:02 +00007972 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
Evan Cheng228c31f2010-02-27 07:36:59 +00007973 DEBUG(dbgs() << "\nReplacing.7 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007974 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007975 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007976 Undef.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007977 dbgs() << " and 2 other values\n");
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +00007978 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007979 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
Hal Finkel2c77fe52014-05-28 15:33:19 +00007980 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
7981 DAG.getUNDEF(N->getValueType(1)));
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007982 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
Evan Cheng7be15282008-01-16 23:11:54 +00007983 removeFromWorkList(N);
Evan Cheng7be15282008-01-16 23:11:54 +00007984 DAG.DeleteNode(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007985 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga684cd22007-05-01 00:38:21 +00007986 }
Evan Chenga684cd22007-05-01 00:38:21 +00007987 }
7988 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007989
Chris Lattnere260ed82005-10-10 22:04:48 +00007990 // If this load is directly stored, replace the load value with the stored
7991 // value.
7992 // TODO: Handle store large -> read small portion.
Jim Laskey0f7c3282006-10-11 17:47:52 +00007993 // TODO: Handle TRUNCSTORE/LOADEXT
Evan Chengadb9c032011-03-11 00:48:56 +00007994 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00007995 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
Evan Chengab51cf22006-10-13 21:14:26 +00007996 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
7997 if (PrevST->getBasePtr() == Ptr &&
7998 PrevST->getValue().getValueType() == N->getValueType(0))
Jim Laskey0f7c3282006-10-11 17:47:52 +00007999 return CombineTo(N, Chain.getOperand(1), Chain);
Evan Chengab51cf22006-10-13 21:14:26 +00008000 }
Jim Laskey0f7c3282006-10-11 17:47:52 +00008001 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00008002
Evan Cheng43cd9e32010-04-01 06:04:33 +00008003 // Try to infer better alignment information than the load already has.
8004 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
Evan Cheng4a5b2042011-11-28 22:37:34 +00008005 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
Owen Andersonde89ecf2013-02-05 19:24:39 +00008006 if (Align > LD->getMemOperand()->getBaseAlignment()) {
8007 SDValue NewLoad =
Andrew Trickef9de2a2013-05-25 02:42:55 +00008008 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
Evan Cheng4a5b2042011-11-28 22:37:34 +00008009 LD->getValueType(0),
8010 Chain, Ptr, LD->getPointerInfo(),
8011 LD->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00008012 LD->isVolatile(), LD->isNonTemporal(), Align,
8013 LD->getTBAAInfo());
Owen Andersonde89ecf2013-02-05 19:24:39 +00008014 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
8015 }
Evan Cheng43cd9e32010-04-01 06:04:33 +00008016 }
8017 }
8018
Hal Finkel5ef4dcc2013-08-29 03:29:55 +00008019 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
8020 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +00008021#ifndef NDEBUG
8022 if (CombinerAAOnlyFunc.getNumOccurrences() &&
8023 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
8024 UseAA = false;
8025#endif
Hal Finkelccc18e12014-01-24 18:25:26 +00008026 if (UseAA && LD->isUnindexed()) {
Jim Laskeyd07be232006-09-25 16:29:54 +00008027 // Walk up chain skipping non-aliasing memory nodes.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008028 SDValue BetterChain = FindBetterChain(N, Chain);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008029
Jim Laskey708d0db2006-10-04 16:53:27 +00008030 // If there is a better chain.
Jim Laskeyd07be232006-09-25 16:29:54 +00008031 if (Chain != BetterChain) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008032 SDValue ReplLoad;
Jim Laskey0f7c3282006-10-11 17:47:52 +00008033
Jim Laskeyd07be232006-09-25 16:29:54 +00008034 // Replace the chain to void dependency.
Jim Laskey0f7c3282006-10-11 17:47:52 +00008035 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00008036 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00008037 BetterChain, Ptr, LD->getMemOperand());
Jim Laskey0f7c3282006-10-11 17:47:52 +00008038 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +00008039 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
Stuart Hastings81c43062011-02-16 16:23:55 +00008040 LD->getValueType(0),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00008041 BetterChain, Ptr, LD->getMemoryVT(),
8042 LD->getMemOperand());
Jim Laskey0f7c3282006-10-11 17:47:52 +00008043 }
Jim Laskeyd07be232006-09-25 16:29:54 +00008044
Jim Laskey708d0db2006-10-04 16:53:27 +00008045 // Create token factor to keep old chain connected.
Andrew Trickef9de2a2013-05-25 02:42:55 +00008046 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
Owen Anderson9f944592009-08-11 20:47:22 +00008047 MVT::Other, Chain, ReplLoad.getValue(1));
Wesley Peck527da1b2010-11-23 03:31:01 +00008048
Nate Begeman879d8f12009-09-15 00:18:30 +00008049 // Make sure the new and old chains are cleaned up.
8050 AddToWorkList(Token.getNode());
Wesley Peck527da1b2010-11-23 03:31:01 +00008051
Jim Laskeydcf983c2006-10-13 23:32:28 +00008052 // Replace uses with load result and token factor. Don't add users
8053 // to work list.
8054 return CombineTo(N, ReplLoad.getValue(0), Token, false);
Jim Laskeyd07be232006-09-25 16:29:54 +00008055 }
8056 }
8057
Evan Cheng357017f2006-11-03 03:06:21 +00008058 // Try transforming N to an indexed load.
Evan Cheng60c68462006-11-07 09:03:05 +00008059 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008060 return SDValue(N, 0);
Evan Cheng357017f2006-11-03 03:06:21 +00008061
Quentin Colombetde0e0622013-10-11 18:29:42 +00008062 // Try to slice up N to more direct loads if the slices are mapped to
8063 // different register banks or pairing can take place.
8064 if (SliceUpLoad(N))
8065 return SDValue(N, 0);
8066
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008067 return SDValue();
Chris Lattnere260ed82005-10-10 22:04:48 +00008068}
8069
Quentin Colombetde0e0622013-10-11 18:29:42 +00008070namespace {
8071/// \brief Helper structure used to slice a load in smaller loads.
8072/// Basically a slice is obtained from the following sequence:
8073/// Origin = load Ty1, Base
8074/// Shift = srl Ty1 Origin, CstTy Amount
8075/// Inst = trunc Shift to Ty2
8076///
8077/// Then, it will be rewriten into:
8078/// Slice = load SliceTy, Base + SliceOffset
8079/// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8080///
8081/// SliceTy is deduced from the number of bits that are actually used to
8082/// build Inst.
8083struct LoadedSlice {
8084 /// \brief Helper structure used to compute the cost of a slice.
8085 struct Cost {
8086 /// Are we optimizing for code size.
8087 bool ForCodeSize;
8088 /// Various cost.
8089 unsigned Loads;
8090 unsigned Truncates;
8091 unsigned CrossRegisterBanksCopies;
8092 unsigned ZExts;
8093 unsigned Shift;
8094
8095 Cost(bool ForCodeSize = false)
8096 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8097 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8098
8099 /// \brief Get the cost of one isolated slice.
8100 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8101 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8102 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8103 EVT TruncType = LS.Inst->getValueType(0);
8104 EVT LoadedType = LS.getLoadedType();
8105 if (TruncType != LoadedType &&
8106 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8107 ZExts = 1;
8108 }
8109
8110 /// \brief Account for slicing gain in the current cost.
8111 /// Slicing provide a few gains like removing a shift or a
8112 /// truncate. This method allows to grow the cost of the original
8113 /// load with the gain from this slice.
8114 void addSliceGain(const LoadedSlice &LS) {
8115 // Each slice saves a truncate.
8116 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8117 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8118 LS.Inst->getOperand(0).getValueType()))
8119 ++Truncates;
8120 // If there is a shift amount, this slice gets rid of it.
8121 if (LS.Shift)
8122 ++Shift;
8123 // If this slice can merge a cross register bank copy, account for it.
8124 if (LS.canMergeExpensiveCrossRegisterBankCopy())
8125 ++CrossRegisterBanksCopies;
8126 }
8127
8128 Cost &operator+=(const Cost &RHS) {
8129 Loads += RHS.Loads;
8130 Truncates += RHS.Truncates;
8131 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8132 ZExts += RHS.ZExts;
8133 Shift += RHS.Shift;
8134 return *this;
8135 }
8136
8137 bool operator==(const Cost &RHS) const {
8138 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8139 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8140 ZExts == RHS.ZExts && Shift == RHS.Shift;
8141 }
8142
8143 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8144
8145 bool operator<(const Cost &RHS) const {
8146 // Assume cross register banks copies are as expensive as loads.
8147 // FIXME: Do we want some more target hooks?
8148 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8149 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8150 // Unless we are optimizing for code size, consider the
8151 // expensive operation first.
8152 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8153 return ExpensiveOpsLHS < ExpensiveOpsRHS;
8154 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8155 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8156 }
8157
8158 bool operator>(const Cost &RHS) const { return RHS < *this; }
8159
8160 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8161
8162 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8163 };
8164 // The last instruction that represent the slice. This should be a
8165 // truncate instruction.
8166 SDNode *Inst;
8167 // The original load instruction.
8168 LoadSDNode *Origin;
8169 // The right shift amount in bits from the original load.
8170 unsigned Shift;
8171 // The DAG from which Origin came from.
8172 // This is used to get some contextual information about legal types, etc.
8173 SelectionDAG *DAG;
8174
Craig Topperc0196b12014-04-14 00:51:57 +00008175 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8176 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
Quentin Colombetde0e0622013-10-11 18:29:42 +00008177 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8178
8179 LoadedSlice(const LoadedSlice &LS)
8180 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8181
8182 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8183 /// \return Result is \p BitWidth and has used bits set to 1 and
8184 /// not used bits set to 0.
8185 APInt getUsedBits() const {
8186 // Reproduce the trunc(lshr) sequence:
8187 // - Start from the truncated value.
8188 // - Zero extend to the desired bit width.
8189 // - Shift left.
8190 assert(Origin && "No original load to compare against.");
8191 unsigned BitWidth = Origin->getValueSizeInBits(0);
8192 assert(Inst && "This slice is not bound to an instruction");
8193 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8194 "Extracted slice is bigger than the whole type!");
8195 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8196 UsedBits.setAllBits();
8197 UsedBits = UsedBits.zext(BitWidth);
8198 UsedBits <<= Shift;
8199 return UsedBits;
8200 }
8201
8202 /// \brief Get the size of the slice to be loaded in bytes.
8203 unsigned getLoadedSize() const {
8204 unsigned SliceSize = getUsedBits().countPopulation();
8205 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8206 return SliceSize / 8;
8207 }
8208
8209 /// \brief Get the type that will be loaded for this slice.
8210 /// Note: This may not be the final type for the slice.
8211 EVT getLoadedType() const {
8212 assert(DAG && "Missing context");
8213 LLVMContext &Ctxt = *DAG->getContext();
8214 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8215 }
8216
8217 /// \brief Get the alignment of the load used for this slice.
8218 unsigned getAlignment() const {
8219 unsigned Alignment = Origin->getAlignment();
8220 unsigned Offset = getOffsetFromBase();
8221 if (Offset != 0)
8222 Alignment = MinAlign(Alignment, Alignment + Offset);
8223 return Alignment;
8224 }
8225
8226 /// \brief Check if this slice can be rewritten with legal operations.
8227 bool isLegal() const {
8228 // An invalid slice is not legal.
8229 if (!Origin || !Inst || !DAG)
8230 return false;
8231
8232 // Offsets are for indexed load only, we do not handle that.
8233 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8234 return false;
8235
8236 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8237
8238 // Check that the type is legal.
8239 EVT SliceType = getLoadedType();
8240 if (!TLI.isTypeLegal(SliceType))
8241 return false;
8242
8243 // Check that the load is legal for this type.
8244 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8245 return false;
8246
8247 // Check that the offset can be computed.
8248 // 1. Check its type.
8249 EVT PtrType = Origin->getBasePtr().getValueType();
8250 if (PtrType == MVT::Untyped || PtrType.isExtended())
8251 return false;
8252
8253 // 2. Check that it fits in the immediate.
8254 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8255 return false;
8256
8257 // 3. Check that the computation is legal.
8258 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8259 return false;
8260
8261 // Check that the zext is legal if it needs one.
8262 EVT TruncateType = Inst->getValueType(0);
8263 if (TruncateType != SliceType &&
8264 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8265 return false;
8266
8267 return true;
8268 }
8269
8270 /// \brief Get the offset in bytes of this slice in the original chunk of
8271 /// bits.
Craig Topperc0196b12014-04-14 00:51:57 +00008272 /// \pre DAG != nullptr.
Quentin Colombetde0e0622013-10-11 18:29:42 +00008273 uint64_t getOffsetFromBase() const {
8274 assert(DAG && "Missing context.");
8275 bool IsBigEndian =
8276 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8277 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8278 uint64_t Offset = Shift / 8;
8279 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8280 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8281 "The size of the original loaded type is not a multiple of a"
8282 " byte.");
8283 // If Offset is bigger than TySizeInBytes, it means we are loading all
8284 // zeros. This should have been optimized before in the process.
8285 assert(TySizeInBytes > Offset &&
8286 "Invalid shift amount for given loaded size");
8287 if (IsBigEndian)
8288 Offset = TySizeInBytes - Offset - getLoadedSize();
8289 return Offset;
8290 }
8291
8292 /// \brief Generate the sequence of instructions to load the slice
8293 /// represented by this object and redirect the uses of this slice to
8294 /// this new sequence of instructions.
8295 /// \pre this->Inst && this->Origin are valid Instructions and this
8296 /// object passed the legal check: LoadedSlice::isLegal returned true.
8297 /// \return The last instruction of the sequence used to load the slice.
8298 SDValue loadSlice() const {
8299 assert(Inst && Origin && "Unable to replace a non-existing slice.");
8300 const SDValue &OldBaseAddr = Origin->getBasePtr();
8301 SDValue BaseAddr = OldBaseAddr;
8302 // Get the offset in that chunk of bytes w.r.t. the endianess.
8303 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8304 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8305 if (Offset) {
8306 // BaseAddr = BaseAddr + Offset.
8307 EVT ArithType = BaseAddr.getValueType();
8308 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8309 DAG->getConstant(Offset, ArithType));
8310 }
8311
8312 // Create the type of the loaded slice according to its size.
8313 EVT SliceType = getLoadedType();
8314
8315 // Create the load for the slice.
8316 SDValue LastInst = DAG->getLoad(
8317 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8318 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8319 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8320 // If the final type is not the same as the loaded type, this means that
8321 // we have to pad with zero. Create a zero extend for that.
8322 EVT FinalType = Inst->getValueType(0);
8323 if (SliceType != FinalType)
8324 LastInst =
8325 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8326 return LastInst;
8327 }
8328
8329 /// \brief Check if this slice can be merged with an expensive cross register
8330 /// bank copy. E.g.,
8331 /// i = load i32
8332 /// f = bitcast i32 i to float
8333 bool canMergeExpensiveCrossRegisterBankCopy() const {
8334 if (!Inst || !Inst->hasOneUse())
8335 return false;
8336 SDNode *Use = *Inst->use_begin();
8337 if (Use->getOpcode() != ISD::BITCAST)
8338 return false;
8339 assert(DAG && "Missing context");
8340 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8341 EVT ResVT = Use->getValueType(0);
8342 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8343 const TargetRegisterClass *ArgRC =
8344 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8345 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8346 return false;
8347
8348 // At this point, we know that we perform a cross-register-bank copy.
8349 // Check if it is expensive.
8350 const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo();
8351 // Assume bitcasts are cheap, unless both register classes do not
8352 // explicitly share a common sub class.
8353 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8354 return false;
8355
8356 // Check if it will be merged with the load.
8357 // 1. Check the alignment constraint.
8358 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8359 ResVT.getTypeForEVT(*DAG->getContext()));
8360
8361 if (RequiredAlignment > getAlignment())
8362 return false;
8363
8364 // 2. Check that the load is a legal operation for that type.
8365 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8366 return false;
8367
8368 // 3. Check that we do not have a zext in the way.
8369 if (Inst->getValueType(0) != getLoadedType())
8370 return false;
8371
8372 return true;
8373 }
8374};
8375}
8376
Quentin Colombetde0e0622013-10-11 18:29:42 +00008377/// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8378/// \p UsedBits looks like 0..0 1..1 0..0.
8379static bool areUsedBitsDense(const APInt &UsedBits) {
8380 // If all the bits are one, this is dense!
8381 if (UsedBits.isAllOnesValue())
8382 return true;
8383
8384 // Get rid of the unused bits on the right.
8385 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8386 // Get rid of the unused bits on the left.
8387 if (NarrowedUsedBits.countLeadingZeros())
8388 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8389 // Check that the chunk of bits is completely used.
8390 return NarrowedUsedBits.isAllOnesValue();
8391}
8392
8393/// \brief Check whether or not \p First and \p Second are next to each other
8394/// in memory. This means that there is no hole between the bits loaded
8395/// by \p First and the bits loaded by \p Second.
8396static bool areSlicesNextToEachOther(const LoadedSlice &First,
8397 const LoadedSlice &Second) {
8398 assert(First.Origin == Second.Origin && First.Origin &&
8399 "Unable to match different memory origins.");
8400 APInt UsedBits = First.getUsedBits();
8401 assert((UsedBits & Second.getUsedBits()) == 0 &&
8402 "Slices are not supposed to overlap.");
8403 UsedBits |= Second.getUsedBits();
8404 return areUsedBitsDense(UsedBits);
8405}
8406
8407/// \brief Adjust the \p GlobalLSCost according to the target
8408/// paring capabilities and the layout of the slices.
8409/// \pre \p GlobalLSCost should account for at least as many loads as
8410/// there is in the slices in \p LoadedSlices.
8411static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8412 LoadedSlice::Cost &GlobalLSCost) {
8413 unsigned NumberOfSlices = LoadedSlices.size();
8414 // If there is less than 2 elements, no pairing is possible.
8415 if (NumberOfSlices < 2)
8416 return;
8417
8418 // Sort the slices so that elements that are likely to be next to each
8419 // other in memory are next to each other in the list.
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00008420 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8421 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8422 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8423 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8424 });
Quentin Colombetde0e0622013-10-11 18:29:42 +00008425 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8426 // First (resp. Second) is the first (resp. Second) potentially candidate
8427 // to be placed in a paired load.
Craig Topperc0196b12014-04-14 00:51:57 +00008428 const LoadedSlice *First = nullptr;
8429 const LoadedSlice *Second = nullptr;
Quentin Colombetde0e0622013-10-11 18:29:42 +00008430 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8431 // Set the beginning of the pair.
8432 First = Second) {
8433
8434 Second = &LoadedSlices[CurrSlice];
8435
8436 // If First is NULL, it means we start a new pair.
8437 // Get to the next slice.
8438 if (!First)
8439 continue;
8440
8441 EVT LoadedType = First->getLoadedType();
8442
8443 // If the types of the slices are different, we cannot pair them.
8444 if (LoadedType != Second->getLoadedType())
8445 continue;
8446
8447 // Check if the target supplies paired loads for this type.
8448 unsigned RequiredAlignment = 0;
8449 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8450 // move to the next pair, this type is hopeless.
Craig Topperc0196b12014-04-14 00:51:57 +00008451 Second = nullptr;
Quentin Colombetde0e0622013-10-11 18:29:42 +00008452 continue;
8453 }
8454 // Check if we meet the alignment requirement.
8455 if (RequiredAlignment > First->getAlignment())
8456 continue;
8457
8458 // Check that both loads are next to each other in memory.
8459 if (!areSlicesNextToEachOther(*First, *Second))
8460 continue;
8461
8462 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8463 --GlobalLSCost.Loads;
8464 // Move to the next pair.
Craig Topperc0196b12014-04-14 00:51:57 +00008465 Second = nullptr;
Quentin Colombetde0e0622013-10-11 18:29:42 +00008466 }
8467}
8468
8469/// \brief Check the profitability of all involved LoadedSlice.
8470/// Currently, it is considered profitable if there is exactly two
8471/// involved slices (1) which are (2) next to each other in memory, and
8472/// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8473///
8474/// Note: The order of the elements in \p LoadedSlices may be modified, but not
8475/// the elements themselves.
8476///
8477/// FIXME: When the cost model will be mature enough, we can relax
8478/// constraints (1) and (2).
8479static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8480 const APInt &UsedBits, bool ForCodeSize) {
8481 unsigned NumberOfSlices = LoadedSlices.size();
8482 if (StressLoadSlicing)
8483 return NumberOfSlices > 1;
8484
8485 // Check (1).
8486 if (NumberOfSlices != 2)
8487 return false;
8488
8489 // Check (2).
8490 if (!areUsedBitsDense(UsedBits))
8491 return false;
8492
8493 // Check (3).
8494 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8495 // The original code has one big load.
8496 OrigCost.Loads = 1;
8497 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8498 const LoadedSlice &LS = LoadedSlices[CurrSlice];
8499 // Accumulate the cost of all the slices.
8500 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8501 GlobalSlicingCost += SliceCost;
8502
8503 // Account as cost in the original configuration the gain obtained
8504 // with the current slices.
8505 OrigCost.addSliceGain(LS);
8506 }
8507
8508 // If the target supports paired load, adjust the cost accordingly.
8509 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8510 return OrigCost > GlobalSlicingCost;
8511}
8512
8513/// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8514/// operations, split it in the various pieces being extracted.
8515///
8516/// This sort of thing is introduced by SROA.
8517/// This slicing takes care not to insert overlapping loads.
8518/// \pre LI is a simple load (i.e., not an atomic or volatile load).
8519bool DAGCombiner::SliceUpLoad(SDNode *N) {
8520 if (Level < AfterLegalizeDAG)
8521 return false;
8522
8523 LoadSDNode *LD = cast<LoadSDNode>(N);
8524 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8525 !LD->getValueType(0).isInteger())
8526 return false;
8527
8528 // Keep track of already used bits to detect overlapping values.
8529 // In that case, we will just abort the transformation.
8530 APInt UsedBits(LD->getValueSizeInBits(0), 0);
8531
8532 SmallVector<LoadedSlice, 4> LoadedSlices;
8533
8534 // Check if this load is used as several smaller chunks of bits.
8535 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8536 // of computation for each trunc.
8537 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8538 UI != UIEnd; ++UI) {
8539 // Skip the uses of the chain.
8540 if (UI.getUse().getResNo() != 0)
8541 continue;
8542
8543 SDNode *User = *UI;
8544 unsigned Shift = 0;
8545
8546 // Check if this is a trunc(lshr).
8547 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8548 isa<ConstantSDNode>(User->getOperand(1))) {
8549 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8550 User = *User->use_begin();
8551 }
8552
8553 // At this point, User is a Truncate, iff we encountered, trunc or
8554 // trunc(lshr).
8555 if (User->getOpcode() != ISD::TRUNCATE)
8556 return false;
8557
8558 // The width of the type must be a power of 2 and greater than 8-bits.
8559 // Otherwise the load cannot be represented in LLVM IR.
Alp Tokerf907b892013-12-05 05:44:44 +00008560 // Moreover, if we shifted with a non-8-bits multiple, the slice
Alp Tokercb402912014-01-24 17:20:08 +00008561 // will be across several bytes. We do not support that.
Quentin Colombetde0e0622013-10-11 18:29:42 +00008562 unsigned Width = User->getValueSizeInBits(0);
8563 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8564 return 0;
8565
8566 // Build the slice for this chain of computations.
8567 LoadedSlice LS(User, LD, Shift, &DAG);
8568 APInt CurrentUsedBits = LS.getUsedBits();
8569
8570 // Check if this slice overlaps with another.
8571 if ((CurrentUsedBits & UsedBits) != 0)
8572 return false;
8573 // Update the bits used globally.
8574 UsedBits |= CurrentUsedBits;
8575
8576 // Check if the new slice would be legal.
8577 if (!LS.isLegal())
8578 return false;
8579
8580 // Record the slice.
8581 LoadedSlices.push_back(LS);
8582 }
8583
8584 // Abort slicing if it does not seem to be profitable.
8585 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8586 return false;
8587
8588 ++SlicedLoads;
8589
8590 // Rewrite each chain to use an independent load.
8591 // By construction, each chain can be represented by a unique load.
8592
8593 // Prepare the argument for the new token factor for all the slices.
8594 SmallVector<SDValue, 8> ArgChains;
8595 for (SmallVectorImpl<LoadedSlice>::const_iterator
8596 LSIt = LoadedSlices.begin(),
8597 LSItEnd = LoadedSlices.end();
8598 LSIt != LSItEnd; ++LSIt) {
8599 SDValue SliceInst = LSIt->loadSlice();
8600 CombineTo(LSIt->Inst, SliceInst, true);
8601 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8602 SliceInst = SliceInst.getOperand(0);
8603 assert(SliceInst->getOpcode() == ISD::LOAD &&
8604 "It takes more than a zext to get to the loaded slice!!");
8605 ArgChains.push_back(SliceInst.getValue(1));
8606 }
8607
8608 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
Craig Topper48d114b2014-04-26 18:35:24 +00008609 ArgChains);
Quentin Colombetde0e0622013-10-11 18:29:42 +00008610 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8611 return true;
8612}
8613
Chris Lattner4041ab62010-04-15 04:48:01 +00008614/// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8615/// load is having specific bytes cleared out. If so, return the byte size
8616/// being masked out and the shift amount.
8617static std::pair<unsigned, unsigned>
8618CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8619 std::pair<unsigned, unsigned> Result(0, 0);
Wesley Peck527da1b2010-11-23 03:31:01 +00008620
Chris Lattner4041ab62010-04-15 04:48:01 +00008621 // Check for the structure we're looking for.
8622 if (V->getOpcode() != ISD::AND ||
8623 !isa<ConstantSDNode>(V->getOperand(1)) ||
8624 !ISD::isNormalLoad(V->getOperand(0).getNode()))
8625 return Result;
Wesley Peck527da1b2010-11-23 03:31:01 +00008626
Chris Lattner3245afd2010-04-15 06:10:49 +00008627 // Check the chain and pointer.
Chris Lattner4041ab62010-04-15 04:48:01 +00008628 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
Chris Lattner3245afd2010-04-15 06:10:49 +00008629 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
Wesley Peck527da1b2010-11-23 03:31:01 +00008630
Chris Lattner3245afd2010-04-15 06:10:49 +00008631 // The store should be chained directly to the load or be an operand of a
8632 // tokenfactor.
8633 if (LD == Chain.getNode())
8634 ; // ok.
8635 else if (Chain->getOpcode() != ISD::TokenFactor)
8636 return Result; // Fail.
8637 else {
8638 bool isOk = false;
8639 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8640 if (Chain->getOperand(i).getNode() == LD) {
8641 isOk = true;
8642 break;
8643 }
8644 if (!isOk) return Result;
8645 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008646
Chris Lattner4041ab62010-04-15 04:48:01 +00008647 // This only handles simple types.
8648 if (V.getValueType() != MVT::i16 &&
8649 V.getValueType() != MVT::i32 &&
8650 V.getValueType() != MVT::i64)
8651 return Result;
8652
8653 // Check the constant mask. Invert it so that the bits being masked out are
8654 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
8655 // follow the sign bit for uniformity.
8656 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00008657 unsigned NotMaskLZ = countLeadingZeros(NotMask);
Chris Lattner4041ab62010-04-15 04:48:01 +00008658 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00008659 unsigned NotMaskTZ = countTrailingZeros(NotMask);
Chris Lattner4041ab62010-04-15 04:48:01 +00008660 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
8661 if (NotMaskLZ == 64) return Result; // All zero mask.
Wesley Peck527da1b2010-11-23 03:31:01 +00008662
Chris Lattner4041ab62010-04-15 04:48:01 +00008663 // See if we have a continuous run of bits. If so, we have 0*1+0*
8664 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8665 return Result;
8666
8667 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8668 if (V.getValueType() != MVT::i64 && NotMaskLZ)
8669 NotMaskLZ -= 64-V.getValueSizeInBits();
Wesley Peck527da1b2010-11-23 03:31:01 +00008670
Chris Lattner4041ab62010-04-15 04:48:01 +00008671 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8672 switch (MaskedBytes) {
Wesley Peck527da1b2010-11-23 03:31:01 +00008673 case 1:
8674 case 2:
Chris Lattner4041ab62010-04-15 04:48:01 +00008675 case 4: break;
8676 default: return Result; // All one mask, or 5-byte mask.
8677 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008678
Chris Lattner4041ab62010-04-15 04:48:01 +00008679 // Verify that the first bit starts at a multiple of mask so that the access
8680 // is aligned the same as the access width.
8681 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
Wesley Peck527da1b2010-11-23 03:31:01 +00008682
Chris Lattner4041ab62010-04-15 04:48:01 +00008683 Result.first = MaskedBytes;
8684 Result.second = NotMaskTZ/8;
8685 return Result;
8686}
8687
8688
8689/// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8690/// provides a value as specified by MaskInfo. If so, replace the specified
8691/// store with a narrower store of truncated IVal.
8692static SDNode *
8693ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8694 SDValue IVal, StoreSDNode *St,
8695 DAGCombiner *DC) {
8696 unsigned NumBytes = MaskInfo.first;
8697 unsigned ByteShift = MaskInfo.second;
8698 SelectionDAG &DAG = DC->getDAG();
Wesley Peck527da1b2010-11-23 03:31:01 +00008699
Chris Lattner4041ab62010-04-15 04:48:01 +00008700 // Check to see if IVal is all zeros in the part being masked in by the 'or'
8701 // that uses this. If not, this is not a replacement.
8702 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8703 ByteShift*8, (ByteShift+NumBytes)*8);
Craig Topperc0196b12014-04-14 00:51:57 +00008704 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
Wesley Peck527da1b2010-11-23 03:31:01 +00008705
Chris Lattner4041ab62010-04-15 04:48:01 +00008706 // Check that it is legal on the target to do this. It is legal if the new
8707 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8708 // legalization.
8709 MVT VT = MVT::getIntegerVT(NumBytes*8);
8710 if (!DC->isTypeLegal(VT))
Craig Topperc0196b12014-04-14 00:51:57 +00008711 return nullptr;
Wesley Peck527da1b2010-11-23 03:31:01 +00008712
Chris Lattner4041ab62010-04-15 04:48:01 +00008713 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
8714 // shifted by ByteShift and truncated down to NumBytes.
8715 if (ByteShift)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008716 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
Owen Andersonb2c80da2011-02-25 21:41:48 +00008717 DAG.getConstant(ByteShift*8,
8718 DC->getShiftAmountTy(IVal.getValueType())));
Chris Lattner4041ab62010-04-15 04:48:01 +00008719
8720 // Figure out the offset for the store and the alignment of the access.
8721 unsigned StOffset;
8722 unsigned NewAlign = St->getAlignment();
8723
8724 if (DAG.getTargetLoweringInfo().isLittleEndian())
8725 StOffset = ByteShift;
8726 else
8727 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
Wesley Peck527da1b2010-11-23 03:31:01 +00008728
Chris Lattner4041ab62010-04-15 04:48:01 +00008729 SDValue Ptr = St->getBasePtr();
8730 if (StOffset) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00008731 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
Chris Lattner4041ab62010-04-15 04:48:01 +00008732 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8733 NewAlign = MinAlign(NewAlign, StOffset);
8734 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008735
Chris Lattner4041ab62010-04-15 04:48:01 +00008736 // Truncate down to the new size.
Andrew Trickef9de2a2013-05-25 02:42:55 +00008737 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
Wesley Peck527da1b2010-11-23 03:31:01 +00008738
Chris Lattner4041ab62010-04-15 04:48:01 +00008739 ++OpsNarrowed;
Andrew Trickef9de2a2013-05-25 02:42:55 +00008740 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
Chris Lattner676c61d2010-09-21 18:41:36 +00008741 St->getPointerInfo().getWithOffset(StOffset),
Chris Lattner4041ab62010-04-15 04:48:01 +00008742 false, false, NewAlign).getNode();
8743}
8744
Evan Chenga9cda8a2009-05-28 00:35:15 +00008745
8746/// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8747/// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8748/// of the loaded bits, try narrowing the load and store if it would end up
8749/// being a win for performance or code size.
8750SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8751 StoreSDNode *ST = cast<StoreSDNode>(N);
Evan Cheng6673ff02009-05-28 18:41:02 +00008752 if (ST->isVolatile())
8753 return SDValue();
8754
Evan Chenga9cda8a2009-05-28 00:35:15 +00008755 SDValue Chain = ST->getChain();
8756 SDValue Value = ST->getValue();
8757 SDValue Ptr = ST->getBasePtr();
Owen Anderson53aa7a92009-08-10 22:56:29 +00008758 EVT VT = Value.getValueType();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008759
8760 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
Evan Cheng6673ff02009-05-28 18:41:02 +00008761 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008762
8763 unsigned Opc = Value.getOpcode();
Wesley Peck527da1b2010-11-23 03:31:01 +00008764
Chris Lattner4041ab62010-04-15 04:48:01 +00008765 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8766 // is a byte mask indicating a consecutive number of bytes, check to see if
8767 // Y is known to provide just those bytes. If so, we try to replace the
8768 // load + replace + store sequence with a single (narrower) store, which makes
8769 // the load dead.
8770 if (Opc == ISD::OR) {
8771 std::pair<unsigned, unsigned> MaskedLoad;
8772 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8773 if (MaskedLoad.first)
8774 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8775 Value.getOperand(1), ST,this))
8776 return SDValue(NewST, 0);
Wesley Peck527da1b2010-11-23 03:31:01 +00008777
Chris Lattner4041ab62010-04-15 04:48:01 +00008778 // Or is commutative, so try swapping X and Y.
8779 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8780 if (MaskedLoad.first)
8781 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8782 Value.getOperand(0), ST,this))
8783 return SDValue(NewST, 0);
8784 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008785
Evan Chenga9cda8a2009-05-28 00:35:15 +00008786 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8787 Value.getOperand(1).getOpcode() != ISD::Constant)
Evan Cheng6673ff02009-05-28 18:41:02 +00008788 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008789
8790 SDValue N0 = Value.getOperand(0);
Dan Gohman3c9b5f32010-09-02 21:18:42 +00008791 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8792 Chain == SDValue(N0.getNode(), 1)) {
Evan Chenga9cda8a2009-05-28 00:35:15 +00008793 LoadSDNode *LD = cast<LoadSDNode>(N0);
Chris Lattnerf72c3c02010-09-21 16:08:50 +00008794 if (LD->getBasePtr() != Ptr ||
8795 LD->getPointerInfo().getAddrSpace() !=
8796 ST->getPointerInfo().getAddrSpace())
Evan Cheng6673ff02009-05-28 18:41:02 +00008797 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008798
8799 // Find the type to narrow it the load / op / store to.
8800 SDValue N1 = Value.getOperand(1);
8801 unsigned BitWidth = N1.getValueSizeInBits();
8802 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8803 if (Opc == ISD::AND)
8804 Imm ^= APInt::getAllOnesValue(BitWidth);
Evan Cheng86cdb4b2009-05-28 23:52:18 +00008805 if (Imm == 0 || Imm.isAllOnesValue())
8806 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008807 unsigned ShAmt = Imm.countTrailingZeros();
8808 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8809 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
Owen Anderson117c9e82009-08-12 00:36:31 +00008810 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
Evan Chenga9cda8a2009-05-28 00:35:15 +00008811 while (NewBW < BitWidth &&
Evan Cheng6673ff02009-05-28 18:41:02 +00008812 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
Evan Chenga9cda8a2009-05-28 00:35:15 +00008813 TLI.isNarrowingProfitable(VT, NewVT))) {
8814 NewBW = NextPowerOf2(NewBW);
Owen Anderson117c9e82009-08-12 00:36:31 +00008815 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
Evan Chenga9cda8a2009-05-28 00:35:15 +00008816 }
Evan Cheng6673ff02009-05-28 18:41:02 +00008817 if (NewBW >= BitWidth)
8818 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008819
8820 // If the lsb changed does not start at the type bitwidth boundary,
8821 // start at the previous one.
8822 if (ShAmt % NewBW)
8823 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
Manman Ren82751a12012-12-12 01:13:50 +00008824 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8825 std::min(BitWidth, ShAmt + NewBW));
Evan Chenga9cda8a2009-05-28 00:35:15 +00008826 if ((Imm & Mask) == Imm) {
8827 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8828 if (Opc == ISD::AND)
8829 NewImm ^= APInt::getAllOnesValue(NewBW);
8830 uint64_t PtrOff = ShAmt / 8;
8831 // For big endian targets, we need to adjust the offset to the pointer to
8832 // load the correct bytes.
8833 if (TLI.isBigEndian())
Evan Cheng6673ff02009-05-28 18:41:02 +00008834 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
Evan Chenga9cda8a2009-05-28 00:35:15 +00008835
8836 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
Chris Lattner229907c2011-07-18 04:54:35 +00008837 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
Micah Villmowcdfe20b2012-10-08 16:38:25 +00008838 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
Evan Cheng6673ff02009-05-28 18:41:02 +00008839 return SDValue();
8840
Andrew Trickef9de2a2013-05-25 02:42:55 +00008841 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
Evan Chenga9cda8a2009-05-28 00:35:15 +00008842 Ptr.getValueType(), Ptr,
8843 DAG.getConstant(PtrOff, Ptr.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +00008844 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
Evan Chenga9cda8a2009-05-28 00:35:15 +00008845 LD->getChain(), NewPtr,
Chris Lattnerf72c3c02010-09-21 16:08:50 +00008846 LD->getPointerInfo().getWithOffset(PtrOff),
David Greene39c6d012010-02-15 17:00:31 +00008847 LD->isVolatile(), LD->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00008848 LD->isInvariant(), NewAlign,
8849 LD->getTBAAInfo());
Andrew Trickef9de2a2013-05-25 02:42:55 +00008850 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
Evan Chenga9cda8a2009-05-28 00:35:15 +00008851 DAG.getConstant(NewImm, NewVT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00008852 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
Evan Chenga9cda8a2009-05-28 00:35:15 +00008853 NewVal, NewPtr,
Chris Lattnerf72c3c02010-09-21 16:08:50 +00008854 ST->getPointerInfo().getWithOffset(PtrOff),
David Greene39c6d012010-02-15 17:00:31 +00008855 false, false, NewAlign);
Evan Chenga9cda8a2009-05-28 00:35:15 +00008856
8857 AddToWorkList(NewPtr.getNode());
8858 AddToWorkList(NewLD.getNode());
8859 AddToWorkList(NewVal.getNode());
8860 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008861 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
Evan Chenga9cda8a2009-05-28 00:35:15 +00008862 ++OpsNarrowed;
8863 return NewST;
8864 }
8865 }
8866
Evan Cheng6673ff02009-05-28 18:41:02 +00008867 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008868}
8869
Evan Chengd42641c2011-02-02 01:06:55 +00008870/// TransformFPLoadStorePair - For a given floating point load / store pair,
8871/// if the load value isn't used by any other operations, then consider
8872/// transforming the pair to integer load / store operations if the target
8873/// deems the transformation profitable.
8874SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8875 StoreSDNode *ST = cast<StoreSDNode>(N);
8876 SDValue Chain = ST->getChain();
8877 SDValue Value = ST->getValue();
8878 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8879 Value.hasOneUse() &&
8880 Chain == SDValue(Value.getNode(), 1)) {
8881 LoadSDNode *LD = cast<LoadSDNode>(Value);
8882 EVT VT = LD->getMemoryVT();
8883 if (!VT.isFloatingPoint() ||
8884 VT != ST->getMemoryVT() ||
8885 LD->isNonTemporal() ||
8886 ST->isNonTemporal() ||
8887 LD->getPointerInfo().getAddrSpace() != 0 ||
8888 ST->getPointerInfo().getAddrSpace() != 0)
8889 return SDValue();
8890
8891 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8892 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8893 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8894 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8895 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8896 return SDValue();
8897
8898 unsigned LDAlign = LD->getAlignment();
8899 unsigned STAlign = ST->getAlignment();
Chris Lattner229907c2011-07-18 04:54:35 +00008900 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
Micah Villmowcdfe20b2012-10-08 16:38:25 +00008901 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
Evan Chengd42641c2011-02-02 01:06:55 +00008902 if (LDAlign < ABIAlign || STAlign < ABIAlign)
8903 return SDValue();
8904
Andrew Trickef9de2a2013-05-25 02:42:55 +00008905 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
Evan Chengd42641c2011-02-02 01:06:55 +00008906 LD->getChain(), LD->getBasePtr(),
8907 LD->getPointerInfo(),
Pete Cooper82cd9e82011-11-08 18:42:53 +00008908 false, false, false, LDAlign);
Evan Chengd42641c2011-02-02 01:06:55 +00008909
Andrew Trickef9de2a2013-05-25 02:42:55 +00008910 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
Evan Chengd42641c2011-02-02 01:06:55 +00008911 NewLD, ST->getBasePtr(),
8912 ST->getPointerInfo(),
8913 false, false, STAlign);
8914
8915 AddToWorkList(NewLD.getNode());
8916 AddToWorkList(NewST.getNode());
8917 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008918 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
Evan Chengd42641c2011-02-02 01:06:55 +00008919 ++LdStFP2Int;
8920 return NewST;
8921 }
8922
8923 return SDValue();
8924}
8925
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008926/// Helper struct to parse and store a memory address as base + index + offset.
8927/// We ignore sign extensions when it is safe to do so.
8928/// The following two expressions are not equivalent. To differentiate we need
8929/// to store whether there was a sign extension involved in the index
8930/// computation.
8931/// (load (i64 add (i64 copyfromreg %c)
8932/// (i64 signextend (add (i8 load %index)
8933/// (i8 1))))
8934/// vs
8935///
8936/// (load (i64 add (i64 copyfromreg %c)
8937/// (i64 signextend (i32 add (i32 signextend (i8 load %index))
8938/// (i32 1)))))
8939struct BaseIndexOffset {
8940 SDValue Base;
8941 SDValue Index;
8942 int64_t Offset;
8943 bool IsIndexSignExt;
8944
8945 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
8946
8947 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
8948 bool IsIndexSignExt) :
8949 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
8950
8951 bool equalBaseIndex(const BaseIndexOffset &Other) {
8952 return Other.Base == Base && Other.Index == Index &&
8953 Other.IsIndexSignExt == IsIndexSignExt;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008954 }
8955
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008956 /// Parses tree in Ptr for base, index, offset addresses.
8957 static BaseIndexOffset match(SDValue Ptr) {
8958 bool IsIndexSignExt = false;
8959
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00008960 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
8961 // instruction, then it could be just the BASE or everything else we don't
8962 // know how to handle. Just use Ptr as BASE and give up.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008963 if (Ptr->getOpcode() != ISD::ADD)
8964 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8965
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00008966 // We know that we have at least an ADD instruction. Try to pattern match
8967 // the simple case of BASE + OFFSET.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008968 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
8969 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
8970 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
8971 IsIndexSignExt);
8972 }
8973
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00008974 // Inside a loop the current BASE pointer is calculated using an ADD and a
Juergen Ributzka11c52c62013-08-28 22:33:58 +00008975 // MUL instruction. In this case Ptr is the actual BASE pointer.
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00008976 // (i64 add (i64 %array_ptr)
8977 // (i64 mul (i64 %induction_var)
8978 // (i64 %element_size)))
Juergen Ributzka11c52c62013-08-28 22:33:58 +00008979 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00008980 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00008981
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008982 // Look at Base + Index + Offset cases.
8983 SDValue Base = Ptr->getOperand(0);
8984 SDValue IndexOffset = Ptr->getOperand(1);
8985
8986 // Skip signextends.
8987 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
8988 IndexOffset = IndexOffset->getOperand(0);
8989 IsIndexSignExt = true;
8990 }
8991
8992 // Either the case of Base + Index (no offset) or something else.
8993 if (IndexOffset->getOpcode() != ISD::ADD)
8994 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
8995
8996 // Now we have the case of Base + Index + offset.
8997 SDValue Index = IndexOffset->getOperand(0);
8998 SDValue Offset = IndexOffset->getOperand(1);
8999
9000 if (!isa<ConstantSDNode>(Offset))
9001 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9002
9003 // Ignore signextends.
9004 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
9005 Index = Index->getOperand(0);
9006 IsIndexSignExt = true;
9007 } else IsIndexSignExt = false;
9008
9009 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
9010 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
9011 }
9012};
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009013
9014/// Holds a pointer to an LSBaseSDNode as well as information on where it
9015/// is located in a sequence of memory operations connected by a chain.
9016struct MemOpLink {
9017 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
9018 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
9019 // Ptr to the mem node.
9020 LSBaseSDNode *MemNode;
9021 // Offset from the base ptr.
9022 int64_t OffsetFromBase;
9023 // What is the sequence number of this mem node.
9024 // Lowest mem operand in the DAG starts at zero.
9025 unsigned SequenceNum;
9026};
9027
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009028bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
9029 EVT MemVT = St->getMemoryVT();
9030 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
Nadav Rotem495b1a42013-02-14 18:28:52 +00009031 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
9032 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009033
9034 // Don't merge vectors into wider inputs.
9035 if (MemVT.isVector() || !MemVT.isSimple())
9036 return false;
9037
9038 // Perform an early exit check. Do not bother looking at stored values that
9039 // are not constants or loads.
9040 SDValue StoredVal = St->getValue();
9041 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
9042 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
9043 !IsLoadSrc)
9044 return false;
9045
9046 // Only look at ends of store sequences.
9047 SDValue Chain = SDValue(St, 1);
9048 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9049 return false;
9050
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009051 // This holds the base pointer, index, and the offset in bytes from the base
9052 // pointer.
9053 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009054
9055 // We must have a base and an offset.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009056 if (!BasePtr.Base.getNode())
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009057 return false;
9058
9059 // Do not handle stores to undef base pointers.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009060 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009061 return false;
9062
Nadav Rotem307d7672012-11-29 00:00:08 +00009063 // Save the LoadSDNodes that we find in the chain.
9064 // We need to make sure that these nodes do not interfere with
9065 // any of the store nodes.
9066 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9067
9068 // Save the StoreSDNodes that we find in the chain.
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009069 SmallVector<MemOpLink, 8> StoreNodes;
Nadav Rotem307d7672012-11-29 00:00:08 +00009070
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009071 // Walk up the chain and look for nodes with offsets from the same
9072 // base pointer. Stop when reaching an instruction with a different kind
9073 // or instruction which has a different base pointer.
9074 unsigned Seq = 0;
9075 StoreSDNode *Index = St;
9076 while (Index) {
9077 // If the chain has more than one use, then we can't reorder the mem ops.
9078 if (Index != St && !SDValue(Index, 1)->hasOneUse())
9079 break;
9080
9081 // Find the base pointer and offset for this memory node.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009082 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009083
9084 // Check that the base pointer is the same as the original one.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009085 if (!Ptr.equalBaseIndex(BasePtr))
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009086 break;
9087
9088 // Check that the alignment is the same.
9089 if (Index->getAlignment() != St->getAlignment())
9090 break;
9091
9092 // The memory operands must not be volatile.
9093 if (Index->isVolatile() || Index->isIndexed())
9094 break;
9095
9096 // No truncation.
9097 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9098 if (St->isTruncatingStore())
9099 break;
9100
9101 // The stored memory type must be the same.
9102 if (Index->getMemoryVT() != MemVT)
9103 break;
9104
9105 // We do not allow unaligned stores because we want to prevent overriding
9106 // stores.
9107 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9108 break;
9109
9110 // We found a potential memory operand to merge.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009111 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009112
Nadav Rotem307d7672012-11-29 00:00:08 +00009113 // Find the next memory operand in the chain. If the next operand in the
9114 // chain is a store then move up and continue the scan with the next
9115 // memory operand. If the next operand is a load save it and use alias
9116 // information to check if it interferes with anything.
9117 SDNode *NextInChain = Index->getChain().getNode();
9118 while (1) {
Nadav Rotemac450eb2012-12-06 17:34:13 +00009119 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
Nadav Rotem307d7672012-11-29 00:00:08 +00009120 // We found a store node. Use it for the next iteration.
Nadav Rotemac450eb2012-12-06 17:34:13 +00009121 Index = STn;
Nadav Rotem307d7672012-11-29 00:00:08 +00009122 break;
9123 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
Bill Wendling9200bb02013-11-25 18:05:22 +00009124 if (Ldn->isVolatile()) {
Craig Topperc0196b12014-04-14 00:51:57 +00009125 Index = nullptr;
Bill Wendling9200bb02013-11-25 18:05:22 +00009126 break;
9127 }
9128
Nadav Rotem307d7672012-11-29 00:00:08 +00009129 // Save the load node for later. Continue the scan.
9130 AliasLoadNodes.push_back(Ldn);
9131 NextInChain = Ldn->getChain().getNode();
9132 continue;
9133 } else {
Craig Topperc0196b12014-04-14 00:51:57 +00009134 Index = nullptr;
Nadav Rotem307d7672012-11-29 00:00:08 +00009135 break;
9136 }
9137 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009138 }
9139
9140 // Check if there is anything to merge.
9141 if (StoreNodes.size() < 2)
9142 return false;
9143
9144 // Sort the memory operands according to their distance from the base pointer.
9145 std::sort(StoreNodes.begin(), StoreNodes.end(),
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00009146 [](MemOpLink LHS, MemOpLink RHS) {
9147 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9148 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9149 LHS.SequenceNum > RHS.SequenceNum);
9150 });
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009151
9152 // Scan the memory operations on the chain and find the first non-consecutive
9153 // store memory address.
9154 unsigned LastConsecutiveStore = 0;
9155 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
Nadav Rotemac450eb2012-12-06 17:34:13 +00009156 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9157
9158 // Check that the addresses are consecutive starting from the second
9159 // element in the list of stores.
9160 if (i > 0) {
9161 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9162 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9163 break;
9164 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009165
Nadav Rotem307d7672012-11-29 00:00:08 +00009166 bool Alias = false;
9167 // Check if this store interferes with any of the loads that we found.
9168 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9169 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9170 Alias = true;
9171 break;
9172 }
Nadav Rotem307d7672012-11-29 00:00:08 +00009173 // We found a load that alias with this store. Stop the sequence.
9174 if (Alias)
9175 break;
9176
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009177 // Mark this node as useful.
9178 LastConsecutiveStore = i;
9179 }
9180
9181 // The node with the lowest store address.
9182 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9183
9184 // Store the constants into memory as one consecutive store.
9185 if (!IsLoadSrc) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009186 unsigned LastLegalType = 0;
Nadav Rotemb27777f2012-10-04 22:35:15 +00009187 unsigned LastLegalVectorType = 0;
9188 bool NonZero = false;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009189 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9190 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9191 SDValue StoredVal = St->getValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +00009192
9193 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
Benjamin Kramer62f7fb92012-10-05 18:19:44 +00009194 NonZero |= !C->isNullValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +00009195 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
Benjamin Kramer62f7fb92012-10-05 18:19:44 +00009196 NonZero |= !C->getConstantFPValue()->isNullValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +00009197 } else {
Alp Tokerf907b892013-12-05 05:44:44 +00009198 // Non-constant.
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009199 break;
Nadav Rotemb27777f2012-10-04 22:35:15 +00009200 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009201
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009202 // Find a legal type for the constant store.
9203 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9204 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9205 if (TLI.isTypeLegal(StoreTy))
9206 LastLegalType = i+1;
Arnold Schwaighoferd6c6e862013-04-02 15:58:51 +00009207 // Or check whether a truncstore is legal.
9208 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9209 TargetLowering::TypePromoteInteger) {
9210 EVT LegalizedStoredValueTy =
9211 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9212 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9213 LastLegalType = i+1;
9214 }
Nadav Rotemb27777f2012-10-04 22:35:15 +00009215
9216 // Find a legal type for the vector store.
9217 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9218 if (TLI.isTypeLegal(Ty))
9219 LastLegalVectorType = i + 1;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009220 }
9221
Bob Wilson3365b802012-12-20 01:36:20 +00009222 // We only use vectors if the constant is known to be zero and the
9223 // function is not marked with the noimplicitfloat attribute.
Nadav Rotem495b1a42013-02-14 18:28:52 +00009224 if (NonZero || NoVectors)
Nadav Rotemb27777f2012-10-04 22:35:15 +00009225 LastLegalVectorType = 0;
9226
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009227 // Check if we found a legal integer type to store.
Nadav Rotemb27777f2012-10-04 22:35:15 +00009228 if (LastLegalType == 0 && LastLegalVectorType == 0)
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009229 return false;
9230
Nadav Rotem495b1a42013-02-14 18:28:52 +00009231 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
Nadav Rotemb27777f2012-10-04 22:35:15 +00009232 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9233
9234 // Make sure we have something to merge.
9235 if (NumElem < 2)
9236 return false;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009237
9238 unsigned EarliestNodeUsed = 0;
9239 for (unsigned i=0; i < NumElem; ++i) {
9240 // Find a chain for the new wide-store operand. Notice that some
9241 // of the store nodes that we found may not be selected for inclusion
9242 // in the wide store. The chain we use needs to be the chain of the
9243 // earliest store node which is *used* and replaced by the wide store.
9244 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9245 EarliestNodeUsed = i;
9246 }
9247
9248 // The earliest Node in the DAG.
9249 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
Andrew Trickef9de2a2013-05-25 02:42:55 +00009250 SDLoc DL(StoreNodes[0].MemNode);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009251
Nadav Rotemb27777f2012-10-04 22:35:15 +00009252 SDValue StoredVal;
9253 if (UseVector) {
9254 // Find a legal type for the vector store.
9255 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9256 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9257 StoredVal = DAG.getConstant(0, Ty);
9258 } else {
9259 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9260 APInt StoreInt(StoreBW, 0);
9261
9262 // Construct a single integer constant which is made of the smaller
9263 // constant inputs.
9264 bool IsLE = TLI.isLittleEndian();
9265 for (unsigned i = 0; i < NumElem ; ++i) {
9266 unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9267 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9268 SDValue Val = St->getValue();
9269 StoreInt<<=ElementSizeBytes*8;
9270 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9271 StoreInt|=C->getAPIntValue().zext(StoreBW);
9272 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9273 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9274 } else {
9275 assert(false && "Invalid constant element type");
9276 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009277 }
Nadav Rotemb27777f2012-10-04 22:35:15 +00009278
9279 // Create the new Load and Store operations.
9280 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9281 StoredVal = DAG.getConstant(StoreInt, StoreTy);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009282 }
9283
Nadav Rotemb27777f2012-10-04 22:35:15 +00009284 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009285 FirstInChain->getBasePtr(),
9286 FirstInChain->getPointerInfo(),
9287 false, false,
9288 FirstInChain->getAlignment());
9289
9290 // Replace the first store with the new store
9291 CombineTo(EarliestOp, NewStore);
9292 // Erase all other stores.
9293 for (unsigned i = 0; i < NumElem ; ++i) {
9294 if (StoreNodes[i].MemNode == EarliestOp)
9295 continue;
9296 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
Rafael Espindolac79532d2012-11-14 05:08:56 +00009297 // ReplaceAllUsesWith will replace all uses that existed when it was
9298 // called, but graph optimizations may cause new ones to appear. For
9299 // example, the case in pr14333 looks like
9300 //
9301 // St's chain -> St -> another store -> X
9302 //
9303 // And the only difference from St to the other store is the chain.
9304 // When we change it's chain to be St's chain they become identical,
9305 // get CSEed and the net result is that X is now a use of St.
9306 // Since we know that St is redundant, just iterate.
9307 while (!St->use_empty())
9308 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009309 removeFromWorkList(St);
9310 DAG.DeleteNode(St);
9311 }
9312
9313 return true;
9314 }
9315
9316 // Below we handle the case of multiple consecutive stores that
9317 // come from multiple consecutive loads. We merge them into a single
9318 // wide load and a single wide store.
9319
9320 // Look for load nodes which are used by the stored values.
9321 SmallVector<MemOpLink, 8> LoadNodes;
9322
9323 // Find acceptable loads. Loads need to have the same chain (token factor),
9324 // must not be zext, volatile, indexed, and they must be consecutive.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009325 BaseIndexOffset LdBasePtr;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009326 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9327 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9328 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9329 if (!Ld) break;
9330
9331 // Loads must only have one use.
9332 if (!Ld->hasNUsesOfValue(1, 0))
9333 break;
9334
9335 // Check that the alignment is the same as the stores.
9336 if (Ld->getAlignment() != St->getAlignment())
9337 break;
9338
9339 // The memory operands must not be volatile.
9340 if (Ld->isVolatile() || Ld->isIndexed())
9341 break;
9342
9343 // We do not accept ext loads.
9344 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9345 break;
9346
9347 // The stored memory type must be the same.
9348 if (Ld->getMemoryVT() != MemVT)
9349 break;
9350
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009351 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009352 // If this is not the first ptr that we check.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009353 if (LdBasePtr.Base.getNode()) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009354 // The base ptr must be the same.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009355 if (!LdPtr.equalBaseIndex(LdBasePtr))
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009356 break;
9357 } else {
9358 // Check that all other base pointers are the same as this one.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009359 LdBasePtr = LdPtr;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009360 }
9361
9362 // We found a potential memory operand to merge.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009363 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009364 }
9365
9366 if (LoadNodes.size() < 2)
9367 return false;
9368
9369 // Scan the memory operations on the chain and find the first non-consecutive
9370 // load memory address. These variables hold the index in the store node
9371 // array.
9372 unsigned LastConsecutiveLoad = 0;
9373 // This variable refers to the size and not index in the array.
9374 unsigned LastLegalVectorType = 0;
9375 unsigned LastLegalIntegerType = 0;
9376 StartAddress = LoadNodes[0].OffsetFromBase;
Nadav Rotemac920662012-10-03 19:30:31 +00009377 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9378 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9379 // All loads much share the same chain.
9380 if (LoadNodes[i].MemNode->getChain() != FirstChain)
9381 break;
Nadav Rotem495b1a42013-02-14 18:28:52 +00009382
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009383 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9384 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9385 break;
9386 LastConsecutiveLoad = i;
9387
9388 // Find a legal type for the vector store.
9389 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9390 if (TLI.isTypeLegal(StoreTy))
9391 LastLegalVectorType = i + 1;
9392
9393 // Find a legal type for the integer store.
9394 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9395 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9396 if (TLI.isTypeLegal(StoreTy))
9397 LastLegalIntegerType = i + 1;
Arnold Schwaighoferd6c6e862013-04-02 15:58:51 +00009398 // Or check whether a truncstore and extload is legal.
9399 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9400 TargetLowering::TypePromoteInteger) {
9401 EVT LegalizedStoredValueTy =
9402 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9403 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9404 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9405 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9406 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9407 LastLegalIntegerType = i+1;
9408 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009409 }
9410
9411 // Only use vector types if the vector type is larger than the integer type.
9412 // If they are the same, use integers.
Nadav Rotem495b1a42013-02-14 18:28:52 +00009413 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009414 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9415
9416 // We add +1 here because the LastXXX variables refer to location while
9417 // the NumElem refers to array/index size.
9418 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9419 NumElem = std::min(LastLegalType, NumElem);
9420
9421 if (NumElem < 2)
9422 return false;
9423
9424 // The earliest Node in the DAG.
9425 unsigned EarliestNodeUsed = 0;
9426 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9427 for (unsigned i=1; i<NumElem; ++i) {
9428 // Find a chain for the new wide-store operand. Notice that some
9429 // of the store nodes that we found may not be selected for inclusion
9430 // in the wide store. The chain we use needs to be the chain of the
9431 // earliest store node which is *used* and replaced by the wide store.
9432 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9433 EarliestNodeUsed = i;
9434 }
9435
9436 // Find if it is better to use vectors or integers to load and store
9437 // to memory.
9438 EVT JointMemOpVT;
9439 if (UseVectorTy) {
9440 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9441 } else {
9442 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9443 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9444 }
9445
Andrew Trickef9de2a2013-05-25 02:42:55 +00009446 SDLoc LoadDL(LoadNodes[0].MemNode);
9447 SDLoc StoreDL(StoreNodes[0].MemNode);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009448
9449 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9450 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9451 FirstLoad->getChain(),
9452 FirstLoad->getBasePtr(),
9453 FirstLoad->getPointerInfo(),
9454 false, false, false,
9455 FirstLoad->getAlignment());
9456
9457 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9458 FirstInChain->getBasePtr(),
9459 FirstInChain->getPointerInfo(), false, false,
9460 FirstInChain->getAlignment());
9461
Nadav Rotemac920662012-10-03 19:30:31 +00009462 // Replace one of the loads with the new load.
9463 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9464 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9465 SDValue(NewLoad.getNode(), 1));
9466
9467 // Remove the rest of the load chains.
9468 for (unsigned i = 1; i < NumElem ; ++i) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009469 // Replace all chain users of the old load nodes with the chain of the new
9470 // load node.
9471 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
Nadav Rotemac920662012-10-03 19:30:31 +00009472 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9473 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009474
Nadav Rotemac920662012-10-03 19:30:31 +00009475 // Replace the first store with the new store.
9476 CombineTo(EarliestOp, NewStore);
9477 // Erase all other stores.
9478 for (unsigned i = 0; i < NumElem ; ++i) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009479 // Remove all Store nodes.
9480 if (StoreNodes[i].MemNode == EarliestOp)
9481 continue;
9482 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9483 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9484 removeFromWorkList(St);
9485 DAG.DeleteNode(St);
9486 }
9487
9488 return true;
9489}
9490
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009491SDValue DAGCombiner::visitSTORE(SDNode *N) {
Evan Chengab51cf22006-10-13 21:14:26 +00009492 StoreSDNode *ST = cast<StoreSDNode>(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009493 SDValue Chain = ST->getChain();
9494 SDValue Value = ST->getValue();
9495 SDValue Ptr = ST->getBasePtr();
Scott Michelcf0da6c2009-02-17 22:15:04 +00009496
Evan Chenga4cf58a2007-05-07 21:27:48 +00009497 // If this is a store of a bit convert, store the input value if the
Evan Chengf325c2a2007-05-09 21:49:47 +00009498 // resultant store does not need a higher alignment than the original.
Wesley Peck527da1b2010-11-23 03:31:01 +00009499 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009500 ST->isUnindexed()) {
Dan Gohmane7fe80f2009-02-20 23:29:13 +00009501 unsigned OrigAlign = ST->getAlignment();
Owen Anderson53aa7a92009-08-10 22:56:29 +00009502 EVT SVT = Value.getOperand(0).getValueType();
Micah Villmowcdfe20b2012-10-08 16:38:25 +00009503 unsigned Align = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +00009504 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
Duncan Sands8651e9c2008-06-13 19:07:40 +00009505 if (Align <= OrigAlign &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00009506 ((!LegalOperations && !ST->isVolatile()) ||
Dan Gohman4aa18462009-01-28 17:46:25 +00009507 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00009508 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
Chris Lattner676c61d2010-09-21 18:41:36 +00009509 Ptr, ST->getPointerInfo(), ST->isVolatile(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009510 ST->isNonTemporal(), OrigAlign,
9511 ST->getTBAAInfo());
Jim Laskeyd07be232006-09-25 16:29:54 +00009512 }
Owen Andersona5192842011-04-14 17:30:49 +00009513
Chris Lattner41c80e82011-04-09 02:32:02 +00009514 // Turn 'store undef, Ptr' -> nothing.
9515 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9516 return Chain;
Duncan Sands8651e9c2008-06-13 19:07:40 +00009517
Nate Begeman8e20c762006-12-11 02:23:46 +00009518 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
Nate Begeman8e20c762006-12-11 02:23:46 +00009519 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
Duncan Sands8651e9c2008-06-13 19:07:40 +00009520 // NOTE: If the original store is volatile, this transform must not increase
9521 // the number of stores. For example, on x86-32 an f64 can be stored in one
9522 // processor operation but an i64 (which is not legal) requires two. So the
9523 // transform should not be done in this case.
Evan Cheng21836982006-12-11 17:25:19 +00009524 if (Value.getOpcode() != ISD::TargetConstantFP) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009525 SDValue Tmp;
Craig Topperd9c27832013-08-15 02:44:19 +00009526 switch (CFP->getSimpleValueType(0).SimpleTy) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00009527 default: llvm_unreachable("Unknown FP type");
Pete Cooper5b614222012-06-21 18:00:39 +00009528 case MVT::f16: // We don't do this for these yet.
9529 case MVT::f80:
Owen Anderson9f944592009-08-11 20:47:22 +00009530 case MVT::f128:
9531 case MVT::ppcf128:
Dale Johannesenaf12b572007-09-18 18:36:59 +00009532 break;
Owen Anderson9f944592009-08-11 20:47:22 +00009533 case MVT::f32:
Chris Lattner4041ab62010-04-15 04:48:01 +00009534 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
Owen Anderson9f944592009-08-11 20:47:22 +00009535 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
Dale Johannesen028084e2007-09-12 03:30:33 +00009536 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
Owen Anderson9f944592009-08-11 20:47:22 +00009537 bitcastToAPInt().getZExtValue(), MVT::i32);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009538 return DAG.getStore(Chain, SDLoc(N), Tmp,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009539 Ptr, ST->getMemOperand());
Chris Lattnerb7524b62006-12-12 04:16:14 +00009540 }
9541 break;
Owen Anderson9f944592009-08-11 20:47:22 +00009542 case MVT::f64:
Chris Lattner4041ab62010-04-15 04:48:01 +00009543 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
Dan Gohman4aa18462009-01-28 17:46:25 +00009544 !ST->isVolatile()) ||
Owen Anderson9f944592009-08-11 20:47:22 +00009545 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
Dale Johannesen54306fe2008-10-09 18:53:47 +00009546 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
Owen Anderson9f944592009-08-11 20:47:22 +00009547 getZExtValue(), MVT::i64);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009548 return DAG.getStore(Chain, SDLoc(N), Tmp,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009549 Ptr, ST->getMemOperand());
Chris Lattner41c80e82011-04-09 02:32:02 +00009550 }
Owen Andersona5192842011-04-14 17:30:49 +00009551
Chris Lattner41c80e82011-04-09 02:32:02 +00009552 if (!ST->isVolatile() &&
9553 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
Duncan Sands1826ded2007-10-28 12:59:45 +00009554 // Many FP stores are not made apparent until after legalize, e.g. for
Chris Lattnerb7524b62006-12-12 04:16:14 +00009555 // argument passing. Since this is so common, custom legalize the
9556 // 64-bit integer store into two 32-bit stores.
Dale Johannesen54306fe2008-10-09 18:53:47 +00009557 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
Owen Anderson9f944592009-08-11 20:47:22 +00009558 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9559 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
Duncan Sands7377f5f2008-02-11 10:37:04 +00009560 if (TLI.isBigEndian()) std::swap(Lo, Hi);
Chris Lattnerb7524b62006-12-12 04:16:14 +00009561
Dan Gohman2af30632007-07-09 22:18:38 +00009562 unsigned Alignment = ST->getAlignment();
9563 bool isVolatile = ST->isVolatile();
David Greene39c6d012010-02-15 17:00:31 +00009564 bool isNonTemporal = ST->isNonTemporal();
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009565 const MDNode *TBAAInfo = ST->getTBAAInfo();
Dan Gohman2af30632007-07-09 22:18:38 +00009566
Andrew Trickef9de2a2013-05-25 02:42:55 +00009567 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
Chris Lattner676c61d2010-09-21 18:41:36 +00009568 Ptr, ST->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +00009569 isVolatile, isNonTemporal,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009570 ST->getAlignment(), TBAAInfo);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009571 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
Chris Lattnerb7524b62006-12-12 04:16:14 +00009572 DAG.getConstant(4, Ptr.getValueType()));
Duncan Sands1826ded2007-10-28 12:59:45 +00009573 Alignment = MinAlign(Alignment, 4U);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009574 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
Chris Lattner676c61d2010-09-21 18:41:36 +00009575 Ptr, ST->getPointerInfo().getWithOffset(4),
9576 isVolatile, isNonTemporal,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009577 Alignment, TBAAInfo);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009578 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
Bill Wendling27d9dd42009-01-30 23:36:47 +00009579 St0, St1);
Chris Lattnerb7524b62006-12-12 04:16:14 +00009580 }
Bill Wendling27d9dd42009-01-30 23:36:47 +00009581
Chris Lattnerb7524b62006-12-12 04:16:14 +00009582 break;
Evan Cheng21836982006-12-11 17:25:19 +00009583 }
Nate Begeman8e20c762006-12-11 02:23:46 +00009584 }
Nate Begeman8e20c762006-12-11 02:23:46 +00009585 }
9586
Evan Cheng43cd9e32010-04-01 06:04:33 +00009587 // Try to infer better alignment information than the store already has.
9588 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
Evan Cheng4a5b2042011-11-28 22:37:34 +00009589 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9590 if (Align > ST->getAlignment())
Andrew Trickef9de2a2013-05-25 02:42:55 +00009591 return DAG.getTruncStore(Chain, SDLoc(N), Value,
Evan Cheng4a5b2042011-11-28 22:37:34 +00009592 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009593 ST->isVolatile(), ST->isNonTemporal(), Align,
9594 ST->getTBAAInfo());
Evan Cheng43cd9e32010-04-01 06:04:33 +00009595 }
9596 }
9597
Evan Chengd42641c2011-02-02 01:06:55 +00009598 // Try transforming a pair floating point load / store ops to integer
9599 // load / store ops.
9600 SDValue NewST = TransformFPLoadStorePair(N);
9601 if (NewST.getNode())
9602 return NewST;
9603
Hal Finkel5ef4dcc2013-08-29 03:29:55 +00009604 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9605 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +00009606#ifndef NDEBUG
9607 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9608 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9609 UseAA = false;
9610#endif
Hal Finkelccc18e12014-01-24 18:25:26 +00009611 if (UseAA && ST->isUnindexed()) {
Jim Laskeyd07be232006-09-25 16:29:54 +00009612 // Walk up chain skipping non-aliasing memory nodes.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009613 SDValue BetterChain = FindBetterChain(N, Chain);
Scott Michelcf0da6c2009-02-17 22:15:04 +00009614
Jim Laskey708d0db2006-10-04 16:53:27 +00009615 // If there is a better chain.
Jim Laskeyd07be232006-09-25 16:29:54 +00009616 if (Chain != BetterChain) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009617 SDValue ReplStore;
Nate Begeman879d8f12009-09-15 00:18:30 +00009618
9619 // Replace the chain to avoid dependency.
Jim Laskey3bf4f3b2006-10-14 12:14:27 +00009620 if (ST->isTruncatingStore()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009621 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009622 ST->getMemoryVT(), ST->getMemOperand());
Jim Laskey3bf4f3b2006-10-14 12:14:27 +00009623 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009624 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009625 ST->getMemOperand());
Jim Laskey3bf4f3b2006-10-14 12:14:27 +00009626 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00009627
Jim Laskeyd07be232006-09-25 16:29:54 +00009628 // Create token to keep both nodes around.
Andrew Trickef9de2a2013-05-25 02:42:55 +00009629 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
Owen Anderson9f944592009-08-11 20:47:22 +00009630 MVT::Other, Chain, ReplStore);
Bill Wendling27d9dd42009-01-30 23:36:47 +00009631
Nate Begeman879d8f12009-09-15 00:18:30 +00009632 // Make sure the new and old chains are cleaned up.
9633 AddToWorkList(Token.getNode());
9634
Jim Laskeydcf983c2006-10-13 23:32:28 +00009635 // Don't add users to work list.
9636 return CombineTo(N, Token, false);
Jim Laskeyd07be232006-09-25 16:29:54 +00009637 }
Jim Laskey5d19d592006-09-21 16:28:59 +00009638 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00009639
Evan Cheng33157702006-11-05 09:31:14 +00009640 // Try transforming N to an indexed store.
Evan Cheng60c68462006-11-07 09:03:05 +00009641 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009642 return SDValue(N, 0);
Evan Cheng33157702006-11-05 09:31:14 +00009643
Chris Lattner3f9c6a72007-12-29 06:26:16 +00009644 // FIXME: is there such a thing as a truncating indexed store?
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009645 if (ST->isTruncatingStore() && ST->isUnindexed() &&
Nadav Rotemd2d9bdb2011-06-15 11:19:12 +00009646 Value.getValueType().isInteger()) {
Chris Lattner5e6fe052007-10-13 06:35:54 +00009647 // See if we can simplify the input to this truncstore with knowledge that
9648 // only the low bits are being used. For example:
9649 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
Scott Michelcf0da6c2009-02-17 22:15:04 +00009650 SDValue Shorter =
Dan Gohman1f372ed2008-02-25 21:11:39 +00009651 GetDemandedBits(Value,
Nadav Rotemd2d9bdb2011-06-15 11:19:12 +00009652 APInt::getLowBitsSet(
9653 Value.getValueType().getScalarType().getSizeInBits(),
9654 ST->getMemoryVT().getScalarType().getSizeInBits()));
Gabor Greiff304a7a2008-08-28 21:40:38 +00009655 AddToWorkList(Value.getNode());
9656 if (Shorter.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00009657 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009658 Ptr, ST->getMemoryVT(), ST->getMemOperand());
Scott Michelcf0da6c2009-02-17 22:15:04 +00009659
Chris Lattnerf47e3062007-10-13 06:58:48 +00009660 // Otherwise, see if we can simplify the operation with
9661 // SimplifyDemandedBits, which only works if the value has a single use.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +00009662 if (SimplifyDemandedBits(Value,
Eric Christopherd9e8eac2010-12-09 04:48:06 +00009663 APInt::getLowBitsSet(
9664 Value.getValueType().getScalarType().getSizeInBits(),
9665 ST->getMemoryVT().getScalarType().getSizeInBits())))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009666 return SDValue(N, 0);
Chris Lattner5e6fe052007-10-13 06:35:54 +00009667 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00009668
Chris Lattner3f9c6a72007-12-29 06:26:16 +00009669 // If this is a load followed by a store to the same location, then the store
9670 // is dead/noop.
9671 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
Dan Gohman47a7d6f2008-01-30 00:15:11 +00009672 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009673 ST->isUnindexed() && !ST->isVolatile() &&
Chris Lattner51b01bf2008-01-08 23:08:06 +00009674 // There can't be any side effects between the load and store, such as
9675 // a call or store.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009676 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
Chris Lattner3f9c6a72007-12-29 06:26:16 +00009677 // The store is dead, remove it.
9678 return Chain;
9679 }
9680 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00009681
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009682 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9683 // truncating store. We can do this even if this is already a truncstore.
9684 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
Gabor Greiff304a7a2008-08-28 21:40:38 +00009685 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009686 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
Dan Gohman47a7d6f2008-01-30 00:15:11 +00009687 ST->getMemoryVT())) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009688 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009689 Ptr, ST->getMemoryVT(), ST->getMemOperand());
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009690 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00009691
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009692 // Only perform this optimization before the types are legal, because we
Nadav Rotemb27777f2012-10-04 22:35:15 +00009693 // don't want to perform this optimization on every DAGCombine invocation.
Nadav Rotem1157e142012-12-02 17:14:09 +00009694 if (!LegalTypes) {
9695 bool EverChanged = false;
9696
9697 do {
9698 // There can be multiple store sequences on the same chain.
9699 // Keep trying to merge store sequences until we are unable to do so
9700 // or until we merge the last store on the chain.
9701 bool Changed = MergeConsecutiveStores(ST);
9702 EverChanged |= Changed;
9703 if (!Changed) break;
9704 } while (ST->getOpcode() != ISD::DELETED_NODE);
9705
9706 if (EverChanged)
9707 return SDValue(N, 0);
9708 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009709
Evan Chenga9cda8a2009-05-28 00:35:15 +00009710 return ReduceLoadOpStoreWidth(N);
Chris Lattner04c73702005-10-10 22:31:19 +00009711}
9712
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009713SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9714 SDValue InVec = N->getOperand(0);
9715 SDValue InVal = N->getOperand(1);
9716 SDValue EltNo = N->getOperand(2);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009717 SDLoc dl(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00009718
Bob Wilson42603952010-05-19 23:42:58 +00009719 // If the inserted element is an UNDEF, just use the input vector.
9720 if (InVal.getOpcode() == ISD::UNDEF)
9721 return InVec;
9722
Nadav Rotemdb2f5482011-02-12 14:40:33 +00009723 EVT VT = InVec.getValueType();
9724
Owen Andersonb2c80da2011-02-25 21:41:48 +00009725 // If we can't generate a legal BUILD_VECTOR, exit
Nadav Rotemdb2f5482011-02-12 14:40:33 +00009726 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9727 return SDValue();
9728
Eli Friedmanb7910b72011-09-09 21:04:06 +00009729 // Check that we know which element is being inserted
9730 if (!isa<ConstantSDNode>(EltNo))
9731 return SDValue();
9732 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00009733
Andrea Di Biagiof99dd642014-06-09 16:54:41 +00009734 // Canonicalize insert_vector_elt dag nodes.
9735 // Example:
9736 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
9737 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
9738 //
9739 // Do this only if the child insert_vector node has one use; also
9740 // do this only if indices are both constants and Idx1 < Idx0.
9741 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
9742 && isa<ConstantSDNode>(InVec.getOperand(2))) {
9743 unsigned OtherElt =
9744 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
9745 if (Elt < OtherElt) {
9746 // Swap nodes.
9747 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
9748 InVec.getOperand(0), InVal, EltNo);
9749 AddToWorkList(NewOp.getNode());
9750 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
9751 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
9752 }
9753 }
9754
Eli Friedmanb7910b72011-09-09 21:04:06 +00009755 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9756 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
9757 // vector elements.
9758 SmallVector<SDValue, 8> Ops;
Quentin Colombet6bf4baa2013-07-30 00:24:09 +00009759 // Do not combine these two vectors if the output vector will not replace
9760 // the input vector.
9761 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
Eli Friedmanb7910b72011-09-09 21:04:06 +00009762 Ops.append(InVec.getNode()->op_begin(),
9763 InVec.getNode()->op_end());
9764 } else if (InVec.getOpcode() == ISD::UNDEF) {
9765 unsigned NElts = VT.getVectorNumElements();
9766 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9767 } else {
9768 return SDValue();
Nate Begeman8d6d4b92009-04-27 18:41:29 +00009769 }
Eli Friedmanb7910b72011-09-09 21:04:06 +00009770
9771 // Insert the element
9772 if (Elt < Ops.size()) {
9773 // All the operands of BUILD_VECTOR must have the same type;
9774 // we enforce that here.
9775 EVT OpVT = Ops[0].getValueType();
9776 if (InVal.getValueType() != OpVT)
9777 InVal = OpVT.bitsGT(InVal.getValueType()) ?
9778 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9779 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9780 Ops[Elt] = InVal;
9781 }
9782
9783 // Return the new vector
Craig Topper48d114b2014-04-26 18:35:24 +00009784 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
Chris Lattner5336a592006-03-19 01:27:56 +00009785}
9786
Michael J. Spencerf375d802014-05-29 01:42:45 +00009787SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
9788 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
9789 EVT ResultVT = EVE->getValueType(0);
9790 EVT VecEltVT = InVecVT.getVectorElementType();
9791 unsigned Align = OriginalLoad->getAlignment();
9792 unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
9793 VecEltVT.getTypeForEVT(*DAG.getContext()));
9794
9795 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
9796 return SDValue();
9797
9798 Align = NewAlign;
9799
9800 SDValue NewPtr = OriginalLoad->getBasePtr();
9801 SDValue Offset;
9802 EVT PtrType = NewPtr.getValueType();
9803 MachinePointerInfo MPI;
9804 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
9805 int Elt = ConstEltNo->getZExtValue();
9806 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
9807 if (TLI.isBigEndian())
9808 PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
9809 Offset = DAG.getConstant(PtrOff, PtrType);
9810 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
9811 } else {
9812 Offset = DAG.getNode(
9813 ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo,
9814 DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType()));
9815 if (TLI.isBigEndian())
9816 Offset = DAG.getNode(
9817 ISD::SUB, SDLoc(EVE), EltNo.getValueType(),
9818 DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset);
9819 MPI = OriginalLoad->getPointerInfo();
9820 }
9821 NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset);
9822
9823 // The replacement we need to do here is a little tricky: we need to
9824 // replace an extractelement of a load with a load.
9825 // Use ReplaceAllUsesOfValuesWith to do the replacement.
9826 // Note that this replacement assumes that the extractvalue is the only
9827 // use of the load; that's okay because we don't want to perform this
9828 // transformation in other cases anyway.
9829 SDValue Load;
9830 SDValue Chain;
9831 if (ResultVT.bitsGT(VecEltVT)) {
9832 // If the result type of vextract is wider than the load, then issue an
9833 // extending load instead.
9834 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, VecEltVT)
9835 ? ISD::ZEXTLOAD
9836 : ISD::EXTLOAD;
9837 Load = DAG.getExtLoad(ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(),
9838 NewPtr, MPI, VecEltVT, OriginalLoad->isVolatile(),
9839 OriginalLoad->isNonTemporal(), Align,
9840 OriginalLoad->getTBAAInfo());
9841 Chain = Load.getValue(1);
9842 } else {
9843 Load = DAG.getLoad(
9844 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
9845 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
9846 OriginalLoad->isInvariant(), Align, OriginalLoad->getTBAAInfo());
9847 Chain = Load.getValue(1);
9848 if (ResultVT.bitsLT(VecEltVT))
9849 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
9850 else
9851 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
9852 }
9853 WorkListRemover DeadNodes(*this);
9854 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
9855 SDValue To[] = { Load, Chain };
9856 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9857 // Since we're explicitly calling ReplaceAllUses, add the new node to the
9858 // worklist explicitly as well.
9859 AddToWorkList(Load.getNode());
9860 AddUsersToWorkList(Load.getNode()); // Add users too
9861 // Make sure to revisit this node to clean it up; it will usually be dead.
9862 AddToWorkList(EVE);
9863 ++OpsNarrowed;
9864 return SDValue(EVE, 0);
9865}
9866
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009867SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
Mon P Wangca6d6de2009-01-17 00:07:25 +00009868 // (vextract (scalar_to_vector val, 0) -> val
9869 SDValue InVec = N->getOperand(0);
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009870 EVT VT = InVec.getValueType();
9871 EVT NVT = N->getValueType(0);
Mon P Wangca6d6de2009-01-17 00:07:25 +00009872
Duncan Sands6be291a2011-05-09 08:03:33 +00009873 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9874 // Check if the result type doesn't match the inserted element type. A
9875 // SCALAR_TO_VECTOR may truncate the inserted element and the
9876 // EXTRACT_VECTOR_ELT may widen the extracted vector.
9877 SDValue InOp = InVec.getOperand(0);
Duncan Sands6be291a2011-05-09 08:03:33 +00009878 if (InOp.getValueType() != NVT) {
9879 assert(InOp.getValueType().isInteger() && NVT.isInteger());
Andrew Trickef9de2a2013-05-25 02:42:55 +00009880 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
Duncan Sands6be291a2011-05-09 08:03:33 +00009881 }
9882 return InOp;
9883 }
Evan Cheng1120279a2008-05-13 08:35:03 +00009884
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009885 SDValue EltNo = N->getOperand(1);
9886 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9887
9888 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9889 // We only perform this optimization before the op legalization phase because
Nadav Rotem841c9a82012-09-20 08:53:31 +00009890 // we may introduce new vector instructions which are not backed by TD
9891 // patterns. For example on AVX, extracting elements from a wide vector
Hal Finkel02807592014-03-31 11:43:19 +00009892 // without using extract_subvector. However, if we can find an underlying
9893 // scalar value, then we can always use that.
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009894 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
Hal Finkel02807592014-03-31 11:43:19 +00009895 && ConstEltNo) {
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009896 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9897 int NumElem = VT.getVectorNumElements();
9898 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9899 // Find the new index to extract from.
9900 int OrigElt = SVOp->getMaskElt(Elt);
9901
9902 // Extracting an undef index is undef.
9903 if (OrigElt == -1)
9904 return DAG.getUNDEF(NVT);
9905
9906 // Select the right vector half to extract from.
Hal Finkel02807592014-03-31 11:43:19 +00009907 SDValue SVInVec;
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009908 if (OrigElt < NumElem) {
Hal Finkel02807592014-03-31 11:43:19 +00009909 SVInVec = InVec->getOperand(0);
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009910 } else {
Hal Finkel02807592014-03-31 11:43:19 +00009911 SVInVec = InVec->getOperand(1);
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009912 OrigElt -= NumElem;
9913 }
9914
Hal Finkel02807592014-03-31 11:43:19 +00009915 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
9916 SDValue InOp = SVInVec.getOperand(OrigElt);
9917 if (InOp.getValueType() != NVT) {
9918 assert(InOp.getValueType().isInteger() && NVT.isInteger());
9919 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
9920 }
9921
9922 return InOp;
9923 }
9924
9925 // FIXME: We should handle recursing on other vector shuffles and
9926 // scalar_to_vector here as well.
9927
9928 if (!LegalOperations) {
9929 EVT IndexTy = TLI.getVectorIdxTy();
9930 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
9931 SVInVec, DAG.getConstant(OrigElt, IndexTy));
9932 }
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009933 }
9934
Michael J. Spencerf375d802014-05-29 01:42:45 +00009935 bool BCNumEltsChanged = false;
9936 EVT ExtVT = VT.getVectorElementType();
9937 EVT LVT = ExtVT;
9938
9939 // If the result of load has to be truncated, then it's not necessarily
9940 // profitable.
9941 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
9942 return SDValue();
9943
9944 if (InVec.getOpcode() == ISD::BITCAST) {
9945 // Don't duplicate a load with other uses.
9946 if (!InVec.hasOneUse())
9947 return SDValue();
9948
9949 EVT BCVT = InVec.getOperand(0).getValueType();
9950 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
9951 return SDValue();
9952 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
9953 BCNumEltsChanged = true;
9954 InVec = InVec.getOperand(0);
9955 ExtVT = BCVT.getVectorElementType();
9956 }
9957
9958 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
9959 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
9960 ISD::isNormalLoad(InVec.getNode())) {
9961 SDValue Index = N->getOperand(1);
9962 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
9963 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
9964 OrigLoad);
9965 }
9966
Evan Cheng1120279a2008-05-13 08:35:03 +00009967 // Perform only after legalization to ensure build_vector / vector_shuffle
9968 // optimizations have already been done.
Duncan Sandsdc2dac12008-11-24 14:53:14 +00009969 if (!LegalOperations) return SDValue();
Evan Cheng1120279a2008-05-13 08:35:03 +00009970
Mon P Wangca6d6de2009-01-17 00:07:25 +00009971 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
9972 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
9973 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
Evan Cheng0de312d2007-10-06 08:19:55 +00009974
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009975 if (ConstEltNo) {
Eric Christopherfcc9e682010-11-03 09:36:40 +00009976 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Evan Cheng0de312d2007-10-06 08:19:55 +00009977
Craig Topperc0196b12014-04-14 00:51:57 +00009978 LoadSDNode *LN0 = nullptr;
9979 const ShuffleVectorSDNode *SVN = nullptr;
Bill Wendling27d9dd42009-01-30 23:36:47 +00009980 if (ISD::isNormalLoad(InVec.getNode())) {
Evan Cheng1120279a2008-05-13 08:35:03 +00009981 LN0 = cast<LoadSDNode>(InVec);
Bill Wendling27d9dd42009-01-30 23:36:47 +00009982 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
Owen Anderson53aa7a92009-08-10 22:56:29 +00009983 InVec.getOperand(0).getValueType() == ExtVT &&
Bill Wendling27d9dd42009-01-30 23:36:47 +00009984 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
Eli Friedmane96286c2011-12-26 22:49:32 +00009985 // Don't duplicate a load with other uses.
9986 if (!InVec.hasOneUse())
9987 return SDValue();
9988
Evan Cheng1120279a2008-05-13 08:35:03 +00009989 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
Nate Begeman5f829d82009-04-29 05:20:52 +00009990 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
Evan Cheng1120279a2008-05-13 08:35:03 +00009991 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
9992 // =>
9993 // (load $addr+1*size)
Scott Michelcf0da6c2009-02-17 22:15:04 +00009994
Eli Friedmane96286c2011-12-26 22:49:32 +00009995 // Don't duplicate a load with other uses.
9996 if (!InVec.hasOneUse())
9997 return SDValue();
9998
Mon P Wangb5eb7202008-12-11 00:26:16 +00009999 // If the bit convert changed the number of elements, it is unsafe
10000 // to examine the mask.
10001 if (BCNumEltsChanged)
10002 return SDValue();
Nate Begeman5f829d82009-04-29 05:20:52 +000010003
10004 // Select the input vector, guarding against out of range extract vector.
10005 unsigned NumElems = VT.getVectorNumElements();
Eric Christopherfcc9e682010-11-03 09:36:40 +000010006 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
Nate Begeman5f829d82009-04-29 05:20:52 +000010007 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
10008
Eli Friedmane96286c2011-12-26 22:49:32 +000010009 if (InVec.getOpcode() == ISD::BITCAST) {
10010 // Don't duplicate a load with other uses.
10011 if (!InVec.hasOneUse())
10012 return SDValue();
10013
Evan Cheng1120279a2008-05-13 08:35:03 +000010014 InVec = InVec.getOperand(0);
Eli Friedmane96286c2011-12-26 22:49:32 +000010015 }
Gabor Greiff304a7a2008-08-28 21:40:38 +000010016 if (ISD::isNormalLoad(InVec.getNode())) {
Evan Cheng1120279a2008-05-13 08:35:03 +000010017 LN0 = cast<LoadSDNode>(InVec);
Ted Kremenekd87bd772010-04-08 18:49:30 +000010018 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
Michael J. Spencerf375d802014-05-29 01:42:45 +000010019 EltNo = DAG.getConstant(Elt, EltNo.getValueType());
Evan Cheng0de312d2007-10-06 08:19:55 +000010020 }
10021 }
Bill Wendling27d9dd42009-01-30 23:36:47 +000010022
Eli Friedmane96286c2011-12-26 22:49:32 +000010023 // Make sure we found a non-volatile load and the extractelement is
10024 // the only use.
Nadav Rotem8a7beb82011-05-11 14:40:50 +000010025 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010026 return SDValue();
Evan Cheng1120279a2008-05-13 08:35:03 +000010027
Eric Christopherc6418b12010-11-03 20:44:42 +000010028 // If Idx was -1 above, Elt is going to be -1, so just return undef.
10029 if (Elt == -1)
Eli Friedmancbd3ba92011-07-25 22:25:42 +000010030 return DAG.getUNDEF(LVT);
Eric Christopherc6418b12010-11-03 20:44:42 +000010031
Michael J. Spencerf375d802014-05-29 01:42:45 +000010032 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
Evan Cheng0de312d2007-10-06 08:19:55 +000010033 }
Bill Wendling27d9dd42009-01-30 23:36:47 +000010034
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010035 return SDValue();
Evan Cheng0de312d2007-10-06 08:19:55 +000010036}
Evan Cheng0de312d2007-10-06 08:19:55 +000010037
Michael Liao6d106b72012-10-23 23:06:52 +000010038// Simplify (build_vec (ext )) to (bitcast (build_vec ))
10039SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
10040 // We perform this optimization post type-legalization because
10041 // the type-legalizer often scalarizes integer-promoted vectors.
10042 // Performing this optimization before may create bit-casts which
10043 // will be type-legalized to complex code sequences.
10044 // We perform this optimization only before the operation legalizer because we
10045 // may introduce illegal operations.
10046 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
10047 return SDValue();
10048
Dan Gohmana8665142007-06-25 16:23:39 +000010049 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +000010050 SDLoc dl(N);
Owen Anderson53aa7a92009-08-10 22:56:29 +000010051 EVT VT = N->getValueType(0);
Nadav Rotema62368c2012-07-15 08:38:23 +000010052
Nadav Rotembf6568b2011-10-29 21:23:04 +000010053 // Check to see if this is a BUILD_VECTOR of a bunch of values
10054 // which come from any_extend or zero_extend nodes. If so, we can create
10055 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
Nadav Rotemf3103612011-10-31 20:08:25 +000010056 // optimizations. We do not handle sign-extend because we can't fill the sign
10057 // using shuffles.
Nadav Rotembf6568b2011-10-29 21:23:04 +000010058 EVT SourceType = MVT::Other;
Craig Topper02cb0fb2012-01-17 09:09:48 +000010059 bool AllAnyExt = true;
Nadav Rotema62368c2012-07-15 08:38:23 +000010060
Craig Topper02cb0fb2012-01-17 09:09:48 +000010061 for (unsigned i = 0; i != NumInScalars; ++i) {
Nadav Rotembf6568b2011-10-29 21:23:04 +000010062 SDValue In = N->getOperand(i);
10063 // Ignore undef inputs.
10064 if (In.getOpcode() == ISD::UNDEF) continue;
10065
10066 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
10067 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
10068
Nadav Rotemf3103612011-10-31 20:08:25 +000010069 // Abort if the element is not an extension.
Nadav Rotembf6568b2011-10-29 21:23:04 +000010070 if (!ZeroExt && !AnyExt) {
Nadav Rotemf3103612011-10-31 20:08:25 +000010071 SourceType = MVT::Other;
Nadav Rotembf6568b2011-10-29 21:23:04 +000010072 break;
10073 }
10074
10075 // The input is a ZeroExt or AnyExt. Check the original type.
10076 EVT InTy = In.getOperand(0).getValueType();
10077
10078 // Check that all of the widened source types are the same.
10079 if (SourceType == MVT::Other)
Nadav Rotemf3103612011-10-31 20:08:25 +000010080 // First time.
Nadav Rotembf6568b2011-10-29 21:23:04 +000010081 SourceType = InTy;
10082 else if (InTy != SourceType) {
10083 // Multiple income types. Abort.
Nadav Rotemf3103612011-10-31 20:08:25 +000010084 SourceType = MVT::Other;
Nadav Rotembf6568b2011-10-29 21:23:04 +000010085 break;
10086 }
10087
10088 // Check if all of the extends are ANY_EXTENDs.
Craig Topper02cb0fb2012-01-17 09:09:48 +000010089 AllAnyExt &= AnyExt;
Nadav Rotembf6568b2011-10-29 21:23:04 +000010090 }
10091
Nadav Rotemf3103612011-10-31 20:08:25 +000010092 // In order to have valid types, all of the inputs must be extended from the
10093 // same source type and all of the inputs must be any or zero extend.
10094 // Scalar sizes must be a power of two.
Michael Liao6d106b72012-10-23 23:06:52 +000010095 EVT OutScalarTy = VT.getScalarType();
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010096 bool ValidTypes = SourceType != MVT::Other &&
Nadav Rotemf3103612011-10-31 20:08:25 +000010097 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10098 isPowerOf2_32(SourceType.getSizeInBits());
10099
Nadav Rotem6fd1d322012-03-15 08:49:06 +000010100 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10101 // turn into a single shuffle instruction.
Michael Liao6d106b72012-10-23 23:06:52 +000010102 if (!ValidTypes)
10103 return SDValue();
Nadav Rotembf6568b2011-10-29 21:23:04 +000010104
Michael Liao6d106b72012-10-23 23:06:52 +000010105 bool isLE = TLI.isLittleEndian();
10106 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10107 assert(ElemRatio > 1 && "Invalid element size ratio");
10108 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10109 DAG.getConstant(0, SourceType);
Nadav Rotembf6568b2011-10-29 21:23:04 +000010110
Michael Liao6d106b72012-10-23 23:06:52 +000010111 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10112 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
Nadav Rotembf6568b2011-10-29 21:23:04 +000010113
Michael Liao6d106b72012-10-23 23:06:52 +000010114 // Populate the new build_vector
Jakub Staszaka6addc22012-10-24 00:38:25 +000010115 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
Michael Liao6d106b72012-10-23 23:06:52 +000010116 SDValue Cast = N->getOperand(i);
10117 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10118 Cast.getOpcode() == ISD::ZERO_EXTEND ||
10119 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10120 SDValue In;
10121 if (Cast.getOpcode() == ISD::UNDEF)
10122 In = DAG.getUNDEF(SourceType);
10123 else
10124 In = Cast->getOperand(0);
10125 unsigned Index = isLE ? (i * ElemRatio) :
10126 (i * ElemRatio + (ElemRatio - 1));
Nadav Rotembf6568b2011-10-29 21:23:04 +000010127
Michael Liao6d106b72012-10-23 23:06:52 +000010128 assert(Index < Ops.size() && "Invalid index");
10129 Ops[Index] = In;
Nadav Rotembf6568b2011-10-29 21:23:04 +000010130 }
Chris Lattner5336a592006-03-19 01:27:56 +000010131
Michael Liao6d106b72012-10-23 23:06:52 +000010132 // The type of the new BUILD_VECTOR node.
10133 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10134 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10135 "Invalid vector size");
10136 // Check if the new vector type is legal.
10137 if (!isTypeLegal(VecVT)) return SDValue();
10138
10139 // Make the new BUILD_VECTOR.
Craig Topper48d114b2014-04-26 18:35:24 +000010140 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
Michael Liao6d106b72012-10-23 23:06:52 +000010141
10142 // The new BUILD_VECTOR node has the potential to be further optimized.
10143 AddToWorkList(BV.getNode());
10144 // Bitcast to the desired type.
10145 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10146}
10147
Michael Liao59229792012-10-24 04:14:18 +000010148SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10149 EVT VT = N->getValueType(0);
10150
10151 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +000010152 SDLoc dl(N);
Michael Liao59229792012-10-24 04:14:18 +000010153
10154 EVT SrcVT = MVT::Other;
10155 unsigned Opcode = ISD::DELETED_NODE;
10156 unsigned NumDefs = 0;
10157
10158 for (unsigned i = 0; i != NumInScalars; ++i) {
10159 SDValue In = N->getOperand(i);
10160 unsigned Opc = In.getOpcode();
10161
10162 if (Opc == ISD::UNDEF)
10163 continue;
10164
10165 // If all scalar values are floats and converted from integers.
10166 if (Opcode == ISD::DELETED_NODE &&
10167 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10168 Opcode = Opc;
Michael Liao59229792012-10-24 04:14:18 +000010169 }
Tom Stellard567f8862013-01-02 22:13:01 +000010170
Michael Liao59229792012-10-24 04:14:18 +000010171 if (Opc != Opcode)
10172 return SDValue();
10173
10174 EVT InVT = In.getOperand(0).getValueType();
10175
10176 // If all scalar values are typed differently, bail out. It's chosen to
10177 // simplify BUILD_VECTOR of integer types.
10178 if (SrcVT == MVT::Other)
10179 SrcVT = InVT;
10180 if (SrcVT != InVT)
10181 return SDValue();
10182 NumDefs++;
10183 }
10184
10185 // If the vector has just one element defined, it's not worth to fold it into
10186 // a vectorized one.
10187 if (NumDefs < 2)
10188 return SDValue();
10189
10190 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10191 && "Should only handle conversion from integer to float.");
10192 assert(SrcVT != MVT::Other && "Cannot determine source type!");
10193
10194 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
Tom Stellard567f8862013-01-02 22:13:01 +000010195
10196 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10197 return SDValue();
10198
Michael Liao59229792012-10-24 04:14:18 +000010199 SmallVector<SDValue, 8> Opnds;
10200 for (unsigned i = 0; i != NumInScalars; ++i) {
10201 SDValue In = N->getOperand(i);
10202
10203 if (In.getOpcode() == ISD::UNDEF)
10204 Opnds.push_back(DAG.getUNDEF(SrcVT));
10205 else
10206 Opnds.push_back(In.getOperand(0));
10207 }
Craig Topper48d114b2014-04-26 18:35:24 +000010208 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
Michael Liao59229792012-10-24 04:14:18 +000010209 AddToWorkList(BV.getNode());
10210
10211 return DAG.getNode(Opcode, dl, VT, BV);
10212}
10213
Michael Liao6d106b72012-10-23 23:06:52 +000010214SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10215 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +000010216 SDLoc dl(N);
Michael Liao6d106b72012-10-23 23:06:52 +000010217 EVT VT = N->getValueType(0);
10218
10219 // A vector built entirely of undefs is undef.
10220 if (ISD::allOperandsUndef(N))
10221 return DAG.getUNDEF(VT);
10222
10223 SDValue V = reduceBuildVecExtToExtBuildVec(N);
10224 if (V.getNode())
10225 return V;
10226
Michael Liao59229792012-10-24 04:14:18 +000010227 V = reduceBuildVecConvertToConvertBuildVec(N);
10228 if (V.getNode())
10229 return V;
10230
Dan Gohmana8665142007-06-25 16:23:39 +000010231 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10232 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10233 // at most two distinct vectors, turn this into a shuffle node.
Duncan Sands3fb2fc62012-03-19 15:35:44 +000010234
10235 // May only combine to shuffle after legalize if shuffle is legal.
10236 if (LegalOperations &&
10237 !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
10238 return SDValue();
10239
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010240 SDValue VecIn1, VecIn2;
Chris Lattnerc9992542006-03-28 20:28:38 +000010241 for (unsigned i = 0; i != NumInScalars; ++i) {
10242 // Ignore undef inputs.
10243 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +000010244
Dan Gohmana8665142007-06-25 16:23:39 +000010245 // If this input is something other than a EXTRACT_VECTOR_ELT with a
Chris Lattnerc9992542006-03-28 20:28:38 +000010246 // constant index, bail out.
Dan Gohmana8665142007-06-25 16:23:39 +000010247 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
Chris Lattnerc9992542006-03-28 20:28:38 +000010248 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
Craig Topperc0196b12014-04-14 00:51:57 +000010249 VecIn1 = VecIn2 = SDValue(nullptr, 0);
Chris Lattnerc9992542006-03-28 20:28:38 +000010250 break;
10251 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010252
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010253 // We allow up to two distinct input vectors.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010254 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
Chris Lattnerc9992542006-03-28 20:28:38 +000010255 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10256 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +000010257
Craig Topperc0196b12014-04-14 00:51:57 +000010258 if (!VecIn1.getNode()) {
Chris Lattnerc9992542006-03-28 20:28:38 +000010259 VecIn1 = ExtractedFromVec;
Craig Topperc0196b12014-04-14 00:51:57 +000010260 } else if (!VecIn2.getNode()) {
Chris Lattnerc9992542006-03-28 20:28:38 +000010261 VecIn2 = ExtractedFromVec;
10262 } else {
10263 // Too many inputs.
Craig Topperc0196b12014-04-14 00:51:57 +000010264 VecIn1 = VecIn2 = SDValue(nullptr, 0);
Chris Lattnerc9992542006-03-28 20:28:38 +000010265 break;
10266 }
10267 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010268
Jim Grosbach2eb60fd2014-04-29 22:41:50 +000010269 // If everything is good, we can make a shuffle operation.
Gabor Greiff304a7a2008-08-28 21:40:38 +000010270 if (VecIn1.getNode()) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010271 SmallVector<int, 8> Mask;
Chris Lattnerc9992542006-03-28 20:28:38 +000010272 for (unsigned i = 0; i != NumInScalars; ++i) {
10273 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010274 Mask.push_back(-1);
Chris Lattnerc9992542006-03-28 20:28:38 +000010275 continue;
10276 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010277
Rafael Espindolab93db662009-04-24 12:40:33 +000010278 // If extracting from the first vector, just use the index directly.
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010279 SDValue Extract = N->getOperand(i);
Mon P Wang523c0852009-03-17 06:33:10 +000010280 SDValue ExtVal = Extract.getOperand(1);
Chris Lattnerc9992542006-03-28 20:28:38 +000010281 if (Extract.getOperand(0) == VecIn1) {
Nate Begeman5f829d82009-04-29 05:20:52 +000010282 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10283 if (ExtIndex > VT.getVectorNumElements())
10284 return SDValue();
Wesley Peck527da1b2010-11-23 03:31:01 +000010285
Nate Begeman5f829d82009-04-29 05:20:52 +000010286 Mask.push_back(ExtIndex);
Chris Lattnerc9992542006-03-28 20:28:38 +000010287 continue;
10288 }
10289
10290 // Otherwise, use InIdx + VecSize
Mon P Wang523c0852009-03-17 06:33:10 +000010291 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010292 Mask.push_back(Idx+NumInScalars);
Chris Lattnerc9992542006-03-28 20:28:38 +000010293 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010294
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010295 // We can't generate a shuffle node with mismatched input and output types.
10296 // Attempt to transform a single input vector to the correct type.
10297 if ((VT != VecIn1.getValueType())) {
10298 // We don't support shuffeling between TWO values of different types.
Craig Topperc0196b12014-04-14 00:51:57 +000010299 if (VecIn2.getNode())
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010300 return SDValue();
10301
10302 // We only support widening of vectors which are half the size of the
10303 // output registers. For example XMM->YMM widening on X86 with AVX.
10304 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10305 return SDValue();
10306
James Molloy1e5c6112012-09-10 14:01:21 +000010307 // If the input vector type has a different base type to the output
10308 // vector type, bail out.
10309 if (VecIn1.getValueType().getVectorElementType() !=
10310 VT.getVectorElementType())
10311 return SDValue();
10312
Stepan Dyatkovskiy99120e02012-08-22 09:33:55 +000010313 // Widen the input vector by adding undef values.
Michael Liao6d106b72012-10-23 23:06:52 +000010314 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
Stepan Dyatkovskiy99120e02012-08-22 09:33:55 +000010315 VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010316 }
10317
10318 // If VecIn2 is unused then change it to undef.
10319 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10320
Nadav Rotem841c9a82012-09-20 08:53:31 +000010321 // Check that we were able to transform all incoming values to the same
10322 // type.
Nadav Rotem0c650642012-02-13 12:42:26 +000010323 if (VecIn2.getValueType() != VecIn1.getValueType() ||
10324 VecIn1.getValueType() != VT)
10325 return SDValue();
10326
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010327 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
Nadav Rotem0c650642012-02-13 12:42:26 +000010328 if (!isTypeLegal(VT))
Duncan Sandsdc2dac12008-11-24 14:53:14 +000010329 return SDValue();
10330
Dan Gohmana8665142007-06-25 16:23:39 +000010331 // Return the new VECTOR_SHUFFLE node.
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010332 SDValue Ops[2];
Chris Lattnerc24a1d32006-08-08 02:23:42 +000010333 Ops[0] = VecIn1;
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010334 Ops[1] = VecIn2;
Michael Liao6d106b72012-10-23 23:06:52 +000010335 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
Chris Lattnerc9992542006-03-28 20:28:38 +000010336 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010337
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010338 return SDValue();
Chris Lattnerc9992542006-03-28 20:28:38 +000010339}
10340
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010341SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
Dan Gohmana8665142007-06-25 16:23:39 +000010342 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10343 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
10344 // inputs come from at most two distinct vectors, turn this into a shuffle
10345 // node.
10346
10347 // If we only have one input vector, we don't need to do any concatenation.
Bill Wendling27d9dd42009-01-30 23:36:47 +000010348 if (N->getNumOperands() == 1)
Dan Gohmana8665142007-06-25 16:23:39 +000010349 return N->getOperand(0);
Dan Gohmana8665142007-06-25 16:23:39 +000010350
Nadav Rotem01892102012-07-14 21:30:27 +000010351 // Check if all of the operands are undefs.
Nadav Rotemd369d4b2013-10-25 06:41:18 +000010352 EVT VT = N->getValueType(0);
Nadav Rotema62368c2012-07-15 08:38:23 +000010353 if (ISD::allOperandsUndef(N))
Nadav Rotemd369d4b2013-10-25 06:41:18 +000010354 return DAG.getUNDEF(VT);
10355
10356 // Optimize concat_vectors where one of the vectors is undef.
10357 if (N->getNumOperands() == 2 &&
10358 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10359 SDValue In = N->getOperand(0);
Nadav Rotem6eee0802013-12-10 01:13:59 +000010360 assert(In.getValueType().isVector() && "Must concat vectors");
Nadav Rotemd369d4b2013-10-25 06:41:18 +000010361
10362 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10363 if (In->getOpcode() == ISD::BITCAST &&
10364 !In->getOperand(0)->getValueType(0).isVector()) {
10365 SDValue Scalar = In->getOperand(0);
10366 EVT SclTy = Scalar->getValueType(0);
10367
10368 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10369 return SDValue();
10370
10371 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10372 VT.getSizeInBits() / SclTy.getSizeInBits());
10373 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10374 return SDValue();
10375
10376 SDLoc dl = SDLoc(N);
10377 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10378 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10379 }
10380 }
Nadav Rotem01892102012-07-14 21:30:27 +000010381
Robert Lougher7d9084f2014-02-11 15:42:46 +000010382 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10383 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10384 if (N->getNumOperands() == 2 &&
10385 N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10386 N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10387 EVT VT = N->getValueType(0);
10388 SDValue N0 = N->getOperand(0);
10389 SDValue N1 = N->getOperand(1);
10390 SmallVector<SDValue, 8> Opnds;
10391 unsigned BuildVecNumElts = N0.getNumOperands();
10392
10393 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10394 Opnds.push_back(N0.getOperand(i));
10395 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10396 Opnds.push_back(N1.getOperand(i));
10397
Craig Topper48d114b2014-04-26 18:35:24 +000010398 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
Robert Lougher7d9084f2014-02-11 15:42:46 +000010399 }
10400
Nadav Roteme5a2dda2013-05-01 19:18:51 +000010401 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10402 // nodes often generate nop CONCAT_VECTOR nodes.
10403 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10404 // place the incoming vectors at the exact same location.
10405 SDValue SingleSource = SDValue();
10406 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10407
10408 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10409 SDValue Op = N->getOperand(i);
10410
10411 if (Op.getOpcode() == ISD::UNDEF)
10412 continue;
10413
10414 // Check if this is the identity extract:
10415 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10416 return SDValue();
10417
10418 // Find the single incoming vector for the extract_subvector.
10419 if (SingleSource.getNode()) {
10420 if (Op.getOperand(0) != SingleSource)
10421 return SDValue();
10422 } else {
10423 SingleSource = Op.getOperand(0);
Michael Kupersteinac868752013-05-06 08:06:13 +000010424
10425 // Check the source type is the same as the type of the result.
10426 // If not, this concat may extend the vector, so we can not
10427 // optimize it away.
10428 if (SingleSource.getValueType() != N->getValueType(0))
10429 return SDValue();
Nadav Roteme5a2dda2013-05-01 19:18:51 +000010430 }
10431
10432 unsigned IdentityIndex = i * PartNumElem;
10433 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10434 // The extract index must be constant.
10435 if (!CS)
10436 return SDValue();
Stephen Lincfe7f352013-07-08 00:37:03 +000010437
Nadav Roteme5a2dda2013-05-01 19:18:51 +000010438 // Check that we are reading from the identity index.
10439 if (CS->getZExtValue() != IdentityIndex)
10440 return SDValue();
10441 }
10442
10443 if (SingleSource.getNode())
10444 return SingleSource;
Stephen Lincfe7f352013-07-08 00:37:03 +000010445
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010446 return SDValue();
Dan Gohmana8665142007-06-25 16:23:39 +000010447}
10448
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +000010449SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10450 EVT NVT = N->getValueType(0);
10451 SDValue V = N->getOperand(0);
10452
Michael Liao7a442c802012-10-17 20:48:33 +000010453 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10454 // Combine:
10455 // (extract_subvec (concat V1, V2, ...), i)
10456 // Into:
10457 // Vi if possible
Jack Carterd4e96152013-10-17 01:34:33 +000010458 // Only operand 0 is checked as 'concat' assumes all inputs of the same
10459 // type.
Michael Liao2c235802012-10-19 03:17:00 +000010460 if (V->getOperand(0).getValueType() != NVT)
10461 return SDValue();
Michael Liao7a442c802012-10-17 20:48:33 +000010462 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10463 unsigned NumElems = NVT.getVectorNumElements();
10464 assert((Idx % NumElems) == 0 &&
10465 "IDX in concat is not a multiple of the result vector length.");
10466 return V->getOperand(Idx / NumElems);
10467 }
10468
Michael Liaobb05a1d2013-03-25 23:47:35 +000010469 // Skip bitcasting
10470 if (V->getOpcode() == ISD::BITCAST)
10471 V = V.getOperand(0);
10472
10473 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010474 SDLoc dl(N);
Michael Liaobb05a1d2013-03-25 23:47:35 +000010475 // Handle only simple case where vector being inserted and vector
10476 // being extracted are of same type, and are half size of larger vectors.
10477 EVT BigVT = V->getOperand(0).getValueType();
10478 EVT SmallVT = V->getOperand(1).getValueType();
10479 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10480 return SDValue();
10481
10482 // Only handle cases where both indexes are constants with the same type.
10483 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10484 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10485
10486 if (InsIdx && ExtIdx &&
10487 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10488 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10489 // Combine:
10490 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10491 // Into:
10492 // indices are equal or bit offsets are equal => V1
10493 // otherwise => (extract_subvec V1, ExtIdx)
10494 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10495 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10496 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10497 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10498 DAG.getNode(ISD::BITCAST, dl,
10499 N->getOperand(0).getValueType(),
10500 V->getOperand(0)), N->getOperand(1));
10501 }
10502 }
10503
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +000010504 return SDValue();
10505}
10506
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010507// Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10508static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10509 EVT VT = N->getValueType(0);
10510 unsigned NumElts = VT.getVectorNumElements();
10511
10512 SDValue N0 = N->getOperand(0);
10513 SDValue N1 = N->getOperand(1);
10514 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10515
10516 SmallVector<SDValue, 4> Ops;
10517 EVT ConcatVT = N0.getOperand(0).getValueType();
10518 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10519 unsigned NumConcats = NumElts / NumElemsPerConcat;
10520
10521 // Look at every vector that's inserted. We're looking for exact
10522 // subvector-sized copies from a concatenated vector
10523 for (unsigned I = 0; I != NumConcats; ++I) {
10524 // Make sure we're dealing with a copy.
10525 unsigned Begin = I * NumElemsPerConcat;
Hao Liubc601962013-05-13 02:07:05 +000010526 bool AllUndef = true, NoUndef = true;
10527 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10528 if (SVN->getMaskElt(J) >= 0)
10529 AllUndef = false;
10530 else
10531 NoUndef = false;
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010532 }
10533
Hao Liubc601962013-05-13 02:07:05 +000010534 if (NoUndef) {
Hao Liubc601962013-05-13 02:07:05 +000010535 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10536 return SDValue();
10537
10538 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10539 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10540 return SDValue();
10541
10542 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10543 if (FirstElt < N0.getNumOperands())
10544 Ops.push_back(N0.getOperand(FirstElt));
10545 else
10546 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10547
10548 } else if (AllUndef) {
10549 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10550 } else { // Mixed with general masks and undefs, can't do optimization.
10551 return SDValue();
10552 }
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010553 }
10554
Craig Topper48d114b2014-04-26 18:35:24 +000010555 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010556}
10557
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010558SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000010559 EVT VT = N->getValueType(0);
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010560 unsigned NumElts = VT.getVectorNumElements();
Chris Lattner39dcf1a2006-03-31 22:16:43 +000010561
Mon P Wang25f01062008-11-10 04:46:22 +000010562 SDValue N0 = N->getOperand(0);
Craig Topper279c77b2012-01-04 08:07:43 +000010563 SDValue N1 = N->getOperand(1);
Mon P Wang25f01062008-11-10 04:46:22 +000010564
Craig Topper5894fe42012-04-09 05:16:56 +000010565 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
Mon P Wang25f01062008-11-10 04:46:22 +000010566
Craig Topper279c77b2012-01-04 08:07:43 +000010567 // Canonicalize shuffle undef, undef -> undef
10568 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10569 return DAG.getUNDEF(VT);
10570
10571 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10572
10573 // Canonicalize shuffle v, v -> v, undef
10574 if (N0 == N1) {
10575 SmallVector<int, 8> NewMask;
10576 for (unsigned i = 0; i != NumElts; ++i) {
10577 int Idx = SVN->getMaskElt(i);
10578 if (Idx >= (int)NumElts) Idx -= NumElts;
10579 NewMask.push_back(Idx);
10580 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000010581 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
Craig Topper279c77b2012-01-04 08:07:43 +000010582 &NewMask[0]);
10583 }
10584
10585 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
10586 if (N0.getOpcode() == ISD::UNDEF) {
10587 SmallVector<int, 8> NewMask;
10588 for (unsigned i = 0; i != NumElts; ++i) {
10589 int Idx = SVN->getMaskElt(i);
Craig Toppere3ad4832012-04-09 05:55:33 +000010590 if (Idx >= 0) {
Craig Topper309dfef2013-08-08 07:38:55 +000010591 if (Idx >= (int)NumElts)
Craig Toppere3ad4832012-04-09 05:55:33 +000010592 Idx -= NumElts;
Craig Topper309dfef2013-08-08 07:38:55 +000010593 else
10594 Idx = -1; // remove reference to lhs
Craig Toppere3ad4832012-04-09 05:55:33 +000010595 }
10596 NewMask.push_back(Idx);
Craig Topper279c77b2012-01-04 08:07:43 +000010597 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000010598 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
Craig Topper279c77b2012-01-04 08:07:43 +000010599 &NewMask[0]);
10600 }
10601
10602 // Remove references to rhs if it is undef
10603 if (N1.getOpcode() == ISD::UNDEF) {
10604 bool Changed = false;
10605 SmallVector<int, 8> NewMask;
10606 for (unsigned i = 0; i != NumElts; ++i) {
10607 int Idx = SVN->getMaskElt(i);
10608 if (Idx >= (int)NumElts) {
10609 Idx = -1;
10610 Changed = true;
10611 }
10612 NewMask.push_back(Idx);
10613 }
10614 if (Changed)
Andrew Trickef9de2a2013-05-25 02:42:55 +000010615 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
Craig Topper279c77b2012-01-04 08:07:43 +000010616 }
Evan Cheng8472e0c2006-07-20 22:44:41 +000010617
Bob Wilsonf63da122010-10-28 17:06:14 +000010618 // If it is a splat, check if the argument vector is another splat or a
10619 // build_vector with all scalar elements the same.
Bob Wilsonf63da122010-10-28 17:06:14 +000010620 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
Gabor Greiff304a7a2008-08-28 21:40:38 +000010621 SDNode *V = N0.getNode();
Evan Cheng7c970b92006-07-21 08:25:53 +000010622
Dan Gohmana8665142007-06-25 16:23:39 +000010623 // If this is a bit convert that changes the element type of the vector but
Evan Chengf3ae00a2006-10-16 22:49:37 +000010624 // not the number of vector elements, look through it. Be careful not to
10625 // look though conversions that change things like v4f32 to v2f64.
Wesley Peck527da1b2010-11-23 03:31:01 +000010626 if (V->getOpcode() == ISD::BITCAST) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010627 SDValue ConvInput = V->getOperand(0);
Evan Chengb8ff2232008-07-22 20:42:56 +000010628 if (ConvInput.getValueType().isVector() &&
10629 ConvInput.getValueType().getVectorNumElements() == NumElts)
Gabor Greiff304a7a2008-08-28 21:40:38 +000010630 V = ConvInput.getNode();
Evan Chengf3ae00a2006-10-16 22:49:37 +000010631 }
10632
Dan Gohmana8665142007-06-25 16:23:39 +000010633 if (V->getOpcode() == ISD::BUILD_VECTOR) {
Bob Wilsonf63da122010-10-28 17:06:14 +000010634 assert(V->getNumOperands() == NumElts &&
10635 "BUILD_VECTOR has wrong number of operands");
10636 SDValue Base;
10637 bool AllSame = true;
10638 for (unsigned i = 0; i != NumElts; ++i) {
10639 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10640 Base = V->getOperand(i);
10641 break;
Evan Cheng7c970b92006-07-21 08:25:53 +000010642 }
Evan Cheng7c970b92006-07-21 08:25:53 +000010643 }
Bob Wilsonf63da122010-10-28 17:06:14 +000010644 // Splat of <u, u, u, u>, return <u, u, u, u>
10645 if (!Base.getNode())
10646 return N0;
10647 for (unsigned i = 0; i != NumElts; ++i) {
10648 if (V->getOperand(i) != Base) {
10649 AllSame = false;
10650 break;
10651 }
10652 }
10653 // Splat of <x, x, x, x>, return <x, x, x, x>
10654 if (AllSame)
10655 return N0;
Evan Cheng7c970b92006-07-21 08:25:53 +000010656 }
10657 }
Nadav Rotemb0783502012-04-01 19:31:22 +000010658
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010659 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10660 Level < AfterLegalizeVectorOps &&
10661 (N1.getOpcode() == ISD::UNDEF ||
10662 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10663 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10664 SDValue V = partitionShuffleOfConcats(N, DAG);
10665
10666 if (V.getNode())
10667 return V;
10668 }
10669
Nadav Rotemb0783502012-04-01 19:31:22 +000010670 // If this shuffle node is simply a swizzle of another shuffle node,
Nadav Rotem71d07ae2012-04-07 21:19:08 +000010671 // and it reverses the swizzle of the previous shuffle then we can
10672 // optimize shuffle(shuffle(x, undef), undef) -> x.
Nadav Rotemb0783502012-04-01 19:31:22 +000010673 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10674 N1.getOpcode() == ISD::UNDEF) {
10675
Nadav Rotemb0783502012-04-01 19:31:22 +000010676 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10677
Nadav Rotem71d07ae2012-04-07 21:19:08 +000010678 // Shuffle nodes can only reverse shuffles with a single non-undef value.
10679 if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
10680 return SDValue();
10681
Craig Topper5894fe42012-04-09 05:16:56 +000010682 // The incoming shuffle must be of the same type as the result of the
10683 // current shuffle.
10684 assert(OtherSV->getOperand(0).getValueType() == VT &&
10685 "Shuffle types don't match");
Nadav Rotemb0783502012-04-01 19:31:22 +000010686
Andrea Di Biagiod261e982014-07-08 15:22:29 +000010687 SmallVector<int, 4> Mask;
10688 // Compute the combined shuffle mask.
Nadav Rotemb0783502012-04-01 19:31:22 +000010689 for (unsigned i = 0; i != NumElts; ++i) {
10690 int Idx = SVN->getMaskElt(i);
Craig Topper5894fe42012-04-09 05:16:56 +000010691 assert(Idx < (int)NumElts && "Index references undef operand");
Nadav Rotemb0783502012-04-01 19:31:22 +000010692 // Next, this index comes from the first value, which is the incoming
10693 // shuffle. Adopt the incoming index.
10694 if (Idx >= 0)
10695 Idx = OtherSV->getMaskElt(Idx);
Andrea Di Biagiod261e982014-07-08 15:22:29 +000010696 Mask.push_back(Idx);
Nadav Rotemb0783502012-04-01 19:31:22 +000010697 }
Nadav Rotem71d07ae2012-04-07 21:19:08 +000010698
Andrea Di Biagiod261e982014-07-08 15:22:29 +000010699 bool IsIdentityMask = true;
10700 for (unsigned i = 0; i != NumElts && IsIdentityMask; ++i) {
10701 // Skip Undefs.
10702 if (Mask[i] < 0)
10703 continue;
10704
10705 // The combined shuffle must map each index to itself.
10706 IsIdentityMask = (unsigned)Mask[i] == i;
10707 }
10708
10709 if (IsIdentityMask)
10710 // optimize shuffle(shuffle(x, undef), undef) -> x.
10711 return OtherSV->getOperand(0);
10712
10713 // It may still be beneficial to combine the two shuffles if the
10714 // resulting shuffle is legal.
10715 // shuffle(shuffle(x, undef, M1), undef, M2) -> shuffle(x, undef, M3).
10716 if (TLI.isShuffleMaskLegal(Mask, VT))
10717 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0), N1,
10718 &Mask[0]);
Nadav Rotemb0783502012-04-01 19:31:22 +000010719 }
10720
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010721 return SDValue();
Chris Lattner39dcf1a2006-03-31 22:16:43 +000010722}
10723
Manman Ren413a6cb2014-01-31 01:10:35 +000010724SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
10725 SDValue N0 = N->getOperand(0);
10726 SDValue N2 = N->getOperand(2);
10727
10728 // If the input vector is a concatenation, and the insert replaces
10729 // one of the halves, we can optimize into a single concat_vectors.
10730 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10731 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
10732 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
10733 EVT VT = N->getValueType(0);
10734
10735 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10736 // (concat_vectors Z, Y)
10737 if (InsIdx == 0)
10738 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10739 N->getOperand(1), N0.getOperand(1));
10740
10741 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10742 // (concat_vectors X, Z)
10743 if (InsIdx == VT.getVectorNumElements()/2)
10744 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10745 N0.getOperand(0), N->getOperand(1));
10746 }
10747
10748 return SDValue();
10749}
10750
Evan Chenga320abc2006-04-20 08:56:16 +000010751/// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
Dan Gohmana8665142007-06-25 16:23:39 +000010752/// an AND to a vector_shuffle with the destination vector and a zero vector.
10753/// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
Evan Chenga320abc2006-04-20 08:56:16 +000010754/// vector_shuffle V, Zero, <0, 4, 2, 4>
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010755SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000010756 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +000010757 SDLoc dl(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010758 SDValue LHS = N->getOperand(0);
10759 SDValue RHS = N->getOperand(1);
Dan Gohmana8665142007-06-25 16:23:39 +000010760 if (N->getOpcode() == ISD::AND) {
Wesley Peck527da1b2010-11-23 03:31:01 +000010761 if (RHS.getOpcode() == ISD::BITCAST)
Evan Chenga320abc2006-04-20 08:56:16 +000010762 RHS = RHS.getOperand(0);
Dan Gohmana8665142007-06-25 16:23:39 +000010763 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010764 SmallVector<int, 8> Indices;
10765 unsigned NumElts = RHS.getNumOperands();
Evan Chenga320abc2006-04-20 08:56:16 +000010766 for (unsigned i = 0; i != NumElts; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010767 SDValue Elt = RHS.getOperand(i);
Evan Chenga320abc2006-04-20 08:56:16 +000010768 if (!isa<ConstantSDNode>(Elt))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010769 return SDValue();
Craig Toppere5893f62012-04-09 05:59:53 +000010770
10771 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010772 Indices.push_back(i);
Evan Chenga320abc2006-04-20 08:56:16 +000010773 else if (cast<ConstantSDNode>(Elt)->isNullValue())
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010774 Indices.push_back(NumElts);
Evan Chenga320abc2006-04-20 08:56:16 +000010775 else
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010776 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000010777 }
10778
10779 // Let's see if the target supports this vector_shuffle.
Owen Anderson53aa7a92009-08-10 22:56:29 +000010780 EVT RVT = RHS.getValueType();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010781 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010782 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000010783
Dan Gohmana8665142007-06-25 16:23:39 +000010784 // Return the new VECTOR_SHUFFLE node.
Dan Gohman08c0a952009-09-23 21:02:20 +000010785 EVT EltVT = RVT.getVectorElementType();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010786 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
Dan Gohman08c0a952009-09-23 21:02:20 +000010787 DAG.getConstant(0, EltVT));
Craig Topper48d114b2014-04-26 18:35:24 +000010788 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
Wesley Peck527da1b2010-11-23 03:31:01 +000010789 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010790 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
Wesley Peck527da1b2010-11-23 03:31:01 +000010791 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
Evan Chenga320abc2006-04-20 08:56:16 +000010792 }
10793 }
Bill Wendling31b50992009-01-30 23:59:18 +000010794
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010795 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000010796}
10797
Dan Gohmana8665142007-06-25 16:23:39 +000010798/// SimplifyVBinOp - Visit a binary vector operation, like ADD.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010799SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
Bob Wilson54081442010-12-17 23:06:49 +000010800 assert(N->getValueType(0).isVector() &&
10801 "SimplifyVBinOp only works on vectors!");
Dan Gohmana8665142007-06-25 16:23:39 +000010802
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010803 SDValue LHS = N->getOperand(0);
10804 SDValue RHS = N->getOperand(1);
10805 SDValue Shuffle = XformToShuffleWithZero(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +000010806 if (Shuffle.getNode()) return Shuffle;
Evan Chenga320abc2006-04-20 08:56:16 +000010807
Dan Gohmana8665142007-06-25 16:23:39 +000010808 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
Chris Lattner0442a182006-04-02 03:25:57 +000010809 // this operation.
Scott Michelcf0da6c2009-02-17 22:15:04 +000010810 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
Dan Gohmana8665142007-06-25 16:23:39 +000010811 RHS.getOpcode() == ISD::BUILD_VECTOR) {
Juergen Ributzka73844052014-01-13 20:51:35 +000010812 // Check if both vectors are constants. If not bail out.
Andrea Di Biagiod7c03ec2014-01-15 19:51:32 +000010813 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
10814 cast<BuildVectorSDNode>(RHS)->isConstant()))
Juergen Ributzka73844052014-01-13 20:51:35 +000010815 return SDValue();
10816
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010817 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +000010818 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010819 SDValue LHSOp = LHS.getOperand(i);
10820 SDValue RHSOp = RHS.getOperand(i);
Bill Wendling31b50992009-01-30 23:59:18 +000010821
Evan Cheng64d28462006-05-31 06:08:35 +000010822 // Can't fold divide by zero.
Dan Gohmana8665142007-06-25 16:23:39 +000010823 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
10824 N->getOpcode() == ISD::FDIV) {
Evan Cheng64d28462006-05-31 06:08:35 +000010825 if ((RHSOp.getOpcode() == ISD::Constant &&
Gabor Greiff304a7a2008-08-28 21:40:38 +000010826 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
Evan Cheng64d28462006-05-31 06:08:35 +000010827 (RHSOp.getOpcode() == ISD::ConstantFP &&
Gabor Greiff304a7a2008-08-28 21:40:38 +000010828 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
Evan Cheng64d28462006-05-31 06:08:35 +000010829 break;
10830 }
Bill Wendling31b50992009-01-30 23:59:18 +000010831
Bob Wilson54081442010-12-17 23:06:49 +000010832 EVT VT = LHSOp.getValueType();
Bob Wilson68156192011-10-18 17:34:47 +000010833 EVT RVT = RHSOp.getValueType();
10834 if (RVT != VT) {
10835 // Integer BUILD_VECTOR operands may have types larger than the element
10836 // size (e.g., when the element type is not legal). Prior to type
10837 // legalization, the types may not match between the two BUILD_VECTORS.
10838 // Truncate one of the operands to make them match.
10839 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010840 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
Bob Wilson68156192011-10-18 17:34:47 +000010841 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010842 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
Bob Wilson68156192011-10-18 17:34:47 +000010843 VT = RVT;
10844 }
10845 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000010846 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
Evan Cheng48f0de92010-05-18 00:03:40 +000010847 LHSOp, RHSOp);
10848 if (FoldOp.getOpcode() != ISD::UNDEF &&
10849 FoldOp.getOpcode() != ISD::Constant &&
10850 FoldOp.getOpcode() != ISD::ConstantFP)
10851 break;
10852 Ops.push_back(FoldOp);
10853 AddToWorkList(FoldOp.getNode());
Chris Lattner0442a182006-04-02 03:25:57 +000010854 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010855
Bob Wilson54081442010-12-17 23:06:49 +000010856 if (Ops.size() == LHS.getNumOperands())
Craig Topper48d114b2014-04-26 18:35:24 +000010857 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
Chris Lattner0442a182006-04-02 03:25:57 +000010858 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010859
Andrea Di Biagio446a5272014-05-30 23:17:53 +000010860 // Type legalization might introduce new shuffles in the DAG.
10861 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
10862 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
10863 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
10864 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
10865 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
10866 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
10867 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
10868 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
10869
10870 if (SVN0->getMask().equals(SVN1->getMask())) {
10871 EVT VT = N->getValueType(0);
10872 SDValue UndefVector = LHS.getOperand(1);
10873 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
10874 LHS.getOperand(0), RHS.getOperand(0));
10875 AddUsersToWorkList(N);
10876 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
10877 &SVN0->getMask()[0]);
10878 }
10879 }
10880
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010881 return SDValue();
Chris Lattner0442a182006-04-02 03:25:57 +000010882}
10883
Craig Topper82384612012-09-11 01:45:21 +000010884/// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
10885SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
Craig Topper82384612012-09-11 01:45:21 +000010886 assert(N->getValueType(0).isVector() &&
10887 "SimplifyVUnaryOp only works on vectors!");
10888
10889 SDValue N0 = N->getOperand(0);
10890
10891 if (N0.getOpcode() != ISD::BUILD_VECTOR)
10892 return SDValue();
10893
10894 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
10895 SmallVector<SDValue, 8> Ops;
10896 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
10897 SDValue Op = N0.getOperand(i);
10898 if (Op.getOpcode() != ISD::UNDEF &&
10899 Op.getOpcode() != ISD::ConstantFP)
10900 break;
10901 EVT EltVT = Op.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +000010902 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
Craig Topper82384612012-09-11 01:45:21 +000010903 if (FoldOp.getOpcode() != ISD::UNDEF &&
10904 FoldOp.getOpcode() != ISD::ConstantFP)
10905 break;
10906 Ops.push_back(FoldOp);
10907 AddToWorkList(FoldOp.getNode());
10908 }
10909
10910 if (Ops.size() != N0.getNumOperands())
10911 return SDValue();
10912
Craig Topper48d114b2014-04-26 18:35:24 +000010913 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
Craig Topper82384612012-09-11 01:45:21 +000010914}
10915
Andrew Trickef9de2a2013-05-25 02:42:55 +000010916SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
Bill Wendling31b50992009-01-30 23:59:18 +000010917 SDValue N1, SDValue N2){
Nate Begeman2042aa52005-10-08 00:29:44 +000010918 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
Scott Michelcf0da6c2009-02-17 22:15:04 +000010919
Bill Wendling31b50992009-01-30 23:59:18 +000010920 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
Nate Begeman2042aa52005-10-08 00:29:44 +000010921 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Bill Wendling31b50992009-01-30 23:59:18 +000010922
Nate Begeman2042aa52005-10-08 00:29:44 +000010923 // If we got a simplified select_cc node back from SimplifySelectCC, then
10924 // break it down into a new SETCC node, and a new SELECT node, and then return
10925 // the SELECT node, since we were called with a SELECT node.
Gabor Greiff304a7a2008-08-28 21:40:38 +000010926 if (SCC.getNode()) {
Nate Begeman2042aa52005-10-08 00:29:44 +000010927 // Check to see if we got a select_cc back (to turn into setcc/select).
10928 // Otherwise, just return whatever node we got back, like fabs.
10929 if (SCC.getOpcode() == ISD::SELECT_CC) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010930 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000010931 N0.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +000010932 SCC.getOperand(0), SCC.getOperand(1),
Bill Wendling31b50992009-01-30 23:59:18 +000010933 SCC.getOperand(4));
Gabor Greiff304a7a2008-08-28 21:40:38 +000010934 AddToWorkList(SETCC.getNode());
Matt Arsenaultd2f03322013-06-14 22:04:37 +000010935 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
10936 SCC.getOperand(2), SCC.getOperand(3), SETCC);
Nate Begeman2042aa52005-10-08 00:29:44 +000010937 }
Bill Wendling31b50992009-01-30 23:59:18 +000010938
Nate Begeman2042aa52005-10-08 00:29:44 +000010939 return SCC;
10940 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010941 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +000010942}
10943
Chris Lattner6c14c352005-10-18 06:04:22 +000010944/// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
10945/// are the two values being selected between, see if we can simplify the
Chris Lattner8f872d22006-05-27 00:43:02 +000010946/// select. Callers of this should assume that TheSelect is deleted if this
10947/// returns true. As such, they should return the appropriate thing (e.g. the
10948/// node) back to the top-level of the DAG combiner loop to avoid it being
10949/// looked at.
Scott Michelcf0da6c2009-02-17 22:15:04 +000010950bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010951 SDValue RHS) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000010952
Nadav Rotema49a02a2011-02-11 19:57:47 +000010953 // Cannot simplify select with vector condition
10954 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
10955
Chris Lattner6c14c352005-10-18 06:04:22 +000010956 // If this is a select from two identical things, try to pull the operation
10957 // through the select.
Chris Lattner254c4452010-09-21 15:46:59 +000010958 if (LHS.getOpcode() != RHS.getOpcode() ||
10959 !LHS.hasOneUse() || !RHS.hasOneUse())
10960 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000010961
Chris Lattner254c4452010-09-21 15:46:59 +000010962 // If this is a load and the token chain is identical, replace the select
10963 // of two loads with a load through a select of the address to load from.
10964 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
10965 // constants have been dropped into the constant pool.
10966 if (LHS.getOpcode() == ISD::LOAD) {
10967 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
10968 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
Wesley Peck527da1b2010-11-23 03:31:01 +000010969
Chris Lattner254c4452010-09-21 15:46:59 +000010970 // Token chains must be identical.
10971 if (LHS.getOperand(0) != RHS.getOperand(0) ||
Duncan Sands8651e9c2008-06-13 19:07:40 +000010972 // Do not let this transformation reduce the number of volatile loads.
Chris Lattner254c4452010-09-21 15:46:59 +000010973 LLD->isVolatile() || RLD->isVolatile() ||
10974 // If this is an EXTLOAD, the VT's must match.
10975 LLD->getMemoryVT() != RLD->getMemoryVT() ||
Duncan Sands12f3b3b2010-11-18 20:05:18 +000010976 // If this is an EXTLOAD, the kind of extension must match.
10977 (LLD->getExtensionType() != RLD->getExtensionType() &&
10978 // The only exception is if one of the extensions is anyext.
10979 LLD->getExtensionType() != ISD::EXTLOAD &&
10980 RLD->getExtensionType() != ISD::EXTLOAD) ||
Dan Gohmanba8735d2009-10-31 14:14:04 +000010981 // FIXME: this discards src value information. This is
10982 // over-conservative. It would be beneficial to be able to remember
Mon P Wangec57c812010-01-11 20:12:49 +000010983 // both potential memory locations. Since we are discarding
10984 // src value info, don't do the transformation if the memory
10985 // locations are not in the default address space.
Chris Lattner254c4452010-09-21 15:46:59 +000010986 LLD->getPointerInfo().getAddrSpace() != 0 ||
Pete Cooper10a3ae72013-02-12 03:14:50 +000010987 RLD->getPointerInfo().getAddrSpace() != 0 ||
10988 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
10989 LLD->getBasePtr().getValueType()))
Chris Lattner254c4452010-09-21 15:46:59 +000010990 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000010991
Chris Lattnere3267522010-09-21 15:58:55 +000010992 // Check that the select condition doesn't reach either load. If so,
10993 // folding this will induce a cycle into the DAG. If not, this is safe to
10994 // xform, so create a select of the addresses.
Chris Lattner254c4452010-09-21 15:46:59 +000010995 SDValue Addr;
10996 if (TheSelect->getOpcode() == ISD::SELECT) {
Chris Lattnere3267522010-09-21 15:58:55 +000010997 SDNode *CondNode = TheSelect->getOperand(0).getNode();
10998 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
10999 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
11000 return false;
Nadav Rotemd5f88592012-10-18 18:06:48 +000011001 // The loads must not depend on one another.
11002 if (LLD->isPredecessorOf(RLD) ||
11003 RLD->isPredecessorOf(LLD))
11004 return false;
Matt Arsenaultd2f03322013-06-14 22:04:37 +000011005 Addr = DAG.getSelect(SDLoc(TheSelect),
11006 LLD->getBasePtr().getValueType(),
11007 TheSelect->getOperand(0), LLD->getBasePtr(),
11008 RLD->getBasePtr());
Chris Lattner254c4452010-09-21 15:46:59 +000011009 } else { // Otherwise SELECT_CC
Chris Lattnere3267522010-09-21 15:58:55 +000011010 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
11011 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
11012
11013 if ((LLD->hasAnyUseOfValue(1) &&
11014 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
Chris Lattner1cc25e82012-03-27 16:27:21 +000011015 (RLD->hasAnyUseOfValue(1) &&
11016 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
Chris Lattnere3267522010-09-21 15:58:55 +000011017 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000011018
Andrew Trickef9de2a2013-05-25 02:42:55 +000011019 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
Chris Lattnere3267522010-09-21 15:58:55 +000011020 LLD->getBasePtr().getValueType(),
11021 TheSelect->getOperand(0),
11022 TheSelect->getOperand(1),
11023 LLD->getBasePtr(), RLD->getBasePtr(),
11024 TheSelect->getOperand(4));
Chris Lattner254c4452010-09-21 15:46:59 +000011025 }
11026
Chris Lattnere3267522010-09-21 15:58:55 +000011027 SDValue Load;
11028 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
11029 Load = DAG.getLoad(TheSelect->getValueType(0),
Andrew Trickef9de2a2013-05-25 02:42:55 +000011030 SDLoc(TheSelect),
Richard Sandiford39c1ce42013-10-28 11:17:59 +000011031 // FIXME: Discards pointer and TBAA info.
Chris Lattnere3267522010-09-21 15:58:55 +000011032 LLD->getChain(), Addr, MachinePointerInfo(),
11033 LLD->isVolatile(), LLD->isNonTemporal(),
Pete Cooper82cd9e82011-11-08 18:42:53 +000011034 LLD->isInvariant(), LLD->getAlignment());
Chris Lattnere3267522010-09-21 15:58:55 +000011035 } else {
Duncan Sandsc92331b2010-11-18 21:16:28 +000011036 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
11037 RLD->getExtensionType() : LLD->getExtensionType(),
Andrew Trickef9de2a2013-05-25 02:42:55 +000011038 SDLoc(TheSelect),
Stuart Hastings81c43062011-02-16 16:23:55 +000011039 TheSelect->getValueType(0),
Richard Sandiford39c1ce42013-10-28 11:17:59 +000011040 // FIXME: Discards pointer and TBAA info.
Chris Lattnere3267522010-09-21 15:58:55 +000011041 LLD->getChain(), Addr, MachinePointerInfo(),
11042 LLD->getMemoryVT(), LLD->isVolatile(),
11043 LLD->isNonTemporal(), LLD->getAlignment());
Chris Lattner6c14c352005-10-18 06:04:22 +000011044 }
Chris Lattnere3267522010-09-21 15:58:55 +000011045
11046 // Users of the select now use the result of the load.
11047 CombineTo(TheSelect, Load);
11048
11049 // Users of the old loads now use the new load's chain. We know the
11050 // old-load value is dead now.
11051 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
11052 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
11053 return true;
Chris Lattner6c14c352005-10-18 06:04:22 +000011054 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011055
Chris Lattner6c14c352005-10-18 06:04:22 +000011056 return false;
11057}
11058
Chris Lattner43d63772009-03-11 05:08:08 +000011059/// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
11060/// where 'cond' is the comparison specified by CC.
Andrew Trickef9de2a2013-05-25 02:42:55 +000011061SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011062 SDValue N2, SDValue N3,
11063 ISD::CondCode CC, bool NotExtCompare) {
Chris Lattner43d63772009-03-11 05:08:08 +000011064 // (x ? y : y) -> y.
11065 if (N2 == N3) return N2;
Wesley Peck527da1b2010-11-23 03:31:01 +000011066
Owen Anderson53aa7a92009-08-10 22:56:29 +000011067 EVT VT = N2.getValueType();
Gabor Greiff304a7a2008-08-28 21:40:38 +000011068 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
11069 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
11070 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000011071
11072 // Determine if the condition we're dealing with is constant
Matt Arsenault758659232013-05-18 00:21:46 +000011073 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
Dale Johannesenf1163e92009-02-03 00:47:48 +000011074 N0, N1, CC, DL, false);
Gabor Greiff304a7a2008-08-28 21:40:38 +000011075 if (SCC.getNode()) AddToWorkList(SCC.getNode());
11076 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000011077
11078 // fold select_cc true, x, y -> x
Dan Gohmanb72127a2008-03-13 22:13:53 +000011079 if (SCCC && !SCCC->isNullValue())
Nate Begeman2042aa52005-10-08 00:29:44 +000011080 return N2;
11081 // fold select_cc false, x, y -> y
Dan Gohmanb72127a2008-03-13 22:13:53 +000011082 if (SCCC && SCCC->isNullValue())
Nate Begeman2042aa52005-10-08 00:29:44 +000011083 return N3;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011084
Nate Begeman2042aa52005-10-08 00:29:44 +000011085 // Check to see if we can simplify the select into an fabs node
11086 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
11087 // Allow either -0.0 or 0.0
Dale Johannesen2cfcf702007-08-25 22:10:57 +000011088 if (CFP->getValueAPF().isZero()) {
Nate Begeman2042aa52005-10-08 00:29:44 +000011089 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
11090 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
11091 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
11092 N2 == N3.getOperand(0))
Bill Wendling31b50992009-01-30 23:59:18 +000011093 return DAG.getNode(ISD::FABS, DL, VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011094
Nate Begeman2042aa52005-10-08 00:29:44 +000011095 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
11096 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
11097 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
11098 N2.getOperand(0) == N3)
Bill Wendling31b50992009-01-30 23:59:18 +000011099 return DAG.getNode(ISD::FABS, DL, VT, N3);
Nate Begeman2042aa52005-10-08 00:29:44 +000011100 }
11101 }
Wesley Peck527da1b2010-11-23 03:31:01 +000011102
Chris Lattner43d63772009-03-11 05:08:08 +000011103 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
11104 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
11105 // in it. This is a win when the constant is not otherwise available because
11106 // it replaces two constant pool loads with one. We only do this if the FP
11107 // type is known to be legal, because if it isn't, then we are before legalize
11108 // types an we want the other legalization to happen first (e.g. to avoid
Mon P Wangc8671562009-03-14 00:25:19 +000011109 // messing with soft float) and if the ConstantFP is not legal, because if
11110 // it is legal, we may not need to store the FP constant in a constant pool.
Chris Lattner43d63772009-03-11 05:08:08 +000011111 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
11112 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
11113 if (TLI.isTypeLegal(N2.getValueType()) &&
Mon P Wangc8671562009-03-14 00:25:19 +000011114 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
Tim Northover863a7892014-04-16 09:03:09 +000011115 TargetLowering::Legal &&
11116 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
11117 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
Chris Lattner43d63772009-03-11 05:08:08 +000011118 // If both constants have multiple uses, then we won't need to do an
11119 // extra load, they are likely around in registers for other users.
11120 (TV->hasOneUse() || FV->hasOneUse())) {
11121 Constant *Elts[] = {
11122 const_cast<ConstantFP*>(FV->getConstantFPValue()),
11123 const_cast<ConstantFP*>(TV->getConstantFPValue())
11124 };
Chris Lattner229907c2011-07-18 04:54:35 +000011125 Type *FPTy = Elts[0]->getType();
Micah Villmowcdfe20b2012-10-08 16:38:25 +000011126 const DataLayout &TD = *TLI.getDataLayout();
Wesley Peck527da1b2010-11-23 03:31:01 +000011127
Chris Lattner43d63772009-03-11 05:08:08 +000011128 // Create a ConstantArray of the two constants.
Jay Foad83be3612011-06-22 09:24:39 +000011129 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
Chris Lattner43d63772009-03-11 05:08:08 +000011130 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
11131 TD.getPrefTypeAlignment(FPTy));
Evan Cheng1fb8aed2009-03-13 07:51:59 +000011132 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
Chris Lattner43d63772009-03-11 05:08:08 +000011133
11134 // Get the offsets to the 0 and 1 element of the array so that we can
11135 // select between them.
11136 SDValue Zero = DAG.getIntPtrConstant(0);
Duncan Sandsaf9eaa82009-05-09 07:06:46 +000011137 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
Chris Lattner43d63772009-03-11 05:08:08 +000011138 SDValue One = DAG.getIntPtrConstant(EltSize);
Wesley Peck527da1b2010-11-23 03:31:01 +000011139
Chris Lattner43d63772009-03-11 05:08:08 +000011140 SDValue Cond = DAG.getSetCC(DL,
Matt Arsenault758659232013-05-18 00:21:46 +000011141 getSetCCResultType(N0.getValueType()),
Chris Lattner43d63772009-03-11 05:08:08 +000011142 N0, N1, CC);
Dan Gohmane83e1b22011-09-22 23:01:29 +000011143 AddToWorkList(Cond.getNode());
Matt Arsenaultd2f03322013-06-14 22:04:37 +000011144 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
11145 Cond, One, Zero);
Dan Gohmane83e1b22011-09-22 23:01:29 +000011146 AddToWorkList(CstOffset.getNode());
Tom Stellard838e2342013-08-26 15:06:10 +000011147 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
Chris Lattner43d63772009-03-11 05:08:08 +000011148 CstOffset);
Dan Gohmane83e1b22011-09-22 23:01:29 +000011149 AddToWorkList(CPIdx.getNode());
Chris Lattner43d63772009-03-11 05:08:08 +000011150 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
Chris Lattnera35499e2010-09-21 07:32:19 +000011151 MachinePointerInfo::getConstantPool(), false,
Pete Cooper82cd9e82011-11-08 18:42:53 +000011152 false, false, Alignment);
Chris Lattner43d63772009-03-11 05:08:08 +000011153
11154 }
Wesley Peck527da1b2010-11-23 03:31:01 +000011155 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011156
Nate Begeman2042aa52005-10-08 00:29:44 +000011157 // Check to see if we can perform the "gzip trick", transforming
Bill Wendling31b50992009-01-30 23:59:18 +000011158 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
Chris Lattnerc8cd62d2006-09-20 06:41:35 +000011159 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
Dan Gohmanb72127a2008-03-13 22:13:53 +000011160 (N1C->isNullValue() || // (a < 0) ? b : 0
11161 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
Owen Anderson53aa7a92009-08-10 22:56:29 +000011162 EVT XType = N0.getValueType();
11163 EVT AType = N2.getValueType();
Duncan Sands11dd4242008-06-08 20:54:56 +000011164 if (XType.bitsGE(AType)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +000011165 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
Nate Begeman6828ed92005-10-10 21:26:48 +000011166 // single-bit constant.
Dan Gohmanb72127a2008-03-13 22:13:53 +000011167 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11168 unsigned ShCtV = N2C->getAPIntValue().logBase2();
Duncan Sands13237ac2008-06-06 12:08:01 +000011169 ShCtV = XType.getSizeInBits()-ShCtV-1;
Owen Andersonb2c80da2011-02-25 21:41:48 +000011170 SDValue ShCt = DAG.getConstant(ShCtV,
11171 getShiftAmountTy(N0.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000011172 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000011173 XType, N0, ShCt);
Gabor Greiff304a7a2008-08-28 21:40:38 +000011174 AddToWorkList(Shift.getNode());
Bill Wendling31b50992009-01-30 23:59:18 +000011175
Duncan Sands11dd4242008-06-08 20:54:56 +000011176 if (XType.bitsGT(AType)) {
Bill Wendling3b585af2009-01-31 03:12:48 +000011177 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
Gabor Greiff304a7a2008-08-28 21:40:38 +000011178 AddToWorkList(Shift.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000011179 }
Bill Wendling31b50992009-01-30 23:59:18 +000011180
11181 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
Nate Begeman2042aa52005-10-08 00:29:44 +000011182 }
Bill Wendling31b50992009-01-30 23:59:18 +000011183
Andrew Trickef9de2a2013-05-25 02:42:55 +000011184 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000011185 XType, N0,
11186 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000011187 getShiftAmountTy(N0.getValueType())));
Gabor Greiff304a7a2008-08-28 21:40:38 +000011188 AddToWorkList(Shift.getNode());
Bill Wendling31b50992009-01-30 23:59:18 +000011189
Duncan Sands11dd4242008-06-08 20:54:56 +000011190 if (XType.bitsGT(AType)) {
Bill Wendling3b585af2009-01-31 03:12:48 +000011191 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
Gabor Greiff304a7a2008-08-28 21:40:38 +000011192 AddToWorkList(Shift.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000011193 }
Bill Wendling31b50992009-01-30 23:59:18 +000011194
11195 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
Nate Begeman2042aa52005-10-08 00:29:44 +000011196 }
11197 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011198
Owen Anderson3231d132010-09-22 22:58:22 +000011199 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11200 // where y is has a single bit set.
11201 // A plaintext description would be, we can turn the SELECT_CC into an AND
11202 // when the condition can be materialized as an all-ones register. Any
11203 // single bit-test can be materialized as an all-ones register with
11204 // shift-left and shift-right-arith.
11205 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11206 N0->getValueType(0) == VT &&
Wesley Peck527da1b2010-11-23 03:31:01 +000011207 N1C && N1C->isNullValue() &&
Owen Anderson3231d132010-09-22 22:58:22 +000011208 N2C && N2C->isNullValue()) {
11209 SDValue AndLHS = N0->getOperand(0);
11210 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11211 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11212 // Shift the tested bit over the sign bit.
11213 APInt AndMask = ConstAndRHS->getAPIntValue();
11214 SDValue ShlAmt =
Owen Andersonb2c80da2011-02-25 21:41:48 +000011215 DAG.getConstant(AndMask.countLeadingZeros(),
11216 getShiftAmountTy(AndLHS.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000011217 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
Wesley Peck527da1b2010-11-23 03:31:01 +000011218
Owen Anderson3231d132010-09-22 22:58:22 +000011219 // Now arithmetic right shift it all the way over, so the result is either
11220 // all-ones, or zero.
11221 SDValue ShrAmt =
Owen Andersonb2c80da2011-02-25 21:41:48 +000011222 DAG.getConstant(AndMask.getBitWidth()-1,
11223 getShiftAmountTy(Shl.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000011224 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
Wesley Peck527da1b2010-11-23 03:31:01 +000011225
Owen Anderson3231d132010-09-22 22:58:22 +000011226 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11227 }
11228 }
11229
Nate Begeman6828ed92005-10-10 21:26:48 +000011230 // fold select C, 16, 0 -> shl C, 4
Dan Gohmanb72127a2008-03-13 22:13:53 +000011231 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
Duncan Sandsf2641e12011-09-06 19:07:46 +000011232 TLI.getBooleanContents(N0.getValueType().isVector()) ==
11233 TargetLowering::ZeroOrOneBooleanContent) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000011234
Chris Lattnera083ffc2007-04-11 06:50:51 +000011235 // If the caller doesn't want us to simplify this into a zext of a compare,
11236 // don't do it.
Dan Gohmanb72127a2008-03-13 22:13:53 +000011237 if (NotExtCompare && N2C->getAPIntValue() == 1)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011238 return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +000011239
Nate Begeman6828ed92005-10-10 21:26:48 +000011240 // Get a SetCC of the condition
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011241 // NOTE: Don't create a SETCC if it's not legal on this target.
11242 if (!LegalOperations ||
11243 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault758659232013-05-18 00:21:46 +000011244 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011245 SDValue Temp, SCC;
11246 // cast from setcc result type to select result type
11247 if (LegalTypes) {
Matt Arsenault758659232013-05-18 00:21:46 +000011248 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011249 N0, N1, CC);
11250 if (N2.getValueType().bitsLT(SCC.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +000011251 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011252 N2.getValueType());
11253 else
Andrew Trickef9de2a2013-05-25 02:42:55 +000011254 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011255 N2.getValueType(), SCC);
11256 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011257 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11258 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
Bill Wendling31b50992009-01-30 23:59:18 +000011259 N2.getValueType(), SCC);
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011260 }
11261
11262 AddToWorkList(SCC.getNode());
11263 AddToWorkList(Temp.getNode());
11264
11265 if (N2C->getAPIntValue() == 1)
11266 return Temp;
11267
11268 // shl setcc result by log2 n2c
Jack Carterd4e96152013-10-17 01:34:33 +000011269 return DAG.getNode(
11270 ISD::SHL, DL, N2.getValueType(), Temp,
11271 DAG.getConstant(N2C->getAPIntValue().logBase2(),
11272 getShiftAmountTy(Temp.getValueType())));
Nate Begemanabac6162006-02-18 02:40:58 +000011273 }
Nate Begeman6828ed92005-10-10 21:26:48 +000011274 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011275
Nate Begeman2042aa52005-10-08 00:29:44 +000011276 // Check to see if this is the equivalent of setcc
11277 // FIXME: Turn all of these into setcc if setcc if setcc is legal
11278 // otherwise, go ahead with the folds.
Dan Gohmanb72127a2008-03-13 22:13:53 +000011279 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000011280 EVT XType = N0.getValueType();
Duncan Sandsdc2dac12008-11-24 14:53:14 +000011281 if (!LegalOperations ||
Matt Arsenault758659232013-05-18 00:21:46 +000011282 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11283 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
Nate Begeman2042aa52005-10-08 00:29:44 +000011284 if (Res.getValueType() != VT)
Bill Wendling31b50992009-01-30 23:59:18 +000011285 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
Nate Begeman2042aa52005-10-08 00:29:44 +000011286 return Res;
11287 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011288
Bill Wendling31b50992009-01-30 23:59:18 +000011289 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
Scott Michelcf0da6c2009-02-17 22:15:04 +000011290 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +000011291 (!LegalOperations ||
Duncan Sandsb1bfff52008-06-14 17:48:34 +000011292 TLI.isOperationLegal(ISD::CTLZ, XType))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011293 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011294 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
Duncan Sands13237ac2008-06-06 12:08:01 +000011295 DAG.getConstant(Log2_32(XType.getSizeInBits()),
Owen Andersonb2c80da2011-02-25 21:41:48 +000011296 getShiftAmountTy(Ctlz.getValueType())));
Nate Begeman2042aa52005-10-08 00:29:44 +000011297 }
Bill Wendling31b50992009-01-30 23:59:18 +000011298 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
Scott Michelcf0da6c2009-02-17 22:15:04 +000011299 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011300 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000011301 XType, DAG.getConstant(0, XType), N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +000011302 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
Bill Wendling31b50992009-01-30 23:59:18 +000011303 return DAG.getNode(ISD::SRL, DL, XType,
Bill Wendlinga6c75ff2009-02-01 11:19:36 +000011304 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
Duncan Sands13237ac2008-06-06 12:08:01 +000011305 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000011306 getShiftAmountTy(XType)));
Nate Begeman2042aa52005-10-08 00:29:44 +000011307 }
Bill Wendling31b50992009-01-30 23:59:18 +000011308 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
Nate Begeman2042aa52005-10-08 00:29:44 +000011309 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011310 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
Bill Wendling31b50992009-01-30 23:59:18 +000011311 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000011312 getShiftAmountTy(N0.getValueType())));
Bill Wendling31b50992009-01-30 23:59:18 +000011313 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
Nate Begeman2042aa52005-10-08 00:29:44 +000011314 }
11315 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011316
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011317 // Check to see if this is an integer abs.
11318 // select_cc setg[te] X, 0, X, -X ->
11319 // select_cc setgt X, -1, X, -X ->
11320 // select_cc setl[te] X, 0, -X, X ->
11321 // select_cc setlt X, 1, -X, X ->
Nate Begeman2042aa52005-10-08 00:29:44 +000011322 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011323 if (N1C) {
Craig Topperc0196b12014-04-14 00:51:57 +000011324 ConstantSDNode *SubC = nullptr;
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011325 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11326 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11327 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11328 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11329 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11330 (N1C->isOne() && CC == ISD::SETLT)) &&
11331 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11332 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11333
Owen Anderson53aa7a92009-08-10 22:56:29 +000011334 EVT XType = N0.getValueType();
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011335 if (SubC && SubC->isNullValue() && XType.isInteger()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011336 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011337 N0,
11338 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000011339 getShiftAmountTy(N0.getValueType())));
Andrew Trickef9de2a2013-05-25 02:42:55 +000011340 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011341 XType, N0, Shift);
11342 AddToWorkList(Shift.getNode());
11343 AddToWorkList(Add.getNode());
11344 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
Nate Begeman2042aa52005-10-08 00:29:44 +000011345 }
11346 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011347
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011348 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +000011349}
11350
Evan Cheng92658d52007-02-08 22:13:59 +000011351/// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
Owen Anderson53aa7a92009-08-10 22:56:29 +000011352SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011353 SDValue N1, ISD::CondCode Cond,
Andrew Trickef9de2a2013-05-25 02:42:55 +000011354 SDLoc DL, bool foldBooleans) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000011355 TargetLowering::DAGCombinerInfo
Nadav Rotemb1dd5242012-12-27 06:47:41 +000011356 DagCombineInfo(DAG, Level, false, this);
Dale Johannesenf1163e92009-02-03 00:47:48 +000011357 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
Nate Begeman24a7eca2005-09-16 00:54:12 +000011358}
11359
Nate Begemanc6f067a2005-10-20 02:15:44 +000011360/// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
11361/// return a DAG expression to select that will generate the same value by
11362/// multiplying by a magic number. See:
11363/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011364SDValue DAGCombiner::BuildSDIV(SDNode *N) {
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011365 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11366 if (!C)
11367 return SDValue();
Benjamin Kramer4dae5982014-04-26 12:06:28 +000011368
11369 // Avoid division by zero.
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011370 if (!C->getAPIntValue())
Benjamin Kramer4dae5982014-04-26 12:06:28 +000011371 return SDValue();
11372
Andrew Lenharth0e57b2c2006-06-12 16:07:18 +000011373 std::vector<SDNode*> Built;
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011374 SDValue S =
11375 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000011376
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011377 for (SDNode *N : Built)
11378 AddToWorkList(N);
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000011379 return S;
Nate Begemanc6f067a2005-10-20 02:15:44 +000011380}
11381
Benjamin Kramer4dae5982014-04-26 12:06:28 +000011382/// BuildUDIV - Given an ISD::UDIV node expressing a divide by constant,
Nate Begemanc6f067a2005-10-20 02:15:44 +000011383/// return a DAG expression to select that will generate the same value by
11384/// multiplying by a magic number. See:
11385/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011386SDValue DAGCombiner::BuildUDIV(SDNode *N) {
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011387 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11388 if (!C)
11389 return SDValue();
Benjamin Kramer4dae5982014-04-26 12:06:28 +000011390
11391 // Avoid division by zero.
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011392 if (!C->getAPIntValue())
Benjamin Kramer4dae5982014-04-26 12:06:28 +000011393 return SDValue();
11394
Andrew Lenharth0e57b2c2006-06-12 16:07:18 +000011395 std::vector<SDNode*> Built;
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011396 SDValue S =
11397 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
Nate Begemanc6f067a2005-10-20 02:15:44 +000011398
Benjamin Kramerda4841b2014-04-26 23:09:49 +000011399 for (SDNode *N : Built)
11400 AddToWorkList(N);
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000011401 return S;
Nate Begemanc6f067a2005-10-20 02:15:44 +000011402}
11403
Nate Begeman18150d52009-09-25 06:05:26 +000011404/// FindBaseOffset - Return true if base is a frame index, which is known not
Eric Christopherd9e8eac2010-12-09 04:48:06 +000011405// to alias with anything but itself. Provides base object and offset as
11406// results.
Nate Begeman18150d52009-09-25 06:05:26 +000011407static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
Roman Divacky93383442012-09-05 22:15:49 +000011408 const GlobalValue *&GV, const void *&CV) {
Jim Laskey0463e082006-10-07 23:37:56 +000011409 // Assume it is a primitive operation.
Craig Topperc0196b12014-04-14 00:51:57 +000011410 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011411
Jim Laskey0463e082006-10-07 23:37:56 +000011412 // If it's an adding a simple constant then integrate the offset.
11413 if (Base.getOpcode() == ISD::ADD) {
11414 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11415 Base = Base.getOperand(0);
Dan Gohmaneffb8942008-09-12 16:56:44 +000011416 Offset += C->getZExtValue();
Jim Laskey0463e082006-10-07 23:37:56 +000011417 }
11418 }
Wesley Peck527da1b2010-11-23 03:31:01 +000011419
Nate Begeman18150d52009-09-25 06:05:26 +000011420 // Return the underlying GlobalValue, and update the Offset. Return false
11421 // for GlobalAddressSDNode since the same GlobalAddress may be represented
11422 // by multiple nodes with different offsets.
11423 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11424 GV = G->getGlobal();
11425 Offset += G->getOffset();
11426 return false;
11427 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011428
Nate Begeman18150d52009-09-25 06:05:26 +000011429 // Return the underlying Constant value, and update the Offset. Return false
11430 // for ConstantSDNodes since the same constant pool entry may be represented
11431 // by multiple nodes with different offsets.
11432 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
Roman Divacky93383442012-09-05 22:15:49 +000011433 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11434 : (const void *)C->getConstVal();
Nate Begeman18150d52009-09-25 06:05:26 +000011435 Offset += C->getOffset();
11436 return false;
11437 }
Jim Laskey0463e082006-10-07 23:37:56 +000011438 // If it's any of the following then it can't alias with anything but itself.
Nate Begeman18150d52009-09-25 06:05:26 +000011439 return isa<FrameIndexSDNode>(Base);
Jim Laskey0463e082006-10-07 23:37:56 +000011440}
11441
11442/// isAlias - Return true if there is any possibility that the two addresses
11443/// overlap.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011444bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
Jim Laskey0463e082006-10-07 23:37:56 +000011445 // If they are the same then they must be aliases.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011446 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011447
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011448 // If they are both volatile then they cannot be reordered.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011449 if (Op0->isVolatile() && Op1->isVolatile()) return true;
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011450
Jim Laskey0463e082006-10-07 23:37:56 +000011451 // Gather base node and offset information.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011452 SDValue Base1, Base2;
Jim Laskey0463e082006-10-07 23:37:56 +000011453 int64_t Offset1, Offset2;
Dan Gohmanbcaf6812010-04-15 01:51:59 +000011454 const GlobalValue *GV1, *GV2;
Roman Divacky93383442012-09-05 22:15:49 +000011455 const void *CV1, *CV2;
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011456 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
11457 Base1, Offset1, GV1, CV1);
11458 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
11459 Base2, Offset2, GV2, CV2);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011460
Nate Begeman18150d52009-09-25 06:05:26 +000011461 // If they have a same base address then check to see if they overlap.
11462 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011463 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11464 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011465
Owen Anderson272ff942010-09-20 20:39:59 +000011466 // It is possible for different frame indices to alias each other, mostly
11467 // when tail call optimization reuses return address slots for arguments.
11468 // To catch this case, look up the actual index of frame indices to compute
11469 // the real alias relationship.
11470 if (isFrameIndex1 && isFrameIndex2) {
11471 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11472 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11473 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011474 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11475 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
Owen Anderson272ff942010-09-20 20:39:59 +000011476 }
11477
Wesley Peck527da1b2010-11-23 03:31:01 +000011478 // Otherwise, if we know what the bases are, and they aren't identical, then
Owen Anderson272ff942010-09-20 20:39:59 +000011479 // we know they cannot alias.
Nate Begeman18150d52009-09-25 06:05:26 +000011480 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11481 return false;
Jim Laskeya15b0eb2006-10-18 12:29:57 +000011482
Nate Begeman879d8f12009-09-15 00:18:30 +000011483 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11484 // compared to the size and offset of the access, we may be able to prove they
11485 // do not alias. This check is conservative for now to catch cases created by
11486 // splitting vector types.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011487 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
11488 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
11489 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
11490 Op1->getMemoryVT().getSizeInBits() >> 3) &&
11491 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
11492 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
11493 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
Wesley Peck527da1b2010-11-23 03:31:01 +000011494
Nate Begeman879d8f12009-09-15 00:18:30 +000011495 // There is no overlap between these relatively aligned accesses of similar
11496 // size, return no alias.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011497 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
11498 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
Nate Begeman879d8f12009-09-15 00:18:30 +000011499 return false;
11500 }
Wesley Peck527da1b2010-11-23 03:31:01 +000011501
Hal Finkel5ef4dcc2013-08-29 03:29:55 +000011502 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11503 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +000011504#ifndef NDEBUG
11505 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11506 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11507 UseAA = false;
11508#endif
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011509 if (UseAA &&
11510 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
Jim Laskey55e4dca2006-10-18 19:08:31 +000011511 // Use alias analysis information.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011512 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
11513 Op1->getSrcValueOffset());
11514 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
11515 Op0->getSrcValueOffset() - MinOffset;
11516 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
11517 Op1->getSrcValueOffset() - MinOffset;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011518 AliasAnalysis::AliasResult AAResult =
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011519 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
11520 Overlap1,
11521 UseTBAA ? Op0->getTBAAInfo() : nullptr),
11522 AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
11523 Overlap2,
11524 UseTBAA ? Op1->getTBAAInfo() : nullptr));
Jim Laskey55e4dca2006-10-18 19:08:31 +000011525 if (AAResult == AliasAnalysis::NoAlias)
11526 return false;
11527 }
Jim Laskeya15b0eb2006-10-18 12:29:57 +000011528
11529 // Otherwise we have to assume they alias.
11530 return true;
Jim Laskey0463e082006-10-07 23:37:56 +000011531}
11532
Jim Laskey708d0db2006-10-04 16:53:27 +000011533/// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11534/// looking for aliasing nodes and adding them to the Aliases vector.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011535void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
Craig Topperb94011f2013-07-14 04:42:23 +000011536 SmallVectorImpl<SDValue> &Aliases) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011537 SmallVector<SDValue, 8> Chains; // List of chains to visit.
Nate Begeman879d8f12009-09-15 00:18:30 +000011538 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
Scott Michelcf0da6c2009-02-17 22:15:04 +000011539
Jim Laskeyd07be232006-09-25 16:29:54 +000011540 // Get alias information for node.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011541 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
Jim Laskeyd07be232006-09-25 16:29:54 +000011542
Jim Laskey708d0db2006-10-04 16:53:27 +000011543 // Starting off.
Jim Laskey6549d222006-10-05 15:07:25 +000011544 Chains.push_back(OriginalChain);
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011545 unsigned Depth = 0;
Wesley Peck527da1b2010-11-23 03:31:01 +000011546
Jim Laskey6549d222006-10-05 15:07:25 +000011547 // Look at each chain and determine if it is an alias. If so, add it to the
11548 // aliases list. If not, then continue up the chain looking for the next
Scott Michelcf0da6c2009-02-17 22:15:04 +000011549 // candidate.
Jim Laskey6549d222006-10-05 15:07:25 +000011550 while (!Chains.empty()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011551 SDValue Chain = Chains.back();
Jim Laskey6549d222006-10-05 15:07:25 +000011552 Chains.pop_back();
Wesley Peck527da1b2010-11-23 03:31:01 +000011553
11554 // For TokenFactor nodes, look at each operand and only continue up the
11555 // chain until we find two aliases. If we've seen two aliases, assume we'll
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011556 // find more and revert to original chain since the xform is unlikely to be
11557 // profitable.
Wesley Peck527da1b2010-11-23 03:31:01 +000011558 //
11559 // FIXME: The depth check could be made to return the last non-aliasing
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011560 // chain we found before we hit a tokenfactor rather than the original
11561 // chain.
11562 if (Depth > 6 || Aliases.size() == 2) {
11563 Aliases.clear();
11564 Aliases.push_back(OriginalChain);
Hal Finkel51a98382014-01-24 20:12:02 +000011565 return;
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011566 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011567
Nate Begeman879d8f12009-09-15 00:18:30 +000011568 // Don't bother if we've been before.
11569 if (!Visited.insert(Chain.getNode()))
11570 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011571
Jim Laskey6549d222006-10-05 15:07:25 +000011572 switch (Chain.getOpcode()) {
11573 case ISD::EntryToken:
11574 // Entry token is ideal chain operand, but handled in FindBetterChain.
11575 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011576
Jim Laskey6549d222006-10-05 15:07:25 +000011577 case ISD::LOAD:
11578 case ISD::STORE: {
11579 // Get alias information for Chain.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011580 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
11581 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
Scott Michelcf0da6c2009-02-17 22:15:04 +000011582
Jim Laskey6549d222006-10-05 15:07:25 +000011583 // If chain is alias then stop here.
11584 if (!(IsLoad && IsOpLoad) &&
Nick Lewyckyaad475b2014-04-15 07:22:52 +000011585 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
Jim Laskey6549d222006-10-05 15:07:25 +000011586 Aliases.push_back(Chain);
11587 } else {
11588 // Look further up the chain.
Scott Michelcf0da6c2009-02-17 22:15:04 +000011589 Chains.push_back(Chain.getOperand(0));
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011590 ++Depth;
Jim Laskeyd07be232006-09-25 16:29:54 +000011591 }
Jim Laskey6549d222006-10-05 15:07:25 +000011592 break;
11593 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011594
Jim Laskey6549d222006-10-05 15:07:25 +000011595 case ISD::TokenFactor:
Nate Begeman879d8f12009-09-15 00:18:30 +000011596 // We have to check each of the operands of the token factor for "small"
11597 // token factors, so we queue them up. Adding the operands to the queue
11598 // (stack) in reverse order maintains the original order and increases the
11599 // likelihood that getNode will find a matching token factor (CSE.)
11600 if (Chain.getNumOperands() > 16) {
11601 Aliases.push_back(Chain);
11602 break;
11603 }
Jim Laskey6549d222006-10-05 15:07:25 +000011604 for (unsigned n = Chain.getNumOperands(); n;)
11605 Chains.push_back(Chain.getOperand(--n));
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011606 ++Depth;
Jim Laskey6549d222006-10-05 15:07:25 +000011607 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011608
Jim Laskey6549d222006-10-05 15:07:25 +000011609 default:
11610 // For all other instructions we will just have to take what we can get.
11611 Aliases.push_back(Chain);
11612 break;
Jim Laskeyd07be232006-09-25 16:29:54 +000011613 }
11614 }
Hal Finkel51a98382014-01-24 20:12:02 +000011615
11616 // We need to be careful here to also search for aliases through the
11617 // value operand of a store, etc. Consider the following situation:
11618 // Token1 = ...
11619 // L1 = load Token1, %52
11620 // S1 = store Token1, L1, %51
11621 // L2 = load Token1, %52+8
11622 // S2 = store Token1, L2, %51+8
11623 // Token2 = Token(S1, S2)
11624 // L3 = load Token2, %53
11625 // S3 = store Token2, L3, %52
11626 // L4 = load Token2, %53+8
11627 // S4 = store Token2, L4, %52+8
11628 // If we search for aliases of S3 (which loads address %52), and we look
11629 // only through the chain, then we'll miss the trivial dependence on L1
11630 // (which also loads from %52). We then might change all loads and
11631 // stores to use Token1 as their chain operand, which could result in
11632 // copying %53 into %52 before copying %52 into %51 (which should
11633 // happen first).
11634 //
11635 // The problem is, however, that searching for such data dependencies
11636 // can become expensive, and the cost is not directly related to the
11637 // chain depth. Instead, we'll rule out such configurations here by
11638 // insisting that we've visited all chain users (except for users
11639 // of the original chain, which is not necessary). When doing this,
11640 // we need to look through nodes we don't care about (otherwise, things
11641 // like register copies will interfere with trivial cases).
11642
11643 SmallVector<const SDNode *, 16> Worklist;
11644 for (SmallPtrSet<SDNode *, 16>::iterator I = Visited.begin(),
11645 IE = Visited.end(); I != IE; ++I)
11646 if (*I != OriginalChain.getNode())
11647 Worklist.push_back(*I);
11648
11649 while (!Worklist.empty()) {
11650 const SDNode *M = Worklist.pop_back_val();
11651
11652 // We have already visited M, and want to make sure we've visited any uses
11653 // of M that we care about. For uses that we've not visisted, and don't
11654 // care about, queue them to the worklist.
11655
11656 for (SDNode::use_iterator UI = M->use_begin(),
11657 UIE = M->use_end(); UI != UIE; ++UI)
11658 if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11659 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11660 // We've not visited this use, and we care about it (it could have an
11661 // ordering dependency with the original node).
11662 Aliases.clear();
11663 Aliases.push_back(OriginalChain);
11664 return;
11665 }
11666
11667 // We've not visited this use, but we don't care about it. Mark it as
11668 // visited and enqueue it to the worklist.
11669 Worklist.push_back(*UI);
11670 }
11671 }
Jim Laskey708d0db2006-10-04 16:53:27 +000011672}
11673
11674/// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11675/// for a better chain (aliasing node.)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011676SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11677 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +000011678
Jim Laskey708d0db2006-10-04 16:53:27 +000011679 // Accumulate all the aliases to this node.
11680 GatherAllAliases(N, OldChain, Aliases);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011681
Dan Gohman4298df62011-05-17 22:20:36 +000011682 // If no operands then chain to entry token.
11683 if (Aliases.size() == 0)
Jim Laskey708d0db2006-10-04 16:53:27 +000011684 return DAG.getEntryNode();
Dan Gohman4298df62011-05-17 22:20:36 +000011685
11686 // If a single operand then chain to it. We don't need to revisit it.
11687 if (Aliases.size() == 1)
Jim Laskey708d0db2006-10-04 16:53:27 +000011688 return Aliases[0];
Wesley Peck527da1b2010-11-23 03:31:01 +000011689
Jim Laskey708d0db2006-10-04 16:53:27 +000011690 // Construct a custom tailored token factor.
Craig Topper48d114b2014-04-26 18:35:24 +000011691 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
Jim Laskeyd07be232006-09-25 16:29:54 +000011692}
11693
Nate Begeman21158fc2005-09-01 00:19:25 +000011694// SelectionDAG::Combine - This is the entry point for the file.
11695//
Bill Wendling084669a2009-04-29 00:15:41 +000011696void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
Bill Wendling026e5d72009-04-29 23:29:43 +000011697 CodeGenOpt::Level OptLevel) {
Nate Begeman21158fc2005-09-01 00:19:25 +000011698 /// run - This is the main entry point to this class.
11699 ///
Bill Wendling084669a2009-04-29 00:15:41 +000011700 DAGCombiner(*this, AA, OptLevel).Run(Level);
Nate Begeman21158fc2005-09-01 00:19:25 +000011701}