blob: 2e2bfee2bc284a9766a0b42a9fe3e94ffdb529df [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
19#define DEBUG_TYPE "dagcombine"
Nate Begeman21158fc2005-09-01 00:19:25 +000020#include "llvm/CodeGen/SelectionDAG.h"
Chris Lattner48fb92f2007-05-16 06:37:59 +000021#include "llvm/ADT/SmallPtrSet.h"
22#include "llvm/ADT/Statistic.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000023#include "llvm/Analysis/AliasAnalysis.h"
24#include "llvm/CodeGen/MachineFrameInfo.h"
25#include "llvm/CodeGen/MachineFunction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/DerivedTypes.h"
28#include "llvm/IR/Function.h"
29#include "llvm/IR/LLVMContext.h"
Jim Laskey5d19d592006-09-21 16:28:59 +000030#include "llvm/Support/CommandLine.h"
Chris Lattner48fb92f2007-05-16 06:37:59 +000031#include "llvm/Support/Debug.h"
Torok Edwinccb29cd2009-07-11 13:10:19 +000032#include "llvm/Support/ErrorHandling.h"
Chris Lattner48fb92f2007-05-16 06:37:59 +000033#include "llvm/Support/MathExtras.h"
Chris Lattner4dc3edd2009-08-23 06:35:02 +000034#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000035#include "llvm/Target/TargetLowering.h"
36#include "llvm/Target/TargetMachine.h"
37#include "llvm/Target/TargetOptions.h"
Quentin Colombetde0e0622013-10-11 18:29:42 +000038#include "llvm/Target/TargetRegisterInfo.h"
Hal Finkel5ef4dcc2013-08-29 03:29:55 +000039#include "llvm/Target/TargetSubtargetInfo.h"
Chris Lattnerbd39c1a2005-09-09 23:53:39 +000040#include <algorithm>
Nate Begeman21158fc2005-09-01 00:19:25 +000041using namespace llvm;
42
Chris Lattneraee775a2006-12-19 22:41:21 +000043STATISTIC(NodesCombined , "Number of dag nodes combined");
44STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
45STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
Evan Chenga9cda8a2009-05-28 00:35:15 +000046STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
Evan Chengd42641c2011-02-02 01:06:55 +000047STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int");
Quentin Colombetde0e0622013-10-11 18:29:42 +000048STATISTIC(SlicedLoads, "Number of load sliced");
Chris Lattneraee775a2006-12-19 22:41:21 +000049
Nate Begeman21158fc2005-09-01 00:19:25 +000050namespace {
Jim Laskey0463e082006-10-07 23:37:56 +000051 static cl::opt<bool>
Owen Anderson7b8d2ae2010-09-19 21:01:26 +000052 CombinerAA("combiner-alias-analysis", cl::Hidden,
Hal Finkel5fb07342014-01-25 17:32:37 +000053 cl::desc("Enable DAG combiner alias-analysis heuristics"));
Jim Laskeydf2ccc32006-10-12 15:22:24 +000054
Jim Laskey55e4dca2006-10-18 19:08:31 +000055 static cl::opt<bool>
56 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
Hal Finkel5fb07342014-01-25 17:32:37 +000057 cl::desc("Enable DAG combiner's use of IR alias analysis"));
Jim Laskey55e4dca2006-10-18 19:08:31 +000058
Hal Finkeldbebb522014-01-25 19:24:54 +000059 static cl::opt<bool>
Hal Finkel3b48d082014-04-12 01:26:00 +000060 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
Hal Finkeldbebb522014-01-25 19:24:54 +000061 cl::desc("Enable DAG combiner's use of TBAA"));
62
Hal Finkel9b2617a2014-01-25 17:32:39 +000063#ifndef NDEBUG
64 static cl::opt<std::string>
65 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
66 cl::desc("Only use DAG-combiner alias analysis in this"
67 " function"));
68#endif
69
Quentin Colombetde0e0622013-10-11 18:29:42 +000070 /// Hidden option to stress test load slicing, i.e., when this option
71 /// is enabled, load slicing bypasses most of its profitability guards.
72 static cl::opt<bool>
73 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
74 cl::desc("Bypass the profitability model of load "
75 "slicing"),
76 cl::init(false));
77
Jim Laskey6549d222006-10-05 15:07:25 +000078//------------------------------ DAGCombiner ---------------------------------//
79
Nick Lewycky02d5f772009-10-25 06:33:48 +000080 class DAGCombiner {
Nate Begeman21158fc2005-09-01 00:19:25 +000081 SelectionDAG &DAG;
Dan Gohman619ef482009-01-15 19:20:50 +000082 const TargetLowering &TLI;
Duncan Sandsdc2dac12008-11-24 14:53:14 +000083 CombineLevel Level;
Bill Wendling026e5d72009-04-29 23:29:43 +000084 CodeGenOpt::Level OptLevel;
Duncan Sandsdc2dac12008-11-24 14:53:14 +000085 bool LegalOperations;
86 bool LegalTypes;
Quentin Colombetde0e0622013-10-11 18:29:42 +000087 bool ForCodeSize;
Nate Begeman21158fc2005-09-01 00:19:25 +000088
89 // Worklist of all of the nodes that need to be simplified.
James Molloy67b6b112012-02-16 09:17:04 +000090 //
91 // This has the semantics that when adding to the worklist,
92 // the item added must be next to be processed. It should
93 // also only appear once. The naive approach to this takes
94 // linear time.
95 //
96 // To reduce the insert/remove time to logarithmic, we use
97 // a set and a vector to maintain our worklist.
98 //
99 // The set contains the items on the worklist, but does not
100 // maintain the order they should be visited.
101 //
102 // The vector maintains the order nodes should be visited, but may
103 // contain duplicate or removed nodes. When choosing a node to
104 // visit, we pop off the order stack until we find an item that is
105 // also in the contents set. All operations are O(log N).
106 SmallPtrSet<SDNode*, 64> WorkListContents;
Benjamin Kramere1e549d2012-03-10 00:23:58 +0000107 SmallVector<SDNode*, 64> WorkListOrder;
Nate Begeman21158fc2005-09-01 00:19:25 +0000108
Jim Laskeydcb2b832006-10-16 20:52:31 +0000109 // AA - Used for DAG load/store alias analysis.
110 AliasAnalysis &AA;
111
Nate Begeman21158fc2005-09-01 00:19:25 +0000112 /// AddUsersToWorkList - When an instruction is simplified, add all users of
113 /// the instruction to the work lists because they might get more simplified
114 /// now.
115 ///
116 void AddUsersToWorkList(SDNode *N) {
Jim Grosbache8160032014-04-11 01:13:13 +0000117 for (SDNode *Node : N->uses())
118 AddToWorkList(Node);
Nate Begeman21158fc2005-09-01 00:19:25 +0000119 }
120
Dan Gohman5c6d0c32007-10-08 17:57:15 +0000121 /// visit - call the node-specific routine that knows how to fold each
122 /// particular type of node.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000123 SDValue visit(SDNode *N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +0000124
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000125 public:
James Molloy920ae8c2012-02-16 09:48:07 +0000126 /// AddToWorkList - Add to the work list making sure its instance is at the
James Molloy67b6b112012-02-16 09:17:04 +0000127 /// back (next to be processed.)
Chris Lattnerfbcd62d2006-03-01 04:03:14 +0000128 void AddToWorkList(SDNode *N) {
James Molloy67b6b112012-02-16 09:17:04 +0000129 WorkListContents.insert(N);
130 WorkListOrder.push_back(N);
Chris Lattnerfbcd62d2006-03-01 04:03:14 +0000131 }
Jim Laskey708d0db2006-10-04 16:53:27 +0000132
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000133 /// removeFromWorkList - remove all instances of N from the worklist.
134 ///
135 void removeFromWorkList(SDNode *N) {
James Molloy67b6b112012-02-16 09:17:04 +0000136 WorkListContents.erase(N);
Chris Lattnere260ed82005-10-10 22:04:48 +0000137 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000138
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000139 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
Evan Chengfd81c732009-03-28 05:57:29 +0000140 bool AddTo = true);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000141
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000142 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
Jim Laskeydcf983c2006-10-13 23:32:28 +0000143 return CombineTo(N, &Res, 1, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000144 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000145
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000146 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
Evan Chengfd81c732009-03-28 05:57:29 +0000147 bool AddTo = true) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000148 SDValue To[] = { Res0, Res1 };
Jim Laskeydcf983c2006-10-13 23:32:28 +0000149 return CombineTo(N, To, 2, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000150 }
Dan Gohmane58ab792009-01-29 01:59:02 +0000151
152 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000153
154 private:
155
Chris Lattner375e1a72006-02-17 21:58:01 +0000156 /// SimplifyDemandedBits - Check the specified integer node value to see if
Chris Lattner232024e2006-03-01 19:55:35 +0000157 /// it can be simplified or if things it uses can be simplified by bit
Chris Lattner375e1a72006-02-17 21:58:01 +0000158 /// propagation. If so, return true.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000159 bool SimplifyDemandedBits(SDValue Op) {
Dan Gohman1d459e42009-12-11 21:31:27 +0000160 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
161 APInt Demanded = APInt::getAllOnesValue(BitWidth);
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000162 return SimplifyDemandedBits(Op, Demanded);
163 }
164
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000165 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
Chris Lattner04c73702005-10-10 22:31:19 +0000166
Chris Lattnerffad2162006-11-11 00:39:41 +0000167 bool CombineToPreIndexedLoadStore(SDNode *N);
168 bool CombineToPostIndexedLoadStore(SDNode *N);
Quentin Colombetde0e0622013-10-11 18:29:42 +0000169 bool SliceUpLoad(SDNode *N);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000170
Evan Cheng0abb54d2010-04-24 04:43:44 +0000171 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
172 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
173 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
174 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
Evan Chengaf56fac2010-04-16 06:14:10 +0000175 SDValue PromoteIntBinOp(SDValue Op);
Evan Chengf1223bd2010-04-22 20:19:46 +0000176 SDValue PromoteIntShiftOp(SDValue Op);
Evan Chenge19aa5c2010-04-19 19:29:22 +0000177 SDValue PromoteExtend(SDValue Op);
178 bool PromoteLoad(SDValue Op);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000179
Craig Toppere0b71182013-07-13 07:43:40 +0000180 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
Andrew Trickef9de2a2013-05-25 02:42:55 +0000181 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
Nick Lewycky6d677cf2011-06-16 01:15:49 +0000182 ISD::NodeType ExtType);
183
Dan Gohman5c6d0c32007-10-08 17:57:15 +0000184 /// combine - call the node-specific routine that knows how to fold each
185 /// particular type of node. If that doesn't do anything, try the
186 /// target-specific DAG combines.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000187 SDValue combine(SDNode *N);
Nate Begeman21158fc2005-09-01 00:19:25 +0000188
189 // Visitation implementation - Implement dag node combining for different
190 // node types. The semantics are as follows:
191 // Return Value:
Evan Cheng5e7658c2008-08-29 22:21:44 +0000192 // SDValue.getNode() == 0 - No change was made
193 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
194 // otherwise - N should be replaced by the returned Operand.
Nate Begeman21158fc2005-09-01 00:19:25 +0000195 //
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000196 SDValue visitTokenFactor(SDNode *N);
197 SDValue visitMERGE_VALUES(SDNode *N);
198 SDValue visitADD(SDNode *N);
199 SDValue visitSUB(SDNode *N);
200 SDValue visitADDC(SDNode *N);
Craig Topper43a1bd62012-01-07 09:06:39 +0000201 SDValue visitSUBC(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000202 SDValue visitADDE(SDNode *N);
Craig Topper43a1bd62012-01-07 09:06:39 +0000203 SDValue visitSUBE(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000204 SDValue visitMUL(SDNode *N);
205 SDValue visitSDIV(SDNode *N);
206 SDValue visitUDIV(SDNode *N);
207 SDValue visitSREM(SDNode *N);
208 SDValue visitUREM(SDNode *N);
209 SDValue visitMULHU(SDNode *N);
210 SDValue visitMULHS(SDNode *N);
211 SDValue visitSMUL_LOHI(SDNode *N);
212 SDValue visitUMUL_LOHI(SDNode *N);
Benjamin Kramer2fd48f22011-05-21 18:31:55 +0000213 SDValue visitSMULO(SDNode *N);
214 SDValue visitUMULO(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000215 SDValue visitSDIVREM(SDNode *N);
216 SDValue visitUDIVREM(SDNode *N);
217 SDValue visitAND(SDNode *N);
218 SDValue visitOR(SDNode *N);
219 SDValue visitXOR(SDNode *N);
220 SDValue SimplifyVBinOp(SDNode *N);
Craig Topper82384612012-09-11 01:45:21 +0000221 SDValue SimplifyVUnaryOp(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000222 SDValue visitSHL(SDNode *N);
223 SDValue visitSRA(SDNode *N);
224 SDValue visitSRL(SDNode *N);
Adam Nemet7f928f12014-03-07 23:56:30 +0000225 SDValue visitRotate(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000226 SDValue visitCTLZ(SDNode *N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +0000227 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000228 SDValue visitCTTZ(SDNode *N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +0000229 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000230 SDValue visitCTPOP(SDNode *N);
231 SDValue visitSELECT(SDNode *N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +0000232 SDValue visitVSELECT(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000233 SDValue visitSELECT_CC(SDNode *N);
234 SDValue visitSETCC(SDNode *N);
235 SDValue visitSIGN_EXTEND(SDNode *N);
236 SDValue visitZERO_EXTEND(SDNode *N);
237 SDValue visitANY_EXTEND(SDNode *N);
238 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
239 SDValue visitTRUNCATE(SDNode *N);
Wesley Peck527da1b2010-11-23 03:31:01 +0000240 SDValue visitBITCAST(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000241 SDValue visitBUILD_PAIR(SDNode *N);
242 SDValue visitFADD(SDNode *N);
243 SDValue visitFSUB(SDNode *N);
244 SDValue visitFMUL(SDNode *N);
Owen Anderson41b06652012-05-02 22:17:40 +0000245 SDValue visitFMA(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000246 SDValue visitFDIV(SDNode *N);
247 SDValue visitFREM(SDNode *N);
248 SDValue visitFCOPYSIGN(SDNode *N);
249 SDValue visitSINT_TO_FP(SDNode *N);
250 SDValue visitUINT_TO_FP(SDNode *N);
251 SDValue visitFP_TO_SINT(SDNode *N);
252 SDValue visitFP_TO_UINT(SDNode *N);
253 SDValue visitFP_ROUND(SDNode *N);
254 SDValue visitFP_ROUND_INREG(SDNode *N);
255 SDValue visitFP_EXTEND(SDNode *N);
256 SDValue visitFNEG(SDNode *N);
257 SDValue visitFABS(SDNode *N);
Owen Andersona40319b2012-08-13 23:32:49 +0000258 SDValue visitFCEIL(SDNode *N);
259 SDValue visitFTRUNC(SDNode *N);
260 SDValue visitFFLOOR(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000261 SDValue visitBRCOND(SDNode *N);
262 SDValue visitBR_CC(SDNode *N);
263 SDValue visitLOAD(SDNode *N);
264 SDValue visitSTORE(SDNode *N);
265 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
266 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
267 SDValue visitBUILD_VECTOR(SDNode *N);
268 SDValue visitCONCAT_VECTORS(SDNode *N);
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +0000269 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000270 SDValue visitVECTOR_SHUFFLE(SDNode *N);
Manman Ren413a6cb2014-01-31 01:10:35 +0000271 SDValue visitINSERT_SUBVECTOR(SDNode *N);
Chris Lattnere260ed82005-10-10 22:04:48 +0000272
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000273 SDValue XformToShuffleWithZero(SDNode *N);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000274 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000275
Matt Arsenault985b9de2014-03-17 18:58:01 +0000276 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
Chris Lattner7c709a52007-12-06 07:33:36 +0000277
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000278 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
279 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000280 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
281 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
Scott Michelcf0da6c2009-02-17 22:15:04 +0000282 SDValue N3, ISD::CondCode CC,
Bill Wendling31b50992009-01-30 23:59:18 +0000283 bool NotExtCompare = false);
Owen Anderson53aa7a92009-08-10 22:56:29 +0000284 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
Andrew Trickef9de2a2013-05-25 02:42:55 +0000285 SDLoc DL, bool foldBooleans = true);
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000286
287 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
288 SDValue &CC) const;
289 bool isOneUseSetCC(SDValue N) const;
290
Scott Michelcf0da6c2009-02-17 22:15:04 +0000291 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
Chris Lattner31e9edc2008-01-26 01:09:19 +0000292 unsigned HiOp);
Owen Anderson53aa7a92009-08-10 22:56:29 +0000293 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
Wesley Peck527da1b2010-11-23 03:31:01 +0000294 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000295 SDValue BuildSDIV(SDNode *N);
296 SDValue BuildUDIV(SDNode *N);
Evan Cheng4c0bd962011-06-21 06:01:08 +0000297 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
298 bool DemandHighBits = true);
299 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
Richard Sandiford95c864d2014-01-08 15:40:47 +0000300 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
301 SDValue InnerPos, SDValue InnerNeg,
302 unsigned PosOpcode, unsigned NegOpcode,
303 SDLoc DL);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000304 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000305 SDValue ReduceLoadWidth(SDNode *N);
Evan Chenga9cda8a2009-05-28 00:35:15 +0000306 SDValue ReduceLoadOpStoreWidth(SDNode *N);
Evan Chengd42641c2011-02-02 01:06:55 +0000307 SDValue TransformFPLoadStorePair(SDNode *N);
Michael Liao6d106b72012-10-23 23:06:52 +0000308 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
Michael Liao59229792012-10-24 04:14:18 +0000309 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000310
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000311 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000312
Jim Laskey708d0db2006-10-04 16:53:27 +0000313 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
314 /// looking for aliasing nodes and adding them to the Aliases vector.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000315 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
Craig Topperb94011f2013-07-14 04:42:23 +0000316 SmallVectorImpl<SDValue> &Aliases);
Jim Laskey708d0db2006-10-04 16:53:27 +0000317
Jim Laskeya15b0eb2006-10-18 12:29:57 +0000318 /// isAlias - Return true if there is any possibility that the two addresses
319 /// overlap.
Richard Sandiford981fdeb2013-10-28 12:00:00 +0000320 bool isAlias(SDValue Ptr1, int64_t Size1, bool IsVolatile1,
Jim Laskeya15b0eb2006-10-18 12:29:57 +0000321 const Value *SrcValue1, int SrcValueOffset1,
Nate Begeman879d8f12009-09-15 00:18:30 +0000322 unsigned SrcValueAlign1,
Dan Gohmana94cc6d2010-10-20 00:31:05 +0000323 const MDNode *TBAAInfo1,
Richard Sandiford981fdeb2013-10-28 12:00:00 +0000324 SDValue Ptr2, int64_t Size2, bool IsVolatile2,
Nate Begeman879d8f12009-09-15 00:18:30 +0000325 const Value *SrcValue2, int SrcValueOffset2,
Dan Gohmana94cc6d2010-10-20 00:31:05 +0000326 unsigned SrcValueAlign2,
327 const MDNode *TBAAInfo2) const;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000328
Nadav Rotem307d7672012-11-29 00:00:08 +0000329 /// isAlias - Return true if there is any possibility that the two addresses
330 /// overlap.
331 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1);
332
Jim Laskey08edf332006-10-11 13:47:09 +0000333 /// FindAliasInfo - Extracts the relevant alias information from the memory
334 /// node. Returns true if the operand was a load.
335 bool FindAliasInfo(SDNode *N,
Richard Sandiford981fdeb2013-10-28 12:00:00 +0000336 SDValue &Ptr, int64_t &Size, bool &IsVolatile,
Nate Begeman879d8f12009-09-15 00:18:30 +0000337 const Value *&SrcValue, int &SrcValueOffset,
Dan Gohmana94cc6d2010-10-20 00:31:05 +0000338 unsigned &SrcValueAlignment,
339 const MDNode *&TBAAInfo) const;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000340
Jim Laskeyd07be232006-09-25 16:29:54 +0000341 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
Jim Laskey708d0db2006-10-04 16:53:27 +0000342 /// looking for a better chain (aliasing node.)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000343 SDValue FindBetterChain(SDNode *N, SDValue Chain);
Duncan Sands41826032009-01-31 15:50:11 +0000344
Nadav Rotem7cbc12a2012-10-03 16:11:15 +0000345 /// Merge consecutive store operations into a wide store.
346 /// This optimization uses wide integers or vectors when possible.
347 /// \return True if some memory operations were changed.
348 bool MergeConsecutiveStores(StoreSDNode *N);
349
Adam Nemet67483892014-03-04 23:28:31 +0000350 /// \brief Try to transform a truncation where C is a constant:
351 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
352 ///
353 /// \p N needs to be a truncation and its first operand an AND. Other
354 /// requirements are checked by the function (e.g. that trunc is
355 /// single-use) and if missed an empty SDValue is returned.
356 SDValue distributeTruncateThroughAnd(SDNode *N);
357
Chris Lattner4041ab62010-04-15 04:48:01 +0000358 public:
Bill Wendling026e5d72009-04-29 23:29:43 +0000359 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
Quentin Colombetde0e0622013-10-11 18:29:42 +0000360 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
361 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
362 AttributeSet FnAttrs =
363 DAG.getMachineFunction().getFunction()->getAttributes();
364 ForCodeSize =
365 FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
366 Attribute::OptimizeForSize) ||
367 FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
368 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000369
Nate Begeman21158fc2005-09-01 00:19:25 +0000370 /// Run - runs the dag combiner on all nodes in the work list
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000371 void Run(CombineLevel AtLevel);
Wesley Peck527da1b2010-11-23 03:31:01 +0000372
Chris Lattner4041ab62010-04-15 04:48:01 +0000373 SelectionDAG &getDAG() const { return DAG; }
Wesley Peck527da1b2010-11-23 03:31:01 +0000374
Chris Lattner4041ab62010-04-15 04:48:01 +0000375 /// getShiftAmountTy - Returns a type large enough to hold any valid
376 /// shift amount - before type legalization these can be huge.
Owen Andersonb2c80da2011-02-25 21:41:48 +0000377 EVT getShiftAmountTy(EVT LHSTy) {
Elena Demikhovsky6769c502013-06-26 10:55:03 +0000378 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
379 if (LHSTy.isVector())
380 return LHSTy;
Jack Carterd4e96152013-10-17 01:34:33 +0000381 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
382 : TLI.getPointerTy();
Chris Lattner4041ab62010-04-15 04:48:01 +0000383 }
Wesley Peck527da1b2010-11-23 03:31:01 +0000384
Chris Lattner4041ab62010-04-15 04:48:01 +0000385 /// isTypeLegal - This method returns true if we are running before type
386 /// legalization or if the specified VT is legal.
387 bool isTypeLegal(const EVT &VT) {
388 if (!LegalTypes) return true;
389 return TLI.isTypeLegal(VT);
390 }
Matt Arsenault758659232013-05-18 00:21:46 +0000391
392 /// getSetCCResultType - Convenience wrapper around
393 /// TargetLowering::getSetCCResultType
394 EVT getSetCCResultType(EVT VT) const {
395 return TLI.getSetCCResultType(*DAG.getContext(), VT);
396 }
Nate Begeman21158fc2005-09-01 00:19:25 +0000397 };
398}
399
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000400
401namespace {
402/// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
403/// nodes from the worklist.
Nick Lewycky02d5f772009-10-25 06:33:48 +0000404class WorkListRemover : public SelectionDAG::DAGUpdateListener {
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000405 DAGCombiner &DC;
406public:
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000407 explicit WorkListRemover(DAGCombiner &dc)
408 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
Scott Michelcf0da6c2009-02-17 22:15:04 +0000409
Craig Topper7b883b32014-03-08 06:31:39 +0000410 void NodeDeleted(SDNode *N, SDNode *E) override {
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000411 DC.removeFromWorkList(N);
412 }
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000413};
414}
415
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000416//===----------------------------------------------------------------------===//
417// TargetLowering::DAGCombinerInfo implementation
418//===----------------------------------------------------------------------===//
419
420void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
421 ((DAGCombiner*)DC)->AddToWorkList(N);
422}
423
Cameron Zwarich8c7bbc02011-04-02 02:40:26 +0000424void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
425 ((DAGCombiner*)DC)->removeFromWorkList(N);
426}
427
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000428SDValue TargetLowering::DAGCombinerInfo::
Evan Chengfd81c732009-03-28 05:57:29 +0000429CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
430 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000431}
432
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000433SDValue TargetLowering::DAGCombinerInfo::
Evan Chengfd81c732009-03-28 05:57:29 +0000434CombineTo(SDNode *N, SDValue Res, bool AddTo) {
435 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000436}
437
438
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000439SDValue TargetLowering::DAGCombinerInfo::
Evan Chengfd81c732009-03-28 05:57:29 +0000440CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
441 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000442}
443
Dan Gohmane58ab792009-01-29 01:59:02 +0000444void TargetLowering::DAGCombinerInfo::
445CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
446 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
447}
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000448
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000449//===----------------------------------------------------------------------===//
Chris Lattnere49c9742007-05-14 22:04:50 +0000450// Helper Functions
451//===----------------------------------------------------------------------===//
452
453/// isNegatibleForFree - Return 1 if we can compute the negated form of the
454/// specified expression for the same cost as the expression itself, or 2 if we
455/// can compute the negated form more cheaply than the expression itself.
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000456static char isNegatibleForFree(SDValue Op, bool LegalOperations,
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000457 const TargetLowering &TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000458 const TargetOptions *Options,
Chris Lattnere7c14012008-02-26 07:04:54 +0000459 unsigned Depth = 0) {
Chris Lattnere49c9742007-05-14 22:04:50 +0000460 // fneg is removable even if it has multiple uses.
461 if (Op.getOpcode() == ISD::FNEG) return 2;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000462
Chris Lattnere49c9742007-05-14 22:04:50 +0000463 // Don't allow anything with multiple uses.
464 if (!Op.hasOneUse()) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000465
Chris Lattner46980832007-05-25 02:19:06 +0000466 // Don't recurse exponentially.
467 if (Depth > 6) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000468
Chris Lattnere49c9742007-05-14 22:04:50 +0000469 switch (Op.getOpcode()) {
470 default: return false;
471 case ISD::ConstantFP:
Chris Lattnere7c14012008-02-26 07:04:54 +0000472 // Don't invert constant FP values after legalize. The negated constant
473 // isn't necessarily legal.
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000474 return LegalOperations ? 0 : 1;
Chris Lattnere49c9742007-05-14 22:04:50 +0000475 case ISD::FADD:
476 // FIXME: determine better conditions for this xform.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000477 if (!Options->UnsafeFPMath) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000478
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000479 // After operation legalization, it might not be legal to create new FSUBs.
480 if (LegalOperations &&
481 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
482 return 0;
483
Craig Topper03f39772012-09-09 22:58:45 +0000484 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000485 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
486 Options, Depth + 1))
Chris Lattnere49c9742007-05-14 22:04:50 +0000487 return V;
Bill Wendling6fbf5492009-01-30 23:10:18 +0000488 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000489 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000490 Depth + 1);
Chris Lattnere49c9742007-05-14 22:04:50 +0000491 case ISD::FSUB:
Scott Michelcf0da6c2009-02-17 22:15:04 +0000492 // We can't turn -(A-B) into B-A when we honor signed zeros.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000493 if (!Options->UnsafeFPMath) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000494
Bill Wendling6fbf5492009-01-30 23:10:18 +0000495 // fold (fneg (fsub A, B)) -> (fsub B, A)
Chris Lattnere49c9742007-05-14 22:04:50 +0000496 return 1;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000497
Chris Lattnere49c9742007-05-14 22:04:50 +0000498 case ISD::FMUL:
499 case ISD::FDIV:
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000500 if (Options->HonorSignDependentRoundingFPMath()) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000501
Bill Wendling6fbf5492009-01-30 23:10:18 +0000502 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000503 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
504 Options, Depth + 1))
Chris Lattnere49c9742007-05-14 22:04:50 +0000505 return V;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000506
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000507 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000508 Depth + 1);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000509
Chris Lattnere49c9742007-05-14 22:04:50 +0000510 case ISD::FP_EXTEND:
511 case ISD::FP_ROUND:
512 case ISD::FSIN:
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000513 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000514 Depth + 1);
Chris Lattnere49c9742007-05-14 22:04:50 +0000515 }
516}
517
518/// GetNegatedExpression - If isNegatibleForFree returns true, this function
519/// returns the newly negated expression.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000520static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000521 bool LegalOperations, unsigned Depth = 0) {
Chris Lattnere49c9742007-05-14 22:04:50 +0000522 // fneg is removable even if it has multiple uses.
523 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000524
Chris Lattnere49c9742007-05-14 22:04:50 +0000525 // Don't allow anything with multiple uses.
526 assert(Op.hasOneUse() && "Unknown reuse!");
Scott Michelcf0da6c2009-02-17 22:15:04 +0000527
Chris Lattner46980832007-05-25 02:19:06 +0000528 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
Chris Lattnere49c9742007-05-14 22:04:50 +0000529 switch (Op.getOpcode()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000530 default: llvm_unreachable("Unknown code");
Dale Johannesen446b9002007-08-31 23:34:27 +0000531 case ISD::ConstantFP: {
532 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
533 V.changeSign();
534 return DAG.getConstantFP(V, Op.getValueType());
535 }
Chris Lattnere49c9742007-05-14 22:04:50 +0000536 case ISD::FADD:
537 // FIXME: determine better conditions for this xform.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000538 assert(DAG.getTarget().Options.UnsafeFPMath);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000539
Bill Wendling6fbf5492009-01-30 23:10:18 +0000540 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000541 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000542 DAG.getTargetLoweringInfo(),
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000543 &DAG.getTarget().Options, Depth+1))
Andrew Trickef9de2a2013-05-25 02:42:55 +0000544 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000545 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000546 LegalOperations, Depth+1),
Chris Lattnere49c9742007-05-14 22:04:50 +0000547 Op.getOperand(1));
Bill Wendling6fbf5492009-01-30 23:10:18 +0000548 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
Andrew Trickef9de2a2013-05-25 02:42:55 +0000549 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000550 GetNegatedExpression(Op.getOperand(1), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000551 LegalOperations, Depth+1),
Chris Lattnere49c9742007-05-14 22:04:50 +0000552 Op.getOperand(0));
553 case ISD::FSUB:
Scott Michelcf0da6c2009-02-17 22:15:04 +0000554 // We can't turn -(A-B) into B-A when we honor signed zeros.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000555 assert(DAG.getTarget().Options.UnsafeFPMath);
Dan Gohman9a708232007-07-02 15:48:56 +0000556
Bill Wendling6fbf5492009-01-30 23:10:18 +0000557 // fold (fneg (fsub 0, B)) -> B
Dan Gohman9a708232007-07-02 15:48:56 +0000558 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
Dale Johannesen446b9002007-08-31 23:34:27 +0000559 if (N0CFP->getValueAPF().isZero())
Dan Gohman9a708232007-07-02 15:48:56 +0000560 return Op.getOperand(1);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000561
Bill Wendling6fbf5492009-01-30 23:10:18 +0000562 // fold (fneg (fsub A, B)) -> (fsub B, A)
Andrew Trickef9de2a2013-05-25 02:42:55 +0000563 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000564 Op.getOperand(1), Op.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +0000565
Chris Lattnere49c9742007-05-14 22:04:50 +0000566 case ISD::FMUL:
567 case ISD::FDIV:
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000568 assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000569
Bill Wendling6fbf5492009-01-30 23:10:18 +0000570 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000571 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000572 DAG.getTargetLoweringInfo(),
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000573 &DAG.getTarget().Options, Depth+1))
Andrew Trickef9de2a2013-05-25 02:42:55 +0000574 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000575 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000576 LegalOperations, Depth+1),
Chris Lattnere49c9742007-05-14 22:04:50 +0000577 Op.getOperand(1));
Scott Michelcf0da6c2009-02-17 22:15:04 +0000578
Bill Wendling6fbf5492009-01-30 23:10:18 +0000579 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
Andrew Trickef9de2a2013-05-25 02:42:55 +0000580 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Chris Lattnere49c9742007-05-14 22:04:50 +0000581 Op.getOperand(0),
Chris Lattnere7c14012008-02-26 07:04:54 +0000582 GetNegatedExpression(Op.getOperand(1), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000583 LegalOperations, Depth+1));
Scott Michelcf0da6c2009-02-17 22:15:04 +0000584
Chris Lattnere49c9742007-05-14 22:04:50 +0000585 case ISD::FP_EXTEND:
Chris Lattnere49c9742007-05-14 22:04:50 +0000586 case ISD::FSIN:
Andrew Trickef9de2a2013-05-25 02:42:55 +0000587 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000588 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000589 LegalOperations, Depth+1));
Chris Lattner72733e52008-01-17 07:00:52 +0000590 case ISD::FP_ROUND:
Andrew Trickef9de2a2013-05-25 02:42:55 +0000591 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000592 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000593 LegalOperations, Depth+1),
Chris Lattner72733e52008-01-17 07:00:52 +0000594 Op.getOperand(1));
Chris Lattnere49c9742007-05-14 22:04:50 +0000595 }
596}
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000597
Nate Begeman2504fe22005-09-01 23:24:04 +0000598// isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000599// that selects between the target values used for true and false, making it
600// equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
601// the appropriate nodes based on the type of node we are checking. This
602// simplifies life a bit for the callers.
603bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
604 SDValue &CC) const {
Nate Begeman7cea6ef2005-09-02 21:18:40 +0000605 if (N.getOpcode() == ISD::SETCC) {
606 LHS = N.getOperand(0);
607 RHS = N.getOperand(1);
608 CC = N.getOperand(2);
Nate Begeman2504fe22005-09-01 23:24:04 +0000609 return true;
Nate Begeman7cea6ef2005-09-02 21:18:40 +0000610 }
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000611
612 if (N.getOpcode() != ISD::SELECT_CC ||
613 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
614 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
615 return false;
616
617 LHS = N.getOperand(0);
618 RHS = N.getOperand(1);
619 CC = N.getOperand(4);
620 return true;
Nate Begeman21158fc2005-09-01 00:19:25 +0000621}
622
Nate Begeman2cc2c9a2005-09-07 23:25:52 +0000623// isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
624// one use. If this is true, it allows the users to invert the operation for
625// free when it is profitable to do so.
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000626bool DAGCombiner::isOneUseSetCC(SDValue N) const {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000627 SDValue N0, N1, N2;
Gabor Greiff304a7a2008-08-28 21:40:38 +0000628 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
Nate Begeman2504fe22005-09-01 23:24:04 +0000629 return true;
630 return false;
631}
632
Matt Arsenault985b9de2014-03-17 18:58:01 +0000633/// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose
634/// elements are all the same constant or undefined.
635static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
636 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
637 if (!C)
638 return false;
639
640 APInt SplatUndef;
641 unsigned SplatBitSize;
642 bool HasAnyUndefs;
643 EVT EltVT = N->getValueType(0).getVectorElementType();
644 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
645 HasAnyUndefs) &&
646 EltVT.getSizeInBits() >= SplatBitSize);
647}
648
649// \brief Returns the SDNode if it is a constant BuildVector or constant.
Juergen Ributzka68402822014-01-13 21:49:25 +0000650static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
651 if (isa<ConstantSDNode>(N))
652 return N.getNode();
653 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
654 if(BV && BV->isConstant())
655 return BV;
Craig Topperc0196b12014-04-14 00:51:57 +0000656 return nullptr;
Juergen Ributzka68402822014-01-13 21:49:25 +0000657}
658
Matt Arsenault985b9de2014-03-17 18:58:01 +0000659// \brief Returns the SDNode if it is a constant splat BuildVector or constant
660// int.
661static ConstantSDNode *isConstOrConstSplat(SDValue N) {
662 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
663 return CN;
664
665 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N))
Andrea Di Biagio5b0aacf2014-03-22 01:47:22 +0000666 return BV->getConstantSplatValue();
Matt Arsenault985b9de2014-03-17 18:58:01 +0000667
668 return nullptr;
669}
670
Andrew Trickef9de2a2013-05-25 02:42:55 +0000671SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000672 SDValue N0, SDValue N1) {
Owen Anderson53aa7a92009-08-10 22:56:29 +0000673 EVT VT = N0.getValueType();
Juergen Ributzka68402822014-01-13 21:49:25 +0000674 if (N0.getOpcode() == Opc) {
675 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
676 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
677 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
678 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
679 if (!OpNode.getNode())
680 return SDValue();
681 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
Juergen Ributzka73844052014-01-13 20:51:35 +0000682 }
Juergen Ributzka68402822014-01-13 21:49:25 +0000683 if (N0.hasOneUse()) {
684 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
685 // use
686 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
687 if (!OpNode.getNode())
688 return SDValue();
689 AddToWorkList(OpNode.getNode());
690 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
Juergen Ributzka73844052014-01-13 20:51:35 +0000691 }
692 }
Nate Begeman22e251a2006-02-03 06:46:56 +0000693 }
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000694
Juergen Ributzka68402822014-01-13 21:49:25 +0000695 if (N1.getOpcode() == Opc) {
696 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
697 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
698 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
699 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
700 if (!OpNode.getNode())
701 return SDValue();
702 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
703 }
704 if (N1.hasOneUse()) {
705 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
706 // use
707 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
708 if (!OpNode.getNode())
709 return SDValue();
710 AddToWorkList(OpNode.getNode());
711 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
712 }
Nate Begeman22e251a2006-02-03 06:46:56 +0000713 }
714 }
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000715
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000716 return SDValue();
Nate Begeman22e251a2006-02-03 06:46:56 +0000717}
718
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000719SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
720 bool AddTo) {
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000721 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
722 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +0000723 DEBUG(dbgs() << "\nReplacing.1 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000724 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000725 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000726 To[0].getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000727 dbgs() << " and " << NumTo-1 << " other values\n";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000728 for (unsigned i = 0, e = NumTo; i != e; ++i)
Jakob Stoklund Olesen32042f92009-12-03 05:15:35 +0000729 assert((!To[i].getNode() ||
730 N->getValueType(i) == To[i].getValueType()) &&
Dan Gohman7e6b9322009-01-21 15:17:51 +0000731 "Cannot combine value to value of different type!"));
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000732 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000733 DAG.ReplaceAllUsesWith(N, To);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000734 if (AddTo) {
735 // Push the new nodes and any users onto the worklist
736 for (unsigned i = 0, e = NumTo; i != e; ++i) {
Chris Lattner4147f082009-03-12 06:52:53 +0000737 if (To[i].getNode()) {
738 AddToWorkList(To[i].getNode());
739 AddUsersToWorkList(To[i].getNode());
740 }
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000741 }
742 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000743
Dan Gohmancd0b1bf2009-01-19 21:44:21 +0000744 // Finally, if the node is now dead, remove it from the graph. The node
745 // may not be dead if the replacement process recursively simplified to
746 // something else needing this node.
747 if (N->use_empty()) {
748 // Nodes can be reintroduced into the worklist. Make sure we do not
749 // process a node that has been replaced.
750 removeFromWorkList(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000751
Dan Gohmancd0b1bf2009-01-19 21:44:21 +0000752 // Finally, since the node is now dead, remove it from the graph.
753 DAG.DeleteNode(N);
754 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000755 return SDValue(N, 0);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000756}
757
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000758void DAGCombiner::
759CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
Scott Michelcf0da6c2009-02-17 22:15:04 +0000760 // Replace all uses. If any nodes become isomorphic to other nodes and
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000761 // are deleted, make sure to remove them from our worklist.
762 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000763 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
Dan Gohmane58ab792009-01-29 01:59:02 +0000764
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000765 // Push the new node and any (possibly new) users onto the worklist.
Gabor Greiff304a7a2008-08-28 21:40:38 +0000766 AddToWorkList(TLO.New.getNode());
767 AddUsersToWorkList(TLO.New.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000768
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000769 // Finally, if the node is now dead, remove it from the graph. The node
770 // may not be dead if the replacement process recursively simplified to
771 // something else needing this node.
Gabor Greiff304a7a2008-08-28 21:40:38 +0000772 if (TLO.Old.getNode()->use_empty()) {
773 removeFromWorkList(TLO.Old.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000774
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000775 // If the operands of this node are only used by the node, they will now
776 // be dead. Make sure to visit them first to delete dead nodes early.
Gabor Greiff304a7a2008-08-28 21:40:38 +0000777 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
778 if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
779 AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000780
Gabor Greiff304a7a2008-08-28 21:40:38 +0000781 DAG.DeleteNode(TLO.Old.getNode());
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000782 }
Dan Gohmane58ab792009-01-29 01:59:02 +0000783}
784
785/// SimplifyDemandedBits - Check the specified integer node value to see if
786/// it can be simplified or if things it uses can be simplified by bit
787/// propagation. If so, return true.
788bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000789 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
Dan Gohmane58ab792009-01-29 01:59:02 +0000790 APInt KnownZero, KnownOne;
791 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
792 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000793
Dan Gohmane58ab792009-01-29 01:59:02 +0000794 // Revisit the node.
795 AddToWorkList(Op.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000796
Dan Gohmane58ab792009-01-29 01:59:02 +0000797 // Replace the old value with the new one.
798 ++NodesCombined;
Wesley Peck527da1b2010-11-23 03:31:01 +0000799 DEBUG(dbgs() << "\nReplacing.2 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000800 TLO.Old.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000801 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000802 TLO.New.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000803 dbgs() << '\n');
Scott Michelcf0da6c2009-02-17 22:15:04 +0000804
Dan Gohmane58ab792009-01-29 01:59:02 +0000805 CommitTargetLoweringOpt(TLO);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000806 return true;
807}
808
Evan Cheng0abb54d2010-04-24 04:43:44 +0000809void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
Andrew Trickef9de2a2013-05-25 02:42:55 +0000810 SDLoc dl(Load);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000811 EVT VT = Load->getValueType(0);
812 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
Evan Chenge19aa5c2010-04-19 19:29:22 +0000813
Evan Cheng0abb54d2010-04-24 04:43:44 +0000814 DEBUG(dbgs() << "\nReplacing.9 ";
815 Load->dump(&DAG);
816 dbgs() << "\nWith: ";
817 Trunc.getNode()->dump(&DAG);
818 dbgs() << '\n');
819 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000820 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
821 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
Evan Cheng0abb54d2010-04-24 04:43:44 +0000822 removeFromWorkList(Load);
823 DAG.DeleteNode(Load);
Evan Chenge8136902010-04-27 19:48:13 +0000824 AddToWorkList(Trunc.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000825}
826
827SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
828 Replace = false;
Andrew Trickef9de2a2013-05-25 02:42:55 +0000829 SDLoc dl(Op);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000830 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
Evan Chenge8136902010-04-27 19:48:13 +0000831 EVT MemVT = LD->getMemoryVT();
832 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
Owen Andersonb2c80da2011-02-25 21:41:48 +0000833 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
Eric Christopherd9e8eac2010-12-09 04:48:06 +0000834 : ISD::EXTLOAD)
Evan Chenge8136902010-04-27 19:48:13 +0000835 : LD->getExtensionType();
Evan Cheng0abb54d2010-04-24 04:43:44 +0000836 Replace = true;
Stuart Hastings81c43062011-02-16 16:23:55 +0000837 return DAG.getExtLoad(ExtType, dl, PVT,
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000838 LD->getChain(), LD->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +0000839 MemVT, LD->getMemOperand());
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000840 }
841
Evan Chenge19aa5c2010-04-19 19:29:22 +0000842 unsigned Opc = Op.getOpcode();
Evan Chengb9ff1302010-04-23 19:10:30 +0000843 switch (Opc) {
844 default: break;
845 case ISD::AssertSext:
Evan Chenge19aa5c2010-04-19 19:29:22 +0000846 return DAG.getNode(ISD::AssertSext, dl, PVT,
Evan Cheng0abb54d2010-04-24 04:43:44 +0000847 SExtPromoteOperand(Op.getOperand(0), PVT),
Evan Chenge19aa5c2010-04-19 19:29:22 +0000848 Op.getOperand(1));
Evan Chengb9ff1302010-04-23 19:10:30 +0000849 case ISD::AssertZext:
Evan Chenge19aa5c2010-04-19 19:29:22 +0000850 return DAG.getNode(ISD::AssertZext, dl, PVT,
Evan Cheng0abb54d2010-04-24 04:43:44 +0000851 ZExtPromoteOperand(Op.getOperand(0), PVT),
Evan Chenge19aa5c2010-04-19 19:29:22 +0000852 Op.getOperand(1));
Evan Chengb9ff1302010-04-23 19:10:30 +0000853 case ISD::Constant: {
854 unsigned ExtOpc =
Evan Chenge19aa5c2010-04-19 19:29:22 +0000855 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
Evan Chengb9ff1302010-04-23 19:10:30 +0000856 return DAG.getNode(ExtOpc, dl, PVT, Op);
Wesley Peck527da1b2010-11-23 03:31:01 +0000857 }
Evan Chengb9ff1302010-04-23 19:10:30 +0000858 }
859
860 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000861 return SDValue();
Evan Chengb9ff1302010-04-23 19:10:30 +0000862 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
Evan Chengaf56fac2010-04-16 06:14:10 +0000863}
864
Evan Cheng0abb54d2010-04-24 04:43:44 +0000865SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000866 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
867 return SDValue();
868 EVT OldVT = Op.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +0000869 SDLoc dl(Op);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000870 bool Replace = false;
871 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
Craig Topperc0196b12014-04-14 00:51:57 +0000872 if (!NewOp.getNode())
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000873 return SDValue();
Evan Chenge8136902010-04-27 19:48:13 +0000874 AddToWorkList(NewOp.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000875
876 if (Replace)
877 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
878 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000879 DAG.getValueType(OldVT));
880}
881
Evan Cheng0abb54d2010-04-24 04:43:44 +0000882SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000883 EVT OldVT = Op.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +0000884 SDLoc dl(Op);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000885 bool Replace = false;
886 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
Craig Topperc0196b12014-04-14 00:51:57 +0000887 if (!NewOp.getNode())
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000888 return SDValue();
Evan Chenge8136902010-04-27 19:48:13 +0000889 AddToWorkList(NewOp.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000890
891 if (Replace)
892 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
893 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000894}
895
Evan Chengaf56fac2010-04-16 06:14:10 +0000896/// PromoteIntBinOp - Promote the specified integer binary operation if the
897/// target indicates it is beneficial. e.g. On x86, it's usually better to
898/// promote i16 operations to i32 since i16 instructions are longer.
899SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
900 if (!LegalOperations)
901 return SDValue();
902
903 EVT VT = Op.getValueType();
904 if (VT.isVector() || !VT.isInteger())
905 return SDValue();
906
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000907 // If operation type is 'undesirable', e.g. i16 on x86, consider
908 // promoting it.
909 unsigned Opc = Op.getOpcode();
910 if (TLI.isTypeDesirableForOp(Opc, VT))
911 return SDValue();
912
Evan Chengaf56fac2010-04-16 06:14:10 +0000913 EVT PVT = VT;
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000914 // Consult target whether it is a good idea to promote this operation and
915 // what's the right type to promote it to.
916 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
Evan Chengaf56fac2010-04-16 06:14:10 +0000917 assert(PVT != VT && "Don't know what type to promote to!");
918
Evan Cheng0abb54d2010-04-24 04:43:44 +0000919 bool Replace0 = false;
920 SDValue N0 = Op.getOperand(0);
921 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
Craig Topperc0196b12014-04-14 00:51:57 +0000922 if (!NN0.getNode())
Evan Chengf1223bd2010-04-22 20:19:46 +0000923 return SDValue();
924
Evan Cheng0abb54d2010-04-24 04:43:44 +0000925 bool Replace1 = false;
926 SDValue N1 = Op.getOperand(1);
Evan Cheng02947a42010-05-10 19:03:57 +0000927 SDValue NN1;
928 if (N0 == N1)
929 NN1 = NN0;
930 else {
931 NN1 = PromoteOperand(N1, PVT, Replace1);
Craig Topperc0196b12014-04-14 00:51:57 +0000932 if (!NN1.getNode())
Evan Cheng02947a42010-05-10 19:03:57 +0000933 return SDValue();
934 }
Evan Chengf1223bd2010-04-22 20:19:46 +0000935
Evan Cheng0abb54d2010-04-24 04:43:44 +0000936 AddToWorkList(NN0.getNode());
Evan Cheng02947a42010-05-10 19:03:57 +0000937 if (NN1.getNode())
938 AddToWorkList(NN1.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000939
940 if (Replace0)
941 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
942 if (Replace1)
943 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
Evan Chengf1223bd2010-04-22 20:19:46 +0000944
Evan Chenge8136902010-04-27 19:48:13 +0000945 DEBUG(dbgs() << "\nPromoting ";
946 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +0000947 SDLoc dl(Op);
Evan Chengf1223bd2010-04-22 20:19:46 +0000948 return DAG.getNode(ISD::TRUNCATE, dl, VT,
Evan Cheng0abb54d2010-04-24 04:43:44 +0000949 DAG.getNode(Opc, dl, PVT, NN0, NN1));
Evan Chengf1223bd2010-04-22 20:19:46 +0000950 }
951 return SDValue();
952}
953
954/// PromoteIntShiftOp - Promote the specified integer shift operation if the
955/// target indicates it is beneficial. e.g. On x86, it's usually better to
956/// promote i16 operations to i32 since i16 instructions are longer.
957SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
958 if (!LegalOperations)
959 return SDValue();
960
961 EVT VT = Op.getValueType();
962 if (VT.isVector() || !VT.isInteger())
963 return SDValue();
964
965 // If operation type is 'undesirable', e.g. i16 on x86, consider
966 // promoting it.
967 unsigned Opc = Op.getOpcode();
968 if (TLI.isTypeDesirableForOp(Opc, VT))
969 return SDValue();
970
971 EVT PVT = VT;
972 // Consult target whether it is a good idea to promote this operation and
973 // what's the right type to promote it to.
974 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
975 assert(PVT != VT && "Don't know what type to promote to!");
976
Evan Cheng0abb54d2010-04-24 04:43:44 +0000977 bool Replace = false;
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000978 SDValue N0 = Op.getOperand(0);
979 if (Opc == ISD::SRA)
Evan Cheng0abb54d2010-04-24 04:43:44 +0000980 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000981 else if (Opc == ISD::SRL)
Evan Cheng0abb54d2010-04-24 04:43:44 +0000982 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000983 else
Evan Cheng0abb54d2010-04-24 04:43:44 +0000984 N0 = PromoteOperand(N0, PVT, Replace);
Craig Topperc0196b12014-04-14 00:51:57 +0000985 if (!N0.getNode())
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000986 return SDValue();
Evan Cheng0abb54d2010-04-24 04:43:44 +0000987
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000988 AddToWorkList(N0.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000989 if (Replace)
990 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
Evan Chengaf56fac2010-04-16 06:14:10 +0000991
Evan Chenge8136902010-04-27 19:48:13 +0000992 DEBUG(dbgs() << "\nPromoting ";
993 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +0000994 SDLoc dl(Op);
Evan Chengaf56fac2010-04-16 06:14:10 +0000995 return DAG.getNode(ISD::TRUNCATE, dl, VT,
Evan Chengf1223bd2010-04-22 20:19:46 +0000996 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
Evan Chengaf56fac2010-04-16 06:14:10 +0000997 }
998 return SDValue();
999}
1000
Evan Chenge19aa5c2010-04-19 19:29:22 +00001001SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1002 if (!LegalOperations)
1003 return SDValue();
1004
1005 EVT VT = Op.getValueType();
1006 if (VT.isVector() || !VT.isInteger())
1007 return SDValue();
1008
1009 // If operation type is 'undesirable', e.g. i16 on x86, consider
1010 // promoting it.
1011 unsigned Opc = Op.getOpcode();
1012 if (TLI.isTypeDesirableForOp(Opc, VT))
1013 return SDValue();
1014
1015 EVT PVT = VT;
1016 // Consult target whether it is a good idea to promote this operation and
1017 // what's the right type to promote it to.
1018 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1019 assert(PVT != VT && "Don't know what type to promote to!");
1020 // fold (aext (aext x)) -> (aext x)
1021 // fold (aext (zext x)) -> (zext x)
1022 // fold (aext (sext x)) -> (sext x)
Evan Chenge8136902010-04-27 19:48:13 +00001023 DEBUG(dbgs() << "\nPromoting ";
1024 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +00001025 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
Evan Chenge19aa5c2010-04-19 19:29:22 +00001026 }
1027 return SDValue();
1028}
1029
1030bool DAGCombiner::PromoteLoad(SDValue Op) {
1031 if (!LegalOperations)
1032 return false;
1033
1034 EVT VT = Op.getValueType();
1035 if (VT.isVector() || !VT.isInteger())
1036 return false;
1037
1038 // If operation type is 'undesirable', e.g. i16 on x86, consider
1039 // promoting it.
1040 unsigned Opc = Op.getOpcode();
1041 if (TLI.isTypeDesirableForOp(Opc, VT))
1042 return false;
1043
1044 EVT PVT = VT;
1045 // Consult target whether it is a good idea to promote this operation and
1046 // what's the right type to promote it to.
1047 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1048 assert(PVT != VT && "Don't know what type to promote to!");
1049
Andrew Trickef9de2a2013-05-25 02:42:55 +00001050 SDLoc dl(Op);
Evan Chenge19aa5c2010-04-19 19:29:22 +00001051 SDNode *N = Op.getNode();
1052 LoadSDNode *LD = cast<LoadSDNode>(N);
Evan Chenge8136902010-04-27 19:48:13 +00001053 EVT MemVT = LD->getMemoryVT();
1054 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
Owen Andersonb2c80da2011-02-25 21:41:48 +00001055 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
Eric Christopherd9e8eac2010-12-09 04:48:06 +00001056 : ISD::EXTLOAD)
Evan Chenge8136902010-04-27 19:48:13 +00001057 : LD->getExtensionType();
Stuart Hastings81c43062011-02-16 16:23:55 +00001058 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
Evan Chenge19aa5c2010-04-19 19:29:22 +00001059 LD->getChain(), LD->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00001060 MemVT, LD->getMemOperand());
Evan Chenge19aa5c2010-04-19 19:29:22 +00001061 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1062
Evan Cheng0abb54d2010-04-24 04:43:44 +00001063 DEBUG(dbgs() << "\nPromoting ";
Evan Chenge19aa5c2010-04-19 19:29:22 +00001064 N->dump(&DAG);
Evan Cheng0abb54d2010-04-24 04:43:44 +00001065 dbgs() << "\nTo: ";
Evan Chenge19aa5c2010-04-19 19:29:22 +00001066 Result.getNode()->dump(&DAG);
1067 dbgs() << '\n');
1068 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001069 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1070 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
Evan Chenge19aa5c2010-04-19 19:29:22 +00001071 removeFromWorkList(N);
1072 DAG.DeleteNode(N);
Evan Chenge8136902010-04-27 19:48:13 +00001073 AddToWorkList(Result.getNode());
Evan Chenge19aa5c2010-04-19 19:29:22 +00001074 return true;
1075 }
1076 return false;
1077}
1078
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001079
Chris Lattnere49c9742007-05-14 22:04:50 +00001080//===----------------------------------------------------------------------===//
1081// Main DAG Combiner implementation
1082//===----------------------------------------------------------------------===//
1083
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001084void DAGCombiner::Run(CombineLevel AtLevel) {
1085 // set the instance variables, so that the various visit routines may use it.
1086 Level = AtLevel;
Eli Friedman9d448e42011-11-12 00:35:34 +00001087 LegalOperations = Level >= AfterLegalizeVectorOps;
1088 LegalTypes = Level >= AfterLegalizeTypes;
Nate Begeman2504fe22005-09-01 23:24:04 +00001089
Evan Cheng5e7658c2008-08-29 22:21:44 +00001090 // Add all the dag nodes to the worklist.
Evan Cheng5e7658c2008-08-29 22:21:44 +00001091 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1092 E = DAG.allnodes_end(); I != E; ++I)
James Molloy67b6b112012-02-16 09:17:04 +00001093 AddToWorkList(I);
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001094
Evan Cheng5e7658c2008-08-29 22:21:44 +00001095 // Create a dummy node (which is not added to allnodes), that adds a reference
1096 // to the root node, preventing it from being deleted, and tracking any
1097 // changes of the root.
1098 HandleSDNode Dummy(DAG.getRoot());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001099
Jim Laskeye7d2c242006-10-17 19:33:52 +00001100 // The root of the dag may dangle to deleted nodes until the dag combiner is
1101 // done. Set it to null to avoid confusion.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001102 DAG.setRoot(SDValue());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001103
James Molloy67b6b112012-02-16 09:17:04 +00001104 // while the worklist isn't empty, find a node and
Evan Cheng5e7658c2008-08-29 22:21:44 +00001105 // try and combine it.
James Molloy67b6b112012-02-16 09:17:04 +00001106 while (!WorkListContents.empty()) {
1107 SDNode *N;
Jack Carterd4e96152013-10-17 01:34:33 +00001108 // The WorkListOrder holds the SDNodes in order, but it may contain
1109 // duplicates.
James Molloy67b6b112012-02-16 09:17:04 +00001110 // In order to avoid a linear scan, we use a set (O(log N)) to hold what the
1111 // worklist *should* contain, and check the node we want to visit is should
1112 // actually be visited.
1113 do {
Benjamin Kramere1e549d2012-03-10 00:23:58 +00001114 N = WorkListOrder.pop_back_val();
James Molloy67b6b112012-02-16 09:17:04 +00001115 } while (!WorkListContents.erase(N));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001116
Evan Cheng5e7658c2008-08-29 22:21:44 +00001117 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1118 // N is deleted from the DAG, since they too may now be dead or may have a
1119 // reduced number of uses, allowing other xforms.
1120 if (N->use_empty() && N != &Dummy) {
1121 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1122 AddToWorkList(N->getOperand(i).getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001123
Evan Cheng5e7658c2008-08-29 22:21:44 +00001124 DAG.DeleteNode(N);
1125 continue;
Nate Begeman21158fc2005-09-01 00:19:25 +00001126 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001127
Evan Cheng5e7658c2008-08-29 22:21:44 +00001128 SDValue RV = combine(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001129
Craig Topperc0196b12014-04-14 00:51:57 +00001130 if (!RV.getNode())
Evan Cheng5e7658c2008-08-29 22:21:44 +00001131 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001132
Evan Cheng5e7658c2008-08-29 22:21:44 +00001133 ++NodesCombined;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001134
Evan Cheng5e7658c2008-08-29 22:21:44 +00001135 // If we get back the same node we passed in, rather than a new node or
1136 // zero, we know that the node must have defined multiple values and
Scott Michelcf0da6c2009-02-17 22:15:04 +00001137 // CombineTo was used. Since CombineTo takes care of the worklist
Evan Cheng5e7658c2008-08-29 22:21:44 +00001138 // mechanics for us, we have no work to do in this case.
1139 if (RV.getNode() == N)
1140 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001141
Evan Cheng5e7658c2008-08-29 22:21:44 +00001142 assert(N->getOpcode() != ISD::DELETED_NODE &&
1143 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1144 "Node was deleted but visit returned new node!");
Chris Lattner8f872d22006-05-27 00:43:02 +00001145
Wesley Peck527da1b2010-11-23 03:31:01 +00001146 DEBUG(dbgs() << "\nReplacing.3 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00001147 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00001148 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00001149 RV.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00001150 dbgs() << '\n');
Eric Christopherd6300d22011-07-14 01:12:15 +00001151
Devang Patelefec7712011-05-23 22:04:42 +00001152 // Transfer debug value.
1153 DAG.TransferDbgValues(SDValue(N, 0), RV);
Evan Cheng5e7658c2008-08-29 22:21:44 +00001154 WorkListRemover DeadNodes(*this);
1155 if (N->getNumValues() == RV.getNode()->getNumValues())
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001156 DAG.ReplaceAllUsesWith(N, RV.getNode());
Evan Cheng5e7658c2008-08-29 22:21:44 +00001157 else {
1158 assert(N->getValueType(0) == RV.getValueType() &&
1159 N->getNumValues() == 1 && "Type mismatch");
1160 SDValue OpV = RV;
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001161 DAG.ReplaceAllUsesWith(N, &OpV);
Evan Cheng5e7658c2008-08-29 22:21:44 +00001162 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001163
Evan Cheng5e7658c2008-08-29 22:21:44 +00001164 // Push the new node and any users onto the worklist
1165 AddToWorkList(RV.getNode());
1166 AddUsersToWorkList(RV.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001167
Evan Cheng5e7658c2008-08-29 22:21:44 +00001168 // Add any uses of the old node to the worklist in case this node is the
1169 // last one that uses them. They may become dead after this node is
1170 // deleted.
1171 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1172 AddToWorkList(N->getOperand(i).getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001173
Dan Gohmancd0b1bf2009-01-19 21:44:21 +00001174 // Finally, if the node is now dead, remove it from the graph. The node
1175 // may not be dead if the replacement process recursively simplified to
1176 // something else needing this node.
1177 if (N->use_empty()) {
1178 // Nodes can be reintroduced into the worklist. Make sure we do not
1179 // process a node that has been replaced.
1180 removeFromWorkList(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001181
Dan Gohmancd0b1bf2009-01-19 21:44:21 +00001182 // Finally, since the node is now dead, remove it from the graph.
1183 DAG.DeleteNode(N);
1184 }
Evan Cheng5e7658c2008-08-29 22:21:44 +00001185 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001186
Chris Lattner06f1d0f2005-10-05 06:35:28 +00001187 // If the root changed (e.g. it was a dead load, update the root).
1188 DAG.setRoot(Dummy.getValue());
Hal Finkele0cf6392012-04-16 03:33:22 +00001189 DAG.RemoveDeadNodes();
Nate Begeman21158fc2005-09-01 00:19:25 +00001190}
1191
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001192SDValue DAGCombiner::visit(SDNode *N) {
Evan Chengf1005572010-04-28 07:10:39 +00001193 switch (N->getOpcode()) {
Nate Begeman21158fc2005-09-01 00:19:25 +00001194 default: break;
Nate Begemane8f78d12005-09-01 00:33:32 +00001195 case ISD::TokenFactor: return visitTokenFactor(N);
Chris Lattneree322b42008-02-13 07:25:05 +00001196 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001197 case ISD::ADD: return visitADD(N);
1198 case ISD::SUB: return visitSUB(N);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001199 case ISD::ADDC: return visitADDC(N);
Craig Topper43a1bd62012-01-07 09:06:39 +00001200 case ISD::SUBC: return visitSUBC(N);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001201 case ISD::ADDE: return visitADDE(N);
Craig Topper43a1bd62012-01-07 09:06:39 +00001202 case ISD::SUBE: return visitSUBE(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001203 case ISD::MUL: return visitMUL(N);
1204 case ISD::SDIV: return visitSDIV(N);
1205 case ISD::UDIV: return visitUDIV(N);
1206 case ISD::SREM: return visitSREM(N);
1207 case ISD::UREM: return visitUREM(N);
1208 case ISD::MULHU: return visitMULHU(N);
1209 case ISD::MULHS: return visitMULHS(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001210 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1211 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00001212 case ISD::SMULO: return visitSMULO(N);
1213 case ISD::UMULO: return visitUMULO(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001214 case ISD::SDIVREM: return visitSDIVREM(N);
1215 case ISD::UDIVREM: return visitUDIVREM(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001216 case ISD::AND: return visitAND(N);
1217 case ISD::OR: return visitOR(N);
1218 case ISD::XOR: return visitXOR(N);
1219 case ISD::SHL: return visitSHL(N);
1220 case ISD::SRA: return visitSRA(N);
1221 case ISD::SRL: return visitSRL(N);
Adam Nemet7f928f12014-03-07 23:56:30 +00001222 case ISD::ROTR:
1223 case ISD::ROTL: return visitRotate(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001224 case ISD::CTLZ: return visitCTLZ(N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00001225 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001226 case ISD::CTTZ: return visitCTTZ(N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00001227 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001228 case ISD::CTPOP: return visitCTPOP(N);
Nate Begeman24a7eca2005-09-16 00:54:12 +00001229 case ISD::SELECT: return visitSELECT(N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00001230 case ISD::VSELECT: return visitVSELECT(N);
Nate Begeman24a7eca2005-09-16 00:54:12 +00001231 case ISD::SELECT_CC: return visitSELECT_CC(N);
1232 case ISD::SETCC: return visitSETCC(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001233 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1234 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
Chris Lattner812646a2006-05-05 05:58:59 +00001235 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001236 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1237 case ISD::TRUNCATE: return visitTRUNCATE(N);
Wesley Peck527da1b2010-11-23 03:31:01 +00001238 case ISD::BITCAST: return visitBITCAST(N);
Evan Chengb980f6f2008-05-12 23:04:07 +00001239 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
Chris Lattner6f3b5772005-09-28 22:28:18 +00001240 case ISD::FADD: return visitFADD(N);
1241 case ISD::FSUB: return visitFSUB(N);
1242 case ISD::FMUL: return visitFMUL(N);
Owen Anderson41b06652012-05-02 22:17:40 +00001243 case ISD::FMA: return visitFMA(N);
Chris Lattner6f3b5772005-09-28 22:28:18 +00001244 case ISD::FDIV: return visitFDIV(N);
1245 case ISD::FREM: return visitFREM(N);
Chris Lattner3bc40502006-03-05 05:30:57 +00001246 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001247 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1248 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1249 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1250 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1251 case ISD::FP_ROUND: return visitFP_ROUND(N);
1252 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1253 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1254 case ISD::FNEG: return visitFNEG(N);
1255 case ISD::FABS: return visitFABS(N);
Owen Andersona40319b2012-08-13 23:32:49 +00001256 case ISD::FFLOOR: return visitFFLOOR(N);
1257 case ISD::FCEIL: return visitFCEIL(N);
1258 case ISD::FTRUNC: return visitFTRUNC(N);
Nate Begemanc760f802005-09-19 22:34:01 +00001259 case ISD::BRCOND: return visitBRCOND(N);
Nate Begemanc760f802005-09-19 22:34:01 +00001260 case ISD::BR_CC: return visitBR_CC(N);
Chris Lattnere260ed82005-10-10 22:04:48 +00001261 case ISD::LOAD: return visitLOAD(N);
Chris Lattner04c73702005-10-10 22:31:19 +00001262 case ISD::STORE: return visitSTORE(N);
Chris Lattner5336a592006-03-19 01:27:56 +00001263 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
Evan Cheng0de312d2007-10-06 08:19:55 +00001264 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
Dan Gohmana8665142007-06-25 16:23:39 +00001265 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1266 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +00001267 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
Chris Lattnera46dfe82006-03-28 22:11:53 +00001268 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
Manman Ren413a6cb2014-01-31 01:10:35 +00001269 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
Nate Begeman21158fc2005-09-01 00:19:25 +00001270 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001271 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001272}
1273
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001274SDValue DAGCombiner::combine(SDNode *N) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001275 SDValue RV = visit(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001276
1277 // If nothing happened, try a target-specific DAG combine.
Craig Topperc0196b12014-04-14 00:51:57 +00001278 if (!RV.getNode()) {
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001279 assert(N->getOpcode() != ISD::DELETED_NODE &&
1280 "Node was deleted but visit returned NULL!");
1281
1282 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1283 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1284
1285 // Expose the DAG combiner to the target combiner impls.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001286 TargetLowering::DAGCombinerInfo
Nadav Rotemb1dd5242012-12-27 06:47:41 +00001287 DagCombineInfo(DAG, Level, false, this);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001288
1289 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1290 }
1291 }
1292
Evan Chengf1005572010-04-28 07:10:39 +00001293 // If nothing happened still, try promoting the operation.
Craig Topperc0196b12014-04-14 00:51:57 +00001294 if (!RV.getNode()) {
Evan Chengf1005572010-04-28 07:10:39 +00001295 switch (N->getOpcode()) {
1296 default: break;
1297 case ISD::ADD:
1298 case ISD::SUB:
1299 case ISD::MUL:
1300 case ISD::AND:
1301 case ISD::OR:
1302 case ISD::XOR:
1303 RV = PromoteIntBinOp(SDValue(N, 0));
1304 break;
1305 case ISD::SHL:
1306 case ISD::SRA:
1307 case ISD::SRL:
1308 RV = PromoteIntShiftOp(SDValue(N, 0));
1309 break;
1310 case ISD::SIGN_EXTEND:
1311 case ISD::ZERO_EXTEND:
1312 case ISD::ANY_EXTEND:
1313 RV = PromoteExtend(SDValue(N, 0));
1314 break;
1315 case ISD::LOAD:
1316 if (PromoteLoad(SDValue(N, 0)))
1317 RV = SDValue(N, 0);
1318 break;
1319 }
1320 }
1321
Scott Michelcf0da6c2009-02-17 22:15:04 +00001322 // If N is a commutative binary node, try commuting it to enable more
Evan Cheng31604a62008-03-22 01:55:50 +00001323 // sdisel CSE.
Craig Topperc0196b12014-04-14 00:51:57 +00001324 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
Evan Cheng31604a62008-03-22 01:55:50 +00001325 N->getNumValues() == 1) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001326 SDValue N0 = N->getOperand(0);
1327 SDValue N1 = N->getOperand(1);
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001328
Evan Cheng31604a62008-03-22 01:55:50 +00001329 // Constant operands are canonicalized to RHS.
1330 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001331 SDValue Ops[] = { N1, N0 };
Evan Cheng31604a62008-03-22 01:55:50 +00001332 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1333 Ops, 2);
Evan Chengfe7610f2008-03-24 23:55:16 +00001334 if (CSENode)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001335 return SDValue(CSENode, 0);
Evan Cheng31604a62008-03-22 01:55:50 +00001336 }
1337 }
1338
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001339 return RV;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001340}
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001341
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001342/// getInputChainForNode - Given a node, return its input chain if it has one,
1343/// otherwise return a null sd operand.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001344static SDValue getInputChainForNode(SDNode *N) {
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001345 if (unsigned NumOps = N->getNumOperands()) {
Owen Anderson9f944592009-08-11 20:47:22 +00001346 if (N->getOperand(0).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001347 return N->getOperand(0);
Stephen Lin8e8424e2013-07-09 00:44:49 +00001348 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001349 return N->getOperand(NumOps-1);
1350 for (unsigned i = 1; i < NumOps-1; ++i)
Owen Anderson9f944592009-08-11 20:47:22 +00001351 if (N->getOperand(i).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001352 return N->getOperand(i);
1353 }
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001354 return SDValue();
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001355}
1356
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001357SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001358 // If N has two operands, where one has an input chain equal to the other,
1359 // the 'other' chain is redundant.
1360 if (N->getNumOperands() == 2) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00001361 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001362 return N->getOperand(0);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001363 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001364 return N->getOperand(1);
1365 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001366
Chris Lattner48fb92f2007-05-16 06:37:59 +00001367 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001368 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001369 SmallPtrSet<SDNode*, 16> SeenOps;
Chris Lattner48fb92f2007-05-16 06:37:59 +00001370 bool Changed = false; // If we should replace this token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001371
Jim Laskey708d0db2006-10-04 16:53:27 +00001372 // Start out with this token factor.
Jim Laskeyd07be232006-09-25 16:29:54 +00001373 TFs.push_back(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001374
Jim Laskey0463e082006-10-07 23:37:56 +00001375 // Iterate through token factors. The TFs grows when new token factors are
Jim Laskey6549d222006-10-05 15:07:25 +00001376 // encountered.
1377 for (unsigned i = 0; i < TFs.size(); ++i) {
1378 SDNode *TF = TFs[i];
Scott Michelcf0da6c2009-02-17 22:15:04 +00001379
Jim Laskey708d0db2006-10-04 16:53:27 +00001380 // Check each of the operands.
1381 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001382 SDValue Op = TF->getOperand(i);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001383
Jim Laskey708d0db2006-10-04 16:53:27 +00001384 switch (Op.getOpcode()) {
1385 case ISD::EntryToken:
Jim Laskey6549d222006-10-05 15:07:25 +00001386 // Entry tokens don't need to be added to the list. They are
1387 // rededundant.
1388 Changed = true;
Jim Laskey708d0db2006-10-04 16:53:27 +00001389 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001390
Jim Laskey708d0db2006-10-04 16:53:27 +00001391 case ISD::TokenFactor:
Nate Begeman879d8f12009-09-15 00:18:30 +00001392 if (Op.hasOneUse() &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00001393 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
Jim Laskey708d0db2006-10-04 16:53:27 +00001394 // Queue up for processing.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001395 TFs.push_back(Op.getNode());
Jim Laskey708d0db2006-10-04 16:53:27 +00001396 // Clean up in case the token factor is removed.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001397 AddToWorkList(Op.getNode());
Jim Laskey708d0db2006-10-04 16:53:27 +00001398 Changed = true;
1399 break;
Jim Laskeyd07be232006-09-25 16:29:54 +00001400 }
Jim Laskey708d0db2006-10-04 16:53:27 +00001401 // Fall thru
Scott Michelcf0da6c2009-02-17 22:15:04 +00001402
Jim Laskey708d0db2006-10-04 16:53:27 +00001403 default:
Chris Lattner48fb92f2007-05-16 06:37:59 +00001404 // Only add if it isn't already in the list.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001405 if (SeenOps.insert(Op.getNode()))
Jim Laskey6549d222006-10-05 15:07:25 +00001406 Ops.push_back(Op);
Chris Lattner48fb92f2007-05-16 06:37:59 +00001407 else
1408 Changed = true;
Jim Laskey708d0db2006-10-04 16:53:27 +00001409 break;
Jim Laskeyd07be232006-09-25 16:29:54 +00001410 }
1411 }
Jim Laskey708d0db2006-10-04 16:53:27 +00001412 }
Wesley Peck527da1b2010-11-23 03:31:01 +00001413
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001414 SDValue Result;
Jim Laskey708d0db2006-10-04 16:53:27 +00001415
1416 // If we've change things around then replace token factor.
1417 if (Changed) {
Dan Gohman70de4cb2008-01-29 13:02:09 +00001418 if (Ops.empty()) {
Jim Laskey708d0db2006-10-04 16:53:27 +00001419 // The entry token is the only possible outcome.
1420 Result = DAG.getEntryNode();
1421 } else {
1422 // New and improved token factor.
Andrew Trickef9de2a2013-05-25 02:42:55 +00001423 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N),
Owen Anderson9f944592009-08-11 20:47:22 +00001424 MVT::Other, &Ops[0], Ops.size());
Nate Begeman02b23c62005-10-13 03:11:28 +00001425 }
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001426
Jim Laskeydcf983c2006-10-13 23:32:28 +00001427 // Don't add users to work list.
1428 return CombineTo(N, Result, false);
Nate Begeman02b23c62005-10-13 03:11:28 +00001429 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001430
Jim Laskey708d0db2006-10-04 16:53:27 +00001431 return Result;
Nate Begeman21158fc2005-09-01 00:19:25 +00001432}
1433
Chris Lattneree322b42008-02-13 07:25:05 +00001434/// MERGE_VALUES can always be eliminated.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001435SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
Chris Lattneree322b42008-02-13 07:25:05 +00001436 WorkListRemover DeadNodes(*this);
Dan Gohman9d26c852009-08-10 23:43:19 +00001437 // Replacing results may cause a different MERGE_VALUES to suddenly
1438 // be CSE'd with N, and carry its uses with it. Iterate until no
1439 // uses remain, to ensure that the node can be safely deleted.
Pete Cooperfe5b84b2012-06-20 19:35:43 +00001440 // First add the users of this node to the work list so that they
1441 // can be tried again once they have new operands.
1442 AddUsersToWorkList(N);
Dan Gohman9d26c852009-08-10 23:43:19 +00001443 do {
1444 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001445 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
Dan Gohman9d26c852009-08-10 23:43:19 +00001446 } while (!N->use_empty());
Chris Lattneree322b42008-02-13 07:25:05 +00001447 removeFromWorkList(N);
1448 DAG.DeleteNode(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001449 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattneree322b42008-02-13 07:25:05 +00001450}
1451
Evan Cheng92011002007-01-19 17:51:44 +00001452static
Andrew Trickef9de2a2013-05-25 02:42:55 +00001453SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
Bill Wendlingcdd96132009-01-30 02:23:43 +00001454 SelectionDAG &DAG) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00001455 EVT VT = N0.getValueType();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001456 SDValue N00 = N0.getOperand(0);
1457 SDValue N01 = N0.getOperand(1);
Evan Cheng92011002007-01-19 17:51:44 +00001458 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
Bill Wendlingcdd96132009-01-30 02:23:43 +00001459
Gabor Greiff304a7a2008-08-28 21:40:38 +00001460 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
Evan Cheng92011002007-01-19 17:51:44 +00001461 isa<ConstantSDNode>(N00.getOperand(1))) {
Bill Wendlingcdd96132009-01-30 02:23:43 +00001462 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
Andrew Trickef9de2a2013-05-25 02:42:55 +00001463 N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1464 DAG.getNode(ISD::SHL, SDLoc(N00), VT,
Bill Wendlingcdd96132009-01-30 02:23:43 +00001465 N00.getOperand(0), N01),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001466 DAG.getNode(ISD::SHL, SDLoc(N01), VT,
Bill Wendlingcdd96132009-01-30 02:23:43 +00001467 N00.getOperand(1), N01));
1468 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
Evan Cheng92011002007-01-19 17:51:44 +00001469 }
Bill Wendlingcdd96132009-01-30 02:23:43 +00001470
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001471 return SDValue();
Evan Cheng92011002007-01-19 17:51:44 +00001472}
1473
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001474SDValue DAGCombiner::visitADD(SDNode *N) {
1475 SDValue N0 = N->getOperand(0);
1476 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001477 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1478 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001479 EVT VT = N0.getValueType();
Dan Gohmana8665142007-06-25 16:23:39 +00001480
1481 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00001482 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001483 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001484 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topperd8005db2012-12-10 08:12:29 +00001485
1486 // fold (add x, 0) -> x, vector edition
1487 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1488 return N0;
1489 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1490 return N1;
Dan Gohman80f9f072007-07-13 20:03:40 +00001491 }
Bill Wendling0864a752008-12-10 22:36:00 +00001492
Dan Gohman06563a82007-07-03 14:03:57 +00001493 // fold (add x, undef) -> undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00001494 if (N0.getOpcode() == ISD::UNDEF)
1495 return N0;
1496 if (N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00001497 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00001498 // fold (add c1, c2) -> c1+c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001499 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00001500 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00001501 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00001502 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001503 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001504 // fold (add x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001505 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00001506 return N0;
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001507 // fold (add Sym, c) -> Sym+c
1508 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001509 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001510 GA->getOpcode() == ISD::GlobalAddress)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001511 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001512 GA->getOffset() +
1513 (uint64_t)N1C->getSExtValue());
Chris Lattner3470b5d2006-01-12 20:22:43 +00001514 // fold ((c1-A)+c2) -> (c1+c2)-A
1515 if (N1C && N0.getOpcode() == ISD::SUB)
1516 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001517 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Dan Gohmanb72127a2008-03-13 22:13:53 +00001518 DAG.getConstant(N1C->getAPIntValue()+
1519 N0C->getAPIntValue(), VT),
Chris Lattner3470b5d2006-01-12 20:22:43 +00001520 N0.getOperand(1));
Nate Begeman22e251a2006-02-03 06:46:56 +00001521 // reassociate add
Andrew Trickef9de2a2013-05-25 02:42:55 +00001522 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00001523 if (RADD.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00001524 return RADD;
Nate Begeman21158fc2005-09-01 00:19:25 +00001525 // fold ((0-A) + B) -> B-A
1526 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1527 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001528 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
Nate Begeman21158fc2005-09-01 00:19:25 +00001529 // fold (A + (0-B)) -> A-B
1530 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1531 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001532 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
Chris Lattner6f3b5772005-09-28 22:28:18 +00001533 // fold (A+(B-A)) -> B
1534 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
Nate Begemand23739d2005-09-06 04:43:02 +00001535 return N1.getOperand(0);
Dale Johannesen73bc0ba2008-11-27 00:43:21 +00001536 // fold ((B-A)+A) -> B
1537 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1538 return N0.getOperand(0);
Dale Johannesen8c766702008-12-02 01:30:54 +00001539 // fold (A+(B-(A+C))) to (B-C)
1540 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001541 N0 == N1.getOperand(1).getOperand(0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001542 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
Dale Johannesen8c766702008-12-02 01:30:54 +00001543 N1.getOperand(1).getOperand(1));
Dale Johannesen8c766702008-12-02 01:30:54 +00001544 // fold (A+(B-(C+A))) to (B-C)
1545 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001546 N0 == N1.getOperand(1).getOperand(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001547 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
Dale Johannesen8c766702008-12-02 01:30:54 +00001548 N1.getOperand(1).getOperand(0));
Dale Johannesenee573fc2008-12-23 23:47:22 +00001549 // fold (A+((B-A)+or-C)) to (B+or-C)
Dale Johannesen54bdec22008-12-02 18:40:40 +00001550 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1551 N1.getOperand(0).getOpcode() == ISD::SUB &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001552 N0 == N1.getOperand(0).getOperand(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001553 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
Bill Wendlingc4423482009-01-30 02:31:17 +00001554 N1.getOperand(0).getOperand(0), N1.getOperand(1));
Dale Johannesen54bdec22008-12-02 18:40:40 +00001555
Dale Johannesen8c766702008-12-02 01:30:54 +00001556 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1557 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1558 SDValue N00 = N0.getOperand(0);
1559 SDValue N01 = N0.getOperand(1);
1560 SDValue N10 = N1.getOperand(0);
1561 SDValue N11 = N1.getOperand(1);
Bill Wendlingc4423482009-01-30 02:31:17 +00001562
1563 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001564 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1565 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1566 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
Dale Johannesen8c766702008-12-02 01:30:54 +00001567 }
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001568
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001569 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1570 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001571
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001572 // fold (a+b) -> (a|b) iff a and b share no bits.
Duncan Sands13237ac2008-06-06 12:08:01 +00001573 if (VT.isInteger() && !VT.isVector()) {
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001574 APInt LHSZero, LHSOne;
1575 APInt RHSZero, RHSOne;
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001576 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
Bill Wendlingc4423482009-01-30 02:31:17 +00001577
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001578 if (LHSZero.getBoolValue()) {
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001579 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001580
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001581 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1582 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
Owen Anderson60a46782014-01-31 00:51:43 +00001583 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1584 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1585 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1586 }
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001587 }
1588 }
Evan Chengeb99bd72006-11-06 08:14:30 +00001589
Evan Cheng92011002007-01-19 17:51:44 +00001590 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
Gabor Greiff304a7a2008-08-28 21:40:38 +00001591 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001592 SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001593 if (Result.getNode()) return Result;
Evan Cheng92011002007-01-19 17:51:44 +00001594 }
Gabor Greiff304a7a2008-08-28 21:40:38 +00001595 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001596 SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001597 if (Result.getNode()) return Result;
Evan Cheng92011002007-01-19 17:51:44 +00001598 }
1599
Dan Gohman954f4902010-01-19 23:30:49 +00001600 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1601 if (N1.getOpcode() == ISD::SHL &&
1602 N1.getOperand(0).getOpcode() == ISD::SUB)
1603 if (ConstantSDNode *C =
1604 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1605 if (C->getAPIntValue() == 0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001606 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1607 DAG.getNode(ISD::SHL, SDLoc(N), VT,
Dan Gohman954f4902010-01-19 23:30:49 +00001608 N1.getOperand(0).getOperand(1),
1609 N1.getOperand(1)));
1610 if (N0.getOpcode() == ISD::SHL &&
1611 N0.getOperand(0).getOpcode() == ISD::SUB)
1612 if (ConstantSDNode *C =
1613 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1614 if (C->getAPIntValue() == 0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001615 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1616 DAG.getNode(ISD::SHL, SDLoc(N), VT,
Dan Gohman954f4902010-01-19 23:30:49 +00001617 N0.getOperand(0).getOperand(1),
1618 N0.getOperand(1)));
1619
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001620 if (N1.getOpcode() == ISD::AND) {
1621 SDValue AndOp0 = N1.getOperand(0);
Wesley Peck527da1b2010-11-23 03:31:01 +00001622 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001623 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1624 unsigned DestBits = VT.getScalarType().getSizeInBits();
Wesley Peck527da1b2010-11-23 03:31:01 +00001625
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001626 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1627 // and similar xforms where the inner op is either ~0 or 0.
1628 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001629 SDLoc DL(N);
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001630 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1631 }
1632 }
1633
Benjamin Kramer1f4dfbb2010-12-22 23:17:45 +00001634 // add (sext i1), X -> sub X, (zext i1)
1635 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1636 N0.getOperand(0).getValueType() == MVT::i1 &&
1637 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001638 SDLoc DL(N);
Benjamin Kramer1f4dfbb2010-12-22 23:17:45 +00001639 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1640 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1641 }
1642
Evan Chengf1005572010-04-28 07:10:39 +00001643 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001644}
1645
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001646SDValue DAGCombiner::visitADDC(SDNode *N) {
1647 SDValue N0 = N->getOperand(0);
1648 SDValue N1 = N->getOperand(1);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001649 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1650 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001651 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001652
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001653 // If the flag result is dead, turn this into an ADD.
Craig Topper0515cd42012-01-07 18:31:09 +00001654 if (!N->hasAnyUseOfValue(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001655 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
Dale Johannesen5234d372009-06-02 03:12:52 +00001656 DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001657 SDLoc(N), MVT::Glue));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001658
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001659 // canonicalize constant to RHS.
Dan Gohmanb4e26372008-06-23 15:29:14 +00001660 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001661 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001662
Chris Lattner47206662007-03-04 20:40:38 +00001663 // fold (addc x, 0) -> x + no carry out
1664 if (N1C && N1C->isNullValue())
Dale Johannesen5234d372009-06-02 03:12:52 +00001665 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001666 SDLoc(N), MVT::Glue));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001667
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001668 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001669 APInt LHSZero, LHSOne;
1670 APInt RHSZero, RHSOne;
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001671 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
Bill Wendling61277572009-01-30 02:38:00 +00001672
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001673 if (LHSZero.getBoolValue()) {
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001674 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001675
Chris Lattner47206662007-03-04 20:40:38 +00001676 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1677 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001678 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001679 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
Dale Johannesen5234d372009-06-02 03:12:52 +00001680 DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001681 SDLoc(N), MVT::Glue));
Chris Lattner47206662007-03-04 20:40:38 +00001682 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001683
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001684 return SDValue();
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001685}
1686
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001687SDValue DAGCombiner::visitADDE(SDNode *N) {
1688 SDValue N0 = N->getOperand(0);
1689 SDValue N1 = N->getOperand(1);
1690 SDValue CarryIn = N->getOperand(2);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001691 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1692 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001693
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001694 // canonicalize constant to RHS
Dan Gohmanb4e26372008-06-23 15:29:14 +00001695 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001696 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
Bill Wendling61277572009-01-30 02:38:00 +00001697 N1, N0, CarryIn);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001698
Chris Lattner47206662007-03-04 20:40:38 +00001699 // fold (adde x, y, false) -> (addc x, y)
Dale Johannesen5234d372009-06-02 03:12:52 +00001700 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001701 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001702
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001703 return SDValue();
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001704}
1705
Eric Christophere5ca1e02011-02-16 04:50:12 +00001706// Since it may not be valid to emit a fold to zero for vector initializers
1707// check if we can before folding.
Andrew Trickef9de2a2013-05-25 02:42:55 +00001708static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
Hal Finkel6c29bd92013-07-09 17:02:45 +00001709 SelectionDAG &DAG,
1710 bool LegalOperations, bool LegalTypes) {
Stephen Lin8e8424e2013-07-09 00:44:49 +00001711 if (!VT.isVector())
Eric Christophere5ca1e02011-02-16 04:50:12 +00001712 return DAG.getConstant(0, VT);
Daniel Sandersb021c6f2013-11-25 11:14:43 +00001713 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1714 return DAG.getConstant(0, VT);
Eric Christophere5ca1e02011-02-16 04:50:12 +00001715 return SDValue();
1716}
1717
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001718SDValue DAGCombiner::visitSUB(SDNode *N) {
1719 SDValue N0 = N->getOperand(0);
1720 SDValue N1 = N->getOperand(1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001721 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1722 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
Craig Topperc0196b12014-04-14 00:51:57 +00001723 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
Eric Christopherd6300d22011-07-14 01:12:15 +00001724 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
Owen Anderson53aa7a92009-08-10 22:56:29 +00001725 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001726
Dan Gohmana8665142007-06-25 16:23:39 +00001727 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00001728 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001729 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001730 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topperd8005db2012-12-10 08:12:29 +00001731
1732 // fold (sub x, 0) -> x, vector edition
1733 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1734 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00001735 }
Bill Wendling0864a752008-12-10 22:36:00 +00001736
Chris Lattnereeb2bda2005-10-17 01:07:11 +00001737 // fold (sub x, x) -> 0
Eric Christopheref721412011-02-16 01:10:03 +00001738 // FIXME: Refactor this and xor and other similar operations together.
Eric Christophere5ca1e02011-02-16 04:50:12 +00001739 if (N0 == N1)
Hal Finkel6c29bd92013-07-09 17:02:45 +00001740 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
Nate Begeman21158fc2005-09-01 00:19:25 +00001741 // fold (sub c1, c2) -> c1-c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001742 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00001743 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
Chris Lattnerc38fb8e2005-10-11 06:07:15 +00001744 // fold (sub x, c) -> (add x, -c)
1745 if (N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001746 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
Dan Gohmanb72127a2008-03-13 22:13:53 +00001747 DAG.getConstant(-N1C->getAPIntValue(), VT));
Evan Cheng88b65bc2010-01-18 21:38:44 +00001748 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1749 if (N0C && N0C->isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001750 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
Benjamin Kramer65bb14d2011-01-29 12:34:05 +00001751 // fold A-(A-B) -> B
1752 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1753 return N1.getOperand(1);
Nate Begeman21158fc2005-09-01 00:19:25 +00001754 // fold (A+B)-A -> B
Chris Lattner6f3b5772005-09-28 22:28:18 +00001755 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
Nate Begemand23739d2005-09-06 04:43:02 +00001756 return N0.getOperand(1);
Nate Begeman21158fc2005-09-01 00:19:25 +00001757 // fold (A+B)-B -> A
Chris Lattner6f3b5772005-09-28 22:28:18 +00001758 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
Scott Michelcf0da6c2009-02-17 22:15:04 +00001759 return N0.getOperand(0);
Eric Christopherd6300d22011-07-14 01:12:15 +00001760 // fold C2-(A+C1) -> (C2-C1)-A
1761 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
Nadav Rotem841c9a82012-09-20 08:53:31 +00001762 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1763 VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00001764 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
Bill Wendlingd1634052012-07-19 00:04:14 +00001765 N1.getOperand(0));
Eric Christopherd6300d22011-07-14 01:12:15 +00001766 }
Dale Johannesenee573fc2008-12-23 23:47:22 +00001767 // fold ((A+(B+or-C))-B) -> A+or-C
Dale Johannesenf51dcef2008-12-16 22:13:49 +00001768 if (N0.getOpcode() == ISD::ADD &&
Dale Johannesenacc84e52008-12-23 23:01:27 +00001769 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1770 N0.getOperand(1).getOpcode() == ISD::ADD) &&
Dale Johannesenf51dcef2008-12-16 22:13:49 +00001771 N0.getOperand(1).getOperand(0) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001772 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001773 N0.getOperand(0), N0.getOperand(1).getOperand(1));
Dale Johannesenacc84e52008-12-23 23:01:27 +00001774 // fold ((A+(C+B))-B) -> A+C
1775 if (N0.getOpcode() == ISD::ADD &&
1776 N0.getOperand(1).getOpcode() == ISD::ADD &&
1777 N0.getOperand(1).getOperand(1) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001778 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001779 N0.getOperand(0), N0.getOperand(1).getOperand(0));
Dale Johannesend2a46852008-12-23 01:59:54 +00001780 // fold ((A-(B-C))-C) -> A-B
1781 if (N0.getOpcode() == ISD::SUB &&
1782 N0.getOperand(1).getOpcode() == ISD::SUB &&
1783 N0.getOperand(1).getOperand(1) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001784 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001785 N0.getOperand(0), N0.getOperand(1).getOperand(0));
Bill Wendling48ff08e2009-01-30 02:42:10 +00001786
Dan Gohman06563a82007-07-03 14:03:57 +00001787 // If either operand of a sub is undef, the result is undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00001788 if (N0.getOpcode() == ISD::UNDEF)
1789 return N0;
1790 if (N1.getOpcode() == ISD::UNDEF)
1791 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00001792
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001793 // If the relocation model supports it, consider symbol offsets.
1794 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001795 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001796 // fold (sub Sym, c) -> Sym-c
1797 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001798 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001799 GA->getOffset() -
1800 (uint64_t)N1C->getSExtValue());
1801 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1802 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1803 if (GA->getGlobal() == GB->getGlobal())
1804 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1805 VT);
1806 }
1807
Evan Chengf1005572010-04-28 07:10:39 +00001808 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001809}
1810
Craig Topper43a1bd62012-01-07 09:06:39 +00001811SDValue DAGCombiner::visitSUBC(SDNode *N) {
1812 SDValue N0 = N->getOperand(0);
1813 SDValue N1 = N->getOperand(1);
1814 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1815 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1816 EVT VT = N0.getValueType();
1817
1818 // If the flag result is dead, turn this into an SUB.
Craig Topper0515cd42012-01-07 18:31:09 +00001819 if (!N->hasAnyUseOfValue(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001820 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1821 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001822 MVT::Glue));
1823
1824 // fold (subc x, x) -> 0 + no borrow
1825 if (N0 == N1)
1826 return CombineTo(N, DAG.getConstant(0, VT),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001827 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001828 MVT::Glue));
1829
1830 // fold (subc x, 0) -> x + no borrow
1831 if (N1C && N1C->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001832 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001833 MVT::Glue));
1834
1835 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1836 if (N0C && N0C->isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001837 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1838 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001839 MVT::Glue));
1840
1841 return SDValue();
1842}
1843
1844SDValue DAGCombiner::visitSUBE(SDNode *N) {
1845 SDValue N0 = N->getOperand(0);
1846 SDValue N1 = N->getOperand(1);
1847 SDValue CarryIn = N->getOperand(2);
1848
1849 // fold (sube x, y, false) -> (subc x, y)
1850 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001851 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
Craig Topper43a1bd62012-01-07 09:06:39 +00001852
1853 return SDValue();
1854}
1855
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001856SDValue DAGCombiner::visitMUL(SDNode *N) {
1857 SDValue N0 = N->getOperand(0);
1858 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001859 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001860
Dan Gohman06563a82007-07-03 14:03:57 +00001861 // fold (mul x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00001862 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00001863 return DAG.getConstant(0, VT);
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001864
1865 bool N0IsConst = false;
1866 bool N1IsConst = false;
1867 APInt ConstValue0, ConstValue1;
1868 // fold vector ops
1869 if (VT.isVector()) {
1870 SDValue FoldedVOp = SimplifyVBinOp(N);
1871 if (FoldedVOp.getNode()) return FoldedVOp;
1872
1873 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1874 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1875 } else {
Craig Topperc0196b12014-04-14 00:51:57 +00001876 N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
Jack Carterd4e96152013-10-17 01:34:33 +00001877 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1878 : APInt();
Craig Topperc0196b12014-04-14 00:51:57 +00001879 N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
Jack Carterd4e96152013-10-17 01:34:33 +00001880 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1881 : APInt();
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001882 }
1883
Nate Begeman21158fc2005-09-01 00:19:25 +00001884 // fold (mul c1, c2) -> c1*c2
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001885 if (N0IsConst && N1IsConst)
1886 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1887
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00001888 // canonicalize constant to RHS
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001889 if (N0IsConst && !N1IsConst)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001890 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001891 // fold (mul x, 0) -> 0
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001892 if (N1IsConst && ConstValue1 == 0)
Nate Begemand23739d2005-09-06 04:43:02 +00001893 return N1;
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001894 // We require a splat of the entire scalar bit width for non-contiguous
1895 // bit patterns.
1896 bool IsFullSplat =
1897 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001898 // fold (mul x, 1) -> x
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001899 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001900 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00001901 // fold (mul x, -1) -> 0-x
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001902 if (N1IsConst && ConstValue1.isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001903 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001904 DAG.getConstant(0, VT), N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001905 // fold (mul x, (1 << c)) -> x << c
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001906 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001907 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001908 DAG.getConstant(ConstValue1.logBase2(),
Owen Andersonb2c80da2011-02-25 21:41:48 +00001909 getShiftAmountTy(N0.getValueType())));
Chris Lattnera70878d2005-10-30 06:41:49 +00001910 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001911 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001912 unsigned Log2Val = (-ConstValue1).logBase2();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001913 // FIXME: If the input is something that is easily negated (e.g. a
Chris Lattnera70878d2005-10-30 06:41:49 +00001914 // single-use add), we should put the negate there.
Andrew Trickef9de2a2013-05-25 02:42:55 +00001915 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001916 DAG.getConstant(0, VT),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001917 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
Owen Andersonb2c80da2011-02-25 21:41:48 +00001918 DAG.getConstant(Log2Val,
1919 getShiftAmountTy(N0.getValueType()))));
Chris Lattner4249b9a2009-03-09 20:22:18 +00001920 }
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001921
1922 APInt Val;
Chris Lattner324871e2006-03-01 03:44:24 +00001923 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
Stephen Lincfe7f352013-07-08 00:37:03 +00001924 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001925 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1926 isa<ConstantSDNode>(N0.getOperand(1)))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001927 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001928 N1, N0.getOperand(1));
Gabor Greiff304a7a2008-08-28 21:40:38 +00001929 AddToWorkList(C3.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00001930 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001931 N0.getOperand(0), C3);
Chris Lattner324871e2006-03-01 03:44:24 +00001932 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001933
Chris Lattner324871e2006-03-01 03:44:24 +00001934 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1935 // use.
1936 {
Craig Topperc0196b12014-04-14 00:51:57 +00001937 SDValue Sh(nullptr,0), Y(nullptr,0);
Chris Lattner324871e2006-03-01 03:44:24 +00001938 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
Stephen Lincfe7f352013-07-08 00:37:03 +00001939 if (N0.getOpcode() == ISD::SHL &&
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001940 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1941 isa<ConstantSDNode>(N0.getOperand(1))) &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00001942 N0.getNode()->hasOneUse()) {
Chris Lattner324871e2006-03-01 03:44:24 +00001943 Sh = N0; Y = N1;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001944 } else if (N1.getOpcode() == ISD::SHL &&
Gabor Greife12264b2008-08-30 19:29:20 +00001945 isa<ConstantSDNode>(N1.getOperand(1)) &&
1946 N1.getNode()->hasOneUse()) {
Chris Lattner324871e2006-03-01 03:44:24 +00001947 Sh = N1; Y = N0;
1948 }
Bill Wendlingb48dcf62009-01-30 02:49:26 +00001949
Gabor Greiff304a7a2008-08-28 21:40:38 +00001950 if (Sh.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001951 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001952 Sh.getOperand(0), Y);
Andrew Trickef9de2a2013-05-25 02:42:55 +00001953 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001954 Mul, Sh.getOperand(1));
Chris Lattner324871e2006-03-01 03:44:24 +00001955 }
1956 }
Bill Wendlingb48dcf62009-01-30 02:49:26 +00001957
Chris Lattnerf29f5202006-03-04 23:33:26 +00001958 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001959 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1960 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1961 isa<ConstantSDNode>(N0.getOperand(1))))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001962 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1963 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001964 N0.getOperand(0), N1),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001965 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001966 N0.getOperand(1), N1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001967
Nate Begeman22e251a2006-02-03 06:46:56 +00001968 // reassociate mul
Andrew Trickef9de2a2013-05-25 02:42:55 +00001969 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00001970 if (RMUL.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00001971 return RMUL;
Dan Gohmana8665142007-06-25 16:23:39 +00001972
Evan Chengf1005572010-04-28 07:10:39 +00001973 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001974}
1975
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001976SDValue DAGCombiner::visitSDIV(SDNode *N) {
1977 SDValue N0 = N->getOperand(0);
1978 SDValue N1 = N->getOperand(1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001979 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1980 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
Owen Anderson53aa7a92009-08-10 22:56:29 +00001981 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001982
Dan Gohmana8665142007-06-25 16:23:39 +00001983 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00001984 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001985 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001986 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00001987 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001988
Nate Begeman21158fc2005-09-01 00:19:25 +00001989 // fold (sdiv c1, c2) -> c1/c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001990 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00001991 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
Nate Begeman4dd38312005-10-21 00:02:42 +00001992 // fold (sdiv X, 1) -> X
Eli Friedmane9e356a2011-10-27 02:06:39 +00001993 if (N1C && N1C->getAPIntValue() == 1LL)
Nate Begeman4dd38312005-10-21 00:02:42 +00001994 return N0;
1995 // fold (sdiv X, -1) -> 0-X
1996 if (N1C && N1C->isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001997 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling5b663e72009-01-30 02:52:17 +00001998 DAG.getConstant(0, VT), N0);
Chris Lattner5bcd0dd82005-10-07 06:10:46 +00001999 // If we know the sign bits of both operands are zero, strength reduce to a
2000 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
Duncan Sands13237ac2008-06-06 12:08:01 +00002001 if (!VT.isVector()) {
Dan Gohman1f372ed2008-02-25 21:11:39 +00002002 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002003 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
Bill Wendling5b663e72009-01-30 02:52:17 +00002004 N0, N1);
Chris Lattner2ee91f42008-01-27 23:32:17 +00002005 }
Nate Begeman57b35672006-02-17 07:26:20 +00002006 // fold (sdiv X, pow2) -> simple ops after legalize
Eli Friedmanf9081a82011-12-07 03:55:52 +00002007 if (N1C && !N1C->isNullValue() &&
Eli Friedmane9e356a2011-10-27 02:06:39 +00002008 (N1C->getAPIntValue().isPowerOf2() ||
2009 (-N1C->getAPIntValue()).isPowerOf2())) {
Nate Begeman4dd38312005-10-21 00:02:42 +00002010 // If dividing by powers of two is cheap, then don't perform the following
2011 // fold.
2012 if (TLI.isPow2DivCheap())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002013 return SDValue();
Bill Wendling5b663e72009-01-30 02:52:17 +00002014
Eli Friedmane9e356a2011-10-27 02:06:39 +00002015 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
Bill Wendling5b663e72009-01-30 02:52:17 +00002016
Chris Lattner471627c2006-02-16 08:02:36 +00002017 // Splat the sign bit into the register
Andrew Trickef9de2a2013-05-25 02:42:55 +00002018 SDValue SGN = DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
Bill Wendling5b663e72009-01-30 02:52:17 +00002019 DAG.getConstant(VT.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002020 getShiftAmountTy(N0.getValueType())));
Gabor Greiff304a7a2008-08-28 21:40:38 +00002021 AddToWorkList(SGN.getNode());
Bill Wendling5b663e72009-01-30 02:52:17 +00002022
Chris Lattner471627c2006-02-16 08:02:36 +00002023 // Add (N0 < 0) ? abs2 - 1 : 0;
Andrew Trickef9de2a2013-05-25 02:42:55 +00002024 SDValue SRL = DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
Bill Wendling5b663e72009-01-30 02:52:17 +00002025 DAG.getConstant(VT.getSizeInBits() - lg2,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002026 getShiftAmountTy(SGN.getValueType())));
Andrew Trickef9de2a2013-05-25 02:42:55 +00002027 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002028 AddToWorkList(SRL.getNode());
2029 AddToWorkList(ADD.getNode()); // Divide by pow2
Andrew Trickef9de2a2013-05-25 02:42:55 +00002030 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002031 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
Bill Wendling5b663e72009-01-30 02:52:17 +00002032
Nate Begeman4dd38312005-10-21 00:02:42 +00002033 // If we're dividing by a positive value, we're done. Otherwise, we must
2034 // negate the result.
Eli Friedmane9e356a2011-10-27 02:06:39 +00002035 if (N1C->getAPIntValue().isNonNegative())
Nate Begeman4dd38312005-10-21 00:02:42 +00002036 return SRA;
Bill Wendling5b663e72009-01-30 02:52:17 +00002037
Gabor Greiff304a7a2008-08-28 21:40:38 +00002038 AddToWorkList(SRA.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002039 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling5b663e72009-01-30 02:52:17 +00002040 DAG.getConstant(0, VT), SRA);
Nate Begeman4dd38312005-10-21 00:02:42 +00002041 }
Bill Wendling5b663e72009-01-30 02:52:17 +00002042
Nate Begemanc6f067a2005-10-20 02:15:44 +00002043 // if integer divide is expensive and we satisfy the requirements, emit an
2044 // alternate sequence.
Eli Friedmane9e356a2011-10-27 02:06:39 +00002045 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002046 SDValue Op = BuildSDIV(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002047 if (Op.getNode()) return Op;
Nate Begemanc6f067a2005-10-20 02:15:44 +00002048 }
Dan Gohmana8665142007-06-25 16:23:39 +00002049
Dan Gohman06563a82007-07-03 14:03:57 +00002050 // undef / X -> 0
2051 if (N0.getOpcode() == ISD::UNDEF)
2052 return DAG.getConstant(0, VT);
2053 // X / undef -> undef
2054 if (N1.getOpcode() == ISD::UNDEF)
2055 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002056
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002057 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002058}
2059
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002060SDValue DAGCombiner::visitUDIV(SDNode *N) {
2061 SDValue N0 = N->getOperand(0);
2062 SDValue N1 = N->getOperand(1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002063 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
2064 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
Owen Anderson53aa7a92009-08-10 22:56:29 +00002065 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002066
Dan Gohmana8665142007-06-25 16:23:39 +00002067 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00002068 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002069 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002070 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00002071 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002072
Nate Begeman21158fc2005-09-01 00:19:25 +00002073 // fold (udiv c1, c2) -> c1/c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002074 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002075 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00002076 // fold (udiv x, (1 << c)) -> x >>u c
Dan Gohmanb72127a2008-03-13 22:13:53 +00002077 if (N1C && N1C->getAPIntValue().isPowerOf2())
Andrew Trickef9de2a2013-05-25 02:42:55 +00002078 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
Dan Gohmanb72127a2008-03-13 22:13:53 +00002079 DAG.getConstant(N1C->getAPIntValue().logBase2(),
Owen Andersonb2c80da2011-02-25 21:41:48 +00002080 getShiftAmountTy(N0.getValueType())));
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002081 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
Nate Begeman25d178b2006-02-05 07:20:23 +00002082 if (N1.getOpcode() == ISD::SHL) {
2083 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
Dan Gohmanb72127a2008-03-13 22:13:53 +00002084 if (SHC->getAPIntValue().isPowerOf2()) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00002085 EVT ADDVT = N1.getOperand(1).getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00002086 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
Bill Wendlingaff3e032009-01-30 02:55:25 +00002087 N1.getOperand(1),
2088 DAG.getConstant(SHC->getAPIntValue()
2089 .logBase2(),
2090 ADDVT));
Gabor Greiff304a7a2008-08-28 21:40:38 +00002091 AddToWorkList(Add.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002092 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
Nate Begeman25d178b2006-02-05 07:20:23 +00002093 }
2094 }
2095 }
Nate Begemanc6f067a2005-10-20 02:15:44 +00002096 // fold (udiv x, c) -> alternate
Dan Gohmanb72127a2008-03-13 22:13:53 +00002097 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002098 SDValue Op = BuildUDIV(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002099 if (Op.getNode()) return Op;
Chris Lattner9faa5b72005-10-22 18:50:15 +00002100 }
Dan Gohmana8665142007-06-25 16:23:39 +00002101
Dan Gohman06563a82007-07-03 14:03:57 +00002102 // undef / X -> 0
2103 if (N0.getOpcode() == ISD::UNDEF)
2104 return DAG.getConstant(0, VT);
2105 // X / undef -> undef
2106 if (N1.getOpcode() == ISD::UNDEF)
2107 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002108
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002109 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002110}
2111
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002112SDValue DAGCombiner::visitSREM(SDNode *N) {
2113 SDValue N0 = N->getOperand(0);
2114 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002115 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2116 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002117 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002118
Nate Begeman21158fc2005-09-01 00:19:25 +00002119 // fold (srem c1, c2) -> c1%c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002120 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002121 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
Nate Begeman6828ed92005-10-10 21:26:48 +00002122 // If we know the sign bits of both operands are zero, strength reduce to a
2123 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
Duncan Sands13237ac2008-06-06 12:08:01 +00002124 if (!VT.isVector()) {
Dan Gohman1f372ed2008-02-25 21:11:39 +00002125 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002126 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
Chris Lattnerd0496d02008-01-27 23:21:58 +00002127 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002128
Dan Gohman9a693412007-11-26 23:46:11 +00002129 // If X/C can be simplified by the division-by-constant logic, lower
2130 // X%C to the equivalent of X-X/C*C.
Chris Lattnerd0620d22006-10-12 20:58:32 +00002131 if (N1C && !N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002132 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002133 AddToWorkList(Div.getNode());
2134 SDValue OptimizedDiv = combine(Div.getNode());
2135 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002136 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendlingd033af02009-01-30 02:57:00 +00002137 OptimizedDiv, N1);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002138 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002139 AddToWorkList(Mul.getNode());
Dan Gohman9a693412007-11-26 23:46:11 +00002140 return Sub;
2141 }
Chris Lattnerd0620d22006-10-12 20:58:32 +00002142 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002143
Dan Gohman06563a82007-07-03 14:03:57 +00002144 // undef % X -> 0
2145 if (N0.getOpcode() == ISD::UNDEF)
2146 return DAG.getConstant(0, VT);
2147 // X % undef -> undef
2148 if (N1.getOpcode() == ISD::UNDEF)
2149 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002150
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002151 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002152}
2153
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002154SDValue DAGCombiner::visitUREM(SDNode *N) {
2155 SDValue N0 = N->getOperand(0);
2156 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002157 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2158 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002159 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002160
Nate Begeman21158fc2005-09-01 00:19:25 +00002161 // fold (urem c1, c2) -> c1%c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002162 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002163 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
Nate Begeman6828ed92005-10-10 21:26:48 +00002164 // fold (urem x, pow2) -> (and x, pow2-1)
Dan Gohmanb72127a2008-03-13 22:13:53 +00002165 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
Andrew Trickef9de2a2013-05-25 02:42:55 +00002166 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
Dan Gohmanb72127a2008-03-13 22:13:53 +00002167 DAG.getConstant(N1C->getAPIntValue()-1,VT));
Nate Begemanc89fdf12006-02-05 07:36:48 +00002168 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2169 if (N1.getOpcode() == ISD::SHL) {
2170 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
Dan Gohmanb72127a2008-03-13 22:13:53 +00002171 if (SHC->getAPIntValue().isPowerOf2()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002172 SDValue Add =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002173 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
Duncan Sands13237ac2008-06-06 12:08:01 +00002174 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
Dan Gohmanb72127a2008-03-13 22:13:53 +00002175 VT));
Gabor Greiff304a7a2008-08-28 21:40:38 +00002176 AddToWorkList(Add.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002177 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
Nate Begemanc89fdf12006-02-05 07:36:48 +00002178 }
2179 }
2180 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002181
Dan Gohman9a693412007-11-26 23:46:11 +00002182 // If X/C can be simplified by the division-by-constant logic, lower
2183 // X%C to the equivalent of X-X/C*C.
Chris Lattnerd0620d22006-10-12 20:58:32 +00002184 if (N1C && !N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002185 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
Dan Gohman1df80f62008-09-08 16:59:01 +00002186 AddToWorkList(Div.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002187 SDValue OptimizedDiv = combine(Div.getNode());
2188 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002189 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendlingd033af02009-01-30 02:57:00 +00002190 OptimizedDiv, N1);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002191 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002192 AddToWorkList(Mul.getNode());
Dan Gohman9a693412007-11-26 23:46:11 +00002193 return Sub;
2194 }
Chris Lattnerd0620d22006-10-12 20:58:32 +00002195 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002196
Dan Gohman06563a82007-07-03 14:03:57 +00002197 // undef % X -> 0
2198 if (N0.getOpcode() == ISD::UNDEF)
2199 return DAG.getConstant(0, VT);
2200 // X % undef -> undef
2201 if (N1.getOpcode() == ISD::UNDEF)
2202 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002203
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002204 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002205}
2206
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002207SDValue DAGCombiner::visitMULHS(SDNode *N) {
2208 SDValue N0 = N->getOperand(0);
2209 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002210 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002211 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002212 SDLoc DL(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002213
Nate Begeman21158fc2005-09-01 00:19:25 +00002214 // fold (mulhs x, 0) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002215 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002216 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00002217 // fold (mulhs x, 1) -> (sra x, size(x)-1)
Dan Gohmanb72127a2008-03-13 22:13:53 +00002218 if (N1C && N1C->getAPIntValue() == 1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002219 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
Bill Wendlingfaed0652009-01-30 03:00:18 +00002220 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002221 getShiftAmountTy(N0.getValueType())));
Dan Gohman06563a82007-07-03 14:03:57 +00002222 // fold (mulhs x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002223 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00002224 return DAG.getConstant(0, VT);
Dan Gohmana8665142007-06-25 16:23:39 +00002225
Chris Lattner10bd29f2010-12-13 08:39:01 +00002226 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2227 // plus a shift.
2228 if (VT.isSimple() && !VT.isVector()) {
2229 MVT Simple = VT.getSimpleVT();
2230 unsigned SimpleSize = Simple.getSizeInBits();
2231 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2232 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2233 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2234 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2235 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
Chris Lattnerb86dcee2010-12-15 05:51:39 +00002236 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002237 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
Chris Lattner10bd29f2010-12-13 08:39:01 +00002238 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2239 }
2240 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002241
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002242 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002243}
2244
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002245SDValue DAGCombiner::visitMULHU(SDNode *N) {
2246 SDValue N0 = N->getOperand(0);
2247 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002248 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002249 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002250 SDLoc DL(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002251
Nate Begeman21158fc2005-09-01 00:19:25 +00002252 // fold (mulhu x, 0) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002253 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002254 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00002255 // fold (mulhu x, 1) -> 0
Dan Gohmanb72127a2008-03-13 22:13:53 +00002256 if (N1C && N1C->getAPIntValue() == 1)
Nate Begemand23739d2005-09-06 04:43:02 +00002257 return DAG.getConstant(0, N0.getValueType());
Dan Gohman06563a82007-07-03 14:03:57 +00002258 // fold (mulhu x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002259 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00002260 return DAG.getConstant(0, VT);
Dan Gohmana8665142007-06-25 16:23:39 +00002261
Chris Lattner10bd29f2010-12-13 08:39:01 +00002262 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2263 // plus a shift.
2264 if (VT.isSimple() && !VT.isVector()) {
2265 MVT Simple = VT.getSimpleVT();
2266 unsigned SimpleSize = Simple.getSizeInBits();
2267 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2268 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2269 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2270 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2271 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2272 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002273 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
Chris Lattner10bd29f2010-12-13 08:39:01 +00002274 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2275 }
2276 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002277
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002278 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002279}
2280
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002281/// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2282/// compute two values. LoOp and HiOp give the opcodes for the two computations
2283/// that are being performed. Return true if a simplification was made.
2284///
Scott Michelcf0da6c2009-02-17 22:15:04 +00002285SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002286 unsigned HiOp) {
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002287 // If the high half is not needed, just compute the low half.
Evan Chengece4c682007-11-08 09:25:29 +00002288 bool HiExists = N->hasAnyUseOfValue(1);
2289 if (!HiExists &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002290 (!LegalOperations ||
Owen Andersonfb00d5b2014-01-20 18:41:34 +00002291 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002292 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
Bill Wendling9b3407e2009-01-30 03:08:40 +00002293 N->op_begin(), N->getNumOperands());
Chris Lattner31e9edc2008-01-26 01:09:19 +00002294 return CombineTo(N, Res, Res);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002295 }
2296
2297 // If the low half is not needed, just compute the high half.
Evan Chengece4c682007-11-08 09:25:29 +00002298 bool LoExists = N->hasAnyUseOfValue(0);
2299 if (!LoExists &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002300 (!LegalOperations ||
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002301 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002302 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
Bill Wendling9b3407e2009-01-30 03:08:40 +00002303 N->op_begin(), N->getNumOperands());
Chris Lattner31e9edc2008-01-26 01:09:19 +00002304 return CombineTo(N, Res, Res);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002305 }
2306
Evan Chengece4c682007-11-08 09:25:29 +00002307 // If both halves are used, return as it is.
2308 if (LoExists && HiExists)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002309 return SDValue();
Evan Chengece4c682007-11-08 09:25:29 +00002310
2311 // If the two computed results can be simplified separately, separate them.
Evan Chengece4c682007-11-08 09:25:29 +00002312 if (LoExists) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002313 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
Bill Wendling9b3407e2009-01-30 03:08:40 +00002314 N->op_begin(), N->getNumOperands());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002315 AddToWorkList(Lo.getNode());
2316 SDValue LoOpt = combine(Lo.getNode());
2317 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002318 (!LegalOperations ||
Duncan Sands8651e9c2008-06-13 19:07:40 +00002319 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
Chris Lattner31e9edc2008-01-26 01:09:19 +00002320 return CombineTo(N, LoOpt, LoOpt);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002321 }
2322
Evan Chengece4c682007-11-08 09:25:29 +00002323 if (HiExists) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002324 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002325 N->op_begin(), N->getNumOperands());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002326 AddToWorkList(Hi.getNode());
2327 SDValue HiOpt = combine(Hi.getNode());
2328 if (HiOpt.getNode() && HiOpt != Hi &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002329 (!LegalOperations ||
Duncan Sands8651e9c2008-06-13 19:07:40 +00002330 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
Chris Lattner31e9edc2008-01-26 01:09:19 +00002331 return CombineTo(N, HiOpt, HiOpt);
Evan Chengece4c682007-11-08 09:25:29 +00002332 }
Bill Wendling9b3407e2009-01-30 03:08:40 +00002333
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002334 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002335}
2336
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002337SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2338 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002339 if (Res.getNode()) return Res;
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002340
Chris Lattner15090e12010-12-15 06:04:19 +00002341 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002342 SDLoc DL(N);
Chris Lattner15090e12010-12-15 06:04:19 +00002343
2344 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2345 // plus a shift.
2346 if (VT.isSimple() && !VT.isVector()) {
2347 MVT Simple = VT.getSimpleVT();
2348 unsigned SimpleSize = Simple.getSizeInBits();
2349 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2350 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2351 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2352 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2353 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2354 // Compute the high part as N1.
2355 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002356 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
Chris Lattner15090e12010-12-15 06:04:19 +00002357 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2358 // Compute the low part as N0.
2359 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2360 return CombineTo(N, Lo, Hi);
2361 }
2362 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002363
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002364 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002365}
2366
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002367SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2368 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002369 if (Res.getNode()) return Res;
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002370
Chris Lattner15090e12010-12-15 06:04:19 +00002371 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002372 SDLoc DL(N);
Owen Andersonb2c80da2011-02-25 21:41:48 +00002373
Chris Lattner15090e12010-12-15 06:04:19 +00002374 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2375 // plus a shift.
2376 if (VT.isSimple() && !VT.isVector()) {
2377 MVT Simple = VT.getSimpleVT();
2378 unsigned SimpleSize = Simple.getSizeInBits();
2379 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2380 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2381 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2382 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2383 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2384 // Compute the high part as N1.
2385 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002386 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
Chris Lattner15090e12010-12-15 06:04:19 +00002387 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2388 // Compute the low part as N0.
2389 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2390 return CombineTo(N, Lo, Hi);
2391 }
2392 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002393
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002394 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002395}
2396
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002397SDValue DAGCombiner::visitSMULO(SDNode *N) {
2398 // (smulo x, 2) -> (saddo x, x)
2399 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2400 if (C2->getAPIntValue() == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002401 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002402 N->getOperand(0), N->getOperand(0));
2403
2404 return SDValue();
2405}
2406
2407SDValue DAGCombiner::visitUMULO(SDNode *N) {
2408 // (umulo x, 2) -> (uaddo x, x)
2409 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2410 if (C2->getAPIntValue() == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002411 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002412 N->getOperand(0), N->getOperand(0));
2413
2414 return SDValue();
2415}
2416
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002417SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2418 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002419 if (Res.getNode()) return Res;
Scott Michelcf0da6c2009-02-17 22:15:04 +00002420
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002421 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002422}
2423
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002424SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2425 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002426 if (Res.getNode()) return Res;
Scott Michelcf0da6c2009-02-17 22:15:04 +00002427
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002428 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002429}
2430
Chris Lattner8d6fc202006-05-05 05:51:50 +00002431/// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2432/// two operands of the same opcode, try to simplify it.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002433SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2434 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002435 EVT VT = N0.getValueType();
Chris Lattner8d6fc202006-05-05 05:51:50 +00002436 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
Scott Michelcf0da6c2009-02-17 22:15:04 +00002437
Dan Gohmandd5286d2010-01-14 03:08:49 +00002438 // Bail early if none of these transforms apply.
2439 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2440
Chris Lattner002ee912006-05-05 06:31:05 +00002441 // For each of OP in AND/OR/XOR:
2442 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2443 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2444 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
Dan Gohman600f62b2010-06-24 14:30:44 +00002445 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
Nate Begeman9655f842009-12-03 07:11:29 +00002446 //
2447 // do not sink logical op inside of a vector extend, since it may combine
2448 // into a vsetcc.
Evan Cheng166a4e62010-01-06 19:38:29 +00002449 EVT Op0VT = N0.getOperand(0).getValueType();
2450 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
Dan Gohmanad3e5492009-04-08 00:15:30 +00002451 N0.getOpcode() == ISD::SIGN_EXTEND ||
Evan Chengf1bd5fc2010-04-17 06:13:15 +00002452 // Avoid infinite looping with PromoteIntBinOp.
2453 (N0.getOpcode() == ISD::ANY_EXTEND &&
2454 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
Dan Gohman600f62b2010-06-24 14:30:44 +00002455 (N0.getOpcode() == ISD::TRUNCATE &&
2456 (!TLI.isZExtFree(VT, Op0VT) ||
2457 !TLI.isTruncateFree(Op0VT, VT)) &&
2458 TLI.isTypeLegal(Op0VT))) &&
Nate Begeman9655f842009-12-03 07:11:29 +00002459 !VT.isVector() &&
Evan Cheng166a4e62010-01-06 19:38:29 +00002460 Op0VT == N1.getOperand(0).getValueType() &&
2461 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002462 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
Bill Wendling781db7a2009-01-30 19:25:47 +00002463 N0.getOperand(0).getValueType(),
2464 N0.getOperand(0), N1.getOperand(0));
Gabor Greiff304a7a2008-08-28 21:40:38 +00002465 AddToWorkList(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002466 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
Chris Lattner8d6fc202006-05-05 05:51:50 +00002467 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002468
Chris Lattner5ac42932006-05-05 06:10:43 +00002469 // For each of OP in SHL/SRL/SRA/AND...
2470 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2471 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2472 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
Chris Lattner8d6fc202006-05-05 05:51:50 +00002473 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
Chris Lattner5ac42932006-05-05 06:10:43 +00002474 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
Chris Lattner8d6fc202006-05-05 05:51:50 +00002475 N0.getOperand(1) == N1.getOperand(1)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002476 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
Bill Wendling781db7a2009-01-30 19:25:47 +00002477 N0.getOperand(0).getValueType(),
2478 N0.getOperand(0), N1.getOperand(0));
Gabor Greiff304a7a2008-08-28 21:40:38 +00002479 AddToWorkList(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002480 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Bill Wendling781db7a2009-01-30 19:25:47 +00002481 ORNode, N0.getOperand(1));
Chris Lattner8d6fc202006-05-05 05:51:50 +00002482 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002483
Nadav Rotemb0783502012-04-01 19:31:22 +00002484 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2485 // Only perform this optimization after type legalization and before
2486 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2487 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2488 // we don't want to undo this promotion.
2489 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2490 // on scalars.
Nadav Rotem841c9a82012-09-20 08:53:31 +00002491 if ((N0.getOpcode() == ISD::BITCAST ||
2492 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2493 Level == AfterLegalizeTypes) {
Nadav Rotemb0783502012-04-01 19:31:22 +00002494 SDValue In0 = N0.getOperand(0);
2495 SDValue In1 = N1.getOperand(0);
2496 EVT In0Ty = In0.getValueType();
2497 EVT In1Ty = In1.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00002498 SDLoc DL(N);
Nadav Rotem841c9a82012-09-20 08:53:31 +00002499 // If both incoming values are integers, and the original types are the
2500 // same.
Nadav Rotemb0783502012-04-01 19:31:22 +00002501 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
Nadav Rotem841c9a82012-09-20 08:53:31 +00002502 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2503 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
Nadav Rotemb0783502012-04-01 19:31:22 +00002504 AddToWorkList(Op.getNode());
2505 return BC;
2506 }
2507 }
2508
2509 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2510 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2511 // If both shuffles use the same mask, and both shuffle within a single
2512 // vector, then it is worthwhile to move the swizzle after the operation.
2513 // The type-legalizer generates this pattern when loading illegal
2514 // vector types from memory. In many cases this allows additional shuffle
2515 // optimizations.
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002516 // There are other cases where moving the shuffle after the xor/and/or
2517 // is profitable even if shuffles don't perform a swizzle.
2518 // If both shuffles use the same mask, and both shuffles have the same first
2519 // or second operand, then it might still be profitable to move the shuffle
2520 // after the xor/and/or operation.
2521 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
Nadav Rotemb0783502012-04-01 19:31:22 +00002522 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2523 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
Craig Topper9c3da312012-04-09 07:19:09 +00002524
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002525 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
Craig Topper9c3da312012-04-09 07:19:09 +00002526 "Inputs to shuffles are not the same type");
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002527
Nadav Rotemb0783502012-04-01 19:31:22 +00002528 // Check that both shuffles use the same mask. The masks are known to be of
2529 // the same length because the result vector type is the same.
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002530 // Check also that shuffles have only one use to avoid introducing extra
2531 // instructions.
2532 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2533 SVN0->getMask().equals(SVN1->getMask())) {
2534 SDValue ShOp = N0->getOperand(1);
Nadav Rotemb0783502012-04-01 19:31:22 +00002535
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002536 // Don't try to fold this node if it requires introducing a
2537 // build vector of all zeros that might be illegal at this stage.
2538 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2539 if (!LegalTypes)
2540 ShOp = DAG.getConstant(0, VT);
2541 else
2542 ShOp = SDValue();
2543 }
2544
2545 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2546 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2547 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2548 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2549 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2550 N0->getOperand(0), N1->getOperand(0));
2551 AddToWorkList(NewNode.getNode());
2552 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2553 &SVN0->getMask()[0]);
2554 }
2555
2556 // Don't try to fold this node if it requires introducing a
2557 // build vector of all zeros that might be illegal at this stage.
2558 ShOp = N0->getOperand(0);
2559 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2560 if (!LegalTypes)
2561 ShOp = DAG.getConstant(0, VT);
2562 else
2563 ShOp = SDValue();
2564 }
2565
2566 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2567 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2568 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2569 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2570 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2571 N0->getOperand(1), N1->getOperand(1));
2572 AddToWorkList(NewNode.getNode());
2573 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2574 &SVN0->getMask()[0]);
2575 }
Nadav Rotemb0783502012-04-01 19:31:22 +00002576 }
2577 }
Craig Topper9c3da312012-04-09 07:19:09 +00002578
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002579 return SDValue();
Chris Lattner8d6fc202006-05-05 05:51:50 +00002580}
2581
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002582SDValue DAGCombiner::visitAND(SDNode *N) {
2583 SDValue N0 = N->getOperand(0);
2584 SDValue N1 = N->getOperand(1);
2585 SDValue LL, LR, RL, RR, CC0, CC1;
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002586 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2587 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002588 EVT VT = N1.getValueType();
Dan Gohmane14c4082010-03-04 00:23:16 +00002589 unsigned BitWidth = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00002590
Dan Gohmana8665142007-06-25 16:23:39 +00002591 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00002592 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002593 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002594 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00002595
2596 // fold (and x, 0) -> 0, vector edition
2597 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2598 return N0;
2599 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2600 return N1;
2601
2602 // fold (and x, -1) -> x, vector edition
2603 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2604 return N1;
2605 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2606 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00002607 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002608
Dan Gohman06563a82007-07-03 14:03:57 +00002609 // fold (and x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002610 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00002611 return DAG.getConstant(0, VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00002612 // fold (and c1, c2) -> c1&c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002613 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00002614 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00002615 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00002616 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002617 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00002618 // fold (and x, -1) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002619 if (N1C && N1C->isAllOnesValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002620 return N0;
2621 // if (and x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002622 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1f372ed2008-02-25 21:11:39 +00002623 APInt::getAllOnesValue(BitWidth)))
Nate Begemand23739d2005-09-06 04:43:02 +00002624 return DAG.getConstant(0, VT);
Nate Begeman22e251a2006-02-03 06:46:56 +00002625 // reassociate and
Andrew Trickef9de2a2013-05-25 02:42:55 +00002626 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00002627 if (RAND.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00002628 return RAND;
Bill Wendlingaf13d822010-03-03 00:35:56 +00002629 // fold (and (or x, C), D) -> D if (C & D) == D
Nate Begemanee065282005-11-02 18:42:59 +00002630 if (N1C && N0.getOpcode() == ISD::OR)
Nate Begeman21158fc2005-09-01 00:19:25 +00002631 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
Dan Gohmanb72127a2008-03-13 22:13:53 +00002632 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002633 return N1;
Chris Lattner49beaf42006-02-02 07:17:31 +00002634 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2635 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002636 SDValue N0Op0 = N0.getOperand(0);
Dan Gohman1f372ed2008-02-25 21:11:39 +00002637 APInt Mask = ~N1C->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00002638 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
Dan Gohman1f372ed2008-02-25 21:11:39 +00002639 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002640 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
Bill Wendling86171912009-01-30 20:43:18 +00002641 N0.getValueType(), N0Op0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002642
Chris Lattner0db2f2c2006-03-01 21:47:21 +00002643 // Replace uses of the AND with uses of the Zero extend node.
2644 CombineTo(N, Zext);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002645
Chris Lattner49beaf42006-02-02 07:17:31 +00002646 // We actually want to replace all uses of the any_extend with the
2647 // zero_extend, to avoid duplicating things. This will later cause this
2648 // AND to be folded.
Gabor Greiff304a7a2008-08-28 21:40:38 +00002649 CombineTo(N0.getNode(), Zext);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002650 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattner49beaf42006-02-02 07:17:31 +00002651 }
2652 }
Stephen Lincfe7f352013-07-08 00:37:03 +00002653 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
James Molloy862fe492012-02-20 12:02:38 +00002654 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2655 // already be zero by virtue of the width of the base type of the load.
2656 //
2657 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2658 // more cases.
2659 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2660 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2661 N0.getOpcode() == ISD::LOAD) {
2662 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2663 N0 : N0.getOperand(0) );
2664
2665 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2666 // This can be a pure constant or a vector splat, in which case we treat the
2667 // vector as a scalar and use the splat value.
2668 APInt Constant = APInt::getNullValue(1);
2669 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2670 Constant = C->getAPIntValue();
2671 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2672 APInt SplatValue, SplatUndef;
2673 unsigned SplatBitSize;
2674 bool HasAnyUndefs;
2675 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2676 SplatBitSize, HasAnyUndefs);
2677 if (IsSplat) {
2678 // Undef bits can contribute to a possible optimisation if set, so
2679 // set them.
2680 SplatValue |= SplatUndef;
2681
2682 // The splat value may be something like "0x00FFFFFF", which means 0 for
2683 // the first vector value and FF for the rest, repeating. We need a mask
2684 // that will apply equally to all members of the vector, so AND all the
2685 // lanes of the constant together.
2686 EVT VT = Vector->getValueType(0);
2687 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
Silviu Baranga3f40d872012-09-05 08:57:21 +00002688
2689 // If the splat value has been compressed to a bitlength lower
2690 // than the size of the vector lane, we need to re-expand it to
2691 // the lane size.
2692 if (BitWidth > SplatBitSize)
2693 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2694 SplatBitSize < BitWidth;
2695 SplatBitSize = SplatBitSize * 2)
2696 SplatValue |= SplatValue.shl(SplatBitSize);
2697
James Molloy862fe492012-02-20 12:02:38 +00002698 Constant = APInt::getAllOnesValue(BitWidth);
Silviu Baranga3f40d872012-09-05 08:57:21 +00002699 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
James Molloy862fe492012-02-20 12:02:38 +00002700 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2701 }
2702 }
2703
2704 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2705 // actually legal and isn't going to get expanded, else this is a false
2706 // optimisation.
2707 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2708 Load->getMemoryVT());
2709
2710 // Resize the constant to the same size as the original memory access before
2711 // extension. If it is still the AllOnesValue then this AND is completely
2712 // unneeded.
2713 Constant =
2714 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2715
2716 bool B;
2717 switch (Load->getExtensionType()) {
2718 default: B = false; break;
2719 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2720 case ISD::ZEXTLOAD:
2721 case ISD::NON_EXTLOAD: B = true; break;
2722 }
2723
2724 if (B && Constant.isAllOnesValue()) {
2725 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2726 // preserve semantics once we get rid of the AND.
2727 SDValue NewLoad(Load, 0);
2728 if (Load->getExtensionType() == ISD::EXTLOAD) {
2729 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
Andrew Trickef9de2a2013-05-25 02:42:55 +00002730 Load->getValueType(0), SDLoc(Load),
James Molloy862fe492012-02-20 12:02:38 +00002731 Load->getChain(), Load->getBasePtr(),
2732 Load->getOffset(), Load->getMemoryVT(),
2733 Load->getMemOperand());
2734 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
Hal Finkel8a311382012-06-20 15:42:48 +00002735 if (Load->getNumValues() == 3) {
2736 // PRE/POST_INC loads have 3 values.
2737 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2738 NewLoad.getValue(2) };
2739 CombineTo(Load, To, 3, true);
2740 } else {
2741 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2742 }
James Molloy862fe492012-02-20 12:02:38 +00002743 }
2744
2745 // Fold the AND away, taking care not to fold to the old load node if we
2746 // replaced it.
2747 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2748
2749 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2750 }
2751 }
Nate Begeman049b7482005-09-09 19:49:52 +00002752 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2753 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2754 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2755 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
Scott Michelcf0da6c2009-02-17 22:15:04 +00002756
Nate Begeman049b7482005-09-09 19:49:52 +00002757 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
Duncan Sands13237ac2008-06-06 12:08:01 +00002758 LL.getValueType().isInteger()) {
Bill Wendling86171912009-01-30 20:43:18 +00002759 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
Dan Gohmanb72127a2008-03-13 22:13:53 +00002760 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002761 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
Bill Wendling86171912009-01-30 20:43:18 +00002762 LR.getValueType(), LL, RL);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002763 AddToWorkList(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002764 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00002765 }
Bill Wendling86171912009-01-30 20:43:18 +00002766 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
Nate Begeman049b7482005-09-09 19:49:52 +00002767 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002768 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
Bill Wendling86171912009-01-30 20:43:18 +00002769 LR.getValueType(), LL, RL);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002770 AddToWorkList(ANDNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002771 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00002772 }
Bill Wendling86171912009-01-30 20:43:18 +00002773 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
Nate Begeman049b7482005-09-09 19:49:52 +00002774 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002775 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
Bill Wendling86171912009-01-30 20:43:18 +00002776 LR.getValueType(), LL, RL);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002777 AddToWorkList(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002778 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00002779 }
2780 }
Jim Grosbach327ccc72013-08-13 21:30:58 +00002781 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2782 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2783 Op0 == Op1 && LL.getValueType().isInteger() &&
2784 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2785 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2786 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2787 cast<ConstantSDNode>(RR)->isNullValue()))) {
2788 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2789 LL, DAG.getConstant(1, LL.getValueType()));
2790 AddToWorkList(ADDNode.getNode());
2791 return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2792 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2793 }
Nate Begeman049b7482005-09-09 19:49:52 +00002794 // canonicalize equivalent to ll == rl
2795 if (LL == RR && LR == RL) {
2796 Op1 = ISD::getSetCCSwappedOperands(Op1);
2797 std::swap(RL, RR);
2798 }
2799 if (LL == RL && LR == RR) {
Duncan Sands13237ac2008-06-06 12:08:01 +00002800 bool isInteger = LL.getValueType().isInteger();
Nate Begeman049b7482005-09-09 19:49:52 +00002801 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
Chris Lattner5fa10402008-10-28 07:11:07 +00002802 if (Result != ISD::SETCC_INVALID &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00002803 (!LegalOperations ||
Owen Andersoncc068992013-02-14 09:07:33 +00002804 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2805 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault758659232013-05-18 00:21:46 +00002806 getSetCCResultType(N0.getSimpleValueType())))))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002807 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
Bill Wendling86171912009-01-30 20:43:18 +00002808 LL, LR, Result);
Nate Begeman049b7482005-09-09 19:49:52 +00002809 }
2810 }
Chris Lattner8d6fc202006-05-05 05:51:50 +00002811
Bill Wendling86171912009-01-30 20:43:18 +00002812 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
Chris Lattner8d6fc202006-05-05 05:51:50 +00002813 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002814 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002815 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00002816 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002817
Nate Begemandc7bba92006-02-03 22:24:05 +00002818 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2819 // fold (and (sra)) -> (and (srl)) when possible.
Duncan Sands13237ac2008-06-06 12:08:01 +00002820 if (!VT.isVector() &&
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002821 SimplifyDemandedBits(SDValue(N, 0)))
2822 return SDValue(N, 0);
Evan Cheng166a4e62010-01-06 19:38:29 +00002823
Nate Begeman02b23c62005-10-13 03:11:28 +00002824 // fold (zext_inreg (extload x)) -> (zextload x)
Gabor Greiff304a7a2008-08-28 21:40:38 +00002825 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00002826 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00002827 EVT MemVT = LN0->getMemoryVT();
Nate Begeman8e022b32005-10-13 18:34:58 +00002828 // If we zero all the possible extended bits, then we can turn this into
2829 // a zextload if we are running before legalize or the operation is legal.
Dan Gohmane14c4082010-03-04 00:23:16 +00002830 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
Dan Gohman1f372ed2008-02-25 21:11:39 +00002831 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
Dan Gohmane14c4082010-03-04 00:23:16 +00002832 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002833 ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00002834 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002835 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
Bill Wendling86171912009-01-30 20:43:18 +00002836 LN0->getChain(), LN0->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002837 MemVT, LN0->getMemOperand());
Chris Lattnerfbcd62d2006-03-01 04:03:14 +00002838 AddToWorkList(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002839 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002840 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00002841 }
2842 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002843 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
Gabor Greiff304a7a2008-08-28 21:40:38 +00002844 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Cheng8a1d09d2007-03-07 08:07:03 +00002845 N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00002846 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00002847 EVT MemVT = LN0->getMemoryVT();
Nate Begeman8e022b32005-10-13 18:34:58 +00002848 // If we zero all the possible extended bits, then we can turn this into
2849 // a zextload if we are running before legalize or the operation is legal.
Dan Gohmane14c4082010-03-04 00:23:16 +00002850 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
Dan Gohman1f372ed2008-02-25 21:11:39 +00002851 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
Dan Gohmane14c4082010-03-04 00:23:16 +00002852 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002853 ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00002854 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002855 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002856 LN0->getChain(), LN0->getBasePtr(),
2857 MemVT, LN0->getMemOperand());
Chris Lattnerfbcd62d2006-03-01 04:03:14 +00002858 AddToWorkList(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002859 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002860 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00002861 }
2862 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002863
Chris Lattnerf0032b32006-02-28 06:49:37 +00002864 // fold (and (load x), 255) -> (zextload x, i8)
2865 // fold (and (extload x, i16), 255) -> (zextload x, i8)
Evan Cheng166a4e62010-01-06 19:38:29 +00002866 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2867 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2868 (N0.getOpcode() == ISD::ANY_EXTEND &&
2869 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2870 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2871 LoadSDNode *LN0 = HasAnyExt
2872 ? cast<LoadSDNode>(N0.getOperand(0))
2873 : cast<LoadSDNode>(N0);
Evan Chenge71fe34d2006-10-09 20:57:25 +00002874 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
Tim Northover68239002013-07-02 09:58:53 +00002875 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
Duncan Sands93b66092008-06-09 11:32:28 +00002876 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
Evan Cheng166a4e62010-01-06 19:38:29 +00002877 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2878 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2879 EVT LoadedVT = LN0->getMemoryVT();
Duncan Sands93b66092008-06-09 11:32:28 +00002880
Evan Cheng166a4e62010-01-06 19:38:29 +00002881 if (ExtVT == LoadedVT &&
2882 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
Chris Lattner88de3842010-01-07 21:53:27 +00002883 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
Wesley Peck527da1b2010-11-23 03:31:01 +00002884
2885 SDValue NewLoad =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002886 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002887 LN0->getChain(), LN0->getBasePtr(), ExtVT,
2888 LN0->getMemOperand());
Chris Lattner88de3842010-01-07 21:53:27 +00002889 AddToWorkList(N);
2890 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2891 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2892 }
Wesley Peck527da1b2010-11-23 03:31:01 +00002893
Chris Lattner88de3842010-01-07 21:53:27 +00002894 // Do not change the width of a volatile load.
2895 // Do not generate loads of non-round integer types since these can
2896 // be expensive (and would be wrong if the type is not byte sized).
2897 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2898 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2899 EVT PtrType = LN0->getOperand(1).getValueType();
Bill Wendling86171912009-01-30 20:43:18 +00002900
Chris Lattner88de3842010-01-07 21:53:27 +00002901 unsigned Alignment = LN0->getAlignment();
2902 SDValue NewPtr = LN0->getBasePtr();
2903
2904 // For big endian targets, we need to add an offset to the pointer
2905 // to load the correct bytes. For little endian systems, we merely
2906 // need to read fewer bytes from the same pointer.
2907 if (TLI.isBigEndian()) {
Evan Cheng166a4e62010-01-06 19:38:29 +00002908 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2909 unsigned EVTStoreBytes = ExtVT.getStoreSize();
2910 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
Andrew Trickef9de2a2013-05-25 02:42:55 +00002911 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
Chris Lattner88de3842010-01-07 21:53:27 +00002912 NewPtr, DAG.getConstant(PtrOff, PtrType));
2913 Alignment = MinAlign(Alignment, PtrOff);
Evan Cheng166a4e62010-01-06 19:38:29 +00002914 }
Chris Lattner88de3842010-01-07 21:53:27 +00002915
2916 AddToWorkList(NewPtr.getNode());
Wesley Peck527da1b2010-11-23 03:31:01 +00002917
Chris Lattner88de3842010-01-07 21:53:27 +00002918 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2919 SDValue Load =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002920 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
Chris Lattner88de3842010-01-07 21:53:27 +00002921 LN0->getChain(), NewPtr,
Chris Lattner3d178ed2010-09-21 17:04:51 +00002922 LN0->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +00002923 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002924 Alignment, LN0->getTBAAInfo());
Chris Lattner88de3842010-01-07 21:53:27 +00002925 AddToWorkList(N);
2926 CombineTo(LN0, Load, Load.getValue(1));
2927 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Duncan Sands1826ded2007-10-28 12:59:45 +00002928 }
Evan Chenge71fe34d2006-10-09 20:57:25 +00002929 }
Chris Lattnerbdbc4472006-02-28 06:35:35 +00002930 }
2931 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002932
Evan Chenge6a3b032012-07-17 18:54:11 +00002933 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2934 VT.getSizeInBits() <= 64) {
2935 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2936 APInt ADDC = ADDI->getAPIntValue();
2937 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2938 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2939 // immediate for an add, but it is legal if its top c2 bits are set,
2940 // transform the ADD so the immediate doesn't need to be materialized
2941 // in a register.
2942 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2943 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2944 SRLI->getZExtValue());
2945 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2946 ADDC |= Mask;
2947 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2948 SDValue NewAdd =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002949 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
Evan Chenge6a3b032012-07-17 18:54:11 +00002950 N0.getOperand(0), DAG.getConstant(ADDC, VT));
2951 CombineTo(N0.getNode(), NewAdd);
2952 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2953 }
2954 }
2955 }
2956 }
2957 }
2958 }
Evan Chenge6a3b032012-07-17 18:54:11 +00002959
Tim Northover819bfb52013-08-27 13:46:45 +00002960 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
2961 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
2962 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
2963 N0.getOperand(1), false);
2964 if (BSwap.getNode())
2965 return BSwap;
2966 }
2967
Evan Chengf1005572010-04-28 07:10:39 +00002968 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002969}
2970
Evan Cheng4c0bd962011-06-21 06:01:08 +00002971/// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2972///
2973SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2974 bool DemandHighBits) {
2975 if (!LegalOperations)
2976 return SDValue();
2977
2978 EVT VT = N->getValueType(0);
2979 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2980 return SDValue();
2981 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2982 return SDValue();
2983
2984 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2985 bool LookPassAnd0 = false;
2986 bool LookPassAnd1 = false;
2987 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2988 std::swap(N0, N1);
2989 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2990 std::swap(N0, N1);
2991 if (N0.getOpcode() == ISD::AND) {
2992 if (!N0.getNode()->hasOneUse())
2993 return SDValue();
2994 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2995 if (!N01C || N01C->getZExtValue() != 0xFF00)
2996 return SDValue();
2997 N0 = N0.getOperand(0);
2998 LookPassAnd0 = true;
2999 }
3000
3001 if (N1.getOpcode() == ISD::AND) {
3002 if (!N1.getNode()->hasOneUse())
3003 return SDValue();
3004 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3005 if (!N11C || N11C->getZExtValue() != 0xFF)
3006 return SDValue();
3007 N1 = N1.getOperand(0);
3008 LookPassAnd1 = true;
3009 }
3010
3011 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3012 std::swap(N0, N1);
3013 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3014 return SDValue();
3015 if (!N0.getNode()->hasOneUse() ||
3016 !N1.getNode()->hasOneUse())
3017 return SDValue();
3018
3019 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3020 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3021 if (!N01C || !N11C)
3022 return SDValue();
3023 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3024 return SDValue();
3025
3026 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3027 SDValue N00 = N0->getOperand(0);
3028 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3029 if (!N00.getNode()->hasOneUse())
3030 return SDValue();
3031 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3032 if (!N001C || N001C->getZExtValue() != 0xFF)
3033 return SDValue();
3034 N00 = N00.getOperand(0);
3035 LookPassAnd0 = true;
3036 }
3037
3038 SDValue N10 = N1->getOperand(0);
3039 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3040 if (!N10.getNode()->hasOneUse())
3041 return SDValue();
3042 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3043 if (!N101C || N101C->getZExtValue() != 0xFF00)
3044 return SDValue();
3045 N10 = N10.getOperand(0);
3046 LookPassAnd1 = true;
3047 }
3048
3049 if (N00 != N10)
3050 return SDValue();
3051
Tim Northover819bfb52013-08-27 13:46:45 +00003052 // Make sure everything beyond the low halfword gets set to zero since the SRL
3053 // 16 will clear the top bits.
Evan Cheng4c0bd962011-06-21 06:01:08 +00003054 unsigned OpSizeInBits = VT.getSizeInBits();
Tim Northover819bfb52013-08-27 13:46:45 +00003055 if (DemandHighBits && OpSizeInBits > 16) {
3056 // If the left-shift isn't masked out then the only way this is a bswap is
3057 // if all bits beyond the low 8 are 0. In that case the entire pattern
3058 // reduces to a left shift anyway: leave it for other parts of the combiner.
3059 if (!LookPassAnd0)
3060 return SDValue();
3061
3062 // However, if the right shift isn't masked out then it might be because
3063 // it's not needed. See if we can spot that too.
3064 if (!LookPassAnd1 &&
3065 !DAG.MaskedValueIsZero(
3066 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3067 return SDValue();
3068 }
Eric Christopherd6300d22011-07-14 01:12:15 +00003069
Andrew Trickef9de2a2013-05-25 02:42:55 +00003070 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
Evan Cheng4c0bd962011-06-21 06:01:08 +00003071 if (OpSizeInBits > 16)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003072 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
Evan Cheng4c0bd962011-06-21 06:01:08 +00003073 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3074 return Res;
3075}
3076
3077/// isBSwapHWordElement - Return true if the specified node is an element
3078/// that makes up a 32-bit packed halfword byteswap. i.e.
3079/// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
Craig Topperb94011f2013-07-14 04:42:23 +00003080static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
Evan Cheng4c0bd962011-06-21 06:01:08 +00003081 if (!N.getNode()->hasOneUse())
3082 return false;
3083
3084 unsigned Opc = N.getOpcode();
3085 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3086 return false;
3087
3088 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3089 if (!N1C)
3090 return false;
3091
3092 unsigned Num;
3093 switch (N1C->getZExtValue()) {
3094 default:
3095 return false;
3096 case 0xFF: Num = 0; break;
3097 case 0xFF00: Num = 1; break;
3098 case 0xFF0000: Num = 2; break;
3099 case 0xFF000000: Num = 3; break;
3100 }
3101
3102 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3103 SDValue N0 = N.getOperand(0);
3104 if (Opc == ISD::AND) {
3105 if (Num == 0 || Num == 2) {
3106 // (x >> 8) & 0xff
3107 // (x >> 8) & 0xff0000
3108 if (N0.getOpcode() != ISD::SRL)
3109 return false;
3110 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3111 if (!C || C->getZExtValue() != 8)
3112 return false;
3113 } else {
3114 // (x << 8) & 0xff00
3115 // (x << 8) & 0xff000000
3116 if (N0.getOpcode() != ISD::SHL)
3117 return false;
3118 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3119 if (!C || C->getZExtValue() != 8)
3120 return false;
3121 }
3122 } else if (Opc == ISD::SHL) {
3123 // (x & 0xff) << 8
3124 // (x & 0xff0000) << 8
3125 if (Num != 0 && Num != 2)
3126 return false;
3127 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3128 if (!C || C->getZExtValue() != 8)
3129 return false;
3130 } else { // Opc == ISD::SRL
3131 // (x & 0xff00) >> 8
3132 // (x & 0xff000000) >> 8
3133 if (Num != 1 && Num != 3)
3134 return false;
3135 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3136 if (!C || C->getZExtValue() != 8)
3137 return false;
3138 }
3139
3140 if (Parts[Num])
3141 return false;
3142
3143 Parts[Num] = N0.getOperand(0).getNode();
3144 return true;
3145}
3146
3147/// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3148/// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3149/// => (rotl (bswap x), 16)
3150SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3151 if (!LegalOperations)
3152 return SDValue();
3153
3154 EVT VT = N->getValueType(0);
3155 if (VT != MVT::i32)
3156 return SDValue();
3157 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3158 return SDValue();
3159
Craig Topperc0196b12014-04-14 00:51:57 +00003160 SmallVector<SDNode*,4> Parts(4, (SDNode*)nullptr);
Evan Cheng4c0bd962011-06-21 06:01:08 +00003161 // Look for either
3162 // (or (or (and), (and)), (or (and), (and)))
3163 // (or (or (or (and), (and)), (and)), (and))
3164 if (N0.getOpcode() != ISD::OR)
3165 return SDValue();
3166 SDValue N00 = N0.getOperand(0);
3167 SDValue N01 = N0.getOperand(1);
3168
Evan Chengbf0baa92012-12-13 01:34:32 +00003169 if (N1.getOpcode() == ISD::OR &&
3170 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
Evan Cheng4c0bd962011-06-21 06:01:08 +00003171 // (or (or (and), (and)), (or (and), (and)))
3172 SDValue N000 = N00.getOperand(0);
3173 if (!isBSwapHWordElement(N000, Parts))
3174 return SDValue();
3175
3176 SDValue N001 = N00.getOperand(1);
3177 if (!isBSwapHWordElement(N001, Parts))
3178 return SDValue();
3179 SDValue N010 = N01.getOperand(0);
3180 if (!isBSwapHWordElement(N010, Parts))
3181 return SDValue();
3182 SDValue N011 = N01.getOperand(1);
3183 if (!isBSwapHWordElement(N011, Parts))
3184 return SDValue();
3185 } else {
3186 // (or (or (or (and), (and)), (and)), (and))
3187 if (!isBSwapHWordElement(N1, Parts))
3188 return SDValue();
3189 if (!isBSwapHWordElement(N01, Parts))
3190 return SDValue();
3191 if (N00.getOpcode() != ISD::OR)
3192 return SDValue();
3193 SDValue N000 = N00.getOperand(0);
3194 if (!isBSwapHWordElement(N000, Parts))
3195 return SDValue();
3196 SDValue N001 = N00.getOperand(1);
3197 if (!isBSwapHWordElement(N001, Parts))
3198 return SDValue();
3199 }
3200
3201 // Make sure the parts are all coming from the same node.
3202 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3203 return SDValue();
3204
Andrew Trickef9de2a2013-05-25 02:42:55 +00003205 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
Evan Cheng4c0bd962011-06-21 06:01:08 +00003206 SDValue(Parts[0],0));
3207
Kay Tiong Khoo9195a5b2013-09-23 18:43:51 +00003208 // Result of the bswap should be rotated by 16. If it's not legal, then
Evan Cheng4c0bd962011-06-21 06:01:08 +00003209 // do (x << 16) | (x >> 16).
3210 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3211 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003212 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
Craig Topper5f9791f2012-09-29 07:18:53 +00003213 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003214 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3215 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3216 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3217 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
Evan Cheng4c0bd962011-06-21 06:01:08 +00003218}
3219
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003220SDValue DAGCombiner::visitOR(SDNode *N) {
3221 SDValue N0 = N->getOperand(0);
3222 SDValue N1 = N->getOperand(1);
3223 SDValue LL, LR, RL, RR, CC0, CC1;
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003224 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3225 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00003226 EVT VT = N1.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003227
Dan Gohmana8665142007-06-25 16:23:39 +00003228 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00003229 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003230 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003231 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00003232
3233 // fold (or x, 0) -> x, vector edition
3234 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3235 return N1;
3236 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3237 return N0;
3238
3239 // fold (or x, -1) -> -1, vector edition
3240 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3241 return N0;
3242 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3243 return N1;
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003244
3245 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3246 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3247 // Do this only if the resulting shuffle is legal.
3248 if (isa<ShuffleVectorSDNode>(N0) &&
3249 isa<ShuffleVectorSDNode>(N1) &&
3250 N0->getOperand(1) == N1->getOperand(1) &&
3251 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3252 bool CanFold = true;
3253 unsigned NumElts = VT.getVectorNumElements();
3254 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3255 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3256 // We construct two shuffle masks:
3257 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3258 // and N1 as the second operand.
3259 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3260 // and N0 as the second operand.
3261 // We do this because OR is commutable and therefore there might be
3262 // two ways to fold this node into a shuffle.
3263 SmallVector<int,4> Mask1;
3264 SmallVector<int,4> Mask2;
3265
3266 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3267 int M0 = SV0->getMaskElt(i);
3268 int M1 = SV1->getMaskElt(i);
3269
3270 // Both shuffle indexes are undef. Propagate Undef.
3271 if (M0 < 0 && M1 < 0) {
3272 Mask1.push_back(M0);
3273 Mask2.push_back(M0);
3274 continue;
3275 }
3276
3277 if (M0 < 0 || M1 < 0 ||
3278 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3279 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3280 CanFold = false;
3281 break;
3282 }
3283
3284 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3285 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3286 }
3287
3288 if (CanFold) {
3289 // Fold this sequence only if the resulting shuffle is 'legal'.
3290 if (TLI.isShuffleMaskLegal(Mask1, VT))
3291 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3292 N1->getOperand(0), &Mask1[0]);
3293 if (TLI.isShuffleMaskLegal(Mask2, VT))
3294 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3295 N0->getOperand(0), &Mask2[0]);
3296 }
3297 }
Dan Gohman80f9f072007-07-13 20:03:40 +00003298 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003299
Dan Gohman06563a82007-07-03 14:03:57 +00003300 // fold (or x, undef) -> -1
Bob Wilson269a89f2010-06-28 23:40:25 +00003301 if (!LegalOperations &&
3302 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
Nate Begeman9655f842009-12-03 07:11:29 +00003303 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3304 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3305 }
Nate Begeman21158fc2005-09-01 00:19:25 +00003306 // fold (or c1, c2) -> c1|c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003307 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00003308 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003309 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00003310 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003311 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00003312 // fold (or x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003313 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003314 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00003315 // fold (or x, -1) -> -1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003316 if (N1C && N1C->isAllOnesValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003317 return N1;
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003318 // fold (or x, c) -> c iff (x & ~c) == 0
Dan Gohman1f372ed2008-02-25 21:11:39 +00003319 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
Nate Begemand23739d2005-09-06 04:43:02 +00003320 return N1;
Evan Cheng4c0bd962011-06-21 06:01:08 +00003321
3322 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3323 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003324 if (BSwap.getNode())
Evan Cheng4c0bd962011-06-21 06:01:08 +00003325 return BSwap;
3326 BSwap = MatchBSwapHWordLow(N, N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003327 if (BSwap.getNode())
Evan Cheng4c0bd962011-06-21 06:01:08 +00003328 return BSwap;
3329
Nate Begeman22e251a2006-02-03 06:46:56 +00003330 // reassociate or
Andrew Trickef9de2a2013-05-25 02:42:55 +00003331 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003332 if (ROR.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00003333 return ROR;
3334 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003335 // iff (c1 & c2) == 0.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003336 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
Chris Lattnerd8c5c062005-10-27 05:06:38 +00003337 isa<ConstantSDNode>(N0.getOperand(1))) {
Chris Lattnerd8c5c062005-10-27 05:06:38 +00003338 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
Juergen Ributzkaf26beda2014-01-25 02:02:55 +00003339 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3340 SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3341 if (!COR.getNode())
3342 return SDValue();
Andrew Trickef9de2a2013-05-25 02:42:55 +00003343 return DAG.getNode(ISD::AND, SDLoc(N), VT,
3344 DAG.getNode(ISD::OR, SDLoc(N0), VT,
Juergen Ributzkaf26beda2014-01-25 02:02:55 +00003345 N0.getOperand(0), N1), COR);
3346 }
Nate Begeman85c1cc42005-09-08 20:18:10 +00003347 }
Nate Begeman049b7482005-09-09 19:49:52 +00003348 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3349 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3350 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3351 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003352
Nate Begeman049b7482005-09-09 19:49:52 +00003353 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
Duncan Sands13237ac2008-06-06 12:08:01 +00003354 LL.getValueType().isInteger()) {
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003355 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3356 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
Scott Michelcf0da6c2009-02-17 22:15:04 +00003357 if (cast<ConstantSDNode>(LR)->isNullValue() &&
Nate Begeman049b7482005-09-09 19:49:52 +00003358 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003359 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003360 LR.getValueType(), LL, RL);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003361 AddToWorkList(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003362 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00003363 }
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003364 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3365 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
Scott Michelcf0da6c2009-02-17 22:15:04 +00003366 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
Nate Begeman049b7482005-09-09 19:49:52 +00003367 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003368 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003369 LR.getValueType(), LL, RL);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003370 AddToWorkList(ANDNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003371 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00003372 }
3373 }
3374 // canonicalize equivalent to ll == rl
3375 if (LL == RR && LR == RL) {
3376 Op1 = ISD::getSetCCSwappedOperands(Op1);
3377 std::swap(RL, RR);
3378 }
3379 if (LL == RL && LR == RR) {
Duncan Sands13237ac2008-06-06 12:08:01 +00003380 bool isInteger = LL.getValueType().isInteger();
Nate Begeman049b7482005-09-09 19:49:52 +00003381 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
Chris Lattner5fa10402008-10-28 07:11:07 +00003382 if (Result != ISD::SETCC_INVALID &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00003383 (!LegalOperations ||
Owen Andersoncc068992013-02-14 09:07:33 +00003384 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3385 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault758659232013-05-18 00:21:46 +00003386 getSetCCResultType(N0.getValueType())))))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003387 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003388 LL, LR, Result);
Nate Begeman049b7482005-09-09 19:49:52 +00003389 }
3390 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003391
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003392 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
Chris Lattner8d6fc202006-05-05 05:51:50 +00003393 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003394 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003395 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00003396 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003397
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003398 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
Chris Lattner46d710e2006-09-14 21:11:37 +00003399 if (N0.getOpcode() == ISD::AND &&
3400 N1.getOpcode() == ISD::AND &&
3401 N0.getOperand(1).getOpcode() == ISD::Constant &&
3402 N1.getOperand(1).getOpcode() == ISD::Constant &&
3403 // Don't increase # computations.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003404 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
Chris Lattner46d710e2006-09-14 21:11:37 +00003405 // We can only do this xform if we know that bits from X that are set in C2
3406 // but not in C1 are already zero. Likewise for Y.
Dan Gohman1f372ed2008-02-25 21:11:39 +00003407 const APInt &LHSMask =
3408 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3409 const APInt &RHSMask =
3410 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003411
Dan Gohman309d3d52007-06-22 14:59:07 +00003412 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3413 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003414 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003415 N0.getOperand(0), N1.getOperand(0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00003416 return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003417 DAG.getConstant(LHSMask | RHSMask, VT));
Chris Lattner46d710e2006-09-14 21:11:37 +00003418 }
3419 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003420
Chris Lattner97614c82006-09-14 20:50:57 +00003421 // See if this is some rotate idiom.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003422 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003423 return SDValue(Rot, 0);
Chris Lattner8d6fc202006-05-05 05:51:50 +00003424
Dan Gohman600f62b2010-06-24 14:30:44 +00003425 // Simplify the operands using demanded-bits information.
3426 if (!VT.isVector() &&
3427 SimplifyDemandedBits(SDValue(N, 0)))
3428 return SDValue(N, 0);
3429
Evan Chengf1005572010-04-28 07:10:39 +00003430 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00003431}
3432
Chris Lattner97614c82006-09-14 20:50:57 +00003433/// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003434static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
Chris Lattner97614c82006-09-14 20:50:57 +00003435 if (Op.getOpcode() == ISD::AND) {
Reid Spencerde46e482006-11-02 20:25:50 +00003436 if (isa<ConstantSDNode>(Op.getOperand(1))) {
Chris Lattner97614c82006-09-14 20:50:57 +00003437 Mask = Op.getOperand(1);
3438 Op = Op.getOperand(0);
3439 } else {
3440 return false;
3441 }
3442 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003443
Chris Lattner97614c82006-09-14 20:50:57 +00003444 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3445 Shift = Op;
3446 return true;
3447 }
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003448
Scott Michelcf0da6c2009-02-17 22:15:04 +00003449 return false;
Chris Lattner97614c82006-09-14 20:50:57 +00003450}
3451
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003452// Return true if we can prove that, whenever Neg and Pos are both in the
3453// range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
Richard Sandiford0f264db2014-01-09 10:49:40 +00003454// for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3455//
3456// (or (shift1 X, Neg), (shift2 X, Pos))
3457//
Adam Nemetc6553a82014-03-07 23:56:24 +00003458// reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3459// in direction shift1 by Neg. The range [0, OpSize) means that we only need
3460// to consider shift amounts with defined behavior.
Richard Sandiford0f264db2014-01-09 10:49:40 +00003461static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003462 // If OpSize is a power of 2 then:
3463 //
3464 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3465 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3466 //
3467 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3468 // for the stronger condition:
3469 //
3470 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3471 //
3472 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3473 // we can just replace Neg with Neg' for the rest of the function.
3474 //
3475 // In other cases we check for the even stronger condition:
3476 //
3477 // Neg == OpSize - Pos [B]
3478 //
3479 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3480 // behavior if Pos == 0 (and consequently Neg == OpSize).
Adam Nemetc6553a82014-03-07 23:56:24 +00003481 //
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003482 // We could actually use [A] whenever OpSize is a power of 2, but the
3483 // only extra cases that it would match are those uninteresting ones
3484 // where Neg and Pos are never in range at the same time. E.g. for
3485 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3486 // as well as (sub 32, Pos), but:
3487 //
3488 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3489 //
3490 // always invokes undefined behavior for 32-bit X.
3491 //
3492 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
Adam Nemetc6553a82014-03-07 23:56:24 +00003493 unsigned MaskLoBits = 0;
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003494 if (Neg.getOpcode() == ISD::AND &&
3495 isPowerOf2_64(OpSize) &&
3496 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3497 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3498 Neg = Neg.getOperand(0);
Adam Nemetc6553a82014-03-07 23:56:24 +00003499 MaskLoBits = Log2_64(OpSize);
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003500 }
3501
Richard Sandiford0f264db2014-01-09 10:49:40 +00003502 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3503 if (Neg.getOpcode() != ISD::SUB)
3504 return 0;
3505 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3506 if (!NegC)
3507 return 0;
3508 SDValue NegOp1 = Neg.getOperand(1);
3509
Adam Nemet5117f5d2014-03-07 23:56:28 +00003510 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3511 // Pos'. The truncation is redundant for the purpose of the equality.
3512 if (MaskLoBits &&
3513 Pos.getOpcode() == ISD::AND &&
3514 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3515 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3516 Pos = Pos.getOperand(0);
3517
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003518 // The condition we need is now:
3519 //
3520 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3521 //
3522 // If NegOp1 == Pos then we need:
3523 //
3524 // OpSize & Mask == NegC & Mask
3525 //
3526 // (because "x & Mask" is a truncation and distributes through subtraction).
3527 APInt Width;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003528 if (Pos == NegOp1)
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003529 Width = NegC->getAPIntValue();
Richard Sandiford0f264db2014-01-09 10:49:40 +00003530 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3531 // Then the condition we want to prove becomes:
Richard Sandiford0f264db2014-01-09 10:49:40 +00003532 //
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003533 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3534 //
3535 // which, again because "x & Mask" is a truncation, becomes:
3536 //
3537 // NegC & Mask == (OpSize - PosC) & Mask
3538 // OpSize & Mask == (NegC + PosC) & Mask
3539 else if (Pos.getOpcode() == ISD::ADD &&
3540 Pos.getOperand(0) == NegOp1 &&
3541 Pos.getOperand(1).getOpcode() == ISD::Constant)
3542 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3543 NegC->getAPIntValue());
3544 else
3545 return false;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003546
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003547 // Now we just need to check that OpSize & Mask == Width & Mask.
Adam Nemetc6553a82014-03-07 23:56:24 +00003548 if (MaskLoBits)
3549 // Opsize & Mask is 0 since Mask is Opsize - 1.
3550 return Width.getLoBits(MaskLoBits) == 0;
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003551 return Width == OpSize;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003552}
3553
Richard Sandiford95c864d2014-01-08 15:40:47 +00003554// A subroutine of MatchRotate used once we have found an OR of two opposite
3555// shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3556// to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3557// former being preferred if supported. InnerPos and InnerNeg are Pos and
3558// Neg with outer conversions stripped away.
3559SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3560 SDValue Neg, SDValue InnerPos,
3561 SDValue InnerNeg, unsigned PosOpcode,
3562 unsigned NegOpcode, SDLoc DL) {
Richard Sandiford95c864d2014-01-08 15:40:47 +00003563 // fold (or (shl x, (*ext y)),
3564 // (srl x, (*ext (sub 32, y)))) ->
3565 // (rotl x, y) or (rotr x, (sub 32, y))
3566 //
3567 // fold (or (shl x, (*ext (sub 32, y))),
3568 // (srl x, (*ext y))) ->
3569 // (rotr x, y) or (rotl x, (sub 32, y))
3570 EVT VT = Shifted.getValueType();
Richard Sandiford0f264db2014-01-09 10:49:40 +00003571 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
Richard Sandiford95c864d2014-01-08 15:40:47 +00003572 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3573 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3574 HasPos ? Pos : Neg).getNode();
3575 }
3576
3577 // fold (or (shl (*ext x), (*ext y)),
3578 // (srl (*ext x), (*ext (sub 32, y)))) ->
3579 // (*ext (rotl x, y)) or (*ext (rotr x, (sub 32, y)))
3580 //
3581 // fold (or (shl (*ext x), (*ext (sub 32, y))),
3582 // (srl (*ext x), (*ext y))) ->
3583 // (*ext (rotr x, y)) or (*ext (rotl x, (sub 32, y)))
3584 if (Shifted.getOpcode() == ISD::ZERO_EXTEND ||
3585 Shifted.getOpcode() == ISD::ANY_EXTEND) {
3586 SDValue InnerShifted = Shifted.getOperand(0);
3587 EVT InnerVT = InnerShifted.getValueType();
3588 bool HasPosInner = TLI.isOperationLegalOrCustom(PosOpcode, InnerVT);
3589 if (HasPosInner || TLI.isOperationLegalOrCustom(NegOpcode, InnerVT)) {
Richard Sandiford0f264db2014-01-09 10:49:40 +00003590 if (matchRotateSub(InnerPos, InnerNeg, InnerVT.getSizeInBits())) {
Richard Sandiford95c864d2014-01-08 15:40:47 +00003591 SDValue V = DAG.getNode(HasPosInner ? PosOpcode : NegOpcode, DL,
3592 InnerVT, InnerShifted, HasPosInner ? Pos : Neg);
3593 return DAG.getNode(Shifted.getOpcode(), DL, VT, V).getNode();
3594 }
3595 }
3596 }
3597
Craig Topperc0196b12014-04-14 00:51:57 +00003598 return nullptr;
Richard Sandiford95c864d2014-01-08 15:40:47 +00003599}
3600
Chris Lattner97614c82006-09-14 20:50:57 +00003601// MatchRotate - Handle an 'or' of two operands. If this is one of the many
3602// idioms for rotate, and if the target supports rotation instructions, generate
3603// a rot[lr].
Andrew Trickef9de2a2013-05-25 02:42:55 +00003604SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
Duncan Sands8651e9c2008-06-13 19:07:40 +00003605 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
Owen Anderson53aa7a92009-08-10 22:56:29 +00003606 EVT VT = LHS.getValueType();
Craig Topperc0196b12014-04-14 00:51:57 +00003607 if (!TLI.isTypeLegal(VT)) return nullptr;
Chris Lattner97614c82006-09-14 20:50:57 +00003608
3609 // The target must have at least one rotate flavor.
Dan Gohman4aa18462009-01-28 17:46:25 +00003610 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3611 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
Craig Topperc0196b12014-04-14 00:51:57 +00003612 if (!HasROTL && !HasROTR) return nullptr;
Duncan Sands8651e9c2008-06-13 19:07:40 +00003613
Chris Lattner97614c82006-09-14 20:50:57 +00003614 // Match "(X shl/srl V1) & V2" where V2 may not be present.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003615 SDValue LHSShift; // The shift.
3616 SDValue LHSMask; // AND value if any.
Chris Lattner97614c82006-09-14 20:50:57 +00003617 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
Craig Topperc0196b12014-04-14 00:51:57 +00003618 return nullptr; // Not part of a rotate.
Chris Lattner97614c82006-09-14 20:50:57 +00003619
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003620 SDValue RHSShift; // The shift.
3621 SDValue RHSMask; // AND value if any.
Chris Lattner97614c82006-09-14 20:50:57 +00003622 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
Craig Topperc0196b12014-04-14 00:51:57 +00003623 return nullptr; // Not part of a rotate.
Scott Michelcf0da6c2009-02-17 22:15:04 +00003624
Chris Lattner97614c82006-09-14 20:50:57 +00003625 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
Craig Topperc0196b12014-04-14 00:51:57 +00003626 return nullptr; // Not shifting the same value.
Chris Lattner97614c82006-09-14 20:50:57 +00003627
3628 if (LHSShift.getOpcode() == RHSShift.getOpcode())
Craig Topperc0196b12014-04-14 00:51:57 +00003629 return nullptr; // Shifts must disagree.
Scott Michelcf0da6c2009-02-17 22:15:04 +00003630
Chris Lattner97614c82006-09-14 20:50:57 +00003631 // Canonicalize shl to left side in a shl/srl pair.
3632 if (RHSShift.getOpcode() == ISD::SHL) {
3633 std::swap(LHS, RHS);
3634 std::swap(LHSShift, RHSShift);
3635 std::swap(LHSMask , RHSMask );
3636 }
3637
Duncan Sands13237ac2008-06-06 12:08:01 +00003638 unsigned OpSizeInBits = VT.getSizeInBits();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003639 SDValue LHSShiftArg = LHSShift.getOperand(0);
3640 SDValue LHSShiftAmt = LHSShift.getOperand(1);
Kai Nacked09bb462013-09-19 23:00:28 +00003641 SDValue RHSShiftArg = RHSShift.getOperand(0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003642 SDValue RHSShiftAmt = RHSShift.getOperand(1);
Chris Lattner97614c82006-09-14 20:50:57 +00003643
3644 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3645 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
Scott Michel16627a52007-04-02 21:36:32 +00003646 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3647 RHSShiftAmt.getOpcode() == ISD::Constant) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00003648 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3649 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
Chris Lattner97614c82006-09-14 20:50:57 +00003650 if ((LShVal + RShVal) != OpSizeInBits)
Craig Topperc0196b12014-04-14 00:51:57 +00003651 return nullptr;
Chris Lattner97614c82006-09-14 20:50:57 +00003652
Craig Topper65161fa2012-09-29 06:54:22 +00003653 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3654 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003655
Chris Lattner97614c82006-09-14 20:50:57 +00003656 // If there is an AND of either shifted operand, apply it to the result.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003657 if (LHSMask.getNode() || RHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003658 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003659
Gabor Greiff304a7a2008-08-28 21:40:38 +00003660 if (LHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003661 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3662 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
Chris Lattner97614c82006-09-14 20:50:57 +00003663 }
Gabor Greiff304a7a2008-08-28 21:40:38 +00003664 if (RHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003665 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3666 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
Chris Lattner97614c82006-09-14 20:50:57 +00003667 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003668
Bill Wendling35972a92009-01-30 21:14:50 +00003669 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
Chris Lattner97614c82006-09-14 20:50:57 +00003670 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003671
Gabor Greiff304a7a2008-08-28 21:40:38 +00003672 return Rot.getNode();
Chris Lattner97614c82006-09-14 20:50:57 +00003673 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003674
Chris Lattner97614c82006-09-14 20:50:57 +00003675 // If there is a mask here, and we have a variable shift, we can't be sure
3676 // that we're masking out the right stuff.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003677 if (LHSMask.getNode() || RHSMask.getNode())
Craig Topperc0196b12014-04-14 00:51:57 +00003678 return nullptr;
Scott Michelcf0da6c2009-02-17 22:15:04 +00003679
Benjamin Kramer64bdb292013-09-24 14:21:28 +00003680 // If the shift amount is sign/zext/any-extended just peel it off.
3681 SDValue LExtOp0 = LHSShiftAmt;
3682 SDValue RExtOp0 = RHSShiftAmt;
Craig Topper5f9791f2012-09-29 07:18:53 +00003683 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3684 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3685 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3686 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3687 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3688 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3689 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3690 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
Benjamin Kramer64bdb292013-09-24 14:21:28 +00003691 LExtOp0 = LHSShiftAmt.getOperand(0);
3692 RExtOp0 = RHSShiftAmt.getOperand(0);
3693 }
3694
Richard Sandiford95c864d2014-01-08 15:40:47 +00003695 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3696 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3697 if (TryL)
3698 return TryL;
3699
3700 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3701 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3702 if (TryR)
3703 return TryR;
Scott Michelcf0da6c2009-02-17 22:15:04 +00003704
Craig Topperc0196b12014-04-14 00:51:57 +00003705 return nullptr;
Chris Lattner97614c82006-09-14 20:50:57 +00003706}
3707
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003708SDValue DAGCombiner::visitXOR(SDNode *N) {
3709 SDValue N0 = N->getOperand(0);
3710 SDValue N1 = N->getOperand(1);
3711 SDValue LHS, RHS, CC;
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003712 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3713 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00003714 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003715
Dan Gohmana8665142007-06-25 16:23:39 +00003716 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00003717 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003718 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003719 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00003720
3721 // fold (xor x, 0) -> x, vector edition
3722 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3723 return N1;
3724 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3725 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00003726 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003727
Evan Chengdf1690d2008-03-25 20:08:07 +00003728 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3729 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3730 return DAG.getConstant(0, VT);
Dan Gohman06563a82007-07-03 14:03:57 +00003731 // fold (xor x, undef) -> undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00003732 if (N0.getOpcode() == ISD::UNDEF)
3733 return N0;
3734 if (N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00003735 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00003736 // fold (xor c1, c2) -> c1^c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003737 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00003738 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003739 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00003740 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003741 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00003742 // fold (xor x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003743 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003744 return N0;
Nate Begeman22e251a2006-02-03 06:46:56 +00003745 // reassociate xor
Andrew Trickef9de2a2013-05-25 02:42:55 +00003746 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003747 if (RXOR.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00003748 return RXOR;
Bill Wendling49a5ce82008-11-11 08:25:46 +00003749
Nate Begeman21158fc2005-09-01 00:19:25 +00003750 // fold !(x cc y) -> (x !cc y)
Dan Gohmanb72127a2008-03-13 22:13:53 +00003751 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
Duncan Sands13237ac2008-06-06 12:08:01 +00003752 bool isInt = LHS.getValueType().isInteger();
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003753 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3754 isInt);
Bill Wendling49a5ce82008-11-11 08:25:46 +00003755
Patrik Hagglundffd057a2012-12-19 10:19:55 +00003756 if (!LegalOperations ||
3757 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
Bill Wendling49a5ce82008-11-11 08:25:46 +00003758 switch (N0.getOpcode()) {
3759 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +00003760 llvm_unreachable("Unhandled SetCC Equivalent!");
Bill Wendling49a5ce82008-11-11 08:25:46 +00003761 case ISD::SETCC:
Andrew Trickef9de2a2013-05-25 02:42:55 +00003762 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
Bill Wendling49a5ce82008-11-11 08:25:46 +00003763 case ISD::SELECT_CC:
Andrew Trickef9de2a2013-05-25 02:42:55 +00003764 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
Bill Wendling49a5ce82008-11-11 08:25:46 +00003765 N0.getOperand(3), NotCC);
3766 }
3767 }
Nate Begeman21158fc2005-09-01 00:19:25 +00003768 }
Bill Wendling49a5ce82008-11-11 08:25:46 +00003769
Chris Lattner58c227b2007-09-10 21:39:07 +00003770 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
Dan Gohmanb72127a2008-03-13 22:13:53 +00003771 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
Gabor Greife12264b2008-08-30 19:29:20 +00003772 N0.getNode()->hasOneUse() &&
3773 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003774 SDValue V = N0.getOperand(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003775 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
Duncan Sands56ab90d2007-10-10 09:54:50 +00003776 DAG.getConstant(1, V.getValueType()));
Gabor Greiff304a7a2008-08-28 21:40:38 +00003777 AddToWorkList(V.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003778 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
Chris Lattner58c227b2007-09-10 21:39:07 +00003779 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003780
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003781 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
Owen Anderson9f944592009-08-11 20:47:22 +00003782 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003783 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003784 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003785 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3786 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
Andrew Trickef9de2a2013-05-25 02:42:55 +00003787 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3788 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
Gabor Greiff304a7a2008-08-28 21:40:38 +00003789 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003790 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
Nate Begeman21158fc2005-09-01 00:19:25 +00003791 }
3792 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003793 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
Scott Michelcf0da6c2009-02-17 22:15:04 +00003794 if (N1C && N1C->isAllOnesValue() &&
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003795 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003796 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003797 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3798 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
Andrew Trickef9de2a2013-05-25 02:42:55 +00003799 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3800 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
Gabor Greiff304a7a2008-08-28 21:40:38 +00003801 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003802 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
Nate Begeman21158fc2005-09-01 00:19:25 +00003803 }
3804 }
David Majnemer386ab7f2013-05-08 06:44:42 +00003805 // fold (xor (and x, y), y) -> (and (not x), y)
3806 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
Benjamin Kramerbb1dd732013-11-17 10:40:03 +00003807 N0->getOperand(1) == N1) {
David Majnemer386ab7f2013-05-08 06:44:42 +00003808 SDValue X = N0->getOperand(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003809 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
David Majnemer386ab7f2013-05-08 06:44:42 +00003810 AddToWorkList(NotX.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003811 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
David Majnemer386ab7f2013-05-08 06:44:42 +00003812 }
Bill Wendling35972a92009-01-30 21:14:50 +00003813 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
Nate Begeman85c1cc42005-09-08 20:18:10 +00003814 if (N1C && N0.getOpcode() == ISD::XOR) {
3815 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3816 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3817 if (N00C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003818 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
Bill Wendling35972a92009-01-30 21:14:50 +00003819 DAG.getConstant(N1C->getAPIntValue() ^
Dan Gohmanb72127a2008-03-13 22:13:53 +00003820 N00C->getAPIntValue(), VT));
Nate Begeman85c1cc42005-09-08 20:18:10 +00003821 if (N01C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003822 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
Bill Wendling35972a92009-01-30 21:14:50 +00003823 DAG.getConstant(N1C->getAPIntValue() ^
Dan Gohmanb72127a2008-03-13 22:13:53 +00003824 N01C->getAPIntValue(), VT));
Nate Begeman85c1cc42005-09-08 20:18:10 +00003825 }
3826 // fold (xor x, x) -> 0
Eric Christophere5ca1e02011-02-16 04:50:12 +00003827 if (N0 == N1)
Hal Finkel6c29bd92013-07-09 17:02:45 +00003828 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003829
Chris Lattner8d6fc202006-05-05 05:51:50 +00003830 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3831 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003832 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003833 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00003834 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003835
Chris Lattner098c01e2006-04-08 04:15:24 +00003836 // Simplify the expression using non-local knowledge.
Duncan Sands13237ac2008-06-06 12:08:01 +00003837 if (!VT.isVector() &&
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003838 SimplifyDemandedBits(SDValue(N, 0)))
3839 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003840
Evan Chengf1005572010-04-28 07:10:39 +00003841 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00003842}
3843
Chris Lattner7c709a52007-12-06 07:33:36 +00003844/// visitShiftByConstant - Handle transforms common to the three shifts, when
3845/// the shift amount is a constant.
Matt Arsenault985b9de2014-03-17 18:58:01 +00003846SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003847 // We can't and shouldn't fold opaque constants.
Matt Arsenault985b9de2014-03-17 18:58:01 +00003848 if (Amt->isOpaque())
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003849 return SDValue();
3850
Gabor Greiff304a7a2008-08-28 21:40:38 +00003851 SDNode *LHS = N->getOperand(0).getNode();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003852 if (!LHS->hasOneUse()) return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003853
Chris Lattner7c709a52007-12-06 07:33:36 +00003854 // We want to pull some binops through shifts, so that we have (and (shift))
3855 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3856 // thing happens with address calculations, so it's important to canonicalize
3857 // it.
3858 bool HighBitSet = false; // Can we transform this if the high bit is set?
Scott Michelcf0da6c2009-02-17 22:15:04 +00003859
Chris Lattner7c709a52007-12-06 07:33:36 +00003860 switch (LHS->getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003861 default: return SDValue();
Chris Lattner7c709a52007-12-06 07:33:36 +00003862 case ISD::OR:
3863 case ISD::XOR:
3864 HighBitSet = false; // We can only transform sra if the high bit is clear.
3865 break;
3866 case ISD::AND:
3867 HighBitSet = true; // We can only transform sra if the high bit is set.
3868 break;
3869 case ISD::ADD:
Scott Michelcf0da6c2009-02-17 22:15:04 +00003870 if (N->getOpcode() != ISD::SHL)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003871 return SDValue(); // only shl(add) not sr[al](add).
Chris Lattner7c709a52007-12-06 07:33:36 +00003872 HighBitSet = false; // We can only transform sra if the high bit is clear.
3873 break;
3874 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003875
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003876 // We require the RHS of the binop to be a constant and not opaque as well.
Chris Lattner7c709a52007-12-06 07:33:36 +00003877 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003878 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003879
3880 // FIXME: disable this unless the input to the binop is a shift by a constant.
3881 // If it is not a shift, it pessimizes some common cases like:
Chris Lattnereedaf922007-12-06 07:47:55 +00003882 //
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003883 // void foo(int *X, int i) { X[i & 1235] = 1; }
3884 // int bar(int *X, int i) { return X[i & 255]; }
Gabor Greiff304a7a2008-08-28 21:40:38 +00003885 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003886 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
Chris Lattnereedaf922007-12-06 07:47:55 +00003887 BinOpLHSVal->getOpcode() != ISD::SRA &&
3888 BinOpLHSVal->getOpcode() != ISD::SRL) ||
3889 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003890 return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003891
Owen Anderson53aa7a92009-08-10 22:56:29 +00003892 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003893
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003894 // If this is a signed shift right, and the high bit is modified by the
3895 // logical operation, do not perform the transformation. The highBitSet
3896 // boolean indicates the value of the high bit of the constant which would
3897 // cause it to be modified for this operation.
Chris Lattner7c709a52007-12-06 07:33:36 +00003898 if (N->getOpcode() == ISD::SRA) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003899 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3900 if (BinOpRHSSignSet != HighBitSet)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003901 return SDValue();
Chris Lattner7c709a52007-12-06 07:33:36 +00003902 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003903
Chris Lattner7c709a52007-12-06 07:33:36 +00003904 // Fold the constants, shifting the binop RHS by the shift amount.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003905 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003906 N->getValueType(0),
3907 LHS->getOperand(1), N->getOperand(1));
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003908 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
Chris Lattner7c709a52007-12-06 07:33:36 +00003909
3910 // Create the new shift.
Eric Christopherd9e8eac2010-12-09 04:48:06 +00003911 SDValue NewShift = DAG.getNode(N->getOpcode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00003912 SDLoc(LHS->getOperand(0)),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003913 VT, LHS->getOperand(0), N->getOperand(1));
Chris Lattner7c709a52007-12-06 07:33:36 +00003914
3915 // Create the new binop.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003916 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
Chris Lattner7c709a52007-12-06 07:33:36 +00003917}
3918
Adam Nemet67483892014-03-04 23:28:31 +00003919SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3920 assert(N->getOpcode() == ISD::TRUNCATE);
3921 assert(N->getOperand(0).getOpcode() == ISD::AND);
3922
3923 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3924 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3925 SDValue N01 = N->getOperand(0).getOperand(1);
3926
Matt Arsenault985b9de2014-03-17 18:58:01 +00003927 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
Adam Nemet67483892014-03-04 23:28:31 +00003928 EVT TruncVT = N->getValueType(0);
3929 SDValue N00 = N->getOperand(0).getOperand(0);
3930 APInt TruncC = N01C->getAPIntValue();
Matt Arsenault985b9de2014-03-17 18:58:01 +00003931 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
Adam Nemet67483892014-03-04 23:28:31 +00003932
3933 return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3934 DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
3935 DAG.getConstant(TruncC, TruncVT));
3936 }
3937 }
3938
3939 return SDValue();
3940}
Adam Nemet7f928f12014-03-07 23:56:30 +00003941
3942SDValue DAGCombiner::visitRotate(SDNode *N) {
3943 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
3944 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
3945 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
3946 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
3947 if (NewOp1.getNode())
3948 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
3949 N->getOperand(0), NewOp1);
3950 }
3951 return SDValue();
3952}
3953
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003954SDValue DAGCombiner::visitSHL(SDNode *N) {
3955 SDValue N0 = N->getOperand(0);
3956 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003957 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3958 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00003959 EVT VT = N0.getValueType();
Matt Arsenault985b9de2014-03-17 18:58:01 +00003960 unsigned OpSizeInBits = VT.getScalarSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003961
Daniel Sandersa1840d22013-11-11 17:23:41 +00003962 // fold vector ops
3963 if (VT.isVector()) {
3964 SDValue FoldedVOp = SimplifyVBinOp(N);
3965 if (FoldedVOp.getNode()) return FoldedVOp;
Quentin Colombet4db08df2014-02-21 23:42:41 +00003966
3967 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
3968 // If setcc produces all-one true value then:
3969 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
Matt Arsenault985b9de2014-03-17 18:58:01 +00003970 if (N1CV && N1CV->isConstant()) {
3971 if (N0.getOpcode() == ISD::AND &&
3972 TLI.getBooleanContents(true) ==
3973 TargetLowering::ZeroOrNegativeOneBooleanContent) {
3974 SDValue N00 = N0->getOperand(0);
3975 SDValue N01 = N0->getOperand(1);
3976 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
Quentin Colombet4db08df2014-02-21 23:42:41 +00003977
Matt Arsenault985b9de2014-03-17 18:58:01 +00003978 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC) {
3979 SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
3980 if (C.getNode())
3981 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
3982 }
3983 } else {
3984 N1C = isConstOrConstSplat(N1);
Quentin Colombet4db08df2014-02-21 23:42:41 +00003985 }
3986 }
Daniel Sandersa1840d22013-11-11 17:23:41 +00003987 }
3988
Nate Begeman21158fc2005-09-01 00:19:25 +00003989 // fold (shl c1, c2) -> c1<<c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003990 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00003991 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00003992 // fold (shl 0, x) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003993 if (N0C && N0C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003994 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00003995 // fold (shl x, c >= size(x)) -> undef
Dan Gohmaneffb8942008-09-12 16:56:44 +00003996 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00003997 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00003998 // fold (shl x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003999 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004000 return N0;
Chad Rosier818e1162011-06-14 22:29:10 +00004001 // fold (shl undef, x) -> 0
4002 if (N0.getOpcode() == ISD::UNDEF)
4003 return DAG.getConstant(0, VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004004 // if (shl x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004005 if (DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1d459e42009-12-11 21:31:27 +00004006 APInt::getAllOnesValue(OpSizeInBits)))
Nate Begemand23739d2005-09-06 04:43:02 +00004007 return DAG.getConstant(0, VT);
Duncan Sands3ed76882009-02-01 18:06:53 +00004008 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004009 if (N1.getOpcode() == ISD::TRUNCATE &&
Adam Nemet67483892014-03-04 23:28:31 +00004010 N1.getOperand(0).getOpcode() == ISD::AND) {
4011 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4012 if (NewOp1.getNode())
4013 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004014 }
4015
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004016 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4017 return SDValue(N, 0);
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004018
4019 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
Matt Arsenault985b9de2014-03-17 18:58:01 +00004020 if (N1C && N0.getOpcode() == ISD::SHL) {
4021 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4022 uint64_t c1 = N0C1->getZExtValue();
4023 uint64_t c2 = N1C->getZExtValue();
4024 if (c1 + c2 >= OpSizeInBits)
4025 return DAG.getConstant(0, VT);
4026 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4027 DAG.getConstant(c1 + c2, N1.getValueType()));
4028 }
Nate Begeman21158fc2005-09-01 00:19:25 +00004029 }
Dale Johannesena94e36b2010-12-21 21:55:50 +00004030
4031 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4032 // For this to be valid, the second form must not preserve any of the bits
4033 // that are shifted out by the inner shift in the first form. This means
4034 // the outer shift size must be >= the number of bits added by the ext.
4035 // As a corollary, we don't care what kind of ext it is.
4036 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4037 N0.getOpcode() == ISD::ANY_EXTEND ||
4038 N0.getOpcode() == ISD::SIGN_EXTEND) &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004039 N0.getOperand(0).getOpcode() == ISD::SHL) {
4040 SDValue N0Op0 = N0.getOperand(0);
4041 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4042 uint64_t c1 = N0Op0C1->getZExtValue();
4043 uint64_t c2 = N1C->getZExtValue();
4044 EVT InnerShiftVT = N0Op0.getValueType();
4045 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4046 if (c2 >= OpSizeInBits - InnerShiftSize) {
4047 if (c1 + c2 >= OpSizeInBits)
4048 return DAG.getConstant(0, VT);
4049 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4050 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4051 N0Op0->getOperand(0)),
4052 DAG.getConstant(c1 + c2, N1.getValueType()));
4053 }
Dale Johannesena94e36b2010-12-21 21:55:50 +00004054 }
4055 }
4056
Andrea Di Biagio56ce9c42013-09-27 11:37:05 +00004057 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4058 // Only fold this if the inner zext has no other uses to avoid increasing
4059 // the total number of instructions.
4060 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004061 N0.getOperand(0).getOpcode() == ISD::SRL) {
4062 SDValue N0Op0 = N0.getOperand(0);
4063 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4064 uint64_t c1 = N0Op0C1->getZExtValue();
4065 if (c1 < VT.getScalarSizeInBits()) {
4066 uint64_t c2 = N1C->getZExtValue();
4067 if (c1 == c2) {
4068 SDValue NewOp0 = N0.getOperand(0);
4069 EVT CountVT = NewOp0.getOperand(1).getValueType();
4070 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4071 NewOp0, DAG.getConstant(c2, CountVT));
4072 AddToWorkList(NewSHL.getNode());
4073 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4074 }
Andrea Di Biagio56ce9c42013-09-27 11:37:05 +00004075 }
4076 }
4077 }
4078
Eli Friedman1877ac92011-06-09 22:14:44 +00004079 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4080 // (and (srl x, (sub c1, c2), MASK)
Chandler Carruthe041a302012-01-05 11:05:55 +00004081 // Only fold this if the inner shift has no other uses -- if it does, folding
4082 // this will increase the total number of instructions.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004083 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4084 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4085 uint64_t c1 = N0C1->getZExtValue();
4086 if (c1 < OpSizeInBits) {
4087 uint64_t c2 = N1C->getZExtValue();
4088 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4089 SDValue Shift;
4090 if (c2 > c1) {
4091 Mask = Mask.shl(c2 - c1);
4092 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4093 DAG.getConstant(c2 - c1, N1.getValueType()));
4094 } else {
4095 Mask = Mask.lshr(c1 - c2);
4096 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4097 DAG.getConstant(c1 - c2, N1.getValueType()));
4098 }
4099 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4100 DAG.getConstant(Mask, VT));
Eli Friedman1877ac92011-06-09 22:14:44 +00004101 }
Evan Chenga7bb55e2009-07-21 05:40:15 +00004102 }
Nate Begeman21158fc2005-09-01 00:19:25 +00004103 }
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004104 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
Dan Gohman5758e1e2009-08-06 09:18:59 +00004105 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004106 unsigned BitSize = VT.getScalarSizeInBits();
Dan Gohman5758e1e2009-08-06 09:18:59 +00004107 SDValue HiBitsMask =
Matt Arsenault985b9de2014-03-17 18:58:01 +00004108 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4109 BitSize - N1C->getZExtValue()), VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004110 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
Dan Gohman5758e1e2009-08-06 09:18:59 +00004111 HiBitsMask);
4112 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004113
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004114 if (N1C) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004115 SDValue NewSHL = visitShiftByConstant(N, N1C);
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004116 if (NewSHL.getNode())
4117 return NewSHL;
4118 }
4119
Evan Chengf1005572010-04-28 07:10:39 +00004120 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004121}
4122
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004123SDValue DAGCombiner::visitSRA(SDNode *N) {
4124 SDValue N0 = N->getOperand(0);
4125 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004126 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4127 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004128 EVT VT = N0.getValueType();
Dan Gohman1d459e42009-12-11 21:31:27 +00004129 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004130
Daniel Sandersa1840d22013-11-11 17:23:41 +00004131 // fold vector ops
4132 if (VT.isVector()) {
4133 SDValue FoldedVOp = SimplifyVBinOp(N);
4134 if (FoldedVOp.getNode()) return FoldedVOp;
Matt Arsenault985b9de2014-03-17 18:58:01 +00004135
4136 N1C = isConstOrConstSplat(N1);
Daniel Sandersa1840d22013-11-11 17:23:41 +00004137 }
4138
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004139 // fold (sra c1, c2) -> (sra c1, c2)
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004140 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00004141 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00004142 // fold (sra 0, x) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004143 if (N0C && N0C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004144 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004145 // fold (sra -1, x) -> -1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004146 if (N0C && N0C->isAllOnesValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004147 return N0;
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004148 // fold (sra x, (setge c, size(x))) -> undef
Dan Gohman1d459e42009-12-11 21:31:27 +00004149 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00004150 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004151 // fold (sra x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004152 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004153 return N0;
Nate Begemanfb5dbad2006-02-17 19:54:08 +00004154 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4155 // sext_inreg.
4156 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
Dan Gohman1d459e42009-12-11 21:31:27 +00004157 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004158 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4159 if (VT.isVector())
4160 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4161 ExtVT, VT.getVectorNumElements());
4162 if ((!LegalOperations ||
4163 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004164 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004165 N0.getOperand(0), DAG.getValueType(ExtVT));
Nate Begemanfb5dbad2006-02-17 19:54:08 +00004166 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00004167
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004168 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
Chris Lattner0f8a7272006-02-28 06:23:04 +00004169 if (N1C && N0.getOpcode() == ISD::SRA) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004170 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00004171 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
Matt Arsenault985b9de2014-03-17 18:58:01 +00004172 if (Sum >= OpSizeInBits)
4173 Sum = OpSizeInBits - 1;
Andrew Trickef9de2a2013-05-25 02:42:55 +00004174 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
Matt Arsenault985b9de2014-03-17 18:58:01 +00004175 DAG.getConstant(Sum, N1.getValueType()));
Chris Lattner0f8a7272006-02-28 06:23:04 +00004176 }
4177 }
Christopher Lamb8fe91092008-03-19 08:30:06 +00004178
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004179 // fold (sra (shl X, m), (sub result_size, n))
4180 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
Scott Michelcf0da6c2009-02-17 22:15:04 +00004181 // result_size - n != m.
4182 // If truncate is free for the target sext(shl) is likely to result in better
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004183 // code.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004184 if (N0.getOpcode() == ISD::SHL && N1C) {
Christopher Lamb8fe91092008-03-19 08:30:06 +00004185 // Get the two constanst of the shifts, CN0 = m, CN = n.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004186 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4187 if (N01C) {
4188 LLVMContext &Ctx = *DAG.getContext();
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004189 // Determine what the truncate's result bitsize and type would be.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004190 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4191
4192 if (VT.isVector())
4193 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4194
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004195 // Determine the residual right-shift amount.
Torok Edwinbe6a9a12009-05-23 17:29:48 +00004196 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
Duncan Sands8651e9c2008-06-13 19:07:40 +00004197
Scott Michelcf0da6c2009-02-17 22:15:04 +00004198 // If the shift is not a no-op (in which case this should be just a sign
4199 // extend already), the truncated to type is legal, sign_extend is legal
Dan Gohman4a618822010-02-10 16:03:48 +00004200 // on that type, and the truncate to that type is both legal and free,
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004201 // perform the transform.
Torok Edwinbe6a9a12009-05-23 17:29:48 +00004202 if ((ShiftAmt > 0) &&
Dan Gohman4aa18462009-01-28 17:46:25 +00004203 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4204 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
Evan Cheng7a3e7502008-03-20 02:18:41 +00004205 TLI.isTruncateFree(VT, TruncVT)) {
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004206
Owen Andersonb2c80da2011-02-25 21:41:48 +00004207 SDValue Amt = DAG.getConstant(ShiftAmt,
4208 getShiftAmountTy(N0.getOperand(0).getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004209 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004210 N0.getOperand(0), Amt);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004211 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004212 Shift);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004213 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004214 N->getValueType(0), Trunc);
Christopher Lamb8fe91092008-03-19 08:30:06 +00004215 }
4216 }
4217 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004218
Duncan Sands3ed76882009-02-01 18:06:53 +00004219 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004220 if (N1.getOpcode() == ISD::TRUNCATE &&
Adam Nemet67483892014-03-04 23:28:31 +00004221 N1.getOperand(0).getOpcode() == ISD::AND) {
4222 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4223 if (NewOp1.getNode())
4224 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004225 }
4226
Matt Arsenault985b9de2014-03-17 18:58:01 +00004227 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
Benjamin Kramer946e1522011-01-30 16:38:43 +00004228 // if c1 is equal to the number of bits the trunc removes
4229 if (N0.getOpcode() == ISD::TRUNCATE &&
4230 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4231 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4232 N0.getOperand(0).hasOneUse() &&
4233 N0.getOperand(0).getOperand(1).hasOneUse() &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004234 N1C) {
4235 SDValue N0Op0 = N0.getOperand(0);
4236 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4237 unsigned LargeShiftVal = LargeShift->getZExtValue();
4238 EVT LargeVT = N0Op0.getValueType();
Benjamin Kramer946e1522011-01-30 16:38:43 +00004239
Matt Arsenault985b9de2014-03-17 18:58:01 +00004240 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4241 SDValue Amt =
4242 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4243 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4244 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4245 N0Op0.getOperand(0), Amt);
4246 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4247 }
Benjamin Kramer946e1522011-01-30 16:38:43 +00004248 }
4249 }
4250
Scott Michelcf0da6c2009-02-17 22:15:04 +00004251 // Simplify, based on bits shifted out of the LHS.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004252 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4253 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004254
4255
Nate Begeman21158fc2005-09-01 00:19:25 +00004256 // If the sign bit is known to be zero, switch this to a SRL.
Dan Gohman1f372ed2008-02-25 21:11:39 +00004257 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004258 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
Chris Lattner7c709a52007-12-06 07:33:36 +00004259
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004260 if (N1C) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004261 SDValue NewSRA = visitShiftByConstant(N, N1C);
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004262 if (NewSRA.getNode())
4263 return NewSRA;
4264 }
4265
Evan Chengf1005572010-04-28 07:10:39 +00004266 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004267}
4268
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004269SDValue DAGCombiner::visitSRL(SDNode *N) {
4270 SDValue N0 = N->getOperand(0);
4271 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004272 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4273 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004274 EVT VT = N0.getValueType();
Dan Gohman1d459e42009-12-11 21:31:27 +00004275 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004276
Daniel Sandersa1840d22013-11-11 17:23:41 +00004277 // fold vector ops
4278 if (VT.isVector()) {
4279 SDValue FoldedVOp = SimplifyVBinOp(N);
4280 if (FoldedVOp.getNode()) return FoldedVOp;
Matt Arsenault985b9de2014-03-17 18:58:01 +00004281
4282 N1C = isConstOrConstSplat(N1);
Daniel Sandersa1840d22013-11-11 17:23:41 +00004283 }
4284
Nate Begeman21158fc2005-09-01 00:19:25 +00004285 // fold (srl c1, c2) -> c1 >>u c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004286 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00004287 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00004288 // fold (srl 0, x) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004289 if (N0C && N0C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004290 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004291 // fold (srl x, c >= size(x)) -> undef
Dan Gohmaneffb8942008-09-12 16:56:44 +00004292 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00004293 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004294 // fold (srl x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004295 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004296 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004297 // if (srl x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004298 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1f372ed2008-02-25 21:11:39 +00004299 APInt::getAllOnesValue(OpSizeInBits)))
Nate Begemand23739d2005-09-06 04:43:02 +00004300 return DAG.getConstant(0, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004301
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004302 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
Matt Arsenault985b9de2014-03-17 18:58:01 +00004303 if (N1C && N0.getOpcode() == ISD::SRL) {
4304 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4305 uint64_t c1 = N01C->getZExtValue();
4306 uint64_t c2 = N1C->getZExtValue();
4307 if (c1 + c2 >= OpSizeInBits)
4308 return DAG.getConstant(0, VT);
4309 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4310 DAG.getConstant(c1 + c2, N1.getValueType()));
4311 }
Nate Begeman21158fc2005-09-01 00:19:25 +00004312 }
Wesley Peck527da1b2010-11-23 03:31:01 +00004313
Dale Johannesencd538af2010-12-17 21:45:49 +00004314 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
Dale Johannesencd538af2010-12-17 21:45:49 +00004315 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4316 N0.getOperand(0).getOpcode() == ISD::SRL &&
Dale Johannesen0a291a32010-12-20 20:10:50 +00004317 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
Owen Andersonb2c80da2011-02-25 21:41:48 +00004318 uint64_t c1 =
Dale Johannesencd538af2010-12-17 21:45:49 +00004319 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4320 uint64_t c2 = N1C->getZExtValue();
Dale Johannesena94e36b2010-12-21 21:55:50 +00004321 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4322 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
Dale Johannesencd538af2010-12-17 21:45:49 +00004323 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
Dale Johannesen0a291a32010-12-20 20:10:50 +00004324 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
Dale Johannesencd538af2010-12-17 21:45:49 +00004325 if (c1 + OpSizeInBits == InnerShiftSize) {
4326 if (c1 + c2 >= InnerShiftSize)
4327 return DAG.getConstant(0, VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004328 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4329 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
Dale Johannesencd538af2010-12-17 21:45:49 +00004330 N0.getOperand(0)->getOperand(0),
Dale Johannesena94e36b2010-12-21 21:55:50 +00004331 DAG.getConstant(c1 + c2, ShiftCountVT)));
Dale Johannesencd538af2010-12-17 21:45:49 +00004332 }
4333 }
4334
Chris Lattnerf9b2e3c2010-04-15 05:28:43 +00004335 // fold (srl (shl x, c), c) -> (and x, cst2)
Matt Arsenault985b9de2014-03-17 18:58:01 +00004336 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4337 unsigned BitSize = N0.getScalarValueSizeInBits();
4338 if (BitSize <= 64) {
4339 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4340 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4341 DAG.getConstant(~0ULL >> ShAmt, VT));
4342 }
Chris Lattnerf9b2e3c2010-04-15 05:28:43 +00004343 }
Wesley Peck527da1b2010-11-23 03:31:01 +00004344
Michael Liao62ebfd82013-06-21 18:45:27 +00004345 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004346 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4347 // Shifting in all undef bits?
Owen Anderson53aa7a92009-08-10 22:56:29 +00004348 EVT SmallVT = N0.getOperand(0).getValueType();
Matt Arsenault985b9de2014-03-17 18:58:01 +00004349 unsigned BitSize = SmallVT.getScalarSizeInBits();
4350 if (N1C->getZExtValue() >= BitSize)
Dale Johannesen84935752009-02-06 23:05:02 +00004351 return DAG.getUNDEF(VT);
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004352
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004353 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
Owen Andersona5192842011-04-14 17:30:49 +00004354 uint64_t ShiftAmt = N1C->getZExtValue();
Andrew Trickef9de2a2013-05-25 02:42:55 +00004355 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
Owen Andersona5192842011-04-14 17:30:49 +00004356 N0.getOperand(0),
4357 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004358 AddToWorkList(SmallShift.getNode());
Matt Arsenault985b9de2014-03-17 18:58:01 +00004359 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
Michael Liao62ebfd82013-06-21 18:45:27 +00004360 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4361 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4362 DAG.getConstant(Mask, VT));
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004363 }
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004364 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004365
Chris Lattner2e33fb42006-10-12 20:23:19 +00004366 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4367 // bit, which is unmodified by sra.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004368 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
Chris Lattner2e33fb42006-10-12 20:23:19 +00004369 if (N0.getOpcode() == ISD::SRA)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004370 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
Chris Lattner2e33fb42006-10-12 20:23:19 +00004371 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004372
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00004373 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
Scott Michelcf0da6c2009-02-17 22:15:04 +00004374 if (N1C && N0.getOpcode() == ISD::CTLZ &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004375 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004376 APInt KnownZero, KnownOne;
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00004377 DAG.ComputeMaskedBits(N0.getOperand(0), KnownZero, KnownOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004378
Chris Lattner49932492006-04-02 06:11:11 +00004379 // If any of the input bits are KnownOne, then the input couldn't be all
4380 // zeros, thus the result of the srl will always be zero.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004381 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004382
Chris Lattner49932492006-04-02 06:11:11 +00004383 // If all of the bits input the to ctlz node are known to be zero, then
4384 // the result of the ctlz is "32" and the result of the shift is one.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00004385 APInt UnknownBits = ~KnownZero;
Chris Lattner49932492006-04-02 06:11:11 +00004386 if (UnknownBits == 0) return DAG.getConstant(1, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004387
Chris Lattner49932492006-04-02 06:11:11 +00004388 // Otherwise, check to see if there is exactly one bit input to the ctlz.
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004389 if ((UnknownBits & (UnknownBits - 1)) == 0) {
Chris Lattner49932492006-04-02 06:11:11 +00004390 // Okay, we know that only that the single bit specified by UnknownBits
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004391 // could be set on input to the CTLZ node. If this bit is set, the SRL
4392 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4393 // to an SRL/XOR pair, which is likely to simplify more.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004394 unsigned ShAmt = UnknownBits.countTrailingZeros();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004395 SDValue Op = N0.getOperand(0);
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004396
Chris Lattner49932492006-04-02 06:11:11 +00004397 if (ShAmt) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004398 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
Owen Andersonb2c80da2011-02-25 21:41:48 +00004399 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
Gabor Greiff304a7a2008-08-28 21:40:38 +00004400 AddToWorkList(Op.getNode());
Chris Lattner49932492006-04-02 06:11:11 +00004401 }
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004402
Andrew Trickef9de2a2013-05-25 02:42:55 +00004403 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004404 Op, DAG.getConstant(1, VT));
Chris Lattner49932492006-04-02 06:11:11 +00004405 }
4406 }
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004407
Duncan Sands3ed76882009-02-01 18:06:53 +00004408 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004409 if (N1.getOpcode() == ISD::TRUNCATE &&
Adam Nemet67483892014-03-04 23:28:31 +00004410 N1.getOperand(0).getOpcode() == ISD::AND) {
4411 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4412 if (NewOp1.getNode())
4413 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004414 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004415
Chris Lattnerf03c90b2007-04-18 03:06:49 +00004416 // fold operands of srl based on knowledge that the low bits are not
4417 // demanded.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004418 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4419 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004420
Evan Chengb175de62009-12-18 21:31:31 +00004421 if (N1C) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004422 SDValue NewSRL = visitShiftByConstant(N, N1C);
Evan Chengb175de62009-12-18 21:31:31 +00004423 if (NewSRL.getNode())
4424 return NewSRL;
4425 }
4426
Dan Gohman600f62b2010-06-24 14:30:44 +00004427 // Attempt to convert a srl of a load into a narrower zero-extending load.
4428 SDValue NarrowLoad = ReduceLoadWidth(N);
4429 if (NarrowLoad.getNode())
4430 return NarrowLoad;
4431
Evan Chengb175de62009-12-18 21:31:31 +00004432 // Here is a common situation. We want to optimize:
4433 //
4434 // %a = ...
4435 // %b = and i32 %a, 2
4436 // %c = srl i32 %b, 1
4437 // brcond i32 %c ...
4438 //
4439 // into
Wesley Peck527da1b2010-11-23 03:31:01 +00004440 //
Evan Chengb175de62009-12-18 21:31:31 +00004441 // %a = ...
4442 // %b = and %a, 2
4443 // %c = setcc eq %b, 0
4444 // brcond %c ...
4445 //
4446 // However when after the source operand of SRL is optimized into AND, the SRL
4447 // itself may not be optimized further. Look for it and add the BRCOND into
4448 // the worklist.
Evan Cheng166a4e62010-01-06 19:38:29 +00004449 if (N->hasOneUse()) {
4450 SDNode *Use = *N->use_begin();
4451 if (Use->getOpcode() == ISD::BRCOND)
4452 AddToWorkList(Use);
4453 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4454 // Also look pass the truncate.
4455 Use = *Use->use_begin();
4456 if (Use->getOpcode() == ISD::BRCOND)
4457 AddToWorkList(Use);
4458 }
4459 }
Evan Chengb175de62009-12-18 21:31:31 +00004460
Evan Chengf1005572010-04-28 07:10:39 +00004461 return SDValue();
Evan Chenge19aa5c2010-04-19 19:29:22 +00004462}
4463
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004464SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4465 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004466 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00004467
4468 // fold (ctlz c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004469 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004470 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004471 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004472}
4473
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004474SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4475 SDValue N0 = N->getOperand(0);
4476 EVT VT = N->getValueType(0);
4477
4478 // fold (ctlz_zero_undef c1) -> c2
4479 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004480 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004481 return SDValue();
4482}
4483
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004484SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4485 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004486 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004487
Nate Begeman21158fc2005-09-01 00:19:25 +00004488 // fold (cttz c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004489 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004490 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004491 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004492}
4493
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004494SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4495 SDValue N0 = N->getOperand(0);
4496 EVT VT = N->getValueType(0);
4497
4498 // fold (cttz_zero_undef c1) -> c2
4499 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004500 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004501 return SDValue();
4502}
4503
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004504SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4505 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004506 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004507
Nate Begeman21158fc2005-09-01 00:19:25 +00004508 // fold (ctpop c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004509 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004510 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004511 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004512}
4513
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004514SDValue DAGCombiner::visitSELECT(SDNode *N) {
4515 SDValue N0 = N->getOperand(0);
4516 SDValue N1 = N->getOperand(1);
4517 SDValue N2 = N->getOperand(2);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004518 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4519 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4520 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004521 EVT VT = N->getValueType(0);
4522 EVT VT0 = N0.getValueType();
Nate Begemanc760f802005-09-19 22:34:01 +00004523
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004524 // fold (select C, X, X) -> X
Nate Begeman24a7eca2005-09-16 00:54:12 +00004525 if (N1 == N2)
4526 return N1;
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004527 // fold (select true, X, Y) -> X
Nate Begeman24a7eca2005-09-16 00:54:12 +00004528 if (N0C && !N0C->isNullValue())
4529 return N1;
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004530 // fold (select false, X, Y) -> Y
Nate Begeman24a7eca2005-09-16 00:54:12 +00004531 if (N0C && N0C->isNullValue())
4532 return N2;
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004533 // fold (select C, 1, X) -> (or C, X)
Owen Anderson9f944592009-08-11 20:47:22 +00004534 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004535 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004536 // fold (select C, 0, 1) -> (xor C, 1)
Bob Wilsonc2dc7ee2009-01-22 22:05:48 +00004537 if (VT.isInteger() &&
Owen Anderson9f944592009-08-11 20:47:22 +00004538 (VT0 == MVT::i1 ||
Bob Wilsonc2dc7ee2009-01-22 22:05:48 +00004539 (VT0.isInteger() &&
Nadav Rotem841c9a82012-09-20 08:53:31 +00004540 TLI.getBooleanContents(false) ==
4541 TargetLowering::ZeroOrOneBooleanContent)) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00004542 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004543 SDValue XORNode;
Evan Chengf5a23ab2007-08-18 05:57:05 +00004544 if (VT == VT0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004545 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004546 N0, DAG.getConstant(1, VT0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004547 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004548 N0, DAG.getConstant(1, VT0));
Gabor Greiff304a7a2008-08-28 21:40:38 +00004549 AddToWorkList(XORNode.getNode());
Duncan Sands11dd4242008-06-08 20:54:56 +00004550 if (VT.bitsGT(VT0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004551 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4552 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
Evan Chengf5a23ab2007-08-18 05:57:05 +00004553 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004554 // fold (select C, 0, X) -> (and (not C), X)
Owen Anderson9f944592009-08-11 20:47:22 +00004555 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004556 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
Bob Wilsonc5890052009-01-22 17:39:32 +00004557 AddToWorkList(NOTNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004558 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004559 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004560 // fold (select C, X, 1) -> (or (not C), X)
Owen Anderson9f944592009-08-11 20:47:22 +00004561 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004562 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
Bob Wilsonc5890052009-01-22 17:39:32 +00004563 AddToWorkList(NOTNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004564 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004565 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004566 // fold (select C, X, 0) -> (and C, X)
Owen Anderson9f944592009-08-11 20:47:22 +00004567 if (VT == MVT::i1 && N2C && N2C->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00004568 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004569 // fold (select X, X, Y) -> (or X, Y)
4570 // fold (select X, 1, Y) -> (or X, Y)
Owen Anderson9f944592009-08-11 20:47:22 +00004571 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004572 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004573 // fold (select X, Y, X) -> (and X, Y)
4574 // fold (select X, Y, 0) -> (and X, Y)
Owen Anderson9f944592009-08-11 20:47:22 +00004575 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004576 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004577
Chris Lattner6c14c352005-10-18 06:04:22 +00004578 // If we can fold this based on the true/false value, do so.
4579 if (SimplifySelectOps(N, N1, N2))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004580 return SDValue(N, 0); // Don't revisit N.
Duncan Sands8651e9c2008-06-13 19:07:40 +00004581
Nate Begemanc760f802005-09-19 22:34:01 +00004582 // fold selects based on a setcc into other things, such as min/max/abs
Anton Korobeynikov035eaac2008-02-20 11:10:28 +00004583 if (N0.getOpcode() == ISD::SETCC) {
Nate Begeman7e7f4392006-02-01 07:19:44 +00004584 // FIXME:
Owen Anderson9f944592009-08-11 20:47:22 +00004585 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
Nate Begeman7e7f4392006-02-01 07:19:44 +00004586 // having to say they don't support SELECT_CC on every type the DAG knows
4587 // about, since there is no way to mark an opcode illegal at all value types
Owen Anderson9f944592009-08-11 20:47:22 +00004588 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
Dan Gohman3f323842009-08-02 16:19:38 +00004589 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004590 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004591 N0.getOperand(0), N0.getOperand(1),
Nate Begeman7e7f4392006-02-01 07:19:44 +00004592 N1, N2, N0.getOperand(2));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004593 return SimplifySelect(SDLoc(N), N0, N1, N2);
Anton Korobeynikov035eaac2008-02-20 11:10:28 +00004594 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004595
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004596 return SDValue();
Nate Begeman24a7eca2005-09-16 00:54:12 +00004597}
4598
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004599static
4600std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4601 SDLoc DL(N);
4602 EVT LoVT, HiVT;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +00004603 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004604
4605 // Split the inputs.
4606 SDValue Lo, Hi, LL, LH, RL, RH;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +00004607 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4608 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004609
4610 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4611 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4612
4613 return std::make_pair(Lo, Hi);
4614}
4615
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00004616SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4617 SDValue N0 = N->getOperand(0);
4618 SDValue N1 = N->getOperand(1);
4619 SDValue N2 = N->getOperand(2);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004620 SDLoc DL(N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00004621
4622 // Canonicalize integer abs.
4623 // vselect (setg[te] X, 0), X, -X ->
4624 // vselect (setgt X, -1), X, -X ->
4625 // vselect (setl[te] X, 0), -X, X ->
4626 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4627 if (N0.getOpcode() == ISD::SETCC) {
4628 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4629 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4630 bool isAbs = false;
4631 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4632
4633 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4634 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4635 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4636 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4637 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4638 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4639 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4640
4641 if (isAbs) {
4642 EVT VT = LHS.getValueType();
4643 SDValue Shift = DAG.getNode(
4644 ISD::SRA, DL, VT, LHS,
4645 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4646 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4647 AddToWorkList(Shift.getNode());
4648 AddToWorkList(Add.getNode());
4649 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4650 }
4651 }
4652
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004653 // If the VSELECT result requires splitting and the mask is provided by a
4654 // SETCC, then split both nodes and its operands before legalization. This
4655 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4656 // and enables future optimizations (e.g. min/max pattern matching on X86).
4657 if (N0.getOpcode() == ISD::SETCC) {
4658 EVT VT = N->getValueType(0);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004659
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004660 // Check if any splitting is required.
4661 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4662 TargetLowering::TypeSplitVector)
4663 return SDValue();
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004664
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004665 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +00004666 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4667 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4668 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004669
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004670 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4671 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004672
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004673 // Add the new VSELECT nodes to the work list in case they need to be split
4674 // again.
4675 AddToWorkList(Lo.getNode());
4676 AddToWorkList(Hi.getNode());
4677
4678 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004679 }
4680
Andrea Di Biagio23df4e42014-01-08 18:33:04 +00004681 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4682 if (ISD::isBuildVectorAllOnes(N0.getNode()))
4683 return N1;
4684 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4685 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4686 return N2;
4687
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00004688 return SDValue();
4689}
4690
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004691SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4692 SDValue N0 = N->getOperand(0);
4693 SDValue N1 = N->getOperand(1);
4694 SDValue N2 = N->getOperand(2);
4695 SDValue N3 = N->getOperand(3);
4696 SDValue N4 = N->getOperand(4);
Nate Begemanc760f802005-09-19 22:34:01 +00004697 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004698
Nate Begemanc760f802005-09-19 22:34:01 +00004699 // fold select_cc lhs, rhs, x, x, cc -> x
4700 if (N2 == N3)
4701 return N2;
Scott Michelcf0da6c2009-02-17 22:15:04 +00004702
Chris Lattner8b68dec2006-09-20 06:19:26 +00004703 // Determine if the condition we're dealing with is constant
Matt Arsenault758659232013-05-18 00:21:46 +00004704 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00004705 N0, N1, CC, SDLoc(N), false);
Stephen Lin605207f2013-06-15 04:03:33 +00004706 if (SCC.getNode()) {
4707 AddToWorkList(SCC.getNode());
Chris Lattner8b68dec2006-09-20 06:19:26 +00004708
Stephen Lin605207f2013-06-15 04:03:33 +00004709 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4710 if (!SCCC->isNullValue())
4711 return N2; // cond always true -> true val
4712 else
4713 return N3; // cond always false -> false val
4714 }
4715
4716 // Fold to a simpler select_cc
4717 if (SCC.getOpcode() == ISD::SETCC)
4718 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4719 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4720 SCC.getOperand(2));
Chris Lattner8b68dec2006-09-20 06:19:26 +00004721 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004722
Chris Lattner6c14c352005-10-18 06:04:22 +00004723 // If we can fold this based on the true/false value, do so.
4724 if (SimplifySelectOps(N, N2, N3))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004725 return SDValue(N, 0); // Don't revisit N.
Scott Michelcf0da6c2009-02-17 22:15:04 +00004726
Nate Begemanc760f802005-09-19 22:34:01 +00004727 // fold select_cc into other things, such as min/max/abs
Andrew Trickef9de2a2013-05-25 02:42:55 +00004728 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004729}
4730
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004731SDValue DAGCombiner::visitSETCC(SDNode *N) {
Nate Begeman24a7eca2005-09-16 00:54:12 +00004732 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
Dale Johannesenf1163e92009-02-03 00:47:48 +00004733 cast<CondCodeSDNode>(N->getOperand(2))->get(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00004734 SDLoc(N));
Nate Begeman24a7eca2005-09-16 00:54:12 +00004735}
4736
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004737// tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4738// dag node into a ConstantSDNode or a build_vector of constants.
4739// This function is called by the DAGCombiner when visiting sext/zext/aext
4740// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
4741// Vector extends are not folded if operations are legal; this is to
4742// avoid introducing illegal build_vector dag nodes.
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004743static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4744 SelectionDAG &DAG, bool LegalTypes,
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004745 bool LegalOperations) {
4746 unsigned Opcode = N->getOpcode();
4747 SDValue N0 = N->getOperand(0);
4748 EVT VT = N->getValueType(0);
4749
4750 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4751 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4752
4753 // fold (sext c1) -> c1
4754 // fold (zext c1) -> c1
4755 // fold (aext c1) -> c1
4756 if (isa<ConstantSDNode>(N0))
4757 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4758
4759 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4760 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4761 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004762 EVT SVT = VT.getScalarType();
4763 if (!(VT.isVector() &&
4764 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004765 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
Craig Topperc0196b12014-04-14 00:51:57 +00004766 return nullptr;
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004767
4768 // We can fold this node into a build_vector.
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004769 unsigned VTBits = SVT.getSizeInBits();
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004770 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4771 unsigned ShAmt = VTBits - EVTBits;
4772 SmallVector<SDValue, 8> Elts;
4773 unsigned NumElts = N0->getNumOperands();
4774 SDLoc DL(N);
4775
4776 for (unsigned i=0; i != NumElts; ++i) {
4777 SDValue Op = N0->getOperand(i);
4778 if (Op->getOpcode() == ISD::UNDEF) {
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004779 Elts.push_back(DAG.getUNDEF(SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004780 continue;
4781 }
4782
4783 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4784 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4785 if (Opcode == ISD::SIGN_EXTEND)
4786 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004787 SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004788 else
4789 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004790 SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004791 }
4792
4793 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, &Elts[0], NumElts).getNode();
4794}
4795
Evan Chenge106e2f2007-10-29 19:58:20 +00004796// ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
Dan Gohman0e8d1992009-04-09 03:51:29 +00004797// "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
Evan Chenge106e2f2007-10-29 19:58:20 +00004798// transformation. Returns true if extension are possible and the above
Scott Michelcf0da6c2009-02-17 22:15:04 +00004799// mentioned transformation is profitable.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004800static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
Evan Chenge106e2f2007-10-29 19:58:20 +00004801 unsigned ExtOpc,
Craig Topperb94011f2013-07-14 04:42:23 +00004802 SmallVectorImpl<SDNode *> &ExtendNodes,
Dan Gohman619ef482009-01-15 19:20:50 +00004803 const TargetLowering &TLI) {
Evan Chenge106e2f2007-10-29 19:58:20 +00004804 bool HasCopyToRegUses = false;
4805 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
Gabor Greife12264b2008-08-30 19:29:20 +00004806 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4807 UE = N0.getNode()->use_end();
Evan Chenge106e2f2007-10-29 19:58:20 +00004808 UI != UE; ++UI) {
Dan Gohman91e5dcb2008-07-27 20:43:25 +00004809 SDNode *User = *UI;
Evan Chenge106e2f2007-10-29 19:58:20 +00004810 if (User == N)
4811 continue;
Dan Gohman0e8d1992009-04-09 03:51:29 +00004812 if (UI.getUse().getResNo() != N0.getResNo())
4813 continue;
Evan Chenge106e2f2007-10-29 19:58:20 +00004814 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
Dan Gohman0e8d1992009-04-09 03:51:29 +00004815 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
Evan Chenge106e2f2007-10-29 19:58:20 +00004816 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4817 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4818 // Sign bits will be lost after a zext.
4819 return false;
4820 bool Add = false;
4821 for (unsigned i = 0; i != 2; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004822 SDValue UseOp = User->getOperand(i);
Evan Chenge106e2f2007-10-29 19:58:20 +00004823 if (UseOp == N0)
4824 continue;
4825 if (!isa<ConstantSDNode>(UseOp))
4826 return false;
4827 Add = true;
4828 }
4829 if (Add)
4830 ExtendNodes.push_back(User);
Dan Gohman0e8d1992009-04-09 03:51:29 +00004831 continue;
Evan Chenge106e2f2007-10-29 19:58:20 +00004832 }
Dan Gohman0e8d1992009-04-09 03:51:29 +00004833 // If truncates aren't free and there are users we can't
4834 // extend, it isn't worthwhile.
4835 if (!isTruncFree)
4836 return false;
4837 // Remember if this value is live-out.
4838 if (User->getOpcode() == ISD::CopyToReg)
4839 HasCopyToRegUses = true;
Evan Chenge106e2f2007-10-29 19:58:20 +00004840 }
4841
4842 if (HasCopyToRegUses) {
4843 bool BothLiveOut = false;
4844 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4845 UI != UE; ++UI) {
Dan Gohman0e8d1992009-04-09 03:51:29 +00004846 SDUse &Use = UI.getUse();
4847 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4848 BothLiveOut = true;
4849 break;
Evan Chenge106e2f2007-10-29 19:58:20 +00004850 }
4851 }
4852 if (BothLiveOut)
4853 // Both unextended and extended values are live out. There had better be
Bob Wilsonf9b96c42010-11-28 06:51:19 +00004854 // a good reason for the transformation.
Evan Chenge106e2f2007-10-29 19:58:20 +00004855 return ExtendNodes.size();
4856 }
4857 return true;
4858}
4859
Craig Toppere0b71182013-07-13 07:43:40 +00004860void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
Andrew Trickef9de2a2013-05-25 02:42:55 +00004861 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004862 ISD::NodeType ExtType) {
4863 // Extend SetCC uses if necessary.
4864 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4865 SDNode *SetCC = SetCCs[i];
4866 SmallVector<SDValue, 4> Ops;
4867
4868 for (unsigned j = 0; j != 2; ++j) {
4869 SDValue SOp = SetCC->getOperand(j);
4870 if (SOp == Trunc)
4871 Ops.push_back(ExtLoad);
4872 else
4873 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4874 }
4875
4876 Ops.push_back(SetCC->getOperand(2));
4877 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0),
4878 &Ops[0], Ops.size()));
4879 }
4880}
4881
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004882SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4883 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004884 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00004885
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00004886 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
4887 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00004888 return SDValue(Res, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004889
Nadav Rotem9450fcf2013-01-20 08:35:56 +00004890 // fold (sext (sext x)) -> (sext x)
4891 // fold (sext (aext x)) -> (sext x)
4892 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004893 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
Nadav Rotem9450fcf2013-01-20 08:35:56 +00004894 N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00004895
Chris Lattnerfce448f2007-02-26 03:13:59 +00004896 if (N0.getOpcode() == ISD::TRUNCATE) {
Dan Gohmanc1a4e212008-05-20 20:56:33 +00004897 // fold (sext (truncate (load x))) -> (sext (smaller load x))
4898 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00004899 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4900 if (NarrowLoad.getNode()) {
Dale Johannesenff384ad2010-05-25 17:50:03 +00004901 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4902 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00004903 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesenff384ad2010-05-25 17:50:03 +00004904 // CombineTo deleted the truncate, if needed, but not what's under it.
4905 AddToWorkList(oye);
4906 }
Dan Gohmanbe36f5c2009-04-27 02:00:55 +00004907 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00004908 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00004909
Dan Gohmanc1a4e212008-05-20 20:56:33 +00004910 // See if the value being truncated is already sign extended. If so, just
4911 // eliminate the trunc/sext pair.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004912 SDValue Op = N0.getOperand(0);
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004913 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
4914 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
4915 unsigned DestBits = VT.getScalarType().getSizeInBits();
Dan Gohman309d3d52007-06-22 14:59:07 +00004916 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004917
Chris Lattnerfce448f2007-02-26 03:13:59 +00004918 if (OpBits == DestBits) {
4919 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
4920 // bits, it is already ready.
4921 if (NumSignBits > DestBits-MidBits)
4922 return Op;
4923 } else if (OpBits < DestBits) {
4924 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
4925 // bits, just sext from i32.
4926 if (NumSignBits > OpBits-MidBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004927 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
Chris Lattnerfce448f2007-02-26 03:13:59 +00004928 } else {
4929 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
4930 // bits, just truncate to i32.
4931 if (NumSignBits > OpBits-MidBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004932 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chris Lattnera31f0a62006-09-21 06:00:20 +00004933 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004934
Chris Lattnerfce448f2007-02-26 03:13:59 +00004935 // fold (sext (truncate x)) -> (sextinreg x).
Duncan Sandsdc2dac12008-11-24 14:53:14 +00004936 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4937 N0.getValueType())) {
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004938 if (OpBits < DestBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004939 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004940 else if (OpBits > DestBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004941 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
4942 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004943 DAG.getValueType(N0.getValueType()));
Chris Lattnerfce448f2007-02-26 03:13:59 +00004944 }
Chris Lattnera31f0a62006-09-21 06:00:20 +00004945 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004946
Evan Chengbce7c472005-12-14 02:19:23 +00004947 // fold (sext (load x)) -> (sext (truncate (sextload x)))
Nadav Rotem502f1b92011-02-24 21:01:34 +00004948 // None of the supported targets knows how to perform load and sign extend
Nadav Rotemb0091302011-02-27 07:40:43 +00004949 // on vectors in one instruction. We only perform this transformation on
4950 // scalars.
Nadav Rotem502f1b92011-02-24 21:01:34 +00004951 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Quentin Colombet0b1a5582014-04-09 20:03:05 +00004952 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00004953 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00004954 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
Evan Chenge106e2f2007-10-29 19:58:20 +00004955 bool DoXform = true;
4956 SmallVector<SDNode*, 4> SetCCs;
4957 if (!N0.hasOneUse())
4958 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
4959 if (DoXform) {
4960 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004961 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Dan Gohman0e8d1992009-04-09 03:51:29 +00004962 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00004963 LN0->getBasePtr(), N0.getValueType(),
4964 LN0->getMemOperand());
Evan Chenge106e2f2007-10-29 19:58:20 +00004965 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004966 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00004967 N0.getValueType(), ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00004968 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004969 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004970 ISD::SIGN_EXTEND);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004971 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenge106e2f2007-10-29 19:58:20 +00004972 }
Nate Begeman8caf81d2005-10-12 20:40:40 +00004973 }
Chris Lattner7dac1082005-12-14 19:05:06 +00004974
4975 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
4976 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00004977 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4978 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00004979 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00004980 EVT MemVT = LN0->getMemoryVT();
Duncan Sandsdc2dac12008-11-24 14:53:14 +00004981 if ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00004982 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004983 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00004984 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00004985 LN0->getBasePtr(), MemVT,
4986 LN0->getMemOperand());
Jim Laskey26df19a2006-12-15 21:38:30 +00004987 CombineTo(N, ExtLoad);
Gabor Greife12264b2008-08-30 19:29:20 +00004988 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00004989 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00004990 N0.getValueType(), ExtLoad),
Jim Laskey26df19a2006-12-15 21:38:30 +00004991 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004992 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Jim Laskey26df19a2006-12-15 21:38:30 +00004993 }
Chris Lattner7dac1082005-12-14 19:05:06 +00004994 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004995
Nick Lewycky6d677cf2011-06-16 01:15:49 +00004996 // fold (sext (and/or/xor (load x), cst)) ->
4997 // (and/or/xor (sextload x), (sext cst))
4998 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4999 N0.getOpcode() == ISD::XOR) &&
5000 isa<LoadSDNode>(N0.getOperand(0)) &&
5001 N0.getOperand(1).getOpcode() == ISD::Constant &&
5002 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
5003 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5004 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005005 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005006 bool DoXform = true;
5007 SmallVector<SDNode*, 4> SetCCs;
5008 if (!N0.hasOneUse())
5009 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5010 SetCCs, TLI);
5011 if (DoXform) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005012 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005013 LN0->getChain(), LN0->getBasePtr(),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005014 LN0->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005015 LN0->getMemOperand());
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005016 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5017 Mask = Mask.sext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005018 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005019 ExtLoad, DAG.getConstant(Mask, VT));
5020 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00005021 SDLoc(N0.getOperand(0)),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005022 N0.getOperand(0).getValueType(), ExtLoad);
5023 CombineTo(N, And);
5024 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005025 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005026 ISD::SIGN_EXTEND);
5027 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5028 }
5029 }
5030 }
5031
Chris Lattner65786b02007-04-11 05:32:27 +00005032 if (N0.getOpcode() == ISD::SETCC) {
Chris Lattner4ac60732009-07-08 00:31:33 +00005033 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
Dan Gohmane82c25e2010-04-30 17:19:19 +00005034 // Only do this before legalize for now.
Owen Anderson2d4cca32013-04-23 18:09:28 +00005035 if (VT.isVector() && !LegalOperations &&
Stephen Lincfe7f352013-07-08 00:37:03 +00005036 TLI.getBooleanContents(true) ==
Owen Anderson2d4cca32013-04-23 18:09:28 +00005037 TargetLowering::ZeroOrNegativeOneBooleanContent) {
Dan Gohmane82c25e2010-04-30 17:19:19 +00005038 EVT N0VT = N0.getOperand(0).getValueType();
Nadav Rotem9d376b62012-04-11 08:26:11 +00005039 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5040 // of the same size as the compared operands. Only optimize sext(setcc())
5041 // if this is the case.
Matt Arsenault758659232013-05-18 00:21:46 +00005042 EVT SVT = getSetCCResultType(N0VT);
Nadav Rotem9d376b62012-04-11 08:26:11 +00005043
5044 // We know that the # elements of the results is the same as the
5045 // # elements of the compare (and the # elements of the compare result
5046 // for that matter). Check to see that they are the same size. If so,
5047 // we know that the element size of the sext'd result matches the
5048 // element size of the compare operands.
5049 if (VT.getSizeInBits() == SVT.getSizeInBits())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005050 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005051 N0.getOperand(1),
5052 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Matt Arsenault04126232013-05-17 21:43:43 +00005053
Dan Gohmane82c25e2010-04-30 17:19:19 +00005054 // If the desired elements are smaller or larger than the source
5055 // elements we can use a matching integer vector type and then
5056 // truncate/sign extend
Matt Arsenault04126232013-05-17 21:43:43 +00005057 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
Craig Topper5f9791f2012-09-29 07:18:53 +00005058 if (SVT == MatchingVectorType) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005059 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
Craig Topper5f9791f2012-09-29 07:18:53 +00005060 N0.getOperand(0), N0.getOperand(1),
5061 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005062 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
Dan Gohmane82c25e2010-04-30 17:19:19 +00005063 }
Chris Lattner4ac60732009-07-08 00:31:33 +00005064 }
Dan Gohmane82c25e2010-04-30 17:19:19 +00005065
Matt Arsenault5f2a92a2014-01-27 21:41:54 +00005066 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
Dan Gohman5544b0c2010-04-24 01:17:30 +00005067 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
Dan Gohman5758e1e2009-08-06 09:18:59 +00005068 SDValue NegOne =
Dan Gohman5544b0c2010-04-24 01:17:30 +00005069 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005070 SDValue SCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005071 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Dan Gohman5758e1e2009-08-06 09:18:59 +00005072 NegOne, DAG.getConstant(0, VT),
Chris Lattnera083ffc2007-04-11 06:50:51 +00005073 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005074 if (SCC.getNode()) return SCC;
Matt Arsenault5f2a92a2014-01-27 21:41:54 +00005075
5076 if (!VT.isVector()) {
5077 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5078 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5079 SDLoc DL(N);
5080 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5081 SDValue SetCC = DAG.getSetCC(DL,
5082 SetCCVT,
5083 N0.getOperand(0), N0.getOperand(1), CC);
5084 EVT SelectVT = getSetCCResultType(VT);
5085 return DAG.getSelect(DL, VT,
5086 DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
5087 NegOne, DAG.getConstant(0, VT));
5088
5089 }
Matt Arsenaultd2f03322013-06-14 22:04:37 +00005090 }
Wesley Peck527da1b2010-11-23 03:31:01 +00005091 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005092
Dan Gohman3eb10f72008-04-28 16:58:24 +00005093 // fold (sext x) -> (zext x) if the sign bit is known zero.
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005094 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
Dan Gohmanc968c1f2008-04-28 18:47:17 +00005095 DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005096 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005097
Evan Chengf1005572010-04-28 07:10:39 +00005098 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00005099}
5100
Rafael Espindola8f62b322012-04-09 16:06:03 +00005101// isTruncateOf - If N is a truncate of some other value, return true, record
5102// the value being truncated in Op and which of Op's bits are zero in KnownZero.
5103// This function computes KnownZero to avoid a duplicated call to
5104// ComputeMaskedBits in the caller.
5105static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5106 APInt &KnownZero) {
5107 APInt KnownOne;
5108 if (N->getOpcode() == ISD::TRUNCATE) {
5109 Op = N->getOperand(0);
5110 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
5111 return true;
5112 }
5113
5114 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5115 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5116 return false;
5117
5118 SDValue Op0 = N->getOperand(0);
5119 SDValue Op1 = N->getOperand(1);
5120 assert(Op0.getValueType() == Op1.getValueType());
5121
5122 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5123 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
Rafael Espindola1d9672b2012-04-10 00:16:22 +00005124 if (COp0 && COp0->isNullValue())
Rafael Espindola8f62b322012-04-09 16:06:03 +00005125 Op = Op1;
Rafael Espindola1d9672b2012-04-10 00:16:22 +00005126 else if (COp1 && COp1->isNullValue())
Rafael Espindola8f62b322012-04-09 16:06:03 +00005127 Op = Op0;
5128 else
5129 return false;
5130
5131 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
5132
5133 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5134 return false;
5135
5136 return true;
5137}
5138
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005139SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5140 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005141 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00005142
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005143 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5144 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005145 return SDValue(Res, 0);
5146
Nate Begeman21158fc2005-09-01 00:19:25 +00005147 // fold (zext (zext x)) -> (zext x)
Chris Lattner7e7bcf32006-05-06 23:06:26 +00005148 // fold (zext (aext x)) -> (zext x)
5149 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005150 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005151 N0.getOperand(0));
Chris Lattnera31f0a62006-09-21 06:00:20 +00005152
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005153 // fold (zext (truncate x)) -> (zext x) or
5154 // (zext (truncate x)) -> (truncate x)
5155 // This is valid when the truncated bits of x are already zero.
5156 // FIXME: We should extend this to work for vectors too.
Rafael Espindola8f62b322012-04-09 16:06:03 +00005157 SDValue Op;
5158 APInt KnownZero;
5159 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5160 APInt TruncatedBits =
5161 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5162 APInt(Op.getValueSizeInBits(), 0) :
5163 APInt::getBitsSet(Op.getValueSizeInBits(),
5164 N0.getValueSizeInBits(),
5165 std::min(Op.getValueSizeInBits(),
5166 VT.getSizeInBits()));
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00005167 if (TruncatedBits == (KnownZero & TruncatedBits)) {
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005168 if (VT.bitsGT(Op.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005169 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005170 if (VT.bitsLT(Op.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005171 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005172
5173 return Op;
5174 }
5175 }
5176
Evan Cheng464dc9b2007-03-22 01:54:19 +00005177 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5178 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
Dale Johannesen4bbd2ee2007-03-30 21:38:07 +00005179 if (N0.getOpcode() == ISD::TRUNCATE) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005180 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5181 if (NarrowLoad.getNode()) {
Dale Johannesenff384ad2010-05-25 17:50:03 +00005182 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5183 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005184 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesenff384ad2010-05-25 17:50:03 +00005185 // CombineTo deleted the truncate, if needed, but not what's under it.
5186 AddToWorkList(oye);
5187 }
Eli Friedman55b0acd2011-04-16 23:25:34 +00005188 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00005189 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005190 }
5191
Chris Lattnera31f0a62006-09-21 06:00:20 +00005192 // fold (zext (truncate x)) -> (and x, mask)
5193 if (N0.getOpcode() == ISD::TRUNCATE &&
Dan Gohman600f62b2010-06-24 14:30:44 +00005194 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
Dan Gohman68fb0042010-11-03 01:47:46 +00005195
5196 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5197 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5198 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5199 if (NarrowLoad.getNode()) {
5200 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5201 if (NarrowLoad.getNode() != N0.getNode()) {
5202 CombineTo(N0.getNode(), NarrowLoad);
5203 // CombineTo deleted the truncate, if needed, but not what's under it.
5204 AddToWorkList(oye);
5205 }
5206 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5207 }
5208
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005209 SDValue Op = N0.getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00005210 if (Op.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005211 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
Elena Demikhovsky8d7e56c2012-04-22 09:39:03 +00005212 AddToWorkList(Op.getNode());
Duncan Sands11dd4242008-06-08 20:54:56 +00005213 } else if (Op.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005214 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Elena Demikhovsky8d7e56c2012-04-22 09:39:03 +00005215 AddToWorkList(Op.getNode());
Chris Lattnera31f0a62006-09-21 06:00:20 +00005216 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00005217 return DAG.getZeroExtendInReg(Op, SDLoc(N),
Dan Gohman1d459e42009-12-11 21:31:27 +00005218 N0.getValueType().getScalarType());
Chris Lattnera31f0a62006-09-21 06:00:20 +00005219 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005220
Dan Gohmanad3e5492009-04-08 00:15:30 +00005221 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5222 // if either of the casts is not free.
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00005223 if (N0.getOpcode() == ISD::AND &&
5224 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
Dan Gohmanad3e5492009-04-08 00:15:30 +00005225 N0.getOperand(1).getOpcode() == ISD::Constant &&
5226 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5227 N0.getValueType()) ||
5228 !TLI.isZExtFree(N0.getValueType(), VT))) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005229 SDValue X = N0.getOperand(0).getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00005230 if (X.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005231 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
Duncan Sands11dd4242008-06-08 20:54:56 +00005232 } else if (X.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005233 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00005234 }
Dan Gohmane1c4f992008-03-03 23:51:38 +00005235 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00005236 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005237 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005238 X, DAG.getConstant(Mask, VT));
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00005239 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005240
Evan Chengbce7c472005-12-14 02:19:23 +00005241 // fold (zext (load x)) -> (zext (truncate (zextload x)))
Nadav Rotem25f2ac92011-02-20 12:37:50 +00005242 // None of the supported targets knows how to perform load and vector_zext
Nadav Rotemb0091302011-02-27 07:40:43 +00005243 // on vectors in one instruction. We only perform this transformation on
5244 // scalars.
Nadav Rotem25f2ac92011-02-20 12:37:50 +00005245 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005246 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005247 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005248 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
Evan Chenge106e2f2007-10-29 19:58:20 +00005249 bool DoXform = true;
5250 SmallVector<SDNode*, 4> SetCCs;
5251 if (!N0.hasOneUse())
5252 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5253 if (DoXform) {
5254 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005255 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005256 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005257 LN0->getBasePtr(), N0.getValueType(),
5258 LN0->getMemOperand());
Evan Chenge106e2f2007-10-29 19:58:20 +00005259 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005260 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00005261 N0.getValueType(), ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005262 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Bill Wendlingc4093182009-01-30 22:23:15 +00005263
Andrew Trickef9de2a2013-05-25 02:42:55 +00005264 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005265 ISD::ZERO_EXTEND);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005266 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenge106e2f2007-10-29 19:58:20 +00005267 }
Evan Chengbce7c472005-12-14 02:19:23 +00005268 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005269
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005270 // fold (zext (and/or/xor (load x), cst)) ->
5271 // (and/or/xor (zextload x), (zext cst))
5272 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5273 N0.getOpcode() == ISD::XOR) &&
5274 isa<LoadSDNode>(N0.getOperand(0)) &&
5275 N0.getOperand(1).getOpcode() == ISD::Constant &&
5276 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5277 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5278 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005279 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005280 bool DoXform = true;
5281 SmallVector<SDNode*, 4> SetCCs;
5282 if (!N0.hasOneUse())
5283 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5284 SetCCs, TLI);
5285 if (DoXform) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005286 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005287 LN0->getChain(), LN0->getBasePtr(),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005288 LN0->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005289 LN0->getMemOperand());
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005290 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5291 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005292 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005293 ExtLoad, DAG.getConstant(Mask, VT));
5294 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00005295 SDLoc(N0.getOperand(0)),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005296 N0.getOperand(0).getValueType(), ExtLoad);
5297 CombineTo(N, And);
5298 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005299 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005300 ISD::ZERO_EXTEND);
5301 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5302 }
5303 }
5304 }
5305
Chris Lattner7dac1082005-12-14 19:05:06 +00005306 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5307 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00005308 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5309 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005310 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00005311 EVT MemVT = LN0->getMemoryVT();
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005312 if ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00005313 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005314 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005315 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005316 LN0->getBasePtr(), MemVT,
5317 LN0->getMemOperand());
Duncan Sands8651e9c2008-06-13 19:07:40 +00005318 CombineTo(N, ExtLoad);
Gabor Greife12264b2008-08-30 19:29:20 +00005319 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005320 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
Bill Wendlingc4093182009-01-30 22:23:15 +00005321 ExtLoad),
Duncan Sands8651e9c2008-06-13 19:07:40 +00005322 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005323 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Duncan Sands8651e9c2008-06-13 19:07:40 +00005324 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005325 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005326
Chris Lattner65786b02007-04-11 05:32:27 +00005327 if (N0.getOpcode() == ISD::SETCC) {
Kevin Qinede9ce12013-12-30 02:05:13 +00005328 if (!LegalOperations && VT.isVector() &&
5329 N0.getValueType().getVectorElementType() == MVT::i1) {
Elena Demikhovsky9d56f1e2014-01-22 12:26:19 +00005330 EVT N0VT = N0.getOperand(0).getValueType();
5331 if (getSetCCResultType(N0VT) == N0.getValueType())
5332 return SDValue();
5333
Evan Chengabd0ad52010-05-19 01:08:17 +00005334 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5335 // Only do this before legalize for now.
Evan Chengabd0ad52010-05-19 01:08:17 +00005336 EVT EltVT = VT.getVectorElementType();
5337 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5338 DAG.getConstant(1, EltVT));
Dan Gohman4298df62011-05-17 22:20:36 +00005339 if (VT.getSizeInBits() == N0VT.getSizeInBits())
Evan Chengabd0ad52010-05-19 01:08:17 +00005340 // We know that the # elements of the results is the same as the
5341 // # elements of the compare (and the # elements of the compare result
5342 // for that matter). Check to see that they are the same size. If so,
5343 // we know that the element size of the sext'd result matches the
5344 // element size of the compare operands.
Andrew Trickef9de2a2013-05-25 02:42:55 +00005345 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5346 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Evan Chengabd0ad52010-05-19 01:08:17 +00005347 N0.getOperand(1),
5348 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005349 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
Evan Chengabd0ad52010-05-19 01:08:17 +00005350 &OneOps[0], OneOps.size()));
Dan Gohman4298df62011-05-17 22:20:36 +00005351
5352 // If the desired elements are smaller or larger than the source
5353 // elements we can use a matching integer vector type and then
5354 // truncate/sign extend
5355 EVT MatchingElementType =
5356 EVT::getIntegerVT(*DAG.getContext(),
5357 N0VT.getScalarType().getSizeInBits());
5358 EVT MatchingVectorType =
5359 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5360 N0VT.getVectorNumElements());
5361 SDValue VsetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005362 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
Dan Gohman4298df62011-05-17 22:20:36 +00005363 N0.getOperand(1),
5364 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005365 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5366 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5367 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
Dan Gohman4298df62011-05-17 22:20:36 +00005368 &OneOps[0], OneOps.size()));
Evan Chengabd0ad52010-05-19 01:08:17 +00005369 }
5370
5371 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
Scott Michelcf0da6c2009-02-17 22:15:04 +00005372 SDValue SCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005373 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Chris Lattner65786b02007-04-11 05:32:27 +00005374 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
Chris Lattnera083ffc2007-04-11 06:50:51 +00005375 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005376 if (SCC.getNode()) return SCC;
Chris Lattner65786b02007-04-11 05:32:27 +00005377 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005378
Evan Cheng852c4862009-12-15 03:00:32 +00005379 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
Evan Chengca7c6902009-12-15 00:41:36 +00005380 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
Evan Cheng852c4862009-12-15 03:00:32 +00005381 isa<ConstantSDNode>(N0.getOperand(1)) &&
Evan Chengca7c6902009-12-15 00:41:36 +00005382 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5383 N0.hasOneUse()) {
Chris Lattnere95d1952011-02-13 19:09:16 +00005384 SDValue ShAmt = N0.getOperand(1);
5385 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
Evan Cheng852c4862009-12-15 03:00:32 +00005386 if (N0.getOpcode() == ISD::SHL) {
Chris Lattnere95d1952011-02-13 19:09:16 +00005387 SDValue InnerZExt = N0.getOperand(0);
Evan Cheng852c4862009-12-15 03:00:32 +00005388 // If the original shl may be shifting out bits, do not perform this
5389 // transformation.
Chris Lattnere95d1952011-02-13 19:09:16 +00005390 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5391 InnerZExt.getOperand(0).getValueType().getSizeInBits();
5392 if (ShAmtVal > KnownZeroBits)
Evan Cheng852c4862009-12-15 03:00:32 +00005393 return SDValue();
5394 }
Chris Lattnere95d1952011-02-13 19:09:16 +00005395
Andrew Trickef9de2a2013-05-25 02:42:55 +00005396 SDLoc DL(N);
Owen Andersonb2c80da2011-02-25 21:41:48 +00005397
5398 // Ensure that the shift amount is wide enough for the shifted value.
Chris Lattnere95d1952011-02-13 19:09:16 +00005399 if (VT.getSizeInBits() >= 256)
5400 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
Owen Andersonb2c80da2011-02-25 21:41:48 +00005401
Chris Lattnere95d1952011-02-13 19:09:16 +00005402 return DAG.getNode(N0.getOpcode(), DL, VT,
5403 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5404 ShAmt);
Evan Chengca7c6902009-12-15 00:41:36 +00005405 }
5406
Evan Chengf1005572010-04-28 07:10:39 +00005407 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00005408}
5409
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005410SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5411 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005412 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005413
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005414 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5415 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005416 return SDValue(Res, 0);
5417
Chris Lattner812646a2006-05-05 05:58:59 +00005418 // fold (aext (aext x)) -> (aext x)
5419 // fold (aext (zext x)) -> (zext x)
5420 // fold (aext (sext x)) -> (sext x)
5421 if (N0.getOpcode() == ISD::ANY_EXTEND ||
5422 N0.getOpcode() == ISD::ZERO_EXTEND ||
5423 N0.getOpcode() == ISD::SIGN_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005424 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00005425
Evan Cheng464dc9b2007-03-22 01:54:19 +00005426 // fold (aext (truncate (load x))) -> (aext (smaller load x))
5427 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5428 if (N0.getOpcode() == ISD::TRUNCATE) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005429 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5430 if (NarrowLoad.getNode()) {
Dale Johannesen60fe2cd2010-05-25 18:47:23 +00005431 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5432 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005433 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesen60fe2cd2010-05-25 18:47:23 +00005434 // CombineTo deleted the truncate, if needed, but not what's under it.
5435 AddToWorkList(oye);
5436 }
Eli Friedman55b0acd2011-04-16 23:25:34 +00005437 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00005438 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005439 }
5440
Chris Lattner8746e2c2006-09-20 06:29:17 +00005441 // fold (aext (truncate x))
5442 if (N0.getOpcode() == ISD::TRUNCATE) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005443 SDValue TruncOp = N0.getOperand(0);
Chris Lattner8746e2c2006-09-20 06:29:17 +00005444 if (TruncOp.getValueType() == VT)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005445 return TruncOp; // x iff x size == zext size.
Duncan Sands11dd4242008-06-08 20:54:56 +00005446 if (TruncOp.getValueType().bitsGT(VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005447 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5448 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
Chris Lattner8746e2c2006-09-20 06:29:17 +00005449 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005450
Dan Gohmanad3e5492009-04-08 00:15:30 +00005451 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5452 // if the trunc is not free.
Chris Lattner082db3f2006-09-21 06:40:43 +00005453 if (N0.getOpcode() == ISD::AND &&
5454 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
Dan Gohmanad3e5492009-04-08 00:15:30 +00005455 N0.getOperand(1).getOpcode() == ISD::Constant &&
5456 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5457 N0.getValueType())) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005458 SDValue X = N0.getOperand(0).getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00005459 if (X.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005460 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
Duncan Sands11dd4242008-06-08 20:54:56 +00005461 } else if (X.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005462 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
Chris Lattner082db3f2006-09-21 06:40:43 +00005463 }
Dan Gohmane1c4f992008-03-03 23:51:38 +00005464 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00005465 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005466 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendling9b3dc8d2009-01-30 22:27:33 +00005467 X, DAG.getConstant(Mask, VT));
Chris Lattner082db3f2006-09-21 06:40:43 +00005468 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005469
Chris Lattner812646a2006-05-05 05:58:59 +00005470 // fold (aext (load x)) -> (aext (truncate (extload x)))
Nadav Rotem502f1b92011-02-24 21:01:34 +00005471 // None of the supported targets knows how to perform load and any_ext
Nadav Rotemb0091302011-02-27 07:40:43 +00005472 // on vectors in one instruction. We only perform this transformation on
5473 // scalars.
Nadav Rotem502f1b92011-02-24 21:01:34 +00005474 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005475 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005476 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005477 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
Dan Gohman0e8d1992009-04-09 03:51:29 +00005478 bool DoXform = true;
5479 SmallVector<SDNode*, 4> SetCCs;
5480 if (!N0.hasOneUse())
5481 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5482 if (DoXform) {
5483 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005484 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
Dan Gohman0e8d1992009-04-09 03:51:29 +00005485 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005486 LN0->getBasePtr(), N0.getValueType(),
5487 LN0->getMemOperand());
Dan Gohman0e8d1992009-04-09 03:51:29 +00005488 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005489 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Dan Gohman0e8d1992009-04-09 03:51:29 +00005490 N0.getValueType(), ExtLoad);
5491 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005492 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005493 ISD::ANY_EXTEND);
Dan Gohman0e8d1992009-04-09 03:51:29 +00005494 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5495 }
Chris Lattner812646a2006-05-05 05:58:59 +00005496 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005497
Chris Lattner812646a2006-05-05 05:58:59 +00005498 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5499 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5500 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
Evan Cheng8a1d09d2007-03-07 08:07:03 +00005501 if (N0.getOpcode() == ISD::LOAD &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00005502 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Chenge71fe34d2006-10-09 20:57:25 +00005503 N0.hasOneUse()) {
5504 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Matt Arsenaultaaf96232014-04-08 21:40:37 +00005505 ISD::LoadExtType ExtType = LN0->getExtensionType();
Dan Gohman08c0a952009-09-23 21:02:20 +00005506 EVT MemVT = LN0->getMemoryVT();
Matt Arsenaultaaf96232014-04-08 21:40:37 +00005507 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5508 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5509 VT, LN0->getChain(), LN0->getBasePtr(),
5510 MemVT, LN0->getMemOperand());
5511 CombineTo(N, ExtLoad);
5512 CombineTo(N0.getNode(),
5513 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5514 N0.getValueType(), ExtLoad),
5515 ExtLoad.getValue(1));
5516 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5517 }
Chris Lattner812646a2006-05-05 05:58:59 +00005518 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005519
Chris Lattner65786b02007-04-11 05:32:27 +00005520 if (N0.getOpcode() == ISD::SETCC) {
Evan Chengabd0ad52010-05-19 01:08:17 +00005521 // aext(setcc) -> sext_in_reg(vsetcc) for vectors.
5522 // Only do this before legalize for now.
5523 if (VT.isVector() && !LegalOperations) {
5524 EVT N0VT = N0.getOperand(0).getValueType();
5525 // We know that the # elements of the results is the same as the
5526 // # elements of the compare (and the # elements of the compare result
5527 // for that matter). Check to see that they are the same size. If so,
5528 // we know that the element size of the sext'd result matches the
5529 // element size of the compare operands.
5530 if (VT.getSizeInBits() == N0VT.getSizeInBits())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005531 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005532 N0.getOperand(1),
5533 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Evan Chengabd0ad52010-05-19 01:08:17 +00005534 // If the desired elements are smaller or larger than the source
5535 // elements we can use a matching integer vector type and then
5536 // truncate/sign extend
5537 else {
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005538 EVT MatchingElementType =
5539 EVT::getIntegerVT(*DAG.getContext(),
5540 N0VT.getScalarType().getSizeInBits());
5541 EVT MatchingVectorType =
5542 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5543 N0VT.getVectorNumElements());
5544 SDValue VsetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005545 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005546 N0.getOperand(1),
5547 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005548 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
Evan Chengabd0ad52010-05-19 01:08:17 +00005549 }
5550 }
5551
5552 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
Scott Michelcf0da6c2009-02-17 22:15:04 +00005553 SDValue SCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005554 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Chris Lattnera083ffc2007-04-11 06:50:51 +00005555 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
Chris Lattner18e4ac42007-04-11 16:51:53 +00005556 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005557 if (SCC.getNode())
Chris Lattnerc5f85d32007-04-11 06:43:25 +00005558 return SCC;
Chris Lattner65786b02007-04-11 05:32:27 +00005559 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005560
Evan Chengf1005572010-04-28 07:10:39 +00005561 return SDValue();
Chris Lattner812646a2006-05-05 05:58:59 +00005562}
5563
Chris Lattner5e6fe052007-10-13 06:35:54 +00005564/// GetDemandedBits - See if the specified operand can be simplified with the
5565/// knowledge that only the bits specified by Mask are used. If so, return the
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005566/// simpler operand, otherwise return a null SDValue.
5567SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
Chris Lattner5e6fe052007-10-13 06:35:54 +00005568 switch (V.getOpcode()) {
5569 default: break;
Lang Hamesb85fcd02011-11-08 18:56:23 +00005570 case ISD::Constant: {
5571 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
Craig Topperc0196b12014-04-14 00:51:57 +00005572 assert(CV && "Const value should be ConstSDNode.");
Lang Hamesb85fcd02011-11-08 18:56:23 +00005573 const APInt &CVal = CV->getAPIntValue();
5574 APInt NewVal = CVal & Mask;
Stephen Lin8e8424e2013-07-09 00:44:49 +00005575 if (NewVal != CVal)
Lang Hamesb85fcd02011-11-08 18:56:23 +00005576 return DAG.getConstant(NewVal, V.getValueType());
Lang Hamesb85fcd02011-11-08 18:56:23 +00005577 break;
5578 }
Chris Lattner5e6fe052007-10-13 06:35:54 +00005579 case ISD::OR:
5580 case ISD::XOR:
5581 // If the LHS or RHS don't contribute bits to the or, drop them.
5582 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5583 return V.getOperand(1);
5584 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5585 return V.getOperand(0);
5586 break;
Chris Lattnerf47e3062007-10-13 06:58:48 +00005587 case ISD::SRL:
5588 // Only look at single-use SRLs.
Gabor Greiff304a7a2008-08-28 21:40:38 +00005589 if (!V.getNode()->hasOneUse())
Chris Lattnerf47e3062007-10-13 06:58:48 +00005590 break;
5591 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5592 // See if we can recursively simplify the LHS.
Dan Gohmaneffb8942008-09-12 16:56:44 +00005593 unsigned Amt = RHSC->getZExtValue();
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005594
Dan Gohmanb9fa1d22009-01-03 19:22:06 +00005595 // Watch out for shift count overflow though.
5596 if (Amt >= Mask.getBitWidth()) break;
Dan Gohman1f372ed2008-02-25 21:11:39 +00005597 APInt NewMask = Mask << Amt;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005598 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005599 if (SimplifyLHS.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005600 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
Chris Lattnerf47e3062007-10-13 06:58:48 +00005601 SimplifyLHS, V.getOperand(1));
Chris Lattnerf47e3062007-10-13 06:58:48 +00005602 }
Chris Lattner5e6fe052007-10-13 06:35:54 +00005603 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005604 return SDValue();
Chris Lattner5e6fe052007-10-13 06:35:54 +00005605}
5606
Evan Cheng464dc9b2007-03-22 01:54:19 +00005607/// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5608/// bits and then truncated to a narrower type and where N is a multiple
5609/// of number of bits of the narrower type, transform it to a narrower load
5610/// from address + N / num of bits of new type. If the result is to be
5611/// extended, also fold the extension to form a extending load.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005612SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
Evan Cheng464dc9b2007-03-22 01:54:19 +00005613 unsigned Opc = N->getOpcode();
Dan Gohman600f62b2010-06-24 14:30:44 +00005614
Evan Cheng464dc9b2007-03-22 01:54:19 +00005615 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005616 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005617 EVT VT = N->getValueType(0);
5618 EVT ExtVT = VT;
Evan Cheng464dc9b2007-03-22 01:54:19 +00005619
Dan Gohman550c9af2008-08-14 20:04:46 +00005620 // This transformation isn't valid for vector loads.
5621 if (VT.isVector())
5622 return SDValue();
5623
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005624 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
Evan Chenga883b582007-03-23 22:13:36 +00005625 // extended to VT.
Evan Cheng464dc9b2007-03-22 01:54:19 +00005626 if (Opc == ISD::SIGN_EXTEND_INREG) {
5627 ExtType = ISD::SEXTLOAD;
Owen Anderson53aa7a92009-08-10 22:56:29 +00005628 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
Dan Gohman600f62b2010-06-24 14:30:44 +00005629 } else if (Opc == ISD::SRL) {
Chris Lattner2a7ff992010-12-21 18:05:22 +00005630 // Another special-case: SRL is basically zero-extending a narrower value.
Dan Gohman600f62b2010-06-24 14:30:44 +00005631 ExtType = ISD::ZEXTLOAD;
5632 N0 = SDValue(N, 0);
5633 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5634 if (!N01) return SDValue();
5635 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5636 VT.getSizeInBits() - N01->getZExtValue());
Evan Cheng464dc9b2007-03-22 01:54:19 +00005637 }
Richard Osborne272e0842011-01-31 17:41:44 +00005638 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5639 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005640
Owen Anderson53aa7a92009-08-10 22:56:29 +00005641 unsigned EVTBits = ExtVT.getSizeInBits();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005642
Chris Lattner9a499e92010-12-22 08:01:44 +00005643 // Do not generate loads of non-round integer types since these can
5644 // be expensive (and would be wrong if the type is not byte sized).
5645 if (!ExtVT.isRound())
5646 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005647
Evan Cheng464dc9b2007-03-22 01:54:19 +00005648 unsigned ShAmt = 0;
Chris Lattner9a499e92010-12-22 08:01:44 +00005649 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
Evan Cheng464dc9b2007-03-22 01:54:19 +00005650 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00005651 ShAmt = N01->getZExtValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005652 // Is the shift amount a multiple of size of VT?
5653 if ((ShAmt & (EVTBits-1)) == 0) {
5654 N0 = N0.getOperand(0);
Eli Friedman1e008c12009-08-19 08:46:10 +00005655 // Is the load width a multiple of size of VT?
5656 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005657 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005658 }
Wesley Peck527da1b2010-11-23 03:31:01 +00005659
Chris Lattnercafc1e62010-12-22 08:02:57 +00005660 // At this point, we must have a load or else we can't do the transform.
5661 if (!isa<LoadSDNode>(N0)) return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005662
Chandler Carruthb27041c2012-12-11 00:36:57 +00005663 // Because a SRL must be assumed to *need* to zero-extend the high bits
5664 // (as opposed to anyext the high bits), we can't combine the zextload
5665 // lowering of SRL and an sextload.
5666 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5667 return SDValue();
5668
Chris Lattnera2050552010-10-01 05:36:09 +00005669 // If the shift amount is larger than the input type then we're not
5670 // accessing any of the loaded bytes. If the load was a zextload/extload
5671 // then the result of the shift+trunc is zero/undef (handled elsewhere).
Chris Lattnercafc1e62010-12-22 08:02:57 +00005672 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
Chris Lattnera2050552010-10-01 05:36:09 +00005673 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005674 }
5675 }
5676
Dan Gohman68fb0042010-11-03 01:47:46 +00005677 // If the load is shifted left (and the result isn't shifted back right),
5678 // we can fold the truncate through the shift.
5679 unsigned ShLeftAmt = 0;
5680 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
Chris Lattner222374d2010-12-22 07:36:50 +00005681 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
Dan Gohman68fb0042010-11-03 01:47:46 +00005682 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5683 ShLeftAmt = N01->getZExtValue();
5684 N0 = N0.getOperand(0);
5685 }
5686 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00005687
Chris Lattner222374d2010-12-22 07:36:50 +00005688 // If we haven't found a load, we can't narrow it. Don't transform one with
5689 // multiple uses, this would require adding a new load.
Bill Schmidtd006c692013-01-14 22:04:38 +00005690 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5691 return SDValue();
5692
5693 // Don't change the width of a volatile load.
5694 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5695 if (LN0->isVolatile())
Chris Lattner222374d2010-12-22 07:36:50 +00005696 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005697
Chris Lattner9a499e92010-12-22 08:01:44 +00005698 // Verify that we are actually reducing a load width here.
Bill Schmidtd006c692013-01-14 22:04:38 +00005699 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
Chris Lattner222374d2010-12-22 07:36:50 +00005700 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005701
Bill Schmidtd006c692013-01-14 22:04:38 +00005702 // For the transform to be legal, the load must produce only two values
5703 // (the value loaded and the chain). Don't transform a pre-increment
Stephen Lincfe7f352013-07-08 00:37:03 +00005704 // load, for example, which produces an extra value. Otherwise the
Bill Schmidtd006c692013-01-14 22:04:38 +00005705 // transformation is not equivalent, and the downstream logic to replace
5706 // uses gets things wrong.
5707 if (LN0->getNumValues() > 2)
5708 return SDValue();
5709
Benjamin Kramerc7332b22013-07-06 14:05:09 +00005710 // If the load that we're shrinking is an extload and we're not just
5711 // discarding the extension we can't simply shrink the load. Bail.
5712 // TODO: It would be possible to merge the extensions in some cases.
5713 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5714 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5715 return SDValue();
5716
Chris Lattner222374d2010-12-22 07:36:50 +00005717 EVT PtrType = N0.getOperand(1).getValueType();
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005718
Evan Cheng4c6f9172012-06-26 01:19:33 +00005719 if (PtrType == MVT::Untyped || PtrType.isExtended())
5720 // It's not possible to generate a constant of extended or untyped type.
5721 return SDValue();
5722
Chris Lattner222374d2010-12-22 07:36:50 +00005723 // For big endian targets, we need to adjust the offset to the pointer to
5724 // load the correct bytes.
5725 if (TLI.isBigEndian()) {
5726 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5727 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5728 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
Evan Cheng464dc9b2007-03-22 01:54:19 +00005729 }
5730
Chris Lattner222374d2010-12-22 07:36:50 +00005731 uint64_t PtrOff = ShAmt / 8;
5732 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005733 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
Chris Lattner222374d2010-12-22 07:36:50 +00005734 PtrType, LN0->getBasePtr(),
5735 DAG.getConstant(PtrOff, PtrType));
5736 AddToWorkList(NewPtr.getNode());
5737
Chris Lattner9a499e92010-12-22 08:01:44 +00005738 SDValue Load;
5739 if (ExtType == ISD::NON_EXTLOAD)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005740 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
Chris Lattner9a499e92010-12-22 08:01:44 +00005741 LN0->getPointerInfo().getWithOffset(PtrOff),
Pete Cooper82cd9e82011-11-08 18:42:53 +00005742 LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005743 LN0->isInvariant(), NewAlign, LN0->getTBAAInfo());
Chris Lattner9a499e92010-12-22 08:01:44 +00005744 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00005745 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
Chris Lattner9a499e92010-12-22 08:01:44 +00005746 LN0->getPointerInfo().getWithOffset(PtrOff),
5747 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005748 NewAlign, LN0->getTBAAInfo());
Chris Lattner222374d2010-12-22 07:36:50 +00005749
5750 // Replace the old load's chain with the new load's chain.
5751 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00005752 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
Chris Lattner222374d2010-12-22 07:36:50 +00005753
5754 // Shift the result left, if we've swallowed a left shift.
5755 SDValue Result = Load;
5756 if (ShLeftAmt != 0) {
Owen Andersonb2c80da2011-02-25 21:41:48 +00005757 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
Chris Lattner222374d2010-12-22 07:36:50 +00005758 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5759 ShImmTy = VT;
Paul Redmond288604e2013-02-12 15:21:21 +00005760 // If the shift amount is as large as the result size (but, presumably,
5761 // no larger than the source) then the useful bits of the result are
5762 // zero; we can't simply return the shortened shift, because the result
5763 // of that operation is undefined.
5764 if (ShLeftAmt >= VT.getSizeInBits())
5765 Result = DAG.getConstant(0, VT);
5766 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00005767 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
Paul Redmond288604e2013-02-12 15:21:21 +00005768 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
Chris Lattner222374d2010-12-22 07:36:50 +00005769 }
5770
5771 // Return the new loaded value.
5772 return Result;
Evan Cheng464dc9b2007-03-22 01:54:19 +00005773}
5774
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005775SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5776 SDValue N0 = N->getOperand(0);
5777 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005778 EVT VT = N->getValueType(0);
5779 EVT EVT = cast<VTSDNode>(N1)->getVT();
Dan Gohman1d459e42009-12-11 21:31:27 +00005780 unsigned VTBits = VT.getScalarType().getSizeInBits();
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005781 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00005782
Nate Begeman21158fc2005-09-01 00:19:25 +00005783 // fold (sext_in_reg c1) -> c1
Chris Lattner29062da2006-05-08 20:59:41 +00005784 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005785 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005786
Chris Lattner2a4d7b82006-05-06 22:43:44 +00005787 // If the input is already sign extended, just drop the extension.
Dan Gohman1d459e42009-12-11 21:31:27 +00005788 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
Chris Lattner1ecb2a22006-05-06 09:30:03 +00005789 return N0;
Scott Michelcf0da6c2009-02-17 22:15:04 +00005790
Nate Begeman7cea6ef2005-09-02 21:18:40 +00005791 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5792 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00005793 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005794 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005795 N0.getOperand(0), N1);
Chris Lattner446e1ef2006-05-08 21:18:59 +00005796
Dan Gohman345d63c2008-07-31 00:50:31 +00005797 // fold (sext_in_reg (sext x)) -> (sext x)
5798 // fold (sext_in_reg (aext x)) -> (sext x)
5799 // if x is small enough.
5800 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5801 SDValue N00 = N0.getOperand(0);
Evan Chengf037f872010-04-16 22:26:19 +00005802 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5803 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005804 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
Dan Gohman345d63c2008-07-31 00:50:31 +00005805 }
5806
Chris Lattner9ad59152007-04-17 19:03:21 +00005807 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
Dan Gohman1f372ed2008-02-25 21:11:39 +00005808 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005809 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005810
Chris Lattner9ad59152007-04-17 19:03:21 +00005811 // fold operands of sext_in_reg based on knowledge that the top bits are not
5812 // demanded.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005813 if (SimplifyDemandedBits(SDValue(N, 0)))
5814 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005815
Evan Cheng464dc9b2007-03-22 01:54:19 +00005816 // fold (sext_in_reg (load x)) -> (smaller sextload x)
5817 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005818 SDValue NarrowLoad = ReduceLoadWidth(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005819 if (NarrowLoad.getNode())
Evan Cheng464dc9b2007-03-22 01:54:19 +00005820 return NarrowLoad;
5821
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005822 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005823 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
Chris Lattner446e1ef2006-05-08 21:18:59 +00005824 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5825 if (N0.getOpcode() == ISD::SRL) {
5826 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
Dan Gohman1d459e42009-12-11 21:31:27 +00005827 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005828 // We can turn this into an SRA iff the input to the SRL is already sign
Chris Lattner446e1ef2006-05-08 21:18:59 +00005829 // extended enough.
Dan Gohman309d3d52007-06-22 14:59:07 +00005830 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
Dan Gohman1d459e42009-12-11 21:31:27 +00005831 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005832 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005833 N0.getOperand(0), N0.getOperand(1));
Chris Lattner446e1ef2006-05-08 21:18:59 +00005834 }
5835 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005836
Nate Begeman02b23c62005-10-13 03:11:28 +00005837 // fold (sext_inreg (extload x)) -> (sextload x)
Scott Michelcf0da6c2009-02-17 22:15:04 +00005838 if (ISD::isEXTLoad(N0.getNode()) &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00005839 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Dan Gohman47a7d6f2008-01-30 00:15:11 +00005840 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005841 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005842 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005843 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005844 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005845 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005846 LN0->getBasePtr(), EVT,
5847 LN0->getMemOperand());
Chris Lattnerd39c60f2005-12-14 19:25:30 +00005848 CombineTo(N, ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005849 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Elena Demikhovsky14a4af02012-12-19 07:50:20 +00005850 AddToWorkList(ExtLoad.getNode());
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005851 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00005852 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005853 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
Gabor Greiff304a7a2008-08-28 21:40:38 +00005854 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Cheng8a1d09d2007-03-07 08:07:03 +00005855 N0.hasOneUse() &&
Dan Gohman47a7d6f2008-01-30 00:15:11 +00005856 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005857 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005858 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005859 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005860 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005861 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005862 LN0->getBasePtr(), EVT,
5863 LN0->getMemOperand());
Chris Lattnerd39c60f2005-12-14 19:25:30 +00005864 CombineTo(N, ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005865 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005866 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00005867 }
Evan Cheng4c0bd962011-06-21 06:01:08 +00005868
5869 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5870 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5871 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5872 N0.getOperand(1), false);
Craig Topperc0196b12014-04-14 00:51:57 +00005873 if (BSwap.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005874 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Evan Cheng4c0bd962011-06-21 06:01:08 +00005875 BSwap, N1);
5876 }
5877
Andrea Di Biagio46dcddb2013-12-27 20:20:28 +00005878 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
5879 // into a build_vector.
5880 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5881 SmallVector<SDValue, 8> Elts;
5882 unsigned NumElts = N0->getNumOperands();
5883 unsigned ShAmt = VTBits - EVTBits;
5884
5885 for (unsigned i = 0; i != NumElts; ++i) {
5886 SDValue Op = N0->getOperand(i);
5887 if (Op->getOpcode() == ISD::UNDEF) {
5888 Elts.push_back(Op);
5889 continue;
5890 }
5891
5892 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
Kevin Qin5cd73c92014-01-06 02:26:10 +00005893 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5894 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
Andrea Di Biagio46dcddb2013-12-27 20:20:28 +00005895 Op.getValueType()));
5896 }
5897
5898 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Elts[0], NumElts);
5899 }
5900
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005901 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00005902}
5903
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005904SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5905 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005906 EVT VT = N->getValueType(0);
Nadav Rotem5399f4d2012-02-03 13:18:25 +00005907 bool isLE = TLI.isLittleEndian();
Nate Begeman21158fc2005-09-01 00:19:25 +00005908
5909 // noop truncate
5910 if (N0.getValueType() == N->getValueType(0))
Nate Begemand23739d2005-09-06 04:43:02 +00005911 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00005912 // fold (truncate c1) -> c1
Chris Lattner7e7bcf32006-05-06 23:06:26 +00005913 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005914 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00005915 // fold (truncate (truncate x)) -> (truncate x)
5916 if (N0.getOpcode() == ISD::TRUNCATE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005917 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
Nate Begeman21158fc2005-09-01 00:19:25 +00005918 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
Chris Lattner6855d622010-04-07 18:13:33 +00005919 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5920 N0.getOpcode() == ISD::SIGN_EXTEND ||
Chris Lattner907e3922006-05-05 22:56:26 +00005921 N0.getOpcode() == ISD::ANY_EXTEND) {
Duncan Sands11dd4242008-06-08 20:54:56 +00005922 if (N0.getOperand(0).getValueType().bitsLT(VT))
Nate Begeman21158fc2005-09-01 00:19:25 +00005923 // if the source is smaller than the dest, we still need an extend
Andrew Trickef9de2a2013-05-25 02:42:55 +00005924 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00005925 N0.getOperand(0));
Craig Topper5f9791f2012-09-29 07:18:53 +00005926 if (N0.getOperand(0).getValueType().bitsGT(VT))
Nate Begeman21158fc2005-09-01 00:19:25 +00005927 // if the source is larger than the dest, than we just need the truncate
Andrew Trickef9de2a2013-05-25 02:42:55 +00005928 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
Craig Topper5f9791f2012-09-29 07:18:53 +00005929 // if the source and dest are the same type, we can drop both the extend
5930 // and the truncate.
5931 return N0.getOperand(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00005932 }
Evan Chengd63baea2007-03-21 20:14:05 +00005933
Nadav Rotem4f4546b2012-02-05 11:39:23 +00005934 // Fold extract-and-trunc into a narrow extract. For example:
5935 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5936 // i32 y = TRUNCATE(i64 x)
5937 // -- becomes --
5938 // v16i8 b = BITCAST (v2i64 val)
5939 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5940 //
5941 // Note: We only run this optimization after type legalization (which often
Nadav Rotem5399f4d2012-02-03 13:18:25 +00005942 // creates this pattern) and before operation legalization after which
5943 // we need to be more careful about the vector instructions that we generate.
5944 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
Hal Finkelab51ecd2014-02-28 00:26:45 +00005945 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
Nadav Rotem5399f4d2012-02-03 13:18:25 +00005946
5947 EVT VecTy = N0.getOperand(0).getValueType();
5948 EVT ExTy = N0.getValueType();
5949 EVT TrTy = N->getValueType(0);
5950
5951 unsigned NumElem = VecTy.getVectorNumElements();
5952 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5953
5954 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5955 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5956
5957 SDValue EltNo = N0->getOperand(1);
5958 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
5959 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Tom Stellardd42c5942013-08-05 22:22:01 +00005960 EVT IndexTy = TLI.getVectorIdxTy();
Nadav Rotem5399f4d2012-02-03 13:18:25 +00005961 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
5962
Andrew Trickef9de2a2013-05-25 02:42:55 +00005963 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
Nadav Rotem5399f4d2012-02-03 13:18:25 +00005964 NVT, N0.getOperand(0));
5965
5966 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
Andrew Trickef9de2a2013-05-25 02:42:55 +00005967 SDLoc(N), TrTy, V,
Jim Grosbach92f6adc2012-05-08 20:56:07 +00005968 DAG.getConstant(Index, IndexTy));
Nadav Rotem5399f4d2012-02-03 13:18:25 +00005969 }
5970 }
5971
Arnold Schwaighofer3f9568e2013-02-20 21:33:32 +00005972 // Fold a series of buildvector, bitcast, and truncate if possible.
5973 // For example fold
5974 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
5975 // (2xi32 (buildvector x, y)).
5976 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
5977 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
5978 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
5979 N0.getOperand(0).hasOneUse()) {
5980
5981 SDValue BuildVect = N0.getOperand(0);
5982 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
5983 EVT TruncVecEltTy = VT.getVectorElementType();
5984
5985 // Check that the element types match.
5986 if (BuildVectEltTy == TruncVecEltTy) {
5987 // Now we only need to compute the offset of the truncated elements.
5988 unsigned BuildVecNumElts = BuildVect.getNumOperands();
5989 unsigned TruncVecNumElts = VT.getVectorNumElements();
5990 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
5991
5992 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
5993 "Invalid number of elements");
5994
5995 SmallVector<SDValue, 8> Opnds;
5996 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
5997 Opnds.push_back(BuildVect.getOperand(i));
5998
Andrew Trickef9de2a2013-05-25 02:42:55 +00005999 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
Arnold Schwaighofer3f9568e2013-02-20 21:33:32 +00006000 Opnds.size());
6001 }
6002 }
6003
Chris Lattner5e6fe052007-10-13 06:35:54 +00006004 // See if we can simplify the input to this truncate through knowledge that
Nadav Rotem502f1b92011-02-24 21:01:34 +00006005 // only the low bits are being used.
6006 // For example "trunc (or (shl x, 8), y)" // -> trunc y
Nadav Rotemb0091302011-02-27 07:40:43 +00006007 // Currently we only perform this optimization on scalars because vectors
Nadav Rotem502f1b92011-02-24 21:01:34 +00006008 // may have different active low bits.
6009 if (!VT.isVector()) {
6010 SDValue Shorter =
6011 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6012 VT.getSizeInBits()));
6013 if (Shorter.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006014 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
Nadav Rotem502f1b92011-02-24 21:01:34 +00006015 }
Nate Begeman8caf81d2005-10-12 20:40:40 +00006016 // fold (truncate (load x)) -> (smaller load x)
Evan Chengd63baea2007-03-21 20:14:05 +00006017 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
Dan Gohman600f62b2010-06-24 14:30:44 +00006018 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6019 SDValue Reduced = ReduceLoadWidth(N);
6020 if (Reduced.getNode())
6021 return Reduced;
Richard Sandifordd1093632013-12-11 11:37:27 +00006022 // Handle the case where the load remains an extending load even
6023 // after truncation.
6024 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6025 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6026 if (!LN0->isVolatile() &&
6027 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6028 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6029 VT, LN0->getChain(), LN0->getBasePtr(),
6030 LN0->getMemoryVT(),
6031 LN0->getMemOperand());
6032 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6033 return NewLoad;
6034 }
6035 }
Dan Gohman600f62b2010-06-24 14:30:44 +00006036 }
Michael Liao3ac82012012-10-17 23:45:54 +00006037 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6038 // where ... are all 'undef'.
6039 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6040 SmallVector<EVT, 8> VTs;
6041 SDValue V;
6042 unsigned Idx = 0;
6043 unsigned NumDefs = 0;
6044
6045 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6046 SDValue X = N0.getOperand(i);
6047 if (X.getOpcode() != ISD::UNDEF) {
6048 V = X;
6049 Idx = i;
6050 NumDefs++;
6051 }
6052 // Stop if more than one members are non-undef.
6053 if (NumDefs > 1)
6054 break;
6055 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6056 VT.getVectorElementType(),
6057 X.getValueType().getVectorNumElements()));
6058 }
6059
6060 if (NumDefs == 0)
6061 return DAG.getUNDEF(VT);
6062
6063 if (NumDefs == 1) {
6064 assert(V.getNode() && "The single defined operand is empty!");
6065 SmallVector<SDValue, 8> Opnds;
6066 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6067 if (i != Idx) {
6068 Opnds.push_back(DAG.getUNDEF(VTs[i]));
6069 continue;
6070 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00006071 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
Michael Liao3ac82012012-10-17 23:45:54 +00006072 AddToWorkList(NV.getNode());
6073 Opnds.push_back(NV);
6074 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00006075 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
Michael Liao3ac82012012-10-17 23:45:54 +00006076 &Opnds[0], Opnds.size());
6077 }
6078 }
Dan Gohman600f62b2010-06-24 14:30:44 +00006079
6080 // Simplify the operands using demanded-bits information.
6081 if (!VT.isVector() &&
6082 SimplifyDemandedBits(SDValue(N, 0)))
6083 return SDValue(N, 0);
6084
Evan Chengf1bd5fc2010-04-17 06:13:15 +00006085 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00006086}
6087
Evan Chengb980f6f2008-05-12 23:04:07 +00006088static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006089 SDValue Elt = N->getOperand(i);
Evan Chengb980f6f2008-05-12 23:04:07 +00006090 if (Elt.getOpcode() != ISD::MERGE_VALUES)
Gabor Greiff304a7a2008-08-28 21:40:38 +00006091 return Elt.getNode();
6092 return Elt.getOperand(Elt.getResNo()).getNode();
Evan Chengb980f6f2008-05-12 23:04:07 +00006093}
6094
6095/// CombineConsecutiveLoads - build_pair (load, load) -> load
Scott Michelcf0da6c2009-02-17 22:15:04 +00006096/// if load locations are consecutive.
Owen Anderson53aa7a92009-08-10 22:56:29 +00006097SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
Evan Chengb980f6f2008-05-12 23:04:07 +00006098 assert(N->getOpcode() == ISD::BUILD_PAIR);
6099
Nate Begeman624690c2009-06-05 21:37:30 +00006100 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6101 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
Chris Lattnerf72c3c02010-09-21 16:08:50 +00006102 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
Matt Arsenault58a76392014-02-24 21:01:15 +00006103 LD1->getAddressSpace() != LD2->getAddressSpace())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006104 return SDValue();
Owen Anderson53aa7a92009-08-10 22:56:29 +00006105 EVT LD1VT = LD1->getValueType(0);
Bill Wendling4e0a6152009-01-30 22:44:24 +00006106
Evan Chengb980f6f2008-05-12 23:04:07 +00006107 if (ISD::isNON_EXTLoad(LD2) &&
6108 LD2->hasOneUse() &&
Duncan Sands8651e9c2008-06-13 19:07:40 +00006109 // If both are volatile this would reduce the number of volatile loads.
6110 // If one is volatile it might be ok, but play conservative and bail out.
Nate Begeman624690c2009-06-05 21:37:30 +00006111 !LD1->isVolatile() &&
6112 !LD2->isVolatile() &&
Evan Chengf5938d52009-12-09 01:36:00 +00006113 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
Nate Begeman624690c2009-06-05 21:37:30 +00006114 unsigned Align = LD1->getAlignment();
Micah Villmowcdfe20b2012-10-08 16:38:25 +00006115 unsigned NewAlign = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +00006116 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
Bill Wendling4e0a6152009-01-30 22:44:24 +00006117
Duncan Sands8651e9c2008-06-13 19:07:40 +00006118 if (NewAlign <= Align &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006119 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006120 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
Chris Lattnerf72c3c02010-09-21 16:08:50 +00006121 LD1->getBasePtr(), LD1->getPointerInfo(),
Pete Cooper82cd9e82011-11-08 18:42:53 +00006122 false, false, false, Align);
Evan Chengb980f6f2008-05-12 23:04:07 +00006123 }
Bill Wendling4e0a6152009-01-30 22:44:24 +00006124
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006125 return SDValue();
Evan Chengb980f6f2008-05-12 23:04:07 +00006126}
6127
Wesley Peck527da1b2010-11-23 03:31:01 +00006128SDValue DAGCombiner::visitBITCAST(SDNode *N) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006129 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006130 EVT VT = N->getValueType(0);
Chris Lattnera1874602005-12-23 05:30:37 +00006131
Dan Gohmana8665142007-06-25 16:23:39 +00006132 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6133 // Only do this before legalize, since afterward the target may be depending
6134 // on the bitconvert.
6135 // First check to see if this is all constant.
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006136 if (!LegalTypes &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00006137 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
Duncan Sands13237ac2008-06-06 12:08:01 +00006138 VT.isVector()) {
Juergen Ributzka73844052014-01-13 20:51:35 +00006139 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006140
Owen Anderson53aa7a92009-08-10 22:56:29 +00006141 EVT DestEltVT = N->getValueType(0).getVectorElementType();
Duncan Sands13237ac2008-06-06 12:08:01 +00006142 assert(!DestEltVT.isVector() &&
Dan Gohmana8665142007-06-25 16:23:39 +00006143 "Element type of vector ValueType must not be vector!");
Bill Wendling4e0a6152009-01-30 22:44:24 +00006144 if (isSimple)
Wesley Peck527da1b2010-11-23 03:31:01 +00006145 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
Dan Gohmana8665142007-06-25 16:23:39 +00006146 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006147
Dan Gohman921ddd62008-09-05 01:58:21 +00006148 // If the input is a constant, let getNode fold it.
Chris Lattnera1874602005-12-23 05:30:37 +00006149 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006150 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
Dan Gohman733a64d2009-08-10 23:15:10 +00006151 if (Res.getNode() != N) {
6152 if (!LegalOperations ||
6153 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6154 return Res;
6155
6156 // Folding it resulted in an illegal node, and it's too late to
6157 // do that. Clean up the old node and forego the transformation.
6158 // Ideally this won't happen very often, because instcombine
6159 // and the earlier dagcombine runs (where illegal nodes are
6160 // permitted) should have folded most of them already.
6161 DAG.DeleteNode(Res.getNode());
6162 }
Chris Lattnera1874602005-12-23 05:30:37 +00006163 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006164
Bill Wendling4e0a6152009-01-30 22:44:24 +00006165 // (conv (conv x, t1), t2) -> (conv x, t2)
Wesley Peck527da1b2010-11-23 03:31:01 +00006166 if (N0.getOpcode() == ISD::BITCAST)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006167 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006168 N0.getOperand(0));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006169
Chris Lattner54560f62005-12-23 05:44:41 +00006170 // fold (conv (load x)) -> (load (conv*)x)
Evan Cheng0de312d2007-10-06 08:19:55 +00006171 // If the resultant load doesn't need a higher alignment than the original!
Gabor Greiff304a7a2008-08-28 21:40:38 +00006172 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Duncan Sands8651e9c2008-06-13 19:07:40 +00006173 // Do not change the width of a volatile load.
6174 !cast<LoadSDNode>(N0)->isVolatile() &&
Matt Arsenaultc5559bb2013-11-15 04:42:23 +00006175 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6176 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00006177 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Micah Villmowcdfe20b2012-10-08 16:38:25 +00006178 unsigned Align = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +00006179 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
Evan Chenga4cf58a2007-05-07 21:27:48 +00006180 unsigned OrigAlign = LN0->getAlignment();
Bill Wendling4e0a6152009-01-30 22:44:24 +00006181
Evan Chenga4cf58a2007-05-07 21:27:48 +00006182 if (Align <= OrigAlign) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006183 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
Chris Lattnerf72c3c02010-09-21 16:08:50 +00006184 LN0->getBasePtr(), LN0->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +00006185 LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00006186 LN0->isInvariant(), OrigAlign,
6187 LN0->getTBAAInfo());
Evan Chenga4cf58a2007-05-07 21:27:48 +00006188 AddToWorkList(N);
Gabor Greife12264b2008-08-30 19:29:20 +00006189 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00006190 DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006191 N0.getValueType(), Load),
Evan Chenga4cf58a2007-05-07 21:27:48 +00006192 Load.getValue(1));
6193 return Load;
6194 }
Chris Lattner54560f62005-12-23 05:44:41 +00006195 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00006196
Bill Wendling4e0a6152009-01-30 22:44:24 +00006197 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6198 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
Chris Lattner888560d2008-01-27 17:42:27 +00006199 // This often reduces constant pool loads.
Tom Stellardc54731a2013-07-23 23:55:03 +00006200 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6201 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
Nadav Rotem24a822a2012-09-13 14:54:28 +00006202 N0.getNode()->hasOneUse() && VT.isInteger() &&
6203 !VT.isVector() && !N0.getValueType().isVector()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006204 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006205 N0.getOperand(0));
Gabor Greiff304a7a2008-08-28 21:40:38 +00006206 AddToWorkList(NewConv.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +00006207
Duncan Sands13237ac2008-06-06 12:08:01 +00006208 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
Chris Lattner888560d2008-01-27 17:42:27 +00006209 if (N0.getOpcode() == ISD::FNEG)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006210 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006211 NewConv, DAG.getConstant(SignBit, VT));
Chris Lattner888560d2008-01-27 17:42:27 +00006212 assert(N0.getOpcode() == ISD::FABS);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006213 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006214 NewConv, DAG.getConstant(~SignBit, VT));
Chris Lattner888560d2008-01-27 17:42:27 +00006215 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006216
Bill Wendling4e0a6152009-01-30 22:44:24 +00006217 // fold (bitconvert (fcopysign cst, x)) ->
6218 // (or (and (bitconvert x), sign), (and cst, (not sign)))
6219 // Note that we don't handle (copysign x, cst) because this can always be
6220 // folded to an fneg or fabs.
Gabor Greiff304a7a2008-08-28 21:40:38 +00006221 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
Chris Lattner2ee91f42008-01-27 23:32:17 +00006222 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
Duncan Sands13237ac2008-06-06 12:08:01 +00006223 VT.isInteger() && !VT.isVector()) {
6224 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
Owen Anderson117c9e82009-08-12 00:36:31 +00006225 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
Chris Lattner4041ab62010-04-15 04:48:01 +00006226 if (isTypeLegal(IntXVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006227 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006228 IntXVT, N0.getOperand(1));
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006229 AddToWorkList(X.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00006230
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006231 // If X has a different width than the result/lhs, sext it or truncate it.
6232 unsigned VTWidth = VT.getSizeInBits();
6233 if (OrigXWidth < VTWidth) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006234 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006235 AddToWorkList(X.getNode());
6236 } else if (OrigXWidth > VTWidth) {
6237 // To get the sign bit in the right place, we have to shift it right
6238 // before truncating.
Andrew Trickef9de2a2013-05-25 02:42:55 +00006239 X = DAG.getNode(ISD::SRL, SDLoc(X),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006240 X.getValueType(), X,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006241 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6242 AddToWorkList(X.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00006243 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006244 AddToWorkList(X.getNode());
6245 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006246
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006247 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00006248 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006249 X, DAG.getConstant(SignBit, VT));
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006250 AddToWorkList(X.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00006251
Andrew Trickef9de2a2013-05-25 02:42:55 +00006252 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006253 VT, N0.getOperand(0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006254 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006255 Cst, DAG.getConstant(~SignBit, VT));
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006256 AddToWorkList(Cst.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00006257
Andrew Trickef9de2a2013-05-25 02:42:55 +00006258 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006259 }
Chris Lattner888560d2008-01-27 17:42:27 +00006260 }
Evan Chengb980f6f2008-05-12 23:04:07 +00006261
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00006262 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
Evan Chengb980f6f2008-05-12 23:04:07 +00006263 if (N0.getOpcode() == ISD::BUILD_PAIR) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00006264 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6265 if (CombineLD.getNode())
Evan Chengb980f6f2008-05-12 23:04:07 +00006266 return CombineLD;
6267 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006268
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006269 return SDValue();
Chris Lattnera1874602005-12-23 05:30:37 +00006270}
6271
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006272SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00006273 EVT VT = N->getValueType(0);
Evan Chengb980f6f2008-05-12 23:04:07 +00006274 return CombineConsecutiveLoads(N, VT);
6275}
6276
Wesley Peck527da1b2010-11-23 03:31:01 +00006277/// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
Scott Michelcf0da6c2009-02-17 22:15:04 +00006278/// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
Chris Lattnere4e64b62006-04-02 02:53:43 +00006279/// destination element value type.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006280SDValue DAGCombiner::
Wesley Peck527da1b2010-11-23 03:31:01 +00006281ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00006282 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006283
Chris Lattnere4e64b62006-04-02 02:53:43 +00006284 // If this is already the right type, we're done.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006285 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006286
Duncan Sands13237ac2008-06-06 12:08:01 +00006287 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6288 unsigned DstBitSize = DstEltVT.getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006289
Chris Lattnere4e64b62006-04-02 02:53:43 +00006290 // If this is a conversion of N elements of one type to N elements of another
6291 // type, convert each element. This handles FP<->INT cases.
6292 if (SrcBitSize == DstBitSize) {
Nate Begeman317b9692010-07-27 18:02:18 +00006293 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6294 BV->getValueType(0).getVectorNumElements());
6295
6296 // Due to the FP element handling below calling this routine recursively,
6297 // we can end up with a scalar-to-vector node here.
6298 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006299 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6300 DAG.getNode(ISD::BITCAST, SDLoc(BV),
Nate Begeman317b9692010-07-27 18:02:18 +00006301 DstEltVT, BV->getOperand(0)));
Wesley Peck527da1b2010-11-23 03:31:01 +00006302
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006303 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +00006304 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
Bob Wilson59dbbb22009-04-13 22:05:19 +00006305 SDValue Op = BV->getOperand(i);
6306 // If the vector element type is not legal, the BUILD_VECTOR operands
6307 // are promoted and implicitly truncated. Make that explicit here.
Bob Wilsonda188eb2009-04-20 17:27:09 +00006308 if (Op.getValueType() != SrcEltVT)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006309 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6310 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
Bob Wilson59dbbb22009-04-13 22:05:19 +00006311 DstEltVT, Op));
Gabor Greiff304a7a2008-08-28 21:40:38 +00006312 AddToWorkList(Ops.back().getNode());
Chris Lattner098c01e2006-04-08 04:15:24 +00006313 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00006314 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
Evan Chenga49de9d2009-02-25 22:49:59 +00006315 &Ops[0], Ops.size());
Chris Lattnere4e64b62006-04-02 02:53:43 +00006316 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006317
Chris Lattnere4e64b62006-04-02 02:53:43 +00006318 // Otherwise, we're growing or shrinking the elements. To avoid having to
6319 // handle annoying details of growing/shrinking FP values, we convert them to
6320 // int first.
Duncan Sands13237ac2008-06-06 12:08:01 +00006321 if (SrcEltVT.isFloatingPoint()) {
Chris Lattnere4e64b62006-04-02 02:53:43 +00006322 // Convert the input float vector to a int vector where the elements are the
6323 // same sizes.
Owen Anderson9f944592009-08-11 20:47:22 +00006324 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
Owen Anderson117c9e82009-08-12 00:36:31 +00006325 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
Wesley Peck527da1b2010-11-23 03:31:01 +00006326 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
Chris Lattnere4e64b62006-04-02 02:53:43 +00006327 SrcEltVT = IntVT;
6328 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006329
Chris Lattnere4e64b62006-04-02 02:53:43 +00006330 // Now we know the input is an integer vector. If the output is a FP type,
6331 // convert to integer first, then to FP of the right size.
Duncan Sands13237ac2008-06-06 12:08:01 +00006332 if (DstEltVT.isFloatingPoint()) {
Owen Anderson9f944592009-08-11 20:47:22 +00006333 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
Owen Anderson117c9e82009-08-12 00:36:31 +00006334 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
Wesley Peck527da1b2010-11-23 03:31:01 +00006335 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006336
Chris Lattnere4e64b62006-04-02 02:53:43 +00006337 // Next, convert to FP elements of the same size.
Wesley Peck527da1b2010-11-23 03:31:01 +00006338 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006339 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006340
Chris Lattnere4e64b62006-04-02 02:53:43 +00006341 // Okay, we know the src/dst types are both integers of differing types.
6342 // Handling growing first.
Duncan Sands13237ac2008-06-06 12:08:01 +00006343 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
Chris Lattnere4e64b62006-04-02 02:53:43 +00006344 if (SrcBitSize < DstBitSize) {
6345 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
Scott Michelcf0da6c2009-02-17 22:15:04 +00006346
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006347 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +00006348 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
Chris Lattnere4e64b62006-04-02 02:53:43 +00006349 i += NumInputsPerOutput) {
6350 bool isLE = TLI.isLittleEndian();
Dan Gohmane1c4f992008-03-03 23:51:38 +00006351 APInt NewBits = APInt(DstBitSize, 0);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006352 bool EltIsUndef = true;
6353 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6354 // Shift the previously computed bits over.
6355 NewBits <<= SrcBitSize;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006356 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006357 if (Op.getOpcode() == ISD::UNDEF) continue;
6358 EltIsUndef = false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00006359
Jay Foad583abbc2010-12-07 08:25:19 +00006360 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
Dan Gohmanecd40a32010-04-12 02:24:01 +00006361 zextOrTrunc(SrcBitSize).zext(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006362 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006363
Chris Lattnere4e64b62006-04-02 02:53:43 +00006364 if (EltIsUndef)
Dale Johannesen84935752009-02-06 23:05:02 +00006365 Ops.push_back(DAG.getUNDEF(DstEltVT));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006366 else
6367 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6368 }
6369
Owen Anderson117c9e82009-08-12 00:36:31 +00006370 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
Andrew Trickef9de2a2013-05-25 02:42:55 +00006371 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
Evan Chenga49de9d2009-02-25 22:49:59 +00006372 &Ops[0], Ops.size());
Chris Lattnere4e64b62006-04-02 02:53:43 +00006373 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006374
Chris Lattnere4e64b62006-04-02 02:53:43 +00006375 // Finally, this must be the case where we are shrinking elements: each input
6376 // turns into multiple outputs.
Evan Cheng6200c222008-02-18 23:04:32 +00006377 bool isS2V = ISD::isScalarToVector(BV);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006378 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
Owen Anderson117c9e82009-08-12 00:36:31 +00006379 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6380 NumOutputsPerInput*BV->getNumOperands());
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006381 SmallVector<SDValue, 8> Ops;
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006382
Dan Gohmana8665142007-06-25 16:23:39 +00006383 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
Chris Lattnere4e64b62006-04-02 02:53:43 +00006384 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6385 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
Dale Johannesen84935752009-02-06 23:05:02 +00006386 Ops.push_back(DAG.getUNDEF(DstEltVT));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006387 continue;
6388 }
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006389
Jay Foad583abbc2010-12-07 08:25:19 +00006390 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6391 getAPIntValue().zextOrTrunc(SrcBitSize);
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006392
Chris Lattnere4e64b62006-04-02 02:53:43 +00006393 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
Jay Foad583abbc2010-12-07 08:25:19 +00006394 APInt ThisVal = OpVal.trunc(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006395 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
Jay Foad583abbc2010-12-07 08:25:19 +00006396 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
Evan Cheng6200c222008-02-18 23:04:32 +00006397 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
Andrew Trickef9de2a2013-05-25 02:42:55 +00006398 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006399 Ops[0]);
Dan Gohmane1c4f992008-03-03 23:51:38 +00006400 OpVal = OpVal.lshr(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006401 }
6402
6403 // For big endian targets, swap the order of the pieces of each element.
Duncan Sands7377f5f2008-02-11 10:37:04 +00006404 if (TLI.isBigEndian())
Chris Lattnere4e64b62006-04-02 02:53:43 +00006405 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6406 }
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006407
Andrew Trickef9de2a2013-05-25 02:42:55 +00006408 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
Evan Chenga49de9d2009-02-25 22:49:59 +00006409 &Ops[0], Ops.size());
Chris Lattnere4e64b62006-04-02 02:53:43 +00006410}
6411
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006412SDValue DAGCombiner::visitFADD(SDNode *N) {
6413 SDValue N0 = N->getOperand(0);
6414 SDValue N1 = N->getOperand(1);
Nate Begeman418c6e42005-10-18 00:28:13 +00006415 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6416 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006417 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006418
Dan Gohmana8665142007-06-25 16:23:39 +00006419 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006420 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006421 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006422 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006423 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006424
Lang Hamesa33db652012-06-14 20:37:15 +00006425 // fold (fadd c1, c2) -> c1 + c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006426 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006427 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
Nate Begeman418c6e42005-10-18 00:28:13 +00006428 // canonicalize constant to RHS
6429 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006430 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006431 // fold (fadd A, 0) -> A
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006432 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6433 N1CFP->getValueAPF().isZero())
Dan Gohman1f3411d2009-01-22 21:58:43 +00006434 return N0;
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006435 // fold (fadd A, (fneg B)) -> (fsub A, B)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006436 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
Nadav Rotem841c9a82012-09-20 08:53:31 +00006437 isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006438 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006439 GetNegatedExpression(N1, DAG, LegalOperations));
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006440 // fold (fadd (fneg A), B) -> (fsub B, A)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006441 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
Nadav Rotem841c9a82012-09-20 08:53:31 +00006442 isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006443 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006444 GetNegatedExpression(N0, DAG, LegalOperations));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006445
Chris Lattner0199fd62007-01-08 23:04:05 +00006446 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006447 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6448 N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6449 isa<ConstantFPSDNode>(N0.getOperand(1)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006450 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6451 DAG.getNode(ISD::FADD, SDLoc(N), VT,
Bill Wendlinga6c75ff2009-02-01 11:19:36 +00006452 N0.getOperand(1), N1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006453
Shuxin Yang93b1f122013-03-25 22:52:29 +00006454 // No FP constant should be created after legalization as Instruction
6455 // Selection pass has hard time in dealing with FP constant.
6456 //
6457 // We don't need test this condition for transformation like following, as
6458 // the DAG being transformed implies it is legal to take FP constant as
6459 // operand.
Stephen Lincfe7f352013-07-08 00:37:03 +00006460 //
Shuxin Yang93b1f122013-03-25 22:52:29 +00006461 // (fadd (fmul c, x), x) -> (fmul c+1, x)
Stephen Lincfe7f352013-07-08 00:37:03 +00006462 //
Shuxin Yang93b1f122013-03-25 22:52:29 +00006463 bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6464
Owen Andersonb351c8d2012-11-01 02:00:53 +00006465 // If allow, fold (fadd (fneg x), x) -> 0.0
Shuxin Yang93b1f122013-03-25 22:52:29 +00006466 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006467 N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
Owen Andersonb351c8d2012-11-01 02:00:53 +00006468 return DAG.getConstantFP(0.0, VT);
Owen Andersonb351c8d2012-11-01 02:00:53 +00006469
6470 // If allow, fold (fadd x, (fneg x)) -> 0.0
Shuxin Yang93b1f122013-03-25 22:52:29 +00006471 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006472 N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
Owen Andersonb351c8d2012-11-01 02:00:53 +00006473 return DAG.getConstantFP(0.0, VT);
Owen Andersonb351c8d2012-11-01 02:00:53 +00006474
Owen Andersoncc61f872012-08-30 23:35:16 +00006475 // In unsafe math mode, we can fold chains of FADD's of the same value
6476 // into multiplications. This transform is not safe in general because
6477 // we are reducing the number of rounding steps.
6478 if (DAG.getTarget().Options.UnsafeFPMath &&
6479 TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6480 !N0CFP && !N1CFP) {
6481 if (N0.getOpcode() == ISD::FMUL) {
6482 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6483 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6484
Stephen Line31f2d22013-06-14 18:17:35 +00006485 // (fadd (fmul c, x), x) -> (fmul x, c+1)
Owen Andersoncc61f872012-08-30 23:35:16 +00006486 if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006487 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006488 SDValue(CFP00, 0),
6489 DAG.getConstantFP(1.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006490 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006491 N1, NewCFP);
6492 }
6493
Stephen Line31f2d22013-06-14 18:17:35 +00006494 // (fadd (fmul x, c), x) -> (fmul x, c+1)
Owen Andersoncc61f872012-08-30 23:35:16 +00006495 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006496 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006497 SDValue(CFP01, 0),
6498 DAG.getConstantFP(1.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006499 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006500 N1, NewCFP);
6501 }
6502
Stephen Line31f2d22013-06-14 18:17:35 +00006503 // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
Owen Andersoncc61f872012-08-30 23:35:16 +00006504 if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6505 N1.getOperand(0) == N1.getOperand(1) &&
6506 N0.getOperand(1) == N1.getOperand(0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006507 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006508 SDValue(CFP00, 0),
6509 DAG.getConstantFP(2.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006510 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006511 N0.getOperand(1), NewCFP);
6512 }
6513
Stephen Line31f2d22013-06-14 18:17:35 +00006514 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
Owen Andersoncc61f872012-08-30 23:35:16 +00006515 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6516 N1.getOperand(0) == N1.getOperand(1) &&
6517 N0.getOperand(0) == N1.getOperand(0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006518 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006519 SDValue(CFP01, 0),
6520 DAG.getConstantFP(2.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006521 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006522 N0.getOperand(0), NewCFP);
6523 }
6524 }
6525
6526 if (N1.getOpcode() == ISD::FMUL) {
6527 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6528 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6529
Stephen Line31f2d22013-06-14 18:17:35 +00006530 // (fadd x, (fmul c, x)) -> (fmul x, c+1)
Owen Andersoncc61f872012-08-30 23:35:16 +00006531 if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006532 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006533 SDValue(CFP10, 0),
6534 DAG.getConstantFP(1.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006535 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006536 N0, NewCFP);
6537 }
6538
Stephen Line31f2d22013-06-14 18:17:35 +00006539 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
Owen Andersoncc61f872012-08-30 23:35:16 +00006540 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006541 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006542 SDValue(CFP11, 0),
6543 DAG.getConstantFP(1.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006544 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006545 N0, NewCFP);
6546 }
6547
Owen Andersoncc61f872012-08-30 23:35:16 +00006548
Stephen Line31f2d22013-06-14 18:17:35 +00006549 // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6550 if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6551 N0.getOperand(0) == N0.getOperand(1) &&
6552 N1.getOperand(1) == N0.getOperand(0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006553 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006554 SDValue(CFP10, 0),
6555 DAG.getConstantFP(2.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006556 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Stephen Line31f2d22013-06-14 18:17:35 +00006557 N1.getOperand(1), NewCFP);
Owen Andersoncc61f872012-08-30 23:35:16 +00006558 }
6559
Stephen Line31f2d22013-06-14 18:17:35 +00006560 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6561 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6562 N0.getOperand(0) == N0.getOperand(1) &&
6563 N1.getOperand(0) == N0.getOperand(0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006564 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006565 SDValue(CFP11, 0),
6566 DAG.getConstantFP(2.0, VT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006567 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Stephen Line31f2d22013-06-14 18:17:35 +00006568 N1.getOperand(0), NewCFP);
Owen Andersoncc61f872012-08-30 23:35:16 +00006569 }
6570 }
6571
Shuxin Yang93b1f122013-03-25 22:52:29 +00006572 if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006573 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
Stephen Lin4e69d012013-06-14 21:33:58 +00006574 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006575 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006576 (N0.getOperand(0) == N1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006577 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006578 N1, DAG.getConstantFP(3.0, VT));
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006579 }
6580
Shuxin Yang93b1f122013-03-25 22:52:29 +00006581 if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006582 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
Stephen Lin4e69d012013-06-14 21:33:58 +00006583 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006584 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006585 N1.getOperand(0) == N0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006586 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006587 N0, DAG.getConstantFP(3.0, VT));
Shuxin Yangcadd8a02013-02-02 00:22:03 +00006588 }
6589
Stephen Lin4e69d012013-06-14 21:33:58 +00006590 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
Shuxin Yang93b1f122013-03-25 22:52:29 +00006591 if (AllowNewFpConst &&
6592 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
Owen Andersoncc61f872012-08-30 23:35:16 +00006593 N0.getOperand(0) == N0.getOperand(1) &&
6594 N1.getOperand(0) == N1.getOperand(1) &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006595 N0.getOperand(0) == N1.getOperand(0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006596 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Andersoncc61f872012-08-30 23:35:16 +00006597 N0.getOperand(0),
6598 DAG.getConstantFP(4.0, VT));
Owen Andersoncc61f872012-08-30 23:35:16 +00006599 }
6600
Lang Hames39fb1d02012-06-19 22:51:23 +00006601 // FADD -> FMA combines:
Lang Hamesb8650f12012-06-22 01:09:09 +00006602 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
Lang Hames39fb1d02012-06-19 22:51:23 +00006603 DAG.getTarget().Options.UnsafeFPMath) &&
Stephen Lin73de7bf2013-07-09 18:16:56 +00006604 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6605 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
Lang Hames39fb1d02012-06-19 22:51:23 +00006606
6607 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
Stephen Lin8e8424e2013-07-09 00:44:49 +00006608 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006609 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006610 N0.getOperand(0), N0.getOperand(1), N1);
Owen Andersoncc61f872012-08-30 23:35:16 +00006611
Michael Liaoec3850122012-09-01 04:09:16 +00006612 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
Lang Hames39fb1d02012-06-19 22:51:23 +00006613 // Note: Commutes FADD operands.
Stephen Lin8e8424e2013-07-09 00:44:49 +00006614 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006615 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006616 N1.getOperand(0), N1.getOperand(1), N0);
Lang Hames39fb1d02012-06-19 22:51:23 +00006617 }
6618
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006619 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006620}
6621
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006622SDValue DAGCombiner::visitFSUB(SDNode *N) {
6623 SDValue N0 = N->getOperand(0);
6624 SDValue N1 = N->getOperand(1);
Nate Begeman418c6e42005-10-18 00:28:13 +00006625 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6626 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006627 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006628 SDLoc dl(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006629
Dan Gohmana8665142007-06-25 16:23:39 +00006630 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006631 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006632 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006633 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006634 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006635
Nate Begeman418c6e42005-10-18 00:28:13 +00006636 // fold (fsub c1, c2) -> c1-c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006637 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006638 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006639 // fold (fsub A, 0) -> A
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006640 if (DAG.getTarget().Options.UnsafeFPMath &&
6641 N1CFP && N1CFP->getValueAPF().isZero())
Dan Gohman1275e282009-01-23 19:10:37 +00006642 return N0;
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006643 // fold (fsub 0, B) -> -B
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006644 if (DAG.getTarget().Options.UnsafeFPMath &&
6645 N0CFP && N0CFP->getValueAPF().isZero()) {
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006646 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006647 return GetNegatedExpression(N1, DAG, LegalOperations);
Dan Gohman1f3411d2009-01-22 21:58:43 +00006648 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006649 return DAG.getNode(ISD::FNEG, dl, VT, N1);
Dan Gohman9a708232007-07-02 15:48:56 +00006650 }
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006651 // fold (fsub A, (fneg B)) -> (fadd A, B)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006652 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006653 return DAG.getNode(ISD::FADD, dl, VT, N0,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006654 GetNegatedExpression(N1, DAG, LegalOperations));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006655
Bill Wendlingdf170db2012-03-15 05:12:00 +00006656 // If 'unsafe math' is enabled, fold
Owen Andersonab63d842012-05-07 20:51:25 +00006657 // (fsub x, x) -> 0.0 &
Bill Wendlingdf170db2012-03-15 05:12:00 +00006658 // (fsub x, (fadd x, y)) -> (fneg y) &
6659 // (fsub x, (fadd y, x)) -> (fneg y)
6660 if (DAG.getTarget().Options.UnsafeFPMath) {
Owen Andersonab63d842012-05-07 20:51:25 +00006661 if (N0 == N1)
6662 return DAG.getConstantFP(0.0f, VT);
6663
Bill Wendlingdf170db2012-03-15 05:12:00 +00006664 if (N1.getOpcode() == ISD::FADD) {
6665 SDValue N10 = N1->getOperand(0);
6666 SDValue N11 = N1->getOperand(1);
6667
6668 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6669 &DAG.getTarget().Options))
6670 return GetNegatedExpression(N11, DAG, LegalOperations);
Stephen Lin10947502013-07-10 20:47:39 +00006671
Stephen Lin8e8424e2013-07-09 00:44:49 +00006672 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6673 &DAG.getTarget().Options))
Bill Wendlingdf170db2012-03-15 05:12:00 +00006674 return GetNegatedExpression(N10, DAG, LegalOperations);
6675 }
6676 }
6677
Lang Hames39fb1d02012-06-19 22:51:23 +00006678 // FSUB -> FMA combines:
Lang Hamesb8650f12012-06-22 01:09:09 +00006679 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
Lang Hames39fb1d02012-06-19 22:51:23 +00006680 DAG.getTarget().Options.UnsafeFPMath) &&
Stephen Lin73de7bf2013-07-09 18:16:56 +00006681 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6682 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
Lang Hames39fb1d02012-06-19 22:51:23 +00006683
6684 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
Stephen Lin8e8424e2013-07-09 00:44:49 +00006685 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006686 return DAG.getNode(ISD::FMA, dl, VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006687 N0.getOperand(0), N0.getOperand(1),
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006688 DAG.getNode(ISD::FNEG, dl, VT, N1));
Lang Hames39fb1d02012-06-19 22:51:23 +00006689
6690 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6691 // Note: Commutes FSUB operands.
Stephen Lin10947502013-07-10 20:47:39 +00006692 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006693 return DAG.getNode(ISD::FMA, dl, VT,
6694 DAG.getNode(ISD::FNEG, dl, VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006695 N1.getOperand(0)),
6696 N1.getOperand(1), N0);
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006697
Stephen Lin8e8424e2013-07-09 00:44:49 +00006698 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
Stephen Lincfe7f352013-07-08 00:37:03 +00006699 if (N0.getOpcode() == ISD::FNEG &&
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006700 N0.getOperand(0).getOpcode() == ISD::FMUL &&
6701 N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6702 SDValue N00 = N0.getOperand(0).getOperand(0);
6703 SDValue N01 = N0.getOperand(0).getOperand(1);
6704 return DAG.getNode(ISD::FMA, dl, VT,
6705 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6706 DAG.getNode(ISD::FNEG, dl, VT, N1));
6707 }
Lang Hames39fb1d02012-06-19 22:51:23 +00006708 }
6709
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006710 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006711}
6712
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006713SDValue DAGCombiner::visitFMUL(SDNode *N) {
6714 SDValue N0 = N->getOperand(0);
6715 SDValue N1 = N->getOperand(1);
Nate Begemanec48a1b2005-10-17 20:40:11 +00006716 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6717 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006718 EVT VT = N->getValueType(0);
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006719 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006720
Dan Gohmana8665142007-06-25 16:23:39 +00006721 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006722 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006723 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006724 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006725 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006726
Nate Begemanec48a1b2005-10-17 20:40:11 +00006727 // fold (fmul c1, c2) -> c1*c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006728 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006729 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
Nate Begemanec48a1b2005-10-17 20:40:11 +00006730 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00006731 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006732 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
Bill Wendling3dc5d242009-01-30 22:57:07 +00006733 // fold (fmul A, 0) -> 0
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006734 if (DAG.getTarget().Options.UnsafeFPMath &&
6735 N1CFP && N1CFP->getValueAPF().isZero())
Dan Gohman1f3411d2009-01-22 21:58:43 +00006736 return N1;
Dan Gohman7b6b5dd2009-06-04 17:12:12 +00006737 // fold (fmul A, 0) -> 0, vector edition.
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006738 if (DAG.getTarget().Options.UnsafeFPMath &&
6739 ISD::isBuildVectorAllZeros(N1.getNode()))
Dan Gohman7b6b5dd2009-06-04 17:12:12 +00006740 return N1;
Owen Andersonb5f167c2012-05-02 21:32:35 +00006741 // fold (fmul A, 1.0) -> A
6742 if (N1CFP && N1CFP->isExactlyValue(1.0))
6743 return N0;
Nate Begemanec48a1b2005-10-17 20:40:11 +00006744 // fold (fmul X, 2.0) -> (fadd X, X)
6745 if (N1CFP && N1CFP->isExactlyValue(+2.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006746 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
Dan Gohmanb7170912009-08-10 16:50:32 +00006747 // fold (fmul X, -1.0) -> (fneg X)
Chris Lattnere49c9742007-05-14 22:04:50 +00006748 if (N1CFP && N1CFP->isExactlyValue(-1.0))
Dan Gohman1f3411d2009-01-22 21:58:43 +00006749 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006750 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006751
Bill Wendling3dc5d242009-01-30 22:57:07 +00006752 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006753 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006754 &DAG.getTarget().Options)) {
Stephen Lincfe7f352013-07-08 00:37:03 +00006755 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006756 &DAG.getTarget().Options)) {
Chris Lattnere49c9742007-05-14 22:04:50 +00006757 // Both can be negated for free, check to see if at least one is cheaper
6758 // negated.
6759 if (LHSNeg == 2 || RHSNeg == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006760 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006761 GetNegatedExpression(N0, DAG, LegalOperations),
6762 GetNegatedExpression(N1, DAG, LegalOperations));
Chris Lattnere49c9742007-05-14 22:04:50 +00006763 }
6764 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006765
Chris Lattner0199fd62007-01-08 23:04:05 +00006766 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006767 if (DAG.getTarget().Options.UnsafeFPMath &&
6768 N1CFP && N0.getOpcode() == ISD::FMUL &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00006769 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006770 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6771 DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Dale Johannesen400dc2e2009-02-06 21:50:26 +00006772 N0.getOperand(1), N1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006773
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006774 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006775}
6776
Owen Anderson41b06652012-05-02 22:17:40 +00006777SDValue DAGCombiner::visitFMA(SDNode *N) {
6778 SDValue N0 = N->getOperand(0);
6779 SDValue N1 = N->getOperand(1);
6780 SDValue N2 = N->getOperand(2);
6781 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6782 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6783 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006784 SDLoc dl(N);
Owen Anderson41b06652012-05-02 22:17:40 +00006785
Owen Andersonb351c8d2012-11-01 02:00:53 +00006786 if (DAG.getTarget().Options.UnsafeFPMath) {
6787 if (N0CFP && N0CFP->isZero())
6788 return N2;
6789 if (N1CFP && N1CFP->isZero())
6790 return N2;
6791 }
Owen Anderson41b06652012-05-02 22:17:40 +00006792 if (N0CFP && N0CFP->isExactlyValue(1.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006793 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
Owen Anderson41b06652012-05-02 22:17:40 +00006794 if (N1CFP && N1CFP->isExactlyValue(1.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006795 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
Owen Anderson41b06652012-05-02 22:17:40 +00006796
Owen Andersonc7aaf522012-05-30 18:50:39 +00006797 // Canonicalize (fma c, x, y) -> (fma x, c, y)
Owen Anderson0eda3e12012-05-30 18:54:50 +00006798 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006799 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
Owen Andersonc7aaf522012-05-30 18:50:39 +00006800
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006801 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6802 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6803 N2.getOpcode() == ISD::FMUL &&
6804 N0 == N2.getOperand(0) &&
6805 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6806 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6807 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6808 }
6809
6810
6811 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6812 if (DAG.getTarget().Options.UnsafeFPMath &&
6813 N0.getOpcode() == ISD::FMUL && N1CFP &&
6814 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6815 return DAG.getNode(ISD::FMA, dl, VT,
6816 N0.getOperand(0),
6817 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6818 N2);
6819 }
6820
6821 // (fma x, 1, y) -> (fadd x, y)
6822 // (fma x, -1, y) -> (fadd (fneg x), y)
6823 if (N1CFP) {
6824 if (N1CFP->isExactlyValue(1.0))
6825 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6826
6827 if (N1CFP->isExactlyValue(-1.0) &&
6828 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6829 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6830 AddToWorkList(RHSNeg.getNode());
6831 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6832 }
6833 }
6834
6835 // (fma x, c, x) -> (fmul x, (c+1))
Stephen Lin8e8424e2013-07-09 00:44:49 +00006836 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6837 return DAG.getNode(ISD::FMUL, dl, VT, N0,
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006838 DAG.getNode(ISD::FADD, dl, VT,
6839 N1, DAG.getConstantFP(1.0, VT)));
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006840
6841 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6842 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006843 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6844 return DAG.getNode(ISD::FMUL, dl, VT, N0,
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006845 DAG.getNode(ISD::FADD, dl, VT,
6846 N1, DAG.getConstantFP(-1.0, VT)));
Owen Anderson90e0eaf2012-09-01 06:04:27 +00006847
6848
Owen Anderson41b06652012-05-02 22:17:40 +00006849 return SDValue();
6850}
6851
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006852SDValue DAGCombiner::visitFDIV(SDNode *N) {
6853 SDValue N0 = N->getOperand(0);
6854 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00006855 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6856 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006857 EVT VT = N->getValueType(0);
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006858 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006859
Dan Gohmana8665142007-06-25 16:23:39 +00006860 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006861 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006862 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006863 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006864 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006865
Nate Begeman569c4392006-01-18 22:35:16 +00006866 // fold (fdiv c1, c2) -> c1/c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006867 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006868 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006869
Duncan Sands2f1dc382012-04-08 18:08:12 +00006870 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006871 if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
Duncan Sands5f8397a2012-04-07 20:04:00 +00006872 // Compute the reciprocal 1.0 / c2.
6873 APFloat N1APF = N1CFP->getValueAPF();
6874 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6875 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
Duncan Sands4f530742012-04-10 20:35:27 +00006876 // Only do the transform if the reciprocal is a legal fp immediate that
6877 // isn't too nasty (eg NaN, denormal, ...).
6878 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
Anton Korobeynikov4d1220d2012-04-10 13:22:49 +00006879 (!LegalOperations ||
6880 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6881 // backend)... we should handle this gracefully after Legalize.
6882 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6883 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6884 TLI.isFPImmLegal(Recip, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006885 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
Duncan Sands5f8397a2012-04-07 20:04:00 +00006886 DAG.getConstantFP(Recip, VT));
6887 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006888
Bill Wendling3dc5d242009-01-30 22:57:07 +00006889 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006890 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006891 &DAG.getTarget().Options)) {
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006892 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +00006893 &DAG.getTarget().Options)) {
Chris Lattnere49c9742007-05-14 22:04:50 +00006894 // Both can be negated for free, check to see if at least one is cheaper
6895 // negated.
6896 if (LHSNeg == 2 || RHSNeg == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006897 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006898 GetNegatedExpression(N0, DAG, LegalOperations),
6899 GetNegatedExpression(N1, DAG, LegalOperations));
Chris Lattnere49c9742007-05-14 22:04:50 +00006900 }
6901 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006902
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006903 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006904}
6905
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006906SDValue DAGCombiner::visitFREM(SDNode *N) {
6907 SDValue N0 = N->getOperand(0);
6908 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00006909 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6910 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006911 EVT VT = N->getValueType(0);
Chris Lattner6f3b5772005-09-28 22:28:18 +00006912
Nate Begeman569c4392006-01-18 22:35:16 +00006913 // fold (frem c1, c2) -> fmod(c1,c2)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006914 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006915 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
Dan Gohmana8665142007-06-25 16:23:39 +00006916
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006917 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006918}
6919
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006920SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6921 SDValue N0 = N->getOperand(0);
6922 SDValue N1 = N->getOperand(1);
Chris Lattner3bc40502006-03-05 05:30:57 +00006923 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6924 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006925 EVT VT = N->getValueType(0);
Chris Lattner3bc40502006-03-05 05:30:57 +00006926
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006927 if (N0CFP && N1CFP) // Constant fold
Andrew Trickef9de2a2013-05-25 02:42:55 +00006928 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006929
Chris Lattner3bc40502006-03-05 05:30:57 +00006930 if (N1CFP) {
Dale Johannesenb6d2bec2007-08-26 01:18:27 +00006931 const APFloat& V = N1CFP->getValueAPF();
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00006932 // copysign(x, c1) -> fabs(x) iff ispos(c1)
6933 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
Dan Gohman1f3411d2009-01-22 21:58:43 +00006934 if (!V.isNegative()) {
6935 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006936 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Dan Gohman1f3411d2009-01-22 21:58:43 +00006937 } else {
6938 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006939 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6940 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
Dan Gohman1f3411d2009-01-22 21:58:43 +00006941 }
Chris Lattner3bc40502006-03-05 05:30:57 +00006942 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006943
Chris Lattner3bc40502006-03-05 05:30:57 +00006944 // copysign(fabs(x), y) -> copysign(x, y)
6945 // copysign(fneg(x), y) -> copysign(x, y)
6946 // copysign(copysign(x,z), y) -> copysign(x, y)
6947 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
6948 N0.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006949 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00006950 N0.getOperand(0), N1);
Chris Lattner3bc40502006-03-05 05:30:57 +00006951
6952 // copysign(x, abs(y)) -> abs(x)
6953 if (N1.getOpcode() == ISD::FABS)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006954 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006955
Chris Lattner3bc40502006-03-05 05:30:57 +00006956 // copysign(x, copysign(y,z)) -> copysign(x, z)
6957 if (N1.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006958 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00006959 N0, N1.getOperand(1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006960
Chris Lattner3bc40502006-03-05 05:30:57 +00006961 // copysign(x, fp_extend(y)) -> copysign(x, y)
6962 // copysign(x, fp_round(y)) -> copysign(x, y)
6963 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006964 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00006965 N0, N1.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006966
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006967 return SDValue();
Chris Lattner3bc40502006-03-05 05:30:57 +00006968}
6969
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006970SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
6971 SDValue N0 = N->getOperand(0);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00006972 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006973 EVT VT = N->getValueType(0);
6974 EVT OpVT = N0.getValueType();
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00006975
Nate Begeman21158fc2005-09-01 00:19:25 +00006976 // fold (sint_to_fp c1) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006977 if (N0C &&
Stuart Hastings6b4007d2011-03-02 19:36:30 +00006978 // ...but only if the target supports immediate floating-point values
Eli Friedman9d448e42011-11-12 00:35:34 +00006979 (!LegalOperations ||
Evan Cheng4c0bd962011-06-21 06:01:08 +00006980 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006981 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006982
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00006983 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
6984 // but UINT_TO_FP is legal on this target, try to convert.
Dan Gohman4aa18462009-01-28 17:46:25 +00006985 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
6986 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
Scott Michelcf0da6c2009-02-17 22:15:04 +00006987 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00006988 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006989 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00006990 }
Bill Wendling0bd29742009-01-30 23:15:49 +00006991
Alp Tokercb402912014-01-24 17:20:08 +00006992 // The next optimizations are desirable only if SELECT_CC can be lowered.
Nadav Rotem90560762012-07-23 07:59:50 +00006993 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6994 // having to say they don't support SELECT_CC on every type the DAG knows
6995 // about, since there is no way to mark an opcode illegal at all value types
6996 // (See also visitSELECT)
6997 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6998 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6999 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7000 !VT.isVector() &&
7001 (!LegalOperations ||
7002 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7003 SDValue Ops[] =
7004 { N0.getOperand(0), N0.getOperand(1),
7005 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7006 N0.getOperand(2) };
Andrew Trickef9de2a2013-05-25 02:42:55 +00007007 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
Nadav Rotem90560762012-07-23 07:59:50 +00007008 }
Owen Andersond4b841f2012-07-09 20:31:12 +00007009
Nadav Rotem90560762012-07-23 07:59:50 +00007010 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7011 // (select_cc x, y, 1.0, 0.0,, cc)
7012 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7013 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7014 (!LegalOperations ||
7015 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7016 SDValue Ops[] =
7017 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7018 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7019 N0.getOperand(0).getOperand(2) };
Andrew Trickef9de2a2013-05-25 02:42:55 +00007020 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
Nadav Rotem90560762012-07-23 07:59:50 +00007021 }
Owen Andersond4b841f2012-07-09 20:31:12 +00007022 }
7023
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007024 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007025}
7026
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007027SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7028 SDValue N0 = N->getOperand(0);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00007029 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007030 EVT VT = N->getValueType(0);
7031 EVT OpVT = N0.getValueType();
Nate Begeman569c4392006-01-18 22:35:16 +00007032
Nate Begeman21158fc2005-09-01 00:19:25 +00007033 // fold (uint_to_fp c1) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007034 if (N0C &&
Stuart Hastings6b4007d2011-03-02 19:36:30 +00007035 // ...but only if the target supports immediate floating-point values
Eli Friedman9d448e42011-11-12 00:35:34 +00007036 (!LegalOperations ||
Evan Cheng4c0bd962011-06-21 06:01:08 +00007037 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007038 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007039
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007040 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7041 // but SINT_TO_FP is legal on this target, try to convert.
Dan Gohman4aa18462009-01-28 17:46:25 +00007042 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7043 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
Scott Michelcf0da6c2009-02-17 22:15:04 +00007044 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007045 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007046 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007047 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007048
Alp Tokercb402912014-01-24 17:20:08 +00007049 // The next optimizations are desirable only if SELECT_CC can be lowered.
Nadav Rotem90560762012-07-23 07:59:50 +00007050 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
7051 // having to say they don't support SELECT_CC on every type the DAG knows
7052 // about, since there is no way to mark an opcode illegal at all value types
7053 // (See also visitSELECT)
7054 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
7055 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
Owen Andersond4b841f2012-07-09 20:31:12 +00007056
Nadav Rotem90560762012-07-23 07:59:50 +00007057 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7058 (!LegalOperations ||
7059 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7060 SDValue Ops[] =
7061 { N0.getOperand(0), N0.getOperand(1),
7062 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
7063 N0.getOperand(2) };
Andrew Trickef9de2a2013-05-25 02:42:55 +00007064 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
Nadav Rotem90560762012-07-23 07:59:50 +00007065 }
7066 }
Owen Andersond4b841f2012-07-09 20:31:12 +00007067
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007068 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007069}
7070
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007071SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7072 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007073 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007074 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007075
Nate Begeman21158fc2005-09-01 00:19:25 +00007076 // fold (fp_to_sint c1fp) -> c1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00007077 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007078 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
Bill Wendling0bd29742009-01-30 23:15:49 +00007079
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007080 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007081}
7082
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007083SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7084 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007085 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007086 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007087
Nate Begeman21158fc2005-09-01 00:19:25 +00007088 // fold (fp_to_uint c1fp) -> c1
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007089 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007090 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
Bill Wendling0bd29742009-01-30 23:15:49 +00007091
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007092 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007093}
7094
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007095SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7096 SDValue N0 = N->getOperand(0);
7097 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00007098 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007099 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007100
Nate Begeman21158fc2005-09-01 00:19:25 +00007101 // fold (fp_round c1fp) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007102 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007103 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007104
Chris Lattner8bb6cb72006-03-13 06:26:26 +00007105 // fold (fp_round (fp_extend x)) -> x
7106 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7107 return N0.getOperand(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007108
Chris Lattner0feb1b02008-01-24 06:45:35 +00007109 // fold (fp_round (fp_round x)) -> (fp_round x)
7110 if (N0.getOpcode() == ISD::FP_ROUND) {
7111 // This is a value preserving truncation if both round's are.
7112 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00007113 N0.getNode()->getConstantOperandVal(1) == 1;
Andrew Trickef9de2a2013-05-25 02:42:55 +00007114 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
Chris Lattner0feb1b02008-01-24 06:45:35 +00007115 DAG.getIntPtrConstant(IsTrunc));
7116 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007117
Chris Lattner8bb6cb72006-03-13 06:26:26 +00007118 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
Gabor Greiff304a7a2008-08-28 21:40:38 +00007119 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007120 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007121 N0.getOperand(0), N1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00007122 AddToWorkList(Tmp.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00007123 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007124 Tmp, N0.getOperand(1));
Chris Lattner8bb6cb72006-03-13 06:26:26 +00007125 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007126
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007127 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007128}
7129
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007130SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7131 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007132 EVT VT = N->getValueType(0);
7133 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
Nate Begeman7cea6ef2005-09-02 21:18:40 +00007134 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007135
Nate Begeman21158fc2005-09-01 00:19:25 +00007136 // fold (fp_round_inreg c1fp) -> c1fp
Chris Lattner4041ab62010-04-15 04:48:01 +00007137 if (N0CFP && isTypeLegal(EVT)) {
Dan Gohmanec270fb2008-09-12 18:08:03 +00007138 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007139 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
Nate Begeman21158fc2005-09-01 00:19:25 +00007140 }
Bill Wendling0bd29742009-01-30 23:15:49 +00007141
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007142 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007143}
7144
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007145SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7146 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007147 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007148 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007149
Chris Lattner5919b482007-12-29 06:55:23 +00007150 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
Scott Michelcf0da6c2009-02-17 22:15:04 +00007151 if (N->hasOneUse() &&
Dan Gohman8e4ac9b2009-01-26 04:35:06 +00007152 N->use_begin()->getOpcode() == ISD::FP_ROUND)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007153 return SDValue();
Chris Lattner72733e52008-01-17 07:00:52 +00007154
Nate Begeman21158fc2005-09-01 00:19:25 +00007155 // fold (fp_extend c1fp) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007156 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007157 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
Chris Lattner72733e52008-01-17 07:00:52 +00007158
7159 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7160 // value of X.
Gabor Greife12264b2008-08-30 19:29:20 +00007161 if (N0.getOpcode() == ISD::FP_ROUND
7162 && N0.getNode()->getConstantOperandVal(1) == 1) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007163 SDValue In = N0.getOperand(0);
Chris Lattner72733e52008-01-17 07:00:52 +00007164 if (In.getValueType() == VT) return In;
Duncan Sands11dd4242008-06-08 20:54:56 +00007165 if (VT.bitsLT(In.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007166 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007167 In, N0.getOperand(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00007168 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
Chris Lattner72733e52008-01-17 07:00:52 +00007169 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007170
Chris Lattner72733e52008-01-17 07:00:52 +00007171 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
Hal Finkeldbc7a8a2013-10-04 22:18:12 +00007172 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007173 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00007174 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00007175 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007176 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007177 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00007178 LN0->getBasePtr(), N0.getValueType(),
7179 LN0->getMemOperand());
Chris Lattner3d265772006-05-05 21:34:35 +00007180 CombineTo(N, ExtLoad);
Bill Wendling0bd29742009-01-30 23:15:49 +00007181 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00007182 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
Bill Wendling0bd29742009-01-30 23:15:49 +00007183 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
Chris Lattner3d265772006-05-05 21:34:35 +00007184 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007185 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattner3d265772006-05-05 21:34:35 +00007186 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00007187
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007188 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007189}
7190
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007191SDValue DAGCombiner::visitFNEG(SDNode *N) {
7192 SDValue N0 = N->getOperand(0);
Anton Korobeynikova6faf602009-10-20 21:37:45 +00007193 EVT VT = N->getValueType(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007194
Craig Topper82384612012-09-11 01:45:21 +00007195 if (VT.isVector()) {
7196 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7197 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topper03f39772012-09-09 22:58:45 +00007198 }
7199
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00007200 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7201 &DAG.getTarget().Options))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007202 return GetNegatedExpression(N0, DAG, LegalOperations);
Dan Gohman9a708232007-07-02 15:48:56 +00007203
Chris Lattner888560d2008-01-27 17:42:27 +00007204 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
7205 // constant pool values.
Owen Anderson98f2c0c2012-04-02 22:10:29 +00007206 if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
Anton Korobeynikova6faf602009-10-20 21:37:45 +00007207 !VT.isVector() &&
7208 N0.getNode()->hasOneUse() &&
7209 N0.getOperand(0).getValueType().isInteger()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007210 SDValue Int = N0.getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007211 EVT IntVT = Int.getValueType();
Duncan Sands13237ac2008-06-06 12:08:01 +00007212 if (IntVT.isInteger() && !IntVT.isVector()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007213 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
Duncan Sands3ed76882009-02-01 18:06:53 +00007214 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
Gabor Greiff304a7a2008-08-28 21:40:38 +00007215 AddToWorkList(Int.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00007216 return DAG.getNode(ISD::BITCAST, SDLoc(N),
Anton Korobeynikova6faf602009-10-20 21:37:45 +00007217 VT, Int);
Chris Lattner888560d2008-01-27 17:42:27 +00007218 }
7219 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007220
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007221 // (fneg (fmul c, x)) -> (fmul -c, x)
7222 if (N0.getOpcode() == ISD::FMUL) {
7223 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
Stephen Lin8e8424e2013-07-09 00:44:49 +00007224 if (CFP1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007225 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007226 N0.getOperand(0),
Andrew Trickef9de2a2013-05-25 02:42:55 +00007227 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007228 N0.getOperand(1)));
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007229 }
7230
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007231 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007232}
7233
Owen Andersona40319b2012-08-13 23:32:49 +00007234SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7235 SDValue N0 = N->getOperand(0);
7236 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7237 EVT VT = N->getValueType(0);
7238
7239 // fold (fceil c1) -> fceil(c1)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007240 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007241 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
Owen Andersona40319b2012-08-13 23:32:49 +00007242
7243 return SDValue();
7244}
7245
7246SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7247 SDValue N0 = N->getOperand(0);
7248 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7249 EVT VT = N->getValueType(0);
7250
7251 // fold (ftrunc c1) -> ftrunc(c1)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007252 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007253 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
Owen Andersona40319b2012-08-13 23:32:49 +00007254
7255 return SDValue();
7256}
7257
7258SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7259 SDValue N0 = N->getOperand(0);
7260 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7261 EVT VT = N->getValueType(0);
7262
7263 // fold (ffloor c1) -> ffloor(c1)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007264 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007265 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
Owen Andersona40319b2012-08-13 23:32:49 +00007266
7267 return SDValue();
7268}
7269
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007270SDValue DAGCombiner::visitFABS(SDNode *N) {
7271 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007272 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007273 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007274
Craig Topper82384612012-09-11 01:45:21 +00007275 if (VT.isVector()) {
7276 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7277 if (FoldedVOp.getNode()) return FoldedVOp;
7278 }
7279
Nate Begeman21158fc2005-09-01 00:19:25 +00007280 // fold (fabs c1) -> fabs(c1)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007281 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007282 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00007283 // fold (fabs (fabs x)) -> (fabs x)
Chris Lattner3bc40502006-03-05 05:30:57 +00007284 if (N0.getOpcode() == ISD::FABS)
Nate Begemand23739d2005-09-06 04:43:02 +00007285 return N->getOperand(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00007286 // fold (fabs (fneg x)) -> (fabs x)
Chris Lattner3bc40502006-03-05 05:30:57 +00007287 // fold (fabs (fcopysign x, y)) -> (fabs x)
7288 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007289 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00007290
Chris Lattner888560d2008-01-27 17:42:27 +00007291 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
7292 // constant pool values.
Stephen Lincfe7f352013-07-08 00:37:03 +00007293 if (!TLI.isFAbsFree(VT) &&
Owen Anderson98f2c0c2012-04-02 22:10:29 +00007294 N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
Duncan Sands13237ac2008-06-06 12:08:01 +00007295 N0.getOperand(0).getValueType().isInteger() &&
7296 !N0.getOperand(0).getValueType().isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007297 SDValue Int = N0.getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007298 EVT IntVT = Int.getValueType();
Duncan Sands13237ac2008-06-06 12:08:01 +00007299 if (IntVT.isInteger() && !IntVT.isVector()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007300 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
Duncan Sands3ed76882009-02-01 18:06:53 +00007301 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
Gabor Greiff304a7a2008-08-28 21:40:38 +00007302 AddToWorkList(Int.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00007303 return DAG.getNode(ISD::BITCAST, SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007304 N->getValueType(0), Int);
Chris Lattner888560d2008-01-27 17:42:27 +00007305 }
7306 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007307
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007308 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007309}
7310
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007311SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7312 SDValue Chain = N->getOperand(0);
7313 SDValue N1 = N->getOperand(1);
7314 SDValue N2 = N->getOperand(2);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007315
Dan Gohman82e80012009-11-17 00:47:23 +00007316 // If N is a constant we could fold this into a fallthrough or unconditional
7317 // branch. However that doesn't happen very often in normal code, because
7318 // Instcombine/SimplifyCFG should have handled the available opportunities.
7319 // If we did this folding here, it would be necessary to update the
7320 // MachineBasicBlock CFG, which is awkward.
7321
Nate Begeman7e7f4392006-02-01 07:19:44 +00007322 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7323 // on the target.
Scott Michelcf0da6c2009-02-17 22:15:04 +00007324 if (N1.getOpcode() == ISD::SETCC &&
Tom Stellardb1588fc2013-03-08 15:36:57 +00007325 TLI.isOperationLegalOrCustom(ISD::BR_CC,
7326 N1.getOperand(0).getValueType())) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007327 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
Bill Wendling306bfc22009-01-30 23:27:35 +00007328 Chain, N1.getOperand(2),
Nate Begeman7e7f4392006-02-01 07:19:44 +00007329 N1.getOperand(0), N1.getOperand(1), N2);
7330 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007331
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007332 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7333 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7334 (N1.getOperand(0).hasOneUse() &&
7335 N1.getOperand(0).getOpcode() == ISD::SRL))) {
Craig Topperc0196b12014-04-14 00:51:57 +00007336 SDNode *Trunc = nullptr;
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007337 if (N1.getOpcode() == ISD::TRUNCATE) {
7338 // Look pass the truncate.
7339 Trunc = N1.getNode();
7340 N1 = N1.getOperand(0);
7341 }
Evan Cheng166a4e62010-01-06 19:38:29 +00007342
Bill Wendlingaa28be62009-03-26 06:14:09 +00007343 // Match this pattern so that we can generate simpler code:
7344 //
7345 // %a = ...
7346 // %b = and i32 %a, 2
7347 // %c = srl i32 %b, 1
7348 // brcond i32 %c ...
7349 //
7350 // into
Wesley Peck527da1b2010-11-23 03:31:01 +00007351 //
Bill Wendlingaa28be62009-03-26 06:14:09 +00007352 // %a = ...
Evan Cheng166a4e62010-01-06 19:38:29 +00007353 // %b = and i32 %a, 2
Bill Wendlingaa28be62009-03-26 06:14:09 +00007354 // %c = setcc eq %b, 0
7355 // brcond %c ...
7356 //
7357 // This applies only when the AND constant value has one bit set and the
7358 // SRL constant is equal to the log2 of the AND constant. The back-end is
7359 // smart enough to convert the result into a TEST/JMP sequence.
7360 SDValue Op0 = N1.getOperand(0);
7361 SDValue Op1 = N1.getOperand(1);
7362
7363 if (Op0.getOpcode() == ISD::AND &&
Bill Wendlingaa28be62009-03-26 06:14:09 +00007364 Op1.getOpcode() == ISD::Constant) {
Bill Wendlingaa28be62009-03-26 06:14:09 +00007365 SDValue AndOp1 = Op0.getOperand(1);
7366
7367 if (AndOp1.getOpcode() == ISD::Constant) {
7368 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7369
7370 if (AndConst.isPowerOf2() &&
7371 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7372 SDValue SetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00007373 DAG.getSetCC(SDLoc(N),
Matt Arsenault758659232013-05-18 00:21:46 +00007374 getSetCCResultType(Op0.getValueType()),
Bill Wendlingaa28be62009-03-26 06:14:09 +00007375 Op0, DAG.getConstant(0, Op0.getValueType()),
7376 ISD::SETNE);
7377
Andrew Trickef9de2a2013-05-25 02:42:55 +00007378 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng166a4e62010-01-06 19:38:29 +00007379 MVT::Other, Chain, SetCC, N2);
7380 // Don't add the new BRCond into the worklist or else SimplifySelectCC
7381 // will convert it back to (X & C1) >> C2.
7382 CombineTo(N, NewBRCond, false);
7383 // Truncate is dead.
7384 if (Trunc) {
7385 removeFromWorkList(Trunc);
7386 DAG.DeleteNode(Trunc);
7387 }
Bill Wendlingaa28be62009-03-26 06:14:09 +00007388 // Replace the uses of SRL with SETCC
Evan Cheng228c31f2010-02-27 07:36:59 +00007389 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007390 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
Bill Wendlingaa28be62009-03-26 06:14:09 +00007391 removeFromWorkList(N1.getNode());
7392 DAG.DeleteNode(N1.getNode());
Evan Cheng166a4e62010-01-06 19:38:29 +00007393 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Bill Wendlingaa28be62009-03-26 06:14:09 +00007394 }
7395 }
7396 }
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007397
7398 if (Trunc)
7399 // Restore N1 if the above transformation doesn't match.
7400 N1 = N->getOperand(1);
Bill Wendlingaa28be62009-03-26 06:14:09 +00007401 }
Wesley Peck527da1b2010-11-23 03:31:01 +00007402
Evan Cheng228c31f2010-02-27 07:36:59 +00007403 // Transform br(xor(x, y)) -> br(x != y)
7404 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7405 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7406 SDNode *TheXor = N1.getNode();
7407 SDValue Op0 = TheXor->getOperand(0);
7408 SDValue Op1 = TheXor->getOperand(1);
7409 if (Op0.getOpcode() == Op1.getOpcode()) {
7410 // Avoid missing important xor optimizations.
7411 SDValue Tmp = visitXOR(TheXor);
Evan Cheng5652a8d2013-01-09 20:56:40 +00007412 if (Tmp.getNode()) {
7413 if (Tmp.getNode() != TheXor) {
7414 DEBUG(dbgs() << "\nReplacing.8 ";
7415 TheXor->dump(&DAG);
7416 dbgs() << "\nWith: ";
7417 Tmp.getNode()->dump(&DAG);
7418 dbgs() << '\n');
7419 WorkListRemover DeadNodes(*this);
7420 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7421 removeFromWorkList(TheXor);
7422 DAG.DeleteNode(TheXor);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007423 return DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng5652a8d2013-01-09 20:56:40 +00007424 MVT::Other, Chain, Tmp, N2);
7425 }
7426
Benjamin Kramer93354432013-03-30 21:28:18 +00007427 // visitXOR has changed XOR's operands or replaced the XOR completely,
7428 // bail out.
7429 return SDValue(N, 0);
Evan Cheng228c31f2010-02-27 07:36:59 +00007430 }
7431 }
7432
7433 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7434 bool Equal = false;
7435 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7436 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7437 Op0.getOpcode() == ISD::XOR) {
7438 TheXor = Op0.getNode();
7439 Equal = true;
7440 }
7441
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007442 EVT SetCCVT = N1.getValueType();
Evan Cheng228c31f2010-02-27 07:36:59 +00007443 if (LegalTypes)
Matt Arsenault758659232013-05-18 00:21:46 +00007444 SetCCVT = getSetCCResultType(SetCCVT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007445 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
Evan Cheng228c31f2010-02-27 07:36:59 +00007446 SetCCVT,
7447 Op0, Op1,
7448 Equal ? ISD::SETEQ : ISD::SETNE);
7449 // Replace the uses of XOR with SETCC
7450 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007451 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007452 removeFromWorkList(N1.getNode());
7453 DAG.DeleteNode(N1.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00007454 return DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng228c31f2010-02-27 07:36:59 +00007455 MVT::Other, Chain, SetCC, N2);
7456 }
7457 }
Bill Wendlingaa28be62009-03-26 06:14:09 +00007458
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007459 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +00007460}
7461
Chris Lattnera49e16f2005-10-05 06:47:48 +00007462// Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7463//
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007464SDValue DAGCombiner::visitBR_CC(SDNode *N) {
Chris Lattnera49e16f2005-10-05 06:47:48 +00007465 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007466 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007467
Dan Gohman82e80012009-11-17 00:47:23 +00007468 // If N is a constant we could fold this into a fallthrough or unconditional
7469 // branch. However that doesn't happen very often in normal code, because
7470 // Instcombine/SimplifyCFG should have handled the available opportunities.
7471 // If we did this folding here, it would be necessary to update the
7472 // MachineBasicBlock CFG, which is awkward.
7473
Duncan Sands93b66092008-06-09 11:32:28 +00007474 // Use SimplifySetCC to simplify SETCC's.
Matt Arsenault758659232013-05-18 00:21:46 +00007475 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00007476 CondLHS, CondRHS, CC->get(), SDLoc(N),
Dale Johannesenf1163e92009-02-03 00:47:48 +00007477 false);
Gabor Greiff304a7a2008-08-28 21:40:38 +00007478 if (Simp.getNode()) AddToWorkList(Simp.getNode());
Chris Lattner6a1b2de2006-10-14 03:52:46 +00007479
Nate Begemanbd7df032005-10-05 21:43:42 +00007480 // fold to a simpler setcc
Gabor Greiff304a7a2008-08-28 21:40:38 +00007481 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007482 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
Bill Wendling306bfc22009-01-30 23:27:35 +00007483 N->getOperand(0), Simp.getOperand(2),
7484 Simp.getOperand(0), Simp.getOperand(1),
7485 N->getOperand(4));
7486
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007487 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +00007488}
7489
Evan Chengfa832632012-01-13 01:37:24 +00007490/// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7491/// uses N as its base pointer and that N may be folded in the load / store
Evan Cheng80893ce2012-03-06 23:33:32 +00007492/// addressing mode.
Evan Chengfa832632012-01-13 01:37:24 +00007493static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7494 SelectionDAG &DAG,
7495 const TargetLowering &TLI) {
7496 EVT VT;
7497 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
7498 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7499 return false;
7500 VT = Use->getValueType(0);
7501 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
7502 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7503 return false;
7504 VT = ST->getValue().getValueType();
7505 } else
7506 return false;
7507
Chandler Carruth95f83e02013-01-07 15:14:13 +00007508 TargetLowering::AddrMode AM;
Evan Chengfa832632012-01-13 01:37:24 +00007509 if (N->getOpcode() == ISD::ADD) {
7510 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7511 if (Offset)
Evan Cheng80893ce2012-03-06 23:33:32 +00007512 // [reg +/- imm]
Evan Chengfa832632012-01-13 01:37:24 +00007513 AM.BaseOffs = Offset->getSExtValue();
7514 else
Evan Cheng80893ce2012-03-06 23:33:32 +00007515 // [reg +/- reg]
7516 AM.Scale = 1;
Evan Chengfa832632012-01-13 01:37:24 +00007517 } else if (N->getOpcode() == ISD::SUB) {
7518 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7519 if (Offset)
Evan Cheng80893ce2012-03-06 23:33:32 +00007520 // [reg +/- imm]
Evan Chengfa832632012-01-13 01:37:24 +00007521 AM.BaseOffs = -Offset->getSExtValue();
7522 else
Evan Cheng80893ce2012-03-06 23:33:32 +00007523 // [reg +/- reg]
7524 AM.Scale = 1;
Evan Chengfa832632012-01-13 01:37:24 +00007525 } else
7526 return false;
7527
7528 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7529}
7530
Duncan Sands075293f2008-06-15 20:12:31 +00007531/// CombineToPreIndexedLoadStore - Try turning a load / store into a
7532/// pre-indexed load / store when the base pointer is an add or subtract
Chris Lattnerffad2162006-11-11 00:39:41 +00007533/// and it has other uses besides the load / store. After the
7534/// transformation, the new indexed load / store has effectively folded
7535/// the add / subtract in and all of its other uses are redirected to the
7536/// new load / store.
7537bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
Eli Friedman9d448e42011-11-12 00:35:34 +00007538 if (Level < AfterLegalizeDAG)
Chris Lattnerffad2162006-11-11 00:39:41 +00007539 return false;
7540
7541 bool isLoad = true;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007542 SDValue Ptr;
Owen Anderson53aa7a92009-08-10 22:56:29 +00007543 EVT VT;
Chris Lattnerffad2162006-11-11 00:39:41 +00007544 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007545 if (LD->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007546 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007547 VT = LD->getMemoryVT();
Evan Cheng8a1d09d2007-03-07 08:07:03 +00007548 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
Chris Lattnerffad2162006-11-11 00:39:41 +00007549 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7550 return false;
7551 Ptr = LD->getBasePtr();
7552 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007553 if (ST->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007554 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007555 VT = ST->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00007556 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7557 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7558 return false;
7559 Ptr = ST->getBasePtr();
7560 isLoad = false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007561 } else {
Chris Lattnerffad2162006-11-11 00:39:41 +00007562 return false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007563 }
Chris Lattnerffad2162006-11-11 00:39:41 +00007564
Chris Lattnereabc15c2006-11-11 00:56:29 +00007565 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7566 // out. There is no reason to make this a preinc/predec.
7567 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
Gabor Greiff304a7a2008-08-28 21:40:38 +00007568 Ptr.getNode()->hasOneUse())
Chris Lattnereabc15c2006-11-11 00:56:29 +00007569 return false;
Chris Lattnerffad2162006-11-11 00:39:41 +00007570
Chris Lattnereabc15c2006-11-11 00:56:29 +00007571 // Ask the target to do addressing mode selection.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007572 SDValue BasePtr;
7573 SDValue Offset;
Chris Lattnereabc15c2006-11-11 00:56:29 +00007574 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7575 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7576 return false;
Hal Finkel25819052013-02-08 21:35:47 +00007577
7578 // Backends without true r+i pre-indexed forms may need to pass a
7579 // constant base with a variable offset so that constant coercion
7580 // will work with the patterns in canonical form.
7581 bool Swapped = false;
7582 if (isa<ConstantSDNode>(BasePtr)) {
7583 std::swap(BasePtr, Offset);
7584 Swapped = true;
7585 }
7586
Evan Cheng044a0a82007-05-03 23:52:19 +00007587 // Don't create a indexed load / store with zero offset.
7588 if (isa<ConstantSDNode>(Offset) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00007589 cast<ConstantSDNode>(Offset)->isNullValue())
Evan Cheng044a0a82007-05-03 23:52:19 +00007590 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007591
Chris Lattnera0a80032006-11-11 01:00:15 +00007592 // Try turning it into a pre-indexed load / store except when:
Evan Chenga4d187b2007-05-24 02:35:39 +00007593 // 1) The new base ptr is a frame index.
7594 // 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 +00007595 // predecessor of the value being stored.
Evan Chenga4d187b2007-05-24 02:35:39 +00007596 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
Chris Lattnereabc15c2006-11-11 00:56:29 +00007597 // that would create a cycle.
Evan Chenga4d187b2007-05-24 02:35:39 +00007598 // 4) All uses are load / store ops that use it as old base ptr.
Chris Lattnerffad2162006-11-11 00:39:41 +00007599
Chris Lattnera0a80032006-11-11 01:00:15 +00007600 // Check #1. Preinc'ing a frame index would require copying the stack pointer
7601 // (plus the implicit offset) to a register to preinc anyway.
Evan Chengcfc05132009-05-06 18:25:01 +00007602 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
Chris Lattnera0a80032006-11-11 01:00:15 +00007603 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007604
Chris Lattnera0a80032006-11-11 01:00:15 +00007605 // Check #2.
Chris Lattnereabc15c2006-11-11 00:56:29 +00007606 if (!isLoad) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007607 SDValue Val = cast<StoreSDNode>(N)->getValue();
Gabor Greiff304a7a2008-08-28 21:40:38 +00007608 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
Chris Lattnereabc15c2006-11-11 00:56:29 +00007609 return false;
Chris Lattnerffad2162006-11-11 00:39:41 +00007610 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00007611
Hal Finkel25819052013-02-08 21:35:47 +00007612 // If the offset is a constant, there may be other adds of constants that
7613 // can be folded with this one. We should do this to avoid having to keep
7614 // a copy of the original base pointer.
7615 SmallVector<SDNode *, 16> OtherUses;
7616 if (isa<ConstantSDNode>(Offset))
Jim Grosbache8160032014-04-11 01:13:13 +00007617 for (SDNode *Use : BasePtr.getNode()->uses()) {
Hal Finkel25819052013-02-08 21:35:47 +00007618 if (Use == Ptr.getNode())
7619 continue;
7620
7621 if (Use->isPredecessorOf(N))
7622 continue;
7623
7624 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7625 OtherUses.clear();
7626 break;
7627 }
7628
7629 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7630 if (Op1.getNode() == BasePtr.getNode())
7631 std::swap(Op0, Op1);
7632 assert(Op0.getNode() == BasePtr.getNode() &&
7633 "Use of ADD/SUB but not an operand");
7634
7635 if (!isa<ConstantSDNode>(Op1)) {
7636 OtherUses.clear();
7637 break;
7638 }
7639
7640 // FIXME: In some cases, we can be smarter about this.
7641 if (Op1.getValueType() != Offset.getValueType()) {
7642 OtherUses.clear();
7643 break;
7644 }
7645
7646 OtherUses.push_back(Use);
7647 }
7648
7649 if (Swapped)
7650 std::swap(BasePtr, Offset);
7651
Evan Chenga4d187b2007-05-24 02:35:39 +00007652 // Now check for #3 and #4.
Chris Lattnereabc15c2006-11-11 00:56:29 +00007653 bool RealUse = false;
Lang Hames5a004992011-07-07 04:31:51 +00007654
7655 // Caches for hasPredecessorHelper
7656 SmallPtrSet<const SDNode *, 32> Visited;
7657 SmallVector<const SDNode *, 16> Worklist;
7658
Jim Grosbache8160032014-04-11 01:13:13 +00007659 for (SDNode *Use : Ptr.getNode()->uses()) {
Chris Lattnereabc15c2006-11-11 00:56:29 +00007660 if (Use == N)
7661 continue;
Lang Hames5a004992011-07-07 04:31:51 +00007662 if (N->hasPredecessorHelper(Use, Visited, Worklist))
Chris Lattnereabc15c2006-11-11 00:56:29 +00007663 return false;
7664
Evan Chengfa832632012-01-13 01:37:24 +00007665 // If Ptr may be folded in addressing mode of other use, then it's
7666 // not profitable to do this transformation.
7667 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
Chris Lattnereabc15c2006-11-11 00:56:29 +00007668 RealUse = true;
7669 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007670
Chris Lattnereabc15c2006-11-11 00:56:29 +00007671 if (!RealUse)
7672 return false;
7673
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007674 SDValue Result;
Chris Lattnereabc15c2006-11-11 00:56:29 +00007675 if (isLoad)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007676 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007677 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007678 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00007679 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007680 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007681 ++PreIndexedNodes;
7682 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +00007683 DEBUG(dbgs() << "\nReplacing.4 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007684 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007685 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007686 Result.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007687 dbgs() << '\n');
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +00007688 WorkListRemover DeadNodes(*this);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007689 if (isLoad) {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007690 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7691 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
Chris Lattnereabc15c2006-11-11 00:56:29 +00007692 } else {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007693 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
Chris Lattnereabc15c2006-11-11 00:56:29 +00007694 }
7695
Chris Lattnereabc15c2006-11-11 00:56:29 +00007696 // Finally, since the node is now dead, remove it from the graph.
7697 DAG.DeleteNode(N);
7698
Hal Finkel25819052013-02-08 21:35:47 +00007699 if (Swapped)
7700 std::swap(BasePtr, Offset);
7701
7702 // Replace other uses of BasePtr that can be updated to use Ptr
7703 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7704 unsigned OffsetIdx = 1;
7705 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7706 OffsetIdx = 0;
7707 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7708 BasePtr.getNode() && "Expected BasePtr operand");
7709
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007710 // We need to replace ptr0 in the following expression:
7711 // x0 * offset0 + y0 * ptr0 = t0
7712 // knowing that
7713 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
Stephen Lincfe7f352013-07-08 00:37:03 +00007714 //
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007715 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7716 // indexed load/store and the expresion that needs to be re-written.
7717 //
7718 // Therefore, we have:
7719 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
Hal Finkel25819052013-02-08 21:35:47 +00007720
7721 ConstantSDNode *CN =
7722 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007723 int X0, X1, Y0, Y1;
7724 APInt Offset0 = CN->getAPIntValue();
7725 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
Hal Finkel25819052013-02-08 21:35:47 +00007726
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007727 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7728 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7729 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7730 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
Hal Finkel25819052013-02-08 21:35:47 +00007731
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00007732 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7733
7734 APInt CNV = Offset0;
7735 if (X0 < 0) CNV = -CNV;
7736 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7737 else CNV = CNV - Offset1;
7738
7739 // We can now generate the new expression.
7740 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7741 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7742
7743 SDValue NewUse = DAG.getNode(Opcode,
Andrew Trickef9de2a2013-05-25 02:42:55 +00007744 SDLoc(OtherUses[i]),
Hal Finkel25819052013-02-08 21:35:47 +00007745 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7746 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7747 removeFromWorkList(OtherUses[i]);
7748 DAG.DeleteNode(OtherUses[i]);
7749 }
7750
Chris Lattnereabc15c2006-11-11 00:56:29 +00007751 // Replace the uses of Ptr with uses of the updated base value.
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007752 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
Gabor Greiff304a7a2008-08-28 21:40:38 +00007753 removeFromWorkList(Ptr.getNode());
7754 DAG.DeleteNode(Ptr.getNode());
Chris Lattnereabc15c2006-11-11 00:56:29 +00007755
7756 return true;
Chris Lattnerffad2162006-11-11 00:39:41 +00007757}
7758
Duncan Sands075293f2008-06-15 20:12:31 +00007759/// CombineToPostIndexedLoadStore - Try to combine a load / store with a
Chris Lattnerffad2162006-11-11 00:39:41 +00007760/// add / sub of the base pointer node into a post-indexed load / store.
7761/// The transformation folded the add / subtract into the new indexed
7762/// load / store effectively and all of its uses are redirected to the
7763/// new load / store.
7764bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
Eli Friedman9d448e42011-11-12 00:35:34 +00007765 if (Level < AfterLegalizeDAG)
Chris Lattnerffad2162006-11-11 00:39:41 +00007766 return false;
7767
7768 bool isLoad = true;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007769 SDValue Ptr;
Owen Anderson53aa7a92009-08-10 22:56:29 +00007770 EVT VT;
Chris Lattnerffad2162006-11-11 00:39:41 +00007771 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007772 if (LD->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007773 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007774 VT = LD->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00007775 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7776 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7777 return false;
7778 Ptr = LD->getBasePtr();
7779 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00007780 if (ST->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00007781 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00007782 VT = ST->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00007783 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7784 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7785 return false;
7786 Ptr = ST->getBasePtr();
7787 isLoad = false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007788 } else {
Chris Lattnerffad2162006-11-11 00:39:41 +00007789 return false;
Bill Wendling306bfc22009-01-30 23:27:35 +00007790 }
Chris Lattnerffad2162006-11-11 00:39:41 +00007791
Gabor Greiff304a7a2008-08-28 21:40:38 +00007792 if (Ptr.getNode()->hasOneUse())
Chris Lattnereabc15c2006-11-11 00:56:29 +00007793 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007794
Jim Grosbache8160032014-04-11 01:13:13 +00007795 for (SDNode *Op : Ptr.getNode()->uses()) {
Chris Lattnereabc15c2006-11-11 00:56:29 +00007796 if (Op == N ||
7797 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7798 continue;
7799
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007800 SDValue BasePtr;
7801 SDValue Offset;
Chris Lattnereabc15c2006-11-11 00:56:29 +00007802 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7803 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
Evan Cheng044a0a82007-05-03 23:52:19 +00007804 // Don't create a indexed load / store with zero offset.
7805 if (isa<ConstantSDNode>(Offset) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00007806 cast<ConstantSDNode>(Offset)->isNullValue())
Evan Cheng044a0a82007-05-03 23:52:19 +00007807 continue;
Chris Lattnerffad2162006-11-11 00:39:41 +00007808
Chris Lattnereabc15c2006-11-11 00:56:29 +00007809 // Try turning it into a post-indexed load / store except when
Evan Chengfa832632012-01-13 01:37:24 +00007810 // 1) All uses are load / store ops that use it as base ptr (and
7811 // it may be folded as addressing mmode).
Chris Lattnereabc15c2006-11-11 00:56:29 +00007812 // 2) Op must be independent of N, i.e. Op is neither a predecessor
7813 // nor a successor of N. Otherwise, if Op is folded that would
7814 // create a cycle.
7815
Evan Chengcfc05132009-05-06 18:25:01 +00007816 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7817 continue;
7818
Chris Lattnereabc15c2006-11-11 00:56:29 +00007819 // Check for #1.
7820 bool TryNext = false;
Jim Grosbache8160032014-04-11 01:13:13 +00007821 for (SDNode *Use : BasePtr.getNode()->uses()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00007822 if (Use == Ptr.getNode())
Chris Lattnerffad2162006-11-11 00:39:41 +00007823 continue;
7824
Chris Lattnereabc15c2006-11-11 00:56:29 +00007825 // If all the uses are load / store addresses, then don't do the
7826 // transformation.
7827 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7828 bool RealUse = false;
Jim Grosbache8160032014-04-11 01:13:13 +00007829 for (SDNode *UseUse : Use->uses()) {
Stephen Lincfe7f352013-07-08 00:37:03 +00007830 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
Chris Lattnereabc15c2006-11-11 00:56:29 +00007831 RealUse = true;
7832 }
Chris Lattnerffad2162006-11-11 00:39:41 +00007833
Chris Lattnereabc15c2006-11-11 00:56:29 +00007834 if (!RealUse) {
7835 TryNext = true;
7836 break;
Chris Lattnerffad2162006-11-11 00:39:41 +00007837 }
7838 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00007839 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007840
Chris Lattnereabc15c2006-11-11 00:56:29 +00007841 if (TryNext)
7842 continue;
Chris Lattnerffad2162006-11-11 00:39:41 +00007843
Chris Lattnereabc15c2006-11-11 00:56:29 +00007844 // Check for #2
Evan Cheng567d2e52008-03-04 00:41:45 +00007845 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007846 SDValue Result = isLoad
Andrew Trickef9de2a2013-05-25 02:42:55 +00007847 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007848 BasePtr, Offset, AM)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007849 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00007850 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007851 ++PostIndexedNodes;
7852 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +00007853 DEBUG(dbgs() << "\nReplacing.5 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007854 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007855 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007856 Result.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007857 dbgs() << '\n');
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +00007858 WorkListRemover DeadNodes(*this);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007859 if (isLoad) {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007860 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7861 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
Chris Lattnereabc15c2006-11-11 00:56:29 +00007862 } else {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007863 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
Chris Lattnerffad2162006-11-11 00:39:41 +00007864 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00007865
Chris Lattnereabc15c2006-11-11 00:56:29 +00007866 // Finally, since the node is now dead, remove it from the graph.
7867 DAG.DeleteNode(N);
7868
7869 // Replace the uses of Use with uses of the updated base value.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007870 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007871 Result.getValue(isLoad ? 1 : 0));
Chris Lattnereabc15c2006-11-11 00:56:29 +00007872 removeFromWorkList(Op);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007873 DAG.DeleteNode(Op);
Chris Lattnereabc15c2006-11-11 00:56:29 +00007874 return true;
Chris Lattnerffad2162006-11-11 00:39:41 +00007875 }
7876 }
7877 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007878
Chris Lattnerffad2162006-11-11 00:39:41 +00007879 return false;
7880}
7881
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007882SDValue DAGCombiner::visitLOAD(SDNode *N) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00007883 LoadSDNode *LD = cast<LoadSDNode>(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007884 SDValue Chain = LD->getChain();
7885 SDValue Ptr = LD->getBasePtr();
Scott Michelcf0da6c2009-02-17 22:15:04 +00007886
Evan Chenga684cd22007-05-01 00:38:21 +00007887 // If load is not volatile and there are no uses of the loaded value (and
7888 // the updated indexed value in case of indexed loads), change uses of the
7889 // chain value into uses of the chain input (i.e. delete the dead load).
7890 if (!LD->isVolatile()) {
Owen Anderson9f944592009-08-11 20:47:22 +00007891 if (N->getValueType(1) == MVT::Other) {
Evan Chengb68343c2007-05-01 08:53:39 +00007892 // Unindexed loads.
Craig Topper0515cd42012-01-07 18:31:09 +00007893 if (!N->hasAnyUseOfValue(0)) {
Evan Cheng7be15282008-01-16 23:11:54 +00007894 // It's not safe to use the two value CombineTo variant here. e.g.
7895 // v1, chain2 = load chain1, loc
7896 // v2, chain3 = load chain2, loc
7897 // v3 = add v2, c
Chris Lattnere97fa8c2008-01-24 07:57:06 +00007898 // Now we replace use of chain2 with chain1. This makes the second load
7899 // isomorphic to the one we are deleting, and thus makes this load live.
David Greenefe5c3522010-01-05 01:25:00 +00007900 DEBUG(dbgs() << "\nReplacing.6 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007901 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007902 dbgs() << "\nWith chain: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007903 Chain.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007904 dbgs() << "\n");
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +00007905 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007906 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
Bill Wendling306bfc22009-01-30 23:27:35 +00007907
Chris Lattnere97fa8c2008-01-24 07:57:06 +00007908 if (N->use_empty()) {
7909 removeFromWorkList(N);
7910 DAG.DeleteNode(N);
7911 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007912
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007913 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Cheng7be15282008-01-16 23:11:54 +00007914 }
Evan Chengb68343c2007-05-01 08:53:39 +00007915 } else {
7916 // Indexed loads.
Owen Anderson9f944592009-08-11 20:47:22 +00007917 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
Craig Topper0515cd42012-01-07 18:31:09 +00007918 if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
Dale Johannesen84935752009-02-06 23:05:02 +00007919 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
Evan Cheng228c31f2010-02-27 07:36:59 +00007920 DEBUG(dbgs() << "\nReplacing.7 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007921 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007922 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00007923 Undef.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00007924 dbgs() << " and 2 other values\n");
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +00007925 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007926 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007927 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007928 DAG.getUNDEF(N->getValueType(1)));
7929 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
Evan Cheng7be15282008-01-16 23:11:54 +00007930 removeFromWorkList(N);
Evan Cheng7be15282008-01-16 23:11:54 +00007931 DAG.DeleteNode(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007932 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga684cd22007-05-01 00:38:21 +00007933 }
Evan Chenga684cd22007-05-01 00:38:21 +00007934 }
7935 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007936
Chris Lattnere260ed82005-10-10 22:04:48 +00007937 // If this load is directly stored, replace the load value with the stored
7938 // value.
7939 // TODO: Handle store large -> read small portion.
Jim Laskey0f7c3282006-10-11 17:47:52 +00007940 // TODO: Handle TRUNCSTORE/LOADEXT
Evan Chengadb9c032011-03-11 00:48:56 +00007941 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00007942 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
Evan Chengab51cf22006-10-13 21:14:26 +00007943 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
7944 if (PrevST->getBasePtr() == Ptr &&
7945 PrevST->getValue().getValueType() == N->getValueType(0))
Jim Laskey0f7c3282006-10-11 17:47:52 +00007946 return CombineTo(N, Chain.getOperand(1), Chain);
Evan Chengab51cf22006-10-13 21:14:26 +00007947 }
Jim Laskey0f7c3282006-10-11 17:47:52 +00007948 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007949
Evan Cheng43cd9e32010-04-01 06:04:33 +00007950 // Try to infer better alignment information than the load already has.
7951 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
Evan Cheng4a5b2042011-11-28 22:37:34 +00007952 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
Owen Andersonde89ecf2013-02-05 19:24:39 +00007953 if (Align > LD->getMemOperand()->getBaseAlignment()) {
7954 SDValue NewLoad =
Andrew Trickef9de2a2013-05-25 02:42:55 +00007955 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
Evan Cheng4a5b2042011-11-28 22:37:34 +00007956 LD->getValueType(0),
7957 Chain, Ptr, LD->getPointerInfo(),
7958 LD->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00007959 LD->isVolatile(), LD->isNonTemporal(), Align,
7960 LD->getTBAAInfo());
Owen Andersonde89ecf2013-02-05 19:24:39 +00007961 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
7962 }
Evan Cheng43cd9e32010-04-01 06:04:33 +00007963 }
7964 }
7965
Hal Finkel5ef4dcc2013-08-29 03:29:55 +00007966 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
7967 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +00007968#ifndef NDEBUG
7969 if (CombinerAAOnlyFunc.getNumOccurrences() &&
7970 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
7971 UseAA = false;
7972#endif
Hal Finkelccc18e12014-01-24 18:25:26 +00007973 if (UseAA && LD->isUnindexed()) {
Jim Laskeyd07be232006-09-25 16:29:54 +00007974 // Walk up chain skipping non-aliasing memory nodes.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007975 SDValue BetterChain = FindBetterChain(N, Chain);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007976
Jim Laskey708d0db2006-10-04 16:53:27 +00007977 // If there is a better chain.
Jim Laskeyd07be232006-09-25 16:29:54 +00007978 if (Chain != BetterChain) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007979 SDValue ReplLoad;
Jim Laskey0f7c3282006-10-11 17:47:52 +00007980
Jim Laskeyd07be232006-09-25 16:29:54 +00007981 // Replace the chain to void dependency.
Jim Laskey0f7c3282006-10-11 17:47:52 +00007982 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007983 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00007984 BetterChain, Ptr, LD->getMemOperand());
Jim Laskey0f7c3282006-10-11 17:47:52 +00007985 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007986 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
Stuart Hastings81c43062011-02-16 16:23:55 +00007987 LD->getValueType(0),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00007988 BetterChain, Ptr, LD->getMemoryVT(),
7989 LD->getMemOperand());
Jim Laskey0f7c3282006-10-11 17:47:52 +00007990 }
Jim Laskeyd07be232006-09-25 16:29:54 +00007991
Jim Laskey708d0db2006-10-04 16:53:27 +00007992 // Create token factor to keep old chain connected.
Andrew Trickef9de2a2013-05-25 02:42:55 +00007993 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
Owen Anderson9f944592009-08-11 20:47:22 +00007994 MVT::Other, Chain, ReplLoad.getValue(1));
Wesley Peck527da1b2010-11-23 03:31:01 +00007995
Nate Begeman879d8f12009-09-15 00:18:30 +00007996 // Make sure the new and old chains are cleaned up.
7997 AddToWorkList(Token.getNode());
Wesley Peck527da1b2010-11-23 03:31:01 +00007998
Jim Laskeydcf983c2006-10-13 23:32:28 +00007999 // Replace uses with load result and token factor. Don't add users
8000 // to work list.
8001 return CombineTo(N, ReplLoad.getValue(0), Token, false);
Jim Laskeyd07be232006-09-25 16:29:54 +00008002 }
8003 }
8004
Evan Cheng357017f2006-11-03 03:06:21 +00008005 // Try transforming N to an indexed load.
Evan Cheng60c68462006-11-07 09:03:05 +00008006 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008007 return SDValue(N, 0);
Evan Cheng357017f2006-11-03 03:06:21 +00008008
Quentin Colombetde0e0622013-10-11 18:29:42 +00008009 // Try to slice up N to more direct loads if the slices are mapped to
8010 // different register banks or pairing can take place.
8011 if (SliceUpLoad(N))
8012 return SDValue(N, 0);
8013
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008014 return SDValue();
Chris Lattnere260ed82005-10-10 22:04:48 +00008015}
8016
Quentin Colombetde0e0622013-10-11 18:29:42 +00008017namespace {
8018/// \brief Helper structure used to slice a load in smaller loads.
8019/// Basically a slice is obtained from the following sequence:
8020/// Origin = load Ty1, Base
8021/// Shift = srl Ty1 Origin, CstTy Amount
8022/// Inst = trunc Shift to Ty2
8023///
8024/// Then, it will be rewriten into:
8025/// Slice = load SliceTy, Base + SliceOffset
8026/// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8027///
8028/// SliceTy is deduced from the number of bits that are actually used to
8029/// build Inst.
8030struct LoadedSlice {
8031 /// \brief Helper structure used to compute the cost of a slice.
8032 struct Cost {
8033 /// Are we optimizing for code size.
8034 bool ForCodeSize;
8035 /// Various cost.
8036 unsigned Loads;
8037 unsigned Truncates;
8038 unsigned CrossRegisterBanksCopies;
8039 unsigned ZExts;
8040 unsigned Shift;
8041
8042 Cost(bool ForCodeSize = false)
8043 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8044 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8045
8046 /// \brief Get the cost of one isolated slice.
8047 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8048 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8049 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8050 EVT TruncType = LS.Inst->getValueType(0);
8051 EVT LoadedType = LS.getLoadedType();
8052 if (TruncType != LoadedType &&
8053 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8054 ZExts = 1;
8055 }
8056
8057 /// \brief Account for slicing gain in the current cost.
8058 /// Slicing provide a few gains like removing a shift or a
8059 /// truncate. This method allows to grow the cost of the original
8060 /// load with the gain from this slice.
8061 void addSliceGain(const LoadedSlice &LS) {
8062 // Each slice saves a truncate.
8063 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8064 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8065 LS.Inst->getOperand(0).getValueType()))
8066 ++Truncates;
8067 // If there is a shift amount, this slice gets rid of it.
8068 if (LS.Shift)
8069 ++Shift;
8070 // If this slice can merge a cross register bank copy, account for it.
8071 if (LS.canMergeExpensiveCrossRegisterBankCopy())
8072 ++CrossRegisterBanksCopies;
8073 }
8074
8075 Cost &operator+=(const Cost &RHS) {
8076 Loads += RHS.Loads;
8077 Truncates += RHS.Truncates;
8078 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8079 ZExts += RHS.ZExts;
8080 Shift += RHS.Shift;
8081 return *this;
8082 }
8083
8084 bool operator==(const Cost &RHS) const {
8085 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8086 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8087 ZExts == RHS.ZExts && Shift == RHS.Shift;
8088 }
8089
8090 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8091
8092 bool operator<(const Cost &RHS) const {
8093 // Assume cross register banks copies are as expensive as loads.
8094 // FIXME: Do we want some more target hooks?
8095 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8096 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8097 // Unless we are optimizing for code size, consider the
8098 // expensive operation first.
8099 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8100 return ExpensiveOpsLHS < ExpensiveOpsRHS;
8101 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8102 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8103 }
8104
8105 bool operator>(const Cost &RHS) const { return RHS < *this; }
8106
8107 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8108
8109 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8110 };
8111 // The last instruction that represent the slice. This should be a
8112 // truncate instruction.
8113 SDNode *Inst;
8114 // The original load instruction.
8115 LoadSDNode *Origin;
8116 // The right shift amount in bits from the original load.
8117 unsigned Shift;
8118 // The DAG from which Origin came from.
8119 // This is used to get some contextual information about legal types, etc.
8120 SelectionDAG *DAG;
8121
Craig Topperc0196b12014-04-14 00:51:57 +00008122 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8123 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
Quentin Colombetde0e0622013-10-11 18:29:42 +00008124 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8125
8126 LoadedSlice(const LoadedSlice &LS)
8127 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8128
8129 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8130 /// \return Result is \p BitWidth and has used bits set to 1 and
8131 /// not used bits set to 0.
8132 APInt getUsedBits() const {
8133 // Reproduce the trunc(lshr) sequence:
8134 // - Start from the truncated value.
8135 // - Zero extend to the desired bit width.
8136 // - Shift left.
8137 assert(Origin && "No original load to compare against.");
8138 unsigned BitWidth = Origin->getValueSizeInBits(0);
8139 assert(Inst && "This slice is not bound to an instruction");
8140 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8141 "Extracted slice is bigger than the whole type!");
8142 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8143 UsedBits.setAllBits();
8144 UsedBits = UsedBits.zext(BitWidth);
8145 UsedBits <<= Shift;
8146 return UsedBits;
8147 }
8148
8149 /// \brief Get the size of the slice to be loaded in bytes.
8150 unsigned getLoadedSize() const {
8151 unsigned SliceSize = getUsedBits().countPopulation();
8152 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8153 return SliceSize / 8;
8154 }
8155
8156 /// \brief Get the type that will be loaded for this slice.
8157 /// Note: This may not be the final type for the slice.
8158 EVT getLoadedType() const {
8159 assert(DAG && "Missing context");
8160 LLVMContext &Ctxt = *DAG->getContext();
8161 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8162 }
8163
8164 /// \brief Get the alignment of the load used for this slice.
8165 unsigned getAlignment() const {
8166 unsigned Alignment = Origin->getAlignment();
8167 unsigned Offset = getOffsetFromBase();
8168 if (Offset != 0)
8169 Alignment = MinAlign(Alignment, Alignment + Offset);
8170 return Alignment;
8171 }
8172
8173 /// \brief Check if this slice can be rewritten with legal operations.
8174 bool isLegal() const {
8175 // An invalid slice is not legal.
8176 if (!Origin || !Inst || !DAG)
8177 return false;
8178
8179 // Offsets are for indexed load only, we do not handle that.
8180 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8181 return false;
8182
8183 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8184
8185 // Check that the type is legal.
8186 EVT SliceType = getLoadedType();
8187 if (!TLI.isTypeLegal(SliceType))
8188 return false;
8189
8190 // Check that the load is legal for this type.
8191 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8192 return false;
8193
8194 // Check that the offset can be computed.
8195 // 1. Check its type.
8196 EVT PtrType = Origin->getBasePtr().getValueType();
8197 if (PtrType == MVT::Untyped || PtrType.isExtended())
8198 return false;
8199
8200 // 2. Check that it fits in the immediate.
8201 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8202 return false;
8203
8204 // 3. Check that the computation is legal.
8205 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8206 return false;
8207
8208 // Check that the zext is legal if it needs one.
8209 EVT TruncateType = Inst->getValueType(0);
8210 if (TruncateType != SliceType &&
8211 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8212 return false;
8213
8214 return true;
8215 }
8216
8217 /// \brief Get the offset in bytes of this slice in the original chunk of
8218 /// bits.
Craig Topperc0196b12014-04-14 00:51:57 +00008219 /// \pre DAG != nullptr.
Quentin Colombetde0e0622013-10-11 18:29:42 +00008220 uint64_t getOffsetFromBase() const {
8221 assert(DAG && "Missing context.");
8222 bool IsBigEndian =
8223 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8224 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8225 uint64_t Offset = Shift / 8;
8226 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8227 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8228 "The size of the original loaded type is not a multiple of a"
8229 " byte.");
8230 // If Offset is bigger than TySizeInBytes, it means we are loading all
8231 // zeros. This should have been optimized before in the process.
8232 assert(TySizeInBytes > Offset &&
8233 "Invalid shift amount for given loaded size");
8234 if (IsBigEndian)
8235 Offset = TySizeInBytes - Offset - getLoadedSize();
8236 return Offset;
8237 }
8238
8239 /// \brief Generate the sequence of instructions to load the slice
8240 /// represented by this object and redirect the uses of this slice to
8241 /// this new sequence of instructions.
8242 /// \pre this->Inst && this->Origin are valid Instructions and this
8243 /// object passed the legal check: LoadedSlice::isLegal returned true.
8244 /// \return The last instruction of the sequence used to load the slice.
8245 SDValue loadSlice() const {
8246 assert(Inst && Origin && "Unable to replace a non-existing slice.");
8247 const SDValue &OldBaseAddr = Origin->getBasePtr();
8248 SDValue BaseAddr = OldBaseAddr;
8249 // Get the offset in that chunk of bytes w.r.t. the endianess.
8250 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8251 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8252 if (Offset) {
8253 // BaseAddr = BaseAddr + Offset.
8254 EVT ArithType = BaseAddr.getValueType();
8255 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8256 DAG->getConstant(Offset, ArithType));
8257 }
8258
8259 // Create the type of the loaded slice according to its size.
8260 EVT SliceType = getLoadedType();
8261
8262 // Create the load for the slice.
8263 SDValue LastInst = DAG->getLoad(
8264 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8265 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8266 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8267 // If the final type is not the same as the loaded type, this means that
8268 // we have to pad with zero. Create a zero extend for that.
8269 EVT FinalType = Inst->getValueType(0);
8270 if (SliceType != FinalType)
8271 LastInst =
8272 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8273 return LastInst;
8274 }
8275
8276 /// \brief Check if this slice can be merged with an expensive cross register
8277 /// bank copy. E.g.,
8278 /// i = load i32
8279 /// f = bitcast i32 i to float
8280 bool canMergeExpensiveCrossRegisterBankCopy() const {
8281 if (!Inst || !Inst->hasOneUse())
8282 return false;
8283 SDNode *Use = *Inst->use_begin();
8284 if (Use->getOpcode() != ISD::BITCAST)
8285 return false;
8286 assert(DAG && "Missing context");
8287 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8288 EVT ResVT = Use->getValueType(0);
8289 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8290 const TargetRegisterClass *ArgRC =
8291 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8292 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8293 return false;
8294
8295 // At this point, we know that we perform a cross-register-bank copy.
8296 // Check if it is expensive.
8297 const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo();
8298 // Assume bitcasts are cheap, unless both register classes do not
8299 // explicitly share a common sub class.
8300 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8301 return false;
8302
8303 // Check if it will be merged with the load.
8304 // 1. Check the alignment constraint.
8305 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8306 ResVT.getTypeForEVT(*DAG->getContext()));
8307
8308 if (RequiredAlignment > getAlignment())
8309 return false;
8310
8311 // 2. Check that the load is a legal operation for that type.
8312 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8313 return false;
8314
8315 // 3. Check that we do not have a zext in the way.
8316 if (Inst->getValueType(0) != getLoadedType())
8317 return false;
8318
8319 return true;
8320 }
8321};
8322}
8323
Quentin Colombetde0e0622013-10-11 18:29:42 +00008324/// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8325/// \p UsedBits looks like 0..0 1..1 0..0.
8326static bool areUsedBitsDense(const APInt &UsedBits) {
8327 // If all the bits are one, this is dense!
8328 if (UsedBits.isAllOnesValue())
8329 return true;
8330
8331 // Get rid of the unused bits on the right.
8332 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8333 // Get rid of the unused bits on the left.
8334 if (NarrowedUsedBits.countLeadingZeros())
8335 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8336 // Check that the chunk of bits is completely used.
8337 return NarrowedUsedBits.isAllOnesValue();
8338}
8339
8340/// \brief Check whether or not \p First and \p Second are next to each other
8341/// in memory. This means that there is no hole between the bits loaded
8342/// by \p First and the bits loaded by \p Second.
8343static bool areSlicesNextToEachOther(const LoadedSlice &First,
8344 const LoadedSlice &Second) {
8345 assert(First.Origin == Second.Origin && First.Origin &&
8346 "Unable to match different memory origins.");
8347 APInt UsedBits = First.getUsedBits();
8348 assert((UsedBits & Second.getUsedBits()) == 0 &&
8349 "Slices are not supposed to overlap.");
8350 UsedBits |= Second.getUsedBits();
8351 return areUsedBitsDense(UsedBits);
8352}
8353
8354/// \brief Adjust the \p GlobalLSCost according to the target
8355/// paring capabilities and the layout of the slices.
8356/// \pre \p GlobalLSCost should account for at least as many loads as
8357/// there is in the slices in \p LoadedSlices.
8358static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8359 LoadedSlice::Cost &GlobalLSCost) {
8360 unsigned NumberOfSlices = LoadedSlices.size();
8361 // If there is less than 2 elements, no pairing is possible.
8362 if (NumberOfSlices < 2)
8363 return;
8364
8365 // Sort the slices so that elements that are likely to be next to each
8366 // other in memory are next to each other in the list.
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00008367 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8368 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8369 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8370 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8371 });
Quentin Colombetde0e0622013-10-11 18:29:42 +00008372 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8373 // First (resp. Second) is the first (resp. Second) potentially candidate
8374 // to be placed in a paired load.
Craig Topperc0196b12014-04-14 00:51:57 +00008375 const LoadedSlice *First = nullptr;
8376 const LoadedSlice *Second = nullptr;
Quentin Colombetde0e0622013-10-11 18:29:42 +00008377 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8378 // Set the beginning of the pair.
8379 First = Second) {
8380
8381 Second = &LoadedSlices[CurrSlice];
8382
8383 // If First is NULL, it means we start a new pair.
8384 // Get to the next slice.
8385 if (!First)
8386 continue;
8387
8388 EVT LoadedType = First->getLoadedType();
8389
8390 // If the types of the slices are different, we cannot pair them.
8391 if (LoadedType != Second->getLoadedType())
8392 continue;
8393
8394 // Check if the target supplies paired loads for this type.
8395 unsigned RequiredAlignment = 0;
8396 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8397 // move to the next pair, this type is hopeless.
Craig Topperc0196b12014-04-14 00:51:57 +00008398 Second = nullptr;
Quentin Colombetde0e0622013-10-11 18:29:42 +00008399 continue;
8400 }
8401 // Check if we meet the alignment requirement.
8402 if (RequiredAlignment > First->getAlignment())
8403 continue;
8404
8405 // Check that both loads are next to each other in memory.
8406 if (!areSlicesNextToEachOther(*First, *Second))
8407 continue;
8408
8409 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8410 --GlobalLSCost.Loads;
8411 // Move to the next pair.
Craig Topperc0196b12014-04-14 00:51:57 +00008412 Second = nullptr;
Quentin Colombetde0e0622013-10-11 18:29:42 +00008413 }
8414}
8415
8416/// \brief Check the profitability of all involved LoadedSlice.
8417/// Currently, it is considered profitable if there is exactly two
8418/// involved slices (1) which are (2) next to each other in memory, and
8419/// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8420///
8421/// Note: The order of the elements in \p LoadedSlices may be modified, but not
8422/// the elements themselves.
8423///
8424/// FIXME: When the cost model will be mature enough, we can relax
8425/// constraints (1) and (2).
8426static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8427 const APInt &UsedBits, bool ForCodeSize) {
8428 unsigned NumberOfSlices = LoadedSlices.size();
8429 if (StressLoadSlicing)
8430 return NumberOfSlices > 1;
8431
8432 // Check (1).
8433 if (NumberOfSlices != 2)
8434 return false;
8435
8436 // Check (2).
8437 if (!areUsedBitsDense(UsedBits))
8438 return false;
8439
8440 // Check (3).
8441 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8442 // The original code has one big load.
8443 OrigCost.Loads = 1;
8444 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8445 const LoadedSlice &LS = LoadedSlices[CurrSlice];
8446 // Accumulate the cost of all the slices.
8447 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8448 GlobalSlicingCost += SliceCost;
8449
8450 // Account as cost in the original configuration the gain obtained
8451 // with the current slices.
8452 OrigCost.addSliceGain(LS);
8453 }
8454
8455 // If the target supports paired load, adjust the cost accordingly.
8456 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8457 return OrigCost > GlobalSlicingCost;
8458}
8459
8460/// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8461/// operations, split it in the various pieces being extracted.
8462///
8463/// This sort of thing is introduced by SROA.
8464/// This slicing takes care not to insert overlapping loads.
8465/// \pre LI is a simple load (i.e., not an atomic or volatile load).
8466bool DAGCombiner::SliceUpLoad(SDNode *N) {
8467 if (Level < AfterLegalizeDAG)
8468 return false;
8469
8470 LoadSDNode *LD = cast<LoadSDNode>(N);
8471 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8472 !LD->getValueType(0).isInteger())
8473 return false;
8474
8475 // Keep track of already used bits to detect overlapping values.
8476 // In that case, we will just abort the transformation.
8477 APInt UsedBits(LD->getValueSizeInBits(0), 0);
8478
8479 SmallVector<LoadedSlice, 4> LoadedSlices;
8480
8481 // Check if this load is used as several smaller chunks of bits.
8482 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8483 // of computation for each trunc.
8484 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8485 UI != UIEnd; ++UI) {
8486 // Skip the uses of the chain.
8487 if (UI.getUse().getResNo() != 0)
8488 continue;
8489
8490 SDNode *User = *UI;
8491 unsigned Shift = 0;
8492
8493 // Check if this is a trunc(lshr).
8494 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8495 isa<ConstantSDNode>(User->getOperand(1))) {
8496 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8497 User = *User->use_begin();
8498 }
8499
8500 // At this point, User is a Truncate, iff we encountered, trunc or
8501 // trunc(lshr).
8502 if (User->getOpcode() != ISD::TRUNCATE)
8503 return false;
8504
8505 // The width of the type must be a power of 2 and greater than 8-bits.
8506 // Otherwise the load cannot be represented in LLVM IR.
Alp Tokerf907b892013-12-05 05:44:44 +00008507 // Moreover, if we shifted with a non-8-bits multiple, the slice
Alp Tokercb402912014-01-24 17:20:08 +00008508 // will be across several bytes. We do not support that.
Quentin Colombetde0e0622013-10-11 18:29:42 +00008509 unsigned Width = User->getValueSizeInBits(0);
8510 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8511 return 0;
8512
8513 // Build the slice for this chain of computations.
8514 LoadedSlice LS(User, LD, Shift, &DAG);
8515 APInt CurrentUsedBits = LS.getUsedBits();
8516
8517 // Check if this slice overlaps with another.
8518 if ((CurrentUsedBits & UsedBits) != 0)
8519 return false;
8520 // Update the bits used globally.
8521 UsedBits |= CurrentUsedBits;
8522
8523 // Check if the new slice would be legal.
8524 if (!LS.isLegal())
8525 return false;
8526
8527 // Record the slice.
8528 LoadedSlices.push_back(LS);
8529 }
8530
8531 // Abort slicing if it does not seem to be profitable.
8532 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8533 return false;
8534
8535 ++SlicedLoads;
8536
8537 // Rewrite each chain to use an independent load.
8538 // By construction, each chain can be represented by a unique load.
8539
8540 // Prepare the argument for the new token factor for all the slices.
8541 SmallVector<SDValue, 8> ArgChains;
8542 for (SmallVectorImpl<LoadedSlice>::const_iterator
8543 LSIt = LoadedSlices.begin(),
8544 LSItEnd = LoadedSlices.end();
8545 LSIt != LSItEnd; ++LSIt) {
8546 SDValue SliceInst = LSIt->loadSlice();
8547 CombineTo(LSIt->Inst, SliceInst, true);
8548 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8549 SliceInst = SliceInst.getOperand(0);
8550 assert(SliceInst->getOpcode() == ISD::LOAD &&
8551 "It takes more than a zext to get to the loaded slice!!");
8552 ArgChains.push_back(SliceInst.getValue(1));
8553 }
8554
8555 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8556 &ArgChains[0], ArgChains.size());
8557 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8558 return true;
8559}
8560
Chris Lattner4041ab62010-04-15 04:48:01 +00008561/// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8562/// load is having specific bytes cleared out. If so, return the byte size
8563/// being masked out and the shift amount.
8564static std::pair<unsigned, unsigned>
8565CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8566 std::pair<unsigned, unsigned> Result(0, 0);
Wesley Peck527da1b2010-11-23 03:31:01 +00008567
Chris Lattner4041ab62010-04-15 04:48:01 +00008568 // Check for the structure we're looking for.
8569 if (V->getOpcode() != ISD::AND ||
8570 !isa<ConstantSDNode>(V->getOperand(1)) ||
8571 !ISD::isNormalLoad(V->getOperand(0).getNode()))
8572 return Result;
Wesley Peck527da1b2010-11-23 03:31:01 +00008573
Chris Lattner3245afd2010-04-15 06:10:49 +00008574 // Check the chain and pointer.
Chris Lattner4041ab62010-04-15 04:48:01 +00008575 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
Chris Lattner3245afd2010-04-15 06:10:49 +00008576 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
Wesley Peck527da1b2010-11-23 03:31:01 +00008577
Chris Lattner3245afd2010-04-15 06:10:49 +00008578 // The store should be chained directly to the load or be an operand of a
8579 // tokenfactor.
8580 if (LD == Chain.getNode())
8581 ; // ok.
8582 else if (Chain->getOpcode() != ISD::TokenFactor)
8583 return Result; // Fail.
8584 else {
8585 bool isOk = false;
8586 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8587 if (Chain->getOperand(i).getNode() == LD) {
8588 isOk = true;
8589 break;
8590 }
8591 if (!isOk) return Result;
8592 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008593
Chris Lattner4041ab62010-04-15 04:48:01 +00008594 // This only handles simple types.
8595 if (V.getValueType() != MVT::i16 &&
8596 V.getValueType() != MVT::i32 &&
8597 V.getValueType() != MVT::i64)
8598 return Result;
8599
8600 // Check the constant mask. Invert it so that the bits being masked out are
8601 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
8602 // follow the sign bit for uniformity.
8603 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00008604 unsigned NotMaskLZ = countLeadingZeros(NotMask);
Chris Lattner4041ab62010-04-15 04:48:01 +00008605 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00008606 unsigned NotMaskTZ = countTrailingZeros(NotMask);
Chris Lattner4041ab62010-04-15 04:48:01 +00008607 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
8608 if (NotMaskLZ == 64) return Result; // All zero mask.
Wesley Peck527da1b2010-11-23 03:31:01 +00008609
Chris Lattner4041ab62010-04-15 04:48:01 +00008610 // See if we have a continuous run of bits. If so, we have 0*1+0*
8611 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8612 return Result;
8613
8614 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8615 if (V.getValueType() != MVT::i64 && NotMaskLZ)
8616 NotMaskLZ -= 64-V.getValueSizeInBits();
Wesley Peck527da1b2010-11-23 03:31:01 +00008617
Chris Lattner4041ab62010-04-15 04:48:01 +00008618 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8619 switch (MaskedBytes) {
Wesley Peck527da1b2010-11-23 03:31:01 +00008620 case 1:
8621 case 2:
Chris Lattner4041ab62010-04-15 04:48:01 +00008622 case 4: break;
8623 default: return Result; // All one mask, or 5-byte mask.
8624 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008625
Chris Lattner4041ab62010-04-15 04:48:01 +00008626 // Verify that the first bit starts at a multiple of mask so that the access
8627 // is aligned the same as the access width.
8628 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
Wesley Peck527da1b2010-11-23 03:31:01 +00008629
Chris Lattner4041ab62010-04-15 04:48:01 +00008630 Result.first = MaskedBytes;
8631 Result.second = NotMaskTZ/8;
8632 return Result;
8633}
8634
8635
8636/// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8637/// provides a value as specified by MaskInfo. If so, replace the specified
8638/// store with a narrower store of truncated IVal.
8639static SDNode *
8640ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8641 SDValue IVal, StoreSDNode *St,
8642 DAGCombiner *DC) {
8643 unsigned NumBytes = MaskInfo.first;
8644 unsigned ByteShift = MaskInfo.second;
8645 SelectionDAG &DAG = DC->getDAG();
Wesley Peck527da1b2010-11-23 03:31:01 +00008646
Chris Lattner4041ab62010-04-15 04:48:01 +00008647 // Check to see if IVal is all zeros in the part being masked in by the 'or'
8648 // that uses this. If not, this is not a replacement.
8649 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8650 ByteShift*8, (ByteShift+NumBytes)*8);
Craig Topperc0196b12014-04-14 00:51:57 +00008651 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
Wesley Peck527da1b2010-11-23 03:31:01 +00008652
Chris Lattner4041ab62010-04-15 04:48:01 +00008653 // Check that it is legal on the target to do this. It is legal if the new
8654 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8655 // legalization.
8656 MVT VT = MVT::getIntegerVT(NumBytes*8);
8657 if (!DC->isTypeLegal(VT))
Craig Topperc0196b12014-04-14 00:51:57 +00008658 return nullptr;
Wesley Peck527da1b2010-11-23 03:31:01 +00008659
Chris Lattner4041ab62010-04-15 04:48:01 +00008660 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
8661 // shifted by ByteShift and truncated down to NumBytes.
8662 if (ByteShift)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008663 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
Owen Andersonb2c80da2011-02-25 21:41:48 +00008664 DAG.getConstant(ByteShift*8,
8665 DC->getShiftAmountTy(IVal.getValueType())));
Chris Lattner4041ab62010-04-15 04:48:01 +00008666
8667 // Figure out the offset for the store and the alignment of the access.
8668 unsigned StOffset;
8669 unsigned NewAlign = St->getAlignment();
8670
8671 if (DAG.getTargetLoweringInfo().isLittleEndian())
8672 StOffset = ByteShift;
8673 else
8674 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
Wesley Peck527da1b2010-11-23 03:31:01 +00008675
Chris Lattner4041ab62010-04-15 04:48:01 +00008676 SDValue Ptr = St->getBasePtr();
8677 if (StOffset) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00008678 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
Chris Lattner4041ab62010-04-15 04:48:01 +00008679 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8680 NewAlign = MinAlign(NewAlign, StOffset);
8681 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008682
Chris Lattner4041ab62010-04-15 04:48:01 +00008683 // Truncate down to the new size.
Andrew Trickef9de2a2013-05-25 02:42:55 +00008684 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
Wesley Peck527da1b2010-11-23 03:31:01 +00008685
Chris Lattner4041ab62010-04-15 04:48:01 +00008686 ++OpsNarrowed;
Andrew Trickef9de2a2013-05-25 02:42:55 +00008687 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
Chris Lattner676c61d2010-09-21 18:41:36 +00008688 St->getPointerInfo().getWithOffset(StOffset),
Chris Lattner4041ab62010-04-15 04:48:01 +00008689 false, false, NewAlign).getNode();
8690}
8691
Evan Chenga9cda8a2009-05-28 00:35:15 +00008692
8693/// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8694/// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8695/// of the loaded bits, try narrowing the load and store if it would end up
8696/// being a win for performance or code size.
8697SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8698 StoreSDNode *ST = cast<StoreSDNode>(N);
Evan Cheng6673ff02009-05-28 18:41:02 +00008699 if (ST->isVolatile())
8700 return SDValue();
8701
Evan Chenga9cda8a2009-05-28 00:35:15 +00008702 SDValue Chain = ST->getChain();
8703 SDValue Value = ST->getValue();
8704 SDValue Ptr = ST->getBasePtr();
Owen Anderson53aa7a92009-08-10 22:56:29 +00008705 EVT VT = Value.getValueType();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008706
8707 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
Evan Cheng6673ff02009-05-28 18:41:02 +00008708 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008709
8710 unsigned Opc = Value.getOpcode();
Wesley Peck527da1b2010-11-23 03:31:01 +00008711
Chris Lattner4041ab62010-04-15 04:48:01 +00008712 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8713 // is a byte mask indicating a consecutive number of bytes, check to see if
8714 // Y is known to provide just those bytes. If so, we try to replace the
8715 // load + replace + store sequence with a single (narrower) store, which makes
8716 // the load dead.
8717 if (Opc == ISD::OR) {
8718 std::pair<unsigned, unsigned> MaskedLoad;
8719 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8720 if (MaskedLoad.first)
8721 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8722 Value.getOperand(1), ST,this))
8723 return SDValue(NewST, 0);
Wesley Peck527da1b2010-11-23 03:31:01 +00008724
Chris Lattner4041ab62010-04-15 04:48:01 +00008725 // Or is commutative, so try swapping X and Y.
8726 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8727 if (MaskedLoad.first)
8728 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8729 Value.getOperand(0), ST,this))
8730 return SDValue(NewST, 0);
8731 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008732
Evan Chenga9cda8a2009-05-28 00:35:15 +00008733 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8734 Value.getOperand(1).getOpcode() != ISD::Constant)
Evan Cheng6673ff02009-05-28 18:41:02 +00008735 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008736
8737 SDValue N0 = Value.getOperand(0);
Dan Gohman3c9b5f32010-09-02 21:18:42 +00008738 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8739 Chain == SDValue(N0.getNode(), 1)) {
Evan Chenga9cda8a2009-05-28 00:35:15 +00008740 LoadSDNode *LD = cast<LoadSDNode>(N0);
Chris Lattnerf72c3c02010-09-21 16:08:50 +00008741 if (LD->getBasePtr() != Ptr ||
8742 LD->getPointerInfo().getAddrSpace() !=
8743 ST->getPointerInfo().getAddrSpace())
Evan Cheng6673ff02009-05-28 18:41:02 +00008744 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008745
8746 // Find the type to narrow it the load / op / store to.
8747 SDValue N1 = Value.getOperand(1);
8748 unsigned BitWidth = N1.getValueSizeInBits();
8749 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8750 if (Opc == ISD::AND)
8751 Imm ^= APInt::getAllOnesValue(BitWidth);
Evan Cheng86cdb4b2009-05-28 23:52:18 +00008752 if (Imm == 0 || Imm.isAllOnesValue())
8753 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008754 unsigned ShAmt = Imm.countTrailingZeros();
8755 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8756 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
Owen Anderson117c9e82009-08-12 00:36:31 +00008757 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
Evan Chenga9cda8a2009-05-28 00:35:15 +00008758 while (NewBW < BitWidth &&
Evan Cheng6673ff02009-05-28 18:41:02 +00008759 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
Evan Chenga9cda8a2009-05-28 00:35:15 +00008760 TLI.isNarrowingProfitable(VT, NewVT))) {
8761 NewBW = NextPowerOf2(NewBW);
Owen Anderson117c9e82009-08-12 00:36:31 +00008762 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
Evan Chenga9cda8a2009-05-28 00:35:15 +00008763 }
Evan Cheng6673ff02009-05-28 18:41:02 +00008764 if (NewBW >= BitWidth)
8765 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008766
8767 // If the lsb changed does not start at the type bitwidth boundary,
8768 // start at the previous one.
8769 if (ShAmt % NewBW)
8770 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
Manman Ren82751a12012-12-12 01:13:50 +00008771 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8772 std::min(BitWidth, ShAmt + NewBW));
Evan Chenga9cda8a2009-05-28 00:35:15 +00008773 if ((Imm & Mask) == Imm) {
8774 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8775 if (Opc == ISD::AND)
8776 NewImm ^= APInt::getAllOnesValue(NewBW);
8777 uint64_t PtrOff = ShAmt / 8;
8778 // For big endian targets, we need to adjust the offset to the pointer to
8779 // load the correct bytes.
8780 if (TLI.isBigEndian())
Evan Cheng6673ff02009-05-28 18:41:02 +00008781 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
Evan Chenga9cda8a2009-05-28 00:35:15 +00008782
8783 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
Chris Lattner229907c2011-07-18 04:54:35 +00008784 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
Micah Villmowcdfe20b2012-10-08 16:38:25 +00008785 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
Evan Cheng6673ff02009-05-28 18:41:02 +00008786 return SDValue();
8787
Andrew Trickef9de2a2013-05-25 02:42:55 +00008788 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
Evan Chenga9cda8a2009-05-28 00:35:15 +00008789 Ptr.getValueType(), Ptr,
8790 DAG.getConstant(PtrOff, Ptr.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +00008791 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
Evan Chenga9cda8a2009-05-28 00:35:15 +00008792 LD->getChain(), NewPtr,
Chris Lattnerf72c3c02010-09-21 16:08:50 +00008793 LD->getPointerInfo().getWithOffset(PtrOff),
David Greene39c6d012010-02-15 17:00:31 +00008794 LD->isVolatile(), LD->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00008795 LD->isInvariant(), NewAlign,
8796 LD->getTBAAInfo());
Andrew Trickef9de2a2013-05-25 02:42:55 +00008797 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
Evan Chenga9cda8a2009-05-28 00:35:15 +00008798 DAG.getConstant(NewImm, NewVT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00008799 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
Evan Chenga9cda8a2009-05-28 00:35:15 +00008800 NewVal, NewPtr,
Chris Lattnerf72c3c02010-09-21 16:08:50 +00008801 ST->getPointerInfo().getWithOffset(PtrOff),
David Greene39c6d012010-02-15 17:00:31 +00008802 false, false, NewAlign);
Evan Chenga9cda8a2009-05-28 00:35:15 +00008803
8804 AddToWorkList(NewPtr.getNode());
8805 AddToWorkList(NewLD.getNode());
8806 AddToWorkList(NewVal.getNode());
8807 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008808 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
Evan Chenga9cda8a2009-05-28 00:35:15 +00008809 ++OpsNarrowed;
8810 return NewST;
8811 }
8812 }
8813
Evan Cheng6673ff02009-05-28 18:41:02 +00008814 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00008815}
8816
Evan Chengd42641c2011-02-02 01:06:55 +00008817/// TransformFPLoadStorePair - For a given floating point load / store pair,
8818/// if the load value isn't used by any other operations, then consider
8819/// transforming the pair to integer load / store operations if the target
8820/// deems the transformation profitable.
8821SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8822 StoreSDNode *ST = cast<StoreSDNode>(N);
8823 SDValue Chain = ST->getChain();
8824 SDValue Value = ST->getValue();
8825 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8826 Value.hasOneUse() &&
8827 Chain == SDValue(Value.getNode(), 1)) {
8828 LoadSDNode *LD = cast<LoadSDNode>(Value);
8829 EVT VT = LD->getMemoryVT();
8830 if (!VT.isFloatingPoint() ||
8831 VT != ST->getMemoryVT() ||
8832 LD->isNonTemporal() ||
8833 ST->isNonTemporal() ||
8834 LD->getPointerInfo().getAddrSpace() != 0 ||
8835 ST->getPointerInfo().getAddrSpace() != 0)
8836 return SDValue();
8837
8838 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8839 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8840 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8841 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8842 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8843 return SDValue();
8844
8845 unsigned LDAlign = LD->getAlignment();
8846 unsigned STAlign = ST->getAlignment();
Chris Lattner229907c2011-07-18 04:54:35 +00008847 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
Micah Villmowcdfe20b2012-10-08 16:38:25 +00008848 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
Evan Chengd42641c2011-02-02 01:06:55 +00008849 if (LDAlign < ABIAlign || STAlign < ABIAlign)
8850 return SDValue();
8851
Andrew Trickef9de2a2013-05-25 02:42:55 +00008852 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
Evan Chengd42641c2011-02-02 01:06:55 +00008853 LD->getChain(), LD->getBasePtr(),
8854 LD->getPointerInfo(),
Pete Cooper82cd9e82011-11-08 18:42:53 +00008855 false, false, false, LDAlign);
Evan Chengd42641c2011-02-02 01:06:55 +00008856
Andrew Trickef9de2a2013-05-25 02:42:55 +00008857 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
Evan Chengd42641c2011-02-02 01:06:55 +00008858 NewLD, ST->getBasePtr(),
8859 ST->getPointerInfo(),
8860 false, false, STAlign);
8861
8862 AddToWorkList(NewLD.getNode());
8863 AddToWorkList(NewST.getNode());
8864 WorkListRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008865 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
Evan Chengd42641c2011-02-02 01:06:55 +00008866 ++LdStFP2Int;
8867 return NewST;
8868 }
8869
8870 return SDValue();
8871}
8872
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008873/// Helper struct to parse and store a memory address as base + index + offset.
8874/// We ignore sign extensions when it is safe to do so.
8875/// The following two expressions are not equivalent. To differentiate we need
8876/// to store whether there was a sign extension involved in the index
8877/// computation.
8878/// (load (i64 add (i64 copyfromreg %c)
8879/// (i64 signextend (add (i8 load %index)
8880/// (i8 1))))
8881/// vs
8882///
8883/// (load (i64 add (i64 copyfromreg %c)
8884/// (i64 signextend (i32 add (i32 signextend (i8 load %index))
8885/// (i32 1)))))
8886struct BaseIndexOffset {
8887 SDValue Base;
8888 SDValue Index;
8889 int64_t Offset;
8890 bool IsIndexSignExt;
8891
8892 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
8893
8894 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
8895 bool IsIndexSignExt) :
8896 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
8897
8898 bool equalBaseIndex(const BaseIndexOffset &Other) {
8899 return Other.Base == Base && Other.Index == Index &&
8900 Other.IsIndexSignExt == IsIndexSignExt;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008901 }
8902
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008903 /// Parses tree in Ptr for base, index, offset addresses.
8904 static BaseIndexOffset match(SDValue Ptr) {
8905 bool IsIndexSignExt = false;
8906
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00008907 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
8908 // instruction, then it could be just the BASE or everything else we don't
8909 // know how to handle. Just use Ptr as BASE and give up.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008910 if (Ptr->getOpcode() != ISD::ADD)
8911 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8912
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00008913 // We know that we have at least an ADD instruction. Try to pattern match
8914 // the simple case of BASE + OFFSET.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008915 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
8916 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
8917 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
8918 IsIndexSignExt);
8919 }
8920
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00008921 // Inside a loop the current BASE pointer is calculated using an ADD and a
Juergen Ributzka11c52c62013-08-28 22:33:58 +00008922 // MUL instruction. In this case Ptr is the actual BASE pointer.
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00008923 // (i64 add (i64 %array_ptr)
8924 // (i64 mul (i64 %induction_var)
8925 // (i64 %element_size)))
Juergen Ributzka11c52c62013-08-28 22:33:58 +00008926 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00008927 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00008928
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008929 // Look at Base + Index + Offset cases.
8930 SDValue Base = Ptr->getOperand(0);
8931 SDValue IndexOffset = Ptr->getOperand(1);
8932
8933 // Skip signextends.
8934 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
8935 IndexOffset = IndexOffset->getOperand(0);
8936 IsIndexSignExt = true;
8937 }
8938
8939 // Either the case of Base + Index (no offset) or something else.
8940 if (IndexOffset->getOpcode() != ISD::ADD)
8941 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
8942
8943 // Now we have the case of Base + Index + offset.
8944 SDValue Index = IndexOffset->getOperand(0);
8945 SDValue Offset = IndexOffset->getOperand(1);
8946
8947 if (!isa<ConstantSDNode>(Offset))
8948 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8949
8950 // Ignore signextends.
8951 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
8952 Index = Index->getOperand(0);
8953 IsIndexSignExt = true;
8954 } else IsIndexSignExt = false;
8955
8956 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
8957 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
8958 }
8959};
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008960
8961/// Holds a pointer to an LSBaseSDNode as well as information on where it
8962/// is located in a sequence of memory operations connected by a chain.
8963struct MemOpLink {
8964 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
8965 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
8966 // Ptr to the mem node.
8967 LSBaseSDNode *MemNode;
8968 // Offset from the base ptr.
8969 int64_t OffsetFromBase;
8970 // What is the sequence number of this mem node.
8971 // Lowest mem operand in the DAG starts at zero.
8972 unsigned SequenceNum;
8973};
8974
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008975bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
8976 EVT MemVT = St->getMemoryVT();
8977 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
Nadav Rotem495b1a42013-02-14 18:28:52 +00008978 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
8979 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00008980
8981 // Don't merge vectors into wider inputs.
8982 if (MemVT.isVector() || !MemVT.isSimple())
8983 return false;
8984
8985 // Perform an early exit check. Do not bother looking at stored values that
8986 // are not constants or loads.
8987 SDValue StoredVal = St->getValue();
8988 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
8989 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
8990 !IsLoadSrc)
8991 return false;
8992
8993 // Only look at ends of store sequences.
8994 SDValue Chain = SDValue(St, 1);
8995 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
8996 return false;
8997
Arnold Schwaighofer67523662013-04-01 18:12:58 +00008998 // This holds the base pointer, index, and the offset in bytes from the base
8999 // pointer.
9000 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009001
9002 // We must have a base and an offset.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009003 if (!BasePtr.Base.getNode())
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009004 return false;
9005
9006 // Do not handle stores to undef base pointers.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009007 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009008 return false;
9009
Nadav Rotem307d7672012-11-29 00:00:08 +00009010 // Save the LoadSDNodes that we find in the chain.
9011 // We need to make sure that these nodes do not interfere with
9012 // any of the store nodes.
9013 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9014
9015 // Save the StoreSDNodes that we find in the chain.
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009016 SmallVector<MemOpLink, 8> StoreNodes;
Nadav Rotem307d7672012-11-29 00:00:08 +00009017
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009018 // Walk up the chain and look for nodes with offsets from the same
9019 // base pointer. Stop when reaching an instruction with a different kind
9020 // or instruction which has a different base pointer.
9021 unsigned Seq = 0;
9022 StoreSDNode *Index = St;
9023 while (Index) {
9024 // If the chain has more than one use, then we can't reorder the mem ops.
9025 if (Index != St && !SDValue(Index, 1)->hasOneUse())
9026 break;
9027
9028 // Find the base pointer and offset for this memory node.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009029 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009030
9031 // Check that the base pointer is the same as the original one.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009032 if (!Ptr.equalBaseIndex(BasePtr))
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009033 break;
9034
9035 // Check that the alignment is the same.
9036 if (Index->getAlignment() != St->getAlignment())
9037 break;
9038
9039 // The memory operands must not be volatile.
9040 if (Index->isVolatile() || Index->isIndexed())
9041 break;
9042
9043 // No truncation.
9044 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9045 if (St->isTruncatingStore())
9046 break;
9047
9048 // The stored memory type must be the same.
9049 if (Index->getMemoryVT() != MemVT)
9050 break;
9051
9052 // We do not allow unaligned stores because we want to prevent overriding
9053 // stores.
9054 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9055 break;
9056
9057 // We found a potential memory operand to merge.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009058 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009059
Nadav Rotem307d7672012-11-29 00:00:08 +00009060 // Find the next memory operand in the chain. If the next operand in the
9061 // chain is a store then move up and continue the scan with the next
9062 // memory operand. If the next operand is a load save it and use alias
9063 // information to check if it interferes with anything.
9064 SDNode *NextInChain = Index->getChain().getNode();
9065 while (1) {
Nadav Rotemac450eb2012-12-06 17:34:13 +00009066 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
Nadav Rotem307d7672012-11-29 00:00:08 +00009067 // We found a store node. Use it for the next iteration.
Nadav Rotemac450eb2012-12-06 17:34:13 +00009068 Index = STn;
Nadav Rotem307d7672012-11-29 00:00:08 +00009069 break;
9070 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
Bill Wendling9200bb02013-11-25 18:05:22 +00009071 if (Ldn->isVolatile()) {
Craig Topperc0196b12014-04-14 00:51:57 +00009072 Index = nullptr;
Bill Wendling9200bb02013-11-25 18:05:22 +00009073 break;
9074 }
9075
Nadav Rotem307d7672012-11-29 00:00:08 +00009076 // Save the load node for later. Continue the scan.
9077 AliasLoadNodes.push_back(Ldn);
9078 NextInChain = Ldn->getChain().getNode();
9079 continue;
9080 } else {
Craig Topperc0196b12014-04-14 00:51:57 +00009081 Index = nullptr;
Nadav Rotem307d7672012-11-29 00:00:08 +00009082 break;
9083 }
9084 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009085 }
9086
9087 // Check if there is anything to merge.
9088 if (StoreNodes.size() < 2)
9089 return false;
9090
9091 // Sort the memory operands according to their distance from the base pointer.
9092 std::sort(StoreNodes.begin(), StoreNodes.end(),
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00009093 [](MemOpLink LHS, MemOpLink RHS) {
9094 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9095 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9096 LHS.SequenceNum > RHS.SequenceNum);
9097 });
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009098
9099 // Scan the memory operations on the chain and find the first non-consecutive
9100 // store memory address.
9101 unsigned LastConsecutiveStore = 0;
9102 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
Nadav Rotemac450eb2012-12-06 17:34:13 +00009103 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9104
9105 // Check that the addresses are consecutive starting from the second
9106 // element in the list of stores.
9107 if (i > 0) {
9108 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9109 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9110 break;
9111 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009112
Nadav Rotem307d7672012-11-29 00:00:08 +00009113 bool Alias = false;
9114 // Check if this store interferes with any of the loads that we found.
9115 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9116 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9117 Alias = true;
9118 break;
9119 }
Nadav Rotem307d7672012-11-29 00:00:08 +00009120 // We found a load that alias with this store. Stop the sequence.
9121 if (Alias)
9122 break;
9123
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009124 // Mark this node as useful.
9125 LastConsecutiveStore = i;
9126 }
9127
9128 // The node with the lowest store address.
9129 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9130
9131 // Store the constants into memory as one consecutive store.
9132 if (!IsLoadSrc) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009133 unsigned LastLegalType = 0;
Nadav Rotemb27777f2012-10-04 22:35:15 +00009134 unsigned LastLegalVectorType = 0;
9135 bool NonZero = false;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009136 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9137 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9138 SDValue StoredVal = St->getValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +00009139
9140 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
Benjamin Kramer62f7fb92012-10-05 18:19:44 +00009141 NonZero |= !C->isNullValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +00009142 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
Benjamin Kramer62f7fb92012-10-05 18:19:44 +00009143 NonZero |= !C->getConstantFPValue()->isNullValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +00009144 } else {
Alp Tokerf907b892013-12-05 05:44:44 +00009145 // Non-constant.
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009146 break;
Nadav Rotemb27777f2012-10-04 22:35:15 +00009147 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009148
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009149 // Find a legal type for the constant store.
9150 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9151 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9152 if (TLI.isTypeLegal(StoreTy))
9153 LastLegalType = i+1;
Arnold Schwaighoferd6c6e862013-04-02 15:58:51 +00009154 // Or check whether a truncstore is legal.
9155 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9156 TargetLowering::TypePromoteInteger) {
9157 EVT LegalizedStoredValueTy =
9158 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9159 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9160 LastLegalType = i+1;
9161 }
Nadav Rotemb27777f2012-10-04 22:35:15 +00009162
9163 // Find a legal type for the vector store.
9164 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9165 if (TLI.isTypeLegal(Ty))
9166 LastLegalVectorType = i + 1;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009167 }
9168
Bob Wilson3365b802012-12-20 01:36:20 +00009169 // We only use vectors if the constant is known to be zero and the
9170 // function is not marked with the noimplicitfloat attribute.
Nadav Rotem495b1a42013-02-14 18:28:52 +00009171 if (NonZero || NoVectors)
Nadav Rotemb27777f2012-10-04 22:35:15 +00009172 LastLegalVectorType = 0;
9173
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009174 // Check if we found a legal integer type to store.
Nadav Rotemb27777f2012-10-04 22:35:15 +00009175 if (LastLegalType == 0 && LastLegalVectorType == 0)
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009176 return false;
9177
Nadav Rotem495b1a42013-02-14 18:28:52 +00009178 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
Nadav Rotemb27777f2012-10-04 22:35:15 +00009179 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9180
9181 // Make sure we have something to merge.
9182 if (NumElem < 2)
9183 return false;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009184
9185 unsigned EarliestNodeUsed = 0;
9186 for (unsigned i=0; i < NumElem; ++i) {
9187 // Find a chain for the new wide-store operand. Notice that some
9188 // of the store nodes that we found may not be selected for inclusion
9189 // in the wide store. The chain we use needs to be the chain of the
9190 // earliest store node which is *used* and replaced by the wide store.
9191 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9192 EarliestNodeUsed = i;
9193 }
9194
9195 // The earliest Node in the DAG.
9196 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
Andrew Trickef9de2a2013-05-25 02:42:55 +00009197 SDLoc DL(StoreNodes[0].MemNode);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009198
Nadav Rotemb27777f2012-10-04 22:35:15 +00009199 SDValue StoredVal;
9200 if (UseVector) {
9201 // Find a legal type for the vector store.
9202 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9203 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9204 StoredVal = DAG.getConstant(0, Ty);
9205 } else {
9206 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9207 APInt StoreInt(StoreBW, 0);
9208
9209 // Construct a single integer constant which is made of the smaller
9210 // constant inputs.
9211 bool IsLE = TLI.isLittleEndian();
9212 for (unsigned i = 0; i < NumElem ; ++i) {
9213 unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9214 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9215 SDValue Val = St->getValue();
9216 StoreInt<<=ElementSizeBytes*8;
9217 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9218 StoreInt|=C->getAPIntValue().zext(StoreBW);
9219 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9220 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9221 } else {
9222 assert(false && "Invalid constant element type");
9223 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009224 }
Nadav Rotemb27777f2012-10-04 22:35:15 +00009225
9226 // Create the new Load and Store operations.
9227 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9228 StoredVal = DAG.getConstant(StoreInt, StoreTy);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009229 }
9230
Nadav Rotemb27777f2012-10-04 22:35:15 +00009231 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009232 FirstInChain->getBasePtr(),
9233 FirstInChain->getPointerInfo(),
9234 false, false,
9235 FirstInChain->getAlignment());
9236
9237 // Replace the first store with the new store
9238 CombineTo(EarliestOp, NewStore);
9239 // Erase all other stores.
9240 for (unsigned i = 0; i < NumElem ; ++i) {
9241 if (StoreNodes[i].MemNode == EarliestOp)
9242 continue;
9243 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
Rafael Espindolac79532d2012-11-14 05:08:56 +00009244 // ReplaceAllUsesWith will replace all uses that existed when it was
9245 // called, but graph optimizations may cause new ones to appear. For
9246 // example, the case in pr14333 looks like
9247 //
9248 // St's chain -> St -> another store -> X
9249 //
9250 // And the only difference from St to the other store is the chain.
9251 // When we change it's chain to be St's chain they become identical,
9252 // get CSEed and the net result is that X is now a use of St.
9253 // Since we know that St is redundant, just iterate.
9254 while (!St->use_empty())
9255 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009256 removeFromWorkList(St);
9257 DAG.DeleteNode(St);
9258 }
9259
9260 return true;
9261 }
9262
9263 // Below we handle the case of multiple consecutive stores that
9264 // come from multiple consecutive loads. We merge them into a single
9265 // wide load and a single wide store.
9266
9267 // Look for load nodes which are used by the stored values.
9268 SmallVector<MemOpLink, 8> LoadNodes;
9269
9270 // Find acceptable loads. Loads need to have the same chain (token factor),
9271 // must not be zext, volatile, indexed, and they must be consecutive.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009272 BaseIndexOffset LdBasePtr;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009273 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9274 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9275 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9276 if (!Ld) break;
9277
9278 // Loads must only have one use.
9279 if (!Ld->hasNUsesOfValue(1, 0))
9280 break;
9281
9282 // Check that the alignment is the same as the stores.
9283 if (Ld->getAlignment() != St->getAlignment())
9284 break;
9285
9286 // The memory operands must not be volatile.
9287 if (Ld->isVolatile() || Ld->isIndexed())
9288 break;
9289
9290 // We do not accept ext loads.
9291 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9292 break;
9293
9294 // The stored memory type must be the same.
9295 if (Ld->getMemoryVT() != MemVT)
9296 break;
9297
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009298 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009299 // If this is not the first ptr that we check.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009300 if (LdBasePtr.Base.getNode()) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009301 // The base ptr must be the same.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009302 if (!LdPtr.equalBaseIndex(LdBasePtr))
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009303 break;
9304 } else {
9305 // Check that all other base pointers are the same as this one.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009306 LdBasePtr = LdPtr;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009307 }
9308
9309 // We found a potential memory operand to merge.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009310 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009311 }
9312
9313 if (LoadNodes.size() < 2)
9314 return false;
9315
9316 // Scan the memory operations on the chain and find the first non-consecutive
9317 // load memory address. These variables hold the index in the store node
9318 // array.
9319 unsigned LastConsecutiveLoad = 0;
9320 // This variable refers to the size and not index in the array.
9321 unsigned LastLegalVectorType = 0;
9322 unsigned LastLegalIntegerType = 0;
9323 StartAddress = LoadNodes[0].OffsetFromBase;
Nadav Rotemac920662012-10-03 19:30:31 +00009324 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9325 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9326 // All loads much share the same chain.
9327 if (LoadNodes[i].MemNode->getChain() != FirstChain)
9328 break;
Nadav Rotem495b1a42013-02-14 18:28:52 +00009329
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009330 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9331 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9332 break;
9333 LastConsecutiveLoad = i;
9334
9335 // Find a legal type for the vector store.
9336 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9337 if (TLI.isTypeLegal(StoreTy))
9338 LastLegalVectorType = i + 1;
9339
9340 // Find a legal type for the integer store.
9341 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9342 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9343 if (TLI.isTypeLegal(StoreTy))
9344 LastLegalIntegerType = i + 1;
Arnold Schwaighoferd6c6e862013-04-02 15:58:51 +00009345 // Or check whether a truncstore and extload is legal.
9346 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9347 TargetLowering::TypePromoteInteger) {
9348 EVT LegalizedStoredValueTy =
9349 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9350 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9351 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9352 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9353 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9354 LastLegalIntegerType = i+1;
9355 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009356 }
9357
9358 // Only use vector types if the vector type is larger than the integer type.
9359 // If they are the same, use integers.
Nadav Rotem495b1a42013-02-14 18:28:52 +00009360 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009361 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9362
9363 // We add +1 here because the LastXXX variables refer to location while
9364 // the NumElem refers to array/index size.
9365 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9366 NumElem = std::min(LastLegalType, NumElem);
9367
9368 if (NumElem < 2)
9369 return false;
9370
9371 // The earliest Node in the DAG.
9372 unsigned EarliestNodeUsed = 0;
9373 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9374 for (unsigned i=1; i<NumElem; ++i) {
9375 // Find a chain for the new wide-store operand. Notice that some
9376 // of the store nodes that we found may not be selected for inclusion
9377 // in the wide store. The chain we use needs to be the chain of the
9378 // earliest store node which is *used* and replaced by the wide store.
9379 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9380 EarliestNodeUsed = i;
9381 }
9382
9383 // Find if it is better to use vectors or integers to load and store
9384 // to memory.
9385 EVT JointMemOpVT;
9386 if (UseVectorTy) {
9387 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9388 } else {
9389 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9390 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9391 }
9392
Andrew Trickef9de2a2013-05-25 02:42:55 +00009393 SDLoc LoadDL(LoadNodes[0].MemNode);
9394 SDLoc StoreDL(StoreNodes[0].MemNode);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009395
9396 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9397 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9398 FirstLoad->getChain(),
9399 FirstLoad->getBasePtr(),
9400 FirstLoad->getPointerInfo(),
9401 false, false, false,
9402 FirstLoad->getAlignment());
9403
9404 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9405 FirstInChain->getBasePtr(),
9406 FirstInChain->getPointerInfo(), false, false,
9407 FirstInChain->getAlignment());
9408
Nadav Rotemac920662012-10-03 19:30:31 +00009409 // Replace one of the loads with the new load.
9410 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9411 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9412 SDValue(NewLoad.getNode(), 1));
9413
9414 // Remove the rest of the load chains.
9415 for (unsigned i = 1; i < NumElem ; ++i) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009416 // Replace all chain users of the old load nodes with the chain of the new
9417 // load node.
9418 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
Nadav Rotemac920662012-10-03 19:30:31 +00009419 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9420 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009421
Nadav Rotemac920662012-10-03 19:30:31 +00009422 // Replace the first store with the new store.
9423 CombineTo(EarliestOp, NewStore);
9424 // Erase all other stores.
9425 for (unsigned i = 0; i < NumElem ; ++i) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009426 // Remove all Store nodes.
9427 if (StoreNodes[i].MemNode == EarliestOp)
9428 continue;
9429 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9430 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9431 removeFromWorkList(St);
9432 DAG.DeleteNode(St);
9433 }
9434
9435 return true;
9436}
9437
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009438SDValue DAGCombiner::visitSTORE(SDNode *N) {
Evan Chengab51cf22006-10-13 21:14:26 +00009439 StoreSDNode *ST = cast<StoreSDNode>(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009440 SDValue Chain = ST->getChain();
9441 SDValue Value = ST->getValue();
9442 SDValue Ptr = ST->getBasePtr();
Scott Michelcf0da6c2009-02-17 22:15:04 +00009443
Evan Chenga4cf58a2007-05-07 21:27:48 +00009444 // If this is a store of a bit convert, store the input value if the
Evan Chengf325c2a2007-05-09 21:49:47 +00009445 // resultant store does not need a higher alignment than the original.
Wesley Peck527da1b2010-11-23 03:31:01 +00009446 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009447 ST->isUnindexed()) {
Dan Gohmane7fe80f2009-02-20 23:29:13 +00009448 unsigned OrigAlign = ST->getAlignment();
Owen Anderson53aa7a92009-08-10 22:56:29 +00009449 EVT SVT = Value.getOperand(0).getValueType();
Micah Villmowcdfe20b2012-10-08 16:38:25 +00009450 unsigned Align = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +00009451 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
Duncan Sands8651e9c2008-06-13 19:07:40 +00009452 if (Align <= OrigAlign &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00009453 ((!LegalOperations && !ST->isVolatile()) ||
Dan Gohman4aa18462009-01-28 17:46:25 +00009454 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00009455 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
Chris Lattner676c61d2010-09-21 18:41:36 +00009456 Ptr, ST->getPointerInfo(), ST->isVolatile(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009457 ST->isNonTemporal(), OrigAlign,
9458 ST->getTBAAInfo());
Jim Laskeyd07be232006-09-25 16:29:54 +00009459 }
Owen Andersona5192842011-04-14 17:30:49 +00009460
Chris Lattner41c80e82011-04-09 02:32:02 +00009461 // Turn 'store undef, Ptr' -> nothing.
9462 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9463 return Chain;
Duncan Sands8651e9c2008-06-13 19:07:40 +00009464
Nate Begeman8e20c762006-12-11 02:23:46 +00009465 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
Nate Begeman8e20c762006-12-11 02:23:46 +00009466 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
Duncan Sands8651e9c2008-06-13 19:07:40 +00009467 // NOTE: If the original store is volatile, this transform must not increase
9468 // the number of stores. For example, on x86-32 an f64 can be stored in one
9469 // processor operation but an i64 (which is not legal) requires two. So the
9470 // transform should not be done in this case.
Evan Cheng21836982006-12-11 17:25:19 +00009471 if (Value.getOpcode() != ISD::TargetConstantFP) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009472 SDValue Tmp;
Craig Topperd9c27832013-08-15 02:44:19 +00009473 switch (CFP->getSimpleValueType(0).SimpleTy) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00009474 default: llvm_unreachable("Unknown FP type");
Pete Cooper5b614222012-06-21 18:00:39 +00009475 case MVT::f16: // We don't do this for these yet.
9476 case MVT::f80:
Owen Anderson9f944592009-08-11 20:47:22 +00009477 case MVT::f128:
9478 case MVT::ppcf128:
Dale Johannesenaf12b572007-09-18 18:36:59 +00009479 break;
Owen Anderson9f944592009-08-11 20:47:22 +00009480 case MVT::f32:
Chris Lattner4041ab62010-04-15 04:48:01 +00009481 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
Owen Anderson9f944592009-08-11 20:47:22 +00009482 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
Dale Johannesen028084e2007-09-12 03:30:33 +00009483 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
Owen Anderson9f944592009-08-11 20:47:22 +00009484 bitcastToAPInt().getZExtValue(), MVT::i32);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009485 return DAG.getStore(Chain, SDLoc(N), Tmp,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009486 Ptr, ST->getMemOperand());
Chris Lattnerb7524b62006-12-12 04:16:14 +00009487 }
9488 break;
Owen Anderson9f944592009-08-11 20:47:22 +00009489 case MVT::f64:
Chris Lattner4041ab62010-04-15 04:48:01 +00009490 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
Dan Gohman4aa18462009-01-28 17:46:25 +00009491 !ST->isVolatile()) ||
Owen Anderson9f944592009-08-11 20:47:22 +00009492 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
Dale Johannesen54306fe2008-10-09 18:53:47 +00009493 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
Owen Anderson9f944592009-08-11 20:47:22 +00009494 getZExtValue(), MVT::i64);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009495 return DAG.getStore(Chain, SDLoc(N), Tmp,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009496 Ptr, ST->getMemOperand());
Chris Lattner41c80e82011-04-09 02:32:02 +00009497 }
Owen Andersona5192842011-04-14 17:30:49 +00009498
Chris Lattner41c80e82011-04-09 02:32:02 +00009499 if (!ST->isVolatile() &&
9500 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
Duncan Sands1826ded2007-10-28 12:59:45 +00009501 // Many FP stores are not made apparent until after legalize, e.g. for
Chris Lattnerb7524b62006-12-12 04:16:14 +00009502 // argument passing. Since this is so common, custom legalize the
9503 // 64-bit integer store into two 32-bit stores.
Dale Johannesen54306fe2008-10-09 18:53:47 +00009504 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
Owen Anderson9f944592009-08-11 20:47:22 +00009505 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9506 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
Duncan Sands7377f5f2008-02-11 10:37:04 +00009507 if (TLI.isBigEndian()) std::swap(Lo, Hi);
Chris Lattnerb7524b62006-12-12 04:16:14 +00009508
Dan Gohman2af30632007-07-09 22:18:38 +00009509 unsigned Alignment = ST->getAlignment();
9510 bool isVolatile = ST->isVolatile();
David Greene39c6d012010-02-15 17:00:31 +00009511 bool isNonTemporal = ST->isNonTemporal();
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009512 const MDNode *TBAAInfo = ST->getTBAAInfo();
Dan Gohman2af30632007-07-09 22:18:38 +00009513
Andrew Trickef9de2a2013-05-25 02:42:55 +00009514 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
Chris Lattner676c61d2010-09-21 18:41:36 +00009515 Ptr, ST->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +00009516 isVolatile, isNonTemporal,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009517 ST->getAlignment(), TBAAInfo);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009518 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
Chris Lattnerb7524b62006-12-12 04:16:14 +00009519 DAG.getConstant(4, Ptr.getValueType()));
Duncan Sands1826ded2007-10-28 12:59:45 +00009520 Alignment = MinAlign(Alignment, 4U);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009521 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
Chris Lattner676c61d2010-09-21 18:41:36 +00009522 Ptr, ST->getPointerInfo().getWithOffset(4),
9523 isVolatile, isNonTemporal,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009524 Alignment, TBAAInfo);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009525 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
Bill Wendling27d9dd42009-01-30 23:36:47 +00009526 St0, St1);
Chris Lattnerb7524b62006-12-12 04:16:14 +00009527 }
Bill Wendling27d9dd42009-01-30 23:36:47 +00009528
Chris Lattnerb7524b62006-12-12 04:16:14 +00009529 break;
Evan Cheng21836982006-12-11 17:25:19 +00009530 }
Nate Begeman8e20c762006-12-11 02:23:46 +00009531 }
Nate Begeman8e20c762006-12-11 02:23:46 +00009532 }
9533
Evan Cheng43cd9e32010-04-01 06:04:33 +00009534 // Try to infer better alignment information than the store already has.
9535 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
Evan Cheng4a5b2042011-11-28 22:37:34 +00009536 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9537 if (Align > ST->getAlignment())
Andrew Trickef9de2a2013-05-25 02:42:55 +00009538 return DAG.getTruncStore(Chain, SDLoc(N), Value,
Evan Cheng4a5b2042011-11-28 22:37:34 +00009539 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009540 ST->isVolatile(), ST->isNonTemporal(), Align,
9541 ST->getTBAAInfo());
Evan Cheng43cd9e32010-04-01 06:04:33 +00009542 }
9543 }
9544
Evan Chengd42641c2011-02-02 01:06:55 +00009545 // Try transforming a pair floating point load / store ops to integer
9546 // load / store ops.
9547 SDValue NewST = TransformFPLoadStorePair(N);
9548 if (NewST.getNode())
9549 return NewST;
9550
Hal Finkel5ef4dcc2013-08-29 03:29:55 +00009551 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9552 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +00009553#ifndef NDEBUG
9554 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9555 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9556 UseAA = false;
9557#endif
Hal Finkelccc18e12014-01-24 18:25:26 +00009558 if (UseAA && ST->isUnindexed()) {
Jim Laskeyd07be232006-09-25 16:29:54 +00009559 // Walk up chain skipping non-aliasing memory nodes.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009560 SDValue BetterChain = FindBetterChain(N, Chain);
Scott Michelcf0da6c2009-02-17 22:15:04 +00009561
Jim Laskey708d0db2006-10-04 16:53:27 +00009562 // If there is a better chain.
Jim Laskeyd07be232006-09-25 16:29:54 +00009563 if (Chain != BetterChain) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009564 SDValue ReplStore;
Nate Begeman879d8f12009-09-15 00:18:30 +00009565
9566 // Replace the chain to avoid dependency.
Jim Laskey3bf4f3b2006-10-14 12:14:27 +00009567 if (ST->isTruncatingStore()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009568 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009569 ST->getMemoryVT(), ST->getMemOperand());
Jim Laskey3bf4f3b2006-10-14 12:14:27 +00009570 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009571 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009572 ST->getMemOperand());
Jim Laskey3bf4f3b2006-10-14 12:14:27 +00009573 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00009574
Jim Laskeyd07be232006-09-25 16:29:54 +00009575 // Create token to keep both nodes around.
Andrew Trickef9de2a2013-05-25 02:42:55 +00009576 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
Owen Anderson9f944592009-08-11 20:47:22 +00009577 MVT::Other, Chain, ReplStore);
Bill Wendling27d9dd42009-01-30 23:36:47 +00009578
Nate Begeman879d8f12009-09-15 00:18:30 +00009579 // Make sure the new and old chains are cleaned up.
9580 AddToWorkList(Token.getNode());
9581
Jim Laskeydcf983c2006-10-13 23:32:28 +00009582 // Don't add users to work list.
9583 return CombineTo(N, Token, false);
Jim Laskeyd07be232006-09-25 16:29:54 +00009584 }
Jim Laskey5d19d592006-09-21 16:28:59 +00009585 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00009586
Evan Cheng33157702006-11-05 09:31:14 +00009587 // Try transforming N to an indexed store.
Evan Cheng60c68462006-11-07 09:03:05 +00009588 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009589 return SDValue(N, 0);
Evan Cheng33157702006-11-05 09:31:14 +00009590
Chris Lattner3f9c6a72007-12-29 06:26:16 +00009591 // FIXME: is there such a thing as a truncating indexed store?
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009592 if (ST->isTruncatingStore() && ST->isUnindexed() &&
Nadav Rotemd2d9bdb2011-06-15 11:19:12 +00009593 Value.getValueType().isInteger()) {
Chris Lattner5e6fe052007-10-13 06:35:54 +00009594 // See if we can simplify the input to this truncstore with knowledge that
9595 // only the low bits are being used. For example:
9596 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
Scott Michelcf0da6c2009-02-17 22:15:04 +00009597 SDValue Shorter =
Dan Gohman1f372ed2008-02-25 21:11:39 +00009598 GetDemandedBits(Value,
Nadav Rotemd2d9bdb2011-06-15 11:19:12 +00009599 APInt::getLowBitsSet(
9600 Value.getValueType().getScalarType().getSizeInBits(),
9601 ST->getMemoryVT().getScalarType().getSizeInBits()));
Gabor Greiff304a7a2008-08-28 21:40:38 +00009602 AddToWorkList(Value.getNode());
9603 if (Shorter.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00009604 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009605 Ptr, ST->getMemoryVT(), ST->getMemOperand());
Scott Michelcf0da6c2009-02-17 22:15:04 +00009606
Chris Lattnerf47e3062007-10-13 06:58:48 +00009607 // Otherwise, see if we can simplify the operation with
9608 // SimplifyDemandedBits, which only works if the value has a single use.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +00009609 if (SimplifyDemandedBits(Value,
Eric Christopherd9e8eac2010-12-09 04:48:06 +00009610 APInt::getLowBitsSet(
9611 Value.getValueType().getScalarType().getSizeInBits(),
9612 ST->getMemoryVT().getScalarType().getSizeInBits())))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009613 return SDValue(N, 0);
Chris Lattner5e6fe052007-10-13 06:35:54 +00009614 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00009615
Chris Lattner3f9c6a72007-12-29 06:26:16 +00009616 // If this is a load followed by a store to the same location, then the store
9617 // is dead/noop.
9618 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
Dan Gohman47a7d6f2008-01-30 00:15:11 +00009619 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009620 ST->isUnindexed() && !ST->isVolatile() &&
Chris Lattner51b01bf2008-01-08 23:08:06 +00009621 // There can't be any side effects between the load and store, such as
9622 // a call or store.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009623 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
Chris Lattner3f9c6a72007-12-29 06:26:16 +00009624 // The store is dead, remove it.
9625 return Chain;
9626 }
9627 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00009628
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009629 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9630 // truncating store. We can do this even if this is already a truncstore.
9631 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
Gabor Greiff304a7a2008-08-28 21:40:38 +00009632 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009633 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
Dan Gohman47a7d6f2008-01-30 00:15:11 +00009634 ST->getMemoryVT())) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009635 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009636 Ptr, ST->getMemoryVT(), ST->getMemOperand());
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009637 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00009638
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009639 // Only perform this optimization before the types are legal, because we
Nadav Rotemb27777f2012-10-04 22:35:15 +00009640 // don't want to perform this optimization on every DAGCombine invocation.
Nadav Rotem1157e142012-12-02 17:14:09 +00009641 if (!LegalTypes) {
9642 bool EverChanged = false;
9643
9644 do {
9645 // There can be multiple store sequences on the same chain.
9646 // Keep trying to merge store sequences until we are unable to do so
9647 // or until we merge the last store on the chain.
9648 bool Changed = MergeConsecutiveStores(ST);
9649 EverChanged |= Changed;
9650 if (!Changed) break;
9651 } while (ST->getOpcode() != ISD::DELETED_NODE);
9652
9653 if (EverChanged)
9654 return SDValue(N, 0);
9655 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009656
Evan Chenga9cda8a2009-05-28 00:35:15 +00009657 return ReduceLoadOpStoreWidth(N);
Chris Lattner04c73702005-10-10 22:31:19 +00009658}
9659
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009660SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9661 SDValue InVec = N->getOperand(0);
9662 SDValue InVal = N->getOperand(1);
9663 SDValue EltNo = N->getOperand(2);
Andrew Trickef9de2a2013-05-25 02:42:55 +00009664 SDLoc dl(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00009665
Bob Wilson42603952010-05-19 23:42:58 +00009666 // If the inserted element is an UNDEF, just use the input vector.
9667 if (InVal.getOpcode() == ISD::UNDEF)
9668 return InVec;
9669
Nadav Rotemdb2f5482011-02-12 14:40:33 +00009670 EVT VT = InVec.getValueType();
9671
Owen Andersonb2c80da2011-02-25 21:41:48 +00009672 // If we can't generate a legal BUILD_VECTOR, exit
Nadav Rotemdb2f5482011-02-12 14:40:33 +00009673 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9674 return SDValue();
9675
Eli Friedmanb7910b72011-09-09 21:04:06 +00009676 // Check that we know which element is being inserted
9677 if (!isa<ConstantSDNode>(EltNo))
9678 return SDValue();
9679 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00009680
Eli Friedmanb7910b72011-09-09 21:04:06 +00009681 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9682 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
9683 // vector elements.
9684 SmallVector<SDValue, 8> Ops;
Quentin Colombet6bf4baa2013-07-30 00:24:09 +00009685 // Do not combine these two vectors if the output vector will not replace
9686 // the input vector.
9687 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
Eli Friedmanb7910b72011-09-09 21:04:06 +00009688 Ops.append(InVec.getNode()->op_begin(),
9689 InVec.getNode()->op_end());
9690 } else if (InVec.getOpcode() == ISD::UNDEF) {
9691 unsigned NElts = VT.getVectorNumElements();
9692 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9693 } else {
9694 return SDValue();
Nate Begeman8d6d4b92009-04-27 18:41:29 +00009695 }
Eli Friedmanb7910b72011-09-09 21:04:06 +00009696
9697 // Insert the element
9698 if (Elt < Ops.size()) {
9699 // All the operands of BUILD_VECTOR must have the same type;
9700 // we enforce that here.
9701 EVT OpVT = Ops[0].getValueType();
9702 if (InVal.getValueType() != OpVT)
9703 InVal = OpVT.bitsGT(InVal.getValueType()) ?
9704 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9705 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9706 Ops[Elt] = InVal;
9707 }
9708
9709 // Return the new vector
9710 return DAG.getNode(ISD::BUILD_VECTOR, dl,
9711 VT, &Ops[0], Ops.size());
Chris Lattner5336a592006-03-19 01:27:56 +00009712}
9713
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009714SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
Mon P Wangca6d6de2009-01-17 00:07:25 +00009715 // (vextract (scalar_to_vector val, 0) -> val
9716 SDValue InVec = N->getOperand(0);
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009717 EVT VT = InVec.getValueType();
9718 EVT NVT = N->getValueType(0);
Mon P Wangca6d6de2009-01-17 00:07:25 +00009719
Duncan Sands6be291a2011-05-09 08:03:33 +00009720 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9721 // Check if the result type doesn't match the inserted element type. A
9722 // SCALAR_TO_VECTOR may truncate the inserted element and the
9723 // EXTRACT_VECTOR_ELT may widen the extracted vector.
9724 SDValue InOp = InVec.getOperand(0);
Duncan Sands6be291a2011-05-09 08:03:33 +00009725 if (InOp.getValueType() != NVT) {
9726 assert(InOp.getValueType().isInteger() && NVT.isInteger());
Andrew Trickef9de2a2013-05-25 02:42:55 +00009727 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
Duncan Sands6be291a2011-05-09 08:03:33 +00009728 }
9729 return InOp;
9730 }
Evan Cheng1120279a2008-05-13 08:35:03 +00009731
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009732 SDValue EltNo = N->getOperand(1);
9733 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9734
9735 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9736 // We only perform this optimization before the op legalization phase because
Nadav Rotem841c9a82012-09-20 08:53:31 +00009737 // we may introduce new vector instructions which are not backed by TD
9738 // patterns. For example on AVX, extracting elements from a wide vector
Hal Finkel02807592014-03-31 11:43:19 +00009739 // without using extract_subvector. However, if we can find an underlying
9740 // scalar value, then we can always use that.
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009741 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
Hal Finkel02807592014-03-31 11:43:19 +00009742 && ConstEltNo) {
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009743 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9744 int NumElem = VT.getVectorNumElements();
9745 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9746 // Find the new index to extract from.
9747 int OrigElt = SVOp->getMaskElt(Elt);
9748
9749 // Extracting an undef index is undef.
9750 if (OrigElt == -1)
9751 return DAG.getUNDEF(NVT);
9752
9753 // Select the right vector half to extract from.
Hal Finkel02807592014-03-31 11:43:19 +00009754 SDValue SVInVec;
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009755 if (OrigElt < NumElem) {
Hal Finkel02807592014-03-31 11:43:19 +00009756 SVInVec = InVec->getOperand(0);
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009757 } else {
Hal Finkel02807592014-03-31 11:43:19 +00009758 SVInVec = InVec->getOperand(1);
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009759 OrigElt -= NumElem;
9760 }
9761
Hal Finkel02807592014-03-31 11:43:19 +00009762 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
9763 SDValue InOp = SVInVec.getOperand(OrigElt);
9764 if (InOp.getValueType() != NVT) {
9765 assert(InOp.getValueType().isInteger() && NVT.isInteger());
9766 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
9767 }
9768
9769 return InOp;
9770 }
9771
9772 // FIXME: We should handle recursing on other vector shuffles and
9773 // scalar_to_vector here as well.
9774
9775 if (!LegalOperations) {
9776 EVT IndexTy = TLI.getVectorIdxTy();
9777 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
9778 SVInVec, DAG.getConstant(OrigElt, IndexTy));
9779 }
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009780 }
9781
Evan Cheng1120279a2008-05-13 08:35:03 +00009782 // Perform only after legalization to ensure build_vector / vector_shuffle
9783 // optimizations have already been done.
Duncan Sandsdc2dac12008-11-24 14:53:14 +00009784 if (!LegalOperations) return SDValue();
Evan Cheng1120279a2008-05-13 08:35:03 +00009785
Mon P Wangca6d6de2009-01-17 00:07:25 +00009786 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
9787 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
9788 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
Evan Cheng0de312d2007-10-06 08:19:55 +00009789
Nadav Rotemfb6ddee2012-01-17 21:44:01 +00009790 if (ConstEltNo) {
Eric Christopherfcc9e682010-11-03 09:36:40 +00009791 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Evan Cheng0de312d2007-10-06 08:19:55 +00009792 bool NewLoad = false;
Mon P Wangb5eb7202008-12-11 00:26:16 +00009793 bool BCNumEltsChanged = false;
Owen Anderson53aa7a92009-08-10 22:56:29 +00009794 EVT ExtVT = VT.getVectorElementType();
9795 EVT LVT = ExtVT;
Bill Wendling27d9dd42009-01-30 23:36:47 +00009796
Evan Cheng7bf83092012-03-13 22:00:52 +00009797 // If the result of load has to be truncated, then it's not necessarily
9798 // profitable.
Evan Chengd5f8e572012-03-13 22:16:11 +00009799 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
Evan Cheng7bf83092012-03-13 22:00:52 +00009800 return SDValue();
9801
Wesley Peck527da1b2010-11-23 03:31:01 +00009802 if (InVec.getOpcode() == ISD::BITCAST) {
Eli Friedmane96286c2011-12-26 22:49:32 +00009803 // Don't duplicate a load with other uses.
9804 if (!InVec.hasOneUse())
9805 return SDValue();
9806
Owen Anderson53aa7a92009-08-10 22:56:29 +00009807 EVT BCVT = InVec.getOperand(0).getValueType();
9808 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009809 return SDValue();
Mon P Wangb5eb7202008-12-11 00:26:16 +00009810 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
9811 BCNumEltsChanged = true;
Evan Cheng1120279a2008-05-13 08:35:03 +00009812 InVec = InVec.getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00009813 ExtVT = BCVT.getVectorElementType();
Evan Cheng1120279a2008-05-13 08:35:03 +00009814 NewLoad = true;
9815 }
Evan Cheng0de312d2007-10-06 08:19:55 +00009816
Craig Topperc0196b12014-04-14 00:51:57 +00009817 LoadSDNode *LN0 = nullptr;
9818 const ShuffleVectorSDNode *SVN = nullptr;
Bill Wendling27d9dd42009-01-30 23:36:47 +00009819 if (ISD::isNormalLoad(InVec.getNode())) {
Evan Cheng1120279a2008-05-13 08:35:03 +00009820 LN0 = cast<LoadSDNode>(InVec);
Bill Wendling27d9dd42009-01-30 23:36:47 +00009821 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
Owen Anderson53aa7a92009-08-10 22:56:29 +00009822 InVec.getOperand(0).getValueType() == ExtVT &&
Bill Wendling27d9dd42009-01-30 23:36:47 +00009823 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
Eli Friedmane96286c2011-12-26 22:49:32 +00009824 // Don't duplicate a load with other uses.
9825 if (!InVec.hasOneUse())
9826 return SDValue();
9827
Evan Cheng1120279a2008-05-13 08:35:03 +00009828 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
Nate Begeman5f829d82009-04-29 05:20:52 +00009829 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
Evan Cheng1120279a2008-05-13 08:35:03 +00009830 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
9831 // =>
9832 // (load $addr+1*size)
Scott Michelcf0da6c2009-02-17 22:15:04 +00009833
Eli Friedmane96286c2011-12-26 22:49:32 +00009834 // Don't duplicate a load with other uses.
9835 if (!InVec.hasOneUse())
9836 return SDValue();
9837
Mon P Wangb5eb7202008-12-11 00:26:16 +00009838 // If the bit convert changed the number of elements, it is unsafe
9839 // to examine the mask.
9840 if (BCNumEltsChanged)
9841 return SDValue();
Nate Begeman5f829d82009-04-29 05:20:52 +00009842
9843 // Select the input vector, guarding against out of range extract vector.
9844 unsigned NumElems = VT.getVectorNumElements();
Eric Christopherfcc9e682010-11-03 09:36:40 +00009845 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
Nate Begeman5f829d82009-04-29 05:20:52 +00009846 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
9847
Eli Friedmane96286c2011-12-26 22:49:32 +00009848 if (InVec.getOpcode() == ISD::BITCAST) {
9849 // Don't duplicate a load with other uses.
9850 if (!InVec.hasOneUse())
9851 return SDValue();
9852
Evan Cheng1120279a2008-05-13 08:35:03 +00009853 InVec = InVec.getOperand(0);
Eli Friedmane96286c2011-12-26 22:49:32 +00009854 }
Gabor Greiff304a7a2008-08-28 21:40:38 +00009855 if (ISD::isNormalLoad(InVec.getNode())) {
Evan Cheng1120279a2008-05-13 08:35:03 +00009856 LN0 = cast<LoadSDNode>(InVec);
Ted Kremenekd87bd772010-04-08 18:49:30 +00009857 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
Evan Cheng0de312d2007-10-06 08:19:55 +00009858 }
9859 }
Bill Wendling27d9dd42009-01-30 23:36:47 +00009860
Eli Friedmane96286c2011-12-26 22:49:32 +00009861 // Make sure we found a non-volatile load and the extractelement is
9862 // the only use.
Nadav Rotem8a7beb82011-05-11 14:40:50 +00009863 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009864 return SDValue();
Evan Cheng1120279a2008-05-13 08:35:03 +00009865
Eric Christopherc6418b12010-11-03 20:44:42 +00009866 // If Idx was -1 above, Elt is going to be -1, so just return undef.
9867 if (Elt == -1)
Eli Friedmancbd3ba92011-07-25 22:25:42 +00009868 return DAG.getUNDEF(LVT);
Eric Christopherc6418b12010-11-03 20:44:42 +00009869
Evan Cheng1120279a2008-05-13 08:35:03 +00009870 unsigned Align = LN0->getAlignment();
9871 if (NewLoad) {
9872 // Check the resultant load doesn't need a higher alignment than the
9873 // original load.
Bill Wendling27d9dd42009-01-30 23:36:47 +00009874 unsigned NewAlign =
Micah Villmowcdfe20b2012-10-08 16:38:25 +00009875 TLI.getDataLayout()
Eric Christopherd9e8eac2010-12-09 04:48:06 +00009876 ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
Bill Wendling27d9dd42009-01-30 23:36:47 +00009877
Dan Gohman4aa18462009-01-28 17:46:25 +00009878 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009879 return SDValue();
Bill Wendling27d9dd42009-01-30 23:36:47 +00009880
Evan Cheng1120279a2008-05-13 08:35:03 +00009881 Align = NewAlign;
9882 }
9883
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009884 SDValue NewPtr = LN0->getBasePtr();
Chris Lattnerf72c3c02010-09-21 16:08:50 +00009885 unsigned PtrOff = 0;
Wesley Peck527da1b2010-11-23 03:31:01 +00009886
Eric Christopherc6418b12010-11-03 20:44:42 +00009887 if (Elt) {
Chris Lattnerf72c3c02010-09-21 16:08:50 +00009888 PtrOff = LVT.getSizeInBits() * Elt / 8;
Owen Anderson53aa7a92009-08-10 22:56:29 +00009889 EVT PtrType = NewPtr.getValueType();
Evan Cheng1120279a2008-05-13 08:35:03 +00009890 if (TLI.isBigEndian())
Duncan Sands13237ac2008-06-06 12:08:01 +00009891 PtrOff = VT.getSizeInBits() / 8 - PtrOff;
Andrew Trickef9de2a2013-05-25 02:42:55 +00009892 NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
Evan Cheng1120279a2008-05-13 08:35:03 +00009893 DAG.getConstant(PtrOff, PtrType));
9894 }
Bill Wendling27d9dd42009-01-30 23:36:47 +00009895
Eli Friedmanff1eaa72011-11-16 23:50:22 +00009896 // The replacement we need to do here is a little tricky: we need to
9897 // replace an extractelement of a load with a load.
9898 // Use ReplaceAllUsesOfValuesWith to do the replacement.
Eli Friedmane96286c2011-12-26 22:49:32 +00009899 // Note that this replacement assumes that the extractvalue is the only
9900 // use of the load; that's okay because we don't want to perform this
9901 // transformation in other cases anyway.
Evan Cheng7bf83092012-03-13 22:00:52 +00009902 SDValue Load;
Evan Chengd5f8e572012-03-13 22:16:11 +00009903 SDValue Chain;
Evan Cheng7bf83092012-03-13 22:00:52 +00009904 if (NVT.bitsGT(LVT)) {
9905 // If the result type of vextract is wider than the load, then issue an
9906 // extending load instead.
9907 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
9908 ? ISD::ZEXTLOAD : ISD::EXTLOAD;
Andrew Trickef9de2a2013-05-25 02:42:55 +00009909 Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
Evan Cheng7bf83092012-03-13 22:00:52 +00009910 NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009911 LVT, LN0->isVolatile(), LN0->isNonTemporal(),
9912 Align, LN0->getTBAAInfo());
Evan Chengd5f8e572012-03-13 22:16:11 +00009913 Chain = Load.getValue(1);
9914 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009915 Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
Evan Cheng7bf83092012-03-13 22:00:52 +00009916 LN0->getPointerInfo().getWithOffset(PtrOff),
Stephen Lincfe7f352013-07-08 00:37:03 +00009917 LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009918 LN0->isInvariant(), Align, LN0->getTBAAInfo());
Evan Chengd5f8e572012-03-13 22:16:11 +00009919 Chain = Load.getValue(1);
9920 if (NVT.bitsLT(LVT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00009921 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
Evan Chengd5f8e572012-03-13 22:16:11 +00009922 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00009923 Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
Evan Chengd5f8e572012-03-13 22:16:11 +00009924 }
Eli Friedmanff1eaa72011-11-16 23:50:22 +00009925 WorkListRemover DeadNodes(*this);
9926 SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
Evan Chengd5f8e572012-03-13 22:16:11 +00009927 SDValue To[] = { Load, Chain };
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00009928 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
Eli Friedmanff1eaa72011-11-16 23:50:22 +00009929 // Since we're explcitly calling ReplaceAllUses, add the new node to the
9930 // worklist explicitly as well.
9931 AddToWorkList(Load.getNode());
Craig Topperaaeae982012-03-20 05:28:39 +00009932 AddUsersToWorkList(Load.getNode()); // Add users too
Eli Friedmanff1eaa72011-11-16 23:50:22 +00009933 // Make sure to revisit this node to clean it up; it will usually be dead.
9934 AddToWorkList(N);
9935 return SDValue(N, 0);
Evan Cheng0de312d2007-10-06 08:19:55 +00009936 }
Bill Wendling27d9dd42009-01-30 23:36:47 +00009937
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009938 return SDValue();
Evan Cheng0de312d2007-10-06 08:19:55 +00009939}
Evan Cheng0de312d2007-10-06 08:19:55 +00009940
Michael Liao6d106b72012-10-23 23:06:52 +00009941// Simplify (build_vec (ext )) to (bitcast (build_vec ))
9942SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
9943 // We perform this optimization post type-legalization because
9944 // the type-legalizer often scalarizes integer-promoted vectors.
9945 // Performing this optimization before may create bit-casts which
9946 // will be type-legalized to complex code sequences.
9947 // We perform this optimization only before the operation legalizer because we
9948 // may introduce illegal operations.
9949 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
9950 return SDValue();
9951
Dan Gohmana8665142007-06-25 16:23:39 +00009952 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +00009953 SDLoc dl(N);
Owen Anderson53aa7a92009-08-10 22:56:29 +00009954 EVT VT = N->getValueType(0);
Nadav Rotema62368c2012-07-15 08:38:23 +00009955
Nadav Rotembf6568b2011-10-29 21:23:04 +00009956 // Check to see if this is a BUILD_VECTOR of a bunch of values
9957 // which come from any_extend or zero_extend nodes. If so, we can create
9958 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
Nadav Rotemf3103612011-10-31 20:08:25 +00009959 // optimizations. We do not handle sign-extend because we can't fill the sign
9960 // using shuffles.
Nadav Rotembf6568b2011-10-29 21:23:04 +00009961 EVT SourceType = MVT::Other;
Craig Topper02cb0fb2012-01-17 09:09:48 +00009962 bool AllAnyExt = true;
Nadav Rotema62368c2012-07-15 08:38:23 +00009963
Craig Topper02cb0fb2012-01-17 09:09:48 +00009964 for (unsigned i = 0; i != NumInScalars; ++i) {
Nadav Rotembf6568b2011-10-29 21:23:04 +00009965 SDValue In = N->getOperand(i);
9966 // Ignore undef inputs.
9967 if (In.getOpcode() == ISD::UNDEF) continue;
9968
9969 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
9970 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
9971
Nadav Rotemf3103612011-10-31 20:08:25 +00009972 // Abort if the element is not an extension.
Nadav Rotembf6568b2011-10-29 21:23:04 +00009973 if (!ZeroExt && !AnyExt) {
Nadav Rotemf3103612011-10-31 20:08:25 +00009974 SourceType = MVT::Other;
Nadav Rotembf6568b2011-10-29 21:23:04 +00009975 break;
9976 }
9977
9978 // The input is a ZeroExt or AnyExt. Check the original type.
9979 EVT InTy = In.getOperand(0).getValueType();
9980
9981 // Check that all of the widened source types are the same.
9982 if (SourceType == MVT::Other)
Nadav Rotemf3103612011-10-31 20:08:25 +00009983 // First time.
Nadav Rotembf6568b2011-10-29 21:23:04 +00009984 SourceType = InTy;
9985 else if (InTy != SourceType) {
9986 // Multiple income types. Abort.
Nadav Rotemf3103612011-10-31 20:08:25 +00009987 SourceType = MVT::Other;
Nadav Rotembf6568b2011-10-29 21:23:04 +00009988 break;
9989 }
9990
9991 // Check if all of the extends are ANY_EXTENDs.
Craig Topper02cb0fb2012-01-17 09:09:48 +00009992 AllAnyExt &= AnyExt;
Nadav Rotembf6568b2011-10-29 21:23:04 +00009993 }
9994
Nadav Rotemf3103612011-10-31 20:08:25 +00009995 // In order to have valid types, all of the inputs must be extended from the
9996 // same source type and all of the inputs must be any or zero extend.
9997 // Scalar sizes must be a power of two.
Michael Liao6d106b72012-10-23 23:06:52 +00009998 EVT OutScalarTy = VT.getScalarType();
Nadav Rotem34ca89a2012-02-12 15:05:31 +00009999 bool ValidTypes = SourceType != MVT::Other &&
Nadav Rotemf3103612011-10-31 20:08:25 +000010000 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10001 isPowerOf2_32(SourceType.getSizeInBits());
10002
Nadav Rotem6fd1d322012-03-15 08:49:06 +000010003 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10004 // turn into a single shuffle instruction.
Michael Liao6d106b72012-10-23 23:06:52 +000010005 if (!ValidTypes)
10006 return SDValue();
Nadav Rotembf6568b2011-10-29 21:23:04 +000010007
Michael Liao6d106b72012-10-23 23:06:52 +000010008 bool isLE = TLI.isLittleEndian();
10009 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10010 assert(ElemRatio > 1 && "Invalid element size ratio");
10011 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10012 DAG.getConstant(0, SourceType);
Nadav Rotembf6568b2011-10-29 21:23:04 +000010013
Michael Liao6d106b72012-10-23 23:06:52 +000010014 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10015 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
Nadav Rotembf6568b2011-10-29 21:23:04 +000010016
Michael Liao6d106b72012-10-23 23:06:52 +000010017 // Populate the new build_vector
Jakub Staszaka6addc22012-10-24 00:38:25 +000010018 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
Michael Liao6d106b72012-10-23 23:06:52 +000010019 SDValue Cast = N->getOperand(i);
10020 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10021 Cast.getOpcode() == ISD::ZERO_EXTEND ||
10022 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10023 SDValue In;
10024 if (Cast.getOpcode() == ISD::UNDEF)
10025 In = DAG.getUNDEF(SourceType);
10026 else
10027 In = Cast->getOperand(0);
10028 unsigned Index = isLE ? (i * ElemRatio) :
10029 (i * ElemRatio + (ElemRatio - 1));
Nadav Rotembf6568b2011-10-29 21:23:04 +000010030
Michael Liao6d106b72012-10-23 23:06:52 +000010031 assert(Index < Ops.size() && "Invalid index");
10032 Ops[Index] = In;
Nadav Rotembf6568b2011-10-29 21:23:04 +000010033 }
Chris Lattner5336a592006-03-19 01:27:56 +000010034
Michael Liao6d106b72012-10-23 23:06:52 +000010035 // The type of the new BUILD_VECTOR node.
10036 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10037 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10038 "Invalid vector size");
10039 // Check if the new vector type is legal.
10040 if (!isTypeLegal(VecVT)) return SDValue();
10041
10042 // Make the new BUILD_VECTOR.
10043 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], Ops.size());
10044
10045 // The new BUILD_VECTOR node has the potential to be further optimized.
10046 AddToWorkList(BV.getNode());
10047 // Bitcast to the desired type.
10048 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10049}
10050
Michael Liao59229792012-10-24 04:14:18 +000010051SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10052 EVT VT = N->getValueType(0);
10053
10054 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +000010055 SDLoc dl(N);
Michael Liao59229792012-10-24 04:14:18 +000010056
10057 EVT SrcVT = MVT::Other;
10058 unsigned Opcode = ISD::DELETED_NODE;
10059 unsigned NumDefs = 0;
10060
10061 for (unsigned i = 0; i != NumInScalars; ++i) {
10062 SDValue In = N->getOperand(i);
10063 unsigned Opc = In.getOpcode();
10064
10065 if (Opc == ISD::UNDEF)
10066 continue;
10067
10068 // If all scalar values are floats and converted from integers.
10069 if (Opcode == ISD::DELETED_NODE &&
10070 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10071 Opcode = Opc;
Michael Liao59229792012-10-24 04:14:18 +000010072 }
Tom Stellard567f8862013-01-02 22:13:01 +000010073
Michael Liao59229792012-10-24 04:14:18 +000010074 if (Opc != Opcode)
10075 return SDValue();
10076
10077 EVT InVT = In.getOperand(0).getValueType();
10078
10079 // If all scalar values are typed differently, bail out. It's chosen to
10080 // simplify BUILD_VECTOR of integer types.
10081 if (SrcVT == MVT::Other)
10082 SrcVT = InVT;
10083 if (SrcVT != InVT)
10084 return SDValue();
10085 NumDefs++;
10086 }
10087
10088 // If the vector has just one element defined, it's not worth to fold it into
10089 // a vectorized one.
10090 if (NumDefs < 2)
10091 return SDValue();
10092
10093 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10094 && "Should only handle conversion from integer to float.");
10095 assert(SrcVT != MVT::Other && "Cannot determine source type!");
10096
10097 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
Tom Stellard567f8862013-01-02 22:13:01 +000010098
10099 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10100 return SDValue();
10101
Michael Liao59229792012-10-24 04:14:18 +000010102 SmallVector<SDValue, 8> Opnds;
10103 for (unsigned i = 0; i != NumInScalars; ++i) {
10104 SDValue In = N->getOperand(i);
10105
10106 if (In.getOpcode() == ISD::UNDEF)
10107 Opnds.push_back(DAG.getUNDEF(SrcVT));
10108 else
10109 Opnds.push_back(In.getOperand(0));
10110 }
10111 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT,
10112 &Opnds[0], Opnds.size());
10113 AddToWorkList(BV.getNode());
10114
10115 return DAG.getNode(Opcode, dl, VT, BV);
10116}
10117
Michael Liao6d106b72012-10-23 23:06:52 +000010118SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10119 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +000010120 SDLoc dl(N);
Michael Liao6d106b72012-10-23 23:06:52 +000010121 EVT VT = N->getValueType(0);
10122
10123 // A vector built entirely of undefs is undef.
10124 if (ISD::allOperandsUndef(N))
10125 return DAG.getUNDEF(VT);
10126
10127 SDValue V = reduceBuildVecExtToExtBuildVec(N);
10128 if (V.getNode())
10129 return V;
10130
Michael Liao59229792012-10-24 04:14:18 +000010131 V = reduceBuildVecConvertToConvertBuildVec(N);
10132 if (V.getNode())
10133 return V;
10134
Dan Gohmana8665142007-06-25 16:23:39 +000010135 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10136 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10137 // at most two distinct vectors, turn this into a shuffle node.
Duncan Sands3fb2fc62012-03-19 15:35:44 +000010138
10139 // May only combine to shuffle after legalize if shuffle is legal.
10140 if (LegalOperations &&
10141 !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
10142 return SDValue();
10143
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010144 SDValue VecIn1, VecIn2;
Chris Lattnerc9992542006-03-28 20:28:38 +000010145 for (unsigned i = 0; i != NumInScalars; ++i) {
10146 // Ignore undef inputs.
10147 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +000010148
Dan Gohmana8665142007-06-25 16:23:39 +000010149 // If this input is something other than a EXTRACT_VECTOR_ELT with a
Chris Lattnerc9992542006-03-28 20:28:38 +000010150 // constant index, bail out.
Dan Gohmana8665142007-06-25 16:23:39 +000010151 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
Chris Lattnerc9992542006-03-28 20:28:38 +000010152 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
Craig Topperc0196b12014-04-14 00:51:57 +000010153 VecIn1 = VecIn2 = SDValue(nullptr, 0);
Chris Lattnerc9992542006-03-28 20:28:38 +000010154 break;
10155 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010156
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010157 // We allow up to two distinct input vectors.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010158 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
Chris Lattnerc9992542006-03-28 20:28:38 +000010159 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10160 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +000010161
Craig Topperc0196b12014-04-14 00:51:57 +000010162 if (!VecIn1.getNode()) {
Chris Lattnerc9992542006-03-28 20:28:38 +000010163 VecIn1 = ExtractedFromVec;
Craig Topperc0196b12014-04-14 00:51:57 +000010164 } else if (!VecIn2.getNode()) {
Chris Lattnerc9992542006-03-28 20:28:38 +000010165 VecIn2 = ExtractedFromVec;
10166 } else {
10167 // Too many inputs.
Craig Topperc0196b12014-04-14 00:51:57 +000010168 VecIn1 = VecIn2 = SDValue(nullptr, 0);
Chris Lattnerc9992542006-03-28 20:28:38 +000010169 break;
10170 }
10171 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010172
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010173 // If everything is good, we can make a shuffle operation.
Gabor Greiff304a7a2008-08-28 21:40:38 +000010174 if (VecIn1.getNode()) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010175 SmallVector<int, 8> Mask;
Chris Lattnerc9992542006-03-28 20:28:38 +000010176 for (unsigned i = 0; i != NumInScalars; ++i) {
10177 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010178 Mask.push_back(-1);
Chris Lattnerc9992542006-03-28 20:28:38 +000010179 continue;
10180 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010181
Rafael Espindolab93db662009-04-24 12:40:33 +000010182 // If extracting from the first vector, just use the index directly.
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010183 SDValue Extract = N->getOperand(i);
Mon P Wang523c0852009-03-17 06:33:10 +000010184 SDValue ExtVal = Extract.getOperand(1);
Chris Lattnerc9992542006-03-28 20:28:38 +000010185 if (Extract.getOperand(0) == VecIn1) {
Nate Begeman5f829d82009-04-29 05:20:52 +000010186 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10187 if (ExtIndex > VT.getVectorNumElements())
10188 return SDValue();
Wesley Peck527da1b2010-11-23 03:31:01 +000010189
Nate Begeman5f829d82009-04-29 05:20:52 +000010190 Mask.push_back(ExtIndex);
Chris Lattnerc9992542006-03-28 20:28:38 +000010191 continue;
10192 }
10193
10194 // Otherwise, use InIdx + VecSize
Mon P Wang523c0852009-03-17 06:33:10 +000010195 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010196 Mask.push_back(Idx+NumInScalars);
Chris Lattnerc9992542006-03-28 20:28:38 +000010197 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010198
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010199 // We can't generate a shuffle node with mismatched input and output types.
10200 // Attempt to transform a single input vector to the correct type.
10201 if ((VT != VecIn1.getValueType())) {
10202 // We don't support shuffeling between TWO values of different types.
Craig Topperc0196b12014-04-14 00:51:57 +000010203 if (VecIn2.getNode())
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010204 return SDValue();
10205
10206 // We only support widening of vectors which are half the size of the
10207 // output registers. For example XMM->YMM widening on X86 with AVX.
10208 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10209 return SDValue();
10210
James Molloy1e5c6112012-09-10 14:01:21 +000010211 // If the input vector type has a different base type to the output
10212 // vector type, bail out.
10213 if (VecIn1.getValueType().getVectorElementType() !=
10214 VT.getVectorElementType())
10215 return SDValue();
10216
Stepan Dyatkovskiy99120e02012-08-22 09:33:55 +000010217 // Widen the input vector by adding undef values.
Michael Liao6d106b72012-10-23 23:06:52 +000010218 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
Stepan Dyatkovskiy99120e02012-08-22 09:33:55 +000010219 VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010220 }
10221
10222 // If VecIn2 is unused then change it to undef.
10223 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10224
Nadav Rotem841c9a82012-09-20 08:53:31 +000010225 // Check that we were able to transform all incoming values to the same
10226 // type.
Nadav Rotem0c650642012-02-13 12:42:26 +000010227 if (VecIn2.getValueType() != VecIn1.getValueType() ||
10228 VecIn1.getValueType() != VT)
10229 return SDValue();
10230
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010231 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
Nadav Rotem0c650642012-02-13 12:42:26 +000010232 if (!isTypeLegal(VT))
Duncan Sandsdc2dac12008-11-24 14:53:14 +000010233 return SDValue();
10234
Dan Gohmana8665142007-06-25 16:23:39 +000010235 // Return the new VECTOR_SHUFFLE node.
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010236 SDValue Ops[2];
Chris Lattnerc24a1d32006-08-08 02:23:42 +000010237 Ops[0] = VecIn1;
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010238 Ops[1] = VecIn2;
Michael Liao6d106b72012-10-23 23:06:52 +000010239 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
Chris Lattnerc9992542006-03-28 20:28:38 +000010240 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010241
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010242 return SDValue();
Chris Lattnerc9992542006-03-28 20:28:38 +000010243}
10244
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010245SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
Dan Gohmana8665142007-06-25 16:23:39 +000010246 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10247 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
10248 // inputs come from at most two distinct vectors, turn this into a shuffle
10249 // node.
10250
10251 // If we only have one input vector, we don't need to do any concatenation.
Bill Wendling27d9dd42009-01-30 23:36:47 +000010252 if (N->getNumOperands() == 1)
Dan Gohmana8665142007-06-25 16:23:39 +000010253 return N->getOperand(0);
Dan Gohmana8665142007-06-25 16:23:39 +000010254
Nadav Rotem01892102012-07-14 21:30:27 +000010255 // Check if all of the operands are undefs.
Nadav Rotemd369d4b2013-10-25 06:41:18 +000010256 EVT VT = N->getValueType(0);
Nadav Rotema62368c2012-07-15 08:38:23 +000010257 if (ISD::allOperandsUndef(N))
Nadav Rotemd369d4b2013-10-25 06:41:18 +000010258 return DAG.getUNDEF(VT);
10259
10260 // Optimize concat_vectors where one of the vectors is undef.
10261 if (N->getNumOperands() == 2 &&
10262 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10263 SDValue In = N->getOperand(0);
Nadav Rotem6eee0802013-12-10 01:13:59 +000010264 assert(In.getValueType().isVector() && "Must concat vectors");
Nadav Rotemd369d4b2013-10-25 06:41:18 +000010265
10266 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10267 if (In->getOpcode() == ISD::BITCAST &&
10268 !In->getOperand(0)->getValueType(0).isVector()) {
10269 SDValue Scalar = In->getOperand(0);
10270 EVT SclTy = Scalar->getValueType(0);
10271
10272 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10273 return SDValue();
10274
10275 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10276 VT.getSizeInBits() / SclTy.getSizeInBits());
10277 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10278 return SDValue();
10279
10280 SDLoc dl = SDLoc(N);
10281 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10282 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10283 }
10284 }
Nadav Rotem01892102012-07-14 21:30:27 +000010285
Robert Lougher7d9084f2014-02-11 15:42:46 +000010286 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10287 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10288 if (N->getNumOperands() == 2 &&
10289 N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10290 N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10291 EVT VT = N->getValueType(0);
10292 SDValue N0 = N->getOperand(0);
10293 SDValue N1 = N->getOperand(1);
10294 SmallVector<SDValue, 8> Opnds;
10295 unsigned BuildVecNumElts = N0.getNumOperands();
10296
10297 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10298 Opnds.push_back(N0.getOperand(i));
10299 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10300 Opnds.push_back(N1.getOperand(i));
10301
10302 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
10303 Opnds.size());
10304 }
10305
Nadav Roteme5a2dda2013-05-01 19:18:51 +000010306 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10307 // nodes often generate nop CONCAT_VECTOR nodes.
10308 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10309 // place the incoming vectors at the exact same location.
10310 SDValue SingleSource = SDValue();
10311 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10312
10313 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10314 SDValue Op = N->getOperand(i);
10315
10316 if (Op.getOpcode() == ISD::UNDEF)
10317 continue;
10318
10319 // Check if this is the identity extract:
10320 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10321 return SDValue();
10322
10323 // Find the single incoming vector for the extract_subvector.
10324 if (SingleSource.getNode()) {
10325 if (Op.getOperand(0) != SingleSource)
10326 return SDValue();
10327 } else {
10328 SingleSource = Op.getOperand(0);
Michael Kupersteinac868752013-05-06 08:06:13 +000010329
10330 // Check the source type is the same as the type of the result.
10331 // If not, this concat may extend the vector, so we can not
10332 // optimize it away.
10333 if (SingleSource.getValueType() != N->getValueType(0))
10334 return SDValue();
Nadav Roteme5a2dda2013-05-01 19:18:51 +000010335 }
10336
10337 unsigned IdentityIndex = i * PartNumElem;
10338 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10339 // The extract index must be constant.
10340 if (!CS)
10341 return SDValue();
Stephen Lincfe7f352013-07-08 00:37:03 +000010342
Nadav Roteme5a2dda2013-05-01 19:18:51 +000010343 // Check that we are reading from the identity index.
10344 if (CS->getZExtValue() != IdentityIndex)
10345 return SDValue();
10346 }
10347
10348 if (SingleSource.getNode())
10349 return SingleSource;
Stephen Lincfe7f352013-07-08 00:37:03 +000010350
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010351 return SDValue();
Dan Gohmana8665142007-06-25 16:23:39 +000010352}
10353
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +000010354SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10355 EVT NVT = N->getValueType(0);
10356 SDValue V = N->getOperand(0);
10357
Michael Liao7a442c802012-10-17 20:48:33 +000010358 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10359 // Combine:
10360 // (extract_subvec (concat V1, V2, ...), i)
10361 // Into:
10362 // Vi if possible
Jack Carterd4e96152013-10-17 01:34:33 +000010363 // Only operand 0 is checked as 'concat' assumes all inputs of the same
10364 // type.
Michael Liao2c235802012-10-19 03:17:00 +000010365 if (V->getOperand(0).getValueType() != NVT)
10366 return SDValue();
Michael Liao7a442c802012-10-17 20:48:33 +000010367 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10368 unsigned NumElems = NVT.getVectorNumElements();
10369 assert((Idx % NumElems) == 0 &&
10370 "IDX in concat is not a multiple of the result vector length.");
10371 return V->getOperand(Idx / NumElems);
10372 }
10373
Michael Liaobb05a1d2013-03-25 23:47:35 +000010374 // Skip bitcasting
10375 if (V->getOpcode() == ISD::BITCAST)
10376 V = V.getOperand(0);
10377
10378 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010379 SDLoc dl(N);
Michael Liaobb05a1d2013-03-25 23:47:35 +000010380 // Handle only simple case where vector being inserted and vector
10381 // being extracted are of same type, and are half size of larger vectors.
10382 EVT BigVT = V->getOperand(0).getValueType();
10383 EVT SmallVT = V->getOperand(1).getValueType();
10384 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10385 return SDValue();
10386
10387 // Only handle cases where both indexes are constants with the same type.
10388 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10389 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10390
10391 if (InsIdx && ExtIdx &&
10392 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10393 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10394 // Combine:
10395 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10396 // Into:
10397 // indices are equal or bit offsets are equal => V1
10398 // otherwise => (extract_subvec V1, ExtIdx)
10399 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10400 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10401 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10402 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10403 DAG.getNode(ISD::BITCAST, dl,
10404 N->getOperand(0).getValueType(),
10405 V->getOperand(0)), N->getOperand(1));
10406 }
10407 }
10408
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +000010409 return SDValue();
10410}
10411
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010412// Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10413static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10414 EVT VT = N->getValueType(0);
10415 unsigned NumElts = VT.getVectorNumElements();
10416
10417 SDValue N0 = N->getOperand(0);
10418 SDValue N1 = N->getOperand(1);
10419 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10420
10421 SmallVector<SDValue, 4> Ops;
10422 EVT ConcatVT = N0.getOperand(0).getValueType();
10423 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10424 unsigned NumConcats = NumElts / NumElemsPerConcat;
10425
10426 // Look at every vector that's inserted. We're looking for exact
10427 // subvector-sized copies from a concatenated vector
10428 for (unsigned I = 0; I != NumConcats; ++I) {
10429 // Make sure we're dealing with a copy.
10430 unsigned Begin = I * NumElemsPerConcat;
Hao Liubc601962013-05-13 02:07:05 +000010431 bool AllUndef = true, NoUndef = true;
10432 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10433 if (SVN->getMaskElt(J) >= 0)
10434 AllUndef = false;
10435 else
10436 NoUndef = false;
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010437 }
10438
Hao Liubc601962013-05-13 02:07:05 +000010439 if (NoUndef) {
Hao Liubc601962013-05-13 02:07:05 +000010440 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10441 return SDValue();
10442
10443 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10444 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10445 return SDValue();
10446
10447 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10448 if (FirstElt < N0.getNumOperands())
10449 Ops.push_back(N0.getOperand(FirstElt));
10450 else
10451 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10452
10453 } else if (AllUndef) {
10454 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10455 } else { // Mixed with general masks and undefs, can't do optimization.
10456 return SDValue();
10457 }
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010458 }
10459
Andrew Trickef9de2a2013-05-25 02:42:55 +000010460 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops.data(),
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010461 Ops.size());
10462}
10463
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010464SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000010465 EVT VT = N->getValueType(0);
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010466 unsigned NumElts = VT.getVectorNumElements();
Chris Lattner39dcf1a2006-03-31 22:16:43 +000010467
Mon P Wang25f01062008-11-10 04:46:22 +000010468 SDValue N0 = N->getOperand(0);
Craig Topper279c77b2012-01-04 08:07:43 +000010469 SDValue N1 = N->getOperand(1);
Mon P Wang25f01062008-11-10 04:46:22 +000010470
Craig Topper5894fe42012-04-09 05:16:56 +000010471 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
Mon P Wang25f01062008-11-10 04:46:22 +000010472
Craig Topper279c77b2012-01-04 08:07:43 +000010473 // Canonicalize shuffle undef, undef -> undef
10474 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10475 return DAG.getUNDEF(VT);
10476
10477 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10478
10479 // Canonicalize shuffle v, v -> v, undef
10480 if (N0 == N1) {
10481 SmallVector<int, 8> NewMask;
10482 for (unsigned i = 0; i != NumElts; ++i) {
10483 int Idx = SVN->getMaskElt(i);
10484 if (Idx >= (int)NumElts) Idx -= NumElts;
10485 NewMask.push_back(Idx);
10486 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000010487 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
Craig Topper279c77b2012-01-04 08:07:43 +000010488 &NewMask[0]);
10489 }
10490
10491 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
10492 if (N0.getOpcode() == ISD::UNDEF) {
10493 SmallVector<int, 8> NewMask;
10494 for (unsigned i = 0; i != NumElts; ++i) {
10495 int Idx = SVN->getMaskElt(i);
Craig Toppere3ad4832012-04-09 05:55:33 +000010496 if (Idx >= 0) {
Craig Topper309dfef2013-08-08 07:38:55 +000010497 if (Idx >= (int)NumElts)
Craig Toppere3ad4832012-04-09 05:55:33 +000010498 Idx -= NumElts;
Craig Topper309dfef2013-08-08 07:38:55 +000010499 else
10500 Idx = -1; // remove reference to lhs
Craig Toppere3ad4832012-04-09 05:55:33 +000010501 }
10502 NewMask.push_back(Idx);
Craig Topper279c77b2012-01-04 08:07:43 +000010503 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000010504 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
Craig Topper279c77b2012-01-04 08:07:43 +000010505 &NewMask[0]);
10506 }
10507
10508 // Remove references to rhs if it is undef
10509 if (N1.getOpcode() == ISD::UNDEF) {
10510 bool Changed = false;
10511 SmallVector<int, 8> NewMask;
10512 for (unsigned i = 0; i != NumElts; ++i) {
10513 int Idx = SVN->getMaskElt(i);
10514 if (Idx >= (int)NumElts) {
10515 Idx = -1;
10516 Changed = true;
10517 }
10518 NewMask.push_back(Idx);
10519 }
10520 if (Changed)
Andrew Trickef9de2a2013-05-25 02:42:55 +000010521 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
Craig Topper279c77b2012-01-04 08:07:43 +000010522 }
Evan Cheng8472e0c2006-07-20 22:44:41 +000010523
Bob Wilsonf63da122010-10-28 17:06:14 +000010524 // If it is a splat, check if the argument vector is another splat or a
10525 // build_vector with all scalar elements the same.
Bob Wilsonf63da122010-10-28 17:06:14 +000010526 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
Gabor Greiff304a7a2008-08-28 21:40:38 +000010527 SDNode *V = N0.getNode();
Evan Cheng7c970b92006-07-21 08:25:53 +000010528
Dan Gohmana8665142007-06-25 16:23:39 +000010529 // If this is a bit convert that changes the element type of the vector but
Evan Chengf3ae00a2006-10-16 22:49:37 +000010530 // not the number of vector elements, look through it. Be careful not to
10531 // look though conversions that change things like v4f32 to v2f64.
Wesley Peck527da1b2010-11-23 03:31:01 +000010532 if (V->getOpcode() == ISD::BITCAST) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010533 SDValue ConvInput = V->getOperand(0);
Evan Chengb8ff2232008-07-22 20:42:56 +000010534 if (ConvInput.getValueType().isVector() &&
10535 ConvInput.getValueType().getVectorNumElements() == NumElts)
Gabor Greiff304a7a2008-08-28 21:40:38 +000010536 V = ConvInput.getNode();
Evan Chengf3ae00a2006-10-16 22:49:37 +000010537 }
10538
Dan Gohmana8665142007-06-25 16:23:39 +000010539 if (V->getOpcode() == ISD::BUILD_VECTOR) {
Bob Wilsonf63da122010-10-28 17:06:14 +000010540 assert(V->getNumOperands() == NumElts &&
10541 "BUILD_VECTOR has wrong number of operands");
10542 SDValue Base;
10543 bool AllSame = true;
10544 for (unsigned i = 0; i != NumElts; ++i) {
10545 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10546 Base = V->getOperand(i);
10547 break;
Evan Cheng7c970b92006-07-21 08:25:53 +000010548 }
Evan Cheng7c970b92006-07-21 08:25:53 +000010549 }
Bob Wilsonf63da122010-10-28 17:06:14 +000010550 // Splat of <u, u, u, u>, return <u, u, u, u>
10551 if (!Base.getNode())
10552 return N0;
10553 for (unsigned i = 0; i != NumElts; ++i) {
10554 if (V->getOperand(i) != Base) {
10555 AllSame = false;
10556 break;
10557 }
10558 }
10559 // Splat of <x, x, x, x>, return <x, x, x, x>
10560 if (AllSame)
10561 return N0;
Evan Cheng7c970b92006-07-21 08:25:53 +000010562 }
10563 }
Nadav Rotemb0783502012-04-01 19:31:22 +000010564
Benjamin Kramerbbae9912013-04-09 17:41:43 +000010565 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10566 Level < AfterLegalizeVectorOps &&
10567 (N1.getOpcode() == ISD::UNDEF ||
10568 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10569 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10570 SDValue V = partitionShuffleOfConcats(N, DAG);
10571
10572 if (V.getNode())
10573 return V;
10574 }
10575
Nadav Rotemb0783502012-04-01 19:31:22 +000010576 // If this shuffle node is simply a swizzle of another shuffle node,
Nadav Rotem71d07ae2012-04-07 21:19:08 +000010577 // and it reverses the swizzle of the previous shuffle then we can
10578 // optimize shuffle(shuffle(x, undef), undef) -> x.
Nadav Rotemb0783502012-04-01 19:31:22 +000010579 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10580 N1.getOpcode() == ISD::UNDEF) {
10581
Nadav Rotemb0783502012-04-01 19:31:22 +000010582 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10583
Nadav Rotem71d07ae2012-04-07 21:19:08 +000010584 // Shuffle nodes can only reverse shuffles with a single non-undef value.
10585 if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
10586 return SDValue();
10587
Craig Topper5894fe42012-04-09 05:16:56 +000010588 // The incoming shuffle must be of the same type as the result of the
10589 // current shuffle.
10590 assert(OtherSV->getOperand(0).getValueType() == VT &&
10591 "Shuffle types don't match");
Nadav Rotemb0783502012-04-01 19:31:22 +000010592
10593 for (unsigned i = 0; i != NumElts; ++i) {
10594 int Idx = SVN->getMaskElt(i);
Craig Topper5894fe42012-04-09 05:16:56 +000010595 assert(Idx < (int)NumElts && "Index references undef operand");
Nadav Rotemb0783502012-04-01 19:31:22 +000010596 // Next, this index comes from the first value, which is the incoming
10597 // shuffle. Adopt the incoming index.
10598 if (Idx >= 0)
10599 Idx = OtherSV->getMaskElt(Idx);
10600
Nadav Rotem71d07ae2012-04-07 21:19:08 +000010601 // The combined shuffle must map each index to itself.
Craig Topper5894fe42012-04-09 05:16:56 +000010602 if (Idx >= 0 && (unsigned)Idx != i)
Nadav Rotem71d07ae2012-04-07 21:19:08 +000010603 return SDValue();
Nadav Rotemb0783502012-04-01 19:31:22 +000010604 }
Nadav Rotem71d07ae2012-04-07 21:19:08 +000010605
10606 return OtherSV->getOperand(0);
Nadav Rotemb0783502012-04-01 19:31:22 +000010607 }
10608
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010609 return SDValue();
Chris Lattner39dcf1a2006-03-31 22:16:43 +000010610}
10611
Manman Ren413a6cb2014-01-31 01:10:35 +000010612SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
10613 SDValue N0 = N->getOperand(0);
10614 SDValue N2 = N->getOperand(2);
10615
10616 // If the input vector is a concatenation, and the insert replaces
10617 // one of the halves, we can optimize into a single concat_vectors.
10618 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10619 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
10620 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
10621 EVT VT = N->getValueType(0);
10622
10623 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10624 // (concat_vectors Z, Y)
10625 if (InsIdx == 0)
10626 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10627 N->getOperand(1), N0.getOperand(1));
10628
10629 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10630 // (concat_vectors X, Z)
10631 if (InsIdx == VT.getVectorNumElements()/2)
10632 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10633 N0.getOperand(0), N->getOperand(1));
10634 }
10635
10636 return SDValue();
10637}
10638
Evan Chenga320abc2006-04-20 08:56:16 +000010639/// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
Dan Gohmana8665142007-06-25 16:23:39 +000010640/// an AND to a vector_shuffle with the destination vector and a zero vector.
10641/// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
Evan Chenga320abc2006-04-20 08:56:16 +000010642/// vector_shuffle V, Zero, <0, 4, 2, 4>
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010643SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000010644 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +000010645 SDLoc dl(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010646 SDValue LHS = N->getOperand(0);
10647 SDValue RHS = N->getOperand(1);
Dan Gohmana8665142007-06-25 16:23:39 +000010648 if (N->getOpcode() == ISD::AND) {
Wesley Peck527da1b2010-11-23 03:31:01 +000010649 if (RHS.getOpcode() == ISD::BITCAST)
Evan Chenga320abc2006-04-20 08:56:16 +000010650 RHS = RHS.getOperand(0);
Dan Gohmana8665142007-06-25 16:23:39 +000010651 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010652 SmallVector<int, 8> Indices;
10653 unsigned NumElts = RHS.getNumOperands();
Evan Chenga320abc2006-04-20 08:56:16 +000010654 for (unsigned i = 0; i != NumElts; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010655 SDValue Elt = RHS.getOperand(i);
Evan Chenga320abc2006-04-20 08:56:16 +000010656 if (!isa<ConstantSDNode>(Elt))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010657 return SDValue();
Craig Toppere5893f62012-04-09 05:59:53 +000010658
10659 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010660 Indices.push_back(i);
Evan Chenga320abc2006-04-20 08:56:16 +000010661 else if (cast<ConstantSDNode>(Elt)->isNullValue())
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010662 Indices.push_back(NumElts);
Evan Chenga320abc2006-04-20 08:56:16 +000010663 else
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010664 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000010665 }
10666
10667 // Let's see if the target supports this vector_shuffle.
Owen Anderson53aa7a92009-08-10 22:56:29 +000010668 EVT RVT = RHS.getValueType();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010669 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010670 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000010671
Dan Gohmana8665142007-06-25 16:23:39 +000010672 // Return the new VECTOR_SHUFFLE node.
Dan Gohman08c0a952009-09-23 21:02:20 +000010673 EVT EltVT = RVT.getVectorElementType();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010674 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
Dan Gohman08c0a952009-09-23 21:02:20 +000010675 DAG.getConstant(0, EltVT));
Andrew Trickef9de2a2013-05-25 02:42:55 +000010676 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010677 RVT, &ZeroOps[0], ZeroOps.size());
Wesley Peck527da1b2010-11-23 03:31:01 +000010678 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010679 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
Wesley Peck527da1b2010-11-23 03:31:01 +000010680 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
Evan Chenga320abc2006-04-20 08:56:16 +000010681 }
10682 }
Bill Wendling31b50992009-01-30 23:59:18 +000010683
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010684 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000010685}
10686
Dan Gohmana8665142007-06-25 16:23:39 +000010687/// SimplifyVBinOp - Visit a binary vector operation, like ADD.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010688SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
Bob Wilson54081442010-12-17 23:06:49 +000010689 assert(N->getValueType(0).isVector() &&
10690 "SimplifyVBinOp only works on vectors!");
Dan Gohmana8665142007-06-25 16:23:39 +000010691
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010692 SDValue LHS = N->getOperand(0);
10693 SDValue RHS = N->getOperand(1);
10694 SDValue Shuffle = XformToShuffleWithZero(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +000010695 if (Shuffle.getNode()) return Shuffle;
Evan Chenga320abc2006-04-20 08:56:16 +000010696
Dan Gohmana8665142007-06-25 16:23:39 +000010697 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
Chris Lattner0442a182006-04-02 03:25:57 +000010698 // this operation.
Scott Michelcf0da6c2009-02-17 22:15:04 +000010699 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
Dan Gohmana8665142007-06-25 16:23:39 +000010700 RHS.getOpcode() == ISD::BUILD_VECTOR) {
Juergen Ributzka73844052014-01-13 20:51:35 +000010701 // Check if both vectors are constants. If not bail out.
Andrea Di Biagiod7c03ec2014-01-15 19:51:32 +000010702 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
10703 cast<BuildVectorSDNode>(RHS)->isConstant()))
Juergen Ributzka73844052014-01-13 20:51:35 +000010704 return SDValue();
10705
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010706 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +000010707 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010708 SDValue LHSOp = LHS.getOperand(i);
10709 SDValue RHSOp = RHS.getOperand(i);
Bill Wendling31b50992009-01-30 23:59:18 +000010710
Evan Cheng64d28462006-05-31 06:08:35 +000010711 // Can't fold divide by zero.
Dan Gohmana8665142007-06-25 16:23:39 +000010712 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
10713 N->getOpcode() == ISD::FDIV) {
Evan Cheng64d28462006-05-31 06:08:35 +000010714 if ((RHSOp.getOpcode() == ISD::Constant &&
Gabor Greiff304a7a2008-08-28 21:40:38 +000010715 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
Evan Cheng64d28462006-05-31 06:08:35 +000010716 (RHSOp.getOpcode() == ISD::ConstantFP &&
Gabor Greiff304a7a2008-08-28 21:40:38 +000010717 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
Evan Cheng64d28462006-05-31 06:08:35 +000010718 break;
10719 }
Bill Wendling31b50992009-01-30 23:59:18 +000010720
Bob Wilson54081442010-12-17 23:06:49 +000010721 EVT VT = LHSOp.getValueType();
Bob Wilson68156192011-10-18 17:34:47 +000010722 EVT RVT = RHSOp.getValueType();
10723 if (RVT != VT) {
10724 // Integer BUILD_VECTOR operands may have types larger than the element
10725 // size (e.g., when the element type is not legal). Prior to type
10726 // legalization, the types may not match between the two BUILD_VECTORS.
10727 // Truncate one of the operands to make them match.
10728 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010729 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
Bob Wilson68156192011-10-18 17:34:47 +000010730 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010731 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
Bob Wilson68156192011-10-18 17:34:47 +000010732 VT = RVT;
10733 }
10734 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000010735 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
Evan Cheng48f0de92010-05-18 00:03:40 +000010736 LHSOp, RHSOp);
10737 if (FoldOp.getOpcode() != ISD::UNDEF &&
10738 FoldOp.getOpcode() != ISD::Constant &&
10739 FoldOp.getOpcode() != ISD::ConstantFP)
10740 break;
10741 Ops.push_back(FoldOp);
10742 AddToWorkList(FoldOp.getNode());
Chris Lattner0442a182006-04-02 03:25:57 +000010743 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010744
Bob Wilson54081442010-12-17 23:06:49 +000010745 if (Ops.size() == LHS.getNumOperands())
Andrew Trickef9de2a2013-05-25 02:42:55 +000010746 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
Bob Wilson54081442010-12-17 23:06:49 +000010747 LHS.getValueType(), &Ops[0], Ops.size());
Chris Lattner0442a182006-04-02 03:25:57 +000010748 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010749
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010750 return SDValue();
Chris Lattner0442a182006-04-02 03:25:57 +000010751}
10752
Craig Topper82384612012-09-11 01:45:21 +000010753/// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
10754SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
Craig Topper82384612012-09-11 01:45:21 +000010755 assert(N->getValueType(0).isVector() &&
10756 "SimplifyVUnaryOp only works on vectors!");
10757
10758 SDValue N0 = N->getOperand(0);
10759
10760 if (N0.getOpcode() != ISD::BUILD_VECTOR)
10761 return SDValue();
10762
10763 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
10764 SmallVector<SDValue, 8> Ops;
10765 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
10766 SDValue Op = N0.getOperand(i);
10767 if (Op.getOpcode() != ISD::UNDEF &&
10768 Op.getOpcode() != ISD::ConstantFP)
10769 break;
10770 EVT EltVT = Op.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +000010771 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
Craig Topper82384612012-09-11 01:45:21 +000010772 if (FoldOp.getOpcode() != ISD::UNDEF &&
10773 FoldOp.getOpcode() != ISD::ConstantFP)
10774 break;
10775 Ops.push_back(FoldOp);
10776 AddToWorkList(FoldOp.getNode());
10777 }
10778
10779 if (Ops.size() != N0.getNumOperands())
10780 return SDValue();
10781
Andrew Trickef9de2a2013-05-25 02:42:55 +000010782 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
Craig Topper82384612012-09-11 01:45:21 +000010783 N0.getValueType(), &Ops[0], Ops.size());
10784}
10785
Andrew Trickef9de2a2013-05-25 02:42:55 +000010786SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
Bill Wendling31b50992009-01-30 23:59:18 +000010787 SDValue N1, SDValue N2){
Nate Begeman2042aa52005-10-08 00:29:44 +000010788 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
Scott Michelcf0da6c2009-02-17 22:15:04 +000010789
Bill Wendling31b50992009-01-30 23:59:18 +000010790 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
Nate Begeman2042aa52005-10-08 00:29:44 +000010791 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Bill Wendling31b50992009-01-30 23:59:18 +000010792
Nate Begeman2042aa52005-10-08 00:29:44 +000010793 // If we got a simplified select_cc node back from SimplifySelectCC, then
10794 // break it down into a new SETCC node, and a new SELECT node, and then return
10795 // the SELECT node, since we were called with a SELECT node.
Gabor Greiff304a7a2008-08-28 21:40:38 +000010796 if (SCC.getNode()) {
Nate Begeman2042aa52005-10-08 00:29:44 +000010797 // Check to see if we got a select_cc back (to turn into setcc/select).
10798 // Otherwise, just return whatever node we got back, like fabs.
10799 if (SCC.getOpcode() == ISD::SELECT_CC) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010800 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000010801 N0.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +000010802 SCC.getOperand(0), SCC.getOperand(1),
Bill Wendling31b50992009-01-30 23:59:18 +000010803 SCC.getOperand(4));
Gabor Greiff304a7a2008-08-28 21:40:38 +000010804 AddToWorkList(SETCC.getNode());
Matt Arsenaultd2f03322013-06-14 22:04:37 +000010805 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
10806 SCC.getOperand(2), SCC.getOperand(3), SETCC);
Nate Begeman2042aa52005-10-08 00:29:44 +000010807 }
Bill Wendling31b50992009-01-30 23:59:18 +000010808
Nate Begeman2042aa52005-10-08 00:29:44 +000010809 return SCC;
10810 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010811 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +000010812}
10813
Chris Lattner6c14c352005-10-18 06:04:22 +000010814/// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
10815/// are the two values being selected between, see if we can simplify the
Chris Lattner8f872d22006-05-27 00:43:02 +000010816/// select. Callers of this should assume that TheSelect is deleted if this
10817/// returns true. As such, they should return the appropriate thing (e.g. the
10818/// node) back to the top-level of the DAG combiner loop to avoid it being
10819/// looked at.
Scott Michelcf0da6c2009-02-17 22:15:04 +000010820bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010821 SDValue RHS) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000010822
Nadav Rotema49a02a2011-02-11 19:57:47 +000010823 // Cannot simplify select with vector condition
10824 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
10825
Chris Lattner6c14c352005-10-18 06:04:22 +000010826 // If this is a select from two identical things, try to pull the operation
10827 // through the select.
Chris Lattner254c4452010-09-21 15:46:59 +000010828 if (LHS.getOpcode() != RHS.getOpcode() ||
10829 !LHS.hasOneUse() || !RHS.hasOneUse())
10830 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000010831
Chris Lattner254c4452010-09-21 15:46:59 +000010832 // If this is a load and the token chain is identical, replace the select
10833 // of two loads with a load through a select of the address to load from.
10834 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
10835 // constants have been dropped into the constant pool.
10836 if (LHS.getOpcode() == ISD::LOAD) {
10837 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
10838 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
Wesley Peck527da1b2010-11-23 03:31:01 +000010839
Chris Lattner254c4452010-09-21 15:46:59 +000010840 // Token chains must be identical.
10841 if (LHS.getOperand(0) != RHS.getOperand(0) ||
Duncan Sands8651e9c2008-06-13 19:07:40 +000010842 // Do not let this transformation reduce the number of volatile loads.
Chris Lattner254c4452010-09-21 15:46:59 +000010843 LLD->isVolatile() || RLD->isVolatile() ||
10844 // If this is an EXTLOAD, the VT's must match.
10845 LLD->getMemoryVT() != RLD->getMemoryVT() ||
Duncan Sands12f3b3b2010-11-18 20:05:18 +000010846 // If this is an EXTLOAD, the kind of extension must match.
10847 (LLD->getExtensionType() != RLD->getExtensionType() &&
10848 // The only exception is if one of the extensions is anyext.
10849 LLD->getExtensionType() != ISD::EXTLOAD &&
10850 RLD->getExtensionType() != ISD::EXTLOAD) ||
Dan Gohmanba8735d2009-10-31 14:14:04 +000010851 // FIXME: this discards src value information. This is
10852 // over-conservative. It would be beneficial to be able to remember
Mon P Wangec57c812010-01-11 20:12:49 +000010853 // both potential memory locations. Since we are discarding
10854 // src value info, don't do the transformation if the memory
10855 // locations are not in the default address space.
Chris Lattner254c4452010-09-21 15:46:59 +000010856 LLD->getPointerInfo().getAddrSpace() != 0 ||
Pete Cooper10a3ae72013-02-12 03:14:50 +000010857 RLD->getPointerInfo().getAddrSpace() != 0 ||
10858 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
10859 LLD->getBasePtr().getValueType()))
Chris Lattner254c4452010-09-21 15:46:59 +000010860 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000010861
Chris Lattnere3267522010-09-21 15:58:55 +000010862 // Check that the select condition doesn't reach either load. If so,
10863 // folding this will induce a cycle into the DAG. If not, this is safe to
10864 // xform, so create a select of the addresses.
Chris Lattner254c4452010-09-21 15:46:59 +000010865 SDValue Addr;
10866 if (TheSelect->getOpcode() == ISD::SELECT) {
Chris Lattnere3267522010-09-21 15:58:55 +000010867 SDNode *CondNode = TheSelect->getOperand(0).getNode();
10868 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
10869 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
10870 return false;
Nadav Rotemd5f88592012-10-18 18:06:48 +000010871 // The loads must not depend on one another.
10872 if (LLD->isPredecessorOf(RLD) ||
10873 RLD->isPredecessorOf(LLD))
10874 return false;
Matt Arsenaultd2f03322013-06-14 22:04:37 +000010875 Addr = DAG.getSelect(SDLoc(TheSelect),
10876 LLD->getBasePtr().getValueType(),
10877 TheSelect->getOperand(0), LLD->getBasePtr(),
10878 RLD->getBasePtr());
Chris Lattner254c4452010-09-21 15:46:59 +000010879 } else { // Otherwise SELECT_CC
Chris Lattnere3267522010-09-21 15:58:55 +000010880 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
10881 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
10882
10883 if ((LLD->hasAnyUseOfValue(1) &&
10884 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
Chris Lattner1cc25e82012-03-27 16:27:21 +000010885 (RLD->hasAnyUseOfValue(1) &&
10886 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
Chris Lattnere3267522010-09-21 15:58:55 +000010887 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000010888
Andrew Trickef9de2a2013-05-25 02:42:55 +000010889 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
Chris Lattnere3267522010-09-21 15:58:55 +000010890 LLD->getBasePtr().getValueType(),
10891 TheSelect->getOperand(0),
10892 TheSelect->getOperand(1),
10893 LLD->getBasePtr(), RLD->getBasePtr(),
10894 TheSelect->getOperand(4));
Chris Lattner254c4452010-09-21 15:46:59 +000010895 }
10896
Chris Lattnere3267522010-09-21 15:58:55 +000010897 SDValue Load;
10898 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
10899 Load = DAG.getLoad(TheSelect->getValueType(0),
Andrew Trickef9de2a2013-05-25 02:42:55 +000010900 SDLoc(TheSelect),
Richard Sandiford39c1ce42013-10-28 11:17:59 +000010901 // FIXME: Discards pointer and TBAA info.
Chris Lattnere3267522010-09-21 15:58:55 +000010902 LLD->getChain(), Addr, MachinePointerInfo(),
10903 LLD->isVolatile(), LLD->isNonTemporal(),
Pete Cooper82cd9e82011-11-08 18:42:53 +000010904 LLD->isInvariant(), LLD->getAlignment());
Chris Lattnere3267522010-09-21 15:58:55 +000010905 } else {
Duncan Sandsc92331b2010-11-18 21:16:28 +000010906 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
10907 RLD->getExtensionType() : LLD->getExtensionType(),
Andrew Trickef9de2a2013-05-25 02:42:55 +000010908 SDLoc(TheSelect),
Stuart Hastings81c43062011-02-16 16:23:55 +000010909 TheSelect->getValueType(0),
Richard Sandiford39c1ce42013-10-28 11:17:59 +000010910 // FIXME: Discards pointer and TBAA info.
Chris Lattnere3267522010-09-21 15:58:55 +000010911 LLD->getChain(), Addr, MachinePointerInfo(),
10912 LLD->getMemoryVT(), LLD->isVolatile(),
10913 LLD->isNonTemporal(), LLD->getAlignment());
Chris Lattner6c14c352005-10-18 06:04:22 +000010914 }
Chris Lattnere3267522010-09-21 15:58:55 +000010915
10916 // Users of the select now use the result of the load.
10917 CombineTo(TheSelect, Load);
10918
10919 // Users of the old loads now use the new load's chain. We know the
10920 // old-load value is dead now.
10921 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
10922 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
10923 return true;
Chris Lattner6c14c352005-10-18 06:04:22 +000010924 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010925
Chris Lattner6c14c352005-10-18 06:04:22 +000010926 return false;
10927}
10928
Chris Lattner43d63772009-03-11 05:08:08 +000010929/// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
10930/// where 'cond' is the comparison specified by CC.
Andrew Trickef9de2a2013-05-25 02:42:55 +000010931SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010932 SDValue N2, SDValue N3,
10933 ISD::CondCode CC, bool NotExtCompare) {
Chris Lattner43d63772009-03-11 05:08:08 +000010934 // (x ? y : y) -> y.
10935 if (N2 == N3) return N2;
Wesley Peck527da1b2010-11-23 03:31:01 +000010936
Owen Anderson53aa7a92009-08-10 22:56:29 +000010937 EVT VT = N2.getValueType();
Gabor Greiff304a7a2008-08-28 21:40:38 +000010938 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
10939 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
10940 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000010941
10942 // Determine if the condition we're dealing with is constant
Matt Arsenault758659232013-05-18 00:21:46 +000010943 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
Dale Johannesenf1163e92009-02-03 00:47:48 +000010944 N0, N1, CC, DL, false);
Gabor Greiff304a7a2008-08-28 21:40:38 +000010945 if (SCC.getNode()) AddToWorkList(SCC.getNode());
10946 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000010947
10948 // fold select_cc true, x, y -> x
Dan Gohmanb72127a2008-03-13 22:13:53 +000010949 if (SCCC && !SCCC->isNullValue())
Nate Begeman2042aa52005-10-08 00:29:44 +000010950 return N2;
10951 // fold select_cc false, x, y -> y
Dan Gohmanb72127a2008-03-13 22:13:53 +000010952 if (SCCC && SCCC->isNullValue())
Nate Begeman2042aa52005-10-08 00:29:44 +000010953 return N3;
Scott Michelcf0da6c2009-02-17 22:15:04 +000010954
Nate Begeman2042aa52005-10-08 00:29:44 +000010955 // Check to see if we can simplify the select into an fabs node
10956 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
10957 // Allow either -0.0 or 0.0
Dale Johannesen2cfcf702007-08-25 22:10:57 +000010958 if (CFP->getValueAPF().isZero()) {
Nate Begeman2042aa52005-10-08 00:29:44 +000010959 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
10960 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
10961 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
10962 N2 == N3.getOperand(0))
Bill Wendling31b50992009-01-30 23:59:18 +000010963 return DAG.getNode(ISD::FABS, DL, VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +000010964
Nate Begeman2042aa52005-10-08 00:29:44 +000010965 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
10966 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
10967 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
10968 N2.getOperand(0) == N3)
Bill Wendling31b50992009-01-30 23:59:18 +000010969 return DAG.getNode(ISD::FABS, DL, VT, N3);
Nate Begeman2042aa52005-10-08 00:29:44 +000010970 }
10971 }
Wesley Peck527da1b2010-11-23 03:31:01 +000010972
Chris Lattner43d63772009-03-11 05:08:08 +000010973 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
10974 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
10975 // in it. This is a win when the constant is not otherwise available because
10976 // it replaces two constant pool loads with one. We only do this if the FP
10977 // type is known to be legal, because if it isn't, then we are before legalize
10978 // types an we want the other legalization to happen first (e.g. to avoid
Mon P Wangc8671562009-03-14 00:25:19 +000010979 // messing with soft float) and if the ConstantFP is not legal, because if
10980 // it is legal, we may not need to store the FP constant in a constant pool.
Chris Lattner43d63772009-03-11 05:08:08 +000010981 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
10982 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
10983 if (TLI.isTypeLegal(N2.getValueType()) &&
Mon P Wangc8671562009-03-14 00:25:19 +000010984 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
10985 TargetLowering::Legal) &&
Chris Lattner43d63772009-03-11 05:08:08 +000010986 // If both constants have multiple uses, then we won't need to do an
10987 // extra load, they are likely around in registers for other users.
10988 (TV->hasOneUse() || FV->hasOneUse())) {
10989 Constant *Elts[] = {
10990 const_cast<ConstantFP*>(FV->getConstantFPValue()),
10991 const_cast<ConstantFP*>(TV->getConstantFPValue())
10992 };
Chris Lattner229907c2011-07-18 04:54:35 +000010993 Type *FPTy = Elts[0]->getType();
Micah Villmowcdfe20b2012-10-08 16:38:25 +000010994 const DataLayout &TD = *TLI.getDataLayout();
Wesley Peck527da1b2010-11-23 03:31:01 +000010995
Chris Lattner43d63772009-03-11 05:08:08 +000010996 // Create a ConstantArray of the two constants.
Jay Foad83be3612011-06-22 09:24:39 +000010997 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
Chris Lattner43d63772009-03-11 05:08:08 +000010998 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
10999 TD.getPrefTypeAlignment(FPTy));
Evan Cheng1fb8aed2009-03-13 07:51:59 +000011000 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
Chris Lattner43d63772009-03-11 05:08:08 +000011001
11002 // Get the offsets to the 0 and 1 element of the array so that we can
11003 // select between them.
11004 SDValue Zero = DAG.getIntPtrConstant(0);
Duncan Sandsaf9eaa82009-05-09 07:06:46 +000011005 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
Chris Lattner43d63772009-03-11 05:08:08 +000011006 SDValue One = DAG.getIntPtrConstant(EltSize);
Wesley Peck527da1b2010-11-23 03:31:01 +000011007
Chris Lattner43d63772009-03-11 05:08:08 +000011008 SDValue Cond = DAG.getSetCC(DL,
Matt Arsenault758659232013-05-18 00:21:46 +000011009 getSetCCResultType(N0.getValueType()),
Chris Lattner43d63772009-03-11 05:08:08 +000011010 N0, N1, CC);
Dan Gohmane83e1b22011-09-22 23:01:29 +000011011 AddToWorkList(Cond.getNode());
Matt Arsenaultd2f03322013-06-14 22:04:37 +000011012 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
11013 Cond, One, Zero);
Dan Gohmane83e1b22011-09-22 23:01:29 +000011014 AddToWorkList(CstOffset.getNode());
Tom Stellard838e2342013-08-26 15:06:10 +000011015 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
Chris Lattner43d63772009-03-11 05:08:08 +000011016 CstOffset);
Dan Gohmane83e1b22011-09-22 23:01:29 +000011017 AddToWorkList(CPIdx.getNode());
Chris Lattner43d63772009-03-11 05:08:08 +000011018 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
Chris Lattnera35499e2010-09-21 07:32:19 +000011019 MachinePointerInfo::getConstantPool(), false,
Pete Cooper82cd9e82011-11-08 18:42:53 +000011020 false, false, Alignment);
Chris Lattner43d63772009-03-11 05:08:08 +000011021
11022 }
Wesley Peck527da1b2010-11-23 03:31:01 +000011023 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011024
Nate Begeman2042aa52005-10-08 00:29:44 +000011025 // Check to see if we can perform the "gzip trick", transforming
Bill Wendling31b50992009-01-30 23:59:18 +000011026 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
Chris Lattnerc8cd62d2006-09-20 06:41:35 +000011027 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
Dan Gohmanb72127a2008-03-13 22:13:53 +000011028 (N1C->isNullValue() || // (a < 0) ? b : 0
11029 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
Owen Anderson53aa7a92009-08-10 22:56:29 +000011030 EVT XType = N0.getValueType();
11031 EVT AType = N2.getValueType();
Duncan Sands11dd4242008-06-08 20:54:56 +000011032 if (XType.bitsGE(AType)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +000011033 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
Nate Begeman6828ed92005-10-10 21:26:48 +000011034 // single-bit constant.
Dan Gohmanb72127a2008-03-13 22:13:53 +000011035 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11036 unsigned ShCtV = N2C->getAPIntValue().logBase2();
Duncan Sands13237ac2008-06-06 12:08:01 +000011037 ShCtV = XType.getSizeInBits()-ShCtV-1;
Owen Andersonb2c80da2011-02-25 21:41:48 +000011038 SDValue ShCt = DAG.getConstant(ShCtV,
11039 getShiftAmountTy(N0.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000011040 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000011041 XType, N0, ShCt);
Gabor Greiff304a7a2008-08-28 21:40:38 +000011042 AddToWorkList(Shift.getNode());
Bill Wendling31b50992009-01-30 23:59:18 +000011043
Duncan Sands11dd4242008-06-08 20:54:56 +000011044 if (XType.bitsGT(AType)) {
Bill Wendling3b585af2009-01-31 03:12:48 +000011045 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
Gabor Greiff304a7a2008-08-28 21:40:38 +000011046 AddToWorkList(Shift.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000011047 }
Bill Wendling31b50992009-01-30 23:59:18 +000011048
11049 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
Nate Begeman2042aa52005-10-08 00:29:44 +000011050 }
Bill Wendling31b50992009-01-30 23:59:18 +000011051
Andrew Trickef9de2a2013-05-25 02:42:55 +000011052 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000011053 XType, N0,
11054 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000011055 getShiftAmountTy(N0.getValueType())));
Gabor Greiff304a7a2008-08-28 21:40:38 +000011056 AddToWorkList(Shift.getNode());
Bill Wendling31b50992009-01-30 23:59:18 +000011057
Duncan Sands11dd4242008-06-08 20:54:56 +000011058 if (XType.bitsGT(AType)) {
Bill Wendling3b585af2009-01-31 03:12:48 +000011059 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
Gabor Greiff304a7a2008-08-28 21:40:38 +000011060 AddToWorkList(Shift.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000011061 }
Bill Wendling31b50992009-01-30 23:59:18 +000011062
11063 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
Nate Begeman2042aa52005-10-08 00:29:44 +000011064 }
11065 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011066
Owen Anderson3231d132010-09-22 22:58:22 +000011067 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11068 // where y is has a single bit set.
11069 // A plaintext description would be, we can turn the SELECT_CC into an AND
11070 // when the condition can be materialized as an all-ones register. Any
11071 // single bit-test can be materialized as an all-ones register with
11072 // shift-left and shift-right-arith.
11073 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11074 N0->getValueType(0) == VT &&
Wesley Peck527da1b2010-11-23 03:31:01 +000011075 N1C && N1C->isNullValue() &&
Owen Anderson3231d132010-09-22 22:58:22 +000011076 N2C && N2C->isNullValue()) {
11077 SDValue AndLHS = N0->getOperand(0);
11078 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11079 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11080 // Shift the tested bit over the sign bit.
11081 APInt AndMask = ConstAndRHS->getAPIntValue();
11082 SDValue ShlAmt =
Owen Andersonb2c80da2011-02-25 21:41:48 +000011083 DAG.getConstant(AndMask.countLeadingZeros(),
11084 getShiftAmountTy(AndLHS.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000011085 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
Wesley Peck527da1b2010-11-23 03:31:01 +000011086
Owen Anderson3231d132010-09-22 22:58:22 +000011087 // Now arithmetic right shift it all the way over, so the result is either
11088 // all-ones, or zero.
11089 SDValue ShrAmt =
Owen Andersonb2c80da2011-02-25 21:41:48 +000011090 DAG.getConstant(AndMask.getBitWidth()-1,
11091 getShiftAmountTy(Shl.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000011092 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
Wesley Peck527da1b2010-11-23 03:31:01 +000011093
Owen Anderson3231d132010-09-22 22:58:22 +000011094 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11095 }
11096 }
11097
Nate Begeman6828ed92005-10-10 21:26:48 +000011098 // fold select C, 16, 0 -> shl C, 4
Dan Gohmanb72127a2008-03-13 22:13:53 +000011099 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
Duncan Sandsf2641e12011-09-06 19:07:46 +000011100 TLI.getBooleanContents(N0.getValueType().isVector()) ==
11101 TargetLowering::ZeroOrOneBooleanContent) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000011102
Chris Lattnera083ffc2007-04-11 06:50:51 +000011103 // If the caller doesn't want us to simplify this into a zext of a compare,
11104 // don't do it.
Dan Gohmanb72127a2008-03-13 22:13:53 +000011105 if (NotExtCompare && N2C->getAPIntValue() == 1)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011106 return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +000011107
Nate Begeman6828ed92005-10-10 21:26:48 +000011108 // Get a SetCC of the condition
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011109 // NOTE: Don't create a SETCC if it's not legal on this target.
11110 if (!LegalOperations ||
11111 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault758659232013-05-18 00:21:46 +000011112 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011113 SDValue Temp, SCC;
11114 // cast from setcc result type to select result type
11115 if (LegalTypes) {
Matt Arsenault758659232013-05-18 00:21:46 +000011116 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011117 N0, N1, CC);
11118 if (N2.getValueType().bitsLT(SCC.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +000011119 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011120 N2.getValueType());
11121 else
Andrew Trickef9de2a2013-05-25 02:42:55 +000011122 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011123 N2.getValueType(), SCC);
11124 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011125 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11126 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
Bill Wendling31b50992009-01-30 23:59:18 +000011127 N2.getValueType(), SCC);
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011128 }
11129
11130 AddToWorkList(SCC.getNode());
11131 AddToWorkList(Temp.getNode());
11132
11133 if (N2C->getAPIntValue() == 1)
11134 return Temp;
11135
11136 // shl setcc result by log2 n2c
Jack Carterd4e96152013-10-17 01:34:33 +000011137 return DAG.getNode(
11138 ISD::SHL, DL, N2.getValueType(), Temp,
11139 DAG.getConstant(N2C->getAPIntValue().logBase2(),
11140 getShiftAmountTy(Temp.getValueType())));
Nate Begemanabac6162006-02-18 02:40:58 +000011141 }
Nate Begeman6828ed92005-10-10 21:26:48 +000011142 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011143
Nate Begeman2042aa52005-10-08 00:29:44 +000011144 // Check to see if this is the equivalent of setcc
11145 // FIXME: Turn all of these into setcc if setcc if setcc is legal
11146 // otherwise, go ahead with the folds.
Dan Gohmanb72127a2008-03-13 22:13:53 +000011147 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000011148 EVT XType = N0.getValueType();
Duncan Sandsdc2dac12008-11-24 14:53:14 +000011149 if (!LegalOperations ||
Matt Arsenault758659232013-05-18 00:21:46 +000011150 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11151 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
Nate Begeman2042aa52005-10-08 00:29:44 +000011152 if (Res.getValueType() != VT)
Bill Wendling31b50992009-01-30 23:59:18 +000011153 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
Nate Begeman2042aa52005-10-08 00:29:44 +000011154 return Res;
11155 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011156
Bill Wendling31b50992009-01-30 23:59:18 +000011157 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
Scott Michelcf0da6c2009-02-17 22:15:04 +000011158 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +000011159 (!LegalOperations ||
Duncan Sandsb1bfff52008-06-14 17:48:34 +000011160 TLI.isOperationLegal(ISD::CTLZ, XType))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011161 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011162 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
Duncan Sands13237ac2008-06-06 12:08:01 +000011163 DAG.getConstant(Log2_32(XType.getSizeInBits()),
Owen Andersonb2c80da2011-02-25 21:41:48 +000011164 getShiftAmountTy(Ctlz.getValueType())));
Nate Begeman2042aa52005-10-08 00:29:44 +000011165 }
Bill Wendling31b50992009-01-30 23:59:18 +000011166 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
Scott Michelcf0da6c2009-02-17 22:15:04 +000011167 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011168 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000011169 XType, DAG.getConstant(0, XType), N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +000011170 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
Bill Wendling31b50992009-01-30 23:59:18 +000011171 return DAG.getNode(ISD::SRL, DL, XType,
Bill Wendlinga6c75ff2009-02-01 11:19:36 +000011172 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
Duncan Sands13237ac2008-06-06 12:08:01 +000011173 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000011174 getShiftAmountTy(XType)));
Nate Begeman2042aa52005-10-08 00:29:44 +000011175 }
Bill Wendling31b50992009-01-30 23:59:18 +000011176 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
Nate Begeman2042aa52005-10-08 00:29:44 +000011177 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011178 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
Bill Wendling31b50992009-01-30 23:59:18 +000011179 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000011180 getShiftAmountTy(N0.getValueType())));
Bill Wendling31b50992009-01-30 23:59:18 +000011181 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
Nate Begeman2042aa52005-10-08 00:29:44 +000011182 }
11183 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011184
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011185 // Check to see if this is an integer abs.
11186 // select_cc setg[te] X, 0, X, -X ->
11187 // select_cc setgt X, -1, X, -X ->
11188 // select_cc setl[te] X, 0, -X, X ->
11189 // select_cc setlt X, 1, -X, X ->
Nate Begeman2042aa52005-10-08 00:29:44 +000011190 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011191 if (N1C) {
Craig Topperc0196b12014-04-14 00:51:57 +000011192 ConstantSDNode *SubC = nullptr;
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011193 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11194 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11195 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11196 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11197 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11198 (N1C->isOne() && CC == ISD::SETLT)) &&
11199 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11200 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11201
Owen Anderson53aa7a92009-08-10 22:56:29 +000011202 EVT XType = N0.getValueType();
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011203 if (SubC && SubC->isNullValue() && XType.isInteger()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011204 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011205 N0,
11206 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000011207 getShiftAmountTy(N0.getValueType())));
Andrew Trickef9de2a2013-05-25 02:42:55 +000011208 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000011209 XType, N0, Shift);
11210 AddToWorkList(Shift.getNode());
11211 AddToWorkList(Add.getNode());
11212 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
Nate Begeman2042aa52005-10-08 00:29:44 +000011213 }
11214 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011215
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011216 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +000011217}
11218
Evan Cheng92658d52007-02-08 22:13:59 +000011219/// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
Owen Anderson53aa7a92009-08-10 22:56:29 +000011220SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011221 SDValue N1, ISD::CondCode Cond,
Andrew Trickef9de2a2013-05-25 02:42:55 +000011222 SDLoc DL, bool foldBooleans) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000011223 TargetLowering::DAGCombinerInfo
Nadav Rotemb1dd5242012-12-27 06:47:41 +000011224 DagCombineInfo(DAG, Level, false, this);
Dale Johannesenf1163e92009-02-03 00:47:48 +000011225 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
Nate Begeman24a7eca2005-09-16 00:54:12 +000011226}
11227
Nate Begemanc6f067a2005-10-20 02:15:44 +000011228/// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
11229/// return a DAG expression to select that will generate the same value by
11230/// multiplying by a magic number. See:
11231/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011232SDValue DAGCombiner::BuildSDIV(SDNode *N) {
Andrew Lenharth0e57b2c2006-06-12 16:07:18 +000011233 std::vector<SDNode*> Built;
Richard Osborne561fac42011-11-07 17:09:05 +000011234 SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, &Built);
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000011235
Andrew Lenharth0e57b2c2006-06-12 16:07:18 +000011236 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000011237 ii != ee; ++ii)
11238 AddToWorkList(*ii);
11239 return S;
Nate Begemanc6f067a2005-10-20 02:15:44 +000011240}
11241
11242/// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
11243/// return a DAG expression to select that will generate the same value by
11244/// multiplying by a magic number. See:
11245/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011246SDValue DAGCombiner::BuildUDIV(SDNode *N) {
Andrew Lenharth0e57b2c2006-06-12 16:07:18 +000011247 std::vector<SDNode*> Built;
Richard Osborne561fac42011-11-07 17:09:05 +000011248 SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, &Built);
Nate Begemanc6f067a2005-10-20 02:15:44 +000011249
Andrew Lenharth0e57b2c2006-06-12 16:07:18 +000011250 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000011251 ii != ee; ++ii)
11252 AddToWorkList(*ii);
11253 return S;
Nate Begemanc6f067a2005-10-20 02:15:44 +000011254}
11255
Nate Begeman18150d52009-09-25 06:05:26 +000011256/// FindBaseOffset - Return true if base is a frame index, which is known not
Eric Christopherd9e8eac2010-12-09 04:48:06 +000011257// to alias with anything but itself. Provides base object and offset as
11258// results.
Nate Begeman18150d52009-09-25 06:05:26 +000011259static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
Roman Divacky93383442012-09-05 22:15:49 +000011260 const GlobalValue *&GV, const void *&CV) {
Jim Laskey0463e082006-10-07 23:37:56 +000011261 // Assume it is a primitive operation.
Craig Topperc0196b12014-04-14 00:51:57 +000011262 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011263
Jim Laskey0463e082006-10-07 23:37:56 +000011264 // If it's an adding a simple constant then integrate the offset.
11265 if (Base.getOpcode() == ISD::ADD) {
11266 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11267 Base = Base.getOperand(0);
Dan Gohmaneffb8942008-09-12 16:56:44 +000011268 Offset += C->getZExtValue();
Jim Laskey0463e082006-10-07 23:37:56 +000011269 }
11270 }
Wesley Peck527da1b2010-11-23 03:31:01 +000011271
Nate Begeman18150d52009-09-25 06:05:26 +000011272 // Return the underlying GlobalValue, and update the Offset. Return false
11273 // for GlobalAddressSDNode since the same GlobalAddress may be represented
11274 // by multiple nodes with different offsets.
11275 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11276 GV = G->getGlobal();
11277 Offset += G->getOffset();
11278 return false;
11279 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011280
Nate Begeman18150d52009-09-25 06:05:26 +000011281 // Return the underlying Constant value, and update the Offset. Return false
11282 // for ConstantSDNodes since the same constant pool entry may be represented
11283 // by multiple nodes with different offsets.
11284 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
Roman Divacky93383442012-09-05 22:15:49 +000011285 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11286 : (const void *)C->getConstVal();
Nate Begeman18150d52009-09-25 06:05:26 +000011287 Offset += C->getOffset();
11288 return false;
11289 }
Jim Laskey0463e082006-10-07 23:37:56 +000011290 // If it's any of the following then it can't alias with anything but itself.
Nate Begeman18150d52009-09-25 06:05:26 +000011291 return isa<FrameIndexSDNode>(Base);
Jim Laskey0463e082006-10-07 23:37:56 +000011292}
11293
11294/// isAlias - Return true if there is any possibility that the two addresses
11295/// overlap.
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011296bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1, bool IsVolatile1,
Jim Laskeya15b0eb2006-10-18 12:29:57 +000011297 const Value *SrcValue1, int SrcValueOffset1,
Nate Begeman879d8f12009-09-15 00:18:30 +000011298 unsigned SrcValueAlign1,
Dan Gohmana94cc6d2010-10-20 00:31:05 +000011299 const MDNode *TBAAInfo1,
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011300 SDValue Ptr2, int64_t Size2, bool IsVolatile2,
Nate Begeman879d8f12009-09-15 00:18:30 +000011301 const Value *SrcValue2, int SrcValueOffset2,
Dan Gohmana94cc6d2010-10-20 00:31:05 +000011302 unsigned SrcValueAlign2,
11303 const MDNode *TBAAInfo2) const {
Jim Laskey0463e082006-10-07 23:37:56 +000011304 // If they are the same then they must be aliases.
11305 if (Ptr1 == Ptr2) return true;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011306
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011307 // If they are both volatile then they cannot be reordered.
11308 if (IsVolatile1 && IsVolatile2) return true;
11309
Jim Laskey0463e082006-10-07 23:37:56 +000011310 // Gather base node and offset information.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011311 SDValue Base1, Base2;
Jim Laskey0463e082006-10-07 23:37:56 +000011312 int64_t Offset1, Offset2;
Dan Gohmanbcaf6812010-04-15 01:51:59 +000011313 const GlobalValue *GV1, *GV2;
Roman Divacky93383442012-09-05 22:15:49 +000011314 const void *CV1, *CV2;
Nate Begeman18150d52009-09-25 06:05:26 +000011315 bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1);
11316 bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011317
Nate Begeman18150d52009-09-25 06:05:26 +000011318 // If they have a same base address then check to see if they overlap.
11319 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
Bill Wendling31b50992009-01-30 23:59:18 +000011320 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011321
Owen Anderson272ff942010-09-20 20:39:59 +000011322 // It is possible for different frame indices to alias each other, mostly
11323 // when tail call optimization reuses return address slots for arguments.
11324 // To catch this case, look up the actual index of frame indices to compute
11325 // the real alias relationship.
11326 if (isFrameIndex1 && isFrameIndex2) {
11327 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11328 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11329 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
11330 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
11331 }
11332
Wesley Peck527da1b2010-11-23 03:31:01 +000011333 // Otherwise, if we know what the bases are, and they aren't identical, then
Owen Anderson272ff942010-09-20 20:39:59 +000011334 // we know they cannot alias.
Nate Begeman18150d52009-09-25 06:05:26 +000011335 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11336 return false;
Jim Laskeya15b0eb2006-10-18 12:29:57 +000011337
Nate Begeman879d8f12009-09-15 00:18:30 +000011338 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11339 // compared to the size and offset of the access, we may be able to prove they
11340 // do not alias. This check is conservative for now to catch cases created by
11341 // splitting vector types.
11342 if ((SrcValueAlign1 == SrcValueAlign2) &&
11343 (SrcValueOffset1 != SrcValueOffset2) &&
11344 (Size1 == Size2) && (SrcValueAlign1 > Size1)) {
11345 int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1;
11346 int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1;
Wesley Peck527da1b2010-11-23 03:31:01 +000011347
Nate Begeman879d8f12009-09-15 00:18:30 +000011348 // There is no overlap between these relatively aligned accesses of similar
11349 // size, return no alias.
11350 if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1)
11351 return false;
11352 }
Wesley Peck527da1b2010-11-23 03:31:01 +000011353
Hal Finkel5ef4dcc2013-08-29 03:29:55 +000011354 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11355 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +000011356#ifndef NDEBUG
11357 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11358 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11359 UseAA = false;
11360#endif
Hal Finkel31658832013-09-15 02:19:49 +000011361 if (UseAA && SrcValue1 && SrcValue2) {
Jim Laskey55e4dca2006-10-18 19:08:31 +000011362 // Use alias analysis information.
Dan Gohman9625d812007-08-27 16:32:11 +000011363 int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
11364 int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
11365 int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011366 AliasAnalysis::AliasResult AAResult =
Hal Finkeldbebb522014-01-25 19:24:54 +000011367 AA.alias(AliasAnalysis::Location(SrcValue1, Overlap1,
Craig Topperc0196b12014-04-14 00:51:57 +000011368 UseTBAA ? TBAAInfo1 : nullptr),
Hal Finkeldbebb522014-01-25 19:24:54 +000011369 AliasAnalysis::Location(SrcValue2, Overlap2,
Craig Topperc0196b12014-04-14 00:51:57 +000011370 UseTBAA ? TBAAInfo2 : nullptr));
Jim Laskey55e4dca2006-10-18 19:08:31 +000011371 if (AAResult == AliasAnalysis::NoAlias)
11372 return false;
11373 }
Jim Laskeya15b0eb2006-10-18 12:29:57 +000011374
11375 // Otherwise we have to assume they alias.
11376 return true;
Jim Laskey0463e082006-10-07 23:37:56 +000011377}
11378
Nadav Rotem307d7672012-11-29 00:00:08 +000011379bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) {
11380 SDValue Ptr0, Ptr1;
11381 int64_t Size0, Size1;
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011382 bool IsVolatile0, IsVolatile1;
Nadav Rotem307d7672012-11-29 00:00:08 +000011383 const Value *SrcValue0, *SrcValue1;
11384 int SrcValueOffset0, SrcValueOffset1;
11385 unsigned SrcValueAlign0, SrcValueAlign1;
11386 const MDNode *SrcTBAAInfo0, *SrcTBAAInfo1;
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011387 FindAliasInfo(Op0, Ptr0, Size0, IsVolatile0, SrcValue0, SrcValueOffset0,
Nadav Rotem307d7672012-11-29 00:00:08 +000011388 SrcValueAlign0, SrcTBAAInfo0);
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011389 FindAliasInfo(Op1, Ptr1, Size1, IsVolatile1, SrcValue1, SrcValueOffset1,
Nadav Rotem307d7672012-11-29 00:00:08 +000011390 SrcValueAlign1, SrcTBAAInfo1);
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011391 return isAlias(Ptr0, Size0, IsVolatile0, SrcValue0, SrcValueOffset0,
Nadav Rotemac450eb2012-12-06 17:34:13 +000011392 SrcValueAlign0, SrcTBAAInfo0,
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011393 Ptr1, Size1, IsVolatile1, SrcValue1, SrcValueOffset1,
Nadav Rotemac450eb2012-12-06 17:34:13 +000011394 SrcValueAlign1, SrcTBAAInfo1);
Nadav Rotem307d7672012-11-29 00:00:08 +000011395}
11396
Jim Laskey0463e082006-10-07 23:37:56 +000011397/// FindAliasInfo - Extracts the relevant alias information from the memory
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011398/// node. Returns true if the operand was a nonvolatile load.
Jim Laskey08edf332006-10-11 13:47:09 +000011399bool DAGCombiner::FindAliasInfo(SDNode *N,
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011400 SDValue &Ptr, int64_t &Size, bool &IsVolatile,
Benjamin Kramer5a377e22012-01-15 11:50:43 +000011401 const Value *&SrcValue,
11402 int &SrcValueOffset,
11403 unsigned &SrcValueAlign,
11404 const MDNode *&TBAAInfo) const {
11405 LSBaseSDNode *LS = cast<LSBaseSDNode>(N);
11406
11407 Ptr = LS->getBasePtr();
11408 Size = LS->getMemoryVT().getSizeInBits() >> 3;
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011409 IsVolatile = LS->isVolatile();
Benjamin Kramer5a377e22012-01-15 11:50:43 +000011410 SrcValue = LS->getSrcValue();
11411 SrcValueOffset = LS->getSrcValueOffset();
11412 SrcValueAlign = LS->getOriginalAlignment();
11413 TBAAInfo = LS->getTBAAInfo();
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011414 return isa<LoadSDNode>(LS) && !IsVolatile;
Jim Laskey0463e082006-10-07 23:37:56 +000011415}
11416
Jim Laskey708d0db2006-10-04 16:53:27 +000011417/// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11418/// looking for aliasing nodes and adding them to the Aliases vector.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011419void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
Craig Topperb94011f2013-07-14 04:42:23 +000011420 SmallVectorImpl<SDValue> &Aliases) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011421 SmallVector<SDValue, 8> Chains; // List of chains to visit.
Nate Begeman879d8f12009-09-15 00:18:30 +000011422 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
Scott Michelcf0da6c2009-02-17 22:15:04 +000011423
Jim Laskeyd07be232006-09-25 16:29:54 +000011424 // Get alias information for node.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011425 SDValue Ptr;
Nate Begeman879d8f12009-09-15 00:18:30 +000011426 int64_t Size;
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011427 bool IsVolatile;
Nate Begeman879d8f12009-09-15 00:18:30 +000011428 const Value *SrcValue;
11429 int SrcValueOffset;
11430 unsigned SrcValueAlign;
Dan Gohmana94cc6d2010-10-20 00:31:05 +000011431 const MDNode *SrcTBAAInfo;
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011432 bool IsLoad = FindAliasInfo(N, Ptr, Size, IsVolatile, SrcValue,
11433 SrcValueOffset, SrcValueAlign, SrcTBAAInfo);
Jim Laskeyd07be232006-09-25 16:29:54 +000011434
Jim Laskey708d0db2006-10-04 16:53:27 +000011435 // Starting off.
Jim Laskey6549d222006-10-05 15:07:25 +000011436 Chains.push_back(OriginalChain);
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011437 unsigned Depth = 0;
Wesley Peck527da1b2010-11-23 03:31:01 +000011438
Jim Laskey6549d222006-10-05 15:07:25 +000011439 // Look at each chain and determine if it is an alias. If so, add it to the
11440 // aliases list. If not, then continue up the chain looking for the next
Scott Michelcf0da6c2009-02-17 22:15:04 +000011441 // candidate.
Jim Laskey6549d222006-10-05 15:07:25 +000011442 while (!Chains.empty()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011443 SDValue Chain = Chains.back();
Jim Laskey6549d222006-10-05 15:07:25 +000011444 Chains.pop_back();
Wesley Peck527da1b2010-11-23 03:31:01 +000011445
11446 // For TokenFactor nodes, look at each operand and only continue up the
11447 // chain until we find two aliases. If we've seen two aliases, assume we'll
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011448 // find more and revert to original chain since the xform is unlikely to be
11449 // profitable.
Wesley Peck527da1b2010-11-23 03:31:01 +000011450 //
11451 // FIXME: The depth check could be made to return the last non-aliasing
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011452 // chain we found before we hit a tokenfactor rather than the original
11453 // chain.
11454 if (Depth > 6 || Aliases.size() == 2) {
11455 Aliases.clear();
11456 Aliases.push_back(OriginalChain);
Hal Finkel51a98382014-01-24 20:12:02 +000011457 return;
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011458 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011459
Nate Begeman879d8f12009-09-15 00:18:30 +000011460 // Don't bother if we've been before.
11461 if (!Visited.insert(Chain.getNode()))
11462 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011463
Jim Laskey6549d222006-10-05 15:07:25 +000011464 switch (Chain.getOpcode()) {
11465 case ISD::EntryToken:
11466 // Entry token is ideal chain operand, but handled in FindBetterChain.
11467 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011468
Jim Laskey6549d222006-10-05 15:07:25 +000011469 case ISD::LOAD:
11470 case ISD::STORE: {
11471 // Get alias information for Chain.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011472 SDValue OpPtr;
Nate Begeman879d8f12009-09-15 00:18:30 +000011473 int64_t OpSize;
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011474 bool OpIsVolatile;
Nate Begeman879d8f12009-09-15 00:18:30 +000011475 const Value *OpSrcValue;
11476 int OpSrcValueOffset;
11477 unsigned OpSrcValueAlign;
Dan Gohmana94cc6d2010-10-20 00:31:05 +000011478 const MDNode *OpSrcTBAAInfo;
Gabor Greiff304a7a2008-08-28 21:40:38 +000011479 bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011480 OpIsVolatile, OpSrcValue, OpSrcValueOffset,
Dan Gohmana94cc6d2010-10-20 00:31:05 +000011481 OpSrcValueAlign,
11482 OpSrcTBAAInfo);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011483
Jim Laskey6549d222006-10-05 15:07:25 +000011484 // If chain is alias then stop here.
11485 if (!(IsLoad && IsOpLoad) &&
Richard Sandiford981fdeb2013-10-28 12:00:00 +000011486 isAlias(Ptr, Size, IsVolatile, SrcValue, SrcValueOffset,
11487 SrcValueAlign, SrcTBAAInfo,
11488 OpPtr, OpSize, OpIsVolatile, OpSrcValue, OpSrcValueOffset,
Dan Gohmana94cc6d2010-10-20 00:31:05 +000011489 OpSrcValueAlign, OpSrcTBAAInfo)) {
Jim Laskey6549d222006-10-05 15:07:25 +000011490 Aliases.push_back(Chain);
11491 } else {
11492 // Look further up the chain.
Scott Michelcf0da6c2009-02-17 22:15:04 +000011493 Chains.push_back(Chain.getOperand(0));
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011494 ++Depth;
Jim Laskeyd07be232006-09-25 16:29:54 +000011495 }
Jim Laskey6549d222006-10-05 15:07:25 +000011496 break;
11497 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011498
Jim Laskey6549d222006-10-05 15:07:25 +000011499 case ISD::TokenFactor:
Nate Begeman879d8f12009-09-15 00:18:30 +000011500 // We have to check each of the operands of the token factor for "small"
11501 // token factors, so we queue them up. Adding the operands to the queue
11502 // (stack) in reverse order maintains the original order and increases the
11503 // likelihood that getNode will find a matching token factor (CSE.)
11504 if (Chain.getNumOperands() > 16) {
11505 Aliases.push_back(Chain);
11506 break;
11507 }
Jim Laskey6549d222006-10-05 15:07:25 +000011508 for (unsigned n = Chain.getNumOperands(); n;)
11509 Chains.push_back(Chain.getOperand(--n));
Nate Begemana3ed9ed2009-10-12 05:53:58 +000011510 ++Depth;
Jim Laskey6549d222006-10-05 15:07:25 +000011511 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011512
Jim Laskey6549d222006-10-05 15:07:25 +000011513 default:
11514 // For all other instructions we will just have to take what we can get.
11515 Aliases.push_back(Chain);
11516 break;
Jim Laskeyd07be232006-09-25 16:29:54 +000011517 }
11518 }
Hal Finkel51a98382014-01-24 20:12:02 +000011519
11520 // We need to be careful here to also search for aliases through the
11521 // value operand of a store, etc. Consider the following situation:
11522 // Token1 = ...
11523 // L1 = load Token1, %52
11524 // S1 = store Token1, L1, %51
11525 // L2 = load Token1, %52+8
11526 // S2 = store Token1, L2, %51+8
11527 // Token2 = Token(S1, S2)
11528 // L3 = load Token2, %53
11529 // S3 = store Token2, L3, %52
11530 // L4 = load Token2, %53+8
11531 // S4 = store Token2, L4, %52+8
11532 // If we search for aliases of S3 (which loads address %52), and we look
11533 // only through the chain, then we'll miss the trivial dependence on L1
11534 // (which also loads from %52). We then might change all loads and
11535 // stores to use Token1 as their chain operand, which could result in
11536 // copying %53 into %52 before copying %52 into %51 (which should
11537 // happen first).
11538 //
11539 // The problem is, however, that searching for such data dependencies
11540 // can become expensive, and the cost is not directly related to the
11541 // chain depth. Instead, we'll rule out such configurations here by
11542 // insisting that we've visited all chain users (except for users
11543 // of the original chain, which is not necessary). When doing this,
11544 // we need to look through nodes we don't care about (otherwise, things
11545 // like register copies will interfere with trivial cases).
11546
11547 SmallVector<const SDNode *, 16> Worklist;
11548 for (SmallPtrSet<SDNode *, 16>::iterator I = Visited.begin(),
11549 IE = Visited.end(); I != IE; ++I)
11550 if (*I != OriginalChain.getNode())
11551 Worklist.push_back(*I);
11552
11553 while (!Worklist.empty()) {
11554 const SDNode *M = Worklist.pop_back_val();
11555
11556 // We have already visited M, and want to make sure we've visited any uses
11557 // of M that we care about. For uses that we've not visisted, and don't
11558 // care about, queue them to the worklist.
11559
11560 for (SDNode::use_iterator UI = M->use_begin(),
11561 UIE = M->use_end(); UI != UIE; ++UI)
11562 if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11563 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11564 // We've not visited this use, and we care about it (it could have an
11565 // ordering dependency with the original node).
11566 Aliases.clear();
11567 Aliases.push_back(OriginalChain);
11568 return;
11569 }
11570
11571 // We've not visited this use, but we don't care about it. Mark it as
11572 // visited and enqueue it to the worklist.
11573 Worklist.push_back(*UI);
11574 }
11575 }
Jim Laskey708d0db2006-10-04 16:53:27 +000011576}
11577
11578/// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11579/// for a better chain (aliasing node.)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011580SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11581 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +000011582
Jim Laskey708d0db2006-10-04 16:53:27 +000011583 // Accumulate all the aliases to this node.
11584 GatherAllAliases(N, OldChain, Aliases);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011585
Dan Gohman4298df62011-05-17 22:20:36 +000011586 // If no operands then chain to entry token.
11587 if (Aliases.size() == 0)
Jim Laskey708d0db2006-10-04 16:53:27 +000011588 return DAG.getEntryNode();
Dan Gohman4298df62011-05-17 22:20:36 +000011589
11590 // If a single operand then chain to it. We don't need to revisit it.
11591 if (Aliases.size() == 1)
Jim Laskey708d0db2006-10-04 16:53:27 +000011592 return Aliases[0];
Wesley Peck527da1b2010-11-23 03:31:01 +000011593
Jim Laskey708d0db2006-10-04 16:53:27 +000011594 // Construct a custom tailored token factor.
Andrew Trickef9de2a2013-05-25 02:42:55 +000011595 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
Nate Begeman879d8f12009-09-15 00:18:30 +000011596 &Aliases[0], Aliases.size());
Jim Laskeyd07be232006-09-25 16:29:54 +000011597}
11598
Nate Begeman21158fc2005-09-01 00:19:25 +000011599// SelectionDAG::Combine - This is the entry point for the file.
11600//
Bill Wendling084669a2009-04-29 00:15:41 +000011601void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
Bill Wendling026e5d72009-04-29 23:29:43 +000011602 CodeGenOpt::Level OptLevel) {
Nate Begeman21158fc2005-09-01 00:19:25 +000011603 /// run - This is the main entry point to this class.
11604 ///
Bill Wendling084669a2009-04-29 00:15:41 +000011605 DAGCombiner(*this, AA, OptLevel).Run(Level);
Nate Begeman21158fc2005-09-01 00:19:25 +000011606}