blob: 7347111728e1062121efb5c707ef56938d57841b [file] [log] [blame]
Nate Begeman2504fe22005-09-01 23:24:04 +00001//===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
Nate Begeman21158fc2005-09-01 00:19:25 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Nate Begeman21158fc2005-09-01 00:19:25 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This pass combines dag nodes to form fewer, simpler DAG nodes. It can be run
11// both before and after the DAG is legalized.
Scott Michelcf0da6c2009-02-17 22:15:04 +000012//
Dan Gohman45399872009-04-25 17:09:45 +000013// This pass is not a substitute for the LLVM IR instcombine pass. This pass is
14// primarily intended to handle simplification opportunities that are implicit
15// in the LLVM IR and exposed by the various codegen lowering phases.
16//
Nate Begeman21158fc2005-09-01 00:19:25 +000017//===----------------------------------------------------------------------===//
18
Nate Begeman21158fc2005-09-01 00:19:25 +000019#include "llvm/CodeGen/SelectionDAG.h"
Chandler Carruthdaa1ff92014-10-05 19:14:34 +000020#include "llvm/ADT/SmallBitVector.h"
Chris Lattner48fb92f2007-05-16 06:37:59 +000021#include "llvm/ADT/SmallPtrSet.h"
Chandler Carruth9a0051c2014-07-23 07:08:53 +000022#include "llvm/ADT/SetVector.h"
Chris Lattner48fb92f2007-05-16 06:37:59 +000023#include "llvm/ADT/Statistic.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000024#include "llvm/Analysis/AliasAnalysis.h"
25#include "llvm/CodeGen/MachineFrameInfo.h"
26#include "llvm/CodeGen/MachineFunction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/DataLayout.h"
28#include "llvm/IR/DerivedTypes.h"
29#include "llvm/IR/Function.h"
30#include "llvm/IR/LLVMContext.h"
Jim Laskey5d19d592006-09-21 16:28:59 +000031#include "llvm/Support/CommandLine.h"
Chris Lattner48fb92f2007-05-16 06:37:59 +000032#include "llvm/Support/Debug.h"
Torok Edwinccb29cd2009-07-11 13:10:19 +000033#include "llvm/Support/ErrorHandling.h"
Chris Lattner48fb92f2007-05-16 06:37:59 +000034#include "llvm/Support/MathExtras.h"
Chris Lattner4dc3edd2009-08-23 06:35:02 +000035#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000036#include "llvm/Target/TargetLowering.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000037#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
Chandler Carruth1b9dde02014-04-22 02:02:50 +000043#define DEBUG_TYPE "dagcombine"
44
Chris Lattneraee775a2006-12-19 22:41:21 +000045STATISTIC(NodesCombined , "Number of dag nodes combined");
46STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
47STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
Evan Chenga9cda8a2009-05-28 00:35:15 +000048STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
Evan Chengd42641c2011-02-02 01:06:55 +000049STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int");
Quentin Colombetde0e0622013-10-11 18:29:42 +000050STATISTIC(SlicedLoads, "Number of load sliced");
Chris Lattneraee775a2006-12-19 22:41:21 +000051
Nate Begeman21158fc2005-09-01 00:19:25 +000052namespace {
Jim Laskey0463e082006-10-07 23:37:56 +000053 static cl::opt<bool>
Owen Anderson7b8d2ae2010-09-19 21:01:26 +000054 CombinerAA("combiner-alias-analysis", cl::Hidden,
Hal Finkel5fb07342014-01-25 17:32:37 +000055 cl::desc("Enable DAG combiner alias-analysis heuristics"));
Jim Laskeydf2ccc32006-10-12 15:22:24 +000056
Jim Laskey55e4dca2006-10-18 19:08:31 +000057 static cl::opt<bool>
58 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
Hal Finkel5fb07342014-01-25 17:32:37 +000059 cl::desc("Enable DAG combiner's use of IR alias analysis"));
Jim Laskey55e4dca2006-10-18 19:08:31 +000060
Hal Finkeldbebb522014-01-25 19:24:54 +000061 static cl::opt<bool>
Hal Finkel3b48d082014-04-12 01:26:00 +000062 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
Hal Finkeldbebb522014-01-25 19:24:54 +000063 cl::desc("Enable DAG combiner's use of TBAA"));
64
Hal Finkel9b2617a2014-01-25 17:32:39 +000065#ifndef NDEBUG
66 static cl::opt<std::string>
67 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
68 cl::desc("Only use DAG-combiner alias analysis in this"
69 " function"));
70#endif
71
Quentin Colombetde0e0622013-10-11 18:29:42 +000072 /// Hidden option to stress test load slicing, i.e., when this option
73 /// is enabled, load slicing bypasses most of its profitability guards.
74 static cl::opt<bool>
75 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
76 cl::desc("Bypass the profitability model of load "
77 "slicing"),
78 cl::init(false));
79
Hal Finkel51e6fa22014-09-02 06:24:04 +000080 static cl::opt<bool>
81 MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
82 cl::desc("DAG combiner may split indexing from loads"));
83
Jim Laskey6549d222006-10-05 15:07:25 +000084//------------------------------ DAGCombiner ---------------------------------//
85
Nick Lewycky02d5f772009-10-25 06:33:48 +000086 class DAGCombiner {
Nate Begeman21158fc2005-09-01 00:19:25 +000087 SelectionDAG &DAG;
Dan Gohman619ef482009-01-15 19:20:50 +000088 const TargetLowering &TLI;
Duncan Sandsdc2dac12008-11-24 14:53:14 +000089 CombineLevel Level;
Bill Wendling026e5d72009-04-29 23:29:43 +000090 CodeGenOpt::Level OptLevel;
Duncan Sandsdc2dac12008-11-24 14:53:14 +000091 bool LegalOperations;
92 bool LegalTypes;
Quentin Colombetde0e0622013-10-11 18:29:42 +000093 bool ForCodeSize;
Nate Begeman21158fc2005-09-01 00:19:25 +000094
Chandler Carruth9a0051c2014-07-23 07:08:53 +000095 /// \brief Worklist of all of the nodes that need to be simplified.
96 ///
97 /// This must behave as a stack -- new nodes to process are pushed onto the
98 /// back and when processing we pop off of the back.
99 ///
100 /// The worklist will not contain duplicates but may contain null entries
101 /// due to nodes being deleted from the underlying DAG.
102 SmallVector<SDNode *, 64> Worklist;
103
104 /// \brief Mapping from an SDNode to its position on the worklist.
105 ///
106 /// This is used to find and remove nodes from the worklist (by nulling
107 /// them) when they are deleted from the underlying DAG. It relies on
108 /// stable indices of nodes within the worklist.
109 DenseMap<SDNode *, unsigned> WorklistMap;
Nate Begeman21158fc2005-09-01 00:19:25 +0000110
Chandler Carruth9f4530b2014-07-24 22:15:28 +0000111 /// \brief Set of nodes which have been combined (at least once).
112 ///
113 /// This is used to allow us to reliably add any operands of a DAG node
114 /// which have not yet been combined to the worklist.
115 SmallPtrSet<SDNode *, 64> CombinedNodes;
116
Jim Laskeydcb2b832006-10-16 20:52:31 +0000117 // AA - Used for DAG load/store alias analysis.
118 AliasAnalysis &AA;
119
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000120 /// When an instruction is simplified, add all users of the instruction to
121 /// the work lists because they might get more simplified now.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000122 void AddUsersToWorklist(SDNode *N) {
Jim Grosbache8160032014-04-11 01:13:13 +0000123 for (SDNode *Node : N->uses())
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000124 AddToWorklist(Node);
Nate Begeman21158fc2005-09-01 00:19:25 +0000125 }
126
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000127 /// Call the node-specific routine that folds each particular type of node.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000128 SDValue visit(SDNode *N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +0000129
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000130 public:
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000131 /// Add to the worklist making sure its instance is at the back (next to be
132 /// processed.)
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000133 void AddToWorklist(SDNode *N) {
Chandler Carruth24ceb0c2014-07-21 08:32:31 +0000134 // Skip handle nodes as they can't usefully be combined and confuse the
135 // zero-use deletion strategy.
136 if (N->getOpcode() == ISD::HANDLENODE)
137 return;
138
Chandler Carruth9a0051c2014-07-23 07:08:53 +0000139 if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
140 Worklist.push_back(N);
Chris Lattnerfbcd62d2006-03-01 04:03:14 +0000141 }
Jim Laskey708d0db2006-10-04 16:53:27 +0000142
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000143 /// Remove all instances of N from the worklist.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000144 void removeFromWorklist(SDNode *N) {
Chandler Carruth9f4530b2014-07-24 22:15:28 +0000145 CombinedNodes.erase(N);
146
Chandler Carruth9a0051c2014-07-23 07:08:53 +0000147 auto It = WorklistMap.find(N);
148 if (It == WorklistMap.end())
149 return; // Not in the worklist.
150
151 // Null out the entry rather than erasing it to avoid a linear operation.
152 Worklist[It->second] = nullptr;
153 WorklistMap.erase(It);
Chris Lattnere260ed82005-10-10 22:04:48 +0000154 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000155
Chandler Carruth18066972014-08-02 10:02:07 +0000156 void deleteAndRecombine(SDNode *N);
Chandler Carruth9a0051c2014-07-23 07:08:53 +0000157 bool recursivelyDeleteUnusedNodes(SDNode *N);
158
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000159 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
Evan Chengfd81c732009-03-28 05:57:29 +0000160 bool AddTo = true);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000161
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000162 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
Jim Laskeydcf983c2006-10-13 23:32:28 +0000163 return CombineTo(N, &Res, 1, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000164 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000165
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000166 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
Evan Chengfd81c732009-03-28 05:57:29 +0000167 bool AddTo = true) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000168 SDValue To[] = { Res0, Res1 };
Jim Laskeydcf983c2006-10-13 23:32:28 +0000169 return CombineTo(N, To, 2, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000170 }
Dan Gohmane58ab792009-01-29 01:59:02 +0000171
172 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000173
174 private:
175
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000176 /// Check the specified integer node value to see if it can be simplified or
177 /// if things it uses can be simplified by bit propagation.
178 /// If so, return true.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000179 bool SimplifyDemandedBits(SDValue Op) {
Dan Gohman1d459e42009-12-11 21:31:27 +0000180 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
181 APInt Demanded = APInt::getAllOnesValue(BitWidth);
Dan Gohmanae2b6fb2008-02-27 00:25:32 +0000182 return SimplifyDemandedBits(Op, Demanded);
183 }
184
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000185 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
Chris Lattner04c73702005-10-10 22:31:19 +0000186
Chris Lattnerffad2162006-11-11 00:39:41 +0000187 bool CombineToPreIndexedLoadStore(SDNode *N);
188 bool CombineToPostIndexedLoadStore(SDNode *N);
Hal Finkel51e6fa22014-09-02 06:24:04 +0000189 SDValue SplitIndexingFromLoad(LoadSDNode *LD);
Quentin Colombetde0e0622013-10-11 18:29:42 +0000190 bool SliceUpLoad(SDNode *N);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000191
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +0000192 /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
193 /// load.
194 ///
195 /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
196 /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
197 /// \param EltNo index of the vector element to load.
198 /// \param OriginalLoad load that EVE came from to be replaced.
199 /// \returns EVE on success SDValue() on failure.
200 SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
201 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000202 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
203 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
204 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
205 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
Evan Chengaf56fac2010-04-16 06:14:10 +0000206 SDValue PromoteIntBinOp(SDValue Op);
Evan Chengf1223bd2010-04-22 20:19:46 +0000207 SDValue PromoteIntShiftOp(SDValue Op);
Evan Chenge19aa5c2010-04-19 19:29:22 +0000208 SDValue PromoteExtend(SDValue Op);
209 bool PromoteLoad(SDValue Op);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000210
Craig Toppere0b71182013-07-13 07:43:40 +0000211 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
Andrew Trickef9de2a2013-05-25 02:42:55 +0000212 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
Nick Lewycky6d677cf2011-06-16 01:15:49 +0000213 ISD::NodeType ExtType);
214
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000215 /// Call the node-specific routine that knows how to fold each
Dan Gohman5c6d0c32007-10-08 17:57:15 +0000216 /// particular type of node. If that doesn't do anything, try the
217 /// target-specific DAG combines.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000218 SDValue combine(SDNode *N);
Nate Begeman21158fc2005-09-01 00:19:25 +0000219
220 // Visitation implementation - Implement dag node combining for different
221 // node types. The semantics are as follows:
222 // Return Value:
Evan Cheng5e7658c2008-08-29 22:21:44 +0000223 // SDValue.getNode() == 0 - No change was made
224 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
225 // otherwise - N should be replaced by the returned Operand.
Nate Begeman21158fc2005-09-01 00:19:25 +0000226 //
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000227 SDValue visitTokenFactor(SDNode *N);
228 SDValue visitMERGE_VALUES(SDNode *N);
229 SDValue visitADD(SDNode *N);
230 SDValue visitSUB(SDNode *N);
231 SDValue visitADDC(SDNode *N);
Craig Topper43a1bd62012-01-07 09:06:39 +0000232 SDValue visitSUBC(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000233 SDValue visitADDE(SDNode *N);
Craig Topper43a1bd62012-01-07 09:06:39 +0000234 SDValue visitSUBE(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000235 SDValue visitMUL(SDNode *N);
236 SDValue visitSDIV(SDNode *N);
237 SDValue visitUDIV(SDNode *N);
238 SDValue visitSREM(SDNode *N);
239 SDValue visitUREM(SDNode *N);
240 SDValue visitMULHU(SDNode *N);
241 SDValue visitMULHS(SDNode *N);
242 SDValue visitSMUL_LOHI(SDNode *N);
243 SDValue visitUMUL_LOHI(SDNode *N);
Benjamin Kramer2fd48f22011-05-21 18:31:55 +0000244 SDValue visitSMULO(SDNode *N);
245 SDValue visitUMULO(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000246 SDValue visitSDIVREM(SDNode *N);
247 SDValue visitUDIVREM(SDNode *N);
248 SDValue visitAND(SDNode *N);
249 SDValue visitOR(SDNode *N);
250 SDValue visitXOR(SDNode *N);
251 SDValue SimplifyVBinOp(SDNode *N);
Craig Topper82384612012-09-11 01:45:21 +0000252 SDValue SimplifyVUnaryOp(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000253 SDValue visitSHL(SDNode *N);
254 SDValue visitSRA(SDNode *N);
255 SDValue visitSRL(SDNode *N);
Adam Nemet7f928f12014-03-07 23:56:30 +0000256 SDValue visitRotate(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000257 SDValue visitCTLZ(SDNode *N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +0000258 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000259 SDValue visitCTTZ(SDNode *N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +0000260 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000261 SDValue visitCTPOP(SDNode *N);
262 SDValue visitSELECT(SDNode *N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +0000263 SDValue visitVSELECT(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000264 SDValue visitSELECT_CC(SDNode *N);
265 SDValue visitSETCC(SDNode *N);
266 SDValue visitSIGN_EXTEND(SDNode *N);
267 SDValue visitZERO_EXTEND(SDNode *N);
268 SDValue visitANY_EXTEND(SDNode *N);
269 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
270 SDValue visitTRUNCATE(SDNode *N);
Wesley Peck527da1b2010-11-23 03:31:01 +0000271 SDValue visitBITCAST(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000272 SDValue visitBUILD_PAIR(SDNode *N);
273 SDValue visitFADD(SDNode *N);
274 SDValue visitFSUB(SDNode *N);
275 SDValue visitFMUL(SDNode *N);
Owen Anderson41b06652012-05-02 22:17:40 +0000276 SDValue visitFMA(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000277 SDValue visitFDIV(SDNode *N);
278 SDValue visitFREM(SDNode *N);
Sanjay Patelbdf1e382014-09-26 23:01:47 +0000279 SDValue visitFSQRT(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000280 SDValue visitFCOPYSIGN(SDNode *N);
281 SDValue visitSINT_TO_FP(SDNode *N);
282 SDValue visitUINT_TO_FP(SDNode *N);
283 SDValue visitFP_TO_SINT(SDNode *N);
284 SDValue visitFP_TO_UINT(SDNode *N);
285 SDValue visitFP_ROUND(SDNode *N);
286 SDValue visitFP_ROUND_INREG(SDNode *N);
287 SDValue visitFP_EXTEND(SDNode *N);
288 SDValue visitFNEG(SDNode *N);
289 SDValue visitFABS(SDNode *N);
Owen Andersona40319b2012-08-13 23:32:49 +0000290 SDValue visitFCEIL(SDNode *N);
291 SDValue visitFTRUNC(SDNode *N);
292 SDValue visitFFLOOR(SDNode *N);
Matt Arsenault7c936902014-10-21 23:01:01 +0000293 SDValue visitFMINNUM(SDNode *N);
294 SDValue visitFMAXNUM(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000295 SDValue visitBRCOND(SDNode *N);
296 SDValue visitBR_CC(SDNode *N);
297 SDValue visitLOAD(SDNode *N);
298 SDValue visitSTORE(SDNode *N);
299 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
300 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
301 SDValue visitBUILD_VECTOR(SDNode *N);
302 SDValue visitCONCAT_VECTORS(SDNode *N);
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +0000303 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000304 SDValue visitVECTOR_SHUFFLE(SDNode *N);
Manman Ren413a6cb2014-01-31 01:10:35 +0000305 SDValue visitINSERT_SUBVECTOR(SDNode *N);
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +0000306 SDValue visitMLOAD(SDNode *N);
307 SDValue visitMSTORE(SDNode *N);
Chris Lattnere260ed82005-10-10 22:04:48 +0000308
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000309 SDValue XformToShuffleWithZero(SDNode *N);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000310 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000311
Matt Arsenault985b9de2014-03-17 18:58:01 +0000312 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
Chris Lattner7c709a52007-12-06 07:33:36 +0000313
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000314 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
315 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000316 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
317 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
Scott Michelcf0da6c2009-02-17 22:15:04 +0000318 SDValue N3, ISD::CondCode CC,
Bill Wendling31b50992009-01-30 23:59:18 +0000319 bool NotExtCompare = false);
Owen Anderson53aa7a92009-08-10 22:56:29 +0000320 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
Andrew Trickef9de2a2013-05-25 02:42:55 +0000321 SDLoc DL, bool foldBooleans = true);
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000322
323 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
324 SDValue &CC) const;
325 bool isOneUseSetCC(SDValue N) const;
326
Scott Michelcf0da6c2009-02-17 22:15:04 +0000327 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
Chris Lattner31e9edc2008-01-26 01:09:19 +0000328 unsigned HiOp);
Owen Anderson53aa7a92009-08-10 22:56:29 +0000329 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
Wesley Peck527da1b2010-11-23 03:31:01 +0000330 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000331 SDValue BuildSDIV(SDNode *N);
Chad Rosier17020f92014-07-23 14:57:52 +0000332 SDValue BuildSDIVPow2(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000333 SDValue BuildUDIV(SDNode *N);
Sanjay Patelbdf1e382014-09-26 23:01:47 +0000334 SDValue BuildReciprocalEstimate(SDValue Op);
335 SDValue BuildRsqrtEstimate(SDValue Op);
Sanjay Patel957efc232014-10-24 17:02:16 +0000336 SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations);
337 SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations);
Evan Cheng4c0bd962011-06-21 06:01:08 +0000338 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
339 bool DemandHighBits = true);
340 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
Richard Sandiford95c864d2014-01-08 15:40:47 +0000341 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
342 SDValue InnerPos, SDValue InnerNeg,
343 unsigned PosOpcode, unsigned NegOpcode,
344 SDLoc DL);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000345 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000346 SDValue ReduceLoadWidth(SDNode *N);
Evan Chenga9cda8a2009-05-28 00:35:15 +0000347 SDValue ReduceLoadOpStoreWidth(SDNode *N);
Evan Chengd42641c2011-02-02 01:06:55 +0000348 SDValue TransformFPLoadStorePair(SDNode *N);
Michael Liao6d106b72012-10-23 23:06:52 +0000349 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
Michael Liao59229792012-10-24 04:14:18 +0000350 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000351
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000352 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000353
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000354 /// Walk up chain skipping non-aliasing memory nodes,
Jim Laskey708d0db2006-10-04 16:53:27 +0000355 /// looking for aliasing nodes and adding them to the Aliases vector.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000356 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
Craig Topperb94011f2013-07-14 04:42:23 +0000357 SmallVectorImpl<SDValue> &Aliases);
Jim Laskey708d0db2006-10-04 16:53:27 +0000358
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000359 /// Return true if there is any possibility that the two addresses overlap.
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000360 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000361
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000362 /// Walk up chain skipping non-aliasing memory nodes, looking for a better
363 /// chain (aliasing node.)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000364 SDValue FindBetterChain(SDNode *N, SDValue Chain);
Duncan Sands41826032009-01-31 15:50:11 +0000365
Nadav Rotem7cbc12a2012-10-03 16:11:15 +0000366 /// Merge consecutive store operations into a wide store.
367 /// This optimization uses wide integers or vectors when possible.
368 /// \return True if some memory operations were changed.
369 bool MergeConsecutiveStores(StoreSDNode *N);
370
Adam Nemet67483892014-03-04 23:28:31 +0000371 /// \brief Try to transform a truncation where C is a constant:
372 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
373 ///
374 /// \p N needs to be a truncation and its first operand an AND. Other
375 /// requirements are checked by the function (e.g. that trunc is
376 /// single-use) and if missed an empty SDValue is returned.
377 SDValue distributeTruncateThroughAnd(SDNode *N);
378
Chris Lattner4041ab62010-04-15 04:48:01 +0000379 public:
Bill Wendling026e5d72009-04-29 23:29:43 +0000380 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
Quentin Colombetde0e0622013-10-11 18:29:42 +0000381 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
382 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
383 AttributeSet FnAttrs =
384 DAG.getMachineFunction().getFunction()->getAttributes();
385 ForCodeSize =
386 FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
387 Attribute::OptimizeForSize) ||
388 FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
389 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000390
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000391 /// Runs the dag combiner on all nodes in the work list
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000392 void Run(CombineLevel AtLevel);
Wesley Peck527da1b2010-11-23 03:31:01 +0000393
Chris Lattner4041ab62010-04-15 04:48:01 +0000394 SelectionDAG &getDAG() const { return DAG; }
Wesley Peck527da1b2010-11-23 03:31:01 +0000395
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000396 /// Returns a type large enough to hold any valid shift amount - before type
397 /// legalization these can be huge.
Owen Andersonb2c80da2011-02-25 21:41:48 +0000398 EVT getShiftAmountTy(EVT LHSTy) {
Elena Demikhovsky6769c502013-06-26 10:55:03 +0000399 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
400 if (LHSTy.isVector())
401 return LHSTy;
Jack Carterd4e96152013-10-17 01:34:33 +0000402 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
403 : TLI.getPointerTy();
Chris Lattner4041ab62010-04-15 04:48:01 +0000404 }
Wesley Peck527da1b2010-11-23 03:31:01 +0000405
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000406 /// This method returns true if we are running before type legalization or
407 /// if the specified VT is legal.
Chris Lattner4041ab62010-04-15 04:48:01 +0000408 bool isTypeLegal(const EVT &VT) {
409 if (!LegalTypes) return true;
410 return TLI.isTypeLegal(VT);
411 }
Matt Arsenault758659232013-05-18 00:21:46 +0000412
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000413 /// Convenience wrapper around TargetLowering::getSetCCResultType
Matt Arsenault758659232013-05-18 00:21:46 +0000414 EVT getSetCCResultType(EVT VT) const {
415 return TLI.getSetCCResultType(*DAG.getContext(), VT);
416 }
Nate Begeman21158fc2005-09-01 00:19:25 +0000417 };
418}
419
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000420
421namespace {
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000422/// This class is a DAGUpdateListener that removes any deleted
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000423/// nodes from the worklist.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000424class WorklistRemover : public SelectionDAG::DAGUpdateListener {
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000425 DAGCombiner &DC;
426public:
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000427 explicit WorklistRemover(DAGCombiner &dc)
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000428 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
Scott Michelcf0da6c2009-02-17 22:15:04 +0000429
Craig Topper7b883b32014-03-08 06:31:39 +0000430 void NodeDeleted(SDNode *N, SDNode *E) override {
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000431 DC.removeFromWorklist(N);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000432 }
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000433};
434}
435
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000436//===----------------------------------------------------------------------===//
437// TargetLowering::DAGCombinerInfo implementation
438//===----------------------------------------------------------------------===//
439
440void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000441 ((DAGCombiner*)DC)->AddToWorklist(N);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000442}
443
Cameron Zwarich8c7bbc02011-04-02 02:40:26 +0000444void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000445 ((DAGCombiner*)DC)->removeFromWorklist(N);
Cameron Zwarich8c7bbc02011-04-02 02:40:26 +0000446}
447
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000448SDValue TargetLowering::DAGCombinerInfo::
Evan Chengfd81c732009-03-28 05:57:29 +0000449CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
450 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000451}
452
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000453SDValue TargetLowering::DAGCombinerInfo::
Evan Chengfd81c732009-03-28 05:57:29 +0000454CombineTo(SDNode *N, SDValue Res, bool AddTo) {
455 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000456}
457
458
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000459SDValue TargetLowering::DAGCombinerInfo::
Evan Chengfd81c732009-03-28 05:57:29 +0000460CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
461 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000462}
463
Dan Gohmane58ab792009-01-29 01:59:02 +0000464void TargetLowering::DAGCombinerInfo::
465CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
466 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
467}
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000468
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000469//===----------------------------------------------------------------------===//
Chris Lattnere49c9742007-05-14 22:04:50 +0000470// Helper Functions
471//===----------------------------------------------------------------------===//
472
Chandler Carruth18066972014-08-02 10:02:07 +0000473void DAGCombiner::deleteAndRecombine(SDNode *N) {
474 removeFromWorklist(N);
475
476 // If the operands of this node are only used by the node, they will now be
477 // dead. Make sure to re-visit them and recursively delete dead nodes.
478 for (const SDValue &Op : N->ops())
Hal Finkel51e6fa22014-09-02 06:24:04 +0000479 // For an operand generating multiple values, one of the values may
480 // become dead allowing further simplification (e.g. split index
481 // arithmetic from an indexed load).
482 if (Op->hasOneUse() || Op->getNumValues() > 1)
Chandler Carruth18066972014-08-02 10:02:07 +0000483 AddToWorklist(Op.getNode());
484
485 DAG.DeleteNode(N);
486}
487
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000488/// Return 1 if we can compute the negated form of the specified expression for
489/// the same cost as the expression itself, or 2 if we can compute the negated
490/// form more cheaply than the expression itself.
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000491static char isNegatibleForFree(SDValue Op, bool LegalOperations,
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000492 const TargetLowering &TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000493 const TargetOptions *Options,
Chris Lattnere7c14012008-02-26 07:04:54 +0000494 unsigned Depth = 0) {
Chris Lattnere49c9742007-05-14 22:04:50 +0000495 // fneg is removable even if it has multiple uses.
496 if (Op.getOpcode() == ISD::FNEG) return 2;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000497
Chris Lattnere49c9742007-05-14 22:04:50 +0000498 // Don't allow anything with multiple uses.
499 if (!Op.hasOneUse()) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000500
Chris Lattner46980832007-05-25 02:19:06 +0000501 // Don't recurse exponentially.
502 if (Depth > 6) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000503
Chris Lattnere49c9742007-05-14 22:04:50 +0000504 switch (Op.getOpcode()) {
505 default: return false;
506 case ISD::ConstantFP:
Chris Lattnere7c14012008-02-26 07:04:54 +0000507 // Don't invert constant FP values after legalize. The negated constant
508 // isn't necessarily legal.
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000509 return LegalOperations ? 0 : 1;
Chris Lattnere49c9742007-05-14 22:04:50 +0000510 case ISD::FADD:
511 // FIXME: determine better conditions for this xform.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000512 if (!Options->UnsafeFPMath) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000513
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000514 // After operation legalization, it might not be legal to create new FSUBs.
515 if (LegalOperations &&
516 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
517 return 0;
518
Craig Topper03f39772012-09-09 22:58:45 +0000519 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000520 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
521 Options, Depth + 1))
Chris Lattnere49c9742007-05-14 22:04:50 +0000522 return V;
Bill Wendling6fbf5492009-01-30 23:10:18 +0000523 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000524 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000525 Depth + 1);
Chris Lattnere49c9742007-05-14 22:04:50 +0000526 case ISD::FSUB:
Scott Michelcf0da6c2009-02-17 22:15:04 +0000527 // We can't turn -(A-B) into B-A when we honor signed zeros.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000528 if (!Options->UnsafeFPMath) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000529
Bill Wendling6fbf5492009-01-30 23:10:18 +0000530 // fold (fneg (fsub A, B)) -> (fsub B, A)
Chris Lattnere49c9742007-05-14 22:04:50 +0000531 return 1;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000532
Chris Lattnere49c9742007-05-14 22:04:50 +0000533 case ISD::FMUL:
534 case ISD::FDIV:
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000535 if (Options->HonorSignDependentRoundingFPMath()) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000536
Bill Wendling6fbf5492009-01-30 23:10:18 +0000537 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000538 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
539 Options, Depth + 1))
Chris Lattnere49c9742007-05-14 22:04:50 +0000540 return V;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000541
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000542 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000543 Depth + 1);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000544
Chris Lattnere49c9742007-05-14 22:04:50 +0000545 case ISD::FP_EXTEND:
546 case ISD::FP_ROUND:
547 case ISD::FSIN:
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000548 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000549 Depth + 1);
Chris Lattnere49c9742007-05-14 22:04:50 +0000550 }
551}
552
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000553/// If isNegatibleForFree returns true, return the newly negated expression.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000554static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000555 bool LegalOperations, unsigned Depth = 0) {
Sanjay Patel78614bf2014-08-28 15:53:16 +0000556 const TargetOptions &Options = DAG.getTarget().Options;
Chris Lattnere49c9742007-05-14 22:04:50 +0000557 // fneg is removable even if it has multiple uses.
558 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000559
Chris Lattnere49c9742007-05-14 22:04:50 +0000560 // Don't allow anything with multiple uses.
561 assert(Op.hasOneUse() && "Unknown reuse!");
Scott Michelcf0da6c2009-02-17 22:15:04 +0000562
Chris Lattner46980832007-05-25 02:19:06 +0000563 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
Chris Lattnere49c9742007-05-14 22:04:50 +0000564 switch (Op.getOpcode()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000565 default: llvm_unreachable("Unknown code");
Dale Johannesen446b9002007-08-31 23:34:27 +0000566 case ISD::ConstantFP: {
567 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
568 V.changeSign();
569 return DAG.getConstantFP(V, Op.getValueType());
570 }
Chris Lattnere49c9742007-05-14 22:04:50 +0000571 case ISD::FADD:
572 // FIXME: determine better conditions for this xform.
Sanjay Patel78614bf2014-08-28 15:53:16 +0000573 assert(Options.UnsafeFPMath);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000574
Bill Wendling6fbf5492009-01-30 23:10:18 +0000575 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000576 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
Sanjay Patel78614bf2014-08-28 15:53:16 +0000577 DAG.getTargetLoweringInfo(), &Options, Depth+1))
Andrew Trickef9de2a2013-05-25 02:42:55 +0000578 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000579 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000580 LegalOperations, Depth+1),
Chris Lattnere49c9742007-05-14 22:04:50 +0000581 Op.getOperand(1));
Bill Wendling6fbf5492009-01-30 23:10:18 +0000582 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
Andrew Trickef9de2a2013-05-25 02:42:55 +0000583 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000584 GetNegatedExpression(Op.getOperand(1), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000585 LegalOperations, Depth+1),
Chris Lattnere49c9742007-05-14 22:04:50 +0000586 Op.getOperand(0));
587 case ISD::FSUB:
Scott Michelcf0da6c2009-02-17 22:15:04 +0000588 // We can't turn -(A-B) into B-A when we honor signed zeros.
Sanjay Patel78614bf2014-08-28 15:53:16 +0000589 assert(Options.UnsafeFPMath);
Dan Gohman9a708232007-07-02 15:48:56 +0000590
Bill Wendling6fbf5492009-01-30 23:10:18 +0000591 // fold (fneg (fsub 0, B)) -> B
Dan Gohman9a708232007-07-02 15:48:56 +0000592 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
Dale Johannesen446b9002007-08-31 23:34:27 +0000593 if (N0CFP->getValueAPF().isZero())
Dan Gohman9a708232007-07-02 15:48:56 +0000594 return Op.getOperand(1);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000595
Bill Wendling6fbf5492009-01-30 23:10:18 +0000596 // fold (fneg (fsub A, B)) -> (fsub B, A)
Andrew Trickef9de2a2013-05-25 02:42:55 +0000597 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000598 Op.getOperand(1), Op.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +0000599
Chris Lattnere49c9742007-05-14 22:04:50 +0000600 case ISD::FMUL:
601 case ISD::FDIV:
Sanjay Patel78614bf2014-08-28 15:53:16 +0000602 assert(!Options.HonorSignDependentRoundingFPMath());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000603
Bill Wendling6fbf5492009-01-30 23:10:18 +0000604 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000605 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
Sanjay Patel78614bf2014-08-28 15:53:16 +0000606 DAG.getTargetLoweringInfo(), &Options, Depth+1))
Andrew Trickef9de2a2013-05-25 02:42:55 +0000607 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000608 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000609 LegalOperations, Depth+1),
Chris Lattnere49c9742007-05-14 22:04:50 +0000610 Op.getOperand(1));
Scott Michelcf0da6c2009-02-17 22:15:04 +0000611
Bill Wendling6fbf5492009-01-30 23:10:18 +0000612 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
Andrew Trickef9de2a2013-05-25 02:42:55 +0000613 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Chris Lattnere49c9742007-05-14 22:04:50 +0000614 Op.getOperand(0),
Chris Lattnere7c14012008-02-26 07:04:54 +0000615 GetNegatedExpression(Op.getOperand(1), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000616 LegalOperations, Depth+1));
Scott Michelcf0da6c2009-02-17 22:15:04 +0000617
Chris Lattnere49c9742007-05-14 22:04:50 +0000618 case ISD::FP_EXTEND:
Chris Lattnere49c9742007-05-14 22:04:50 +0000619 case ISD::FSIN:
Andrew Trickef9de2a2013-05-25 02:42:55 +0000620 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000621 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000622 LegalOperations, Depth+1));
Chris Lattner72733e52008-01-17 07:00:52 +0000623 case ISD::FP_ROUND:
Andrew Trickef9de2a2013-05-25 02:42:55 +0000624 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000625 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000626 LegalOperations, Depth+1),
Chris Lattner72733e52008-01-17 07:00:52 +0000627 Op.getOperand(1));
Chris Lattnere49c9742007-05-14 22:04:50 +0000628 }
629}
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000630
Sanjay Patelf4b8deb2014-09-05 20:55:46 +0000631// Return true if this node is a setcc, or is a select_cc
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000632// that selects between the target values used for true and false, making it
633// equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
634// the appropriate nodes based on the type of node we are checking. This
635// simplifies life a bit for the callers.
636bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
637 SDValue &CC) const {
Nate Begeman7cea6ef2005-09-02 21:18:40 +0000638 if (N.getOpcode() == ISD::SETCC) {
639 LHS = N.getOperand(0);
640 RHS = N.getOperand(1);
641 CC = N.getOperand(2);
Nate Begeman2504fe22005-09-01 23:24:04 +0000642 return true;
Nate Begeman7cea6ef2005-09-02 21:18:40 +0000643 }
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000644
645 if (N.getOpcode() != ISD::SELECT_CC ||
646 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
647 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
648 return false;
649
Oliver Stannardd29db9b2014-11-17 10:49:31 +0000650 if (TLI.getBooleanContents(N.getValueType()) ==
651 TargetLowering::UndefinedBooleanContent)
652 return false;
653
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000654 LHS = N.getOperand(0);
655 RHS = N.getOperand(1);
656 CC = N.getOperand(4);
657 return true;
Nate Begeman21158fc2005-09-01 00:19:25 +0000658}
659
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000660/// Return true if this is a SetCC-equivalent operation with only one use.
661/// If this is true, it allows the users to invert the operation for free when
662/// it is profitable to do so.
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000663bool DAGCombiner::isOneUseSetCC(SDValue N) const {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000664 SDValue N0, N1, N2;
Gabor Greiff304a7a2008-08-28 21:40:38 +0000665 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
Nate Begeman2504fe22005-09-01 23:24:04 +0000666 return true;
667 return false;
668}
669
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000670/// Returns true if N is a BUILD_VECTOR node whose
Matt Arsenault985b9de2014-03-17 18:58:01 +0000671/// elements are all the same constant or undefined.
672static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
673 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
674 if (!C)
675 return false;
676
677 APInt SplatUndef;
678 unsigned SplatBitSize;
679 bool HasAnyUndefs;
680 EVT EltVT = N->getValueType(0).getVectorElementType();
681 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
682 HasAnyUndefs) &&
683 EltVT.getSizeInBits() >= SplatBitSize);
684}
685
686// \brief Returns the SDNode if it is a constant BuildVector or constant.
Juergen Ributzka68402822014-01-13 21:49:25 +0000687static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
688 if (isa<ConstantSDNode>(N))
689 return N.getNode();
690 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
Sanjay Patelf4b8deb2014-09-05 20:55:46 +0000691 if (BV && BV->isConstant())
Juergen Ributzka68402822014-01-13 21:49:25 +0000692 return BV;
Craig Topperc0196b12014-04-14 00:51:57 +0000693 return nullptr;
Juergen Ributzka68402822014-01-13 21:49:25 +0000694}
695
Matt Arsenault985b9de2014-03-17 18:58:01 +0000696// \brief Returns the SDNode if it is a constant splat BuildVector or constant
697// int.
698static ConstantSDNode *isConstOrConstSplat(SDValue N) {
699 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
700 return CN;
701
Chandler Carruthbeeacac2014-07-07 19:03:32 +0000702 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
Chandler Carruthf0a33b72014-07-09 00:41:34 +0000703 BitVector UndefElements;
704 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
Chandler Carruthbeeacac2014-07-07 19:03:32 +0000705
706 // BuildVectors can truncate their operands. Ignore that case here.
Chandler Carruthb844e722014-07-08 07:19:55 +0000707 // FIXME: We blindly ignore splats which include undef which is overly
708 // pessimistic.
Chandler Carruthf0a33b72014-07-09 00:41:34 +0000709 if (CN && UndefElements.none() &&
Chandler Carruthb844e722014-07-08 07:19:55 +0000710 CN->getValueType(0) == N.getValueType().getScalarType())
Chandler Carruthbeeacac2014-07-07 19:03:32 +0000711 return CN;
712 }
Matt Arsenault985b9de2014-03-17 18:58:01 +0000713
714 return nullptr;
715}
716
Matt Arsenault6cc00422014-08-16 10:14:19 +0000717// \brief Returns the SDNode if it is a constant splat BuildVector or constant
718// float.
719static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
720 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
721 return CN;
722
723 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
724 BitVector UndefElements;
725 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
726
Matt Arsenault965de302014-09-02 18:33:51 +0000727 if (CN && UndefElements.none())
Matt Arsenault6cc00422014-08-16 10:14:19 +0000728 return CN;
729 }
730
731 return nullptr;
732}
733
Andrew Trickef9de2a2013-05-25 02:42:55 +0000734SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000735 SDValue N0, SDValue N1) {
Owen Anderson53aa7a92009-08-10 22:56:29 +0000736 EVT VT = N0.getValueType();
Juergen Ributzka68402822014-01-13 21:49:25 +0000737 if (N0.getOpcode() == Opc) {
738 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
739 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
740 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
741 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
742 if (!OpNode.getNode())
743 return SDValue();
744 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
Juergen Ributzka73844052014-01-13 20:51:35 +0000745 }
Juergen Ributzka68402822014-01-13 21:49:25 +0000746 if (N0.hasOneUse()) {
747 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
748 // use
749 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
750 if (!OpNode.getNode())
751 return SDValue();
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000752 AddToWorklist(OpNode.getNode());
Juergen Ributzka68402822014-01-13 21:49:25 +0000753 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
Juergen Ributzka73844052014-01-13 20:51:35 +0000754 }
755 }
Nate Begeman22e251a2006-02-03 06:46:56 +0000756 }
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000757
Juergen Ributzka68402822014-01-13 21:49:25 +0000758 if (N1.getOpcode() == Opc) {
759 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
760 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
761 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
762 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
763 if (!OpNode.getNode())
764 return SDValue();
765 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
766 }
767 if (N1.hasOneUse()) {
768 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
769 // use
770 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
771 if (!OpNode.getNode())
772 return SDValue();
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000773 AddToWorklist(OpNode.getNode());
Juergen Ributzka68402822014-01-13 21:49:25 +0000774 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
775 }
Nate Begeman22e251a2006-02-03 06:46:56 +0000776 }
777 }
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000778
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000779 return SDValue();
Nate Begeman22e251a2006-02-03 06:46:56 +0000780}
781
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000782SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
783 bool AddTo) {
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000784 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
785 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +0000786 DEBUG(dbgs() << "\nReplacing.1 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000787 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000788 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000789 To[0].getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000790 dbgs() << " and " << NumTo-1 << " other values\n";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000791 for (unsigned i = 0, e = NumTo; i != e; ++i)
Jakob Stoklund Olesen32042f92009-12-03 05:15:35 +0000792 assert((!To[i].getNode() ||
793 N->getValueType(i) == To[i].getValueType()) &&
Dan Gohman7e6b9322009-01-21 15:17:51 +0000794 "Cannot combine value to value of different type!"));
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000795 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000796 DAG.ReplaceAllUsesWith(N, To);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000797 if (AddTo) {
798 // Push the new nodes and any users onto the worklist
799 for (unsigned i = 0, e = NumTo; i != e; ++i) {
Chris Lattner4147f082009-03-12 06:52:53 +0000800 if (To[i].getNode()) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000801 AddToWorklist(To[i].getNode());
802 AddUsersToWorklist(To[i].getNode());
Chris Lattner4147f082009-03-12 06:52:53 +0000803 }
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000804 }
805 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000806
Dan Gohmancd0b1bf2009-01-19 21:44:21 +0000807 // Finally, if the node is now dead, remove it from the graph. The node
808 // may not be dead if the replacement process recursively simplified to
809 // something else needing this node.
Chandler Carruth18066972014-08-02 10:02:07 +0000810 if (N->use_empty())
811 deleteAndRecombine(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000812 return SDValue(N, 0);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000813}
814
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000815void DAGCombiner::
816CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
Scott Michelcf0da6c2009-02-17 22:15:04 +0000817 // Replace all uses. If any nodes become isomorphic to other nodes and
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000818 // are deleted, make sure to remove them from our worklist.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000819 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000820 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
Dan Gohmane58ab792009-01-29 01:59:02 +0000821
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000822 // Push the new node and any (possibly new) users onto the worklist.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000823 AddToWorklist(TLO.New.getNode());
824 AddUsersToWorklist(TLO.New.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000825
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000826 // Finally, if the node is now dead, remove it from the graph. The node
827 // may not be dead if the replacement process recursively simplified to
828 // something else needing this node.
Chandler Carruth18066972014-08-02 10:02:07 +0000829 if (TLO.Old.getNode()->use_empty())
830 deleteAndRecombine(TLO.Old.getNode());
Dan Gohmane58ab792009-01-29 01:59:02 +0000831}
832
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000833/// Check the specified integer node value to see if it can be simplified or if
834/// things it uses can be simplified by bit propagation. If so, return true.
Dan Gohmane58ab792009-01-29 01:59:02 +0000835bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000836 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
Dan Gohmane58ab792009-01-29 01:59:02 +0000837 APInt KnownZero, KnownOne;
838 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
839 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000840
Dan Gohmane58ab792009-01-29 01:59:02 +0000841 // Revisit the node.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000842 AddToWorklist(Op.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000843
Dan Gohmane58ab792009-01-29 01:59:02 +0000844 // Replace the old value with the new one.
845 ++NodesCombined;
Wesley Peck527da1b2010-11-23 03:31:01 +0000846 DEBUG(dbgs() << "\nReplacing.2 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000847 TLO.Old.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000848 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000849 TLO.New.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000850 dbgs() << '\n');
Scott Michelcf0da6c2009-02-17 22:15:04 +0000851
Dan Gohmane58ab792009-01-29 01:59:02 +0000852 CommitTargetLoweringOpt(TLO);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000853 return true;
854}
855
Evan Cheng0abb54d2010-04-24 04:43:44 +0000856void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
Andrew Trickef9de2a2013-05-25 02:42:55 +0000857 SDLoc dl(Load);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000858 EVT VT = Load->getValueType(0);
859 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
Evan Chenge19aa5c2010-04-19 19:29:22 +0000860
Evan Cheng0abb54d2010-04-24 04:43:44 +0000861 DEBUG(dbgs() << "\nReplacing.9 ";
862 Load->dump(&DAG);
863 dbgs() << "\nWith: ";
864 Trunc.getNode()->dump(&DAG);
865 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000866 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000867 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
868 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
Chandler Carruth18066972014-08-02 10:02:07 +0000869 deleteAndRecombine(Load);
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000870 AddToWorklist(Trunc.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000871}
872
873SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
874 Replace = false;
Andrew Trickef9de2a2013-05-25 02:42:55 +0000875 SDLoc dl(Op);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000876 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
Evan Chenge8136902010-04-27 19:48:13 +0000877 EVT MemVT = LD->getMemoryVT();
878 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
Owen Andersonb2c80da2011-02-25 21:41:48 +0000879 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
Eric Christopherd9e8eac2010-12-09 04:48:06 +0000880 : ISD::EXTLOAD)
Evan Chenge8136902010-04-27 19:48:13 +0000881 : LD->getExtensionType();
Evan Cheng0abb54d2010-04-24 04:43:44 +0000882 Replace = true;
Stuart Hastings81c43062011-02-16 16:23:55 +0000883 return DAG.getExtLoad(ExtType, dl, PVT,
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000884 LD->getChain(), LD->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +0000885 MemVT, LD->getMemOperand());
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000886 }
887
Evan Chenge19aa5c2010-04-19 19:29:22 +0000888 unsigned Opc = Op.getOpcode();
Evan Chengb9ff1302010-04-23 19:10:30 +0000889 switch (Opc) {
890 default: break;
891 case ISD::AssertSext:
Evan Chenge19aa5c2010-04-19 19:29:22 +0000892 return DAG.getNode(ISD::AssertSext, dl, PVT,
Evan Cheng0abb54d2010-04-24 04:43:44 +0000893 SExtPromoteOperand(Op.getOperand(0), PVT),
Evan Chenge19aa5c2010-04-19 19:29:22 +0000894 Op.getOperand(1));
Evan Chengb9ff1302010-04-23 19:10:30 +0000895 case ISD::AssertZext:
Evan Chenge19aa5c2010-04-19 19:29:22 +0000896 return DAG.getNode(ISD::AssertZext, dl, PVT,
Evan Cheng0abb54d2010-04-24 04:43:44 +0000897 ZExtPromoteOperand(Op.getOperand(0), PVT),
Evan Chenge19aa5c2010-04-19 19:29:22 +0000898 Op.getOperand(1));
Evan Chengb9ff1302010-04-23 19:10:30 +0000899 case ISD::Constant: {
900 unsigned ExtOpc =
Evan Chenge19aa5c2010-04-19 19:29:22 +0000901 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
Evan Chengb9ff1302010-04-23 19:10:30 +0000902 return DAG.getNode(ExtOpc, dl, PVT, Op);
Wesley Peck527da1b2010-11-23 03:31:01 +0000903 }
Evan Chengb9ff1302010-04-23 19:10:30 +0000904 }
905
906 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000907 return SDValue();
Evan Chengb9ff1302010-04-23 19:10:30 +0000908 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
Evan Chengaf56fac2010-04-16 06:14:10 +0000909}
910
Evan Cheng0abb54d2010-04-24 04:43:44 +0000911SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000912 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
913 return SDValue();
914 EVT OldVT = Op.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +0000915 SDLoc dl(Op);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000916 bool Replace = false;
917 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
Craig Topperc0196b12014-04-14 00:51:57 +0000918 if (!NewOp.getNode())
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000919 return SDValue();
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000920 AddToWorklist(NewOp.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000921
922 if (Replace)
923 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
924 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000925 DAG.getValueType(OldVT));
926}
927
Evan Cheng0abb54d2010-04-24 04:43:44 +0000928SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000929 EVT OldVT = Op.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +0000930 SDLoc dl(Op);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000931 bool Replace = false;
932 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
Craig Topperc0196b12014-04-14 00:51:57 +0000933 if (!NewOp.getNode())
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000934 return SDValue();
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000935 AddToWorklist(NewOp.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000936
937 if (Replace)
938 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
939 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000940}
941
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000942/// Promote the specified integer binary operation if the target indicates it is
943/// beneficial. e.g. On x86, it's usually better to promote i16 operations to
944/// i32 since i16 instructions are longer.
Evan Chengaf56fac2010-04-16 06:14:10 +0000945SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
946 if (!LegalOperations)
947 return SDValue();
948
949 EVT VT = Op.getValueType();
950 if (VT.isVector() || !VT.isInteger())
951 return SDValue();
952
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000953 // If operation type is 'undesirable', e.g. i16 on x86, consider
954 // promoting it.
955 unsigned Opc = Op.getOpcode();
956 if (TLI.isTypeDesirableForOp(Opc, VT))
957 return SDValue();
958
Evan Chengaf56fac2010-04-16 06:14:10 +0000959 EVT PVT = VT;
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000960 // Consult target whether it is a good idea to promote this operation and
961 // what's the right type to promote it to.
962 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
Evan Chengaf56fac2010-04-16 06:14:10 +0000963 assert(PVT != VT && "Don't know what type to promote to!");
964
Evan Cheng0abb54d2010-04-24 04:43:44 +0000965 bool Replace0 = false;
966 SDValue N0 = Op.getOperand(0);
967 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
Craig Topperc0196b12014-04-14 00:51:57 +0000968 if (!NN0.getNode())
Evan Chengf1223bd2010-04-22 20:19:46 +0000969 return SDValue();
970
Evan Cheng0abb54d2010-04-24 04:43:44 +0000971 bool Replace1 = false;
972 SDValue N1 = Op.getOperand(1);
Evan Cheng02947a42010-05-10 19:03:57 +0000973 SDValue NN1;
974 if (N0 == N1)
975 NN1 = NN0;
976 else {
977 NN1 = PromoteOperand(N1, PVT, Replace1);
Craig Topperc0196b12014-04-14 00:51:57 +0000978 if (!NN1.getNode())
Evan Cheng02947a42010-05-10 19:03:57 +0000979 return SDValue();
980 }
Evan Chengf1223bd2010-04-22 20:19:46 +0000981
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000982 AddToWorklist(NN0.getNode());
Evan Cheng02947a42010-05-10 19:03:57 +0000983 if (NN1.getNode())
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000984 AddToWorklist(NN1.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000985
986 if (Replace0)
987 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
988 if (Replace1)
989 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
Evan Chengf1223bd2010-04-22 20:19:46 +0000990
Evan Chenge8136902010-04-27 19:48:13 +0000991 DEBUG(dbgs() << "\nPromoting ";
992 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +0000993 SDLoc dl(Op);
Evan Chengf1223bd2010-04-22 20:19:46 +0000994 return DAG.getNode(ISD::TRUNCATE, dl, VT,
Evan Cheng0abb54d2010-04-24 04:43:44 +0000995 DAG.getNode(Opc, dl, PVT, NN0, NN1));
Evan Chengf1223bd2010-04-22 20:19:46 +0000996 }
997 return SDValue();
998}
999
Sanjay Patel50cbfc52014-08-28 16:29:51 +00001000/// Promote the specified integer shift operation if the target indicates it is
1001/// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1002/// i32 since i16 instructions are longer.
Evan Chengf1223bd2010-04-22 20:19:46 +00001003SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1004 if (!LegalOperations)
1005 return SDValue();
1006
1007 EVT VT = Op.getValueType();
1008 if (VT.isVector() || !VT.isInteger())
1009 return SDValue();
1010
1011 // If operation type is 'undesirable', e.g. i16 on x86, consider
1012 // promoting it.
1013 unsigned Opc = Op.getOpcode();
1014 if (TLI.isTypeDesirableForOp(Opc, VT))
1015 return SDValue();
1016
1017 EVT PVT = VT;
1018 // Consult target whether it is a good idea to promote this operation and
1019 // what's the right type to promote it to.
1020 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1021 assert(PVT != VT && "Don't know what type to promote to!");
1022
Evan Cheng0abb54d2010-04-24 04:43:44 +00001023 bool Replace = false;
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001024 SDValue N0 = Op.getOperand(0);
1025 if (Opc == ISD::SRA)
Evan Cheng0abb54d2010-04-24 04:43:44 +00001026 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001027 else if (Opc == ISD::SRL)
Evan Cheng0abb54d2010-04-24 04:43:44 +00001028 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001029 else
Evan Cheng0abb54d2010-04-24 04:43:44 +00001030 N0 = PromoteOperand(N0, PVT, Replace);
Craig Topperc0196b12014-04-14 00:51:57 +00001031 if (!N0.getNode())
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001032 return SDValue();
Evan Cheng0abb54d2010-04-24 04:43:44 +00001033
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001034 AddToWorklist(N0.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +00001035 if (Replace)
1036 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
Evan Chengaf56fac2010-04-16 06:14:10 +00001037
Evan Chenge8136902010-04-27 19:48:13 +00001038 DEBUG(dbgs() << "\nPromoting ";
1039 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +00001040 SDLoc dl(Op);
Evan Chengaf56fac2010-04-16 06:14:10 +00001041 return DAG.getNode(ISD::TRUNCATE, dl, VT,
Evan Chengf1223bd2010-04-22 20:19:46 +00001042 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
Evan Chengaf56fac2010-04-16 06:14:10 +00001043 }
1044 return SDValue();
1045}
1046
Evan Chenge19aa5c2010-04-19 19:29:22 +00001047SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1048 if (!LegalOperations)
1049 return SDValue();
1050
1051 EVT VT = Op.getValueType();
1052 if (VT.isVector() || !VT.isInteger())
1053 return SDValue();
1054
1055 // If operation type is 'undesirable', e.g. i16 on x86, consider
1056 // promoting it.
1057 unsigned Opc = Op.getOpcode();
1058 if (TLI.isTypeDesirableForOp(Opc, VT))
1059 return SDValue();
1060
1061 EVT PVT = VT;
1062 // Consult target whether it is a good idea to promote this operation and
1063 // what's the right type to promote it to.
1064 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1065 assert(PVT != VT && "Don't know what type to promote to!");
1066 // fold (aext (aext x)) -> (aext x)
1067 // fold (aext (zext x)) -> (zext x)
1068 // fold (aext (sext x)) -> (sext x)
Evan Chenge8136902010-04-27 19:48:13 +00001069 DEBUG(dbgs() << "\nPromoting ";
1070 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +00001071 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
Evan Chenge19aa5c2010-04-19 19:29:22 +00001072 }
1073 return SDValue();
1074}
1075
1076bool DAGCombiner::PromoteLoad(SDValue Op) {
1077 if (!LegalOperations)
1078 return false;
1079
1080 EVT VT = Op.getValueType();
1081 if (VT.isVector() || !VT.isInteger())
1082 return false;
1083
1084 // If operation type is 'undesirable', e.g. i16 on x86, consider
1085 // promoting it.
1086 unsigned Opc = Op.getOpcode();
1087 if (TLI.isTypeDesirableForOp(Opc, VT))
1088 return false;
1089
1090 EVT PVT = VT;
1091 // Consult target whether it is a good idea to promote this operation and
1092 // what's the right type to promote it to.
1093 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1094 assert(PVT != VT && "Don't know what type to promote to!");
1095
Andrew Trickef9de2a2013-05-25 02:42:55 +00001096 SDLoc dl(Op);
Evan Chenge19aa5c2010-04-19 19:29:22 +00001097 SDNode *N = Op.getNode();
1098 LoadSDNode *LD = cast<LoadSDNode>(N);
Evan Chenge8136902010-04-27 19:48:13 +00001099 EVT MemVT = LD->getMemoryVT();
1100 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
Owen Andersonb2c80da2011-02-25 21:41:48 +00001101 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
Eric Christopherd9e8eac2010-12-09 04:48:06 +00001102 : ISD::EXTLOAD)
Evan Chenge8136902010-04-27 19:48:13 +00001103 : LD->getExtensionType();
Stuart Hastings81c43062011-02-16 16:23:55 +00001104 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
Evan Chenge19aa5c2010-04-19 19:29:22 +00001105 LD->getChain(), LD->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00001106 MemVT, LD->getMemOperand());
Evan Chenge19aa5c2010-04-19 19:29:22 +00001107 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1108
Evan Cheng0abb54d2010-04-24 04:43:44 +00001109 DEBUG(dbgs() << "\nPromoting ";
Evan Chenge19aa5c2010-04-19 19:29:22 +00001110 N->dump(&DAG);
Evan Cheng0abb54d2010-04-24 04:43:44 +00001111 dbgs() << "\nTo: ";
Evan Chenge19aa5c2010-04-19 19:29:22 +00001112 Result.getNode()->dump(&DAG);
1113 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001114 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001115 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1116 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
Chandler Carruth18066972014-08-02 10:02:07 +00001117 deleteAndRecombine(N);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001118 AddToWorklist(Result.getNode());
Evan Chenge19aa5c2010-04-19 19:29:22 +00001119 return true;
1120 }
1121 return false;
1122}
1123
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001124/// \brief Recursively delete a node which has no uses and any operands for
1125/// which it is the only use.
1126///
1127/// Note that this both deletes the nodes and removes them from the worklist.
1128/// It also adds any nodes who have had a user deleted to the worklist as they
1129/// may now have only one use and subject to other combines.
1130bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1131 if (!N->use_empty())
1132 return false;
1133
1134 SmallSetVector<SDNode *, 16> Nodes;
1135 Nodes.insert(N);
1136 do {
1137 N = Nodes.pop_back_val();
1138 if (!N)
1139 continue;
1140
1141 if (N->use_empty()) {
1142 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1143 Nodes.insert(N->getOperand(i).getNode());
1144
1145 removeFromWorklist(N);
1146 DAG.DeleteNode(N);
1147 } else {
1148 AddToWorklist(N);
1149 }
1150 } while (!Nodes.empty());
1151 return true;
1152}
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001153
Chris Lattnere49c9742007-05-14 22:04:50 +00001154//===----------------------------------------------------------------------===//
1155// Main DAG Combiner implementation
1156//===----------------------------------------------------------------------===//
1157
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001158void DAGCombiner::Run(CombineLevel AtLevel) {
1159 // set the instance variables, so that the various visit routines may use it.
1160 Level = AtLevel;
Eli Friedman9d448e42011-11-12 00:35:34 +00001161 LegalOperations = Level >= AfterLegalizeVectorOps;
1162 LegalTypes = Level >= AfterLegalizeTypes;
Nate Begeman2504fe22005-09-01 23:24:04 +00001163
Paul Robinsonad06e432014-11-03 18:19:26 +00001164 // Early exit if this basic block is in an optnone function.
1165 AttributeSet FnAttrs =
1166 DAG.getMachineFunction().getFunction()->getAttributes();
1167 if (FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
1168 Attribute::OptimizeNone))
1169 return;
1170
Evan Cheng5e7658c2008-08-29 22:21:44 +00001171 // Add all the dag nodes to the worklist.
Evan Cheng5e7658c2008-08-29 22:21:44 +00001172 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1173 E = DAG.allnodes_end(); I != E; ++I)
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001174 AddToWorklist(I);
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001175
Evan Cheng5e7658c2008-08-29 22:21:44 +00001176 // Create a dummy node (which is not added to allnodes), that adds a reference
1177 // to the root node, preventing it from being deleted, and tracking any
1178 // changes of the root.
1179 HandleSDNode Dummy(DAG.getRoot());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001180
James Molloy67b6b112012-02-16 09:17:04 +00001181 // while the worklist isn't empty, find a node and
Evan Cheng5e7658c2008-08-29 22:21:44 +00001182 // try and combine it.
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001183 while (!WorklistMap.empty()) {
James Molloy67b6b112012-02-16 09:17:04 +00001184 SDNode *N;
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001185 // The Worklist holds the SDNodes in order, but it may contain null entries.
James Molloy67b6b112012-02-16 09:17:04 +00001186 do {
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001187 N = Worklist.pop_back_val();
1188 } while (!N);
1189
1190 bool GoodWorklistEntry = WorklistMap.erase(N);
1191 (void)GoodWorklistEntry;
1192 assert(GoodWorklistEntry &&
1193 "Found a worklist entry without a corresponding map entry!");
Scott Michelcf0da6c2009-02-17 22:15:04 +00001194
Evan Cheng5e7658c2008-08-29 22:21:44 +00001195 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1196 // N is deleted from the DAG, since they too may now be dead or may have a
1197 // reduced number of uses, allowing other xforms.
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001198 if (recursivelyDeleteUnusedNodes(N))
Evan Cheng5e7658c2008-08-29 22:21:44 +00001199 continue;
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001200
1201 WorklistRemover DeadNodes(*this);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001202
Chandler Carruth411fb402014-07-26 05:49:40 +00001203 // If this combine is running after legalizing the DAG, re-legalize any
1204 // nodes pulled off the worklist.
1205 if (Level == AfterLegalizeDAG) {
1206 SmallSetVector<SDNode *, 16> UpdatedNodes;
1207 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1208
1209 for (SDNode *LN : UpdatedNodes) {
1210 AddToWorklist(LN);
1211 AddUsersToWorklist(LN);
1212 }
1213 if (!NIsValid)
1214 continue;
1215 }
1216
Chandler Carruthb1432742014-07-28 17:55:07 +00001217 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1218
Chandler Carruthcde4eb52014-08-03 23:10:59 +00001219 // Add any operands of the new node which have not yet been combined to the
1220 // worklist as well. Because the worklist uniques things already, this
1221 // won't repeatedly process the same operand.
1222 CombinedNodes.insert(N);
1223 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1224 if (!CombinedNodes.count(N->getOperand(i).getNode()))
1225 AddToWorklist(N->getOperand(i).getNode());
1226
Evan Cheng5e7658c2008-08-29 22:21:44 +00001227 SDValue RV = combine(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001228
Craig Topperc0196b12014-04-14 00:51:57 +00001229 if (!RV.getNode())
Evan Cheng5e7658c2008-08-29 22:21:44 +00001230 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001231
Evan Cheng5e7658c2008-08-29 22:21:44 +00001232 ++NodesCombined;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001233
Evan Cheng5e7658c2008-08-29 22:21:44 +00001234 // If we get back the same node we passed in, rather than a new node or
1235 // zero, we know that the node must have defined multiple values and
Scott Michelcf0da6c2009-02-17 22:15:04 +00001236 // CombineTo was used. Since CombineTo takes care of the worklist
Evan Cheng5e7658c2008-08-29 22:21:44 +00001237 // mechanics for us, we have no work to do in this case.
1238 if (RV.getNode() == N)
1239 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001240
Evan Cheng5e7658c2008-08-29 22:21:44 +00001241 assert(N->getOpcode() != ISD::DELETED_NODE &&
1242 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1243 "Node was deleted but visit returned new node!");
Chris Lattner8f872d22006-05-27 00:43:02 +00001244
Chandler Carruth9f4530b2014-07-24 22:15:28 +00001245 DEBUG(dbgs() << " ... into: ";
1246 RV.getNode()->dump(&DAG));
Eric Christopherd6300d22011-07-14 01:12:15 +00001247
Devang Patelefec7712011-05-23 22:04:42 +00001248 // Transfer debug value.
1249 DAG.TransferDbgValues(SDValue(N, 0), RV);
Evan Cheng5e7658c2008-08-29 22:21:44 +00001250 if (N->getNumValues() == RV.getNode()->getNumValues())
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001251 DAG.ReplaceAllUsesWith(N, RV.getNode());
Evan Cheng5e7658c2008-08-29 22:21:44 +00001252 else {
1253 assert(N->getValueType(0) == RV.getValueType() &&
1254 N->getNumValues() == 1 && "Type mismatch");
1255 SDValue OpV = RV;
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001256 DAG.ReplaceAllUsesWith(N, &OpV);
Evan Cheng5e7658c2008-08-29 22:21:44 +00001257 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001258
Evan Cheng5e7658c2008-08-29 22:21:44 +00001259 // Push the new node and any users onto the worklist
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001260 AddToWorklist(RV.getNode());
1261 AddUsersToWorklist(RV.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001262
Dan Gohmancd0b1bf2009-01-19 21:44:21 +00001263 // Finally, if the node is now dead, remove it from the graph. The node
1264 // may not be dead if the replacement process recursively simplified to
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001265 // something else needing this node. This will also take care of adding any
1266 // operands which have lost a user to the worklist.
1267 recursivelyDeleteUnusedNodes(N);
Evan Cheng5e7658c2008-08-29 22:21:44 +00001268 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001269
Chris Lattner06f1d0f2005-10-05 06:35:28 +00001270 // If the root changed (e.g. it was a dead load, update the root).
1271 DAG.setRoot(Dummy.getValue());
Hal Finkele0cf6392012-04-16 03:33:22 +00001272 DAG.RemoveDeadNodes();
Nate Begeman21158fc2005-09-01 00:19:25 +00001273}
1274
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001275SDValue DAGCombiner::visit(SDNode *N) {
Evan Chengf1005572010-04-28 07:10:39 +00001276 switch (N->getOpcode()) {
Nate Begeman21158fc2005-09-01 00:19:25 +00001277 default: break;
Nate Begemane8f78d12005-09-01 00:33:32 +00001278 case ISD::TokenFactor: return visitTokenFactor(N);
Chris Lattneree322b42008-02-13 07:25:05 +00001279 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001280 case ISD::ADD: return visitADD(N);
1281 case ISD::SUB: return visitSUB(N);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001282 case ISD::ADDC: return visitADDC(N);
Craig Topper43a1bd62012-01-07 09:06:39 +00001283 case ISD::SUBC: return visitSUBC(N);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001284 case ISD::ADDE: return visitADDE(N);
Craig Topper43a1bd62012-01-07 09:06:39 +00001285 case ISD::SUBE: return visitSUBE(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001286 case ISD::MUL: return visitMUL(N);
1287 case ISD::SDIV: return visitSDIV(N);
1288 case ISD::UDIV: return visitUDIV(N);
1289 case ISD::SREM: return visitSREM(N);
1290 case ISD::UREM: return visitUREM(N);
1291 case ISD::MULHU: return visitMULHU(N);
1292 case ISD::MULHS: return visitMULHS(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001293 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1294 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00001295 case ISD::SMULO: return visitSMULO(N);
1296 case ISD::UMULO: return visitUMULO(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001297 case ISD::SDIVREM: return visitSDIVREM(N);
1298 case ISD::UDIVREM: return visitUDIVREM(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001299 case ISD::AND: return visitAND(N);
1300 case ISD::OR: return visitOR(N);
1301 case ISD::XOR: return visitXOR(N);
1302 case ISD::SHL: return visitSHL(N);
1303 case ISD::SRA: return visitSRA(N);
1304 case ISD::SRL: return visitSRL(N);
Adam Nemet7f928f12014-03-07 23:56:30 +00001305 case ISD::ROTR:
1306 case ISD::ROTL: return visitRotate(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001307 case ISD::CTLZ: return visitCTLZ(N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00001308 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001309 case ISD::CTTZ: return visitCTTZ(N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00001310 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001311 case ISD::CTPOP: return visitCTPOP(N);
Nate Begeman24a7eca2005-09-16 00:54:12 +00001312 case ISD::SELECT: return visitSELECT(N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00001313 case ISD::VSELECT: return visitVSELECT(N);
Nate Begeman24a7eca2005-09-16 00:54:12 +00001314 case ISD::SELECT_CC: return visitSELECT_CC(N);
1315 case ISD::SETCC: return visitSETCC(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001316 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1317 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
Chris Lattner812646a2006-05-05 05:58:59 +00001318 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001319 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1320 case ISD::TRUNCATE: return visitTRUNCATE(N);
Wesley Peck527da1b2010-11-23 03:31:01 +00001321 case ISD::BITCAST: return visitBITCAST(N);
Evan Chengb980f6f2008-05-12 23:04:07 +00001322 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
Chris Lattner6f3b5772005-09-28 22:28:18 +00001323 case ISD::FADD: return visitFADD(N);
1324 case ISD::FSUB: return visitFSUB(N);
1325 case ISD::FMUL: return visitFMUL(N);
Owen Anderson41b06652012-05-02 22:17:40 +00001326 case ISD::FMA: return visitFMA(N);
Chris Lattner6f3b5772005-09-28 22:28:18 +00001327 case ISD::FDIV: return visitFDIV(N);
1328 case ISD::FREM: return visitFREM(N);
Sanjay Patelbdf1e382014-09-26 23:01:47 +00001329 case ISD::FSQRT: return visitFSQRT(N);
Chris Lattner3bc40502006-03-05 05:30:57 +00001330 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001331 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1332 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1333 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1334 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1335 case ISD::FP_ROUND: return visitFP_ROUND(N);
1336 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1337 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1338 case ISD::FNEG: return visitFNEG(N);
1339 case ISD::FABS: return visitFABS(N);
Owen Andersona40319b2012-08-13 23:32:49 +00001340 case ISD::FFLOOR: return visitFFLOOR(N);
Matt Arsenault7c936902014-10-21 23:01:01 +00001341 case ISD::FMINNUM: return visitFMINNUM(N);
1342 case ISD::FMAXNUM: return visitFMAXNUM(N);
Owen Andersona40319b2012-08-13 23:32:49 +00001343 case ISD::FCEIL: return visitFCEIL(N);
1344 case ISD::FTRUNC: return visitFTRUNC(N);
Nate Begemanc760f802005-09-19 22:34:01 +00001345 case ISD::BRCOND: return visitBRCOND(N);
Nate Begemanc760f802005-09-19 22:34:01 +00001346 case ISD::BR_CC: return visitBR_CC(N);
Chris Lattnere260ed82005-10-10 22:04:48 +00001347 case ISD::LOAD: return visitLOAD(N);
Chris Lattner04c73702005-10-10 22:31:19 +00001348 case ISD::STORE: return visitSTORE(N);
Chris Lattner5336a592006-03-19 01:27:56 +00001349 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
Evan Cheng0de312d2007-10-06 08:19:55 +00001350 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
Dan Gohmana8665142007-06-25 16:23:39 +00001351 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1352 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +00001353 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
Chris Lattnera46dfe82006-03-28 22:11:53 +00001354 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
Manman Ren413a6cb2014-01-31 01:10:35 +00001355 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00001356 case ISD::MLOAD: return visitMLOAD(N);
1357 case ISD::MSTORE: return visitMSTORE(N);
Nate Begeman21158fc2005-09-01 00:19:25 +00001358 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001359 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001360}
1361
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001362SDValue DAGCombiner::combine(SDNode *N) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001363 SDValue RV = visit(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001364
1365 // If nothing happened, try a target-specific DAG combine.
Craig Topperc0196b12014-04-14 00:51:57 +00001366 if (!RV.getNode()) {
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001367 assert(N->getOpcode() != ISD::DELETED_NODE &&
1368 "Node was deleted but visit returned NULL!");
1369
1370 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1371 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1372
1373 // Expose the DAG combiner to the target combiner impls.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001374 TargetLowering::DAGCombinerInfo
Nadav Rotemb1dd5242012-12-27 06:47:41 +00001375 DagCombineInfo(DAG, Level, false, this);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001376
1377 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1378 }
1379 }
1380
Evan Chengf1005572010-04-28 07:10:39 +00001381 // If nothing happened still, try promoting the operation.
Craig Topperc0196b12014-04-14 00:51:57 +00001382 if (!RV.getNode()) {
Evan Chengf1005572010-04-28 07:10:39 +00001383 switch (N->getOpcode()) {
1384 default: break;
1385 case ISD::ADD:
1386 case ISD::SUB:
1387 case ISD::MUL:
1388 case ISD::AND:
1389 case ISD::OR:
1390 case ISD::XOR:
1391 RV = PromoteIntBinOp(SDValue(N, 0));
1392 break;
1393 case ISD::SHL:
1394 case ISD::SRA:
1395 case ISD::SRL:
1396 RV = PromoteIntShiftOp(SDValue(N, 0));
1397 break;
1398 case ISD::SIGN_EXTEND:
1399 case ISD::ZERO_EXTEND:
1400 case ISD::ANY_EXTEND:
1401 RV = PromoteExtend(SDValue(N, 0));
1402 break;
1403 case ISD::LOAD:
1404 if (PromoteLoad(SDValue(N, 0)))
1405 RV = SDValue(N, 0);
1406 break;
1407 }
1408 }
1409
Scott Michelcf0da6c2009-02-17 22:15:04 +00001410 // If N is a commutative binary node, try commuting it to enable more
Evan Cheng31604a62008-03-22 01:55:50 +00001411 // sdisel CSE.
Craig Topperc0196b12014-04-14 00:51:57 +00001412 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
Evan Cheng31604a62008-03-22 01:55:50 +00001413 N->getNumValues() == 1) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001414 SDValue N0 = N->getOperand(0);
1415 SDValue N1 = N->getOperand(1);
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001416
Evan Cheng31604a62008-03-22 01:55:50 +00001417 // Constant operands are canonicalized to RHS.
1418 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
Andrea Di Biagio4db1abe2014-06-09 12:32:53 +00001419 SDValue Ops[] = {N1, N0};
1420 SDNode *CSENode;
1421 if (const BinaryWithFlagsSDNode *BinNode =
1422 dyn_cast<BinaryWithFlagsSDNode>(N)) {
1423 CSENode = DAG.getNodeIfExists(
1424 N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1425 BinNode->hasNoSignedWrap(), BinNode->isExact());
1426 } else {
1427 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1428 }
Evan Chengfe7610f2008-03-24 23:55:16 +00001429 if (CSENode)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001430 return SDValue(CSENode, 0);
Evan Cheng31604a62008-03-22 01:55:50 +00001431 }
1432 }
1433
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001434 return RV;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001435}
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001436
Sanjay Patel50cbfc52014-08-28 16:29:51 +00001437/// Given a node, return its input chain if it has one, otherwise return a null
1438/// sd operand.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001439static SDValue getInputChainForNode(SDNode *N) {
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001440 if (unsigned NumOps = N->getNumOperands()) {
Owen Anderson9f944592009-08-11 20:47:22 +00001441 if (N->getOperand(0).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001442 return N->getOperand(0);
Stephen Lin8e8424e2013-07-09 00:44:49 +00001443 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001444 return N->getOperand(NumOps-1);
1445 for (unsigned i = 1; i < NumOps-1; ++i)
Owen Anderson9f944592009-08-11 20:47:22 +00001446 if (N->getOperand(i).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001447 return N->getOperand(i);
1448 }
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001449 return SDValue();
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001450}
1451
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001452SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001453 // If N has two operands, where one has an input chain equal to the other,
1454 // the 'other' chain is redundant.
1455 if (N->getNumOperands() == 2) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00001456 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001457 return N->getOperand(0);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001458 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001459 return N->getOperand(1);
1460 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001461
Chris Lattner48fb92f2007-05-16 06:37:59 +00001462 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001463 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001464 SmallPtrSet<SDNode*, 16> SeenOps;
Chris Lattner48fb92f2007-05-16 06:37:59 +00001465 bool Changed = false; // If we should replace this token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001466
Jim Laskey708d0db2006-10-04 16:53:27 +00001467 // Start out with this token factor.
Jim Laskeyd07be232006-09-25 16:29:54 +00001468 TFs.push_back(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001469
Jim Laskey0463e082006-10-07 23:37:56 +00001470 // Iterate through token factors. The TFs grows when new token factors are
Jim Laskey6549d222006-10-05 15:07:25 +00001471 // encountered.
1472 for (unsigned i = 0; i < TFs.size(); ++i) {
1473 SDNode *TF = TFs[i];
Scott Michelcf0da6c2009-02-17 22:15:04 +00001474
Jim Laskey708d0db2006-10-04 16:53:27 +00001475 // Check each of the operands.
1476 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001477 SDValue Op = TF->getOperand(i);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001478
Jim Laskey708d0db2006-10-04 16:53:27 +00001479 switch (Op.getOpcode()) {
1480 case ISD::EntryToken:
Jim Laskey6549d222006-10-05 15:07:25 +00001481 // Entry tokens don't need to be added to the list. They are
1482 // rededundant.
1483 Changed = true;
Jim Laskey708d0db2006-10-04 16:53:27 +00001484 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001485
Jim Laskey708d0db2006-10-04 16:53:27 +00001486 case ISD::TokenFactor:
Nate Begeman879d8f12009-09-15 00:18:30 +00001487 if (Op.hasOneUse() &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00001488 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
Jim Laskey708d0db2006-10-04 16:53:27 +00001489 // Queue up for processing.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001490 TFs.push_back(Op.getNode());
Jim Laskey708d0db2006-10-04 16:53:27 +00001491 // Clean up in case the token factor is removed.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001492 AddToWorklist(Op.getNode());
Jim Laskey708d0db2006-10-04 16:53:27 +00001493 Changed = true;
1494 break;
Jim Laskeyd07be232006-09-25 16:29:54 +00001495 }
Jim Laskey708d0db2006-10-04 16:53:27 +00001496 // Fall thru
Scott Michelcf0da6c2009-02-17 22:15:04 +00001497
Jim Laskey708d0db2006-10-04 16:53:27 +00001498 default:
Chris Lattner48fb92f2007-05-16 06:37:59 +00001499 // Only add if it isn't already in the list.
David Blaikie70573dc2014-11-19 07:49:26 +00001500 if (SeenOps.insert(Op.getNode()).second)
Jim Laskey6549d222006-10-05 15:07:25 +00001501 Ops.push_back(Op);
Chris Lattner48fb92f2007-05-16 06:37:59 +00001502 else
1503 Changed = true;
Jim Laskey708d0db2006-10-04 16:53:27 +00001504 break;
Jim Laskeyd07be232006-09-25 16:29:54 +00001505 }
1506 }
Jim Laskey708d0db2006-10-04 16:53:27 +00001507 }
Wesley Peck527da1b2010-11-23 03:31:01 +00001508
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001509 SDValue Result;
Jim Laskey708d0db2006-10-04 16:53:27 +00001510
1511 // If we've change things around then replace token factor.
1512 if (Changed) {
Dan Gohman70de4cb2008-01-29 13:02:09 +00001513 if (Ops.empty()) {
Jim Laskey708d0db2006-10-04 16:53:27 +00001514 // The entry token is the only possible outcome.
1515 Result = DAG.getEntryNode();
1516 } else {
1517 // New and improved token factor.
Craig Topper48d114b2014-04-26 18:35:24 +00001518 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
Nate Begeman02b23c62005-10-13 03:11:28 +00001519 }
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001520
Jim Laskeydcf983c2006-10-13 23:32:28 +00001521 // Don't add users to work list.
1522 return CombineTo(N, Result, false);
Nate Begeman02b23c62005-10-13 03:11:28 +00001523 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001524
Jim Laskey708d0db2006-10-04 16:53:27 +00001525 return Result;
Nate Begeman21158fc2005-09-01 00:19:25 +00001526}
1527
Chris Lattneree322b42008-02-13 07:25:05 +00001528/// MERGE_VALUES can always be eliminated.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001529SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001530 WorklistRemover DeadNodes(*this);
Dan Gohman9d26c852009-08-10 23:43:19 +00001531 // Replacing results may cause a different MERGE_VALUES to suddenly
1532 // be CSE'd with N, and carry its uses with it. Iterate until no
1533 // uses remain, to ensure that the node can be safely deleted.
Pete Cooperfe5b84b2012-06-20 19:35:43 +00001534 // First add the users of this node to the work list so that they
1535 // can be tried again once they have new operands.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001536 AddUsersToWorklist(N);
Dan Gohman9d26c852009-08-10 23:43:19 +00001537 do {
1538 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001539 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
Dan Gohman9d26c852009-08-10 23:43:19 +00001540 } while (!N->use_empty());
Chandler Carruth18066972014-08-02 10:02:07 +00001541 deleteAndRecombine(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001542 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattneree322b42008-02-13 07:25:05 +00001543}
1544
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001545SDValue DAGCombiner::visitADD(SDNode *N) {
1546 SDValue N0 = N->getOperand(0);
1547 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001548 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1549 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001550 EVT VT = N0.getValueType();
Dan Gohmana8665142007-06-25 16:23:39 +00001551
1552 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00001553 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001554 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001555 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topperd8005db2012-12-10 08:12:29 +00001556
1557 // fold (add x, 0) -> x, vector edition
1558 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1559 return N0;
1560 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1561 return N1;
Dan Gohman80f9f072007-07-13 20:03:40 +00001562 }
Bill Wendling0864a752008-12-10 22:36:00 +00001563
Dan Gohman06563a82007-07-03 14:03:57 +00001564 // fold (add x, undef) -> undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00001565 if (N0.getOpcode() == ISD::UNDEF)
1566 return N0;
1567 if (N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00001568 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00001569 // fold (add c1, c2) -> c1+c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001570 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00001571 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00001572 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00001573 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001574 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001575 // fold (add x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001576 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00001577 return N0;
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001578 // fold (add Sym, c) -> Sym+c
1579 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001580 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001581 GA->getOpcode() == ISD::GlobalAddress)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001582 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001583 GA->getOffset() +
1584 (uint64_t)N1C->getSExtValue());
Chris Lattner3470b5d2006-01-12 20:22:43 +00001585 // fold ((c1-A)+c2) -> (c1+c2)-A
1586 if (N1C && N0.getOpcode() == ISD::SUB)
1587 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001588 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Dan Gohmanb72127a2008-03-13 22:13:53 +00001589 DAG.getConstant(N1C->getAPIntValue()+
1590 N0C->getAPIntValue(), VT),
Chris Lattner3470b5d2006-01-12 20:22:43 +00001591 N0.getOperand(1));
Nate Begeman22e251a2006-02-03 06:46:56 +00001592 // reassociate add
Andrew Trickef9de2a2013-05-25 02:42:55 +00001593 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00001594 if (RADD.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00001595 return RADD;
Nate Begeman21158fc2005-09-01 00:19:25 +00001596 // fold ((0-A) + B) -> B-A
1597 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1598 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001599 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
Nate Begeman21158fc2005-09-01 00:19:25 +00001600 // fold (A + (0-B)) -> A-B
1601 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1602 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001603 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
Chris Lattner6f3b5772005-09-28 22:28:18 +00001604 // fold (A+(B-A)) -> B
1605 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
Nate Begemand23739d2005-09-06 04:43:02 +00001606 return N1.getOperand(0);
Dale Johannesen73bc0ba2008-11-27 00:43:21 +00001607 // fold ((B-A)+A) -> B
1608 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1609 return N0.getOperand(0);
Dale Johannesen8c766702008-12-02 01:30:54 +00001610 // fold (A+(B-(A+C))) to (B-C)
1611 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001612 N0 == N1.getOperand(1).getOperand(0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001613 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
Dale Johannesen8c766702008-12-02 01:30:54 +00001614 N1.getOperand(1).getOperand(1));
Dale Johannesen8c766702008-12-02 01:30:54 +00001615 // fold (A+(B-(C+A))) to (B-C)
1616 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001617 N0 == N1.getOperand(1).getOperand(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001618 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
Dale Johannesen8c766702008-12-02 01:30:54 +00001619 N1.getOperand(1).getOperand(0));
Dale Johannesenee573fc2008-12-23 23:47:22 +00001620 // fold (A+((B-A)+or-C)) to (B+or-C)
Dale Johannesen54bdec22008-12-02 18:40:40 +00001621 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1622 N1.getOperand(0).getOpcode() == ISD::SUB &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001623 N0 == N1.getOperand(0).getOperand(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001624 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
Bill Wendlingc4423482009-01-30 02:31:17 +00001625 N1.getOperand(0).getOperand(0), N1.getOperand(1));
Dale Johannesen54bdec22008-12-02 18:40:40 +00001626
Dale Johannesen8c766702008-12-02 01:30:54 +00001627 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1628 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1629 SDValue N00 = N0.getOperand(0);
1630 SDValue N01 = N0.getOperand(1);
1631 SDValue N10 = N1.getOperand(0);
1632 SDValue N11 = N1.getOperand(1);
Bill Wendlingc4423482009-01-30 02:31:17 +00001633
1634 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001635 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1636 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1637 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
Dale Johannesen8c766702008-12-02 01:30:54 +00001638 }
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001639
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001640 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1641 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001642
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001643 // fold (a+b) -> (a|b) iff a and b share no bits.
Duncan Sands13237ac2008-06-06 12:08:01 +00001644 if (VT.isInteger() && !VT.isVector()) {
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001645 APInt LHSZero, LHSOne;
1646 APInt RHSZero, RHSOne;
Jay Foada0653a32014-05-14 21:14:37 +00001647 DAG.computeKnownBits(N0, LHSZero, LHSOne);
Bill Wendlingc4423482009-01-30 02:31:17 +00001648
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001649 if (LHSZero.getBoolValue()) {
Jay Foada0653a32014-05-14 21:14:37 +00001650 DAG.computeKnownBits(N1, RHSZero, RHSOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001651
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001652 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1653 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
Owen Anderson60a46782014-01-31 00:51:43 +00001654 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1655 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1656 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1657 }
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001658 }
1659 }
Evan Chengeb99bd72006-11-06 08:14:30 +00001660
Dan Gohman954f4902010-01-19 23:30:49 +00001661 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1662 if (N1.getOpcode() == ISD::SHL &&
1663 N1.getOperand(0).getOpcode() == ISD::SUB)
1664 if (ConstantSDNode *C =
1665 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1666 if (C->getAPIntValue() == 0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001667 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1668 DAG.getNode(ISD::SHL, SDLoc(N), VT,
Dan Gohman954f4902010-01-19 23:30:49 +00001669 N1.getOperand(0).getOperand(1),
1670 N1.getOperand(1)));
1671 if (N0.getOpcode() == ISD::SHL &&
1672 N0.getOperand(0).getOpcode() == ISD::SUB)
1673 if (ConstantSDNode *C =
1674 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1675 if (C->getAPIntValue() == 0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001676 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1677 DAG.getNode(ISD::SHL, SDLoc(N), VT,
Dan Gohman954f4902010-01-19 23:30:49 +00001678 N0.getOperand(0).getOperand(1),
1679 N0.getOperand(1)));
1680
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001681 if (N1.getOpcode() == ISD::AND) {
1682 SDValue AndOp0 = N1.getOperand(0);
Wesley Peck527da1b2010-11-23 03:31:01 +00001683 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001684 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1685 unsigned DestBits = VT.getScalarType().getSizeInBits();
Wesley Peck527da1b2010-11-23 03:31:01 +00001686
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001687 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1688 // and similar xforms where the inner op is either ~0 or 0.
1689 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001690 SDLoc DL(N);
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001691 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1692 }
1693 }
1694
Benjamin Kramer1f4dfbb2010-12-22 23:17:45 +00001695 // add (sext i1), X -> sub X, (zext i1)
1696 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1697 N0.getOperand(0).getValueType() == MVT::i1 &&
1698 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001699 SDLoc DL(N);
Benjamin Kramer1f4dfbb2010-12-22 23:17:45 +00001700 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1701 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1702 }
1703
Jan Veselyaf62cf42014-10-17 14:45:25 +00001704 // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1705 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1706 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1707 if (TN->getVT() == MVT::i1) {
1708 SDLoc DL(N);
1709 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1710 DAG.getConstant(1, VT));
1711 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1712 }
1713 }
1714
Evan Chengf1005572010-04-28 07:10:39 +00001715 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001716}
1717
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001718SDValue DAGCombiner::visitADDC(SDNode *N) {
1719 SDValue N0 = N->getOperand(0);
1720 SDValue N1 = N->getOperand(1);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001721 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1722 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001723 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001724
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001725 // If the flag result is dead, turn this into an ADD.
Craig Topper0515cd42012-01-07 18:31:09 +00001726 if (!N->hasAnyUseOfValue(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001727 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
Dale Johannesen5234d372009-06-02 03:12:52 +00001728 DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001729 SDLoc(N), MVT::Glue));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001730
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001731 // canonicalize constant to RHS.
Dan Gohmanb4e26372008-06-23 15:29:14 +00001732 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001733 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001734
Chris Lattner47206662007-03-04 20:40:38 +00001735 // fold (addc x, 0) -> x + no carry out
1736 if (N1C && N1C->isNullValue())
Dale Johannesen5234d372009-06-02 03:12:52 +00001737 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001738 SDLoc(N), MVT::Glue));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001739
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001740 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001741 APInt LHSZero, LHSOne;
1742 APInt RHSZero, RHSOne;
Jay Foada0653a32014-05-14 21:14:37 +00001743 DAG.computeKnownBits(N0, LHSZero, LHSOne);
Bill Wendling61277572009-01-30 02:38:00 +00001744
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001745 if (LHSZero.getBoolValue()) {
Jay Foada0653a32014-05-14 21:14:37 +00001746 DAG.computeKnownBits(N1, RHSZero, RHSOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001747
Chris Lattner47206662007-03-04 20:40:38 +00001748 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1749 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001750 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001751 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
Dale Johannesen5234d372009-06-02 03:12:52 +00001752 DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001753 SDLoc(N), MVT::Glue));
Chris Lattner47206662007-03-04 20:40:38 +00001754 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001755
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001756 return SDValue();
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001757}
1758
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001759SDValue DAGCombiner::visitADDE(SDNode *N) {
1760 SDValue N0 = N->getOperand(0);
1761 SDValue N1 = N->getOperand(1);
1762 SDValue CarryIn = N->getOperand(2);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001763 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1764 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001765
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001766 // canonicalize constant to RHS
Dan Gohmanb4e26372008-06-23 15:29:14 +00001767 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001768 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
Bill Wendling61277572009-01-30 02:38:00 +00001769 N1, N0, CarryIn);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001770
Chris Lattner47206662007-03-04 20:40:38 +00001771 // fold (adde x, y, false) -> (addc x, y)
Dale Johannesen5234d372009-06-02 03:12:52 +00001772 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001773 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001774
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001775 return SDValue();
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001776}
1777
Eric Christophere5ca1e02011-02-16 04:50:12 +00001778// Since it may not be valid to emit a fold to zero for vector initializers
1779// check if we can before folding.
Andrew Trickef9de2a2013-05-25 02:42:55 +00001780static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
Hal Finkel6c29bd92013-07-09 17:02:45 +00001781 SelectionDAG &DAG,
1782 bool LegalOperations, bool LegalTypes) {
Stephen Lin8e8424e2013-07-09 00:44:49 +00001783 if (!VT.isVector())
Eric Christophere5ca1e02011-02-16 04:50:12 +00001784 return DAG.getConstant(0, VT);
Daniel Sandersb021c6f2013-11-25 11:14:43 +00001785 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1786 return DAG.getConstant(0, VT);
Eric Christophere5ca1e02011-02-16 04:50:12 +00001787 return SDValue();
1788}
1789
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001790SDValue DAGCombiner::visitSUB(SDNode *N) {
1791 SDValue N0 = N->getOperand(0);
1792 SDValue N1 = N->getOperand(1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001793 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1794 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
Craig Topperc0196b12014-04-14 00:51:57 +00001795 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
Eric Christopherd6300d22011-07-14 01:12:15 +00001796 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
Owen Anderson53aa7a92009-08-10 22:56:29 +00001797 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001798
Dan Gohmana8665142007-06-25 16:23:39 +00001799 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00001800 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001801 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001802 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topperd8005db2012-12-10 08:12:29 +00001803
1804 // fold (sub x, 0) -> x, vector edition
1805 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1806 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00001807 }
Bill Wendling0864a752008-12-10 22:36:00 +00001808
Chris Lattnereeb2bda2005-10-17 01:07:11 +00001809 // fold (sub x, x) -> 0
Eric Christopheref721412011-02-16 01:10:03 +00001810 // FIXME: Refactor this and xor and other similar operations together.
Eric Christophere5ca1e02011-02-16 04:50:12 +00001811 if (N0 == N1)
Hal Finkel6c29bd92013-07-09 17:02:45 +00001812 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
Nate Begeman21158fc2005-09-01 00:19:25 +00001813 // fold (sub c1, c2) -> c1-c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001814 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00001815 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
Chris Lattnerc38fb8e2005-10-11 06:07:15 +00001816 // fold (sub x, c) -> (add x, -c)
1817 if (N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001818 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
Dan Gohmanb72127a2008-03-13 22:13:53 +00001819 DAG.getConstant(-N1C->getAPIntValue(), VT));
Evan Cheng88b65bc2010-01-18 21:38:44 +00001820 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1821 if (N0C && N0C->isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001822 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
Benjamin Kramer65bb14d2011-01-29 12:34:05 +00001823 // fold A-(A-B) -> B
1824 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1825 return N1.getOperand(1);
Nate Begeman21158fc2005-09-01 00:19:25 +00001826 // fold (A+B)-A -> B
Chris Lattner6f3b5772005-09-28 22:28:18 +00001827 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
Nate Begemand23739d2005-09-06 04:43:02 +00001828 return N0.getOperand(1);
Nate Begeman21158fc2005-09-01 00:19:25 +00001829 // fold (A+B)-B -> A
Chris Lattner6f3b5772005-09-28 22:28:18 +00001830 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
Scott Michelcf0da6c2009-02-17 22:15:04 +00001831 return N0.getOperand(0);
Eric Christopherd6300d22011-07-14 01:12:15 +00001832 // fold C2-(A+C1) -> (C2-C1)-A
1833 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
Nadav Rotem841c9a82012-09-20 08:53:31 +00001834 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1835 VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00001836 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
Bill Wendlingd1634052012-07-19 00:04:14 +00001837 N1.getOperand(0));
Eric Christopherd6300d22011-07-14 01:12:15 +00001838 }
Dale Johannesenee573fc2008-12-23 23:47:22 +00001839 // fold ((A+(B+or-C))-B) -> A+or-C
Dale Johannesenf51dcef2008-12-16 22:13:49 +00001840 if (N0.getOpcode() == ISD::ADD &&
Dale Johannesenacc84e52008-12-23 23:01:27 +00001841 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1842 N0.getOperand(1).getOpcode() == ISD::ADD) &&
Dale Johannesenf51dcef2008-12-16 22:13:49 +00001843 N0.getOperand(1).getOperand(0) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001844 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001845 N0.getOperand(0), N0.getOperand(1).getOperand(1));
Dale Johannesenacc84e52008-12-23 23:01:27 +00001846 // fold ((A+(C+B))-B) -> A+C
1847 if (N0.getOpcode() == ISD::ADD &&
1848 N0.getOperand(1).getOpcode() == ISD::ADD &&
1849 N0.getOperand(1).getOperand(1) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001850 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001851 N0.getOperand(0), N0.getOperand(1).getOperand(0));
Dale Johannesend2a46852008-12-23 01:59:54 +00001852 // fold ((A-(B-C))-C) -> A-B
1853 if (N0.getOpcode() == ISD::SUB &&
1854 N0.getOperand(1).getOpcode() == ISD::SUB &&
1855 N0.getOperand(1).getOperand(1) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001856 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001857 N0.getOperand(0), N0.getOperand(1).getOperand(0));
Bill Wendling48ff08e2009-01-30 02:42:10 +00001858
Dan Gohman06563a82007-07-03 14:03:57 +00001859 // If either operand of a sub is undef, the result is undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00001860 if (N0.getOpcode() == ISD::UNDEF)
1861 return N0;
1862 if (N1.getOpcode() == ISD::UNDEF)
1863 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00001864
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001865 // If the relocation model supports it, consider symbol offsets.
1866 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001867 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001868 // fold (sub Sym, c) -> Sym-c
1869 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001870 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001871 GA->getOffset() -
1872 (uint64_t)N1C->getSExtValue());
1873 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1874 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1875 if (GA->getGlobal() == GB->getGlobal())
1876 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1877 VT);
1878 }
1879
Jan Veselyaf62cf42014-10-17 14:45:25 +00001880 // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1881 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1882 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1883 if (TN->getVT() == MVT::i1) {
1884 SDLoc DL(N);
1885 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1886 DAG.getConstant(1, VT));
1887 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1888 }
1889 }
1890
Evan Chengf1005572010-04-28 07:10:39 +00001891 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001892}
1893
Craig Topper43a1bd62012-01-07 09:06:39 +00001894SDValue DAGCombiner::visitSUBC(SDNode *N) {
1895 SDValue N0 = N->getOperand(0);
1896 SDValue N1 = N->getOperand(1);
1897 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1898 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1899 EVT VT = N0.getValueType();
1900
1901 // If the flag result is dead, turn this into an SUB.
Craig Topper0515cd42012-01-07 18:31:09 +00001902 if (!N->hasAnyUseOfValue(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001903 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1904 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001905 MVT::Glue));
1906
1907 // fold (subc x, x) -> 0 + no borrow
1908 if (N0 == N1)
1909 return CombineTo(N, DAG.getConstant(0, VT),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001910 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001911 MVT::Glue));
1912
1913 // fold (subc x, 0) -> x + no borrow
1914 if (N1C && N1C->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001915 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001916 MVT::Glue));
1917
1918 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1919 if (N0C && N0C->isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001920 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1921 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001922 MVT::Glue));
1923
1924 return SDValue();
1925}
1926
1927SDValue DAGCombiner::visitSUBE(SDNode *N) {
1928 SDValue N0 = N->getOperand(0);
1929 SDValue N1 = N->getOperand(1);
1930 SDValue CarryIn = N->getOperand(2);
1931
1932 // fold (sube x, y, false) -> (subc x, y)
1933 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001934 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
Craig Topper43a1bd62012-01-07 09:06:39 +00001935
1936 return SDValue();
1937}
1938
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001939SDValue DAGCombiner::visitMUL(SDNode *N) {
1940 SDValue N0 = N->getOperand(0);
1941 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001942 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001943
Dan Gohman06563a82007-07-03 14:03:57 +00001944 // fold (mul x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00001945 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00001946 return DAG.getConstant(0, VT);
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001947
1948 bool N0IsConst = false;
1949 bool N1IsConst = false;
1950 APInt ConstValue0, ConstValue1;
1951 // fold vector ops
1952 if (VT.isVector()) {
1953 SDValue FoldedVOp = SimplifyVBinOp(N);
1954 if (FoldedVOp.getNode()) return FoldedVOp;
1955
1956 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1957 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1958 } else {
Craig Topperc0196b12014-04-14 00:51:57 +00001959 N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
Jack Carterd4e96152013-10-17 01:34:33 +00001960 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1961 : APInt();
Craig Topperc0196b12014-04-14 00:51:57 +00001962 N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
Jack Carterd4e96152013-10-17 01:34:33 +00001963 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1964 : APInt();
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001965 }
1966
Nate Begeman21158fc2005-09-01 00:19:25 +00001967 // fold (mul c1, c2) -> c1*c2
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001968 if (N0IsConst && N1IsConst)
1969 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1970
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00001971 // canonicalize constant to RHS
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001972 if (N0IsConst && !N1IsConst)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001973 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001974 // fold (mul x, 0) -> 0
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001975 if (N1IsConst && ConstValue1 == 0)
Nate Begemand23739d2005-09-06 04:43:02 +00001976 return N1;
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001977 // We require a splat of the entire scalar bit width for non-contiguous
1978 // bit patterns.
1979 bool IsFullSplat =
1980 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001981 // fold (mul x, 1) -> x
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001982 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001983 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00001984 // fold (mul x, -1) -> 0-x
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001985 if (N1IsConst && ConstValue1.isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001986 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001987 DAG.getConstant(0, VT), N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001988 // fold (mul x, (1 << c)) -> x << c
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001989 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001990 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001991 DAG.getConstant(ConstValue1.logBase2(),
Owen Andersonb2c80da2011-02-25 21:41:48 +00001992 getShiftAmountTy(N0.getValueType())));
Chris Lattnera70878d2005-10-30 06:41:49 +00001993 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001994 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001995 unsigned Log2Val = (-ConstValue1).logBase2();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001996 // FIXME: If the input is something that is easily negated (e.g. a
Chris Lattnera70878d2005-10-30 06:41:49 +00001997 // single-use add), we should put the negate there.
Andrew Trickef9de2a2013-05-25 02:42:55 +00001998 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00001999 DAG.getConstant(0, VT),
Andrew Trickef9de2a2013-05-25 02:42:55 +00002000 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002001 DAG.getConstant(Log2Val,
2002 getShiftAmountTy(N0.getValueType()))));
Chris Lattner4249b9a2009-03-09 20:22:18 +00002003 }
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002004
2005 APInt Val;
Chris Lattner324871e2006-03-01 03:44:24 +00002006 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
Stephen Lincfe7f352013-07-08 00:37:03 +00002007 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002008 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2009 isa<ConstantSDNode>(N0.getOperand(1)))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002010 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002011 N1, N0.getOperand(1));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002012 AddToWorklist(C3.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002013 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002014 N0.getOperand(0), C3);
Chris Lattner324871e2006-03-01 03:44:24 +00002015 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002016
Chris Lattner324871e2006-03-01 03:44:24 +00002017 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2018 // use.
2019 {
Craig Topperc0196b12014-04-14 00:51:57 +00002020 SDValue Sh(nullptr,0), Y(nullptr,0);
Chris Lattner324871e2006-03-01 03:44:24 +00002021 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
Stephen Lincfe7f352013-07-08 00:37:03 +00002022 if (N0.getOpcode() == ISD::SHL &&
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002023 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2024 isa<ConstantSDNode>(N0.getOperand(1))) &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00002025 N0.getNode()->hasOneUse()) {
Chris Lattner324871e2006-03-01 03:44:24 +00002026 Sh = N0; Y = N1;
Scott Michelcf0da6c2009-02-17 22:15:04 +00002027 } else if (N1.getOpcode() == ISD::SHL &&
Gabor Greife12264b2008-08-30 19:29:20 +00002028 isa<ConstantSDNode>(N1.getOperand(1)) &&
2029 N1.getNode()->hasOneUse()) {
Chris Lattner324871e2006-03-01 03:44:24 +00002030 Sh = N1; Y = N0;
2031 }
Bill Wendlingb48dcf62009-01-30 02:49:26 +00002032
Gabor Greiff304a7a2008-08-28 21:40:38 +00002033 if (Sh.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002034 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002035 Sh.getOperand(0), Y);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002036 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002037 Mul, Sh.getOperand(1));
Chris Lattner324871e2006-03-01 03:44:24 +00002038 }
2039 }
Bill Wendlingb48dcf62009-01-30 02:49:26 +00002040
Chris Lattnerf29f5202006-03-04 23:33:26 +00002041 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002042 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2043 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2044 isa<ConstantSDNode>(N0.getOperand(1))))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002045 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2046 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002047 N0.getOperand(0), N1),
Andrew Trickef9de2a2013-05-25 02:42:55 +00002048 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002049 N0.getOperand(1), N1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00002050
Nate Begeman22e251a2006-02-03 06:46:56 +00002051 // reassociate mul
Andrew Trickef9de2a2013-05-25 02:42:55 +00002052 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00002053 if (RMUL.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00002054 return RMUL;
Dan Gohmana8665142007-06-25 16:23:39 +00002055
Evan Chengf1005572010-04-28 07:10:39 +00002056 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002057}
2058
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002059SDValue DAGCombiner::visitSDIV(SDNode *N) {
2060 SDValue N0 = N->getOperand(0);
2061 SDValue N1 = N->getOperand(1);
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002062 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2063 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002064 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00002065
Dan Gohmana8665142007-06-25 16:23:39 +00002066 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00002067 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002068 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002069 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00002070 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002071
Nate Begeman21158fc2005-09-01 00:19:25 +00002072 // fold (sdiv c1, c2) -> c1/c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002073 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002074 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
Nate Begeman4dd38312005-10-21 00:02:42 +00002075 // fold (sdiv X, 1) -> X
Eli Friedmane9e356a2011-10-27 02:06:39 +00002076 if (N1C && N1C->getAPIntValue() == 1LL)
Nate Begeman4dd38312005-10-21 00:02:42 +00002077 return N0;
2078 // fold (sdiv X, -1) -> 0-X
2079 if (N1C && N1C->isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00002080 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling5b663e72009-01-30 02:52:17 +00002081 DAG.getConstant(0, VT), N0);
Chris Lattner5bcd0dd82005-10-07 06:10:46 +00002082 // If we know the sign bits of both operands are zero, strength reduce to a
2083 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
Duncan Sands13237ac2008-06-06 12:08:01 +00002084 if (!VT.isVector()) {
Dan Gohman1f372ed2008-02-25 21:11:39 +00002085 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002086 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
Bill Wendling5b663e72009-01-30 02:52:17 +00002087 N0, N1);
Chris Lattner2ee91f42008-01-27 23:32:17 +00002088 }
Benjamin Kramerad016872014-04-26 13:00:53 +00002089
Nate Begeman57b35672006-02-17 07:26:20 +00002090 // fold (sdiv X, pow2) -> simple ops after legalize
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002091 if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2092 (-N1C->getAPIntValue()).isPowerOf2())) {
Nate Begeman4dd38312005-10-21 00:02:42 +00002093 // If dividing by powers of two is cheap, then don't perform the following
2094 // fold.
Sanjay Patel2cdea4c2014-08-21 22:31:48 +00002095 if (TLI.isPow2SDivCheap())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002096 return SDValue();
Bill Wendling5b663e72009-01-30 02:52:17 +00002097
Chad Rosier17020f92014-07-23 14:57:52 +00002098 // Target-specific implementation of sdiv x, pow2.
2099 SDValue Res = BuildSDIVPow2(N);
2100 if (Res.getNode())
2101 return Res;
2102
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002103 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
Bill Wendling5b663e72009-01-30 02:52:17 +00002104
Chris Lattner471627c2006-02-16 08:02:36 +00002105 // Splat the sign bit into the register
Benjamin Kramerad016872014-04-26 13:00:53 +00002106 SDValue SGN =
2107 DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2108 DAG.getConstant(VT.getScalarSizeInBits() - 1,
2109 getShiftAmountTy(N0.getValueType())));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002110 AddToWorklist(SGN.getNode());
Bill Wendling5b663e72009-01-30 02:52:17 +00002111
Chris Lattner471627c2006-02-16 08:02:36 +00002112 // Add (N0 < 0) ? abs2 - 1 : 0;
Benjamin Kramerad016872014-04-26 13:00:53 +00002113 SDValue SRL =
2114 DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2115 DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2116 getShiftAmountTy(SGN.getValueType())));
Andrew Trickef9de2a2013-05-25 02:42:55 +00002117 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002118 AddToWorklist(SRL.getNode());
2119 AddToWorklist(ADD.getNode()); // Divide by pow2
Andrew Trickef9de2a2013-05-25 02:42:55 +00002120 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002121 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
Bill Wendling5b663e72009-01-30 02:52:17 +00002122
Nate Begeman4dd38312005-10-21 00:02:42 +00002123 // If we're dividing by a positive value, we're done. Otherwise, we must
2124 // negate the result.
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002125 if (N1C->getAPIntValue().isNonNegative())
Nate Begeman4dd38312005-10-21 00:02:42 +00002126 return SRA;
Bill Wendling5b663e72009-01-30 02:52:17 +00002127
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002128 AddToWorklist(SRA.getNode());
Benjamin Kramerad016872014-04-26 13:00:53 +00002129 return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
Nate Begeman4dd38312005-10-21 00:02:42 +00002130 }
Bill Wendling5b663e72009-01-30 02:52:17 +00002131
Nate Begemanc6f067a2005-10-20 02:15:44 +00002132 // if integer divide is expensive and we satisfy the requirements, emit an
2133 // alternate sequence.
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002134 if (N1C && !TLI.isIntDivCheap()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002135 SDValue Op = BuildSDIV(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002136 if (Op.getNode()) return Op;
Nate Begemanc6f067a2005-10-20 02:15:44 +00002137 }
Dan Gohmana8665142007-06-25 16:23:39 +00002138
Dan Gohman06563a82007-07-03 14:03:57 +00002139 // undef / X -> 0
2140 if (N0.getOpcode() == ISD::UNDEF)
2141 return DAG.getConstant(0, VT);
2142 // X / undef -> undef
2143 if (N1.getOpcode() == ISD::UNDEF)
2144 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002145
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002146 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002147}
2148
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002149SDValue DAGCombiner::visitUDIV(SDNode *N) {
2150 SDValue N0 = N->getOperand(0);
2151 SDValue N1 = N->getOperand(1);
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002152 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2153 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002154 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002155
Dan Gohmana8665142007-06-25 16:23:39 +00002156 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00002157 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002158 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002159 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00002160 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002161
Nate Begeman21158fc2005-09-01 00:19:25 +00002162 // fold (udiv c1, c2) -> c1/c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002163 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002164 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00002165 // fold (udiv x, (1 << c)) -> x >>u c
Dan Gohmanb72127a2008-03-13 22:13:53 +00002166 if (N1C && N1C->getAPIntValue().isPowerOf2())
Andrew Trickef9de2a2013-05-25 02:42:55 +00002167 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
Dan Gohmanb72127a2008-03-13 22:13:53 +00002168 DAG.getConstant(N1C->getAPIntValue().logBase2(),
Owen Andersonb2c80da2011-02-25 21:41:48 +00002169 getShiftAmountTy(N0.getValueType())));
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002170 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
Nate Begeman25d178b2006-02-05 07:20:23 +00002171 if (N1.getOpcode() == ISD::SHL) {
2172 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
Dan Gohmanb72127a2008-03-13 22:13:53 +00002173 if (SHC->getAPIntValue().isPowerOf2()) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00002174 EVT ADDVT = N1.getOperand(1).getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00002175 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
Bill Wendlingaff3e032009-01-30 02:55:25 +00002176 N1.getOperand(1),
2177 DAG.getConstant(SHC->getAPIntValue()
2178 .logBase2(),
2179 ADDVT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002180 AddToWorklist(Add.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002181 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
Nate Begeman25d178b2006-02-05 07:20:23 +00002182 }
2183 }
2184 }
Nate Begemanc6f067a2005-10-20 02:15:44 +00002185 // fold (udiv x, c) -> alternate
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002186 if (N1C && !TLI.isIntDivCheap()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002187 SDValue Op = BuildUDIV(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002188 if (Op.getNode()) return Op;
Chris Lattner9faa5b72005-10-22 18:50:15 +00002189 }
Dan Gohmana8665142007-06-25 16:23:39 +00002190
Dan Gohman06563a82007-07-03 14:03:57 +00002191 // undef / X -> 0
2192 if (N0.getOpcode() == ISD::UNDEF)
2193 return DAG.getConstant(0, VT);
2194 // X / undef -> undef
2195 if (N1.getOpcode() == ISD::UNDEF)
2196 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002197
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002198 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002199}
2200
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002201SDValue DAGCombiner::visitSREM(SDNode *N) {
2202 SDValue N0 = N->getOperand(0);
2203 SDValue N1 = N->getOperand(1);
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002204 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2205 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002206 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002207
Nate Begeman21158fc2005-09-01 00:19:25 +00002208 // fold (srem c1, c2) -> c1%c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002209 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002210 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
Nate Begeman6828ed92005-10-10 21:26:48 +00002211 // If we know the sign bits of both operands are zero, strength reduce to a
2212 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
Duncan Sands13237ac2008-06-06 12:08:01 +00002213 if (!VT.isVector()) {
Dan Gohman1f372ed2008-02-25 21:11:39 +00002214 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002215 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
Chris Lattnerd0496d02008-01-27 23:21:58 +00002216 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002217
Dan Gohman9a693412007-11-26 23:46:11 +00002218 // If X/C can be simplified by the division-by-constant logic, lower
2219 // X%C to the equivalent of X-X/C*C.
Chris Lattnerd0620d22006-10-12 20:58:32 +00002220 if (N1C && !N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002221 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002222 AddToWorklist(Div.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002223 SDValue OptimizedDiv = combine(Div.getNode());
2224 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002225 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendlingd033af02009-01-30 02:57:00 +00002226 OptimizedDiv, N1);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002227 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002228 AddToWorklist(Mul.getNode());
Dan Gohman9a693412007-11-26 23:46:11 +00002229 return Sub;
2230 }
Chris Lattnerd0620d22006-10-12 20:58:32 +00002231 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002232
Dan Gohman06563a82007-07-03 14:03:57 +00002233 // undef % X -> 0
2234 if (N0.getOpcode() == ISD::UNDEF)
2235 return DAG.getConstant(0, VT);
2236 // X % undef -> undef
2237 if (N1.getOpcode() == ISD::UNDEF)
2238 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002239
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002240 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002241}
2242
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002243SDValue DAGCombiner::visitUREM(SDNode *N) {
2244 SDValue N0 = N->getOperand(0);
2245 SDValue N1 = N->getOperand(1);
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002246 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2247 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002248 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002249
Nate Begeman21158fc2005-09-01 00:19:25 +00002250 // fold (urem c1, c2) -> c1%c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002251 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002252 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
Nate Begeman6828ed92005-10-10 21:26:48 +00002253 // fold (urem x, pow2) -> (and x, pow2-1)
Dan Gohmanb72127a2008-03-13 22:13:53 +00002254 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
Andrew Trickef9de2a2013-05-25 02:42:55 +00002255 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
Dan Gohmanb72127a2008-03-13 22:13:53 +00002256 DAG.getConstant(N1C->getAPIntValue()-1,VT));
Nate Begemanc89fdf12006-02-05 07:36:48 +00002257 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2258 if (N1.getOpcode() == ISD::SHL) {
2259 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
Dan Gohmanb72127a2008-03-13 22:13:53 +00002260 if (SHC->getAPIntValue().isPowerOf2()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002261 SDValue Add =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002262 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
Duncan Sands13237ac2008-06-06 12:08:01 +00002263 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
Dan Gohmanb72127a2008-03-13 22:13:53 +00002264 VT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002265 AddToWorklist(Add.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002266 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
Nate Begemanc89fdf12006-02-05 07:36:48 +00002267 }
2268 }
2269 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002270
Dan Gohman9a693412007-11-26 23:46:11 +00002271 // If X/C can be simplified by the division-by-constant logic, lower
2272 // X%C to the equivalent of X-X/C*C.
Chris Lattnerd0620d22006-10-12 20:58:32 +00002273 if (N1C && !N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002274 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002275 AddToWorklist(Div.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002276 SDValue OptimizedDiv = combine(Div.getNode());
2277 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002278 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendlingd033af02009-01-30 02:57:00 +00002279 OptimizedDiv, N1);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002280 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002281 AddToWorklist(Mul.getNode());
Dan Gohman9a693412007-11-26 23:46:11 +00002282 return Sub;
2283 }
Chris Lattnerd0620d22006-10-12 20:58:32 +00002284 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002285
Dan Gohman06563a82007-07-03 14:03:57 +00002286 // undef % X -> 0
2287 if (N0.getOpcode() == ISD::UNDEF)
2288 return DAG.getConstant(0, VT);
2289 // X % undef -> undef
2290 if (N1.getOpcode() == ISD::UNDEF)
2291 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002292
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002293 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002294}
2295
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002296SDValue DAGCombiner::visitMULHS(SDNode *N) {
2297 SDValue N0 = N->getOperand(0);
2298 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002299 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002300 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002301 SDLoc DL(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002302
Nate Begeman21158fc2005-09-01 00:19:25 +00002303 // fold (mulhs x, 0) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002304 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002305 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00002306 // fold (mulhs x, 1) -> (sra x, size(x)-1)
Dan Gohmanb72127a2008-03-13 22:13:53 +00002307 if (N1C && N1C->getAPIntValue() == 1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002308 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
Bill Wendlingfaed0652009-01-30 03:00:18 +00002309 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002310 getShiftAmountTy(N0.getValueType())));
Dan Gohman06563a82007-07-03 14:03:57 +00002311 // fold (mulhs x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002312 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00002313 return DAG.getConstant(0, VT);
Dan Gohmana8665142007-06-25 16:23:39 +00002314
Chris Lattner10bd29f2010-12-13 08:39:01 +00002315 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2316 // plus a shift.
2317 if (VT.isSimple() && !VT.isVector()) {
2318 MVT Simple = VT.getSimpleVT();
2319 unsigned SimpleSize = Simple.getSizeInBits();
2320 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2321 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2322 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2323 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2324 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
Chris Lattnerb86dcee2010-12-15 05:51:39 +00002325 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002326 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
Chris Lattner10bd29f2010-12-13 08:39:01 +00002327 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2328 }
2329 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002330
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002331 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002332}
2333
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002334SDValue DAGCombiner::visitMULHU(SDNode *N) {
2335 SDValue N0 = N->getOperand(0);
2336 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002337 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002338 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002339 SDLoc DL(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002340
Nate Begeman21158fc2005-09-01 00:19:25 +00002341 // fold (mulhu x, 0) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002342 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002343 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00002344 // fold (mulhu x, 1) -> 0
Dan Gohmanb72127a2008-03-13 22:13:53 +00002345 if (N1C && N1C->getAPIntValue() == 1)
Nate Begemand23739d2005-09-06 04:43:02 +00002346 return DAG.getConstant(0, N0.getValueType());
Dan Gohman06563a82007-07-03 14:03:57 +00002347 // fold (mulhu x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002348 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00002349 return DAG.getConstant(0, VT);
Dan Gohmana8665142007-06-25 16:23:39 +00002350
Chris Lattner10bd29f2010-12-13 08:39:01 +00002351 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2352 // plus a shift.
2353 if (VT.isSimple() && !VT.isVector()) {
2354 MVT Simple = VT.getSimpleVT();
2355 unsigned SimpleSize = Simple.getSizeInBits();
2356 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2357 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2358 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2359 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2360 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2361 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002362 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
Chris Lattner10bd29f2010-12-13 08:39:01 +00002363 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2364 }
2365 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002366
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002367 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002368}
2369
Sanjay Patel50cbfc52014-08-28 16:29:51 +00002370/// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2371/// give the opcodes for the two computations that are being performed. Return
2372/// true if a simplification was made.
Scott Michelcf0da6c2009-02-17 22:15:04 +00002373SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002374 unsigned HiOp) {
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002375 // If the high half is not needed, just compute the low half.
Evan Chengece4c682007-11-08 09:25:29 +00002376 bool HiExists = N->hasAnyUseOfValue(1);
2377 if (!HiExists &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002378 (!LegalOperations ||
Owen Andersonfb00d5b2014-01-20 18:41:34 +00002379 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
Craig Toppere1d12942014-08-27 05:25:25 +00002380 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
Chris Lattner31e9edc2008-01-26 01:09:19 +00002381 return CombineTo(N, Res, Res);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002382 }
2383
2384 // If the low half is not needed, just compute the high half.
Evan Chengece4c682007-11-08 09:25:29 +00002385 bool LoExists = N->hasAnyUseOfValue(0);
2386 if (!LoExists &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002387 (!LegalOperations ||
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002388 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
Craig Toppere1d12942014-08-27 05:25:25 +00002389 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
Chris Lattner31e9edc2008-01-26 01:09:19 +00002390 return CombineTo(N, Res, Res);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002391 }
2392
Evan Chengece4c682007-11-08 09:25:29 +00002393 // If both halves are used, return as it is.
2394 if (LoExists && HiExists)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002395 return SDValue();
Evan Chengece4c682007-11-08 09:25:29 +00002396
2397 // If the two computed results can be simplified separately, separate them.
Evan Chengece4c682007-11-08 09:25:29 +00002398 if (LoExists) {
Craig Toppere1d12942014-08-27 05:25:25 +00002399 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002400 AddToWorklist(Lo.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002401 SDValue LoOpt = combine(Lo.getNode());
2402 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002403 (!LegalOperations ||
Duncan Sands8651e9c2008-06-13 19:07:40 +00002404 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
Chris Lattner31e9edc2008-01-26 01:09:19 +00002405 return CombineTo(N, LoOpt, LoOpt);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002406 }
2407
Evan Chengece4c682007-11-08 09:25:29 +00002408 if (HiExists) {
Craig Toppere1d12942014-08-27 05:25:25 +00002409 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002410 AddToWorklist(Hi.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002411 SDValue HiOpt = combine(Hi.getNode());
2412 if (HiOpt.getNode() && HiOpt != Hi &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002413 (!LegalOperations ||
Duncan Sands8651e9c2008-06-13 19:07:40 +00002414 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
Chris Lattner31e9edc2008-01-26 01:09:19 +00002415 return CombineTo(N, HiOpt, HiOpt);
Evan Chengece4c682007-11-08 09:25:29 +00002416 }
Bill Wendling9b3407e2009-01-30 03:08:40 +00002417
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002418 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002419}
2420
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002421SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2422 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002423 if (Res.getNode()) return Res;
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002424
Chris Lattner15090e12010-12-15 06:04:19 +00002425 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002426 SDLoc DL(N);
Chris Lattner15090e12010-12-15 06:04:19 +00002427
2428 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2429 // plus a shift.
2430 if (VT.isSimple() && !VT.isVector()) {
2431 MVT Simple = VT.getSimpleVT();
2432 unsigned SimpleSize = Simple.getSizeInBits();
2433 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2434 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2435 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2436 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2437 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2438 // Compute the high part as N1.
2439 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002440 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
Chris Lattner15090e12010-12-15 06:04:19 +00002441 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2442 // Compute the low part as N0.
2443 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2444 return CombineTo(N, Lo, Hi);
2445 }
2446 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002447
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002448 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002449}
2450
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002451SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2452 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002453 if (Res.getNode()) return Res;
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002454
Chris Lattner15090e12010-12-15 06:04:19 +00002455 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002456 SDLoc DL(N);
Owen Andersonb2c80da2011-02-25 21:41:48 +00002457
Chris Lattner15090e12010-12-15 06:04:19 +00002458 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2459 // plus a shift.
2460 if (VT.isSimple() && !VT.isVector()) {
2461 MVT Simple = VT.getSimpleVT();
2462 unsigned SimpleSize = Simple.getSizeInBits();
2463 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2464 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2465 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2466 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2467 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2468 // Compute the high part as N1.
2469 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002470 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
Chris Lattner15090e12010-12-15 06:04:19 +00002471 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2472 // Compute the low part as N0.
2473 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2474 return CombineTo(N, Lo, Hi);
2475 }
2476 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002477
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002478 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002479}
2480
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002481SDValue DAGCombiner::visitSMULO(SDNode *N) {
2482 // (smulo x, 2) -> (saddo x, x)
2483 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2484 if (C2->getAPIntValue() == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002485 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002486 N->getOperand(0), N->getOperand(0));
2487
2488 return SDValue();
2489}
2490
2491SDValue DAGCombiner::visitUMULO(SDNode *N) {
2492 // (umulo x, 2) -> (uaddo x, x)
2493 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2494 if (C2->getAPIntValue() == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002495 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002496 N->getOperand(0), N->getOperand(0));
2497
2498 return SDValue();
2499}
2500
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002501SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2502 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002503 if (Res.getNode()) return Res;
Scott Michelcf0da6c2009-02-17 22:15:04 +00002504
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002505 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002506}
2507
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002508SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2509 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002510 if (Res.getNode()) return Res;
Scott Michelcf0da6c2009-02-17 22:15:04 +00002511
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002512 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002513}
2514
Sanjay Patel50cbfc52014-08-28 16:29:51 +00002515/// If this is a binary operator with two operands of the same opcode, try to
2516/// simplify it.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002517SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2518 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002519 EVT VT = N0.getValueType();
Chris Lattner8d6fc202006-05-05 05:51:50 +00002520 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
Scott Michelcf0da6c2009-02-17 22:15:04 +00002521
Dan Gohmandd5286d2010-01-14 03:08:49 +00002522 // Bail early if none of these transforms apply.
2523 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2524
Chris Lattner002ee912006-05-05 06:31:05 +00002525 // For each of OP in AND/OR/XOR:
2526 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2527 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2528 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
Dan Gohman600f62b2010-06-24 14:30:44 +00002529 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
Nate Begeman9655f842009-12-03 07:11:29 +00002530 //
2531 // do not sink logical op inside of a vector extend, since it may combine
2532 // into a vsetcc.
Evan Cheng166a4e62010-01-06 19:38:29 +00002533 EVT Op0VT = N0.getOperand(0).getValueType();
2534 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
Dan Gohmanad3e5492009-04-08 00:15:30 +00002535 N0.getOpcode() == ISD::SIGN_EXTEND ||
Evan Chengf1bd5fc2010-04-17 06:13:15 +00002536 // Avoid infinite looping with PromoteIntBinOp.
2537 (N0.getOpcode() == ISD::ANY_EXTEND &&
2538 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
Dan Gohman600f62b2010-06-24 14:30:44 +00002539 (N0.getOpcode() == ISD::TRUNCATE &&
2540 (!TLI.isZExtFree(VT, Op0VT) ||
2541 !TLI.isTruncateFree(Op0VT, VT)) &&
2542 TLI.isTypeLegal(Op0VT))) &&
Nate Begeman9655f842009-12-03 07:11:29 +00002543 !VT.isVector() &&
Evan Cheng166a4e62010-01-06 19:38:29 +00002544 Op0VT == N1.getOperand(0).getValueType() &&
2545 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002546 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
Bill Wendling781db7a2009-01-30 19:25:47 +00002547 N0.getOperand(0).getValueType(),
2548 N0.getOperand(0), N1.getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002549 AddToWorklist(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002550 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
Chris Lattner8d6fc202006-05-05 05:51:50 +00002551 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002552
Chris Lattner5ac42932006-05-05 06:10:43 +00002553 // For each of OP in SHL/SRL/SRA/AND...
2554 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2555 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2556 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
Chris Lattner8d6fc202006-05-05 05:51:50 +00002557 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
Chris Lattner5ac42932006-05-05 06:10:43 +00002558 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
Chris Lattner8d6fc202006-05-05 05:51:50 +00002559 N0.getOperand(1) == N1.getOperand(1)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002560 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
Bill Wendling781db7a2009-01-30 19:25:47 +00002561 N0.getOperand(0).getValueType(),
2562 N0.getOperand(0), N1.getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002563 AddToWorklist(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002564 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Bill Wendling781db7a2009-01-30 19:25:47 +00002565 ORNode, N0.getOperand(1));
Chris Lattner8d6fc202006-05-05 05:51:50 +00002566 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002567
Nadav Rotemb0783502012-04-01 19:31:22 +00002568 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2569 // Only perform this optimization after type legalization and before
2570 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2571 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2572 // we don't want to undo this promotion.
2573 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2574 // on scalars.
Nadav Rotem841c9a82012-09-20 08:53:31 +00002575 if ((N0.getOpcode() == ISD::BITCAST ||
2576 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2577 Level == AfterLegalizeTypes) {
Nadav Rotemb0783502012-04-01 19:31:22 +00002578 SDValue In0 = N0.getOperand(0);
2579 SDValue In1 = N1.getOperand(0);
2580 EVT In0Ty = In0.getValueType();
2581 EVT In1Ty = In1.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00002582 SDLoc DL(N);
Nadav Rotem841c9a82012-09-20 08:53:31 +00002583 // If both incoming values are integers, and the original types are the
2584 // same.
Nadav Rotemb0783502012-04-01 19:31:22 +00002585 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
Nadav Rotem841c9a82012-09-20 08:53:31 +00002586 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2587 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002588 AddToWorklist(Op.getNode());
Nadav Rotemb0783502012-04-01 19:31:22 +00002589 return BC;
2590 }
2591 }
2592
2593 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2594 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2595 // If both shuffles use the same mask, and both shuffle within a single
2596 // vector, then it is worthwhile to move the swizzle after the operation.
2597 // The type-legalizer generates this pattern when loading illegal
2598 // vector types from memory. In many cases this allows additional shuffle
2599 // optimizations.
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002600 // There are other cases where moving the shuffle after the xor/and/or
2601 // is profitable even if shuffles don't perform a swizzle.
2602 // If both shuffles use the same mask, and both shuffles have the same first
2603 // or second operand, then it might still be profitable to move the shuffle
2604 // after the xor/and/or operation.
2605 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
Nadav Rotemb0783502012-04-01 19:31:22 +00002606 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2607 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
Craig Topper9c3da312012-04-09 07:19:09 +00002608
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002609 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
Craig Topper9c3da312012-04-09 07:19:09 +00002610 "Inputs to shuffles are not the same type");
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00002611
Nadav Rotemb0783502012-04-01 19:31:22 +00002612 // Check that both shuffles use the same mask. The masks are known to be of
2613 // the same length because the result vector type is the same.
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002614 // Check also that shuffles have only one use to avoid introducing extra
2615 // instructions.
2616 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2617 SVN0->getMask().equals(SVN1->getMask())) {
2618 SDValue ShOp = N0->getOperand(1);
Nadav Rotemb0783502012-04-01 19:31:22 +00002619
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002620 // Don't try to fold this node if it requires introducing a
2621 // build vector of all zeros that might be illegal at this stage.
2622 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2623 if (!LegalTypes)
2624 ShOp = DAG.getConstant(0, VT);
2625 else
2626 ShOp = SDValue();
2627 }
2628
2629 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2630 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2631 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2632 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2633 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2634 N0->getOperand(0), N1->getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002635 AddToWorklist(NewNode.getNode());
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002636 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2637 &SVN0->getMask()[0]);
2638 }
2639
2640 // Don't try to fold this node if it requires introducing a
2641 // build vector of all zeros that might be illegal at this stage.
2642 ShOp = N0->getOperand(0);
2643 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2644 if (!LegalTypes)
2645 ShOp = DAG.getConstant(0, VT);
2646 else
2647 ShOp = SDValue();
2648 }
2649
2650 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2651 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2652 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2653 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2654 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2655 N0->getOperand(1), N1->getOperand(1));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002656 AddToWorklist(NewNode.getNode());
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002657 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2658 &SVN0->getMask()[0]);
2659 }
Nadav Rotemb0783502012-04-01 19:31:22 +00002660 }
2661 }
Craig Topper9c3da312012-04-09 07:19:09 +00002662
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002663 return SDValue();
Chris Lattner8d6fc202006-05-05 05:51:50 +00002664}
2665
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002666SDValue DAGCombiner::visitAND(SDNode *N) {
2667 SDValue N0 = N->getOperand(0);
2668 SDValue N1 = N->getOperand(1);
2669 SDValue LL, LR, RL, RR, CC0, CC1;
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002670 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2671 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002672 EVT VT = N1.getValueType();
Dan Gohmane14c4082010-03-04 00:23:16 +00002673 unsigned BitWidth = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00002674
Dan Gohmana8665142007-06-25 16:23:39 +00002675 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00002676 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002677 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002678 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00002679
2680 // fold (and x, 0) -> 0, vector edition
2681 if (ISD::isBuildVectorAllZeros(N0.getNode()))
David Xuf7aff682014-09-11 05:10:28 +00002682 // do not return N0, because undef node may exist in N0
2683 return DAG.getConstant(
2684 APInt::getNullValue(
2685 N0.getValueType().getScalarType().getSizeInBits()),
2686 N0.getValueType());
Craig Toppera183ddb2012-12-08 22:49:19 +00002687 if (ISD::isBuildVectorAllZeros(N1.getNode()))
David Xuf7aff682014-09-11 05:10:28 +00002688 // do not return N1, because undef node may exist in N1
2689 return DAG.getConstant(
2690 APInt::getNullValue(
2691 N1.getValueType().getScalarType().getSizeInBits()),
2692 N1.getValueType());
Craig Toppera183ddb2012-12-08 22:49:19 +00002693
2694 // fold (and x, -1) -> x, vector edition
2695 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2696 return N1;
2697 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2698 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00002699 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002700
Dan Gohman06563a82007-07-03 14:03:57 +00002701 // fold (and x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002702 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00002703 return DAG.getConstant(0, VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00002704 // fold (and c1, c2) -> c1&c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002705 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00002706 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00002707 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00002708 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002709 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00002710 // fold (and x, -1) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002711 if (N1C && N1C->isAllOnesValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002712 return N0;
2713 // if (and x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002714 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1f372ed2008-02-25 21:11:39 +00002715 APInt::getAllOnesValue(BitWidth)))
Nate Begemand23739d2005-09-06 04:43:02 +00002716 return DAG.getConstant(0, VT);
Nate Begeman22e251a2006-02-03 06:46:56 +00002717 // reassociate and
Andrew Trickef9de2a2013-05-25 02:42:55 +00002718 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00002719 if (RAND.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00002720 return RAND;
Bill Wendlingaf13d822010-03-03 00:35:56 +00002721 // fold (and (or x, C), D) -> D if (C & D) == D
Nate Begemanee065282005-11-02 18:42:59 +00002722 if (N1C && N0.getOpcode() == ISD::OR)
Nate Begeman21158fc2005-09-01 00:19:25 +00002723 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
Dan Gohmanb72127a2008-03-13 22:13:53 +00002724 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002725 return N1;
Chris Lattner49beaf42006-02-02 07:17:31 +00002726 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2727 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002728 SDValue N0Op0 = N0.getOperand(0);
Dan Gohman1f372ed2008-02-25 21:11:39 +00002729 APInt Mask = ~N1C->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00002730 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
Dan Gohman1f372ed2008-02-25 21:11:39 +00002731 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002732 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
Bill Wendling86171912009-01-30 20:43:18 +00002733 N0.getValueType(), N0Op0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002734
Chris Lattner0db2f2c2006-03-01 21:47:21 +00002735 // Replace uses of the AND with uses of the Zero extend node.
2736 CombineTo(N, Zext);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002737
Chris Lattner49beaf42006-02-02 07:17:31 +00002738 // We actually want to replace all uses of the any_extend with the
2739 // zero_extend, to avoid duplicating things. This will later cause this
2740 // AND to be folded.
Gabor Greiff304a7a2008-08-28 21:40:38 +00002741 CombineTo(N0.getNode(), Zext);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002742 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattner49beaf42006-02-02 07:17:31 +00002743 }
2744 }
Stephen Lincfe7f352013-07-08 00:37:03 +00002745 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
James Molloy862fe492012-02-20 12:02:38 +00002746 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2747 // already be zero by virtue of the width of the base type of the load.
2748 //
2749 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2750 // more cases.
2751 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2752 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2753 N0.getOpcode() == ISD::LOAD) {
2754 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2755 N0 : N0.getOperand(0) );
2756
2757 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2758 // This can be a pure constant or a vector splat, in which case we treat the
2759 // vector as a scalar and use the splat value.
2760 APInt Constant = APInt::getNullValue(1);
2761 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2762 Constant = C->getAPIntValue();
2763 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2764 APInt SplatValue, SplatUndef;
2765 unsigned SplatBitSize;
2766 bool HasAnyUndefs;
2767 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2768 SplatBitSize, HasAnyUndefs);
2769 if (IsSplat) {
2770 // Undef bits can contribute to a possible optimisation if set, so
2771 // set them.
2772 SplatValue |= SplatUndef;
2773
2774 // The splat value may be something like "0x00FFFFFF", which means 0 for
2775 // the first vector value and FF for the rest, repeating. We need a mask
2776 // that will apply equally to all members of the vector, so AND all the
2777 // lanes of the constant together.
2778 EVT VT = Vector->getValueType(0);
2779 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
Silviu Baranga3f40d872012-09-05 08:57:21 +00002780
2781 // If the splat value has been compressed to a bitlength lower
2782 // than the size of the vector lane, we need to re-expand it to
2783 // the lane size.
2784 if (BitWidth > SplatBitSize)
2785 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2786 SplatBitSize < BitWidth;
2787 SplatBitSize = SplatBitSize * 2)
2788 SplatValue |= SplatValue.shl(SplatBitSize);
2789
James Molloy862fe492012-02-20 12:02:38 +00002790 Constant = APInt::getAllOnesValue(BitWidth);
Silviu Baranga3f40d872012-09-05 08:57:21 +00002791 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
James Molloy862fe492012-02-20 12:02:38 +00002792 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2793 }
2794 }
2795
2796 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2797 // actually legal and isn't going to get expanded, else this is a false
2798 // optimisation.
2799 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2800 Load->getMemoryVT());
2801
2802 // Resize the constant to the same size as the original memory access before
2803 // extension. If it is still the AllOnesValue then this AND is completely
2804 // unneeded.
2805 Constant =
2806 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2807
2808 bool B;
2809 switch (Load->getExtensionType()) {
2810 default: B = false; break;
2811 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2812 case ISD::ZEXTLOAD:
2813 case ISD::NON_EXTLOAD: B = true; break;
2814 }
2815
2816 if (B && Constant.isAllOnesValue()) {
2817 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2818 // preserve semantics once we get rid of the AND.
2819 SDValue NewLoad(Load, 0);
2820 if (Load->getExtensionType() == ISD::EXTLOAD) {
2821 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
Andrew Trickef9de2a2013-05-25 02:42:55 +00002822 Load->getValueType(0), SDLoc(Load),
James Molloy862fe492012-02-20 12:02:38 +00002823 Load->getChain(), Load->getBasePtr(),
2824 Load->getOffset(), Load->getMemoryVT(),
2825 Load->getMemOperand());
2826 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
Hal Finkel8a311382012-06-20 15:42:48 +00002827 if (Load->getNumValues() == 3) {
2828 // PRE/POST_INC loads have 3 values.
2829 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2830 NewLoad.getValue(2) };
2831 CombineTo(Load, To, 3, true);
2832 } else {
2833 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2834 }
James Molloy862fe492012-02-20 12:02:38 +00002835 }
2836
2837 // Fold the AND away, taking care not to fold to the old load node if we
2838 // replaced it.
2839 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2840
2841 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2842 }
2843 }
Nate Begeman049b7482005-09-09 19:49:52 +00002844 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2845 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2846 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2847 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
Scott Michelcf0da6c2009-02-17 22:15:04 +00002848
Tom Stellard7783b0a2014-06-12 16:04:47 +00002849 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
Duncan Sands13237ac2008-06-06 12:08:01 +00002850 LL.getValueType().isInteger()) {
Bill Wendling86171912009-01-30 20:43:18 +00002851 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
Tom Stellard7783b0a2014-06-12 16:04:47 +00002852 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002853 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
Bill Wendling86171912009-01-30 20:43:18 +00002854 LR.getValueType(), LL, RL);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002855 AddToWorklist(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002856 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00002857 }
Bill Wendling86171912009-01-30 20:43:18 +00002858 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
Tom Stellard7783b0a2014-06-12 16:04:47 +00002859 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002860 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
Bill Wendling86171912009-01-30 20:43:18 +00002861 LR.getValueType(), LL, RL);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002862 AddToWorklist(ANDNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002863 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00002864 }
Bill Wendling86171912009-01-30 20:43:18 +00002865 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
Tom Stellard7783b0a2014-06-12 16:04:47 +00002866 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002867 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
Bill Wendling86171912009-01-30 20:43:18 +00002868 LR.getValueType(), LL, RL);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002869 AddToWorklist(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002870 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00002871 }
2872 }
Jim Grosbach327ccc72013-08-13 21:30:58 +00002873 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2874 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2875 Op0 == Op1 && LL.getValueType().isInteger() &&
2876 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2877 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2878 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2879 cast<ConstantSDNode>(RR)->isNullValue()))) {
2880 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2881 LL, DAG.getConstant(1, LL.getValueType()));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002882 AddToWorklist(ADDNode.getNode());
Jim Grosbach327ccc72013-08-13 21:30:58 +00002883 return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2884 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2885 }
Nate Begeman049b7482005-09-09 19:49:52 +00002886 // canonicalize equivalent to ll == rl
2887 if (LL == RR && LR == RL) {
2888 Op1 = ISD::getSetCCSwappedOperands(Op1);
2889 std::swap(RL, RR);
2890 }
2891 if (LL == RL && LR == RR) {
Duncan Sands13237ac2008-06-06 12:08:01 +00002892 bool isInteger = LL.getValueType().isInteger();
Nate Begeman049b7482005-09-09 19:49:52 +00002893 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
Chris Lattner5fa10402008-10-28 07:11:07 +00002894 if (Result != ISD::SETCC_INVALID &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00002895 (!LegalOperations ||
Owen Andersoncc068992013-02-14 09:07:33 +00002896 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2897 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault758659232013-05-18 00:21:46 +00002898 getSetCCResultType(N0.getSimpleValueType())))))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002899 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
Bill Wendling86171912009-01-30 20:43:18 +00002900 LL, LR, Result);
Nate Begeman049b7482005-09-09 19:49:52 +00002901 }
2902 }
Chris Lattner8d6fc202006-05-05 05:51:50 +00002903
Bill Wendling86171912009-01-30 20:43:18 +00002904 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
Chris Lattner8d6fc202006-05-05 05:51:50 +00002905 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002906 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002907 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00002908 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002909
Nate Begemandc7bba92006-02-03 22:24:05 +00002910 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2911 // fold (and (sra)) -> (and (srl)) when possible.
Duncan Sands13237ac2008-06-06 12:08:01 +00002912 if (!VT.isVector() &&
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002913 SimplifyDemandedBits(SDValue(N, 0)))
2914 return SDValue(N, 0);
Evan Cheng166a4e62010-01-06 19:38:29 +00002915
Nate Begeman02b23c62005-10-13 03:11:28 +00002916 // fold (zext_inreg (extload x)) -> (zextload x)
Gabor Greiff304a7a2008-08-28 21:40:38 +00002917 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00002918 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00002919 EVT MemVT = LN0->getMemoryVT();
Nate Begeman8e022b32005-10-13 18:34:58 +00002920 // If we zero all the possible extended bits, then we can turn this into
2921 // a zextload if we are running before legalize or the operation is legal.
Dan Gohmane14c4082010-03-04 00:23:16 +00002922 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
Dan Gohman1f372ed2008-02-25 21:11:39 +00002923 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
Dan Gohmane14c4082010-03-04 00:23:16 +00002924 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002925 ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00002926 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002927 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
Bill Wendling86171912009-01-30 20:43:18 +00002928 LN0->getChain(), LN0->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002929 MemVT, LN0->getMemOperand());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002930 AddToWorklist(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002931 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002932 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00002933 }
2934 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002935 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
Gabor Greiff304a7a2008-08-28 21:40:38 +00002936 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Cheng8a1d09d2007-03-07 08:07:03 +00002937 N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00002938 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00002939 EVT MemVT = LN0->getMemoryVT();
Nate Begeman8e022b32005-10-13 18:34:58 +00002940 // If we zero all the possible extended bits, then we can turn this into
2941 // a zextload if we are running before legalize or the operation is legal.
Dan Gohmane14c4082010-03-04 00:23:16 +00002942 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
Dan Gohman1f372ed2008-02-25 21:11:39 +00002943 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
Dan Gohmane14c4082010-03-04 00:23:16 +00002944 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002945 ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00002946 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002947 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002948 LN0->getChain(), LN0->getBasePtr(),
2949 MemVT, LN0->getMemOperand());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002950 AddToWorklist(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002951 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002952 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00002953 }
2954 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002955
Chris Lattnerf0032b32006-02-28 06:49:37 +00002956 // fold (and (load x), 255) -> (zextload x, i8)
2957 // fold (and (extload x, i16), 255) -> (zextload x, i8)
Evan Cheng166a4e62010-01-06 19:38:29 +00002958 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2959 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2960 (N0.getOpcode() == ISD::ANY_EXTEND &&
2961 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2962 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2963 LoadSDNode *LN0 = HasAnyExt
2964 ? cast<LoadSDNode>(N0.getOperand(0))
2965 : cast<LoadSDNode>(N0);
Evan Chenge71fe34d2006-10-09 20:57:25 +00002966 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
Tim Northover68239002013-07-02 09:58:53 +00002967 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
Duncan Sands93b66092008-06-09 11:32:28 +00002968 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
Evan Cheng166a4e62010-01-06 19:38:29 +00002969 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2970 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2971 EVT LoadedVT = LN0->getMemoryVT();
Duncan Sands93b66092008-06-09 11:32:28 +00002972
Evan Cheng166a4e62010-01-06 19:38:29 +00002973 if (ExtVT == LoadedVT &&
2974 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
Chris Lattner88de3842010-01-07 21:53:27 +00002975 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
Wesley Peck527da1b2010-11-23 03:31:01 +00002976
2977 SDValue NewLoad =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002978 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002979 LN0->getChain(), LN0->getBasePtr(), ExtVT,
2980 LN0->getMemOperand());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002981 AddToWorklist(N);
Chris Lattner88de3842010-01-07 21:53:27 +00002982 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2983 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2984 }
Wesley Peck527da1b2010-11-23 03:31:01 +00002985
Chris Lattner88de3842010-01-07 21:53:27 +00002986 // Do not change the width of a volatile load.
2987 // Do not generate loads of non-round integer types since these can
2988 // be expensive (and would be wrong if the type is not byte sized).
2989 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2990 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2991 EVT PtrType = LN0->getOperand(1).getValueType();
Bill Wendling86171912009-01-30 20:43:18 +00002992
Chris Lattner88de3842010-01-07 21:53:27 +00002993 unsigned Alignment = LN0->getAlignment();
2994 SDValue NewPtr = LN0->getBasePtr();
2995
2996 // For big endian targets, we need to add an offset to the pointer
2997 // to load the correct bytes. For little endian systems, we merely
2998 // need to read fewer bytes from the same pointer.
2999 if (TLI.isBigEndian()) {
Evan Cheng166a4e62010-01-06 19:38:29 +00003000 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3001 unsigned EVTStoreBytes = ExtVT.getStoreSize();
3002 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
Andrew Trickef9de2a2013-05-25 02:42:55 +00003003 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
Chris Lattner88de3842010-01-07 21:53:27 +00003004 NewPtr, DAG.getConstant(PtrOff, PtrType));
3005 Alignment = MinAlign(Alignment, PtrOff);
Evan Cheng166a4e62010-01-06 19:38:29 +00003006 }
Chris Lattner88de3842010-01-07 21:53:27 +00003007
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003008 AddToWorklist(NewPtr.getNode());
Wesley Peck527da1b2010-11-23 03:31:01 +00003009
Chris Lattner88de3842010-01-07 21:53:27 +00003010 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3011 SDValue Load =
Andrew Trickef9de2a2013-05-25 02:42:55 +00003012 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
Chris Lattner88de3842010-01-07 21:53:27 +00003013 LN0->getChain(), NewPtr,
Chris Lattner3d178ed2010-09-21 17:04:51 +00003014 LN0->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +00003015 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
Louis Gerbarg67474e32014-07-31 21:45:05 +00003016 LN0->isInvariant(), Alignment, LN0->getAAInfo());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003017 AddToWorklist(N);
Chris Lattner88de3842010-01-07 21:53:27 +00003018 CombineTo(LN0, Load, Load.getValue(1));
3019 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Duncan Sands1826ded2007-10-28 12:59:45 +00003020 }
Evan Chenge71fe34d2006-10-09 20:57:25 +00003021 }
Chris Lattnerbdbc4472006-02-28 06:35:35 +00003022 }
3023 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003024
Evan Chenge6a3b032012-07-17 18:54:11 +00003025 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
3026 VT.getSizeInBits() <= 64) {
3027 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3028 APInt ADDC = ADDI->getAPIntValue();
3029 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3030 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
3031 // immediate for an add, but it is legal if its top c2 bits are set,
3032 // transform the ADD so the immediate doesn't need to be materialized
3033 // in a register.
3034 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
3035 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3036 SRLI->getZExtValue());
3037 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
3038 ADDC |= Mask;
3039 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3040 SDValue NewAdd =
Andrew Trickef9de2a2013-05-25 02:42:55 +00003041 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
Evan Chenge6a3b032012-07-17 18:54:11 +00003042 N0.getOperand(0), DAG.getConstant(ADDC, VT));
3043 CombineTo(N0.getNode(), NewAdd);
3044 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3045 }
3046 }
3047 }
3048 }
3049 }
3050 }
Evan Chenge6a3b032012-07-17 18:54:11 +00003051
Tim Northover819bfb52013-08-27 13:46:45 +00003052 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3053 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3054 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3055 N0.getOperand(1), false);
3056 if (BSwap.getNode())
3057 return BSwap;
3058 }
3059
Evan Chengf1005572010-04-28 07:10:39 +00003060 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00003061}
3062
Sanjay Patel50cbfc52014-08-28 16:29:51 +00003063/// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
Evan Cheng4c0bd962011-06-21 06:01:08 +00003064SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3065 bool DemandHighBits) {
3066 if (!LegalOperations)
3067 return SDValue();
3068
3069 EVT VT = N->getValueType(0);
3070 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3071 return SDValue();
3072 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3073 return SDValue();
3074
3075 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3076 bool LookPassAnd0 = false;
3077 bool LookPassAnd1 = false;
3078 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3079 std::swap(N0, N1);
3080 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3081 std::swap(N0, N1);
3082 if (N0.getOpcode() == ISD::AND) {
3083 if (!N0.getNode()->hasOneUse())
3084 return SDValue();
3085 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3086 if (!N01C || N01C->getZExtValue() != 0xFF00)
3087 return SDValue();
3088 N0 = N0.getOperand(0);
3089 LookPassAnd0 = true;
3090 }
3091
3092 if (N1.getOpcode() == ISD::AND) {
3093 if (!N1.getNode()->hasOneUse())
3094 return SDValue();
3095 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3096 if (!N11C || N11C->getZExtValue() != 0xFF)
3097 return SDValue();
3098 N1 = N1.getOperand(0);
3099 LookPassAnd1 = true;
3100 }
3101
3102 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3103 std::swap(N0, N1);
3104 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3105 return SDValue();
3106 if (!N0.getNode()->hasOneUse() ||
3107 !N1.getNode()->hasOneUse())
3108 return SDValue();
3109
3110 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3111 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3112 if (!N01C || !N11C)
3113 return SDValue();
3114 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3115 return SDValue();
3116
3117 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3118 SDValue N00 = N0->getOperand(0);
3119 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3120 if (!N00.getNode()->hasOneUse())
3121 return SDValue();
3122 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3123 if (!N001C || N001C->getZExtValue() != 0xFF)
3124 return SDValue();
3125 N00 = N00.getOperand(0);
3126 LookPassAnd0 = true;
3127 }
3128
3129 SDValue N10 = N1->getOperand(0);
3130 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3131 if (!N10.getNode()->hasOneUse())
3132 return SDValue();
3133 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3134 if (!N101C || N101C->getZExtValue() != 0xFF00)
3135 return SDValue();
3136 N10 = N10.getOperand(0);
3137 LookPassAnd1 = true;
3138 }
3139
3140 if (N00 != N10)
3141 return SDValue();
3142
Tim Northover819bfb52013-08-27 13:46:45 +00003143 // Make sure everything beyond the low halfword gets set to zero since the SRL
3144 // 16 will clear the top bits.
Evan Cheng4c0bd962011-06-21 06:01:08 +00003145 unsigned OpSizeInBits = VT.getSizeInBits();
Tim Northover819bfb52013-08-27 13:46:45 +00003146 if (DemandHighBits && OpSizeInBits > 16) {
3147 // If the left-shift isn't masked out then the only way this is a bswap is
3148 // if all bits beyond the low 8 are 0. In that case the entire pattern
3149 // reduces to a left shift anyway: leave it for other parts of the combiner.
3150 if (!LookPassAnd0)
3151 return SDValue();
3152
3153 // However, if the right shift isn't masked out then it might be because
3154 // it's not needed. See if we can spot that too.
3155 if (!LookPassAnd1 &&
3156 !DAG.MaskedValueIsZero(
3157 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3158 return SDValue();
3159 }
Eric Christopherd6300d22011-07-14 01:12:15 +00003160
Andrew Trickef9de2a2013-05-25 02:42:55 +00003161 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
Evan Cheng4c0bd962011-06-21 06:01:08 +00003162 if (OpSizeInBits > 16)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003163 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
Evan Cheng4c0bd962011-06-21 06:01:08 +00003164 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3165 return Res;
3166}
3167
Sanjay Patel50cbfc52014-08-28 16:29:51 +00003168/// Return true if the specified node is an element that makes up a 32-bit
3169/// packed halfword byteswap.
3170/// ((x & 0x000000ff) << 8) |
3171/// ((x & 0x0000ff00) >> 8) |
3172/// ((x & 0x00ff0000) << 8) |
3173/// ((x & 0xff000000) >> 8)
Benjamin Kramer7ad22402014-10-22 19:55:26 +00003174static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
Evan Cheng4c0bd962011-06-21 06:01:08 +00003175 if (!N.getNode()->hasOneUse())
3176 return false;
3177
3178 unsigned Opc = N.getOpcode();
3179 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3180 return false;
3181
3182 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3183 if (!N1C)
3184 return false;
3185
3186 unsigned Num;
3187 switch (N1C->getZExtValue()) {
3188 default:
3189 return false;
3190 case 0xFF: Num = 0; break;
3191 case 0xFF00: Num = 1; break;
3192 case 0xFF0000: Num = 2; break;
3193 case 0xFF000000: Num = 3; break;
3194 }
3195
3196 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3197 SDValue N0 = N.getOperand(0);
3198 if (Opc == ISD::AND) {
3199 if (Num == 0 || Num == 2) {
3200 // (x >> 8) & 0xff
3201 // (x >> 8) & 0xff0000
3202 if (N0.getOpcode() != ISD::SRL)
3203 return false;
3204 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3205 if (!C || C->getZExtValue() != 8)
3206 return false;
3207 } else {
3208 // (x << 8) & 0xff00
3209 // (x << 8) & 0xff000000
3210 if (N0.getOpcode() != ISD::SHL)
3211 return false;
3212 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3213 if (!C || C->getZExtValue() != 8)
3214 return false;
3215 }
3216 } else if (Opc == ISD::SHL) {
3217 // (x & 0xff) << 8
3218 // (x & 0xff0000) << 8
3219 if (Num != 0 && Num != 2)
3220 return false;
3221 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3222 if (!C || C->getZExtValue() != 8)
3223 return false;
3224 } else { // Opc == ISD::SRL
3225 // (x & 0xff00) >> 8
3226 // (x & 0xff000000) >> 8
3227 if (Num != 1 && Num != 3)
3228 return false;
3229 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3230 if (!C || C->getZExtValue() != 8)
3231 return false;
3232 }
3233
3234 if (Parts[Num])
3235 return false;
3236
3237 Parts[Num] = N0.getOperand(0).getNode();
3238 return true;
3239}
3240
Sanjay Patel50cbfc52014-08-28 16:29:51 +00003241/// Match a 32-bit packed halfword bswap. That is
3242/// ((x & 0x000000ff) << 8) |
3243/// ((x & 0x0000ff00) >> 8) |
3244/// ((x & 0x00ff0000) << 8) |
3245/// ((x & 0xff000000) >> 8)
Evan Cheng4c0bd962011-06-21 06:01:08 +00003246/// => (rotl (bswap x), 16)
3247SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3248 if (!LegalOperations)
3249 return SDValue();
3250
3251 EVT VT = N->getValueType(0);
3252 if (VT != MVT::i32)
3253 return SDValue();
3254 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3255 return SDValue();
3256
Evan Cheng4c0bd962011-06-21 06:01:08 +00003257 // Look for either
3258 // (or (or (and), (and)), (or (and), (and)))
3259 // (or (or (or (and), (and)), (and)), (and))
3260 if (N0.getOpcode() != ISD::OR)
3261 return SDValue();
3262 SDValue N00 = N0.getOperand(0);
3263 SDValue N01 = N0.getOperand(1);
Benjamin Kramer7ad22402014-10-22 19:55:26 +00003264 SDNode *Parts[4] = {};
Evan Cheng4c0bd962011-06-21 06:01:08 +00003265
Evan Chengbf0baa92012-12-13 01:34:32 +00003266 if (N1.getOpcode() == ISD::OR &&
3267 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
Evan Cheng4c0bd962011-06-21 06:01:08 +00003268 // (or (or (and), (and)), (or (and), (and)))
3269 SDValue N000 = N00.getOperand(0);
3270 if (!isBSwapHWordElement(N000, Parts))
3271 return SDValue();
3272
3273 SDValue N001 = N00.getOperand(1);
3274 if (!isBSwapHWordElement(N001, Parts))
3275 return SDValue();
3276 SDValue N010 = N01.getOperand(0);
3277 if (!isBSwapHWordElement(N010, Parts))
3278 return SDValue();
3279 SDValue N011 = N01.getOperand(1);
3280 if (!isBSwapHWordElement(N011, Parts))
3281 return SDValue();
3282 } else {
3283 // (or (or (or (and), (and)), (and)), (and))
3284 if (!isBSwapHWordElement(N1, Parts))
3285 return SDValue();
3286 if (!isBSwapHWordElement(N01, Parts))
3287 return SDValue();
3288 if (N00.getOpcode() != ISD::OR)
3289 return SDValue();
3290 SDValue N000 = N00.getOperand(0);
3291 if (!isBSwapHWordElement(N000, Parts))
3292 return SDValue();
3293 SDValue N001 = N00.getOperand(1);
3294 if (!isBSwapHWordElement(N001, Parts))
3295 return SDValue();
3296 }
3297
3298 // Make sure the parts are all coming from the same node.
3299 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3300 return SDValue();
3301
Andrew Trickef9de2a2013-05-25 02:42:55 +00003302 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
Evan Cheng4c0bd962011-06-21 06:01:08 +00003303 SDValue(Parts[0],0));
3304
Kay Tiong Khoo9195a5b2013-09-23 18:43:51 +00003305 // Result of the bswap should be rotated by 16. If it's not legal, then
Evan Cheng4c0bd962011-06-21 06:01:08 +00003306 // do (x << 16) | (x >> 16).
3307 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3308 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003309 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
Craig Topper5f9791f2012-09-29 07:18:53 +00003310 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003311 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3312 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3313 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3314 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
Evan Cheng4c0bd962011-06-21 06:01:08 +00003315}
3316
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003317SDValue DAGCombiner::visitOR(SDNode *N) {
3318 SDValue N0 = N->getOperand(0);
3319 SDValue N1 = N->getOperand(1);
3320 SDValue LL, LR, RL, RR, CC0, CC1;
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003321 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3322 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00003323 EVT VT = N1.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003324
Dan Gohmana8665142007-06-25 16:23:39 +00003325 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00003326 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003327 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003328 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00003329
3330 // fold (or x, 0) -> x, vector edition
3331 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3332 return N1;
3333 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3334 return N0;
3335
3336 // fold (or x, -1) -> -1, vector edition
3337 if (ISD::isBuildVectorAllOnes(N0.getNode()))
David Xuf7aff682014-09-11 05:10:28 +00003338 // do not return N0, because undef node may exist in N0
3339 return DAG.getConstant(
3340 APInt::getAllOnesValue(
3341 N0.getValueType().getScalarType().getSizeInBits()),
3342 N0.getValueType());
Craig Toppera183ddb2012-12-08 22:49:19 +00003343 if (ISD::isBuildVectorAllOnes(N1.getNode()))
David Xuf7aff682014-09-11 05:10:28 +00003344 // do not return N1, because undef node may exist in N1
3345 return DAG.getConstant(
3346 APInt::getAllOnesValue(
3347 N1.getValueType().getScalarType().getSizeInBits()),
3348 N1.getValueType());
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003349
3350 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3351 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3352 // Do this only if the resulting shuffle is legal.
3353 if (isa<ShuffleVectorSDNode>(N0) &&
3354 isa<ShuffleVectorSDNode>(N1) &&
Andrea Di Biagio2152a6c2014-07-15 00:02:32 +00003355 // Avoid folding a node with illegal type.
3356 TLI.isTypeLegal(VT) &&
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003357 N0->getOperand(1) == N1->getOperand(1) &&
3358 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3359 bool CanFold = true;
3360 unsigned NumElts = VT.getVectorNumElements();
3361 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3362 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3363 // We construct two shuffle masks:
3364 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3365 // and N1 as the second operand.
3366 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3367 // and N0 as the second operand.
3368 // We do this because OR is commutable and therefore there might be
3369 // two ways to fold this node into a shuffle.
3370 SmallVector<int,4> Mask1;
3371 SmallVector<int,4> Mask2;
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00003372
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003373 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3374 int M0 = SV0->getMaskElt(i);
3375 int M1 = SV1->getMaskElt(i);
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00003376
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003377 // Both shuffle indexes are undef. Propagate Undef.
3378 if (M0 < 0 && M1 < 0) {
3379 Mask1.push_back(M0);
3380 Mask2.push_back(M0);
3381 continue;
3382 }
3383
3384 if (M0 < 0 || M1 < 0 ||
3385 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3386 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3387 CanFold = false;
3388 break;
3389 }
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00003390
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003391 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3392 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3393 }
3394
3395 if (CanFold) {
3396 // Fold this sequence only if the resulting shuffle is 'legal'.
3397 if (TLI.isShuffleMaskLegal(Mask1, VT))
3398 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3399 N1->getOperand(0), &Mask1[0]);
3400 if (TLI.isShuffleMaskLegal(Mask2, VT))
3401 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3402 N0->getOperand(0), &Mask2[0]);
3403 }
3404 }
Dan Gohman80f9f072007-07-13 20:03:40 +00003405 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003406
Dan Gohman06563a82007-07-03 14:03:57 +00003407 // fold (or x, undef) -> -1
Bob Wilson269a89f2010-06-28 23:40:25 +00003408 if (!LegalOperations &&
3409 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
Nate Begeman9655f842009-12-03 07:11:29 +00003410 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3411 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3412 }
Nate Begeman21158fc2005-09-01 00:19:25 +00003413 // fold (or c1, c2) -> c1|c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003414 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00003415 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003416 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00003417 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003418 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00003419 // fold (or x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003420 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003421 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00003422 // fold (or x, -1) -> -1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003423 if (N1C && N1C->isAllOnesValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003424 return N1;
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003425 // fold (or x, c) -> c iff (x & ~c) == 0
Dan Gohman1f372ed2008-02-25 21:11:39 +00003426 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
Nate Begemand23739d2005-09-06 04:43:02 +00003427 return N1;
Evan Cheng4c0bd962011-06-21 06:01:08 +00003428
3429 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3430 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003431 if (BSwap.getNode())
Evan Cheng4c0bd962011-06-21 06:01:08 +00003432 return BSwap;
3433 BSwap = MatchBSwapHWordLow(N, N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003434 if (BSwap.getNode())
Evan Cheng4c0bd962011-06-21 06:01:08 +00003435 return BSwap;
3436
Nate Begeman22e251a2006-02-03 06:46:56 +00003437 // reassociate or
Andrew Trickef9de2a2013-05-25 02:42:55 +00003438 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003439 if (ROR.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00003440 return ROR;
3441 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003442 // iff (c1 & c2) == 0.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003443 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
Chris Lattnerd8c5c062005-10-27 05:06:38 +00003444 isa<ConstantSDNode>(N0.getOperand(1))) {
Chris Lattnerd8c5c062005-10-27 05:06:38 +00003445 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
Juergen Ributzkaf26beda2014-01-25 02:02:55 +00003446 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3447 SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3448 if (!COR.getNode())
3449 return SDValue();
Andrew Trickef9de2a2013-05-25 02:42:55 +00003450 return DAG.getNode(ISD::AND, SDLoc(N), VT,
3451 DAG.getNode(ISD::OR, SDLoc(N0), VT,
Juergen Ributzkaf26beda2014-01-25 02:02:55 +00003452 N0.getOperand(0), N1), COR);
3453 }
Nate Begeman85c1cc42005-09-08 20:18:10 +00003454 }
Nate Begeman049b7482005-09-09 19:49:52 +00003455 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3456 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3457 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3458 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003459
Nate Begeman049b7482005-09-09 19:49:52 +00003460 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
Duncan Sands13237ac2008-06-06 12:08:01 +00003461 LL.getValueType().isInteger()) {
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003462 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3463 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
Scott Michelcf0da6c2009-02-17 22:15:04 +00003464 if (cast<ConstantSDNode>(LR)->isNullValue() &&
Nate Begeman049b7482005-09-09 19:49:52 +00003465 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003466 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003467 LR.getValueType(), LL, RL);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003468 AddToWorklist(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003469 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00003470 }
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003471 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3472 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
Scott Michelcf0da6c2009-02-17 22:15:04 +00003473 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
Nate Begeman049b7482005-09-09 19:49:52 +00003474 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003475 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003476 LR.getValueType(), LL, RL);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003477 AddToWorklist(ANDNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003478 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00003479 }
3480 }
3481 // canonicalize equivalent to ll == rl
3482 if (LL == RR && LR == RL) {
3483 Op1 = ISD::getSetCCSwappedOperands(Op1);
3484 std::swap(RL, RR);
3485 }
3486 if (LL == RL && LR == RR) {
Duncan Sands13237ac2008-06-06 12:08:01 +00003487 bool isInteger = LL.getValueType().isInteger();
Nate Begeman049b7482005-09-09 19:49:52 +00003488 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
Chris Lattner5fa10402008-10-28 07:11:07 +00003489 if (Result != ISD::SETCC_INVALID &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00003490 (!LegalOperations ||
Owen Andersoncc068992013-02-14 09:07:33 +00003491 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3492 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault758659232013-05-18 00:21:46 +00003493 getSetCCResultType(N0.getValueType())))))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003494 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003495 LL, LR, Result);
Nate Begeman049b7482005-09-09 19:49:52 +00003496 }
3497 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003498
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003499 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
Chris Lattner8d6fc202006-05-05 05:51:50 +00003500 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003501 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003502 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00003503 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003504
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003505 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
Chris Lattner46d710e2006-09-14 21:11:37 +00003506 if (N0.getOpcode() == ISD::AND &&
3507 N1.getOpcode() == ISD::AND &&
3508 N0.getOperand(1).getOpcode() == ISD::Constant &&
3509 N1.getOperand(1).getOpcode() == ISD::Constant &&
3510 // Don't increase # computations.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003511 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
Chris Lattner46d710e2006-09-14 21:11:37 +00003512 // We can only do this xform if we know that bits from X that are set in C2
3513 // but not in C1 are already zero. Likewise for Y.
Dan Gohman1f372ed2008-02-25 21:11:39 +00003514 const APInt &LHSMask =
3515 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3516 const APInt &RHSMask =
3517 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003518
Dan Gohman309d3d52007-06-22 14:59:07 +00003519 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3520 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003521 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003522 N0.getOperand(0), N1.getOperand(0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00003523 return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003524 DAG.getConstant(LHSMask | RHSMask, VT));
Chris Lattner46d710e2006-09-14 21:11:37 +00003525 }
3526 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003527
Chris Lattner97614c82006-09-14 20:50:57 +00003528 // See if this is some rotate idiom.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003529 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003530 return SDValue(Rot, 0);
Chris Lattner8d6fc202006-05-05 05:51:50 +00003531
Dan Gohman600f62b2010-06-24 14:30:44 +00003532 // Simplify the operands using demanded-bits information.
3533 if (!VT.isVector() &&
3534 SimplifyDemandedBits(SDValue(N, 0)))
3535 return SDValue(N, 0);
3536
Evan Chengf1005572010-04-28 07:10:39 +00003537 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00003538}
3539
Sanjay Patel50cbfc52014-08-28 16:29:51 +00003540/// Match "(X shl/srl V1) & V2" where V2 may not be present.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003541static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
Chris Lattner97614c82006-09-14 20:50:57 +00003542 if (Op.getOpcode() == ISD::AND) {
Reid Spencerde46e482006-11-02 20:25:50 +00003543 if (isa<ConstantSDNode>(Op.getOperand(1))) {
Chris Lattner97614c82006-09-14 20:50:57 +00003544 Mask = Op.getOperand(1);
3545 Op = Op.getOperand(0);
3546 } else {
3547 return false;
3548 }
3549 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003550
Chris Lattner97614c82006-09-14 20:50:57 +00003551 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3552 Shift = Op;
3553 return true;
3554 }
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003555
Scott Michelcf0da6c2009-02-17 22:15:04 +00003556 return false;
Chris Lattner97614c82006-09-14 20:50:57 +00003557}
3558
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003559// Return true if we can prove that, whenever Neg and Pos are both in the
3560// range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
Richard Sandiford0f264db2014-01-09 10:49:40 +00003561// for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3562//
3563// (or (shift1 X, Neg), (shift2 X, Pos))
3564//
Adam Nemetc6553a82014-03-07 23:56:24 +00003565// reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3566// in direction shift1 by Neg. The range [0, OpSize) means that we only need
3567// to consider shift amounts with defined behavior.
Richard Sandiford0f264db2014-01-09 10:49:40 +00003568static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003569 // If OpSize is a power of 2 then:
3570 //
3571 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3572 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3573 //
3574 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3575 // for the stronger condition:
3576 //
3577 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3578 //
3579 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3580 // we can just replace Neg with Neg' for the rest of the function.
3581 //
3582 // In other cases we check for the even stronger condition:
3583 //
3584 // Neg == OpSize - Pos [B]
3585 //
3586 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3587 // behavior if Pos == 0 (and consequently Neg == OpSize).
Adam Nemetc6553a82014-03-07 23:56:24 +00003588 //
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003589 // We could actually use [A] whenever OpSize is a power of 2, but the
3590 // only extra cases that it would match are those uninteresting ones
3591 // where Neg and Pos are never in range at the same time. E.g. for
3592 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3593 // as well as (sub 32, Pos), but:
3594 //
3595 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3596 //
3597 // always invokes undefined behavior for 32-bit X.
3598 //
3599 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
Adam Nemetc6553a82014-03-07 23:56:24 +00003600 unsigned MaskLoBits = 0;
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003601 if (Neg.getOpcode() == ISD::AND &&
3602 isPowerOf2_64(OpSize) &&
3603 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3604 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3605 Neg = Neg.getOperand(0);
Adam Nemetc6553a82014-03-07 23:56:24 +00003606 MaskLoBits = Log2_64(OpSize);
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003607 }
3608
Richard Sandiford0f264db2014-01-09 10:49:40 +00003609 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3610 if (Neg.getOpcode() != ISD::SUB)
3611 return 0;
3612 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3613 if (!NegC)
3614 return 0;
3615 SDValue NegOp1 = Neg.getOperand(1);
3616
Adam Nemet5117f5d2014-03-07 23:56:28 +00003617 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3618 // Pos'. The truncation is redundant for the purpose of the equality.
3619 if (MaskLoBits &&
3620 Pos.getOpcode() == ISD::AND &&
3621 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3622 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3623 Pos = Pos.getOperand(0);
3624
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003625 // The condition we need is now:
3626 //
3627 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3628 //
3629 // If NegOp1 == Pos then we need:
3630 //
3631 // OpSize & Mask == NegC & Mask
3632 //
3633 // (because "x & Mask" is a truncation and distributes through subtraction).
3634 APInt Width;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003635 if (Pos == NegOp1)
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003636 Width = NegC->getAPIntValue();
Richard Sandiford0f264db2014-01-09 10:49:40 +00003637 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3638 // Then the condition we want to prove becomes:
Richard Sandiford0f264db2014-01-09 10:49:40 +00003639 //
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003640 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3641 //
3642 // which, again because "x & Mask" is a truncation, becomes:
3643 //
3644 // NegC & Mask == (OpSize - PosC) & Mask
3645 // OpSize & Mask == (NegC + PosC) & Mask
3646 else if (Pos.getOpcode() == ISD::ADD &&
3647 Pos.getOperand(0) == NegOp1 &&
3648 Pos.getOperand(1).getOpcode() == ISD::Constant)
3649 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3650 NegC->getAPIntValue());
3651 else
3652 return false;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003653
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003654 // Now we just need to check that OpSize & Mask == Width & Mask.
Adam Nemetc6553a82014-03-07 23:56:24 +00003655 if (MaskLoBits)
3656 // Opsize & Mask is 0 since Mask is Opsize - 1.
3657 return Width.getLoBits(MaskLoBits) == 0;
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003658 return Width == OpSize;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003659}
3660
Richard Sandiford95c864d2014-01-08 15:40:47 +00003661// A subroutine of MatchRotate used once we have found an OR of two opposite
3662// shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3663// to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3664// former being preferred if supported. InnerPos and InnerNeg are Pos and
3665// Neg with outer conversions stripped away.
3666SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3667 SDValue Neg, SDValue InnerPos,
3668 SDValue InnerNeg, unsigned PosOpcode,
3669 unsigned NegOpcode, SDLoc DL) {
Richard Sandiford95c864d2014-01-08 15:40:47 +00003670 // fold (or (shl x, (*ext y)),
3671 // (srl x, (*ext (sub 32, y)))) ->
3672 // (rotl x, y) or (rotr x, (sub 32, y))
3673 //
3674 // fold (or (shl x, (*ext (sub 32, y))),
3675 // (srl x, (*ext y))) ->
3676 // (rotr x, y) or (rotl x, (sub 32, y))
3677 EVT VT = Shifted.getValueType();
Richard Sandiford0f264db2014-01-09 10:49:40 +00003678 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
Richard Sandiford95c864d2014-01-08 15:40:47 +00003679 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3680 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3681 HasPos ? Pos : Neg).getNode();
3682 }
3683
Craig Topperc0196b12014-04-14 00:51:57 +00003684 return nullptr;
Richard Sandiford95c864d2014-01-08 15:40:47 +00003685}
3686
Chris Lattner97614c82006-09-14 20:50:57 +00003687// MatchRotate - Handle an 'or' of two operands. If this is one of the many
3688// idioms for rotate, and if the target supports rotation instructions, generate
3689// a rot[lr].
Andrew Trickef9de2a2013-05-25 02:42:55 +00003690SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
Duncan Sands8651e9c2008-06-13 19:07:40 +00003691 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
Owen Anderson53aa7a92009-08-10 22:56:29 +00003692 EVT VT = LHS.getValueType();
Craig Topperc0196b12014-04-14 00:51:57 +00003693 if (!TLI.isTypeLegal(VT)) return nullptr;
Chris Lattner97614c82006-09-14 20:50:57 +00003694
3695 // The target must have at least one rotate flavor.
Dan Gohman4aa18462009-01-28 17:46:25 +00003696 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3697 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
Craig Topperc0196b12014-04-14 00:51:57 +00003698 if (!HasROTL && !HasROTR) return nullptr;
Duncan Sands8651e9c2008-06-13 19:07:40 +00003699
Chris Lattner97614c82006-09-14 20:50:57 +00003700 // Match "(X shl/srl V1) & V2" where V2 may not be present.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003701 SDValue LHSShift; // The shift.
3702 SDValue LHSMask; // AND value if any.
Chris Lattner97614c82006-09-14 20:50:57 +00003703 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
Craig Topperc0196b12014-04-14 00:51:57 +00003704 return nullptr; // Not part of a rotate.
Chris Lattner97614c82006-09-14 20:50:57 +00003705
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003706 SDValue RHSShift; // The shift.
3707 SDValue RHSMask; // AND value if any.
Chris Lattner97614c82006-09-14 20:50:57 +00003708 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
Craig Topperc0196b12014-04-14 00:51:57 +00003709 return nullptr; // Not part of a rotate.
Scott Michelcf0da6c2009-02-17 22:15:04 +00003710
Chris Lattner97614c82006-09-14 20:50:57 +00003711 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
Craig Topperc0196b12014-04-14 00:51:57 +00003712 return nullptr; // Not shifting the same value.
Chris Lattner97614c82006-09-14 20:50:57 +00003713
3714 if (LHSShift.getOpcode() == RHSShift.getOpcode())
Craig Topperc0196b12014-04-14 00:51:57 +00003715 return nullptr; // Shifts must disagree.
Scott Michelcf0da6c2009-02-17 22:15:04 +00003716
Chris Lattner97614c82006-09-14 20:50:57 +00003717 // Canonicalize shl to left side in a shl/srl pair.
3718 if (RHSShift.getOpcode() == ISD::SHL) {
3719 std::swap(LHS, RHS);
3720 std::swap(LHSShift, RHSShift);
3721 std::swap(LHSMask , RHSMask );
3722 }
3723
Duncan Sands13237ac2008-06-06 12:08:01 +00003724 unsigned OpSizeInBits = VT.getSizeInBits();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003725 SDValue LHSShiftArg = LHSShift.getOperand(0);
3726 SDValue LHSShiftAmt = LHSShift.getOperand(1);
Kai Nacked09bb462013-09-19 23:00:28 +00003727 SDValue RHSShiftArg = RHSShift.getOperand(0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003728 SDValue RHSShiftAmt = RHSShift.getOperand(1);
Chris Lattner97614c82006-09-14 20:50:57 +00003729
3730 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3731 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
Scott Michel16627a52007-04-02 21:36:32 +00003732 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3733 RHSShiftAmt.getOpcode() == ISD::Constant) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00003734 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3735 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
Chris Lattner97614c82006-09-14 20:50:57 +00003736 if ((LShVal + RShVal) != OpSizeInBits)
Craig Topperc0196b12014-04-14 00:51:57 +00003737 return nullptr;
Chris Lattner97614c82006-09-14 20:50:57 +00003738
Craig Topper65161fa2012-09-29 06:54:22 +00003739 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3740 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003741
Chris Lattner97614c82006-09-14 20:50:57 +00003742 // If there is an AND of either shifted operand, apply it to the result.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003743 if (LHSMask.getNode() || RHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003744 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003745
Gabor Greiff304a7a2008-08-28 21:40:38 +00003746 if (LHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003747 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3748 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
Chris Lattner97614c82006-09-14 20:50:57 +00003749 }
Gabor Greiff304a7a2008-08-28 21:40:38 +00003750 if (RHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003751 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3752 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
Chris Lattner97614c82006-09-14 20:50:57 +00003753 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003754
Bill Wendling35972a92009-01-30 21:14:50 +00003755 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
Chris Lattner97614c82006-09-14 20:50:57 +00003756 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003757
Gabor Greiff304a7a2008-08-28 21:40:38 +00003758 return Rot.getNode();
Chris Lattner97614c82006-09-14 20:50:57 +00003759 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003760
Chris Lattner97614c82006-09-14 20:50:57 +00003761 // If there is a mask here, and we have a variable shift, we can't be sure
3762 // that we're masking out the right stuff.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003763 if (LHSMask.getNode() || RHSMask.getNode())
Craig Topperc0196b12014-04-14 00:51:57 +00003764 return nullptr;
Scott Michelcf0da6c2009-02-17 22:15:04 +00003765
Benjamin Kramer64bdb292013-09-24 14:21:28 +00003766 // If the shift amount is sign/zext/any-extended just peel it off.
3767 SDValue LExtOp0 = LHSShiftAmt;
3768 SDValue RExtOp0 = RHSShiftAmt;
Craig Topper5f9791f2012-09-29 07:18:53 +00003769 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3770 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3771 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3772 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3773 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3774 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3775 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3776 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
Benjamin Kramer64bdb292013-09-24 14:21:28 +00003777 LExtOp0 = LHSShiftAmt.getOperand(0);
3778 RExtOp0 = RHSShiftAmt.getOperand(0);
3779 }
3780
Richard Sandiford95c864d2014-01-08 15:40:47 +00003781 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3782 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3783 if (TryL)
3784 return TryL;
3785
3786 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3787 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3788 if (TryR)
3789 return TryR;
Scott Michelcf0da6c2009-02-17 22:15:04 +00003790
Craig Topperc0196b12014-04-14 00:51:57 +00003791 return nullptr;
Chris Lattner97614c82006-09-14 20:50:57 +00003792}
3793
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003794SDValue DAGCombiner::visitXOR(SDNode *N) {
3795 SDValue N0 = N->getOperand(0);
3796 SDValue N1 = N->getOperand(1);
3797 SDValue LHS, RHS, CC;
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003798 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3799 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00003800 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003801
Dan Gohmana8665142007-06-25 16:23:39 +00003802 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00003803 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003804 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003805 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00003806
3807 // fold (xor x, 0) -> x, vector edition
3808 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3809 return N1;
3810 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3811 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00003812 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003813
Evan Chengdf1690d2008-03-25 20:08:07 +00003814 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3815 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3816 return DAG.getConstant(0, VT);
Dan Gohman06563a82007-07-03 14:03:57 +00003817 // fold (xor x, undef) -> undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00003818 if (N0.getOpcode() == ISD::UNDEF)
3819 return N0;
3820 if (N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00003821 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00003822 // fold (xor c1, c2) -> c1^c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003823 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00003824 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003825 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00003826 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003827 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00003828 // fold (xor x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003829 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003830 return N0;
Nate Begeman22e251a2006-02-03 06:46:56 +00003831 // reassociate xor
Andrew Trickef9de2a2013-05-25 02:42:55 +00003832 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003833 if (RXOR.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00003834 return RXOR;
Bill Wendling49a5ce82008-11-11 08:25:46 +00003835
Nate Begeman21158fc2005-09-01 00:19:25 +00003836 // fold !(x cc y) -> (x !cc y)
Oliver Stannardd29db9b2014-11-17 10:49:31 +00003837 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
Duncan Sands13237ac2008-06-06 12:08:01 +00003838 bool isInt = LHS.getValueType().isInteger();
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003839 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3840 isInt);
Bill Wendling49a5ce82008-11-11 08:25:46 +00003841
Patrik Hagglundffd057a2012-12-19 10:19:55 +00003842 if (!LegalOperations ||
3843 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
Bill Wendling49a5ce82008-11-11 08:25:46 +00003844 switch (N0.getOpcode()) {
3845 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +00003846 llvm_unreachable("Unhandled SetCC Equivalent!");
Bill Wendling49a5ce82008-11-11 08:25:46 +00003847 case ISD::SETCC:
Andrew Trickef9de2a2013-05-25 02:42:55 +00003848 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
Bill Wendling49a5ce82008-11-11 08:25:46 +00003849 case ISD::SELECT_CC:
Andrew Trickef9de2a2013-05-25 02:42:55 +00003850 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
Bill Wendling49a5ce82008-11-11 08:25:46 +00003851 N0.getOperand(3), NotCC);
3852 }
3853 }
Nate Begeman21158fc2005-09-01 00:19:25 +00003854 }
Bill Wendling49a5ce82008-11-11 08:25:46 +00003855
Chris Lattner58c227b2007-09-10 21:39:07 +00003856 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
Dan Gohmanb72127a2008-03-13 22:13:53 +00003857 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
Gabor Greife12264b2008-08-30 19:29:20 +00003858 N0.getNode()->hasOneUse() &&
3859 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003860 SDValue V = N0.getOperand(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003861 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
Duncan Sands56ab90d2007-10-10 09:54:50 +00003862 DAG.getConstant(1, V.getValueType()));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003863 AddToWorklist(V.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003864 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
Chris Lattner58c227b2007-09-10 21:39:07 +00003865 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003866
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003867 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
Owen Anderson9f944592009-08-11 20:47:22 +00003868 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003869 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003870 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003871 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3872 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
Andrew Trickef9de2a2013-05-25 02:42:55 +00003873 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3874 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003875 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003876 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
Nate Begeman21158fc2005-09-01 00:19:25 +00003877 }
3878 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003879 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
Scott Michelcf0da6c2009-02-17 22:15:04 +00003880 if (N1C && N1C->isAllOnesValue() &&
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003881 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003882 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003883 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3884 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
Andrew Trickef9de2a2013-05-25 02:42:55 +00003885 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3886 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003887 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003888 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
Nate Begeman21158fc2005-09-01 00:19:25 +00003889 }
3890 }
David Majnemer386ab7f2013-05-08 06:44:42 +00003891 // fold (xor (and x, y), y) -> (and (not x), y)
3892 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
Benjamin Kramerbb1dd732013-11-17 10:40:03 +00003893 N0->getOperand(1) == N1) {
David Majnemer386ab7f2013-05-08 06:44:42 +00003894 SDValue X = N0->getOperand(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003895 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003896 AddToWorklist(NotX.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003897 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
David Majnemer386ab7f2013-05-08 06:44:42 +00003898 }
Bill Wendling35972a92009-01-30 21:14:50 +00003899 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
Nate Begeman85c1cc42005-09-08 20:18:10 +00003900 if (N1C && N0.getOpcode() == ISD::XOR) {
3901 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3902 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3903 if (N00C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003904 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
Bill Wendling35972a92009-01-30 21:14:50 +00003905 DAG.getConstant(N1C->getAPIntValue() ^
Dan Gohmanb72127a2008-03-13 22:13:53 +00003906 N00C->getAPIntValue(), VT));
Nate Begeman85c1cc42005-09-08 20:18:10 +00003907 if (N01C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003908 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
Bill Wendling35972a92009-01-30 21:14:50 +00003909 DAG.getConstant(N1C->getAPIntValue() ^
Dan Gohmanb72127a2008-03-13 22:13:53 +00003910 N01C->getAPIntValue(), VT));
Nate Begeman85c1cc42005-09-08 20:18:10 +00003911 }
3912 // fold (xor x, x) -> 0
Eric Christophere5ca1e02011-02-16 04:50:12 +00003913 if (N0 == N1)
Hal Finkel6c29bd92013-07-09 17:02:45 +00003914 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003915
Chris Lattner8d6fc202006-05-05 05:51:50 +00003916 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3917 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003918 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003919 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00003920 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003921
Chris Lattner098c01e2006-04-08 04:15:24 +00003922 // Simplify the expression using non-local knowledge.
Duncan Sands13237ac2008-06-06 12:08:01 +00003923 if (!VT.isVector() &&
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003924 SimplifyDemandedBits(SDValue(N, 0)))
3925 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003926
Evan Chengf1005572010-04-28 07:10:39 +00003927 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00003928}
3929
Sanjay Patel50cbfc52014-08-28 16:29:51 +00003930/// Handle transforms common to the three shifts, when the shift amount is a
3931/// constant.
Matt Arsenault985b9de2014-03-17 18:58:01 +00003932SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003933 // We can't and shouldn't fold opaque constants.
Matt Arsenault985b9de2014-03-17 18:58:01 +00003934 if (Amt->isOpaque())
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003935 return SDValue();
3936
Gabor Greiff304a7a2008-08-28 21:40:38 +00003937 SDNode *LHS = N->getOperand(0).getNode();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003938 if (!LHS->hasOneUse()) return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003939
Chris Lattner7c709a52007-12-06 07:33:36 +00003940 // We want to pull some binops through shifts, so that we have (and (shift))
3941 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3942 // thing happens with address calculations, so it's important to canonicalize
3943 // it.
3944 bool HighBitSet = false; // Can we transform this if the high bit is set?
Scott Michelcf0da6c2009-02-17 22:15:04 +00003945
Chris Lattner7c709a52007-12-06 07:33:36 +00003946 switch (LHS->getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003947 default: return SDValue();
Chris Lattner7c709a52007-12-06 07:33:36 +00003948 case ISD::OR:
3949 case ISD::XOR:
3950 HighBitSet = false; // We can only transform sra if the high bit is clear.
3951 break;
3952 case ISD::AND:
3953 HighBitSet = true; // We can only transform sra if the high bit is set.
3954 break;
3955 case ISD::ADD:
Scott Michelcf0da6c2009-02-17 22:15:04 +00003956 if (N->getOpcode() != ISD::SHL)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003957 return SDValue(); // only shl(add) not sr[al](add).
Chris Lattner7c709a52007-12-06 07:33:36 +00003958 HighBitSet = false; // We can only transform sra if the high bit is clear.
3959 break;
3960 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003961
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003962 // We require the RHS of the binop to be a constant and not opaque as well.
Chris Lattner7c709a52007-12-06 07:33:36 +00003963 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003964 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003965
3966 // FIXME: disable this unless the input to the binop is a shift by a constant.
3967 // If it is not a shift, it pessimizes some common cases like:
Chris Lattnereedaf922007-12-06 07:47:55 +00003968 //
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003969 // void foo(int *X, int i) { X[i & 1235] = 1; }
3970 // int bar(int *X, int i) { return X[i & 255]; }
Gabor Greiff304a7a2008-08-28 21:40:38 +00003971 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003972 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
Chris Lattnereedaf922007-12-06 07:47:55 +00003973 BinOpLHSVal->getOpcode() != ISD::SRA &&
3974 BinOpLHSVal->getOpcode() != ISD::SRL) ||
3975 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003976 return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003977
Owen Anderson53aa7a92009-08-10 22:56:29 +00003978 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003979
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003980 // If this is a signed shift right, and the high bit is modified by the
3981 // logical operation, do not perform the transformation. The highBitSet
3982 // boolean indicates the value of the high bit of the constant which would
3983 // cause it to be modified for this operation.
Chris Lattner7c709a52007-12-06 07:33:36 +00003984 if (N->getOpcode() == ISD::SRA) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003985 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3986 if (BinOpRHSSignSet != HighBitSet)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003987 return SDValue();
Chris Lattner7c709a52007-12-06 07:33:36 +00003988 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003989
Weiming Zhao7f6daf12014-04-30 21:07:24 +00003990 if (!TLI.isDesirableToCommuteWithShift(LHS))
3991 return SDValue();
3992
Chris Lattner7c709a52007-12-06 07:33:36 +00003993 // Fold the constants, shifting the binop RHS by the shift amount.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003994 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003995 N->getValueType(0),
3996 LHS->getOperand(1), N->getOperand(1));
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003997 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
Chris Lattner7c709a52007-12-06 07:33:36 +00003998
3999 // Create the new shift.
Eric Christopherd9e8eac2010-12-09 04:48:06 +00004000 SDValue NewShift = DAG.getNode(N->getOpcode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00004001 SDLoc(LHS->getOperand(0)),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004002 VT, LHS->getOperand(0), N->getOperand(1));
Chris Lattner7c709a52007-12-06 07:33:36 +00004003
4004 // Create the new binop.
Andrew Trickef9de2a2013-05-25 02:42:55 +00004005 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
Chris Lattner7c709a52007-12-06 07:33:36 +00004006}
4007
Adam Nemet67483892014-03-04 23:28:31 +00004008SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4009 assert(N->getOpcode() == ISD::TRUNCATE);
4010 assert(N->getOperand(0).getOpcode() == ISD::AND);
4011
4012 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4013 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4014 SDValue N01 = N->getOperand(0).getOperand(1);
4015
Matt Arsenault985b9de2014-03-17 18:58:01 +00004016 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
Adam Nemet67483892014-03-04 23:28:31 +00004017 EVT TruncVT = N->getValueType(0);
4018 SDValue N00 = N->getOperand(0).getOperand(0);
4019 APInt TruncC = N01C->getAPIntValue();
Matt Arsenault985b9de2014-03-17 18:58:01 +00004020 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
Adam Nemet67483892014-03-04 23:28:31 +00004021
4022 return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
4023 DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
4024 DAG.getConstant(TruncC, TruncVT));
4025 }
4026 }
4027
4028 return SDValue();
4029}
Adam Nemet7f928f12014-03-07 23:56:30 +00004030
4031SDValue DAGCombiner::visitRotate(SDNode *N) {
4032 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4033 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4034 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4035 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4036 if (NewOp1.getNode())
4037 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4038 N->getOperand(0), NewOp1);
4039 }
4040 return SDValue();
4041}
4042
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004043SDValue DAGCombiner::visitSHL(SDNode *N) {
4044 SDValue N0 = N->getOperand(0);
4045 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004046 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4047 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004048 EVT VT = N0.getValueType();
Matt Arsenault985b9de2014-03-17 18:58:01 +00004049 unsigned OpSizeInBits = VT.getScalarSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004050
Daniel Sandersa1840d22013-11-11 17:23:41 +00004051 // fold vector ops
4052 if (VT.isVector()) {
4053 SDValue FoldedVOp = SimplifyVBinOp(N);
4054 if (FoldedVOp.getNode()) return FoldedVOp;
Quentin Colombet4db08df2014-02-21 23:42:41 +00004055
4056 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4057 // If setcc produces all-one true value then:
4058 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
Matt Arsenault985b9de2014-03-17 18:58:01 +00004059 if (N1CV && N1CV->isConstant()) {
Daniel Sanderscbd44c52014-07-10 10:18:12 +00004060 if (N0.getOpcode() == ISD::AND) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004061 SDValue N00 = N0->getOperand(0);
4062 SDValue N01 = N0->getOperand(1);
4063 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
Quentin Colombet4db08df2014-02-21 23:42:41 +00004064
Daniel Sanderscbd44c52014-07-10 10:18:12 +00004065 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4066 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4067 TargetLowering::ZeroOrNegativeOneBooleanContent) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004068 SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
4069 if (C.getNode())
4070 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4071 }
4072 } else {
4073 N1C = isConstOrConstSplat(N1);
Quentin Colombet4db08df2014-02-21 23:42:41 +00004074 }
4075 }
Daniel Sandersa1840d22013-11-11 17:23:41 +00004076 }
4077
Nate Begeman21158fc2005-09-01 00:19:25 +00004078 // fold (shl c1, c2) -> c1<<c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004079 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00004080 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00004081 // fold (shl 0, x) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004082 if (N0C && N0C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004083 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004084 // fold (shl x, c >= size(x)) -> undef
Dan Gohmaneffb8942008-09-12 16:56:44 +00004085 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00004086 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004087 // fold (shl x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004088 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004089 return N0;
Chad Rosier818e1162011-06-14 22:29:10 +00004090 // fold (shl undef, x) -> 0
4091 if (N0.getOpcode() == ISD::UNDEF)
4092 return DAG.getConstant(0, VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004093 // if (shl x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004094 if (DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1d459e42009-12-11 21:31:27 +00004095 APInt::getAllOnesValue(OpSizeInBits)))
Nate Begemand23739d2005-09-06 04:43:02 +00004096 return DAG.getConstant(0, VT);
Duncan Sands3ed76882009-02-01 18:06:53 +00004097 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004098 if (N1.getOpcode() == ISD::TRUNCATE &&
Adam Nemet67483892014-03-04 23:28:31 +00004099 N1.getOperand(0).getOpcode() == ISD::AND) {
4100 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4101 if (NewOp1.getNode())
4102 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004103 }
4104
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004105 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4106 return SDValue(N, 0);
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004107
4108 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
Matt Arsenault985b9de2014-03-17 18:58:01 +00004109 if (N1C && N0.getOpcode() == ISD::SHL) {
4110 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4111 uint64_t c1 = N0C1->getZExtValue();
4112 uint64_t c2 = N1C->getZExtValue();
4113 if (c1 + c2 >= OpSizeInBits)
4114 return DAG.getConstant(0, VT);
4115 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4116 DAG.getConstant(c1 + c2, N1.getValueType()));
4117 }
Nate Begeman21158fc2005-09-01 00:19:25 +00004118 }
Dale Johannesena94e36b2010-12-21 21:55:50 +00004119
4120 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4121 // For this to be valid, the second form must not preserve any of the bits
4122 // that are shifted out by the inner shift in the first form. This means
4123 // the outer shift size must be >= the number of bits added by the ext.
4124 // As a corollary, we don't care what kind of ext it is.
4125 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4126 N0.getOpcode() == ISD::ANY_EXTEND ||
4127 N0.getOpcode() == ISD::SIGN_EXTEND) &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004128 N0.getOperand(0).getOpcode() == ISD::SHL) {
4129 SDValue N0Op0 = N0.getOperand(0);
4130 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4131 uint64_t c1 = N0Op0C1->getZExtValue();
4132 uint64_t c2 = N1C->getZExtValue();
4133 EVT InnerShiftVT = N0Op0.getValueType();
4134 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4135 if (c2 >= OpSizeInBits - InnerShiftSize) {
4136 if (c1 + c2 >= OpSizeInBits)
4137 return DAG.getConstant(0, VT);
4138 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4139 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4140 N0Op0->getOperand(0)),
4141 DAG.getConstant(c1 + c2, N1.getValueType()));
4142 }
Dale Johannesena94e36b2010-12-21 21:55:50 +00004143 }
4144 }
4145
Andrea Di Biagio56ce9c42013-09-27 11:37:05 +00004146 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4147 // Only fold this if the inner zext has no other uses to avoid increasing
4148 // the total number of instructions.
4149 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004150 N0.getOperand(0).getOpcode() == ISD::SRL) {
4151 SDValue N0Op0 = N0.getOperand(0);
4152 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4153 uint64_t c1 = N0Op0C1->getZExtValue();
4154 if (c1 < VT.getScalarSizeInBits()) {
4155 uint64_t c2 = N1C->getZExtValue();
4156 if (c1 == c2) {
4157 SDValue NewOp0 = N0.getOperand(0);
4158 EVT CountVT = NewOp0.getOperand(1).getValueType();
4159 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4160 NewOp0, DAG.getConstant(c2, CountVT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004161 AddToWorklist(NewSHL.getNode());
Matt Arsenault985b9de2014-03-17 18:58:01 +00004162 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4163 }
Andrea Di Biagio56ce9c42013-09-27 11:37:05 +00004164 }
4165 }
4166 }
4167
Eli Friedman1877ac92011-06-09 22:14:44 +00004168 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4169 // (and (srl x, (sub c1, c2), MASK)
Chandler Carruthe041a302012-01-05 11:05:55 +00004170 // Only fold this if the inner shift has no other uses -- if it does, folding
4171 // this will increase the total number of instructions.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004172 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4173 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4174 uint64_t c1 = N0C1->getZExtValue();
4175 if (c1 < OpSizeInBits) {
4176 uint64_t c2 = N1C->getZExtValue();
4177 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4178 SDValue Shift;
4179 if (c2 > c1) {
4180 Mask = Mask.shl(c2 - c1);
4181 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4182 DAG.getConstant(c2 - c1, N1.getValueType()));
4183 } else {
4184 Mask = Mask.lshr(c1 - c2);
4185 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4186 DAG.getConstant(c1 - c2, N1.getValueType()));
4187 }
4188 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4189 DAG.getConstant(Mask, VT));
Eli Friedman1877ac92011-06-09 22:14:44 +00004190 }
Evan Chenga7bb55e2009-07-21 05:40:15 +00004191 }
Nate Begeman21158fc2005-09-01 00:19:25 +00004192 }
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004193 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
Dan Gohman5758e1e2009-08-06 09:18:59 +00004194 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004195 unsigned BitSize = VT.getScalarSizeInBits();
Dan Gohman5758e1e2009-08-06 09:18:59 +00004196 SDValue HiBitsMask =
Matt Arsenault985b9de2014-03-17 18:58:01 +00004197 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4198 BitSize - N1C->getZExtValue()), VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004199 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
Dan Gohman5758e1e2009-08-06 09:18:59 +00004200 HiBitsMask);
4201 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004202
Matt Arsenault8239eaa2014-09-11 17:34:19 +00004203 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4204 // Variant of version done on multiply, except mul by a power of 2 is turned
4205 // into a shift.
4206 APInt Val;
4207 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4208 (isa<ConstantSDNode>(N0.getOperand(1)) ||
4209 isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4210 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4211 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4212 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4213 }
4214
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004215 if (N1C) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004216 SDValue NewSHL = visitShiftByConstant(N, N1C);
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004217 if (NewSHL.getNode())
4218 return NewSHL;
4219 }
4220
Evan Chengf1005572010-04-28 07:10:39 +00004221 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004222}
4223
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004224SDValue DAGCombiner::visitSRA(SDNode *N) {
4225 SDValue N0 = N->getOperand(0);
4226 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004227 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4228 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004229 EVT VT = N0.getValueType();
Dan Gohman1d459e42009-12-11 21:31:27 +00004230 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004231
Daniel Sandersa1840d22013-11-11 17:23:41 +00004232 // fold vector ops
4233 if (VT.isVector()) {
4234 SDValue FoldedVOp = SimplifyVBinOp(N);
4235 if (FoldedVOp.getNode()) return FoldedVOp;
Matt Arsenault985b9de2014-03-17 18:58:01 +00004236
4237 N1C = isConstOrConstSplat(N1);
Daniel Sandersa1840d22013-11-11 17:23:41 +00004238 }
4239
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004240 // fold (sra c1, c2) -> (sra c1, c2)
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004241 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00004242 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00004243 // fold (sra 0, x) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004244 if (N0C && N0C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004245 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004246 // fold (sra -1, x) -> -1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004247 if (N0C && N0C->isAllOnesValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004248 return N0;
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004249 // fold (sra x, (setge c, size(x))) -> undef
Dan Gohman1d459e42009-12-11 21:31:27 +00004250 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00004251 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004252 // fold (sra x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004253 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004254 return N0;
Nate Begemanfb5dbad2006-02-17 19:54:08 +00004255 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4256 // sext_inreg.
4257 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
Dan Gohman1d459e42009-12-11 21:31:27 +00004258 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004259 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4260 if (VT.isVector())
4261 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4262 ExtVT, VT.getVectorNumElements());
4263 if ((!LegalOperations ||
4264 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004265 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004266 N0.getOperand(0), DAG.getValueType(ExtVT));
Nate Begemanfb5dbad2006-02-17 19:54:08 +00004267 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00004268
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004269 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
Chris Lattner0f8a7272006-02-28 06:23:04 +00004270 if (N1C && N0.getOpcode() == ISD::SRA) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004271 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00004272 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
Matt Arsenault985b9de2014-03-17 18:58:01 +00004273 if (Sum >= OpSizeInBits)
4274 Sum = OpSizeInBits - 1;
Andrew Trickef9de2a2013-05-25 02:42:55 +00004275 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
Matt Arsenault985b9de2014-03-17 18:58:01 +00004276 DAG.getConstant(Sum, N1.getValueType()));
Chris Lattner0f8a7272006-02-28 06:23:04 +00004277 }
4278 }
Christopher Lamb8fe91092008-03-19 08:30:06 +00004279
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004280 // fold (sra (shl X, m), (sub result_size, n))
4281 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
Scott Michelcf0da6c2009-02-17 22:15:04 +00004282 // result_size - n != m.
4283 // If truncate is free for the target sext(shl) is likely to result in better
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004284 // code.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004285 if (N0.getOpcode() == ISD::SHL && N1C) {
Christopher Lamb8fe91092008-03-19 08:30:06 +00004286 // Get the two constanst of the shifts, CN0 = m, CN = n.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004287 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4288 if (N01C) {
4289 LLVMContext &Ctx = *DAG.getContext();
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004290 // Determine what the truncate's result bitsize and type would be.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004291 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4292
4293 if (VT.isVector())
4294 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4295
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004296 // Determine the residual right-shift amount.
Torok Edwinbe6a9a12009-05-23 17:29:48 +00004297 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
Duncan Sands8651e9c2008-06-13 19:07:40 +00004298
Scott Michelcf0da6c2009-02-17 22:15:04 +00004299 // If the shift is not a no-op (in which case this should be just a sign
4300 // extend already), the truncated to type is legal, sign_extend is legal
Dan Gohman4a618822010-02-10 16:03:48 +00004301 // on that type, and the truncate to that type is both legal and free,
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004302 // perform the transform.
Torok Edwinbe6a9a12009-05-23 17:29:48 +00004303 if ((ShiftAmt > 0) &&
Dan Gohman4aa18462009-01-28 17:46:25 +00004304 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4305 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
Evan Cheng7a3e7502008-03-20 02:18:41 +00004306 TLI.isTruncateFree(VT, TruncVT)) {
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004307
Owen Andersonb2c80da2011-02-25 21:41:48 +00004308 SDValue Amt = DAG.getConstant(ShiftAmt,
4309 getShiftAmountTy(N0.getOperand(0).getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004310 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004311 N0.getOperand(0), Amt);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004312 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004313 Shift);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004314 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004315 N->getValueType(0), Trunc);
Christopher Lamb8fe91092008-03-19 08:30:06 +00004316 }
4317 }
4318 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004319
Duncan Sands3ed76882009-02-01 18:06:53 +00004320 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004321 if (N1.getOpcode() == ISD::TRUNCATE &&
Adam Nemet67483892014-03-04 23:28:31 +00004322 N1.getOperand(0).getOpcode() == ISD::AND) {
4323 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4324 if (NewOp1.getNode())
4325 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004326 }
4327
Matt Arsenault985b9de2014-03-17 18:58:01 +00004328 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
Benjamin Kramer946e1522011-01-30 16:38:43 +00004329 // if c1 is equal to the number of bits the trunc removes
4330 if (N0.getOpcode() == ISD::TRUNCATE &&
4331 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4332 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4333 N0.getOperand(0).hasOneUse() &&
4334 N0.getOperand(0).getOperand(1).hasOneUse() &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004335 N1C) {
4336 SDValue N0Op0 = N0.getOperand(0);
4337 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4338 unsigned LargeShiftVal = LargeShift->getZExtValue();
4339 EVT LargeVT = N0Op0.getValueType();
Benjamin Kramer946e1522011-01-30 16:38:43 +00004340
Matt Arsenault985b9de2014-03-17 18:58:01 +00004341 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4342 SDValue Amt =
4343 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4344 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4345 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4346 N0Op0.getOperand(0), Amt);
4347 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4348 }
Benjamin Kramer946e1522011-01-30 16:38:43 +00004349 }
4350 }
4351
Scott Michelcf0da6c2009-02-17 22:15:04 +00004352 // Simplify, based on bits shifted out of the LHS.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004353 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4354 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004355
4356
Nate Begeman21158fc2005-09-01 00:19:25 +00004357 // If the sign bit is known to be zero, switch this to a SRL.
Dan Gohman1f372ed2008-02-25 21:11:39 +00004358 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004359 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
Chris Lattner7c709a52007-12-06 07:33:36 +00004360
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004361 if (N1C) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004362 SDValue NewSRA = visitShiftByConstant(N, N1C);
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004363 if (NewSRA.getNode())
4364 return NewSRA;
4365 }
4366
Evan Chengf1005572010-04-28 07:10:39 +00004367 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004368}
4369
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004370SDValue DAGCombiner::visitSRL(SDNode *N) {
4371 SDValue N0 = N->getOperand(0);
4372 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004373 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4374 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004375 EVT VT = N0.getValueType();
Dan Gohman1d459e42009-12-11 21:31:27 +00004376 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004377
Daniel Sandersa1840d22013-11-11 17:23:41 +00004378 // fold vector ops
4379 if (VT.isVector()) {
4380 SDValue FoldedVOp = SimplifyVBinOp(N);
4381 if (FoldedVOp.getNode()) return FoldedVOp;
Matt Arsenault985b9de2014-03-17 18:58:01 +00004382
4383 N1C = isConstOrConstSplat(N1);
Daniel Sandersa1840d22013-11-11 17:23:41 +00004384 }
4385
Nate Begeman21158fc2005-09-01 00:19:25 +00004386 // fold (srl c1, c2) -> c1 >>u c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004387 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00004388 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00004389 // fold (srl 0, x) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004390 if (N0C && N0C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004391 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004392 // fold (srl x, c >= size(x)) -> undef
Dan Gohmaneffb8942008-09-12 16:56:44 +00004393 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00004394 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004395 // fold (srl x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004396 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004397 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004398 // if (srl x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004399 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1f372ed2008-02-25 21:11:39 +00004400 APInt::getAllOnesValue(OpSizeInBits)))
Nate Begemand23739d2005-09-06 04:43:02 +00004401 return DAG.getConstant(0, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004402
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004403 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
Matt Arsenault985b9de2014-03-17 18:58:01 +00004404 if (N1C && N0.getOpcode() == ISD::SRL) {
4405 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4406 uint64_t c1 = N01C->getZExtValue();
4407 uint64_t c2 = N1C->getZExtValue();
4408 if (c1 + c2 >= OpSizeInBits)
4409 return DAG.getConstant(0, VT);
4410 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4411 DAG.getConstant(c1 + c2, N1.getValueType()));
4412 }
Nate Begeman21158fc2005-09-01 00:19:25 +00004413 }
Wesley Peck527da1b2010-11-23 03:31:01 +00004414
Dale Johannesencd538af2010-12-17 21:45:49 +00004415 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
Dale Johannesencd538af2010-12-17 21:45:49 +00004416 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4417 N0.getOperand(0).getOpcode() == ISD::SRL &&
Dale Johannesen0a291a32010-12-20 20:10:50 +00004418 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
Owen Andersonb2c80da2011-02-25 21:41:48 +00004419 uint64_t c1 =
Dale Johannesencd538af2010-12-17 21:45:49 +00004420 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4421 uint64_t c2 = N1C->getZExtValue();
Dale Johannesena94e36b2010-12-21 21:55:50 +00004422 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4423 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
Dale Johannesencd538af2010-12-17 21:45:49 +00004424 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
Dale Johannesen0a291a32010-12-20 20:10:50 +00004425 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
Dale Johannesencd538af2010-12-17 21:45:49 +00004426 if (c1 + OpSizeInBits == InnerShiftSize) {
4427 if (c1 + c2 >= InnerShiftSize)
4428 return DAG.getConstant(0, VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004429 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4430 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
Dale Johannesencd538af2010-12-17 21:45:49 +00004431 N0.getOperand(0)->getOperand(0),
Dale Johannesena94e36b2010-12-21 21:55:50 +00004432 DAG.getConstant(c1 + c2, ShiftCountVT)));
Dale Johannesencd538af2010-12-17 21:45:49 +00004433 }
4434 }
4435
Chris Lattnerf9b2e3c2010-04-15 05:28:43 +00004436 // fold (srl (shl x, c), c) -> (and x, cst2)
Matt Arsenault985b9de2014-03-17 18:58:01 +00004437 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4438 unsigned BitSize = N0.getScalarValueSizeInBits();
4439 if (BitSize <= 64) {
4440 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4441 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4442 DAG.getConstant(~0ULL >> ShAmt, VT));
4443 }
Chris Lattnerf9b2e3c2010-04-15 05:28:43 +00004444 }
Wesley Peck527da1b2010-11-23 03:31:01 +00004445
Michael Liao62ebfd82013-06-21 18:45:27 +00004446 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004447 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4448 // Shifting in all undef bits?
Owen Anderson53aa7a92009-08-10 22:56:29 +00004449 EVT SmallVT = N0.getOperand(0).getValueType();
Matt Arsenault985b9de2014-03-17 18:58:01 +00004450 unsigned BitSize = SmallVT.getScalarSizeInBits();
4451 if (N1C->getZExtValue() >= BitSize)
Dale Johannesen84935752009-02-06 23:05:02 +00004452 return DAG.getUNDEF(VT);
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004453
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004454 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
Owen Andersona5192842011-04-14 17:30:49 +00004455 uint64_t ShiftAmt = N1C->getZExtValue();
Andrew Trickef9de2a2013-05-25 02:42:55 +00004456 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
Owen Andersona5192842011-04-14 17:30:49 +00004457 N0.getOperand(0),
4458 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004459 AddToWorklist(SmallShift.getNode());
Matt Arsenault985b9de2014-03-17 18:58:01 +00004460 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
Michael Liao62ebfd82013-06-21 18:45:27 +00004461 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4462 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4463 DAG.getConstant(Mask, VT));
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004464 }
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004465 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004466
Chris Lattner2e33fb42006-10-12 20:23:19 +00004467 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4468 // bit, which is unmodified by sra.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004469 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
Chris Lattner2e33fb42006-10-12 20:23:19 +00004470 if (N0.getOpcode() == ISD::SRA)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004471 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
Chris Lattner2e33fb42006-10-12 20:23:19 +00004472 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004473
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00004474 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
Scott Michelcf0da6c2009-02-17 22:15:04 +00004475 if (N1C && N0.getOpcode() == ISD::CTLZ &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004476 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004477 APInt KnownZero, KnownOne;
Jay Foada0653a32014-05-14 21:14:37 +00004478 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004479
Chris Lattner49932492006-04-02 06:11:11 +00004480 // If any of the input bits are KnownOne, then the input couldn't be all
4481 // zeros, thus the result of the srl will always be zero.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004482 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004483
Chris Lattner49932492006-04-02 06:11:11 +00004484 // If all of the bits input the to ctlz node are known to be zero, then
4485 // the result of the ctlz is "32" and the result of the shift is one.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00004486 APInt UnknownBits = ~KnownZero;
Chris Lattner49932492006-04-02 06:11:11 +00004487 if (UnknownBits == 0) return DAG.getConstant(1, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004488
Chris Lattner49932492006-04-02 06:11:11 +00004489 // Otherwise, check to see if there is exactly one bit input to the ctlz.
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004490 if ((UnknownBits & (UnknownBits - 1)) == 0) {
Chris Lattner49932492006-04-02 06:11:11 +00004491 // Okay, we know that only that the single bit specified by UnknownBits
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004492 // could be set on input to the CTLZ node. If this bit is set, the SRL
4493 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4494 // to an SRL/XOR pair, which is likely to simplify more.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004495 unsigned ShAmt = UnknownBits.countTrailingZeros();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004496 SDValue Op = N0.getOperand(0);
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004497
Chris Lattner49932492006-04-02 06:11:11 +00004498 if (ShAmt) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004499 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
Owen Andersonb2c80da2011-02-25 21:41:48 +00004500 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004501 AddToWorklist(Op.getNode());
Chris Lattner49932492006-04-02 06:11:11 +00004502 }
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004503
Andrew Trickef9de2a2013-05-25 02:42:55 +00004504 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004505 Op, DAG.getConstant(1, VT));
Chris Lattner49932492006-04-02 06:11:11 +00004506 }
4507 }
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004508
Duncan Sands3ed76882009-02-01 18:06:53 +00004509 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004510 if (N1.getOpcode() == ISD::TRUNCATE &&
Adam Nemet67483892014-03-04 23:28:31 +00004511 N1.getOperand(0).getOpcode() == ISD::AND) {
4512 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4513 if (NewOp1.getNode())
4514 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004515 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004516
Chris Lattnerf03c90b2007-04-18 03:06:49 +00004517 // fold operands of srl based on knowledge that the low bits are not
4518 // demanded.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004519 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4520 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004521
Evan Chengb175de62009-12-18 21:31:31 +00004522 if (N1C) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004523 SDValue NewSRL = visitShiftByConstant(N, N1C);
Evan Chengb175de62009-12-18 21:31:31 +00004524 if (NewSRL.getNode())
4525 return NewSRL;
4526 }
4527
Dan Gohman600f62b2010-06-24 14:30:44 +00004528 // Attempt to convert a srl of a load into a narrower zero-extending load.
4529 SDValue NarrowLoad = ReduceLoadWidth(N);
4530 if (NarrowLoad.getNode())
4531 return NarrowLoad;
4532
Evan Chengb175de62009-12-18 21:31:31 +00004533 // Here is a common situation. We want to optimize:
4534 //
4535 // %a = ...
4536 // %b = and i32 %a, 2
4537 // %c = srl i32 %b, 1
4538 // brcond i32 %c ...
4539 //
4540 // into
Wesley Peck527da1b2010-11-23 03:31:01 +00004541 //
Evan Chengb175de62009-12-18 21:31:31 +00004542 // %a = ...
4543 // %b = and %a, 2
4544 // %c = setcc eq %b, 0
4545 // brcond %c ...
4546 //
4547 // However when after the source operand of SRL is optimized into AND, the SRL
4548 // itself may not be optimized further. Look for it and add the BRCOND into
4549 // the worklist.
Evan Cheng166a4e62010-01-06 19:38:29 +00004550 if (N->hasOneUse()) {
4551 SDNode *Use = *N->use_begin();
4552 if (Use->getOpcode() == ISD::BRCOND)
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004553 AddToWorklist(Use);
Evan Cheng166a4e62010-01-06 19:38:29 +00004554 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4555 // Also look pass the truncate.
4556 Use = *Use->use_begin();
4557 if (Use->getOpcode() == ISD::BRCOND)
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004558 AddToWorklist(Use);
Evan Cheng166a4e62010-01-06 19:38:29 +00004559 }
4560 }
Evan Chengb175de62009-12-18 21:31:31 +00004561
Evan Chengf1005572010-04-28 07:10:39 +00004562 return SDValue();
Evan Chenge19aa5c2010-04-19 19:29:22 +00004563}
4564
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004565SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4566 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004567 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00004568
4569 // fold (ctlz c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004570 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004571 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004572 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004573}
4574
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004575SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4576 SDValue N0 = N->getOperand(0);
4577 EVT VT = N->getValueType(0);
4578
4579 // fold (ctlz_zero_undef c1) -> c2
4580 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004581 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004582 return SDValue();
4583}
4584
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004585SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4586 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004587 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004588
Nate Begeman21158fc2005-09-01 00:19:25 +00004589 // fold (cttz c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004590 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004591 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004592 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004593}
4594
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004595SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4596 SDValue N0 = N->getOperand(0);
4597 EVT VT = N->getValueType(0);
4598
4599 // fold (cttz_zero_undef c1) -> c2
4600 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004601 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004602 return SDValue();
4603}
4604
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004605SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4606 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004607 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004608
Nate Begeman21158fc2005-09-01 00:19:25 +00004609 // fold (ctpop c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004610 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004611 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004612 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004613}
4614
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004615SDValue DAGCombiner::visitSELECT(SDNode *N) {
4616 SDValue N0 = N->getOperand(0);
4617 SDValue N1 = N->getOperand(1);
4618 SDValue N2 = N->getOperand(2);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004619 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4620 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4621 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004622 EVT VT = N->getValueType(0);
4623 EVT VT0 = N0.getValueType();
Nate Begemanc760f802005-09-19 22:34:01 +00004624
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004625 // fold (select C, X, X) -> X
Nate Begeman24a7eca2005-09-16 00:54:12 +00004626 if (N1 == N2)
4627 return N1;
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004628 // fold (select true, X, Y) -> X
Nate Begeman24a7eca2005-09-16 00:54:12 +00004629 if (N0C && !N0C->isNullValue())
4630 return N1;
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004631 // fold (select false, X, Y) -> Y
Nate Begeman24a7eca2005-09-16 00:54:12 +00004632 if (N0C && N0C->isNullValue())
4633 return N2;
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004634 // fold (select C, 1, X) -> (or C, X)
Owen Anderson9f944592009-08-11 20:47:22 +00004635 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004636 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004637 // fold (select C, 0, 1) -> (xor C, 1)
Daniel Sanderscbd44c52014-07-10 10:18:12 +00004638 // We can't do this reliably if integer based booleans have different contents
4639 // to floating point based booleans. This is because we can't tell whether we
4640 // have an integer-based boolean or a floating-point-based boolean unless we
4641 // can find the SETCC that produced it and inspect its operands. This is
4642 // fairly easy if C is the SETCC node, but it can potentially be
4643 // undiscoverable (or not reasonably discoverable). For example, it could be
4644 // in another basic block or it could require searching a complicated
4645 // expression.
Bob Wilsonc2dc7ee2009-01-22 22:05:48 +00004646 if (VT.isInteger() &&
Daniel Sanderscbd44c52014-07-10 10:18:12 +00004647 (VT0 == MVT::i1 || (VT0.isInteger() &&
4648 TLI.getBooleanContents(false, false) ==
4649 TLI.getBooleanContents(false, true) &&
4650 TLI.getBooleanContents(false, false) ==
4651 TargetLowering::ZeroOrOneBooleanContent)) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00004652 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004653 SDValue XORNode;
Evan Chengf5a23ab2007-08-18 05:57:05 +00004654 if (VT == VT0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004655 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004656 N0, DAG.getConstant(1, VT0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004657 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004658 N0, DAG.getConstant(1, VT0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004659 AddToWorklist(XORNode.getNode());
Duncan Sands11dd4242008-06-08 20:54:56 +00004660 if (VT.bitsGT(VT0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004661 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4662 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
Evan Chengf5a23ab2007-08-18 05:57:05 +00004663 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004664 // fold (select C, 0, X) -> (and (not C), X)
Owen Anderson9f944592009-08-11 20:47:22 +00004665 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004666 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004667 AddToWorklist(NOTNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004668 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004669 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004670 // fold (select C, X, 1) -> (or (not C), X)
Owen Anderson9f944592009-08-11 20:47:22 +00004671 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004672 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004673 AddToWorklist(NOTNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004674 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004675 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004676 // fold (select C, X, 0) -> (and C, X)
Owen Anderson9f944592009-08-11 20:47:22 +00004677 if (VT == MVT::i1 && N2C && N2C->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00004678 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004679 // fold (select X, X, Y) -> (or X, Y)
4680 // fold (select X, 1, Y) -> (or X, Y)
Owen Anderson9f944592009-08-11 20:47:22 +00004681 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004682 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004683 // fold (select X, Y, X) -> (and X, Y)
4684 // fold (select X, Y, 0) -> (and X, Y)
Owen Anderson9f944592009-08-11 20:47:22 +00004685 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004686 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004687
Chris Lattner6c14c352005-10-18 06:04:22 +00004688 // If we can fold this based on the true/false value, do so.
4689 if (SimplifySelectOps(N, N1, N2))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004690 return SDValue(N, 0); // Don't revisit N.
Duncan Sands8651e9c2008-06-13 19:07:40 +00004691
Nate Begemanc760f802005-09-19 22:34:01 +00004692 // fold selects based on a setcc into other things, such as min/max/abs
Anton Korobeynikov035eaac2008-02-20 11:10:28 +00004693 if (N0.getOpcode() == ISD::SETCC) {
Tom Stellard3787b122014-06-10 16:01:29 +00004694 if ((!LegalOperations &&
4695 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00004696 TLI.isOperationLegal(ISD::SELECT_CC, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004697 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004698 N0.getOperand(0), N0.getOperand(1),
Nate Begeman7e7f4392006-02-01 07:19:44 +00004699 N1, N2, N0.getOperand(2));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004700 return SimplifySelect(SDLoc(N), N0, N1, N2);
Anton Korobeynikov035eaac2008-02-20 11:10:28 +00004701 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004702
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004703 return SDValue();
Nate Begeman24a7eca2005-09-16 00:54:12 +00004704}
4705
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004706static
4707std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4708 SDLoc DL(N);
4709 EVT LoVT, HiVT;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +00004710 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004711
4712 // Split the inputs.
4713 SDValue Lo, Hi, LL, LH, RL, RH;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +00004714 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4715 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004716
4717 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4718 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4719
4720 return std::make_pair(Lo, Hi);
4721}
4722
Filipe Cabecinhas82111f12014-05-30 23:03:11 +00004723// This function assumes all the vselect's arguments are CONCAT_VECTOR
4724// nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4725static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4726 SDLoc dl(N);
4727 SDValue Cond = N->getOperand(0);
4728 SDValue LHS = N->getOperand(1);
4729 SDValue RHS = N->getOperand(2);
Benjamin Kramerff8b8832014-08-21 13:28:02 +00004730 EVT VT = N->getValueType(0);
Filipe Cabecinhas82111f12014-05-30 23:03:11 +00004731 int NumElems = VT.getVectorNumElements();
4732 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4733 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4734 Cond.getOpcode() == ISD::BUILD_VECTOR);
4735
Benjamin Kramerff8b8832014-08-21 13:28:02 +00004736 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
4737 // binary ones here.
4738 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
4739 return SDValue();
4740
Filipe Cabecinhas82111f12014-05-30 23:03:11 +00004741 // We're sure we have an even number of elements due to the
4742 // concat_vectors we have as arguments to vselect.
4743 // Skip BV elements until we find one that's not an UNDEF
4744 // After we find an UNDEF element, keep looping until we get to half the
4745 // length of the BV and see if all the non-undef nodes are the same.
4746 ConstantSDNode *BottomHalf = nullptr;
4747 for (int i = 0; i < NumElems / 2; ++i) {
4748 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4749 continue;
4750
4751 if (BottomHalf == nullptr)
4752 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4753 else if (Cond->getOperand(i).getNode() != BottomHalf)
4754 return SDValue();
4755 }
4756
4757 // Do the same for the second half of the BuildVector
4758 ConstantSDNode *TopHalf = nullptr;
4759 for (int i = NumElems / 2; i < NumElems; ++i) {
4760 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4761 continue;
4762
4763 if (TopHalf == nullptr)
4764 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4765 else if (Cond->getOperand(i).getNode() != TopHalf)
4766 return SDValue();
4767 }
4768
4769 assert(TopHalf && BottomHalf &&
4770 "One half of the selector was all UNDEFs and the other was all the "
4771 "same value. This should have been addressed before this function.");
4772 return DAG.getNode(
4773 ISD::CONCAT_VECTORS, dl, VT,
4774 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4775 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4776}
4777
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00004778SDValue DAGCombiner::visitMSTORE(SDNode *N) {
4779
4780 if (Level >= AfterLegalizeTypes)
4781 return SDValue();
4782
4783 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
4784 SDValue Mask = MST->getMask();
4785 SDValue Data = MST->getData();
4786 SDLoc DL(N);
4787
4788 // If the MSTORE data type requires splitting and the mask is provided by a
4789 // SETCC, then split both nodes and its operands before legalization. This
4790 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4791 // and enables future optimizations (e.g. min/max pattern matching on X86).
4792 if (Mask.getOpcode() == ISD::SETCC) {
4793
4794 // Check if any splitting is required.
4795 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
4796 TargetLowering::TypeSplitVector)
4797 return SDValue();
4798
4799 SDValue MaskLo, MaskHi, Lo, Hi;
4800 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
4801
4802 EVT LoVT, HiVT;
4803 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
4804
4805 SDValue Chain = MST->getChain();
4806 SDValue Ptr = MST->getBasePtr();
4807
4808 EVT MemoryVT = MST->getMemoryVT();
4809 unsigned Alignment = MST->getOriginalAlignment();
4810
4811 // if Alignment is equal to the vector size,
4812 // take the half of it for the second part
4813 unsigned SecondHalfAlignment =
4814 (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
4815 Alignment/2 : Alignment;
4816
4817 EVT LoMemVT, HiMemVT;
4818 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
4819
4820 SDValue DataLo, DataHi;
4821 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
4822
4823 MachineMemOperand *MMO = DAG.getMachineFunction().
4824 getMachineMemOperand(MST->getPointerInfo(),
4825 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
4826 Alignment, MST->getAAInfo(), MST->getRanges());
4827
4828 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, MMO);
4829
4830 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
4831 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4832 DAG.getConstant(IncrementSize, Ptr.getValueType()));
4833
4834 MMO = DAG.getMachineFunction().
4835 getMachineMemOperand(MST->getPointerInfo(),
4836 MachineMemOperand::MOStore, HiMemVT.getStoreSize(),
4837 SecondHalfAlignment, MST->getAAInfo(),
4838 MST->getRanges());
4839
4840 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, MMO);
4841
4842 AddToWorklist(Lo.getNode());
4843 AddToWorklist(Hi.getNode());
4844
4845 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
4846 }
4847 return SDValue();
4848}
4849
4850SDValue DAGCombiner::visitMLOAD(SDNode *N) {
4851
4852 if (Level >= AfterLegalizeTypes)
4853 return SDValue();
4854
4855 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
4856 SDValue Mask = MLD->getMask();
4857 SDLoc DL(N);
4858
4859 // If the MLOAD result requires splitting and the mask is provided by a
4860 // SETCC, then split both nodes and its operands before legalization. This
4861 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4862 // and enables future optimizations (e.g. min/max pattern matching on X86).
4863
4864 if (Mask.getOpcode() == ISD::SETCC) {
4865 EVT VT = N->getValueType(0);
4866
4867 // Check if any splitting is required.
4868 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4869 TargetLowering::TypeSplitVector)
4870 return SDValue();
4871
4872 SDValue MaskLo, MaskHi, Lo, Hi;
4873 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
4874
4875 SDValue Src0 = MLD->getSrc0();
4876 SDValue Src0Lo, Src0Hi;
4877 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
4878
4879 EVT LoVT, HiVT;
4880 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
4881
4882 SDValue Chain = MLD->getChain();
4883 SDValue Ptr = MLD->getBasePtr();
4884 EVT MemoryVT = MLD->getMemoryVT();
4885 unsigned Alignment = MLD->getOriginalAlignment();
4886
4887 // if Alignment is equal to the vector size,
4888 // take the half of it for the second part
4889 unsigned SecondHalfAlignment =
4890 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
4891 Alignment/2 : Alignment;
4892
4893 EVT LoMemVT, HiMemVT;
4894 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
4895
4896 MachineMemOperand *MMO = DAG.getMachineFunction().
4897 getMachineMemOperand(MLD->getPointerInfo(),
4898 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
4899 Alignment, MLD->getAAInfo(), MLD->getRanges());
4900
4901 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, MMO);
4902
4903 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
4904 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4905 DAG.getConstant(IncrementSize, Ptr.getValueType()));
4906
4907 MMO = DAG.getMachineFunction().
4908 getMachineMemOperand(MLD->getPointerInfo(),
4909 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(),
4910 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
4911
4912 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, MMO);
4913
4914 AddToWorklist(Lo.getNode());
4915 AddToWorklist(Hi.getNode());
4916
4917 // Build a factor node to remember that this load is independent of the
4918 // other one.
4919 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
4920 Hi.getValue(1));
4921
4922 // Legalized the chain result - switch anything that used the old chain to
4923 // use the new one.
4924 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
4925
4926 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4927
4928 SDValue RetOps[] = { LoadRes, Chain };
4929 return DAG.getMergeValues(RetOps, DL);
4930 }
4931 return SDValue();
4932}
4933
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00004934SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4935 SDValue N0 = N->getOperand(0);
4936 SDValue N1 = N->getOperand(1);
4937 SDValue N2 = N->getOperand(2);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004938 SDLoc DL(N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00004939
4940 // Canonicalize integer abs.
4941 // vselect (setg[te] X, 0), X, -X ->
4942 // vselect (setgt X, -1), X, -X ->
4943 // vselect (setl[te] X, 0), -X, X ->
4944 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4945 if (N0.getOpcode() == ISD::SETCC) {
4946 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4947 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4948 bool isAbs = false;
4949 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4950
4951 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4952 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4953 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4954 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4955 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4956 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4957 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4958
4959 if (isAbs) {
4960 EVT VT = LHS.getValueType();
4961 SDValue Shift = DAG.getNode(
4962 ISD::SRA, DL, VT, LHS,
4963 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4964 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004965 AddToWorklist(Shift.getNode());
4966 AddToWorklist(Add.getNode());
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00004967 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4968 }
4969 }
4970
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004971 // If the VSELECT result requires splitting and the mask is provided by a
4972 // SETCC, then split both nodes and its operands before legalization. This
4973 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4974 // and enables future optimizations (e.g. min/max pattern matching on X86).
4975 if (N0.getOpcode() == ISD::SETCC) {
4976 EVT VT = N->getValueType(0);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004977
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004978 // Check if any splitting is required.
4979 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4980 TargetLowering::TypeSplitVector)
4981 return SDValue();
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004982
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004983 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +00004984 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4985 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4986 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004987
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004988 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4989 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004990
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004991 // Add the new VSELECT nodes to the work list in case they need to be split
4992 // again.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004993 AddToWorklist(Lo.getNode());
4994 AddToWorklist(Hi.getNode());
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004995
4996 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00004997 }
4998
Andrea Di Biagio23df4e42014-01-08 18:33:04 +00004999 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5000 if (ISD::isBuildVectorAllOnes(N0.getNode()))
5001 return N1;
5002 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5003 if (ISD::isBuildVectorAllZeros(N0.getNode()))
5004 return N2;
5005
Filipe Cabecinhas82111f12014-05-30 23:03:11 +00005006 // The ConvertSelectToConcatVector function is assuming both the above
5007 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5008 // and addressed.
5009 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5010 N2.getOpcode() == ISD::CONCAT_VECTORS &&
5011 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5012 SDValue CV = ConvertSelectToConcatVector(N, DAG);
5013 if (CV.getNode())
5014 return CV;
5015 }
5016
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00005017 return SDValue();
5018}
5019
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005020SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5021 SDValue N0 = N->getOperand(0);
5022 SDValue N1 = N->getOperand(1);
5023 SDValue N2 = N->getOperand(2);
5024 SDValue N3 = N->getOperand(3);
5025 SDValue N4 = N->getOperand(4);
Nate Begemanc760f802005-09-19 22:34:01 +00005026 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
Scott Michelcf0da6c2009-02-17 22:15:04 +00005027
Nate Begemanc760f802005-09-19 22:34:01 +00005028 // fold select_cc lhs, rhs, x, x, cc -> x
5029 if (N2 == N3)
5030 return N2;
Scott Michelcf0da6c2009-02-17 22:15:04 +00005031
Chris Lattner8b68dec2006-09-20 06:19:26 +00005032 // Determine if the condition we're dealing with is constant
Matt Arsenault758659232013-05-18 00:21:46 +00005033 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005034 N0, N1, CC, SDLoc(N), false);
Stephen Lin605207f2013-06-15 04:03:33 +00005035 if (SCC.getNode()) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005036 AddToWorklist(SCC.getNode());
Chris Lattner8b68dec2006-09-20 06:19:26 +00005037
Stephen Lin605207f2013-06-15 04:03:33 +00005038 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5039 if (!SCCC->isNullValue())
5040 return N2; // cond always true -> true val
5041 else
5042 return N3; // cond always false -> false val
5043 }
5044
5045 // Fold to a simpler select_cc
5046 if (SCC.getOpcode() == ISD::SETCC)
5047 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5048 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5049 SCC.getOperand(2));
Chris Lattner8b68dec2006-09-20 06:19:26 +00005050 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005051
Chris Lattner6c14c352005-10-18 06:04:22 +00005052 // If we can fold this based on the true/false value, do so.
5053 if (SimplifySelectOps(N, N2, N3))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005054 return SDValue(N, 0); // Don't revisit N.
Scott Michelcf0da6c2009-02-17 22:15:04 +00005055
Nate Begemanc760f802005-09-19 22:34:01 +00005056 // fold select_cc into other things, such as min/max/abs
Andrew Trickef9de2a2013-05-25 02:42:55 +00005057 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
Nate Begeman24a7eca2005-09-16 00:54:12 +00005058}
5059
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005060SDValue DAGCombiner::visitSETCC(SDNode *N) {
Nate Begeman24a7eca2005-09-16 00:54:12 +00005061 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
Dale Johannesenf1163e92009-02-03 00:47:48 +00005062 cast<CondCodeSDNode>(N->getOperand(2))->get(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005063 SDLoc(N));
Nate Begeman24a7eca2005-09-16 00:54:12 +00005064}
5065
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005066// tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
5067// dag node into a ConstantSDNode or a build_vector of constants.
5068// This function is called by the DAGCombiner when visiting sext/zext/aext
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00005069// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005070// Vector extends are not folded if operations are legal; this is to
5071// avoid introducing illegal build_vector dag nodes.
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005072static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5073 SelectionDAG &DAG, bool LegalTypes,
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005074 bool LegalOperations) {
5075 unsigned Opcode = N->getOpcode();
5076 SDValue N0 = N->getOperand(0);
5077 EVT VT = N->getValueType(0);
5078
5079 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5080 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
5081
5082 // fold (sext c1) -> c1
5083 // fold (zext c1) -> c1
5084 // fold (aext c1) -> c1
5085 if (isa<ConstantSDNode>(N0))
5086 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5087
5088 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5089 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5090 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005091 EVT SVT = VT.getScalarType();
5092 if (!(VT.isVector() &&
5093 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005094 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
Craig Topperc0196b12014-04-14 00:51:57 +00005095 return nullptr;
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00005096
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005097 // We can fold this node into a build_vector.
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005098 unsigned VTBits = SVT.getSizeInBits();
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005099 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5100 unsigned ShAmt = VTBits - EVTBits;
5101 SmallVector<SDValue, 8> Elts;
5102 unsigned NumElts = N0->getNumOperands();
5103 SDLoc DL(N);
5104
5105 for (unsigned i=0; i != NumElts; ++i) {
5106 SDValue Op = N0->getOperand(i);
5107 if (Op->getOpcode() == ISD::UNDEF) {
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005108 Elts.push_back(DAG.getUNDEF(SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005109 continue;
5110 }
5111
5112 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5113 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5114 if (Opcode == ISD::SIGN_EXTEND)
5115 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005116 SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005117 else
5118 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005119 SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005120 }
5121
Craig Topper48d114b2014-04-26 18:35:24 +00005122 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005123}
5124
Evan Chenge106e2f2007-10-29 19:58:20 +00005125// ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
Dan Gohman0e8d1992009-04-09 03:51:29 +00005126// "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
Evan Chenge106e2f2007-10-29 19:58:20 +00005127// transformation. Returns true if extension are possible and the above
Scott Michelcf0da6c2009-02-17 22:15:04 +00005128// mentioned transformation is profitable.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005129static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
Evan Chenge106e2f2007-10-29 19:58:20 +00005130 unsigned ExtOpc,
Craig Topperb94011f2013-07-14 04:42:23 +00005131 SmallVectorImpl<SDNode *> &ExtendNodes,
Dan Gohman619ef482009-01-15 19:20:50 +00005132 const TargetLowering &TLI) {
Evan Chenge106e2f2007-10-29 19:58:20 +00005133 bool HasCopyToRegUses = false;
5134 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
Gabor Greife12264b2008-08-30 19:29:20 +00005135 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5136 UE = N0.getNode()->use_end();
Evan Chenge106e2f2007-10-29 19:58:20 +00005137 UI != UE; ++UI) {
Dan Gohman91e5dcb2008-07-27 20:43:25 +00005138 SDNode *User = *UI;
Evan Chenge106e2f2007-10-29 19:58:20 +00005139 if (User == N)
5140 continue;
Dan Gohman0e8d1992009-04-09 03:51:29 +00005141 if (UI.getUse().getResNo() != N0.getResNo())
5142 continue;
Evan Chenge106e2f2007-10-29 19:58:20 +00005143 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
Dan Gohman0e8d1992009-04-09 03:51:29 +00005144 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
Evan Chenge106e2f2007-10-29 19:58:20 +00005145 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5146 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5147 // Sign bits will be lost after a zext.
5148 return false;
5149 bool Add = false;
5150 for (unsigned i = 0; i != 2; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005151 SDValue UseOp = User->getOperand(i);
Evan Chenge106e2f2007-10-29 19:58:20 +00005152 if (UseOp == N0)
5153 continue;
5154 if (!isa<ConstantSDNode>(UseOp))
5155 return false;
5156 Add = true;
5157 }
5158 if (Add)
5159 ExtendNodes.push_back(User);
Dan Gohman0e8d1992009-04-09 03:51:29 +00005160 continue;
Evan Chenge106e2f2007-10-29 19:58:20 +00005161 }
Dan Gohman0e8d1992009-04-09 03:51:29 +00005162 // If truncates aren't free and there are users we can't
5163 // extend, it isn't worthwhile.
5164 if (!isTruncFree)
5165 return false;
5166 // Remember if this value is live-out.
5167 if (User->getOpcode() == ISD::CopyToReg)
5168 HasCopyToRegUses = true;
Evan Chenge106e2f2007-10-29 19:58:20 +00005169 }
5170
5171 if (HasCopyToRegUses) {
5172 bool BothLiveOut = false;
5173 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5174 UI != UE; ++UI) {
Dan Gohman0e8d1992009-04-09 03:51:29 +00005175 SDUse &Use = UI.getUse();
5176 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5177 BothLiveOut = true;
5178 break;
Evan Chenge106e2f2007-10-29 19:58:20 +00005179 }
5180 }
5181 if (BothLiveOut)
5182 // Both unextended and extended values are live out. There had better be
Bob Wilsonf9b96c42010-11-28 06:51:19 +00005183 // a good reason for the transformation.
Evan Chenge106e2f2007-10-29 19:58:20 +00005184 return ExtendNodes.size();
5185 }
5186 return true;
5187}
5188
Craig Toppere0b71182013-07-13 07:43:40 +00005189void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
Andrew Trickef9de2a2013-05-25 02:42:55 +00005190 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005191 ISD::NodeType ExtType) {
5192 // Extend SetCC uses if necessary.
5193 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5194 SDNode *SetCC = SetCCs[i];
5195 SmallVector<SDValue, 4> Ops;
5196
5197 for (unsigned j = 0; j != 2; ++j) {
5198 SDValue SOp = SetCC->getOperand(j);
5199 if (SOp == Trunc)
5200 Ops.push_back(ExtLoad);
5201 else
5202 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5203 }
5204
5205 Ops.push_back(SetCC->getOperand(2));
Craig Topper48d114b2014-04-26 18:35:24 +00005206 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005207 }
5208}
5209
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005210SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5211 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005212 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00005213
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005214 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5215 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005216 return SDValue(Res, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005217
Nadav Rotem9450fcf2013-01-20 08:35:56 +00005218 // fold (sext (sext x)) -> (sext x)
5219 // fold (sext (aext x)) -> (sext x)
5220 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005221 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
Nadav Rotem9450fcf2013-01-20 08:35:56 +00005222 N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00005223
Chris Lattnerfce448f2007-02-26 03:13:59 +00005224 if (N0.getOpcode() == ISD::TRUNCATE) {
Dan Gohmanc1a4e212008-05-20 20:56:33 +00005225 // fold (sext (truncate (load x))) -> (sext (smaller load x))
5226 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00005227 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5228 if (NarrowLoad.getNode()) {
Dale Johannesenff384ad2010-05-25 17:50:03 +00005229 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5230 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005231 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesenff384ad2010-05-25 17:50:03 +00005232 // CombineTo deleted the truncate, if needed, but not what's under it.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005233 AddToWorklist(oye);
Dale Johannesenff384ad2010-05-25 17:50:03 +00005234 }
Dan Gohmanbe36f5c2009-04-27 02:00:55 +00005235 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00005236 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005237
Dan Gohmanc1a4e212008-05-20 20:56:33 +00005238 // See if the value being truncated is already sign extended. If so, just
5239 // eliminate the trunc/sext pair.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005240 SDValue Op = N0.getOperand(0);
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005241 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
5242 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
5243 unsigned DestBits = VT.getScalarType().getSizeInBits();
Dan Gohman309d3d52007-06-22 14:59:07 +00005244 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005245
Chris Lattnerfce448f2007-02-26 03:13:59 +00005246 if (OpBits == DestBits) {
5247 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
5248 // bits, it is already ready.
5249 if (NumSignBits > DestBits-MidBits)
5250 return Op;
5251 } else if (OpBits < DestBits) {
5252 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
5253 // bits, just sext from i32.
5254 if (NumSignBits > OpBits-MidBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005255 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
Chris Lattnerfce448f2007-02-26 03:13:59 +00005256 } else {
5257 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
5258 // bits, just truncate to i32.
5259 if (NumSignBits > OpBits-MidBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005260 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chris Lattnera31f0a62006-09-21 06:00:20 +00005261 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005262
Chris Lattnerfce448f2007-02-26 03:13:59 +00005263 // fold (sext (truncate x)) -> (sextinreg x).
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005264 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5265 N0.getValueType())) {
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005266 if (OpBits < DestBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005267 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005268 else if (OpBits > DestBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005269 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5270 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005271 DAG.getValueType(N0.getValueType()));
Chris Lattnerfce448f2007-02-26 03:13:59 +00005272 }
Chris Lattnera31f0a62006-09-21 06:00:20 +00005273 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005274
Evan Chengbce7c472005-12-14 02:19:23 +00005275 // fold (sext (load x)) -> (sext (truncate (sextload x)))
Nadav Rotem502f1b92011-02-24 21:01:34 +00005276 // None of the supported targets knows how to perform load and sign extend
Nadav Rotemb0091302011-02-27 07:40:43 +00005277 // on vectors in one instruction. We only perform this transformation on
5278 // scalars.
Nadav Rotem502f1b92011-02-24 21:01:34 +00005279 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005280 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005281 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005282 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
Evan Chenge106e2f2007-10-29 19:58:20 +00005283 bool DoXform = true;
5284 SmallVector<SDNode*, 4> SetCCs;
5285 if (!N0.hasOneUse())
5286 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5287 if (DoXform) {
5288 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005289 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Dan Gohman0e8d1992009-04-09 03:51:29 +00005290 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005291 LN0->getBasePtr(), N0.getValueType(),
5292 LN0->getMemOperand());
Evan Chenge106e2f2007-10-29 19:58:20 +00005293 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005294 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00005295 N0.getValueType(), ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005296 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005297 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005298 ISD::SIGN_EXTEND);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005299 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenge106e2f2007-10-29 19:58:20 +00005300 }
Nate Begeman8caf81d2005-10-12 20:40:40 +00005301 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005302
5303 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5304 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00005305 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5306 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005307 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00005308 EVT MemVT = LN0->getMemoryVT();
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005309 if ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00005310 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005311 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005312 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005313 LN0->getBasePtr(), MemVT,
5314 LN0->getMemOperand());
Jim Laskey26df19a2006-12-15 21:38:30 +00005315 CombineTo(N, ExtLoad);
Gabor Greife12264b2008-08-30 19:29:20 +00005316 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005317 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00005318 N0.getValueType(), ExtLoad),
Jim Laskey26df19a2006-12-15 21:38:30 +00005319 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005320 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Jim Laskey26df19a2006-12-15 21:38:30 +00005321 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005322 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005323
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005324 // fold (sext (and/or/xor (load x), cst)) ->
5325 // (and/or/xor (sextload x), (sext cst))
5326 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5327 N0.getOpcode() == ISD::XOR) &&
5328 isa<LoadSDNode>(N0.getOperand(0)) &&
5329 N0.getOperand(1).getOpcode() == ISD::Constant &&
5330 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
5331 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5332 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005333 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005334 bool DoXform = true;
5335 SmallVector<SDNode*, 4> SetCCs;
5336 if (!N0.hasOneUse())
5337 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5338 SetCCs, TLI);
5339 if (DoXform) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005340 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005341 LN0->getChain(), LN0->getBasePtr(),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005342 LN0->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005343 LN0->getMemOperand());
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005344 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5345 Mask = Mask.sext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005346 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005347 ExtLoad, DAG.getConstant(Mask, VT));
5348 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00005349 SDLoc(N0.getOperand(0)),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005350 N0.getOperand(0).getValueType(), ExtLoad);
5351 CombineTo(N, And);
5352 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005353 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005354 ISD::SIGN_EXTEND);
5355 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5356 }
5357 }
5358 }
5359
Chris Lattner65786b02007-04-11 05:32:27 +00005360 if (N0.getOpcode() == ISD::SETCC) {
Daniel Sanderscbd44c52014-07-10 10:18:12 +00005361 EVT N0VT = N0.getOperand(0).getValueType();
Chris Lattner4ac60732009-07-08 00:31:33 +00005362 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
Dan Gohmane82c25e2010-04-30 17:19:19 +00005363 // Only do this before legalize for now.
Owen Anderson2d4cca32013-04-23 18:09:28 +00005364 if (VT.isVector() && !LegalOperations &&
Daniel Sanderscbd44c52014-07-10 10:18:12 +00005365 TLI.getBooleanContents(N0VT) ==
5366 TargetLowering::ZeroOrNegativeOneBooleanContent) {
Nadav Rotem9d376b62012-04-11 08:26:11 +00005367 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5368 // of the same size as the compared operands. Only optimize sext(setcc())
5369 // if this is the case.
Matt Arsenault758659232013-05-18 00:21:46 +00005370 EVT SVT = getSetCCResultType(N0VT);
Nadav Rotem9d376b62012-04-11 08:26:11 +00005371
5372 // We know that the # elements of the results is the same as the
5373 // # elements of the compare (and the # elements of the compare result
5374 // for that matter). Check to see that they are the same size. If so,
5375 // we know that the element size of the sext'd result matches the
5376 // element size of the compare operands.
5377 if (VT.getSizeInBits() == SVT.getSizeInBits())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005378 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005379 N0.getOperand(1),
5380 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Matt Arsenault04126232013-05-17 21:43:43 +00005381
Dan Gohmane82c25e2010-04-30 17:19:19 +00005382 // If the desired elements are smaller or larger than the source
5383 // elements we can use a matching integer vector type and then
5384 // truncate/sign extend
Matt Arsenault04126232013-05-17 21:43:43 +00005385 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
Craig Topper5f9791f2012-09-29 07:18:53 +00005386 if (SVT == MatchingVectorType) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005387 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
Craig Topper5f9791f2012-09-29 07:18:53 +00005388 N0.getOperand(0), N0.getOperand(1),
5389 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005390 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
Dan Gohmane82c25e2010-04-30 17:19:19 +00005391 }
Chris Lattner4ac60732009-07-08 00:31:33 +00005392 }
Dan Gohmane82c25e2010-04-30 17:19:19 +00005393
Matt Arsenault5f2a92a2014-01-27 21:41:54 +00005394 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
Dan Gohman5544b0c2010-04-24 01:17:30 +00005395 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
Dan Gohman5758e1e2009-08-06 09:18:59 +00005396 SDValue NegOne =
Dan Gohman5544b0c2010-04-24 01:17:30 +00005397 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005398 SDValue SCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005399 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Dan Gohman5758e1e2009-08-06 09:18:59 +00005400 NegOne, DAG.getConstant(0, VT),
Chris Lattnera083ffc2007-04-11 06:50:51 +00005401 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005402 if (SCC.getNode()) return SCC;
Matt Arsenault5f2a92a2014-01-27 21:41:54 +00005403
5404 if (!VT.isVector()) {
5405 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5406 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5407 SDLoc DL(N);
5408 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
Hal Finkel98085952014-10-06 20:19:47 +00005409 SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
Matt Arsenault5f2a92a2014-01-27 21:41:54 +00005410 N0.getOperand(0), N0.getOperand(1), CC);
Hal Finkel98085952014-10-06 20:19:47 +00005411 return DAG.getSelect(DL, VT, SetCC,
Matt Arsenault5f2a92a2014-01-27 21:41:54 +00005412 NegOne, DAG.getConstant(0, VT));
Matt Arsenault5f2a92a2014-01-27 21:41:54 +00005413 }
Matt Arsenaultd2f03322013-06-14 22:04:37 +00005414 }
Wesley Peck527da1b2010-11-23 03:31:01 +00005415 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005416
Dan Gohman3eb10f72008-04-28 16:58:24 +00005417 // fold (sext x) -> (zext x) if the sign bit is known zero.
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005418 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
Dan Gohmanc968c1f2008-04-28 18:47:17 +00005419 DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005420 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005421
Evan Chengf1005572010-04-28 07:10:39 +00005422 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00005423}
5424
Rafael Espindola8f62b322012-04-09 16:06:03 +00005425// isTruncateOf - If N is a truncate of some other value, return true, record
5426// the value being truncated in Op and which of Op's bits are zero in KnownZero.
5427// This function computes KnownZero to avoid a duplicated call to
Jay Foada0653a32014-05-14 21:14:37 +00005428// computeKnownBits in the caller.
Rafael Espindola8f62b322012-04-09 16:06:03 +00005429static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5430 APInt &KnownZero) {
5431 APInt KnownOne;
5432 if (N->getOpcode() == ISD::TRUNCATE) {
5433 Op = N->getOperand(0);
Jay Foada0653a32014-05-14 21:14:37 +00005434 DAG.computeKnownBits(Op, KnownZero, KnownOne);
Rafael Espindola8f62b322012-04-09 16:06:03 +00005435 return true;
5436 }
5437
5438 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5439 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5440 return false;
5441
5442 SDValue Op0 = N->getOperand(0);
5443 SDValue Op1 = N->getOperand(1);
5444 assert(Op0.getValueType() == Op1.getValueType());
5445
5446 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5447 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
Rafael Espindola1d9672b2012-04-10 00:16:22 +00005448 if (COp0 && COp0->isNullValue())
Rafael Espindola8f62b322012-04-09 16:06:03 +00005449 Op = Op1;
Rafael Espindola1d9672b2012-04-10 00:16:22 +00005450 else if (COp1 && COp1->isNullValue())
Rafael Espindola8f62b322012-04-09 16:06:03 +00005451 Op = Op0;
5452 else
5453 return false;
5454
Jay Foada0653a32014-05-14 21:14:37 +00005455 DAG.computeKnownBits(Op, KnownZero, KnownOne);
Rafael Espindola8f62b322012-04-09 16:06:03 +00005456
5457 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5458 return false;
5459
5460 return true;
5461}
5462
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005463SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5464 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005465 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00005466
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005467 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5468 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005469 return SDValue(Res, 0);
5470
Nate Begeman21158fc2005-09-01 00:19:25 +00005471 // fold (zext (zext x)) -> (zext x)
Chris Lattner7e7bcf32006-05-06 23:06:26 +00005472 // fold (zext (aext x)) -> (zext x)
5473 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005474 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005475 N0.getOperand(0));
Chris Lattnera31f0a62006-09-21 06:00:20 +00005476
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005477 // fold (zext (truncate x)) -> (zext x) or
5478 // (zext (truncate x)) -> (truncate x)
5479 // This is valid when the truncated bits of x are already zero.
5480 // FIXME: We should extend this to work for vectors too.
Rafael Espindola8f62b322012-04-09 16:06:03 +00005481 SDValue Op;
5482 APInt KnownZero;
5483 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5484 APInt TruncatedBits =
5485 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5486 APInt(Op.getValueSizeInBits(), 0) :
5487 APInt::getBitsSet(Op.getValueSizeInBits(),
5488 N0.getValueSizeInBits(),
5489 std::min(Op.getValueSizeInBits(),
5490 VT.getSizeInBits()));
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00005491 if (TruncatedBits == (KnownZero & TruncatedBits)) {
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005492 if (VT.bitsGT(Op.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005493 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005494 if (VT.bitsLT(Op.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005495 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005496
5497 return Op;
5498 }
5499 }
5500
Evan Cheng464dc9b2007-03-22 01:54:19 +00005501 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5502 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
Dale Johannesen4bbd2ee2007-03-30 21:38:07 +00005503 if (N0.getOpcode() == ISD::TRUNCATE) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005504 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5505 if (NarrowLoad.getNode()) {
Dale Johannesenff384ad2010-05-25 17:50:03 +00005506 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5507 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005508 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesenff384ad2010-05-25 17:50:03 +00005509 // CombineTo deleted the truncate, if needed, but not what's under it.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005510 AddToWorklist(oye);
Dale Johannesenff384ad2010-05-25 17:50:03 +00005511 }
Eli Friedman55b0acd2011-04-16 23:25:34 +00005512 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00005513 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005514 }
5515
Chris Lattnera31f0a62006-09-21 06:00:20 +00005516 // fold (zext (truncate x)) -> (and x, mask)
5517 if (N0.getOpcode() == ISD::TRUNCATE &&
Dan Gohman600f62b2010-06-24 14:30:44 +00005518 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
Dan Gohman68fb0042010-11-03 01:47:46 +00005519
5520 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5521 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5522 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5523 if (NarrowLoad.getNode()) {
5524 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5525 if (NarrowLoad.getNode() != N0.getNode()) {
5526 CombineTo(N0.getNode(), NarrowLoad);
5527 // CombineTo deleted the truncate, if needed, but not what's under it.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005528 AddToWorklist(oye);
Dan Gohman68fb0042010-11-03 01:47:46 +00005529 }
5530 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5531 }
5532
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005533 SDValue Op = N0.getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00005534 if (Op.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005535 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005536 AddToWorklist(Op.getNode());
Duncan Sands11dd4242008-06-08 20:54:56 +00005537 } else if (Op.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005538 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005539 AddToWorklist(Op.getNode());
Chris Lattnera31f0a62006-09-21 06:00:20 +00005540 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00005541 return DAG.getZeroExtendInReg(Op, SDLoc(N),
Dan Gohman1d459e42009-12-11 21:31:27 +00005542 N0.getValueType().getScalarType());
Chris Lattnera31f0a62006-09-21 06:00:20 +00005543 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005544
Dan Gohmanad3e5492009-04-08 00:15:30 +00005545 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5546 // if either of the casts is not free.
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00005547 if (N0.getOpcode() == ISD::AND &&
5548 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
Dan Gohmanad3e5492009-04-08 00:15:30 +00005549 N0.getOperand(1).getOpcode() == ISD::Constant &&
5550 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5551 N0.getValueType()) ||
5552 !TLI.isZExtFree(N0.getValueType(), VT))) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005553 SDValue X = N0.getOperand(0).getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00005554 if (X.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005555 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
Duncan Sands11dd4242008-06-08 20:54:56 +00005556 } else if (X.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005557 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00005558 }
Dan Gohmane1c4f992008-03-03 23:51:38 +00005559 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00005560 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005561 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005562 X, DAG.getConstant(Mask, VT));
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00005563 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005564
Evan Chengbce7c472005-12-14 02:19:23 +00005565 // fold (zext (load x)) -> (zext (truncate (zextload x)))
Nadav Rotem25f2ac92011-02-20 12:37:50 +00005566 // None of the supported targets knows how to perform load and vector_zext
Nadav Rotemb0091302011-02-27 07:40:43 +00005567 // on vectors in one instruction. We only perform this transformation on
5568 // scalars.
Nadav Rotem25f2ac92011-02-20 12:37:50 +00005569 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005570 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005571 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00005572 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
Evan Chenge106e2f2007-10-29 19:58:20 +00005573 bool DoXform = true;
5574 SmallVector<SDNode*, 4> SetCCs;
5575 if (!N0.hasOneUse())
5576 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5577 if (DoXform) {
5578 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005579 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005580 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005581 LN0->getBasePtr(), N0.getValueType(),
5582 LN0->getMemOperand());
Evan Chenge106e2f2007-10-29 19:58:20 +00005583 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005584 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00005585 N0.getValueType(), ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005586 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Bill Wendlingc4093182009-01-30 22:23:15 +00005587
Andrew Trickef9de2a2013-05-25 02:42:55 +00005588 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005589 ISD::ZERO_EXTEND);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005590 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenge106e2f2007-10-29 19:58:20 +00005591 }
Evan Chengbce7c472005-12-14 02:19:23 +00005592 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005593
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005594 // fold (zext (and/or/xor (load x), cst)) ->
5595 // (and/or/xor (zextload x), (zext cst))
5596 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5597 N0.getOpcode() == ISD::XOR) &&
5598 isa<LoadSDNode>(N0.getOperand(0)) &&
5599 N0.getOperand(1).getOpcode() == ISD::Constant &&
5600 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5601 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5602 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005603 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005604 bool DoXform = true;
5605 SmallVector<SDNode*, 4> SetCCs;
5606 if (!N0.hasOneUse())
5607 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5608 SetCCs, TLI);
5609 if (DoXform) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005610 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005611 LN0->getChain(), LN0->getBasePtr(),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005612 LN0->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005613 LN0->getMemOperand());
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005614 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5615 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005616 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005617 ExtLoad, DAG.getConstant(Mask, VT));
5618 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00005619 SDLoc(N0.getOperand(0)),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005620 N0.getOperand(0).getValueType(), ExtLoad);
5621 CombineTo(N, And);
5622 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005623 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005624 ISD::ZERO_EXTEND);
5625 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5626 }
5627 }
5628 }
5629
Chris Lattner7dac1082005-12-14 19:05:06 +00005630 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5631 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00005632 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5633 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005634 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00005635 EVT MemVT = LN0->getMemoryVT();
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005636 if ((!LegalOperations && !LN0->isVolatile()) ||
Dan Gohman08c0a952009-09-23 21:02:20 +00005637 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005638 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005639 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005640 LN0->getBasePtr(), MemVT,
5641 LN0->getMemOperand());
Duncan Sands8651e9c2008-06-13 19:07:40 +00005642 CombineTo(N, ExtLoad);
Gabor Greife12264b2008-08-30 19:29:20 +00005643 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005644 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
Bill Wendlingc4093182009-01-30 22:23:15 +00005645 ExtLoad),
Duncan Sands8651e9c2008-06-13 19:07:40 +00005646 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005647 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Duncan Sands8651e9c2008-06-13 19:07:40 +00005648 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005649 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005650
Chris Lattner65786b02007-04-11 05:32:27 +00005651 if (N0.getOpcode() == ISD::SETCC) {
Kevin Qinede9ce12013-12-30 02:05:13 +00005652 if (!LegalOperations && VT.isVector() &&
5653 N0.getValueType().getVectorElementType() == MVT::i1) {
Elena Demikhovsky9d56f1e2014-01-22 12:26:19 +00005654 EVT N0VT = N0.getOperand(0).getValueType();
5655 if (getSetCCResultType(N0VT) == N0.getValueType())
5656 return SDValue();
5657
Evan Chengabd0ad52010-05-19 01:08:17 +00005658 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5659 // Only do this before legalize for now.
Evan Chengabd0ad52010-05-19 01:08:17 +00005660 EVT EltVT = VT.getVectorElementType();
5661 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5662 DAG.getConstant(1, EltVT));
Dan Gohman4298df62011-05-17 22:20:36 +00005663 if (VT.getSizeInBits() == N0VT.getSizeInBits())
Evan Chengabd0ad52010-05-19 01:08:17 +00005664 // We know that the # elements of the results is the same as the
5665 // # elements of the compare (and the # elements of the compare result
5666 // for that matter). Check to see that they are the same size. If so,
5667 // we know that the element size of the sext'd result matches the
5668 // element size of the compare operands.
Andrew Trickef9de2a2013-05-25 02:42:55 +00005669 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5670 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Evan Chengabd0ad52010-05-19 01:08:17 +00005671 N0.getOperand(1),
5672 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005673 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
Craig Topper48d114b2014-04-26 18:35:24 +00005674 OneOps));
Dan Gohman4298df62011-05-17 22:20:36 +00005675
5676 // If the desired elements are smaller or larger than the source
5677 // elements we can use a matching integer vector type and then
5678 // truncate/sign extend
5679 EVT MatchingElementType =
5680 EVT::getIntegerVT(*DAG.getContext(),
5681 N0VT.getScalarType().getSizeInBits());
5682 EVT MatchingVectorType =
5683 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5684 N0VT.getVectorNumElements());
5685 SDValue VsetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005686 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
Dan Gohman4298df62011-05-17 22:20:36 +00005687 N0.getOperand(1),
5688 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005689 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5690 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
Craig Topper48d114b2014-04-26 18:35:24 +00005691 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
Evan Chengabd0ad52010-05-19 01:08:17 +00005692 }
5693
5694 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
Scott Michelcf0da6c2009-02-17 22:15:04 +00005695 SDValue SCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005696 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Chris Lattner65786b02007-04-11 05:32:27 +00005697 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
Chris Lattnera083ffc2007-04-11 06:50:51 +00005698 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005699 if (SCC.getNode()) return SCC;
Chris Lattner65786b02007-04-11 05:32:27 +00005700 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005701
Evan Cheng852c4862009-12-15 03:00:32 +00005702 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
Evan Chengca7c6902009-12-15 00:41:36 +00005703 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
Evan Cheng852c4862009-12-15 03:00:32 +00005704 isa<ConstantSDNode>(N0.getOperand(1)) &&
Evan Chengca7c6902009-12-15 00:41:36 +00005705 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5706 N0.hasOneUse()) {
Chris Lattnere95d1952011-02-13 19:09:16 +00005707 SDValue ShAmt = N0.getOperand(1);
5708 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
Evan Cheng852c4862009-12-15 03:00:32 +00005709 if (N0.getOpcode() == ISD::SHL) {
Chris Lattnere95d1952011-02-13 19:09:16 +00005710 SDValue InnerZExt = N0.getOperand(0);
Evan Cheng852c4862009-12-15 03:00:32 +00005711 // If the original shl may be shifting out bits, do not perform this
5712 // transformation.
Chris Lattnere95d1952011-02-13 19:09:16 +00005713 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5714 InnerZExt.getOperand(0).getValueType().getSizeInBits();
5715 if (ShAmtVal > KnownZeroBits)
Evan Cheng852c4862009-12-15 03:00:32 +00005716 return SDValue();
5717 }
Chris Lattnere95d1952011-02-13 19:09:16 +00005718
Andrew Trickef9de2a2013-05-25 02:42:55 +00005719 SDLoc DL(N);
Owen Andersonb2c80da2011-02-25 21:41:48 +00005720
5721 // Ensure that the shift amount is wide enough for the shifted value.
Chris Lattnere95d1952011-02-13 19:09:16 +00005722 if (VT.getSizeInBits() >= 256)
5723 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
Owen Andersonb2c80da2011-02-25 21:41:48 +00005724
Chris Lattnere95d1952011-02-13 19:09:16 +00005725 return DAG.getNode(N0.getOpcode(), DL, VT,
5726 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5727 ShAmt);
Evan Chengca7c6902009-12-15 00:41:36 +00005728 }
5729
Evan Chengf1005572010-04-28 07:10:39 +00005730 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00005731}
5732
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005733SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5734 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005735 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005736
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005737 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5738 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005739 return SDValue(Res, 0);
5740
Chris Lattner812646a2006-05-05 05:58:59 +00005741 // fold (aext (aext x)) -> (aext x)
5742 // fold (aext (zext x)) -> (zext x)
5743 // fold (aext (sext x)) -> (sext x)
5744 if (N0.getOpcode() == ISD::ANY_EXTEND ||
5745 N0.getOpcode() == ISD::ZERO_EXTEND ||
5746 N0.getOpcode() == ISD::SIGN_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005747 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00005748
Evan Cheng464dc9b2007-03-22 01:54:19 +00005749 // fold (aext (truncate (load x))) -> (aext (smaller load x))
5750 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5751 if (N0.getOpcode() == ISD::TRUNCATE) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005752 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5753 if (NarrowLoad.getNode()) {
Dale Johannesen60fe2cd2010-05-25 18:47:23 +00005754 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5755 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005756 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesen60fe2cd2010-05-25 18:47:23 +00005757 // CombineTo deleted the truncate, if needed, but not what's under it.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005758 AddToWorklist(oye);
Dale Johannesen60fe2cd2010-05-25 18:47:23 +00005759 }
Eli Friedman55b0acd2011-04-16 23:25:34 +00005760 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00005761 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005762 }
5763
Chris Lattner8746e2c2006-09-20 06:29:17 +00005764 // fold (aext (truncate x))
5765 if (N0.getOpcode() == ISD::TRUNCATE) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005766 SDValue TruncOp = N0.getOperand(0);
Chris Lattner8746e2c2006-09-20 06:29:17 +00005767 if (TruncOp.getValueType() == VT)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005768 return TruncOp; // x iff x size == zext size.
Duncan Sands11dd4242008-06-08 20:54:56 +00005769 if (TruncOp.getValueType().bitsGT(VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005770 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5771 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
Chris Lattner8746e2c2006-09-20 06:29:17 +00005772 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005773
Dan Gohmanad3e5492009-04-08 00:15:30 +00005774 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5775 // if the trunc is not free.
Chris Lattner082db3f2006-09-21 06:40:43 +00005776 if (N0.getOpcode() == ISD::AND &&
5777 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
Dan Gohmanad3e5492009-04-08 00:15:30 +00005778 N0.getOperand(1).getOpcode() == ISD::Constant &&
5779 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5780 N0.getValueType())) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005781 SDValue X = N0.getOperand(0).getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00005782 if (X.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005783 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
Duncan Sands11dd4242008-06-08 20:54:56 +00005784 } else if (X.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005785 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
Chris Lattner082db3f2006-09-21 06:40:43 +00005786 }
Dan Gohmane1c4f992008-03-03 23:51:38 +00005787 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00005788 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005789 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendling9b3dc8d2009-01-30 22:27:33 +00005790 X, DAG.getConstant(Mask, VT));
Chris Lattner082db3f2006-09-21 06:40:43 +00005791 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005792
Chris Lattner812646a2006-05-05 05:58:59 +00005793 // fold (aext (load x)) -> (aext (truncate (extload x)))
Nadav Rotem502f1b92011-02-24 21:01:34 +00005794 // None of the supported targets knows how to perform load and any_ext
Nadav Rotemb0091302011-02-27 07:40:43 +00005795 // on vectors in one instruction. We only perform this transformation on
5796 // scalars.
Nadav Rotem502f1b92011-02-24 21:01:34 +00005797 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005798 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Tim Northover7f3e11e2014-07-16 15:37:24 +00005799 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
Dan Gohman0e8d1992009-04-09 03:51:29 +00005800 bool DoXform = true;
5801 SmallVector<SDNode*, 4> SetCCs;
5802 if (!N0.hasOneUse())
5803 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5804 if (DoXform) {
5805 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005806 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
Dan Gohman0e8d1992009-04-09 03:51:29 +00005807 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005808 LN0->getBasePtr(), N0.getValueType(),
5809 LN0->getMemOperand());
Dan Gohman0e8d1992009-04-09 03:51:29 +00005810 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005811 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Dan Gohman0e8d1992009-04-09 03:51:29 +00005812 N0.getValueType(), ExtLoad);
5813 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005814 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005815 ISD::ANY_EXTEND);
Dan Gohman0e8d1992009-04-09 03:51:29 +00005816 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5817 }
Chris Lattner812646a2006-05-05 05:58:59 +00005818 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005819
Chris Lattner812646a2006-05-05 05:58:59 +00005820 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5821 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5822 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
Evan Cheng8a1d09d2007-03-07 08:07:03 +00005823 if (N0.getOpcode() == ISD::LOAD &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00005824 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Chenge71fe34d2006-10-09 20:57:25 +00005825 N0.hasOneUse()) {
5826 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Matt Arsenaultaaf96232014-04-08 21:40:37 +00005827 ISD::LoadExtType ExtType = LN0->getExtensionType();
Dan Gohman08c0a952009-09-23 21:02:20 +00005828 EVT MemVT = LN0->getMemoryVT();
Matt Arsenaultaaf96232014-04-08 21:40:37 +00005829 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5830 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5831 VT, LN0->getChain(), LN0->getBasePtr(),
5832 MemVT, LN0->getMemOperand());
5833 CombineTo(N, ExtLoad);
5834 CombineTo(N0.getNode(),
5835 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5836 N0.getValueType(), ExtLoad),
5837 ExtLoad.getValue(1));
5838 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5839 }
Chris Lattner812646a2006-05-05 05:58:59 +00005840 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005841
Chris Lattner65786b02007-04-11 05:32:27 +00005842 if (N0.getOpcode() == ISD::SETCC) {
Hao Liuc636d152014-04-22 09:57:06 +00005843 // For vectors:
5844 // aext(setcc) -> vsetcc
5845 // aext(setcc) -> truncate(vsetcc)
5846 // aext(setcc) -> aext(vsetcc)
Evan Chengabd0ad52010-05-19 01:08:17 +00005847 // Only do this before legalize for now.
5848 if (VT.isVector() && !LegalOperations) {
5849 EVT N0VT = N0.getOperand(0).getValueType();
5850 // We know that the # elements of the results is the same as the
5851 // # elements of the compare (and the # elements of the compare result
5852 // for that matter). Check to see that they are the same size. If so,
5853 // we know that the element size of the sext'd result matches the
5854 // element size of the compare operands.
5855 if (VT.getSizeInBits() == N0VT.getSizeInBits())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005856 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005857 N0.getOperand(1),
5858 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Evan Chengabd0ad52010-05-19 01:08:17 +00005859 // If the desired elements are smaller or larger than the source
5860 // elements we can use a matching integer vector type and then
Hao Liuc636d152014-04-22 09:57:06 +00005861 // truncate/any extend
Evan Chengabd0ad52010-05-19 01:08:17 +00005862 else {
Hao Liuc636d152014-04-22 09:57:06 +00005863 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005864 SDValue VsetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005865 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005866 N0.getOperand(1),
5867 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Hao Liuc636d152014-04-22 09:57:06 +00005868 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
Evan Chengabd0ad52010-05-19 01:08:17 +00005869 }
5870 }
5871
5872 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
Scott Michelcf0da6c2009-02-17 22:15:04 +00005873 SDValue SCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005874 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Chris Lattnera083ffc2007-04-11 06:50:51 +00005875 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
Chris Lattner18e4ac42007-04-11 16:51:53 +00005876 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005877 if (SCC.getNode())
Chris Lattnerc5f85d32007-04-11 06:43:25 +00005878 return SCC;
Chris Lattner65786b02007-04-11 05:32:27 +00005879 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005880
Evan Chengf1005572010-04-28 07:10:39 +00005881 return SDValue();
Chris Lattner812646a2006-05-05 05:58:59 +00005882}
5883
Sanjay Patel50cbfc52014-08-28 16:29:51 +00005884/// See if the specified operand can be simplified with the knowledge that only
5885/// the bits specified by Mask are used. If so, return the simpler operand,
5886/// otherwise return a null SDValue.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005887SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
Chris Lattner5e6fe052007-10-13 06:35:54 +00005888 switch (V.getOpcode()) {
5889 default: break;
Lang Hamesb85fcd02011-11-08 18:56:23 +00005890 case ISD::Constant: {
5891 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
Craig Topperc0196b12014-04-14 00:51:57 +00005892 assert(CV && "Const value should be ConstSDNode.");
Lang Hamesb85fcd02011-11-08 18:56:23 +00005893 const APInt &CVal = CV->getAPIntValue();
5894 APInt NewVal = CVal & Mask;
Stephen Lin8e8424e2013-07-09 00:44:49 +00005895 if (NewVal != CVal)
Lang Hamesb85fcd02011-11-08 18:56:23 +00005896 return DAG.getConstant(NewVal, V.getValueType());
Lang Hamesb85fcd02011-11-08 18:56:23 +00005897 break;
5898 }
Chris Lattner5e6fe052007-10-13 06:35:54 +00005899 case ISD::OR:
5900 case ISD::XOR:
5901 // If the LHS or RHS don't contribute bits to the or, drop them.
5902 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5903 return V.getOperand(1);
5904 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5905 return V.getOperand(0);
5906 break;
Chris Lattnerf47e3062007-10-13 06:58:48 +00005907 case ISD::SRL:
5908 // Only look at single-use SRLs.
Gabor Greiff304a7a2008-08-28 21:40:38 +00005909 if (!V.getNode()->hasOneUse())
Chris Lattnerf47e3062007-10-13 06:58:48 +00005910 break;
5911 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5912 // See if we can recursively simplify the LHS.
Dan Gohmaneffb8942008-09-12 16:56:44 +00005913 unsigned Amt = RHSC->getZExtValue();
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005914
Dan Gohmanb9fa1d22009-01-03 19:22:06 +00005915 // Watch out for shift count overflow though.
5916 if (Amt >= Mask.getBitWidth()) break;
Dan Gohman1f372ed2008-02-25 21:11:39 +00005917 APInt NewMask = Mask << Amt;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005918 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
Bill Wendling7bfa43b2009-01-30 22:33:24 +00005919 if (SimplifyLHS.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005920 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
Chris Lattnerf47e3062007-10-13 06:58:48 +00005921 SimplifyLHS, V.getOperand(1));
Chris Lattnerf47e3062007-10-13 06:58:48 +00005922 }
Chris Lattner5e6fe052007-10-13 06:35:54 +00005923 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005924 return SDValue();
Chris Lattner5e6fe052007-10-13 06:35:54 +00005925}
5926
Sanjay Patel50cbfc52014-08-28 16:29:51 +00005927/// If the result of a wider load is shifted to right of N bits and then
5928/// truncated to a narrower type and where N is a multiple of number of bits of
5929/// the narrower type, transform it to a narrower load from address + N / num of
5930/// bits of new type. If the result is to be extended, also fold the extension
5931/// to form a extending load.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005932SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
Evan Cheng464dc9b2007-03-22 01:54:19 +00005933 unsigned Opc = N->getOpcode();
Dan Gohman600f62b2010-06-24 14:30:44 +00005934
Evan Cheng464dc9b2007-03-22 01:54:19 +00005935 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005936 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005937 EVT VT = N->getValueType(0);
5938 EVT ExtVT = VT;
Evan Cheng464dc9b2007-03-22 01:54:19 +00005939
Dan Gohman550c9af2008-08-14 20:04:46 +00005940 // This transformation isn't valid for vector loads.
5941 if (VT.isVector())
5942 return SDValue();
5943
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005944 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
Evan Chenga883b582007-03-23 22:13:36 +00005945 // extended to VT.
Evan Cheng464dc9b2007-03-22 01:54:19 +00005946 if (Opc == ISD::SIGN_EXTEND_INREG) {
5947 ExtType = ISD::SEXTLOAD;
Owen Anderson53aa7a92009-08-10 22:56:29 +00005948 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
Dan Gohman600f62b2010-06-24 14:30:44 +00005949 } else if (Opc == ISD::SRL) {
Chris Lattner2a7ff992010-12-21 18:05:22 +00005950 // Another special-case: SRL is basically zero-extending a narrower value.
Dan Gohman600f62b2010-06-24 14:30:44 +00005951 ExtType = ISD::ZEXTLOAD;
5952 N0 = SDValue(N, 0);
5953 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5954 if (!N01) return SDValue();
5955 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5956 VT.getSizeInBits() - N01->getZExtValue());
Evan Cheng464dc9b2007-03-22 01:54:19 +00005957 }
Richard Osborne272e0842011-01-31 17:41:44 +00005958 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5959 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005960
Owen Anderson53aa7a92009-08-10 22:56:29 +00005961 unsigned EVTBits = ExtVT.getSizeInBits();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005962
Chris Lattner9a499e92010-12-22 08:01:44 +00005963 // Do not generate loads of non-round integer types since these can
5964 // be expensive (and would be wrong if the type is not byte sized).
5965 if (!ExtVT.isRound())
5966 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005967
Evan Cheng464dc9b2007-03-22 01:54:19 +00005968 unsigned ShAmt = 0;
Chris Lattner9a499e92010-12-22 08:01:44 +00005969 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
Evan Cheng464dc9b2007-03-22 01:54:19 +00005970 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00005971 ShAmt = N01->getZExtValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005972 // Is the shift amount a multiple of size of VT?
5973 if ((ShAmt & (EVTBits-1)) == 0) {
5974 N0 = N0.getOperand(0);
Eli Friedman1e008c12009-08-19 08:46:10 +00005975 // Is the load width a multiple of size of VT?
5976 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005977 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005978 }
Wesley Peck527da1b2010-11-23 03:31:01 +00005979
Chris Lattnercafc1e62010-12-22 08:02:57 +00005980 // At this point, we must have a load or else we can't do the transform.
5981 if (!isa<LoadSDNode>(N0)) return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00005982
Chandler Carruthb27041c2012-12-11 00:36:57 +00005983 // Because a SRL must be assumed to *need* to zero-extend the high bits
5984 // (as opposed to anyext the high bits), we can't combine the zextload
5985 // lowering of SRL and an sextload.
5986 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5987 return SDValue();
5988
Chris Lattnera2050552010-10-01 05:36:09 +00005989 // If the shift amount is larger than the input type then we're not
5990 // accessing any of the loaded bytes. If the load was a zextload/extload
5991 // then the result of the shift+trunc is zero/undef (handled elsewhere).
Chris Lattnercafc1e62010-12-22 08:02:57 +00005992 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
Chris Lattnera2050552010-10-01 05:36:09 +00005993 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00005994 }
5995 }
5996
Dan Gohman68fb0042010-11-03 01:47:46 +00005997 // If the load is shifted left (and the result isn't shifted back right),
5998 // we can fold the truncate through the shift.
5999 unsigned ShLeftAmt = 0;
6000 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
Chris Lattner222374d2010-12-22 07:36:50 +00006001 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
Dan Gohman68fb0042010-11-03 01:47:46 +00006002 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6003 ShLeftAmt = N01->getZExtValue();
6004 N0 = N0.getOperand(0);
6005 }
6006 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00006007
Chris Lattner222374d2010-12-22 07:36:50 +00006008 // If we haven't found a load, we can't narrow it. Don't transform one with
6009 // multiple uses, this would require adding a new load.
Bill Schmidtd006c692013-01-14 22:04:38 +00006010 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6011 return SDValue();
6012
6013 // Don't change the width of a volatile load.
6014 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6015 if (LN0->isVolatile())
Chris Lattner222374d2010-12-22 07:36:50 +00006016 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00006017
Chris Lattner9a499e92010-12-22 08:01:44 +00006018 // Verify that we are actually reducing a load width here.
Bill Schmidtd006c692013-01-14 22:04:38 +00006019 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
Chris Lattner222374d2010-12-22 07:36:50 +00006020 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00006021
Bill Schmidtd006c692013-01-14 22:04:38 +00006022 // For the transform to be legal, the load must produce only two values
6023 // (the value loaded and the chain). Don't transform a pre-increment
Stephen Lincfe7f352013-07-08 00:37:03 +00006024 // load, for example, which produces an extra value. Otherwise the
Bill Schmidtd006c692013-01-14 22:04:38 +00006025 // transformation is not equivalent, and the downstream logic to replace
6026 // uses gets things wrong.
6027 if (LN0->getNumValues() > 2)
6028 return SDValue();
6029
Benjamin Kramerc7332b22013-07-06 14:05:09 +00006030 // If the load that we're shrinking is an extload and we're not just
6031 // discarding the extension we can't simply shrink the load. Bail.
6032 // TODO: It would be possible to merge the extensions in some cases.
6033 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6034 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6035 return SDValue();
6036
Chris Lattner222374d2010-12-22 07:36:50 +00006037 EVT PtrType = N0.getOperand(1).getValueType();
Bill Wendling7bfa43b2009-01-30 22:33:24 +00006038
Evan Cheng4c6f9172012-06-26 01:19:33 +00006039 if (PtrType == MVT::Untyped || PtrType.isExtended())
6040 // It's not possible to generate a constant of extended or untyped type.
6041 return SDValue();
6042
Chris Lattner222374d2010-12-22 07:36:50 +00006043 // For big endian targets, we need to adjust the offset to the pointer to
6044 // load the correct bytes.
6045 if (TLI.isBigEndian()) {
6046 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6047 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6048 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
Evan Cheng464dc9b2007-03-22 01:54:19 +00006049 }
6050
Chris Lattner222374d2010-12-22 07:36:50 +00006051 uint64_t PtrOff = ShAmt / 8;
6052 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006053 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
Chris Lattner222374d2010-12-22 07:36:50 +00006054 PtrType, LN0->getBasePtr(),
6055 DAG.getConstant(PtrOff, PtrType));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006056 AddToWorklist(NewPtr.getNode());
Chris Lattner222374d2010-12-22 07:36:50 +00006057
Chris Lattner9a499e92010-12-22 08:01:44 +00006058 SDValue Load;
6059 if (ExtType == ISD::NON_EXTLOAD)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006060 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
Chris Lattner9a499e92010-12-22 08:01:44 +00006061 LN0->getPointerInfo().getWithOffset(PtrOff),
Pete Cooper82cd9e82011-11-08 18:42:53 +00006062 LN0->isVolatile(), LN0->isNonTemporal(),
Hal Finkelcc39b672014-07-24 12:16:19 +00006063 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
Chris Lattner9a499e92010-12-22 08:01:44 +00006064 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00006065 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
Chris Lattner9a499e92010-12-22 08:01:44 +00006066 LN0->getPointerInfo().getWithOffset(PtrOff),
6067 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
Louis Gerbarg67474e32014-07-31 21:45:05 +00006068 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
Chris Lattner222374d2010-12-22 07:36:50 +00006069
6070 // Replace the old load's chain with the new load's chain.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006071 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00006072 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
Chris Lattner222374d2010-12-22 07:36:50 +00006073
6074 // Shift the result left, if we've swallowed a left shift.
6075 SDValue Result = Load;
6076 if (ShLeftAmt != 0) {
Owen Andersonb2c80da2011-02-25 21:41:48 +00006077 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
Chris Lattner222374d2010-12-22 07:36:50 +00006078 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6079 ShImmTy = VT;
Paul Redmond288604e2013-02-12 15:21:21 +00006080 // If the shift amount is as large as the result size (but, presumably,
6081 // no larger than the source) then the useful bits of the result are
6082 // zero; we can't simply return the shortened shift, because the result
6083 // of that operation is undefined.
6084 if (ShLeftAmt >= VT.getSizeInBits())
6085 Result = DAG.getConstant(0, VT);
6086 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00006087 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
Paul Redmond288604e2013-02-12 15:21:21 +00006088 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
Chris Lattner222374d2010-12-22 07:36:50 +00006089 }
6090
6091 // Return the new loaded value.
6092 return Result;
Evan Cheng464dc9b2007-03-22 01:54:19 +00006093}
6094
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006095SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6096 SDValue N0 = N->getOperand(0);
6097 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006098 EVT VT = N->getValueType(0);
6099 EVT EVT = cast<VTSDNode>(N1)->getVT();
Dan Gohman1d459e42009-12-11 21:31:27 +00006100 unsigned VTBits = VT.getScalarType().getSizeInBits();
Dan Gohman6bd3ef82010-01-09 02:13:55 +00006101 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006102
Nate Begeman21158fc2005-09-01 00:19:25 +00006103 // fold (sext_in_reg c1) -> c1
Chris Lattner29062da2006-05-08 20:59:41 +00006104 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006105 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006106
Chris Lattner2a4d7b82006-05-06 22:43:44 +00006107 // If the input is already sign extended, just drop the extension.
Dan Gohman1d459e42009-12-11 21:31:27 +00006108 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
Chris Lattner1ecb2a22006-05-06 09:30:03 +00006109 return N0;
Scott Michelcf0da6c2009-02-17 22:15:04 +00006110
Nate Begeman7cea6ef2005-09-02 21:18:40 +00006111 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6112 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006113 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006114 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00006115 N0.getOperand(0), N1);
Chris Lattner446e1ef2006-05-08 21:18:59 +00006116
Dan Gohman345d63c2008-07-31 00:50:31 +00006117 // fold (sext_in_reg (sext x)) -> (sext x)
6118 // fold (sext_in_reg (aext x)) -> (sext x)
6119 // if x is small enough.
6120 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6121 SDValue N00 = N0.getOperand(0);
Evan Chengf037f872010-04-16 22:26:19 +00006122 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6123 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006124 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
Dan Gohman345d63c2008-07-31 00:50:31 +00006125 }
6126
Chris Lattner9ad59152007-04-17 19:03:21 +00006127 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
Dan Gohman1f372ed2008-02-25 21:11:39 +00006128 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006129 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006130
Chris Lattner9ad59152007-04-17 19:03:21 +00006131 // fold operands of sext_in_reg based on knowledge that the top bits are not
6132 // demanded.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006133 if (SimplifyDemandedBits(SDValue(N, 0)))
6134 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006135
Evan Cheng464dc9b2007-03-22 01:54:19 +00006136 // fold (sext_in_reg (load x)) -> (smaller sextload x)
6137 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006138 SDValue NarrowLoad = ReduceLoadWidth(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006139 if (NarrowLoad.getNode())
Evan Cheng464dc9b2007-03-22 01:54:19 +00006140 return NarrowLoad;
6141
Bill Wendling7bfa43b2009-01-30 22:33:24 +00006142 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00006143 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
Chris Lattner446e1ef2006-05-08 21:18:59 +00006144 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6145 if (N0.getOpcode() == ISD::SRL) {
6146 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
Dan Gohman1d459e42009-12-11 21:31:27 +00006147 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00006148 // We can turn this into an SRA iff the input to the SRL is already sign
Chris Lattner446e1ef2006-05-08 21:18:59 +00006149 // extended enough.
Dan Gohman309d3d52007-06-22 14:59:07 +00006150 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
Dan Gohman1d459e42009-12-11 21:31:27 +00006151 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006152 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00006153 N0.getOperand(0), N0.getOperand(1));
Chris Lattner446e1ef2006-05-08 21:18:59 +00006154 }
6155 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00006156
Nate Begeman02b23c62005-10-13 03:11:28 +00006157 // fold (sext_inreg (extload x)) -> (sextload x)
Scott Michelcf0da6c2009-02-17 22:15:04 +00006158 if (ISD::isEXTLoad(N0.getNode()) &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00006159 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Dan Gohman47a7d6f2008-01-30 00:15:11 +00006160 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006161 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00006162 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00006163 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006164 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00006165 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00006166 LN0->getBasePtr(), EVT,
6167 LN0->getMemOperand());
Chris Lattnerd39c60f2005-12-14 19:25:30 +00006168 CombineTo(N, ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006169 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006170 AddToWorklist(ExtLoad.getNode());
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006171 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00006172 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00006173 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
Gabor Greiff304a7a2008-08-28 21:40:38 +00006174 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Cheng8a1d09d2007-03-07 08:07:03 +00006175 N0.hasOneUse() &&
Dan Gohman47a7d6f2008-01-30 00:15:11 +00006176 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006177 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Evan Cheng07d53b12008-10-14 21:26:46 +00006178 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00006179 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006180 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00006181 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00006182 LN0->getBasePtr(), EVT,
6183 LN0->getMemOperand());
Chris Lattnerd39c60f2005-12-14 19:25:30 +00006184 CombineTo(N, ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006185 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006186 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00006187 }
Evan Cheng4c0bd962011-06-21 06:01:08 +00006188
6189 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6190 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6191 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6192 N0.getOperand(1), false);
Craig Topperc0196b12014-04-14 00:51:57 +00006193 if (BSwap.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006194 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Evan Cheng4c0bd962011-06-21 06:01:08 +00006195 BSwap, N1);
6196 }
6197
Andrea Di Biagio46dcddb2013-12-27 20:20:28 +00006198 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6199 // into a build_vector.
6200 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6201 SmallVector<SDValue, 8> Elts;
6202 unsigned NumElts = N0->getNumOperands();
6203 unsigned ShAmt = VTBits - EVTBits;
6204
6205 for (unsigned i = 0; i != NumElts; ++i) {
6206 SDValue Op = N0->getOperand(i);
6207 if (Op->getOpcode() == ISD::UNDEF) {
6208 Elts.push_back(Op);
6209 continue;
6210 }
6211
6212 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
Kevin Qin5cd73c92014-01-06 02:26:10 +00006213 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6214 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
Andrea Di Biagio46dcddb2013-12-27 20:20:28 +00006215 Op.getValueType()));
6216 }
6217
Craig Topper48d114b2014-04-26 18:35:24 +00006218 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
Andrea Di Biagio46dcddb2013-12-27 20:20:28 +00006219 }
6220
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006221 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00006222}
6223
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006224SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6225 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006226 EVT VT = N->getValueType(0);
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006227 bool isLE = TLI.isLittleEndian();
Nate Begeman21158fc2005-09-01 00:19:25 +00006228
6229 // noop truncate
6230 if (N0.getValueType() == N->getValueType(0))
Nate Begemand23739d2005-09-06 04:43:02 +00006231 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00006232 // fold (truncate c1) -> c1
Chris Lattner7e7bcf32006-05-06 23:06:26 +00006233 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006234 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00006235 // fold (truncate (truncate x)) -> (truncate x)
6236 if (N0.getOpcode() == ISD::TRUNCATE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006237 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
Nate Begeman21158fc2005-09-01 00:19:25 +00006238 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
Chris Lattner6855d622010-04-07 18:13:33 +00006239 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6240 N0.getOpcode() == ISD::SIGN_EXTEND ||
Chris Lattner907e3922006-05-05 22:56:26 +00006241 N0.getOpcode() == ISD::ANY_EXTEND) {
Duncan Sands11dd4242008-06-08 20:54:56 +00006242 if (N0.getOperand(0).getValueType().bitsLT(VT))
Nate Begeman21158fc2005-09-01 00:19:25 +00006243 // if the source is smaller than the dest, we still need an extend
Andrew Trickef9de2a2013-05-25 02:42:55 +00006244 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006245 N0.getOperand(0));
Craig Topper5f9791f2012-09-29 07:18:53 +00006246 if (N0.getOperand(0).getValueType().bitsGT(VT))
Nate Begeman21158fc2005-09-01 00:19:25 +00006247 // if the source is larger than the dest, than we just need the truncate
Andrew Trickef9de2a2013-05-25 02:42:55 +00006248 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
Craig Topper5f9791f2012-09-29 07:18:53 +00006249 // if the source and dest are the same type, we can drop both the extend
6250 // and the truncate.
6251 return N0.getOperand(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00006252 }
Evan Chengd63baea2007-03-21 20:14:05 +00006253
Nadav Rotem4f4546b2012-02-05 11:39:23 +00006254 // Fold extract-and-trunc into a narrow extract. For example:
6255 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6256 // i32 y = TRUNCATE(i64 x)
6257 // -- becomes --
6258 // v16i8 b = BITCAST (v2i64 val)
6259 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6260 //
6261 // Note: We only run this optimization after type legalization (which often
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006262 // creates this pattern) and before operation legalization after which
6263 // we need to be more careful about the vector instructions that we generate.
6264 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
Hal Finkelab51ecd2014-02-28 00:26:45 +00006265 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006266
6267 EVT VecTy = N0.getOperand(0).getValueType();
6268 EVT ExTy = N0.getValueType();
6269 EVT TrTy = N->getValueType(0);
6270
6271 unsigned NumElem = VecTy.getVectorNumElements();
6272 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6273
6274 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6275 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6276
6277 SDValue EltNo = N0->getOperand(1);
6278 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6279 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Tom Stellardd42c5942013-08-05 22:22:01 +00006280 EVT IndexTy = TLI.getVectorIdxTy();
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006281 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6282
Andrew Trickef9de2a2013-05-25 02:42:55 +00006283 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006284 NVT, N0.getOperand(0));
6285
6286 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
Andrew Trickef9de2a2013-05-25 02:42:55 +00006287 SDLoc(N), TrTy, V,
Jim Grosbach92f6adc2012-05-08 20:56:07 +00006288 DAG.getConstant(Index, IndexTy));
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006289 }
6290 }
6291
Matt Arsenault3332b702014-07-10 18:21:04 +00006292 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6293 if (N0.getOpcode() == ISD::SELECT) {
6294 EVT SrcVT = N0.getValueType();
6295 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6296 TLI.isTruncateFree(SrcVT, VT)) {
6297 SDLoc SL(N0);
6298 SDValue Cond = N0.getOperand(0);
6299 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6300 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6301 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6302 }
6303 }
6304
Arnold Schwaighofer3f9568e2013-02-20 21:33:32 +00006305 // Fold a series of buildvector, bitcast, and truncate if possible.
6306 // For example fold
6307 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6308 // (2xi32 (buildvector x, y)).
6309 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6310 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6311 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6312 N0.getOperand(0).hasOneUse()) {
6313
6314 SDValue BuildVect = N0.getOperand(0);
6315 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6316 EVT TruncVecEltTy = VT.getVectorElementType();
6317
6318 // Check that the element types match.
6319 if (BuildVectEltTy == TruncVecEltTy) {
6320 // Now we only need to compute the offset of the truncated elements.
6321 unsigned BuildVecNumElts = BuildVect.getNumOperands();
6322 unsigned TruncVecNumElts = VT.getVectorNumElements();
6323 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6324
6325 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6326 "Invalid number of elements");
6327
6328 SmallVector<SDValue, 8> Opnds;
6329 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6330 Opnds.push_back(BuildVect.getOperand(i));
6331
Craig Topper48d114b2014-04-26 18:35:24 +00006332 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
Arnold Schwaighofer3f9568e2013-02-20 21:33:32 +00006333 }
6334 }
6335
Chris Lattner5e6fe052007-10-13 06:35:54 +00006336 // See if we can simplify the input to this truncate through knowledge that
Nadav Rotem502f1b92011-02-24 21:01:34 +00006337 // only the low bits are being used.
6338 // For example "trunc (or (shl x, 8), y)" // -> trunc y
Nadav Rotemb0091302011-02-27 07:40:43 +00006339 // Currently we only perform this optimization on scalars because vectors
Nadav Rotem502f1b92011-02-24 21:01:34 +00006340 // may have different active low bits.
6341 if (!VT.isVector()) {
6342 SDValue Shorter =
6343 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6344 VT.getSizeInBits()));
6345 if (Shorter.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006346 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
Nadav Rotem502f1b92011-02-24 21:01:34 +00006347 }
Nate Begeman8caf81d2005-10-12 20:40:40 +00006348 // fold (truncate (load x)) -> (smaller load x)
Evan Chengd63baea2007-03-21 20:14:05 +00006349 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
Dan Gohman600f62b2010-06-24 14:30:44 +00006350 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6351 SDValue Reduced = ReduceLoadWidth(N);
6352 if (Reduced.getNode())
6353 return Reduced;
Richard Sandifordd1093632013-12-11 11:37:27 +00006354 // Handle the case where the load remains an extending load even
6355 // after truncation.
6356 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6357 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6358 if (!LN0->isVolatile() &&
6359 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6360 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6361 VT, LN0->getChain(), LN0->getBasePtr(),
6362 LN0->getMemoryVT(),
6363 LN0->getMemOperand());
6364 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6365 return NewLoad;
6366 }
6367 }
Dan Gohman600f62b2010-06-24 14:30:44 +00006368 }
Michael Liao3ac82012012-10-17 23:45:54 +00006369 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6370 // where ... are all 'undef'.
6371 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6372 SmallVector<EVT, 8> VTs;
6373 SDValue V;
6374 unsigned Idx = 0;
6375 unsigned NumDefs = 0;
6376
6377 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6378 SDValue X = N0.getOperand(i);
6379 if (X.getOpcode() != ISD::UNDEF) {
6380 V = X;
6381 Idx = i;
6382 NumDefs++;
6383 }
6384 // Stop if more than one members are non-undef.
6385 if (NumDefs > 1)
6386 break;
6387 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6388 VT.getVectorElementType(),
6389 X.getValueType().getVectorNumElements()));
6390 }
6391
6392 if (NumDefs == 0)
6393 return DAG.getUNDEF(VT);
6394
6395 if (NumDefs == 1) {
6396 assert(V.getNode() && "The single defined operand is empty!");
6397 SmallVector<SDValue, 8> Opnds;
6398 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6399 if (i != Idx) {
6400 Opnds.push_back(DAG.getUNDEF(VTs[i]));
6401 continue;
6402 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00006403 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006404 AddToWorklist(NV.getNode());
Michael Liao3ac82012012-10-17 23:45:54 +00006405 Opnds.push_back(NV);
6406 }
Craig Topper48d114b2014-04-26 18:35:24 +00006407 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
Michael Liao3ac82012012-10-17 23:45:54 +00006408 }
6409 }
Dan Gohman600f62b2010-06-24 14:30:44 +00006410
6411 // Simplify the operands using demanded-bits information.
6412 if (!VT.isVector() &&
6413 SimplifyDemandedBits(SDValue(N, 0)))
6414 return SDValue(N, 0);
6415
Evan Chengf1bd5fc2010-04-17 06:13:15 +00006416 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00006417}
6418
Evan Chengb980f6f2008-05-12 23:04:07 +00006419static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006420 SDValue Elt = N->getOperand(i);
Evan Chengb980f6f2008-05-12 23:04:07 +00006421 if (Elt.getOpcode() != ISD::MERGE_VALUES)
Gabor Greiff304a7a2008-08-28 21:40:38 +00006422 return Elt.getNode();
6423 return Elt.getOperand(Elt.getResNo()).getNode();
Evan Chengb980f6f2008-05-12 23:04:07 +00006424}
6425
Sanjay Patel50cbfc52014-08-28 16:29:51 +00006426/// build_pair (load, load) -> load
Scott Michelcf0da6c2009-02-17 22:15:04 +00006427/// if load locations are consecutive.
Owen Anderson53aa7a92009-08-10 22:56:29 +00006428SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
Evan Chengb980f6f2008-05-12 23:04:07 +00006429 assert(N->getOpcode() == ISD::BUILD_PAIR);
6430
Nate Begeman624690c2009-06-05 21:37:30 +00006431 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6432 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
Chris Lattnerf72c3c02010-09-21 16:08:50 +00006433 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
Matt Arsenault58a76392014-02-24 21:01:15 +00006434 LD1->getAddressSpace() != LD2->getAddressSpace())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006435 return SDValue();
Owen Anderson53aa7a92009-08-10 22:56:29 +00006436 EVT LD1VT = LD1->getValueType(0);
Bill Wendling4e0a6152009-01-30 22:44:24 +00006437
Evan Chengb980f6f2008-05-12 23:04:07 +00006438 if (ISD::isNON_EXTLoad(LD2) &&
6439 LD2->hasOneUse() &&
Duncan Sands8651e9c2008-06-13 19:07:40 +00006440 // If both are volatile this would reduce the number of volatile loads.
6441 // If one is volatile it might be ok, but play conservative and bail out.
Nate Begeman624690c2009-06-05 21:37:30 +00006442 !LD1->isVolatile() &&
6443 !LD2->isVolatile() &&
Evan Chengf5938d52009-12-09 01:36:00 +00006444 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
Nate Begeman624690c2009-06-05 21:37:30 +00006445 unsigned Align = LD1->getAlignment();
Micah Villmowcdfe20b2012-10-08 16:38:25 +00006446 unsigned NewAlign = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +00006447 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
Bill Wendling4e0a6152009-01-30 22:44:24 +00006448
Duncan Sands8651e9c2008-06-13 19:07:40 +00006449 if (NewAlign <= Align &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006450 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006451 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
Chris Lattnerf72c3c02010-09-21 16:08:50 +00006452 LD1->getBasePtr(), LD1->getPointerInfo(),
Pete Cooper82cd9e82011-11-08 18:42:53 +00006453 false, false, false, Align);
Evan Chengb980f6f2008-05-12 23:04:07 +00006454 }
Bill Wendling4e0a6152009-01-30 22:44:24 +00006455
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006456 return SDValue();
Evan Chengb980f6f2008-05-12 23:04:07 +00006457}
6458
Wesley Peck527da1b2010-11-23 03:31:01 +00006459SDValue DAGCombiner::visitBITCAST(SDNode *N) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006460 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006461 EVT VT = N->getValueType(0);
Chris Lattnera1874602005-12-23 05:30:37 +00006462
Dan Gohmana8665142007-06-25 16:23:39 +00006463 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6464 // Only do this before legalize, since afterward the target may be depending
6465 // on the bitconvert.
6466 // First check to see if this is all constant.
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006467 if (!LegalTypes &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00006468 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
Duncan Sands13237ac2008-06-06 12:08:01 +00006469 VT.isVector()) {
Juergen Ributzka73844052014-01-13 20:51:35 +00006470 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006471
Owen Anderson53aa7a92009-08-10 22:56:29 +00006472 EVT DestEltVT = N->getValueType(0).getVectorElementType();
Duncan Sands13237ac2008-06-06 12:08:01 +00006473 assert(!DestEltVT.isVector() &&
Dan Gohmana8665142007-06-25 16:23:39 +00006474 "Element type of vector ValueType must not be vector!");
Bill Wendling4e0a6152009-01-30 22:44:24 +00006475 if (isSimple)
Wesley Peck527da1b2010-11-23 03:31:01 +00006476 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
Dan Gohmana8665142007-06-25 16:23:39 +00006477 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006478
Dan Gohman921ddd62008-09-05 01:58:21 +00006479 // If the input is a constant, let getNode fold it.
Chris Lattnera1874602005-12-23 05:30:37 +00006480 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006481 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
Dan Gohman733a64d2009-08-10 23:15:10 +00006482 if (Res.getNode() != N) {
6483 if (!LegalOperations ||
6484 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6485 return Res;
6486
6487 // Folding it resulted in an illegal node, and it's too late to
6488 // do that. Clean up the old node and forego the transformation.
6489 // Ideally this won't happen very often, because instcombine
6490 // and the earlier dagcombine runs (where illegal nodes are
6491 // permitted) should have folded most of them already.
Chandler Carruth18066972014-08-02 10:02:07 +00006492 deleteAndRecombine(Res.getNode());
Dan Gohman733a64d2009-08-10 23:15:10 +00006493 }
Chris Lattnera1874602005-12-23 05:30:37 +00006494 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006495
Bill Wendling4e0a6152009-01-30 22:44:24 +00006496 // (conv (conv x, t1), t2) -> (conv x, t2)
Wesley Peck527da1b2010-11-23 03:31:01 +00006497 if (N0.getOpcode() == ISD::BITCAST)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006498 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006499 N0.getOperand(0));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006500
Chris Lattner54560f62005-12-23 05:44:41 +00006501 // fold (conv (load x)) -> (load (conv*)x)
Evan Cheng0de312d2007-10-06 08:19:55 +00006502 // If the resultant load doesn't need a higher alignment than the original!
Gabor Greiff304a7a2008-08-28 21:40:38 +00006503 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Duncan Sands8651e9c2008-06-13 19:07:40 +00006504 // Do not change the width of a volatile load.
6505 !cast<LoadSDNode>(N0)->isVolatile() &&
Ulrich Weigandf236bb12014-07-03 15:06:47 +00006506 // Do not remove the cast if the types differ in endian layout.
6507 TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6508 TLI.hasBigEndianPartOrdering(VT) &&
Matt Arsenaultc5559bb2013-11-15 04:42:23 +00006509 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6510 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00006511 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Micah Villmowcdfe20b2012-10-08 16:38:25 +00006512 unsigned Align = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +00006513 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
Evan Chenga4cf58a2007-05-07 21:27:48 +00006514 unsigned OrigAlign = LN0->getAlignment();
Bill Wendling4e0a6152009-01-30 22:44:24 +00006515
Evan Chenga4cf58a2007-05-07 21:27:48 +00006516 if (Align <= OrigAlign) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006517 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
Chris Lattnerf72c3c02010-09-21 16:08:50 +00006518 LN0->getBasePtr(), LN0->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +00006519 LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00006520 LN0->isInvariant(), OrigAlign,
Hal Finkelcc39b672014-07-24 12:16:19 +00006521 LN0->getAAInfo());
Chandler Carruth7cd15be2014-08-14 08:18:34 +00006522 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
Evan Chenga4cf58a2007-05-07 21:27:48 +00006523 return Load;
6524 }
Chris Lattner54560f62005-12-23 05:44:41 +00006525 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00006526
Bill Wendling4e0a6152009-01-30 22:44:24 +00006527 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6528 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
Chris Lattner888560d2008-01-27 17:42:27 +00006529 // This often reduces constant pool loads.
Tom Stellardc54731a2013-07-23 23:55:03 +00006530 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6531 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
Nadav Rotem24a822a2012-09-13 14:54:28 +00006532 N0.getNode()->hasOneUse() && VT.isInteger() &&
6533 !VT.isVector() && !N0.getValueType().isVector()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006534 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006535 N0.getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006536 AddToWorklist(NewConv.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +00006537
Duncan Sands13237ac2008-06-06 12:08:01 +00006538 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
Chris Lattner888560d2008-01-27 17:42:27 +00006539 if (N0.getOpcode() == ISD::FNEG)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006540 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006541 NewConv, DAG.getConstant(SignBit, VT));
Chris Lattner888560d2008-01-27 17:42:27 +00006542 assert(N0.getOpcode() == ISD::FABS);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006543 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006544 NewConv, DAG.getConstant(~SignBit, VT));
Chris Lattner888560d2008-01-27 17:42:27 +00006545 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006546
Bill Wendling4e0a6152009-01-30 22:44:24 +00006547 // fold (bitconvert (fcopysign cst, x)) ->
6548 // (or (and (bitconvert x), sign), (and cst, (not sign)))
6549 // Note that we don't handle (copysign x, cst) because this can always be
6550 // folded to an fneg or fabs.
Gabor Greiff304a7a2008-08-28 21:40:38 +00006551 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
Chris Lattner2ee91f42008-01-27 23:32:17 +00006552 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
Duncan Sands13237ac2008-06-06 12:08:01 +00006553 VT.isInteger() && !VT.isVector()) {
6554 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
Owen Anderson117c9e82009-08-12 00:36:31 +00006555 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
Chris Lattner4041ab62010-04-15 04:48:01 +00006556 if (isTypeLegal(IntXVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006557 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006558 IntXVT, N0.getOperand(1));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006559 AddToWorklist(X.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00006560
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006561 // If X has a different width than the result/lhs, sext it or truncate it.
6562 unsigned VTWidth = VT.getSizeInBits();
6563 if (OrigXWidth < VTWidth) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006564 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006565 AddToWorklist(X.getNode());
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006566 } else if (OrigXWidth > VTWidth) {
6567 // To get the sign bit in the right place, we have to shift it right
6568 // before truncating.
Andrew Trickef9de2a2013-05-25 02:42:55 +00006569 X = DAG.getNode(ISD::SRL, SDLoc(X),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006570 X.getValueType(), X,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006571 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006572 AddToWorklist(X.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00006573 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006574 AddToWorklist(X.getNode());
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006575 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006576
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006577 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00006578 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006579 X, DAG.getConstant(SignBit, VT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006580 AddToWorklist(X.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00006581
Andrew Trickef9de2a2013-05-25 02:42:55 +00006582 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006583 VT, N0.getOperand(0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006584 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006585 Cst, DAG.getConstant(~SignBit, VT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006586 AddToWorklist(Cst.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00006587
Andrew Trickef9de2a2013-05-25 02:42:55 +00006588 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006589 }
Chris Lattner888560d2008-01-27 17:42:27 +00006590 }
Evan Chengb980f6f2008-05-12 23:04:07 +00006591
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00006592 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
Evan Chengb980f6f2008-05-12 23:04:07 +00006593 if (N0.getOpcode() == ISD::BUILD_PAIR) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00006594 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6595 if (CombineLD.getNode())
Evan Chengb980f6f2008-05-12 23:04:07 +00006596 return CombineLD;
6597 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006598
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006599 return SDValue();
Chris Lattnera1874602005-12-23 05:30:37 +00006600}
6601
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006602SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00006603 EVT VT = N->getValueType(0);
Evan Chengb980f6f2008-05-12 23:04:07 +00006604 return CombineConsecutiveLoads(N, VT);
6605}
6606
Sanjay Patel50cbfc52014-08-28 16:29:51 +00006607/// We know that BV is a build_vector node with Constant, ConstantFP or Undef
6608/// operands. DstEltVT indicates the destination element value type.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006609SDValue DAGCombiner::
Wesley Peck527da1b2010-11-23 03:31:01 +00006610ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00006611 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006612
Chris Lattnere4e64b62006-04-02 02:53:43 +00006613 // If this is already the right type, we're done.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006614 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006615
Duncan Sands13237ac2008-06-06 12:08:01 +00006616 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6617 unsigned DstBitSize = DstEltVT.getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006618
Chris Lattnere4e64b62006-04-02 02:53:43 +00006619 // If this is a conversion of N elements of one type to N elements of another
6620 // type, convert each element. This handles FP<->INT cases.
6621 if (SrcBitSize == DstBitSize) {
Nate Begeman317b9692010-07-27 18:02:18 +00006622 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6623 BV->getValueType(0).getVectorNumElements());
6624
6625 // Due to the FP element handling below calling this routine recursively,
6626 // we can end up with a scalar-to-vector node here.
6627 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006628 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6629 DAG.getNode(ISD::BITCAST, SDLoc(BV),
Nate Begeman317b9692010-07-27 18:02:18 +00006630 DstEltVT, BV->getOperand(0)));
Wesley Peck527da1b2010-11-23 03:31:01 +00006631
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006632 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +00006633 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
Bob Wilson59dbbb22009-04-13 22:05:19 +00006634 SDValue Op = BV->getOperand(i);
6635 // If the vector element type is not legal, the BUILD_VECTOR operands
6636 // are promoted and implicitly truncated. Make that explicit here.
Bob Wilsonda188eb2009-04-20 17:27:09 +00006637 if (Op.getValueType() != SrcEltVT)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006638 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6639 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
Bob Wilson59dbbb22009-04-13 22:05:19 +00006640 DstEltVT, Op));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006641 AddToWorklist(Ops.back().getNode());
Chris Lattner098c01e2006-04-08 04:15:24 +00006642 }
Craig Topper48d114b2014-04-26 18:35:24 +00006643 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006644 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006645
Chris Lattnere4e64b62006-04-02 02:53:43 +00006646 // Otherwise, we're growing or shrinking the elements. To avoid having to
6647 // handle annoying details of growing/shrinking FP values, we convert them to
6648 // int first.
Duncan Sands13237ac2008-06-06 12:08:01 +00006649 if (SrcEltVT.isFloatingPoint()) {
Chris Lattnere4e64b62006-04-02 02:53:43 +00006650 // Convert the input float vector to a int vector where the elements are the
6651 // same sizes.
Owen Anderson9f944592009-08-11 20:47:22 +00006652 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
Owen Anderson117c9e82009-08-12 00:36:31 +00006653 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
Wesley Peck527da1b2010-11-23 03:31:01 +00006654 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
Chris Lattnere4e64b62006-04-02 02:53:43 +00006655 SrcEltVT = IntVT;
6656 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006657
Chris Lattnere4e64b62006-04-02 02:53:43 +00006658 // Now we know the input is an integer vector. If the output is a FP type,
6659 // convert to integer first, then to FP of the right size.
Duncan Sands13237ac2008-06-06 12:08:01 +00006660 if (DstEltVT.isFloatingPoint()) {
Owen Anderson9f944592009-08-11 20:47:22 +00006661 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
Owen Anderson117c9e82009-08-12 00:36:31 +00006662 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
Wesley Peck527da1b2010-11-23 03:31:01 +00006663 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006664
Chris Lattnere4e64b62006-04-02 02:53:43 +00006665 // Next, convert to FP elements of the same size.
Wesley Peck527da1b2010-11-23 03:31:01 +00006666 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006667 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006668
Chris Lattnere4e64b62006-04-02 02:53:43 +00006669 // Okay, we know the src/dst types are both integers of differing types.
6670 // Handling growing first.
Duncan Sands13237ac2008-06-06 12:08:01 +00006671 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
Chris Lattnere4e64b62006-04-02 02:53:43 +00006672 if (SrcBitSize < DstBitSize) {
6673 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
Scott Michelcf0da6c2009-02-17 22:15:04 +00006674
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006675 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +00006676 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
Chris Lattnere4e64b62006-04-02 02:53:43 +00006677 i += NumInputsPerOutput) {
6678 bool isLE = TLI.isLittleEndian();
Dan Gohmane1c4f992008-03-03 23:51:38 +00006679 APInt NewBits = APInt(DstBitSize, 0);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006680 bool EltIsUndef = true;
6681 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6682 // Shift the previously computed bits over.
6683 NewBits <<= SrcBitSize;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006684 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006685 if (Op.getOpcode() == ISD::UNDEF) continue;
6686 EltIsUndef = false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00006687
Jay Foad583abbc2010-12-07 08:25:19 +00006688 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
Dan Gohmanecd40a32010-04-12 02:24:01 +00006689 zextOrTrunc(SrcBitSize).zext(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006690 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006691
Chris Lattnere4e64b62006-04-02 02:53:43 +00006692 if (EltIsUndef)
Dale Johannesen84935752009-02-06 23:05:02 +00006693 Ops.push_back(DAG.getUNDEF(DstEltVT));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006694 else
6695 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6696 }
6697
Owen Anderson117c9e82009-08-12 00:36:31 +00006698 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
Craig Topper48d114b2014-04-26 18:35:24 +00006699 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006700 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006701
Chris Lattnere4e64b62006-04-02 02:53:43 +00006702 // Finally, this must be the case where we are shrinking elements: each input
6703 // turns into multiple outputs.
Evan Cheng6200c222008-02-18 23:04:32 +00006704 bool isS2V = ISD::isScalarToVector(BV);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006705 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
Owen Anderson117c9e82009-08-12 00:36:31 +00006706 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6707 NumOutputsPerInput*BV->getNumOperands());
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006708 SmallVector<SDValue, 8> Ops;
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006709
Dan Gohmana8665142007-06-25 16:23:39 +00006710 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
Chris Lattnere4e64b62006-04-02 02:53:43 +00006711 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6712 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
Dale Johannesen84935752009-02-06 23:05:02 +00006713 Ops.push_back(DAG.getUNDEF(DstEltVT));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006714 continue;
6715 }
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006716
Jay Foad583abbc2010-12-07 08:25:19 +00006717 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6718 getAPIntValue().zextOrTrunc(SrcBitSize);
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006719
Chris Lattnere4e64b62006-04-02 02:53:43 +00006720 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
Jay Foad583abbc2010-12-07 08:25:19 +00006721 APInt ThisVal = OpVal.trunc(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006722 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
Jay Foad583abbc2010-12-07 08:25:19 +00006723 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
Evan Cheng6200c222008-02-18 23:04:32 +00006724 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
Andrew Trickef9de2a2013-05-25 02:42:55 +00006725 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006726 Ops[0]);
Dan Gohmane1c4f992008-03-03 23:51:38 +00006727 OpVal = OpVal.lshr(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006728 }
6729
6730 // For big endian targets, swap the order of the pieces of each element.
Duncan Sands7377f5f2008-02-11 10:37:04 +00006731 if (TLI.isBigEndian())
Chris Lattnere4e64b62006-04-02 02:53:43 +00006732 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6733 }
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006734
Craig Topper48d114b2014-04-26 18:35:24 +00006735 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006736}
6737
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006738SDValue DAGCombiner::visitFADD(SDNode *N) {
6739 SDValue N0 = N->getOperand(0);
6740 SDValue N1 = N->getOperand(1);
Nate Begeman418c6e42005-10-18 00:28:13 +00006741 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6742 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006743 EVT VT = N->getValueType(0);
Sanjay Patel78614bf2014-08-28 15:53:16 +00006744 const TargetOptions &Options = DAG.getTarget().Options;
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00006745
Dan Gohmana8665142007-06-25 16:23:39 +00006746 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006747 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006748 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006749 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006750 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006751
Lang Hamesa33db652012-06-14 20:37:15 +00006752 // fold (fadd c1, c2) -> c1 + c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006753 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006754 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
Sanjay Patel8170dea2014-09-08 17:32:19 +00006755
Nate Begeman418c6e42005-10-18 00:28:13 +00006756 // canonicalize constant to RHS
6757 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006758 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
Sanjay Patel8170dea2014-09-08 17:32:19 +00006759
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006760 // fold (fadd A, (fneg B)) -> (fsub A, B)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006761 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
Sanjay Patel8170dea2014-09-08 17:32:19 +00006762 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006763 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006764 GetNegatedExpression(N1, DAG, LegalOperations));
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00006765
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006766 // fold (fadd (fneg A), B) -> (fsub B, A)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006767 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
Sanjay Patel8170dea2014-09-08 17:32:19 +00006768 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006769 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006770 GetNegatedExpression(N0, DAG, LegalOperations));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006771
Sanjay Patel8170dea2014-09-08 17:32:19 +00006772 // If 'unsafe math' is enabled, fold lots of things.
6773 if (Options.UnsafeFPMath) {
6774 // No FP constant should be created after legalization as Instruction
6775 // Selection pass has a hard time dealing with FP constants.
6776 bool AllowNewConst = (Level < AfterLegalizeDAG);
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00006777
Sanjay Patel8170dea2014-09-08 17:32:19 +00006778 // fold (fadd A, 0) -> A
6779 if (N1CFP && N1CFP->getValueAPF().isZero())
6780 return N0;
Scott Michelcf0da6c2009-02-17 22:15:04 +00006781
Sanjay Patel8170dea2014-09-08 17:32:19 +00006782 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6783 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6784 isa<ConstantFPSDNode>(N0.getOperand(1)))
6785 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6786 DAG.getNode(ISD::FADD, SDLoc(N), VT,
6787 N0.getOperand(1), N1));
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00006788
Sanjay Patel8170dea2014-09-08 17:32:19 +00006789 // If allowed, fold (fadd (fneg x), x) -> 0.0
6790 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6791 return DAG.getConstantFP(0.0, VT);
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00006792
Sanjay Patel8170dea2014-09-08 17:32:19 +00006793 // If allowed, fold (fadd x, (fneg x)) -> 0.0
6794 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6795 return DAG.getConstantFP(0.0, VT);
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00006796
Sanjay Patel8170dea2014-09-08 17:32:19 +00006797 // We can fold chains of FADD's of the same value into multiplications.
6798 // This transform is not safe in general because we are reducing the number
6799 // of rounding steps.
Sanjay Patel8170dea2014-09-08 17:32:19 +00006800 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
6801 if (N0.getOpcode() == ISD::FMUL) {
6802 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6803 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00006804
Sanjay Patel8170dea2014-09-08 17:32:19 +00006805 // (fadd (fmul x, c), x) -> (fmul x, c+1)
6806 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6807 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6808 SDValue(CFP01, 0),
6809 DAG.getConstantFP(1.0, VT));
6810 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, NewCFP);
6811 }
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00006812
Sanjay Patel8170dea2014-09-08 17:32:19 +00006813 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6814 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6815 N1.getOperand(0) == N1.getOperand(1) &&
6816 N0.getOperand(0) == N1.getOperand(0)) {
6817 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6818 SDValue(CFP01, 0),
6819 DAG.getConstantFP(2.0, VT));
6820 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6821 N0.getOperand(0), NewCFP);
6822 }
Owen Andersoncc61f872012-08-30 23:35:16 +00006823 }
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00006824
Sanjay Patel8170dea2014-09-08 17:32:19 +00006825 if (N1.getOpcode() == ISD::FMUL) {
6826 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6827 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00006828
Sanjay Patel8170dea2014-09-08 17:32:19 +00006829 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6830 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6831 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6832 SDValue(CFP11, 0),
6833 DAG.getConstantFP(1.0, VT));
6834 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, NewCFP);
6835 }
Sanjay Patelf4b7a6b2014-09-08 18:22:51 +00006836
Sanjay Patel8170dea2014-09-08 17:32:19 +00006837 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6838 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6839 N0.getOperand(0) == N0.getOperand(1) &&
6840 N1.getOperand(0) == N0.getOperand(0)) {
6841 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6842 SDValue(CFP11, 0),
6843 DAG.getConstantFP(2.0, VT));
6844 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1.getOperand(0), NewCFP);
6845 }
Owen Andersoncc61f872012-08-30 23:35:16 +00006846 }
Sanjay Patelf4b7a6b2014-09-08 18:22:51 +00006847
Sanjay Patel8170dea2014-09-08 17:32:19 +00006848 if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
6849 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6850 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6851 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6852 (N0.getOperand(0) == N1))
6853 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6854 N1, DAG.getConstantFP(3.0, VT));
Owen Andersoncc61f872012-08-30 23:35:16 +00006855 }
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00006856
Sanjay Patel8170dea2014-09-08 17:32:19 +00006857 if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
6858 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6859 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6860 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6861 N1.getOperand(0) == N0)
6862 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6863 N0, DAG.getConstantFP(3.0, VT));
Owen Andersoncc61f872012-08-30 23:35:16 +00006864 }
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00006865
Sanjay Patel8170dea2014-09-08 17:32:19 +00006866 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6867 if (AllowNewConst &&
6868 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
Stephen Line31f2d22013-06-14 18:17:35 +00006869 N0.getOperand(0) == N0.getOperand(1) &&
Sanjay Patel8170dea2014-09-08 17:32:19 +00006870 N1.getOperand(0) == N1.getOperand(1) &&
6871 N0.getOperand(0) == N1.getOperand(0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006872 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Sanjay Patel8170dea2014-09-08 17:32:19 +00006873 N0.getOperand(0), DAG.getConstantFP(4.0, VT));
Owen Andersoncc61f872012-08-30 23:35:16 +00006874 }
Sanjay Patel8170dea2014-09-08 17:32:19 +00006875 } // enable-unsafe-fp-math
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00006876
Lang Hames39fb1d02012-06-19 22:51:23 +00006877 // FADD -> FMA combines:
Sanjay Patel78614bf2014-08-28 15:53:16 +00006878 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
Eric Christopherf55d4712014-10-08 23:38:39 +00006879 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
Stephen Lin73de7bf2013-07-09 18:16:56 +00006880 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
Lang Hames39fb1d02012-06-19 22:51:23 +00006881
6882 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
Hal Finkel62ac7362014-09-19 11:42:56 +00006883 if (N0.getOpcode() == ISD::FMUL &&
6884 (N0->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006885 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006886 N0.getOperand(0), N0.getOperand(1), N1);
Owen Andersoncc61f872012-08-30 23:35:16 +00006887
Michael Liaoec3850122012-09-01 04:09:16 +00006888 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
Lang Hames39fb1d02012-06-19 22:51:23 +00006889 // Note: Commutes FADD operands.
Hal Finkel62ac7362014-09-19 11:42:56 +00006890 if (N1.getOpcode() == ISD::FMUL &&
6891 (N1->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006892 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006893 N1.getOperand(0), N1.getOperand(1), N0);
Lang Hames39fb1d02012-06-19 22:51:23 +00006894 }
6895
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006896 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006897}
6898
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006899SDValue DAGCombiner::visitFSUB(SDNode *N) {
6900 SDValue N0 = N->getOperand(0);
6901 SDValue N1 = N->getOperand(1);
Sanjay Patel75cc90e2014-09-05 22:26:22 +00006902 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
6903 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006904 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006905 SDLoc dl(N);
Sanjay Patel78614bf2014-08-28 15:53:16 +00006906 const TargetOptions &Options = DAG.getTarget().Options;
Scott Michelcf0da6c2009-02-17 22:15:04 +00006907
Dan Gohmana8665142007-06-25 16:23:39 +00006908 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006909 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006910 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006911 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006912 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006913
Nate Begeman418c6e42005-10-18 00:28:13 +00006914 // fold (fsub c1, c2) -> c1-c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006915 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006916 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
Sanjay Patelae402a32014-08-27 20:57:52 +00006917
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006918 // fold (fsub A, (fneg B)) -> (fadd A, B)
Sanjay Patel78614bf2014-08-28 15:53:16 +00006919 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006920 return DAG.getNode(ISD::FADD, dl, VT, N0,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006921 GetNegatedExpression(N1, DAG, LegalOperations));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006922
Sanjay Patelae402a32014-08-27 20:57:52 +00006923 // If 'unsafe math' is enabled, fold lots of things.
Sanjay Patel78614bf2014-08-28 15:53:16 +00006924 if (Options.UnsafeFPMath) {
Sanjay Patelae402a32014-08-27 20:57:52 +00006925 // (fsub A, 0) -> A
6926 if (N1CFP && N1CFP->getValueAPF().isZero())
6927 return N0;
6928
6929 // (fsub 0, B) -> -B
6930 if (N0CFP && N0CFP->getValueAPF().isZero()) {
Sanjay Patel78614bf2014-08-28 15:53:16 +00006931 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
Sanjay Patelae402a32014-08-27 20:57:52 +00006932 return GetNegatedExpression(N1, DAG, LegalOperations);
6933 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6934 return DAG.getNode(ISD::FNEG, dl, VT, N1);
6935 }
6936
6937 // (fsub x, x) -> 0.0
Owen Andersonab63d842012-05-07 20:51:25 +00006938 if (N0 == N1)
6939 return DAG.getConstantFP(0.0f, VT);
6940
Sanjay Patelae402a32014-08-27 20:57:52 +00006941 // (fsub x, (fadd x, y)) -> (fneg y)
6942 // (fsub x, (fadd y, x)) -> (fneg y)
Bill Wendlingdf170db2012-03-15 05:12:00 +00006943 if (N1.getOpcode() == ISD::FADD) {
6944 SDValue N10 = N1->getOperand(0);
6945 SDValue N11 = N1->getOperand(1);
6946
Sanjay Patel78614bf2014-08-28 15:53:16 +00006947 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
Bill Wendlingdf170db2012-03-15 05:12:00 +00006948 return GetNegatedExpression(N11, DAG, LegalOperations);
Stephen Lin10947502013-07-10 20:47:39 +00006949
Sanjay Patel78614bf2014-08-28 15:53:16 +00006950 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
Bill Wendlingdf170db2012-03-15 05:12:00 +00006951 return GetNegatedExpression(N10, DAG, LegalOperations);
6952 }
6953 }
6954
Lang Hames39fb1d02012-06-19 22:51:23 +00006955 // FSUB -> FMA combines:
Sanjay Patel78614bf2014-08-28 15:53:16 +00006956 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
Eric Christopherf55d4712014-10-08 23:38:39 +00006957 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
Stephen Lin73de7bf2013-07-09 18:16:56 +00006958 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
Lang Hames39fb1d02012-06-19 22:51:23 +00006959
6960 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
Hal Finkel62ac7362014-09-19 11:42:56 +00006961 if (N0.getOpcode() == ISD::FMUL &&
6962 (N0->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006963 return DAG.getNode(ISD::FMA, dl, VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006964 N0.getOperand(0), N0.getOperand(1),
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006965 DAG.getNode(ISD::FNEG, dl, VT, N1));
Lang Hames39fb1d02012-06-19 22:51:23 +00006966
6967 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6968 // Note: Commutes FSUB operands.
Hal Finkel62ac7362014-09-19 11:42:56 +00006969 if (N1.getOpcode() == ISD::FMUL &&
6970 (N1->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006971 return DAG.getNode(ISD::FMA, dl, VT,
6972 DAG.getNode(ISD::FNEG, dl, VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00006973 N1.getOperand(0)),
6974 N1.getOperand(1), N0);
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006975
Stephen Lin8e8424e2013-07-09 00:44:49 +00006976 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
Stephen Lincfe7f352013-07-08 00:37:03 +00006977 if (N0.getOpcode() == ISD::FNEG &&
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006978 N0.getOperand(0).getOpcode() == ISD::FMUL &&
Hal Finkel62ac7362014-09-19 11:42:56 +00006979 ((N0->hasOneUse() && N0.getOperand(0).hasOneUse()) ||
6980 TLI.enableAggressiveFMAFusion(VT))) {
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00006981 SDValue N00 = N0.getOperand(0).getOperand(0);
6982 SDValue N01 = N0.getOperand(0).getOperand(1);
6983 return DAG.getNode(ISD::FMA, dl, VT,
6984 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6985 DAG.getNode(ISD::FNEG, dl, VT, N1));
6986 }
Lang Hames39fb1d02012-06-19 22:51:23 +00006987 }
6988
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006989 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00006990}
6991
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006992SDValue DAGCombiner::visitFMUL(SDNode *N) {
6993 SDValue N0 = N->getOperand(0);
6994 SDValue N1 = N->getOperand(1);
Matt Arsenault6cc00422014-08-16 10:14:19 +00006995 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
6996 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006997 EVT VT = N->getValueType(0);
Sanjay Patel78614bf2014-08-28 15:53:16 +00006998 const TargetOptions &Options = DAG.getTarget().Options;
Chris Lattner6f3b5772005-09-28 22:28:18 +00006999
Dan Gohmana8665142007-06-25 16:23:39 +00007000 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00007001 if (VT.isVector()) {
Sanjay Patel7bd228a2014-09-11 15:45:27 +00007002 // This just handles C1 * C2 for vectors. Other vector folds are below.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007003 SDValue FoldedVOp = SimplifyVBinOp(N);
Sanjay Patel7bd228a2014-09-11 15:45:27 +00007004 if (FoldedVOp.getNode())
7005 return FoldedVOp;
7006 // Canonicalize vector constant to RHS.
7007 if (N0.getOpcode() == ISD::BUILD_VECTOR &&
7008 N1.getOpcode() != ISD::BUILD_VECTOR)
7009 if (auto *BV0 = dyn_cast<BuildVectorSDNode>(N0))
7010 if (BV0->isConstant())
7011 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
Dan Gohman80f9f072007-07-13 20:03:40 +00007012 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007013
Nate Begemanec48a1b2005-10-17 20:40:11 +00007014 // fold (fmul c1, c2) -> c1*c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007015 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007016 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
Sanjay Patel394c3332014-09-08 20:16:42 +00007017
Nate Begemanec48a1b2005-10-17 20:40:11 +00007018 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00007019 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007020 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
Sanjay Patel394c3332014-09-08 20:16:42 +00007021
Owen Andersonb5f167c2012-05-02 21:32:35 +00007022 // fold (fmul A, 1.0) -> A
7023 if (N1CFP && N1CFP->isExactlyValue(1.0))
7024 return N0;
Matt Arsenault6cc00422014-08-16 10:14:19 +00007025
Sanjay Patel394c3332014-09-08 20:16:42 +00007026 if (Options.UnsafeFPMath) {
7027 // fold (fmul A, 0) -> 0
7028 if (N1CFP && N1CFP->getValueAPF().isZero())
7029 return N1;
7030
7031 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
Sanjay Patel7bd228a2014-09-11 15:45:27 +00007032 if (N0.getOpcode() == ISD::FMUL) {
7033 // Fold scalars or any vector constants (not just splats).
7034 // This fold is done in general by InstCombine, but extra fmul insts
7035 // may have been generated during lowering.
7036 SDValue N01 = N0.getOperand(1);
7037 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
7038 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
7039 if ((N1CFP && isConstOrConstSplatFP(N01)) ||
7040 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
7041 SDLoc SL(N);
7042 SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, N01, N1);
7043 return DAG.getNode(ISD::FMUL, SL, VT, N0.getOperand(0), MulConsts);
7044 }
Matt Arsenaultc1a71212014-09-02 19:02:53 +00007045 }
7046
Sanjay Patel394c3332014-09-08 20:16:42 +00007047 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
Matt Arsenaultc1a71212014-09-02 19:02:53 +00007048 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
7049 // during an early run of DAGCombiner can prevent folding with fmuls
7050 // inserted during lowering.
7051 if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
7052 SDLoc SL(N);
7053 const SDValue Two = DAG.getConstantFP(2.0, VT);
7054 SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, Two, N1);
7055 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), MulConsts);
7056 }
7057 }
7058
Nate Begemanec48a1b2005-10-17 20:40:11 +00007059 // fold (fmul X, 2.0) -> (fadd X, X)
7060 if (N1CFP && N1CFP->isExactlyValue(+2.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007061 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
Sanjay Patel394c3332014-09-08 20:16:42 +00007062
Dan Gohmanb7170912009-08-10 16:50:32 +00007063 // fold (fmul X, -1.0) -> (fneg X)
Chris Lattnere49c9742007-05-14 22:04:50 +00007064 if (N1CFP && N1CFP->isExactlyValue(-1.0))
Dan Gohman1f3411d2009-01-22 21:58:43 +00007065 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007066 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007067
Bill Wendling3dc5d242009-01-30 22:57:07 +00007068 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
Sanjay Patel78614bf2014-08-28 15:53:16 +00007069 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7070 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
Chris Lattnere49c9742007-05-14 22:04:50 +00007071 // Both can be negated for free, check to see if at least one is cheaper
7072 // negated.
7073 if (LHSNeg == 2 || RHSNeg == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007074 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007075 GetNegatedExpression(N0, DAG, LegalOperations),
7076 GetNegatedExpression(N1, DAG, LegalOperations));
Chris Lattnere49c9742007-05-14 22:04:50 +00007077 }
7078 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007079
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007080 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00007081}
7082
Owen Anderson41b06652012-05-02 22:17:40 +00007083SDValue DAGCombiner::visitFMA(SDNode *N) {
7084 SDValue N0 = N->getOperand(0);
7085 SDValue N1 = N->getOperand(1);
7086 SDValue N2 = N->getOperand(2);
7087 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7088 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7089 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007090 SDLoc dl(N);
Sanjay Patel78614bf2014-08-28 15:53:16 +00007091 const TargetOptions &Options = DAG.getTarget().Options;
Owen Anderson9d5a8c22014-08-02 08:45:33 +00007092
7093 // Constant fold FMA.
7094 if (isa<ConstantFPSDNode>(N0) &&
7095 isa<ConstantFPSDNode>(N1) &&
7096 isa<ConstantFPSDNode>(N2)) {
7097 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
7098 }
7099
Sanjay Patel78614bf2014-08-28 15:53:16 +00007100 if (Options.UnsafeFPMath) {
Owen Andersonb351c8d2012-11-01 02:00:53 +00007101 if (N0CFP && N0CFP->isZero())
7102 return N2;
7103 if (N1CFP && N1CFP->isZero())
7104 return N2;
7105 }
Owen Anderson41b06652012-05-02 22:17:40 +00007106 if (N0CFP && N0CFP->isExactlyValue(1.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007107 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
Owen Anderson41b06652012-05-02 22:17:40 +00007108 if (N1CFP && N1CFP->isExactlyValue(1.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007109 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
Owen Anderson41b06652012-05-02 22:17:40 +00007110
Owen Andersonc7aaf522012-05-30 18:50:39 +00007111 // Canonicalize (fma c, x, y) -> (fma x, c, y)
Owen Anderson0eda3e12012-05-30 18:54:50 +00007112 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007113 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
Owen Andersonc7aaf522012-05-30 18:50:39 +00007114
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007115 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
Sanjay Patel78614bf2014-08-28 15:53:16 +00007116 if (Options.UnsafeFPMath && N1CFP &&
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007117 N2.getOpcode() == ISD::FMUL &&
7118 N0 == N2.getOperand(0) &&
7119 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
7120 return DAG.getNode(ISD::FMUL, dl, VT, N0,
7121 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
7122 }
7123
7124
7125 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
Sanjay Patel78614bf2014-08-28 15:53:16 +00007126 if (Options.UnsafeFPMath &&
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007127 N0.getOpcode() == ISD::FMUL && N1CFP &&
7128 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
7129 return DAG.getNode(ISD::FMA, dl, VT,
7130 N0.getOperand(0),
7131 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
7132 N2);
7133 }
7134
7135 // (fma x, 1, y) -> (fadd x, y)
7136 // (fma x, -1, y) -> (fadd (fneg x), y)
7137 if (N1CFP) {
7138 if (N1CFP->isExactlyValue(1.0))
7139 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
7140
7141 if (N1CFP->isExactlyValue(-1.0) &&
7142 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
7143 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007144 AddToWorklist(RHSNeg.getNode());
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007145 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
7146 }
7147 }
7148
7149 // (fma x, c, x) -> (fmul x, (c+1))
Sanjay Patel78614bf2014-08-28 15:53:16 +00007150 if (Options.UnsafeFPMath && N1CFP && N0 == N2)
Stephen Lin8e8424e2013-07-09 00:44:49 +00007151 return DAG.getNode(ISD::FMUL, dl, VT, N0,
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007152 DAG.getNode(ISD::FADD, dl, VT,
7153 N1, DAG.getConstantFP(1.0, VT)));
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007154
7155 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
Sanjay Patel78614bf2014-08-28 15:53:16 +00007156 if (Options.UnsafeFPMath && N1CFP &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00007157 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
7158 return DAG.getNode(ISD::FMUL, dl, VT, N0,
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007159 DAG.getNode(ISD::FADD, dl, VT,
7160 N1, DAG.getConstantFP(-1.0, VT)));
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007161
7162
Owen Anderson41b06652012-05-02 22:17:40 +00007163 return SDValue();
7164}
7165
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007166SDValue DAGCombiner::visitFDIV(SDNode *N) {
7167 SDValue N0 = N->getOperand(0);
7168 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00007169 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7170 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007171 EVT VT = N->getValueType(0);
Sanjay Patelbdf1e382014-09-26 23:01:47 +00007172 SDLoc DL(N);
Sanjay Patel78614bf2014-08-28 15:53:16 +00007173 const TargetOptions &Options = DAG.getTarget().Options;
Chris Lattner6f3b5772005-09-28 22:28:18 +00007174
Dan Gohmana8665142007-06-25 16:23:39 +00007175 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00007176 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007177 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00007178 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00007179 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007180
Nate Begeman569c4392006-01-18 22:35:16 +00007181 // fold (fdiv c1, c2) -> c1/c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007182 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007183 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007184
Sanjay Patelb67bd262014-09-21 15:19:15 +00007185 if (Options.UnsafeFPMath) {
7186 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
7187 if (N1CFP) {
7188 // Compute the reciprocal 1.0 / c2.
7189 APFloat N1APF = N1CFP->getValueAPF();
7190 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
7191 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
7192 // Only do the transform if the reciprocal is a legal fp immediate that
7193 // isn't too nasty (eg NaN, denormal, ...).
7194 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
7195 (!LegalOperations ||
7196 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
7197 // backend)... we should handle this gracefully after Legalize.
7198 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
7199 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
7200 TLI.isFPImmLegal(Recip, VT)))
7201 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
7202 DAG.getConstantFP(Recip, VT));
7203 }
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007204
Sanjay Patelb67bd262014-09-21 15:19:15 +00007205 // If this FDIV is part of a reciprocal square root, it may be folded
7206 // into a target-specific square root estimate instruction.
Sanjay Patelbdf1e382014-09-26 23:01:47 +00007207 if (N1.getOpcode() == ISD::FSQRT) {
7208 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
Sanjay Patelbdf1e382014-09-26 23:01:47 +00007209 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7210 }
7211 } else if (N1.getOpcode() == ISD::FP_EXTEND &&
7212 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7213 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
Sanjay Patelbdf1e382014-09-26 23:01:47 +00007214 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
7215 AddToWorklist(RV.getNode());
7216 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7217 }
7218 } else if (N1.getOpcode() == ISD::FP_ROUND &&
7219 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7220 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
Sanjay Patelbdf1e382014-09-26 23:01:47 +00007221 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
7222 AddToWorklist(RV.getNode());
7223 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7224 }
Sanjay Patel7bc91852014-10-06 19:31:18 +00007225 } else if (N1.getOpcode() == ISD::FMUL) {
7226 // Look through an FMUL. Even though this won't remove the FDIV directly,
7227 // it's still worthwhile to get rid of the FSQRT if possible.
7228 SDValue SqrtOp;
7229 SDValue OtherOp;
7230 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7231 SqrtOp = N1.getOperand(0);
7232 OtherOp = N1.getOperand(1);
7233 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
7234 SqrtOp = N1.getOperand(1);
7235 OtherOp = N1.getOperand(0);
7236 }
7237 if (SqrtOp.getNode()) {
7238 // We found a FSQRT, so try to make this fold:
7239 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
7240 if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
Sanjay Patel7bc91852014-10-06 19:31:18 +00007241 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
7242 AddToWorklist(RV.getNode());
7243 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7244 }
7245 }
Sanjay Patelbdf1e382014-09-26 23:01:47 +00007246 }
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007247
Sanjay Patelbdf1e382014-09-26 23:01:47 +00007248 // Fold into a reciprocal estimate and multiply instead of a real divide.
7249 if (SDValue RV = BuildReciprocalEstimate(N1)) {
7250 AddToWorklist(RV.getNode());
7251 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7252 }
Duncan Sands5f8397a2012-04-07 20:04:00 +00007253 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007254
Bill Wendling3dc5d242009-01-30 22:57:07 +00007255 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
Sanjay Patel78614bf2014-08-28 15:53:16 +00007256 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7257 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
Chris Lattnere49c9742007-05-14 22:04:50 +00007258 // Both can be negated for free, check to see if at least one is cheaper
7259 // negated.
7260 if (LHSNeg == 2 || RHSNeg == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007261 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007262 GetNegatedExpression(N0, DAG, LegalOperations),
7263 GetNegatedExpression(N1, DAG, LegalOperations));
Chris Lattnere49c9742007-05-14 22:04:50 +00007264 }
7265 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007266
Hao Liu44e5d7a2014-11-21 06:39:58 +00007267 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
7268 // reciprocal.
7269 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
7270 // Notice that this is not always beneficial. One reason is different target
7271 // may have different costs for FDIV and FMUL, so sometimes the cost of two
7272 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
7273 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
7274 if (Options.UnsafeFPMath) {
7275 // Skip if current node is a reciprocal.
7276 if (N0CFP && N0CFP->isExactlyValue(1.0))
7277 return SDValue();
7278
7279 SmallVector<SDNode *, 4> Users;
7280 // Find all FDIV users of the same divisor.
7281 for (SDNode::use_iterator UI = N1.getNode()->use_begin(),
7282 UE = N1.getNode()->use_end();
7283 UI != UE; ++UI) {
7284 SDNode *User = UI.getUse().getUser();
7285 if (User->getOpcode() == ISD::FDIV && User->getOperand(1) == N1)
7286 Users.push_back(User);
7287 }
7288
7289 if (TLI.combineRepeatedFPDivisors(Users.size())) {
7290 SDValue FPOne = DAG.getConstantFP(1.0, VT); // floating point 1.0
7291 SDValue Reciprocal = DAG.getNode(ISD::FDIV, SDLoc(N), VT, FPOne, N1);
7292
7293 // Dividend / Divisor -> Dividend * Reciprocal
7294 for (auto I = Users.begin(), E = Users.end(); I != E; ++I) {
7295 if ((*I)->getOperand(0) != FPOne) {
7296 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(*I), VT,
7297 (*I)->getOperand(0), Reciprocal);
7298 DAG.ReplaceAllUsesWith(*I, NewNode.getNode());
7299 }
7300 }
7301 return SDValue();
7302 }
7303 }
7304
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007305 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00007306}
7307
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007308SDValue DAGCombiner::visitFREM(SDNode *N) {
7309 SDValue N0 = N->getOperand(0);
7310 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00007311 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7312 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007313 EVT VT = N->getValueType(0);
Chris Lattner6f3b5772005-09-28 22:28:18 +00007314
Nate Begeman569c4392006-01-18 22:35:16 +00007315 // fold (frem c1, c2) -> fmod(c1,c2)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007316 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007317 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
Dan Gohmana8665142007-06-25 16:23:39 +00007318
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007319 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00007320}
7321
Sanjay Patelbdf1e382014-09-26 23:01:47 +00007322SDValue DAGCombiner::visitFSQRT(SDNode *N) {
7323 if (DAG.getTarget().Options.UnsafeFPMath) {
Sanjay Patel3d497cd2014-10-09 21:26:35 +00007324 // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
Sanjay Patelbdf1e382014-09-26 23:01:47 +00007325 if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
Sanjay Patel3d497cd2014-10-09 21:26:35 +00007326 EVT VT = RV.getValueType();
7327 RV = DAG.getNode(ISD::FMUL, SDLoc(N), VT, N->getOperand(0), RV);
7328 AddToWorklist(RV.getNode());
Sanjay Patelbdf1e382014-09-26 23:01:47 +00007329
Sanjay Patel3d497cd2014-10-09 21:26:35 +00007330 // Unfortunately, RV is now NaN if the input was exactly 0.
7331 // Select out this case and force the answer to 0.
7332 SDValue Zero = DAG.getConstantFP(0.0, VT);
7333 SDValue ZeroCmp =
7334 DAG.getSetCC(SDLoc(N), TLI.getSetCCResultType(*DAG.getContext(), VT),
7335 N->getOperand(0), Zero, ISD::SETEQ);
7336 AddToWorklist(ZeroCmp.getNode());
7337 AddToWorklist(RV.getNode());
7338
7339 RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
7340 SDLoc(N), VT, ZeroCmp, Zero, RV);
7341 return RV;
Sanjay Patelbdf1e382014-09-26 23:01:47 +00007342 }
7343 }
7344 return SDValue();
7345}
7346
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007347SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
7348 SDValue N0 = N->getOperand(0);
7349 SDValue N1 = N->getOperand(1);
Chris Lattner3bc40502006-03-05 05:30:57 +00007350 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7351 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007352 EVT VT = N->getValueType(0);
Chris Lattner3bc40502006-03-05 05:30:57 +00007353
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007354 if (N0CFP && N1CFP) // Constant fold
Andrew Trickef9de2a2013-05-25 02:42:55 +00007355 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007356
Chris Lattner3bc40502006-03-05 05:30:57 +00007357 if (N1CFP) {
Dale Johannesenb6d2bec2007-08-26 01:18:27 +00007358 const APFloat& V = N1CFP->getValueAPF();
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00007359 // copysign(x, c1) -> fabs(x) iff ispos(c1)
7360 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
Dan Gohman1f3411d2009-01-22 21:58:43 +00007361 if (!V.isNegative()) {
7362 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007363 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Dan Gohman1f3411d2009-01-22 21:58:43 +00007364 } else {
7365 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007366 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7367 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
Dan Gohman1f3411d2009-01-22 21:58:43 +00007368 }
Chris Lattner3bc40502006-03-05 05:30:57 +00007369 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007370
Chris Lattner3bc40502006-03-05 05:30:57 +00007371 // copysign(fabs(x), y) -> copysign(x, y)
7372 // copysign(fneg(x), y) -> copysign(x, y)
7373 // copysign(copysign(x,z), y) -> copysign(x, y)
7374 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7375 N0.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007376 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007377 N0.getOperand(0), N1);
Chris Lattner3bc40502006-03-05 05:30:57 +00007378
7379 // copysign(x, abs(y)) -> abs(x)
7380 if (N1.getOpcode() == ISD::FABS)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007381 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007382
Chris Lattner3bc40502006-03-05 05:30:57 +00007383 // copysign(x, copysign(y,z)) -> copysign(x, z)
7384 if (N1.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007385 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007386 N0, N1.getOperand(1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00007387
Chris Lattner3bc40502006-03-05 05:30:57 +00007388 // copysign(x, fp_extend(y)) -> copysign(x, y)
7389 // copysign(x, fp_round(y)) -> copysign(x, y)
7390 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007391 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007392 N0, N1.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00007393
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007394 return SDValue();
Chris Lattner3bc40502006-03-05 05:30:57 +00007395}
7396
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007397SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7398 SDValue N0 = N->getOperand(0);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00007399 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007400 EVT VT = N->getValueType(0);
7401 EVT OpVT = N0.getValueType();
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007402
Nate Begeman21158fc2005-09-01 00:19:25 +00007403 // fold (sint_to_fp c1) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007404 if (N0C &&
Stuart Hastings6b4007d2011-03-02 19:36:30 +00007405 // ...but only if the target supports immediate floating-point values
Eli Friedman9d448e42011-11-12 00:35:34 +00007406 (!LegalOperations ||
Evan Cheng4c0bd962011-06-21 06:01:08 +00007407 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007408 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007409
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007410 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7411 // but UINT_TO_FP is legal on this target, try to convert.
Dan Gohman4aa18462009-01-28 17:46:25 +00007412 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7413 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
Scott Michelcf0da6c2009-02-17 22:15:04 +00007414 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007415 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007416 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007417 }
Bill Wendling0bd29742009-01-30 23:15:49 +00007418
Alp Tokercb402912014-01-24 17:20:08 +00007419 // The next optimizations are desirable only if SELECT_CC can be lowered.
Tom Stellard3787b122014-06-10 16:01:29 +00007420 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
Nadav Rotem90560762012-07-23 07:59:50 +00007421 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7422 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7423 !VT.isVector() &&
7424 (!LegalOperations ||
7425 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7426 SDValue Ops[] =
7427 { N0.getOperand(0), N0.getOperand(1),
7428 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7429 N0.getOperand(2) };
Craig Topper48d114b2014-04-26 18:35:24 +00007430 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
Nadav Rotem90560762012-07-23 07:59:50 +00007431 }
Owen Andersond4b841f2012-07-09 20:31:12 +00007432
Nadav Rotem90560762012-07-23 07:59:50 +00007433 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7434 // (select_cc x, y, 1.0, 0.0,, cc)
7435 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7436 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7437 (!LegalOperations ||
7438 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7439 SDValue Ops[] =
7440 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7441 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7442 N0.getOperand(0).getOperand(2) };
Craig Topper48d114b2014-04-26 18:35:24 +00007443 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
Nadav Rotem90560762012-07-23 07:59:50 +00007444 }
Owen Andersond4b841f2012-07-09 20:31:12 +00007445 }
7446
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007447 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007448}
7449
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007450SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7451 SDValue N0 = N->getOperand(0);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00007452 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007453 EVT VT = N->getValueType(0);
7454 EVT OpVT = N0.getValueType();
Nate Begeman569c4392006-01-18 22:35:16 +00007455
Nate Begeman21158fc2005-09-01 00:19:25 +00007456 // fold (uint_to_fp c1) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007457 if (N0C &&
Stuart Hastings6b4007d2011-03-02 19:36:30 +00007458 // ...but only if the target supports immediate floating-point values
Eli Friedman9d448e42011-11-12 00:35:34 +00007459 (!LegalOperations ||
Evan Cheng4c0bd962011-06-21 06:01:08 +00007460 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007461 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007462
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007463 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7464 // but SINT_TO_FP is legal on this target, try to convert.
Dan Gohman4aa18462009-01-28 17:46:25 +00007465 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7466 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
Scott Michelcf0da6c2009-02-17 22:15:04 +00007467 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007468 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007469 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007470 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007471
Alp Tokercb402912014-01-24 17:20:08 +00007472 // The next optimizations are desirable only if SELECT_CC can be lowered.
Tom Stellard3787b122014-06-10 16:01:29 +00007473 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
Nadav Rotem90560762012-07-23 07:59:50 +00007474 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
Owen Andersond4b841f2012-07-09 20:31:12 +00007475
Nadav Rotem90560762012-07-23 07:59:50 +00007476 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7477 (!LegalOperations ||
7478 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7479 SDValue Ops[] =
7480 { N0.getOperand(0), N0.getOperand(1),
7481 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
7482 N0.getOperand(2) };
Craig Topper48d114b2014-04-26 18:35:24 +00007483 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
Nadav Rotem90560762012-07-23 07:59:50 +00007484 }
7485 }
Owen Andersond4b841f2012-07-09 20:31:12 +00007486
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007487 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007488}
7489
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007490SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7491 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007492 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007493 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007494
Nate Begeman21158fc2005-09-01 00:19:25 +00007495 // fold (fp_to_sint c1fp) -> c1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00007496 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007497 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
Bill Wendling0bd29742009-01-30 23:15:49 +00007498
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007499 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007500}
7501
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007502SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7503 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007504 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007505 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007506
Nate Begeman21158fc2005-09-01 00:19:25 +00007507 // fold (fp_to_uint c1fp) -> c1
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007508 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007509 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
Bill Wendling0bd29742009-01-30 23:15:49 +00007510
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007511 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007512}
7513
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007514SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7515 SDValue N0 = N->getOperand(0);
7516 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00007517 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007518 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007519
Nate Begeman21158fc2005-09-01 00:19:25 +00007520 // fold (fp_round c1fp) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007521 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007522 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007523
Chris Lattner8bb6cb72006-03-13 06:26:26 +00007524 // fold (fp_round (fp_extend x)) -> x
7525 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7526 return N0.getOperand(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007527
Chris Lattner0feb1b02008-01-24 06:45:35 +00007528 // fold (fp_round (fp_round x)) -> (fp_round x)
7529 if (N0.getOpcode() == ISD::FP_ROUND) {
7530 // This is a value preserving truncation if both round's are.
7531 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00007532 N0.getNode()->getConstantOperandVal(1) == 1;
Andrew Trickef9de2a2013-05-25 02:42:55 +00007533 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
Chris Lattner0feb1b02008-01-24 06:45:35 +00007534 DAG.getIntPtrConstant(IsTrunc));
7535 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007536
Chris Lattner8bb6cb72006-03-13 06:26:26 +00007537 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
Gabor Greiff304a7a2008-08-28 21:40:38 +00007538 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007539 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007540 N0.getOperand(0), N1);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007541 AddToWorklist(Tmp.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00007542 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007543 Tmp, N0.getOperand(1));
Chris Lattner8bb6cb72006-03-13 06:26:26 +00007544 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007545
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007546 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007547}
7548
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007549SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7550 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007551 EVT VT = N->getValueType(0);
7552 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
Nate Begeman7cea6ef2005-09-02 21:18:40 +00007553 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007554
Nate Begeman21158fc2005-09-01 00:19:25 +00007555 // fold (fp_round_inreg c1fp) -> c1fp
Chris Lattner4041ab62010-04-15 04:48:01 +00007556 if (N0CFP && isTypeLegal(EVT)) {
Dan Gohmanec270fb2008-09-12 18:08:03 +00007557 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007558 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
Nate Begeman21158fc2005-09-01 00:19:25 +00007559 }
Bill Wendling0bd29742009-01-30 23:15:49 +00007560
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007561 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007562}
7563
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007564SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7565 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007566 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007567 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007568
Chris Lattner5919b482007-12-29 06:55:23 +00007569 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
Scott Michelcf0da6c2009-02-17 22:15:04 +00007570 if (N->hasOneUse() &&
Dan Gohman8e4ac9b2009-01-26 04:35:06 +00007571 N->use_begin()->getOpcode() == ISD::FP_ROUND)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007572 return SDValue();
Chris Lattner72733e52008-01-17 07:00:52 +00007573
Nate Begeman21158fc2005-09-01 00:19:25 +00007574 // fold (fp_extend c1fp) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007575 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007576 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
Chris Lattner72733e52008-01-17 07:00:52 +00007577
7578 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7579 // value of X.
Gabor Greife12264b2008-08-30 19:29:20 +00007580 if (N0.getOpcode() == ISD::FP_ROUND
7581 && N0.getNode()->getConstantOperandVal(1) == 1) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007582 SDValue In = N0.getOperand(0);
Chris Lattner72733e52008-01-17 07:00:52 +00007583 if (In.getValueType() == VT) return In;
Duncan Sands11dd4242008-06-08 20:54:56 +00007584 if (VT.bitsLT(In.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007585 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007586 In, N0.getOperand(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00007587 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
Chris Lattner72733e52008-01-17 07:00:52 +00007588 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007589
Chris Lattner72733e52008-01-17 07:00:52 +00007590 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
Hal Finkeldbc7a8a2013-10-04 22:18:12 +00007591 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Tim Northover7f3e11e2014-07-16 15:37:24 +00007592 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00007593 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007594 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007595 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00007596 LN0->getBasePtr(), N0.getValueType(),
7597 LN0->getMemOperand());
Chris Lattner3d265772006-05-05 21:34:35 +00007598 CombineTo(N, ExtLoad);
Bill Wendling0bd29742009-01-30 23:15:49 +00007599 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00007600 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
Bill Wendling0bd29742009-01-30 23:15:49 +00007601 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
Chris Lattner3d265772006-05-05 21:34:35 +00007602 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007603 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattner3d265772006-05-05 21:34:35 +00007604 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00007605
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007606 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007607}
7608
Sanjay Patelccd26762014-08-28 21:51:37 +00007609SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7610 SDValue N0 = N->getOperand(0);
7611 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7612 EVT VT = N->getValueType(0);
7613
7614 // fold (fceil c1) -> fceil(c1)
7615 if (N0CFP)
7616 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7617
7618 return SDValue();
7619}
7620
7621SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7622 SDValue N0 = N->getOperand(0);
7623 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7624 EVT VT = N->getValueType(0);
7625
7626 // fold (ftrunc c1) -> ftrunc(c1)
7627 if (N0CFP)
7628 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7629
7630 return SDValue();
7631}
7632
7633SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7634 SDValue N0 = N->getOperand(0);
7635 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7636 EVT VT = N->getValueType(0);
7637
7638 // fold (ffloor c1) -> ffloor(c1)
7639 if (N0CFP)
7640 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7641
7642 return SDValue();
7643}
7644
7645// FIXME: FNEG and FABS have a lot in common; refactor.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007646SDValue DAGCombiner::visitFNEG(SDNode *N) {
7647 SDValue N0 = N->getOperand(0);
Anton Korobeynikova6faf602009-10-20 21:37:45 +00007648 EVT VT = N->getValueType(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007649
Craig Topper82384612012-09-11 01:45:21 +00007650 if (VT.isVector()) {
7651 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7652 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topper03f39772012-09-09 22:58:45 +00007653 }
7654
Sanjay Patelccd26762014-08-28 21:51:37 +00007655 // Constant fold FNEG.
7656 if (isa<ConstantFPSDNode>(N0))
7657 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N->getOperand(0));
7658
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00007659 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7660 &DAG.getTarget().Options))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007661 return GetNegatedExpression(N0, DAG, LegalOperations);
Dan Gohman9a708232007-07-02 15:48:56 +00007662
Sanjay Patel35d31332014-08-14 15:15:28 +00007663 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
Chris Lattner888560d2008-01-27 17:42:27 +00007664 // constant pool values.
Sanjay Patelccd26762014-08-28 21:51:37 +00007665 if (!TLI.isFNegFree(VT) &&
7666 N0.getOpcode() == ISD::BITCAST &&
Sanjay Patel35d31332014-08-14 15:15:28 +00007667 N0.getNode()->hasOneUse()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007668 SDValue Int = N0.getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007669 EVT IntVT = Int.getValueType();
Duncan Sands13237ac2008-06-06 12:08:01 +00007670 if (IntVT.isInteger() && !IntVT.isVector()) {
Sanjay Patel35d31332014-08-14 15:15:28 +00007671 APInt SignMask;
7672 if (N0.getValueType().isVector()) {
7673 // For a vector, get a mask such as 0x80... per scalar element
7674 // and splat it.
7675 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7676 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7677 } else {
7678 // For a scalar, just generate 0x80...
7679 SignMask = APInt::getSignBit(IntVT.getSizeInBits());
7680 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00007681 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
Sanjay Patel35d31332014-08-14 15:15:28 +00007682 DAG.getConstant(SignMask, IntVT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007683 AddToWorklist(Int.getNode());
Sanjay Patel35d31332014-08-14 15:15:28 +00007684 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
Chris Lattner888560d2008-01-27 17:42:27 +00007685 }
7686 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007687
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007688 // (fneg (fmul c, x)) -> (fmul -c, x)
7689 if (N0.getOpcode() == ISD::FMUL) {
7690 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
Tim Northover820e0412014-05-02 17:25:02 +00007691 if (CFP1) {
7692 APFloat CVal = CFP1->getValueAPF();
7693 CVal.changeSign();
7694 if (Level >= AfterLegalizeDAG &&
7695 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
7696 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
7697 return DAG.getNode(
7698 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
7699 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
7700 }
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007701 }
7702
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007703 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007704}
7705
Matt Arsenault7c936902014-10-21 23:01:01 +00007706SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
7707 SDValue N0 = N->getOperand(0);
7708 SDValue N1 = N->getOperand(1);
7709 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7710 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7711
7712 if (N0CFP && N1CFP) {
7713 const APFloat &C0 = N0CFP->getValueAPF();
7714 const APFloat &C1 = N1CFP->getValueAPF();
7715 return DAG.getConstantFP(minnum(C0, C1), N->getValueType(0));
7716 }
7717
7718 if (N0CFP) {
7719 EVT VT = N->getValueType(0);
7720 // Canonicalize to constant on RHS.
7721 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
7722 }
7723
7724 return SDValue();
7725}
7726
7727SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
7728 SDValue N0 = N->getOperand(0);
7729 SDValue N1 = N->getOperand(1);
7730 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7731 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7732
7733 if (N0CFP && N1CFP) {
7734 const APFloat &C0 = N0CFP->getValueAPF();
7735 const APFloat &C1 = N1CFP->getValueAPF();
7736 return DAG.getConstantFP(maxnum(C0, C1), N->getValueType(0));
7737 }
7738
7739 if (N0CFP) {
7740 EVT VT = N->getValueType(0);
7741 // Canonicalize to constant on RHS.
7742 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
7743 }
7744
7745 return SDValue();
7746}
7747
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007748SDValue DAGCombiner::visitFABS(SDNode *N) {
7749 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007750 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007751
Craig Topper82384612012-09-11 01:45:21 +00007752 if (VT.isVector()) {
7753 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7754 if (FoldedVOp.getNode()) return FoldedVOp;
7755 }
7756
Nate Begeman21158fc2005-09-01 00:19:25 +00007757 // fold (fabs c1) -> fabs(c1)
Sanjay Patelccd26762014-08-28 21:51:37 +00007758 if (isa<ConstantFPSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007759 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007760
Nate Begeman21158fc2005-09-01 00:19:25 +00007761 // fold (fabs (fabs x)) -> (fabs x)
Chris Lattner3bc40502006-03-05 05:30:57 +00007762 if (N0.getOpcode() == ISD::FABS)
Nate Begemand23739d2005-09-06 04:43:02 +00007763 return N->getOperand(0);
Sanjay Patelccd26762014-08-28 21:51:37 +00007764
Nate Begeman21158fc2005-09-01 00:19:25 +00007765 // fold (fabs (fneg x)) -> (fabs x)
Chris Lattner3bc40502006-03-05 05:30:57 +00007766 // fold (fabs (fcopysign x, y)) -> (fabs x)
7767 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007768 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00007769
Sanjay Patel8e5beb62014-08-05 17:35:22 +00007770 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
Chris Lattner888560d2008-01-27 17:42:27 +00007771 // constant pool values.
Stephen Lincfe7f352013-07-08 00:37:03 +00007772 if (!TLI.isFAbsFree(VT) &&
Sanjay Patel8e5beb62014-08-05 17:35:22 +00007773 N0.getOpcode() == ISD::BITCAST &&
7774 N0.getNode()->hasOneUse()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007775 SDValue Int = N0.getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007776 EVT IntVT = Int.getValueType();
Duncan Sands13237ac2008-06-06 12:08:01 +00007777 if (IntVT.isInteger() && !IntVT.isVector()) {
Sanjay Patel8e5beb62014-08-05 17:35:22 +00007778 APInt SignMask;
7779 if (N0.getValueType().isVector()) {
7780 // For a vector, get a mask such as 0x7f... per scalar element
7781 // and splat it.
7782 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7783 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7784 } else {
7785 // For a scalar, just generate 0x7f...
7786 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
7787 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00007788 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
Sanjay Patel8e5beb62014-08-05 17:35:22 +00007789 DAG.getConstant(SignMask, IntVT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007790 AddToWorklist(Int.getNode());
Sanjay Patel8e5beb62014-08-05 17:35:22 +00007791 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
Chris Lattner888560d2008-01-27 17:42:27 +00007792 }
7793 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007794
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007795 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007796}
7797
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007798SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7799 SDValue Chain = N->getOperand(0);
7800 SDValue N1 = N->getOperand(1);
7801 SDValue N2 = N->getOperand(2);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007802
Dan Gohman82e80012009-11-17 00:47:23 +00007803 // If N is a constant we could fold this into a fallthrough or unconditional
7804 // branch. However that doesn't happen very often in normal code, because
7805 // Instcombine/SimplifyCFG should have handled the available opportunities.
7806 // If we did this folding here, it would be necessary to update the
7807 // MachineBasicBlock CFG, which is awkward.
7808
Nate Begeman7e7f4392006-02-01 07:19:44 +00007809 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7810 // on the target.
Scott Michelcf0da6c2009-02-17 22:15:04 +00007811 if (N1.getOpcode() == ISD::SETCC &&
Tom Stellardb1588fc2013-03-08 15:36:57 +00007812 TLI.isOperationLegalOrCustom(ISD::BR_CC,
7813 N1.getOperand(0).getValueType())) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007814 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
Bill Wendling306bfc22009-01-30 23:27:35 +00007815 Chain, N1.getOperand(2),
Nate Begeman7e7f4392006-02-01 07:19:44 +00007816 N1.getOperand(0), N1.getOperand(1), N2);
7817 }
Bill Wendling306bfc22009-01-30 23:27:35 +00007818
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007819 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7820 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7821 (N1.getOperand(0).hasOneUse() &&
7822 N1.getOperand(0).getOpcode() == ISD::SRL))) {
Craig Topperc0196b12014-04-14 00:51:57 +00007823 SDNode *Trunc = nullptr;
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007824 if (N1.getOpcode() == ISD::TRUNCATE) {
7825 // Look pass the truncate.
7826 Trunc = N1.getNode();
7827 N1 = N1.getOperand(0);
7828 }
Evan Cheng166a4e62010-01-06 19:38:29 +00007829
Bill Wendlingaa28be62009-03-26 06:14:09 +00007830 // Match this pattern so that we can generate simpler code:
7831 //
7832 // %a = ...
7833 // %b = and i32 %a, 2
7834 // %c = srl i32 %b, 1
7835 // brcond i32 %c ...
7836 //
7837 // into
Wesley Peck527da1b2010-11-23 03:31:01 +00007838 //
Bill Wendlingaa28be62009-03-26 06:14:09 +00007839 // %a = ...
Evan Cheng166a4e62010-01-06 19:38:29 +00007840 // %b = and i32 %a, 2
Bill Wendlingaa28be62009-03-26 06:14:09 +00007841 // %c = setcc eq %b, 0
7842 // brcond %c ...
7843 //
7844 // This applies only when the AND constant value has one bit set and the
7845 // SRL constant is equal to the log2 of the AND constant. The back-end is
7846 // smart enough to convert the result into a TEST/JMP sequence.
7847 SDValue Op0 = N1.getOperand(0);
7848 SDValue Op1 = N1.getOperand(1);
7849
7850 if (Op0.getOpcode() == ISD::AND &&
Bill Wendlingaa28be62009-03-26 06:14:09 +00007851 Op1.getOpcode() == ISD::Constant) {
Bill Wendlingaa28be62009-03-26 06:14:09 +00007852 SDValue AndOp1 = Op0.getOperand(1);
7853
7854 if (AndOp1.getOpcode() == ISD::Constant) {
7855 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7856
7857 if (AndConst.isPowerOf2() &&
7858 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7859 SDValue SetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00007860 DAG.getSetCC(SDLoc(N),
Matt Arsenault758659232013-05-18 00:21:46 +00007861 getSetCCResultType(Op0.getValueType()),
Bill Wendlingaa28be62009-03-26 06:14:09 +00007862 Op0, DAG.getConstant(0, Op0.getValueType()),
7863 ISD::SETNE);
7864
Andrew Trickef9de2a2013-05-25 02:42:55 +00007865 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng166a4e62010-01-06 19:38:29 +00007866 MVT::Other, Chain, SetCC, N2);
7867 // Don't add the new BRCond into the worklist or else SimplifySelectCC
7868 // will convert it back to (X & C1) >> C2.
7869 CombineTo(N, NewBRCond, false);
7870 // Truncate is dead.
Chandler Carruth18066972014-08-02 10:02:07 +00007871 if (Trunc)
7872 deleteAndRecombine(Trunc);
Bill Wendlingaa28be62009-03-26 06:14:09 +00007873 // Replace the uses of SRL with SETCC
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007874 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007875 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
Chandler Carruth18066972014-08-02 10:02:07 +00007876 deleteAndRecombine(N1.getNode());
Evan Cheng166a4e62010-01-06 19:38:29 +00007877 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Bill Wendlingaa28be62009-03-26 06:14:09 +00007878 }
7879 }
7880 }
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007881
7882 if (Trunc)
7883 // Restore N1 if the above transformation doesn't match.
7884 N1 = N->getOperand(1);
Bill Wendlingaa28be62009-03-26 06:14:09 +00007885 }
Wesley Peck527da1b2010-11-23 03:31:01 +00007886
Evan Cheng228c31f2010-02-27 07:36:59 +00007887 // Transform br(xor(x, y)) -> br(x != y)
7888 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7889 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7890 SDNode *TheXor = N1.getNode();
7891 SDValue Op0 = TheXor->getOperand(0);
7892 SDValue Op1 = TheXor->getOperand(1);
7893 if (Op0.getOpcode() == Op1.getOpcode()) {
7894 // Avoid missing important xor optimizations.
7895 SDValue Tmp = visitXOR(TheXor);
Evan Cheng5652a8d2013-01-09 20:56:40 +00007896 if (Tmp.getNode()) {
7897 if (Tmp.getNode() != TheXor) {
7898 DEBUG(dbgs() << "\nReplacing.8 ";
7899 TheXor->dump(&DAG);
7900 dbgs() << "\nWith: ";
7901 Tmp.getNode()->dump(&DAG);
7902 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007903 WorklistRemover DeadNodes(*this);
Evan Cheng5652a8d2013-01-09 20:56:40 +00007904 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
Chandler Carruth18066972014-08-02 10:02:07 +00007905 deleteAndRecombine(TheXor);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007906 return DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng5652a8d2013-01-09 20:56:40 +00007907 MVT::Other, Chain, Tmp, N2);
7908 }
7909
Benjamin Kramer93354432013-03-30 21:28:18 +00007910 // visitXOR has changed XOR's operands or replaced the XOR completely,
7911 // bail out.
7912 return SDValue(N, 0);
Evan Cheng228c31f2010-02-27 07:36:59 +00007913 }
7914 }
7915
7916 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7917 bool Equal = false;
7918 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7919 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7920 Op0.getOpcode() == ISD::XOR) {
7921 TheXor = Op0.getNode();
7922 Equal = true;
7923 }
7924
Evan Chengc8d6cfd2010-10-04 22:41:01 +00007925 EVT SetCCVT = N1.getValueType();
Evan Cheng228c31f2010-02-27 07:36:59 +00007926 if (LegalTypes)
Matt Arsenault758659232013-05-18 00:21:46 +00007927 SetCCVT = getSetCCResultType(SetCCVT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007928 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
Evan Cheng228c31f2010-02-27 07:36:59 +00007929 SetCCVT,
7930 Op0, Op1,
7931 Equal ? ISD::SETEQ : ISD::SETNE);
7932 // Replace the uses of XOR with SETCC
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007933 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00007934 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
Chandler Carruth18066972014-08-02 10:02:07 +00007935 deleteAndRecombine(N1.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00007936 return DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng228c31f2010-02-27 07:36:59 +00007937 MVT::Other, Chain, SetCC, N2);
7938 }
7939 }
Bill Wendlingaa28be62009-03-26 06:14:09 +00007940
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007941 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +00007942}
7943
Chris Lattnera49e16f2005-10-05 06:47:48 +00007944// Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7945//
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007946SDValue DAGCombiner::visitBR_CC(SDNode *N) {
Chris Lattnera49e16f2005-10-05 06:47:48 +00007947 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007948 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007949
Dan Gohman82e80012009-11-17 00:47:23 +00007950 // If N is a constant we could fold this into a fallthrough or unconditional
7951 // branch. However that doesn't happen very often in normal code, because
7952 // Instcombine/SimplifyCFG should have handled the available opportunities.
7953 // If we did this folding here, it would be necessary to update the
7954 // MachineBasicBlock CFG, which is awkward.
7955
Duncan Sands93b66092008-06-09 11:32:28 +00007956 // Use SimplifySetCC to simplify SETCC's.
Matt Arsenault758659232013-05-18 00:21:46 +00007957 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00007958 CondLHS, CondRHS, CC->get(), SDLoc(N),
Dale Johannesenf1163e92009-02-03 00:47:48 +00007959 false);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007960 if (Simp.getNode()) AddToWorklist(Simp.getNode());
Chris Lattner6a1b2de2006-10-14 03:52:46 +00007961
Nate Begemanbd7df032005-10-05 21:43:42 +00007962 // fold to a simpler setcc
Gabor Greiff304a7a2008-08-28 21:40:38 +00007963 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007964 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
Bill Wendling306bfc22009-01-30 23:27:35 +00007965 N->getOperand(0), Simp.getOperand(2),
7966 Simp.getOperand(0), Simp.getOperand(1),
7967 N->getOperand(4));
7968
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007969 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +00007970}
7971
Sanjay Patel50cbfc52014-08-28 16:29:51 +00007972/// Return true if 'Use' is a load or a store that uses N as its base pointer
7973/// and that N may be folded in the load / store addressing mode.
Evan Chengfa832632012-01-13 01:37:24 +00007974static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7975 SelectionDAG &DAG,
7976 const TargetLowering &TLI) {
7977 EVT VT;
7978 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
7979 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7980 return false;
7981 VT = Use->getValueType(0);
7982 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
7983 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7984 return false;
7985 VT = ST->getValue().getValueType();
7986 } else
7987 return false;
7988
Chandler Carruth95f83e02013-01-07 15:14:13 +00007989 TargetLowering::AddrMode AM;
Evan Chengfa832632012-01-13 01:37:24 +00007990 if (N->getOpcode() == ISD::ADD) {
7991 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7992 if (Offset)
Evan Cheng80893ce2012-03-06 23:33:32 +00007993 // [reg +/- imm]
Evan Chengfa832632012-01-13 01:37:24 +00007994 AM.BaseOffs = Offset->getSExtValue();
7995 else
Evan Cheng80893ce2012-03-06 23:33:32 +00007996 // [reg +/- reg]
7997 AM.Scale = 1;
Evan Chengfa832632012-01-13 01:37:24 +00007998 } else if (N->getOpcode() == ISD::SUB) {
7999 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
8000 if (Offset)
Evan Cheng80893ce2012-03-06 23:33:32 +00008001 // [reg +/- imm]
Evan Chengfa832632012-01-13 01:37:24 +00008002 AM.BaseOffs = -Offset->getSExtValue();
8003 else
Evan Cheng80893ce2012-03-06 23:33:32 +00008004 // [reg +/- reg]
8005 AM.Scale = 1;
Evan Chengfa832632012-01-13 01:37:24 +00008006 } else
8007 return false;
8008
8009 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
8010}
8011
Sanjay Patel50cbfc52014-08-28 16:29:51 +00008012/// Try turning a load/store into a pre-indexed load/store when the base
8013/// pointer is an add or subtract and it has other uses besides the load/store.
8014/// After the transformation, the new indexed load/store has effectively folded
8015/// the add/subtract in and all of its other uses are redirected to the
8016/// new load/store.
Chris Lattnerffad2162006-11-11 00:39:41 +00008017bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
Eli Friedman9d448e42011-11-12 00:35:34 +00008018 if (Level < AfterLegalizeDAG)
Chris Lattnerffad2162006-11-11 00:39:41 +00008019 return false;
8020
8021 bool isLoad = true;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008022 SDValue Ptr;
Owen Anderson53aa7a92009-08-10 22:56:29 +00008023 EVT VT;
Chris Lattnerffad2162006-11-11 00:39:41 +00008024 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00008025 if (LD->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00008026 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00008027 VT = LD->getMemoryVT();
Evan Cheng8a1d09d2007-03-07 08:07:03 +00008028 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
Chris Lattnerffad2162006-11-11 00:39:41 +00008029 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
8030 return false;
8031 Ptr = LD->getBasePtr();
8032 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00008033 if (ST->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00008034 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00008035 VT = ST->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00008036 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
8037 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
8038 return false;
8039 Ptr = ST->getBasePtr();
8040 isLoad = false;
Bill Wendling306bfc22009-01-30 23:27:35 +00008041 } else {
Chris Lattnerffad2162006-11-11 00:39:41 +00008042 return false;
Bill Wendling306bfc22009-01-30 23:27:35 +00008043 }
Chris Lattnerffad2162006-11-11 00:39:41 +00008044
Chris Lattnereabc15c2006-11-11 00:56:29 +00008045 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
8046 // out. There is no reason to make this a preinc/predec.
8047 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
Gabor Greiff304a7a2008-08-28 21:40:38 +00008048 Ptr.getNode()->hasOneUse())
Chris Lattnereabc15c2006-11-11 00:56:29 +00008049 return false;
Chris Lattnerffad2162006-11-11 00:39:41 +00008050
Chris Lattnereabc15c2006-11-11 00:56:29 +00008051 // Ask the target to do addressing mode selection.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008052 SDValue BasePtr;
8053 SDValue Offset;
Chris Lattnereabc15c2006-11-11 00:56:29 +00008054 ISD::MemIndexedMode AM = ISD::UNINDEXED;
8055 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
8056 return false;
Hal Finkel25819052013-02-08 21:35:47 +00008057
8058 // Backends without true r+i pre-indexed forms may need to pass a
8059 // constant base with a variable offset so that constant coercion
8060 // will work with the patterns in canonical form.
8061 bool Swapped = false;
8062 if (isa<ConstantSDNode>(BasePtr)) {
8063 std::swap(BasePtr, Offset);
8064 Swapped = true;
8065 }
8066
Evan Cheng044a0a82007-05-03 23:52:19 +00008067 // Don't create a indexed load / store with zero offset.
8068 if (isa<ConstantSDNode>(Offset) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00008069 cast<ConstantSDNode>(Offset)->isNullValue())
Evan Cheng044a0a82007-05-03 23:52:19 +00008070 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00008071
Chris Lattnera0a80032006-11-11 01:00:15 +00008072 // Try turning it into a pre-indexed load / store except when:
Evan Chenga4d187b2007-05-24 02:35:39 +00008073 // 1) The new base ptr is a frame index.
8074 // 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 +00008075 // predecessor of the value being stored.
Evan Chenga4d187b2007-05-24 02:35:39 +00008076 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
Chris Lattnereabc15c2006-11-11 00:56:29 +00008077 // that would create a cycle.
Evan Chenga4d187b2007-05-24 02:35:39 +00008078 // 4) All uses are load / store ops that use it as old base ptr.
Chris Lattnerffad2162006-11-11 00:39:41 +00008079
Chris Lattnera0a80032006-11-11 01:00:15 +00008080 // Check #1. Preinc'ing a frame index would require copying the stack pointer
8081 // (plus the implicit offset) to a register to preinc anyway.
Evan Chengcfc05132009-05-06 18:25:01 +00008082 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
Chris Lattnera0a80032006-11-11 01:00:15 +00008083 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00008084
Chris Lattnera0a80032006-11-11 01:00:15 +00008085 // Check #2.
Chris Lattnereabc15c2006-11-11 00:56:29 +00008086 if (!isLoad) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008087 SDValue Val = cast<StoreSDNode>(N)->getValue();
Gabor Greiff304a7a2008-08-28 21:40:38 +00008088 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
Chris Lattnereabc15c2006-11-11 00:56:29 +00008089 return false;
Chris Lattnerffad2162006-11-11 00:39:41 +00008090 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00008091
Hal Finkel25819052013-02-08 21:35:47 +00008092 // If the offset is a constant, there may be other adds of constants that
8093 // can be folded with this one. We should do this to avoid having to keep
8094 // a copy of the original base pointer.
8095 SmallVector<SDNode *, 16> OtherUses;
8096 if (isa<ConstantSDNode>(Offset))
Jim Grosbache8160032014-04-11 01:13:13 +00008097 for (SDNode *Use : BasePtr.getNode()->uses()) {
Hal Finkel25819052013-02-08 21:35:47 +00008098 if (Use == Ptr.getNode())
8099 continue;
8100
8101 if (Use->isPredecessorOf(N))
8102 continue;
8103
8104 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
8105 OtherUses.clear();
8106 break;
8107 }
8108
8109 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
8110 if (Op1.getNode() == BasePtr.getNode())
8111 std::swap(Op0, Op1);
8112 assert(Op0.getNode() == BasePtr.getNode() &&
8113 "Use of ADD/SUB but not an operand");
8114
8115 if (!isa<ConstantSDNode>(Op1)) {
8116 OtherUses.clear();
8117 break;
8118 }
8119
8120 // FIXME: In some cases, we can be smarter about this.
8121 if (Op1.getValueType() != Offset.getValueType()) {
8122 OtherUses.clear();
8123 break;
8124 }
8125
8126 OtherUses.push_back(Use);
8127 }
8128
8129 if (Swapped)
8130 std::swap(BasePtr, Offset);
8131
Evan Chenga4d187b2007-05-24 02:35:39 +00008132 // Now check for #3 and #4.
Chris Lattnereabc15c2006-11-11 00:56:29 +00008133 bool RealUse = false;
Lang Hames5a004992011-07-07 04:31:51 +00008134
8135 // Caches for hasPredecessorHelper
8136 SmallPtrSet<const SDNode *, 32> Visited;
8137 SmallVector<const SDNode *, 16> Worklist;
8138
Jim Grosbache8160032014-04-11 01:13:13 +00008139 for (SDNode *Use : Ptr.getNode()->uses()) {
Chris Lattnereabc15c2006-11-11 00:56:29 +00008140 if (Use == N)
8141 continue;
Lang Hames5a004992011-07-07 04:31:51 +00008142 if (N->hasPredecessorHelper(Use, Visited, Worklist))
Chris Lattnereabc15c2006-11-11 00:56:29 +00008143 return false;
8144
Evan Chengfa832632012-01-13 01:37:24 +00008145 // If Ptr may be folded in addressing mode of other use, then it's
8146 // not profitable to do this transformation.
8147 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
Chris Lattnereabc15c2006-11-11 00:56:29 +00008148 RealUse = true;
8149 }
Bill Wendling306bfc22009-01-30 23:27:35 +00008150
Chris Lattnereabc15c2006-11-11 00:56:29 +00008151 if (!RealUse)
8152 return false;
8153
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008154 SDValue Result;
Chris Lattnereabc15c2006-11-11 00:56:29 +00008155 if (isLoad)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008156 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00008157 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00008158 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00008159 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00008160 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00008161 ++PreIndexedNodes;
8162 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +00008163 DEBUG(dbgs() << "\nReplacing.4 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00008164 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00008165 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00008166 Result.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00008167 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008168 WorklistRemover DeadNodes(*this);
Chris Lattnereabc15c2006-11-11 00:56:29 +00008169 if (isLoad) {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008170 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8171 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
Chris Lattnereabc15c2006-11-11 00:56:29 +00008172 } else {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008173 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
Chris Lattnereabc15c2006-11-11 00:56:29 +00008174 }
8175
Chris Lattnereabc15c2006-11-11 00:56:29 +00008176 // Finally, since the node is now dead, remove it from the graph.
Chandler Carruth18066972014-08-02 10:02:07 +00008177 deleteAndRecombine(N);
Chris Lattnereabc15c2006-11-11 00:56:29 +00008178
Hal Finkel25819052013-02-08 21:35:47 +00008179 if (Swapped)
8180 std::swap(BasePtr, Offset);
8181
8182 // Replace other uses of BasePtr that can be updated to use Ptr
8183 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
8184 unsigned OffsetIdx = 1;
8185 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
8186 OffsetIdx = 0;
8187 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
8188 BasePtr.getNode() && "Expected BasePtr operand");
8189
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00008190 // We need to replace ptr0 in the following expression:
8191 // x0 * offset0 + y0 * ptr0 = t0
8192 // knowing that
8193 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
Stephen Lincfe7f352013-07-08 00:37:03 +00008194 //
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00008195 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
8196 // indexed load/store and the expresion that needs to be re-written.
8197 //
8198 // Therefore, we have:
8199 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
Hal Finkel25819052013-02-08 21:35:47 +00008200
8201 ConstantSDNode *CN =
8202 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00008203 int X0, X1, Y0, Y1;
8204 APInt Offset0 = CN->getAPIntValue();
8205 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
Hal Finkel25819052013-02-08 21:35:47 +00008206
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00008207 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
8208 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
8209 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
8210 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
Hal Finkel25819052013-02-08 21:35:47 +00008211
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00008212 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
8213
8214 APInt CNV = Offset0;
8215 if (X0 < 0) CNV = -CNV;
8216 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
8217 else CNV = CNV - Offset1;
8218
8219 // We can now generate the new expression.
8220 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
8221 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
8222
8223 SDValue NewUse = DAG.getNode(Opcode,
Andrew Trickef9de2a2013-05-25 02:42:55 +00008224 SDLoc(OtherUses[i]),
Hal Finkel25819052013-02-08 21:35:47 +00008225 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
8226 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
Chandler Carruth18066972014-08-02 10:02:07 +00008227 deleteAndRecombine(OtherUses[i]);
Hal Finkel25819052013-02-08 21:35:47 +00008228 }
8229
Chris Lattnereabc15c2006-11-11 00:56:29 +00008230 // Replace the uses of Ptr with uses of the updated base value.
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008231 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
Chandler Carruth18066972014-08-02 10:02:07 +00008232 deleteAndRecombine(Ptr.getNode());
Chris Lattnereabc15c2006-11-11 00:56:29 +00008233
8234 return true;
Chris Lattnerffad2162006-11-11 00:39:41 +00008235}
8236
Sanjay Patel50cbfc52014-08-28 16:29:51 +00008237/// Try to combine a load/store with a add/sub of the base pointer node into a
8238/// post-indexed load/store. The transformation folded the add/subtract into the
8239/// new indexed load/store effectively and all of its uses are redirected to the
8240/// new load/store.
Chris Lattnerffad2162006-11-11 00:39:41 +00008241bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
Eli Friedman9d448e42011-11-12 00:35:34 +00008242 if (Level < AfterLegalizeDAG)
Chris Lattnerffad2162006-11-11 00:39:41 +00008243 return false;
8244
8245 bool isLoad = true;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008246 SDValue Ptr;
Owen Anderson53aa7a92009-08-10 22:56:29 +00008247 EVT VT;
Chris Lattnerffad2162006-11-11 00:39:41 +00008248 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00008249 if (LD->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00008250 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00008251 VT = LD->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00008252 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
8253 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
8254 return false;
8255 Ptr = LD->getBasePtr();
8256 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00008257 if (ST->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00008258 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00008259 VT = ST->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00008260 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
8261 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
8262 return false;
8263 Ptr = ST->getBasePtr();
8264 isLoad = false;
Bill Wendling306bfc22009-01-30 23:27:35 +00008265 } else {
Chris Lattnerffad2162006-11-11 00:39:41 +00008266 return false;
Bill Wendling306bfc22009-01-30 23:27:35 +00008267 }
Chris Lattnerffad2162006-11-11 00:39:41 +00008268
Gabor Greiff304a7a2008-08-28 21:40:38 +00008269 if (Ptr.getNode()->hasOneUse())
Chris Lattnereabc15c2006-11-11 00:56:29 +00008270 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00008271
Jim Grosbache8160032014-04-11 01:13:13 +00008272 for (SDNode *Op : Ptr.getNode()->uses()) {
Chris Lattnereabc15c2006-11-11 00:56:29 +00008273 if (Op == N ||
8274 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
8275 continue;
8276
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008277 SDValue BasePtr;
8278 SDValue Offset;
Chris Lattnereabc15c2006-11-11 00:56:29 +00008279 ISD::MemIndexedMode AM = ISD::UNINDEXED;
8280 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
Evan Cheng044a0a82007-05-03 23:52:19 +00008281 // Don't create a indexed load / store with zero offset.
8282 if (isa<ConstantSDNode>(Offset) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00008283 cast<ConstantSDNode>(Offset)->isNullValue())
Evan Cheng044a0a82007-05-03 23:52:19 +00008284 continue;
Chris Lattnerffad2162006-11-11 00:39:41 +00008285
Chris Lattnereabc15c2006-11-11 00:56:29 +00008286 // Try turning it into a post-indexed load / store except when
Evan Chengfa832632012-01-13 01:37:24 +00008287 // 1) All uses are load / store ops that use it as base ptr (and
8288 // it may be folded as addressing mmode).
Chris Lattnereabc15c2006-11-11 00:56:29 +00008289 // 2) Op must be independent of N, i.e. Op is neither a predecessor
8290 // nor a successor of N. Otherwise, if Op is folded that would
8291 // create a cycle.
8292
Evan Chengcfc05132009-05-06 18:25:01 +00008293 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
8294 continue;
8295
Chris Lattnereabc15c2006-11-11 00:56:29 +00008296 // Check for #1.
8297 bool TryNext = false;
Jim Grosbache8160032014-04-11 01:13:13 +00008298 for (SDNode *Use : BasePtr.getNode()->uses()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00008299 if (Use == Ptr.getNode())
Chris Lattnerffad2162006-11-11 00:39:41 +00008300 continue;
8301
Chris Lattnereabc15c2006-11-11 00:56:29 +00008302 // If all the uses are load / store addresses, then don't do the
8303 // transformation.
8304 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
8305 bool RealUse = false;
Jim Grosbache8160032014-04-11 01:13:13 +00008306 for (SDNode *UseUse : Use->uses()) {
Stephen Lincfe7f352013-07-08 00:37:03 +00008307 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
Chris Lattnereabc15c2006-11-11 00:56:29 +00008308 RealUse = true;
8309 }
Chris Lattnerffad2162006-11-11 00:39:41 +00008310
Chris Lattnereabc15c2006-11-11 00:56:29 +00008311 if (!RealUse) {
8312 TryNext = true;
8313 break;
Chris Lattnerffad2162006-11-11 00:39:41 +00008314 }
8315 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00008316 }
Bill Wendling306bfc22009-01-30 23:27:35 +00008317
Chris Lattnereabc15c2006-11-11 00:56:29 +00008318 if (TryNext)
8319 continue;
Chris Lattnerffad2162006-11-11 00:39:41 +00008320
Chris Lattnereabc15c2006-11-11 00:56:29 +00008321 // Check for #2
Evan Cheng567d2e52008-03-04 00:41:45 +00008322 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008323 SDValue Result = isLoad
Andrew Trickef9de2a2013-05-25 02:42:55 +00008324 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00008325 BasePtr, Offset, AM)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008326 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00008327 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00008328 ++PostIndexedNodes;
8329 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +00008330 DEBUG(dbgs() << "\nReplacing.5 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00008331 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00008332 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00008333 Result.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00008334 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008335 WorklistRemover DeadNodes(*this);
Chris Lattnereabc15c2006-11-11 00:56:29 +00008336 if (isLoad) {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008337 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8338 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
Chris Lattnereabc15c2006-11-11 00:56:29 +00008339 } else {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008340 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
Chris Lattnerffad2162006-11-11 00:39:41 +00008341 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00008342
Chris Lattnereabc15c2006-11-11 00:56:29 +00008343 // Finally, since the node is now dead, remove it from the graph.
Chandler Carruth18066972014-08-02 10:02:07 +00008344 deleteAndRecombine(N);
Chris Lattnereabc15c2006-11-11 00:56:29 +00008345
8346 // Replace the uses of Use with uses of the updated base value.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008347 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008348 Result.getValue(isLoad ? 1 : 0));
Chandler Carruth18066972014-08-02 10:02:07 +00008349 deleteAndRecombine(Op);
Chris Lattnereabc15c2006-11-11 00:56:29 +00008350 return true;
Chris Lattnerffad2162006-11-11 00:39:41 +00008351 }
8352 }
8353 }
Bill Wendling306bfc22009-01-30 23:27:35 +00008354
Chris Lattnerffad2162006-11-11 00:39:41 +00008355 return false;
8356}
8357
Hal Finkel51e6fa22014-09-02 06:24:04 +00008358/// \brief Return the base-pointer arithmetic from an indexed \p LD.
8359SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
8360 ISD::MemIndexedMode AM = LD->getAddressingMode();
8361 assert(AM != ISD::UNINDEXED);
8362 SDValue BP = LD->getOperand(1);
8363 SDValue Inc = LD->getOperand(2);
Hal Finkele19006e2014-09-02 16:05:23 +00008364
8365 // Some backends use TargetConstants for load offsets, but don't expect
8366 // TargetConstants in general ADD nodes. We can convert these constants into
8367 // regular Constants (if the constant is not opaque).
8368 assert((Inc.getOpcode() != ISD::TargetConstant ||
8369 !cast<ConstantSDNode>(Inc)->isOpaque()) &&
8370 "Cannot split out indexing using opaque target constants");
8371 if (Inc.getOpcode() == ISD::TargetConstant) {
8372 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
8373 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(),
8374 ConstInc->getValueType(0));
8375 }
8376
Hal Finkel51e6fa22014-09-02 06:24:04 +00008377 unsigned Opc =
8378 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
8379 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
8380}
8381
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008382SDValue DAGCombiner::visitLOAD(SDNode *N) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00008383 LoadSDNode *LD = cast<LoadSDNode>(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008384 SDValue Chain = LD->getChain();
8385 SDValue Ptr = LD->getBasePtr();
Scott Michelcf0da6c2009-02-17 22:15:04 +00008386
Evan Chenga684cd22007-05-01 00:38:21 +00008387 // If load is not volatile and there are no uses of the loaded value (and
8388 // the updated indexed value in case of indexed loads), change uses of the
8389 // chain value into uses of the chain input (i.e. delete the dead load).
8390 if (!LD->isVolatile()) {
Owen Anderson9f944592009-08-11 20:47:22 +00008391 if (N->getValueType(1) == MVT::Other) {
Evan Chengb68343c2007-05-01 08:53:39 +00008392 // Unindexed loads.
Craig Topper0515cd42012-01-07 18:31:09 +00008393 if (!N->hasAnyUseOfValue(0)) {
Evan Cheng7be15282008-01-16 23:11:54 +00008394 // It's not safe to use the two value CombineTo variant here. e.g.
8395 // v1, chain2 = load chain1, loc
8396 // v2, chain3 = load chain2, loc
8397 // v3 = add v2, c
Chris Lattnere97fa8c2008-01-24 07:57:06 +00008398 // Now we replace use of chain2 with chain1. This makes the second load
8399 // isomorphic to the one we are deleting, and thus makes this load live.
David Greenefe5c3522010-01-05 01:25:00 +00008400 DEBUG(dbgs() << "\nReplacing.6 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00008401 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00008402 dbgs() << "\nWith chain: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00008403 Chain.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00008404 dbgs() << "\n");
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008405 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008406 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
Bill Wendling306bfc22009-01-30 23:27:35 +00008407
Chandler Carruth18066972014-08-02 10:02:07 +00008408 if (N->use_empty())
8409 deleteAndRecombine(N);
Bill Wendling306bfc22009-01-30 23:27:35 +00008410
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008411 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Cheng7be15282008-01-16 23:11:54 +00008412 }
Evan Chengb68343c2007-05-01 08:53:39 +00008413 } else {
8414 // Indexed loads.
Owen Anderson9f944592009-08-11 20:47:22 +00008415 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
Hal Finkel51e6fa22014-09-02 06:24:04 +00008416
Hal Finkele19006e2014-09-02 16:05:23 +00008417 // If this load has an opaque TargetConstant offset, then we cannot split
8418 // the indexing into an add/sub directly (that TargetConstant may not be
8419 // valid for a different type of node, and we cannot convert an opaque
8420 // target constant into a regular constant).
8421 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
8422 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
Hal Finkel51e6fa22014-09-02 06:24:04 +00008423
8424 if (!N->hasAnyUseOfValue(0) &&
Hal Finkele19006e2014-09-02 16:05:23 +00008425 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
Dale Johannesen84935752009-02-06 23:05:02 +00008426 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
Hal Finkel51e6fa22014-09-02 06:24:04 +00008427 SDValue Index;
Hal Finkele19006e2014-09-02 16:05:23 +00008428 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
Hal Finkel51e6fa22014-09-02 06:24:04 +00008429 Index = SplitIndexingFromLoad(LD);
8430 // Try to fold the base pointer arithmetic into subsequent loads and
8431 // stores.
8432 AddUsersToWorklist(N);
8433 } else
8434 Index = DAG.getUNDEF(N->getValueType(1));
Evan Cheng228c31f2010-02-27 07:36:59 +00008435 DEBUG(dbgs() << "\nReplacing.7 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00008436 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00008437 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00008438 Undef.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00008439 dbgs() << " and 2 other values\n");
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008440 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008441 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
Hal Finkel51e6fa22014-09-02 06:24:04 +00008442 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008443 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
Chandler Carruth18066972014-08-02 10:02:07 +00008444 deleteAndRecombine(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008445 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga684cd22007-05-01 00:38:21 +00008446 }
Evan Chenga684cd22007-05-01 00:38:21 +00008447 }
8448 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00008449
Chris Lattnere260ed82005-10-10 22:04:48 +00008450 // If this load is directly stored, replace the load value with the stored
8451 // value.
8452 // TODO: Handle store large -> read small portion.
Jim Laskey0f7c3282006-10-11 17:47:52 +00008453 // TODO: Handle TRUNCSTORE/LOADEXT
Evan Chengadb9c032011-03-11 00:48:56 +00008454 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00008455 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
Evan Chengab51cf22006-10-13 21:14:26 +00008456 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
8457 if (PrevST->getBasePtr() == Ptr &&
8458 PrevST->getValue().getValueType() == N->getValueType(0))
Jim Laskey0f7c3282006-10-11 17:47:52 +00008459 return CombineTo(N, Chain.getOperand(1), Chain);
Evan Chengab51cf22006-10-13 21:14:26 +00008460 }
Jim Laskey0f7c3282006-10-11 17:47:52 +00008461 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00008462
Evan Cheng43cd9e32010-04-01 06:04:33 +00008463 // Try to infer better alignment information than the load already has.
8464 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
Evan Cheng4a5b2042011-11-28 22:37:34 +00008465 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
Owen Andersonde89ecf2013-02-05 19:24:39 +00008466 if (Align > LD->getMemOperand()->getBaseAlignment()) {
8467 SDValue NewLoad =
Andrew Trickef9de2a2013-05-25 02:42:55 +00008468 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
Evan Cheng4a5b2042011-11-28 22:37:34 +00008469 LD->getValueType(0),
8470 Chain, Ptr, LD->getPointerInfo(),
8471 LD->getMemoryVT(),
Louis Gerbarg67474e32014-07-31 21:45:05 +00008472 LD->isVolatile(), LD->isNonTemporal(),
8473 LD->isInvariant(), Align, LD->getAAInfo());
Owen Andersonde89ecf2013-02-05 19:24:39 +00008474 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
8475 }
Evan Cheng43cd9e32010-04-01 06:04:33 +00008476 }
8477 }
8478
Eric Christopherf55d4712014-10-08 23:38:39 +00008479 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
8480 : DAG.getSubtarget().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +00008481#ifndef NDEBUG
8482 if (CombinerAAOnlyFunc.getNumOccurrences() &&
8483 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
8484 UseAA = false;
8485#endif
Hal Finkelccc18e12014-01-24 18:25:26 +00008486 if (UseAA && LD->isUnindexed()) {
Jim Laskeyd07be232006-09-25 16:29:54 +00008487 // Walk up chain skipping non-aliasing memory nodes.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008488 SDValue BetterChain = FindBetterChain(N, Chain);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008489
Jim Laskey708d0db2006-10-04 16:53:27 +00008490 // If there is a better chain.
Jim Laskeyd07be232006-09-25 16:29:54 +00008491 if (Chain != BetterChain) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008492 SDValue ReplLoad;
Jim Laskey0f7c3282006-10-11 17:47:52 +00008493
Jim Laskeyd07be232006-09-25 16:29:54 +00008494 // Replace the chain to void dependency.
Jim Laskey0f7c3282006-10-11 17:47:52 +00008495 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00008496 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00008497 BetterChain, Ptr, LD->getMemOperand());
Jim Laskey0f7c3282006-10-11 17:47:52 +00008498 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +00008499 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
Stuart Hastings81c43062011-02-16 16:23:55 +00008500 LD->getValueType(0),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00008501 BetterChain, Ptr, LD->getMemoryVT(),
8502 LD->getMemOperand());
Jim Laskey0f7c3282006-10-11 17:47:52 +00008503 }
Jim Laskeyd07be232006-09-25 16:29:54 +00008504
Jim Laskey708d0db2006-10-04 16:53:27 +00008505 // Create token factor to keep old chain connected.
Andrew Trickef9de2a2013-05-25 02:42:55 +00008506 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
Owen Anderson9f944592009-08-11 20:47:22 +00008507 MVT::Other, Chain, ReplLoad.getValue(1));
Wesley Peck527da1b2010-11-23 03:31:01 +00008508
Nate Begeman879d8f12009-09-15 00:18:30 +00008509 // Make sure the new and old chains are cleaned up.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008510 AddToWorklist(Token.getNode());
Wesley Peck527da1b2010-11-23 03:31:01 +00008511
Jim Laskeydcf983c2006-10-13 23:32:28 +00008512 // Replace uses with load result and token factor. Don't add users
8513 // to work list.
8514 return CombineTo(N, ReplLoad.getValue(0), Token, false);
Jim Laskeyd07be232006-09-25 16:29:54 +00008515 }
8516 }
8517
Evan Cheng357017f2006-11-03 03:06:21 +00008518 // Try transforming N to an indexed load.
Evan Cheng60c68462006-11-07 09:03:05 +00008519 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008520 return SDValue(N, 0);
Evan Cheng357017f2006-11-03 03:06:21 +00008521
Quentin Colombetde0e0622013-10-11 18:29:42 +00008522 // Try to slice up N to more direct loads if the slices are mapped to
8523 // different register banks or pairing can take place.
8524 if (SliceUpLoad(N))
8525 return SDValue(N, 0);
8526
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008527 return SDValue();
Chris Lattnere260ed82005-10-10 22:04:48 +00008528}
8529
Quentin Colombetde0e0622013-10-11 18:29:42 +00008530namespace {
8531/// \brief Helper structure used to slice a load in smaller loads.
8532/// Basically a slice is obtained from the following sequence:
8533/// Origin = load Ty1, Base
8534/// Shift = srl Ty1 Origin, CstTy Amount
8535/// Inst = trunc Shift to Ty2
8536///
8537/// Then, it will be rewriten into:
8538/// Slice = load SliceTy, Base + SliceOffset
8539/// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8540///
8541/// SliceTy is deduced from the number of bits that are actually used to
8542/// build Inst.
8543struct LoadedSlice {
8544 /// \brief Helper structure used to compute the cost of a slice.
8545 struct Cost {
8546 /// Are we optimizing for code size.
8547 bool ForCodeSize;
8548 /// Various cost.
8549 unsigned Loads;
8550 unsigned Truncates;
8551 unsigned CrossRegisterBanksCopies;
8552 unsigned ZExts;
8553 unsigned Shift;
8554
8555 Cost(bool ForCodeSize = false)
8556 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8557 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8558
8559 /// \brief Get the cost of one isolated slice.
8560 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8561 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8562 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8563 EVT TruncType = LS.Inst->getValueType(0);
8564 EVT LoadedType = LS.getLoadedType();
8565 if (TruncType != LoadedType &&
8566 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8567 ZExts = 1;
8568 }
8569
8570 /// \brief Account for slicing gain in the current cost.
8571 /// Slicing provide a few gains like removing a shift or a
8572 /// truncate. This method allows to grow the cost of the original
8573 /// load with the gain from this slice.
8574 void addSliceGain(const LoadedSlice &LS) {
8575 // Each slice saves a truncate.
8576 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8577 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8578 LS.Inst->getOperand(0).getValueType()))
8579 ++Truncates;
8580 // If there is a shift amount, this slice gets rid of it.
8581 if (LS.Shift)
8582 ++Shift;
8583 // If this slice can merge a cross register bank copy, account for it.
8584 if (LS.canMergeExpensiveCrossRegisterBankCopy())
8585 ++CrossRegisterBanksCopies;
8586 }
8587
8588 Cost &operator+=(const Cost &RHS) {
8589 Loads += RHS.Loads;
8590 Truncates += RHS.Truncates;
8591 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8592 ZExts += RHS.ZExts;
8593 Shift += RHS.Shift;
8594 return *this;
8595 }
8596
8597 bool operator==(const Cost &RHS) const {
8598 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8599 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8600 ZExts == RHS.ZExts && Shift == RHS.Shift;
8601 }
8602
8603 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8604
8605 bool operator<(const Cost &RHS) const {
8606 // Assume cross register banks copies are as expensive as loads.
8607 // FIXME: Do we want some more target hooks?
8608 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8609 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8610 // Unless we are optimizing for code size, consider the
8611 // expensive operation first.
8612 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8613 return ExpensiveOpsLHS < ExpensiveOpsRHS;
8614 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8615 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8616 }
8617
8618 bool operator>(const Cost &RHS) const { return RHS < *this; }
8619
8620 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8621
8622 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8623 };
8624 // The last instruction that represent the slice. This should be a
8625 // truncate instruction.
8626 SDNode *Inst;
8627 // The original load instruction.
8628 LoadSDNode *Origin;
8629 // The right shift amount in bits from the original load.
8630 unsigned Shift;
8631 // The DAG from which Origin came from.
8632 // This is used to get some contextual information about legal types, etc.
8633 SelectionDAG *DAG;
8634
Craig Topperc0196b12014-04-14 00:51:57 +00008635 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8636 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
Quentin Colombetde0e0622013-10-11 18:29:42 +00008637 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8638
8639 LoadedSlice(const LoadedSlice &LS)
8640 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8641
8642 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8643 /// \return Result is \p BitWidth and has used bits set to 1 and
8644 /// not used bits set to 0.
8645 APInt getUsedBits() const {
8646 // Reproduce the trunc(lshr) sequence:
8647 // - Start from the truncated value.
8648 // - Zero extend to the desired bit width.
8649 // - Shift left.
8650 assert(Origin && "No original load to compare against.");
8651 unsigned BitWidth = Origin->getValueSizeInBits(0);
8652 assert(Inst && "This slice is not bound to an instruction");
8653 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8654 "Extracted slice is bigger than the whole type!");
8655 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8656 UsedBits.setAllBits();
8657 UsedBits = UsedBits.zext(BitWidth);
8658 UsedBits <<= Shift;
8659 return UsedBits;
8660 }
8661
8662 /// \brief Get the size of the slice to be loaded in bytes.
8663 unsigned getLoadedSize() const {
8664 unsigned SliceSize = getUsedBits().countPopulation();
8665 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8666 return SliceSize / 8;
8667 }
8668
8669 /// \brief Get the type that will be loaded for this slice.
8670 /// Note: This may not be the final type for the slice.
8671 EVT getLoadedType() const {
8672 assert(DAG && "Missing context");
8673 LLVMContext &Ctxt = *DAG->getContext();
8674 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8675 }
8676
8677 /// \brief Get the alignment of the load used for this slice.
8678 unsigned getAlignment() const {
8679 unsigned Alignment = Origin->getAlignment();
8680 unsigned Offset = getOffsetFromBase();
8681 if (Offset != 0)
8682 Alignment = MinAlign(Alignment, Alignment + Offset);
8683 return Alignment;
8684 }
8685
8686 /// \brief Check if this slice can be rewritten with legal operations.
8687 bool isLegal() const {
8688 // An invalid slice is not legal.
8689 if (!Origin || !Inst || !DAG)
8690 return false;
8691
8692 // Offsets are for indexed load only, we do not handle that.
8693 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8694 return false;
8695
8696 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8697
8698 // Check that the type is legal.
8699 EVT SliceType = getLoadedType();
8700 if (!TLI.isTypeLegal(SliceType))
8701 return false;
8702
8703 // Check that the load is legal for this type.
8704 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8705 return false;
8706
8707 // Check that the offset can be computed.
8708 // 1. Check its type.
8709 EVT PtrType = Origin->getBasePtr().getValueType();
8710 if (PtrType == MVT::Untyped || PtrType.isExtended())
8711 return false;
8712
8713 // 2. Check that it fits in the immediate.
8714 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8715 return false;
8716
8717 // 3. Check that the computation is legal.
8718 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8719 return false;
8720
8721 // Check that the zext is legal if it needs one.
8722 EVT TruncateType = Inst->getValueType(0);
8723 if (TruncateType != SliceType &&
8724 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8725 return false;
8726
8727 return true;
8728 }
8729
8730 /// \brief Get the offset in bytes of this slice in the original chunk of
8731 /// bits.
Craig Topperc0196b12014-04-14 00:51:57 +00008732 /// \pre DAG != nullptr.
Quentin Colombetde0e0622013-10-11 18:29:42 +00008733 uint64_t getOffsetFromBase() const {
8734 assert(DAG && "Missing context.");
8735 bool IsBigEndian =
8736 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8737 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8738 uint64_t Offset = Shift / 8;
8739 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8740 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8741 "The size of the original loaded type is not a multiple of a"
8742 " byte.");
8743 // If Offset is bigger than TySizeInBytes, it means we are loading all
8744 // zeros. This should have been optimized before in the process.
8745 assert(TySizeInBytes > Offset &&
8746 "Invalid shift amount for given loaded size");
8747 if (IsBigEndian)
8748 Offset = TySizeInBytes - Offset - getLoadedSize();
8749 return Offset;
8750 }
8751
8752 /// \brief Generate the sequence of instructions to load the slice
8753 /// represented by this object and redirect the uses of this slice to
8754 /// this new sequence of instructions.
8755 /// \pre this->Inst && this->Origin are valid Instructions and this
8756 /// object passed the legal check: LoadedSlice::isLegal returned true.
8757 /// \return The last instruction of the sequence used to load the slice.
8758 SDValue loadSlice() const {
8759 assert(Inst && Origin && "Unable to replace a non-existing slice.");
8760 const SDValue &OldBaseAddr = Origin->getBasePtr();
8761 SDValue BaseAddr = OldBaseAddr;
8762 // Get the offset in that chunk of bytes w.r.t. the endianess.
8763 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8764 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8765 if (Offset) {
8766 // BaseAddr = BaseAddr + Offset.
8767 EVT ArithType = BaseAddr.getValueType();
8768 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8769 DAG->getConstant(Offset, ArithType));
8770 }
8771
8772 // Create the type of the loaded slice according to its size.
8773 EVT SliceType = getLoadedType();
8774
8775 // Create the load for the slice.
8776 SDValue LastInst = DAG->getLoad(
8777 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8778 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8779 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8780 // If the final type is not the same as the loaded type, this means that
8781 // we have to pad with zero. Create a zero extend for that.
8782 EVT FinalType = Inst->getValueType(0);
8783 if (SliceType != FinalType)
8784 LastInst =
8785 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8786 return LastInst;
8787 }
8788
8789 /// \brief Check if this slice can be merged with an expensive cross register
8790 /// bank copy. E.g.,
8791 /// i = load i32
8792 /// f = bitcast i32 i to float
8793 bool canMergeExpensiveCrossRegisterBankCopy() const {
8794 if (!Inst || !Inst->hasOneUse())
8795 return false;
8796 SDNode *Use = *Inst->use_begin();
8797 if (Use->getOpcode() != ISD::BITCAST)
8798 return false;
8799 assert(DAG && "Missing context");
8800 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8801 EVT ResVT = Use->getValueType(0);
8802 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8803 const TargetRegisterClass *ArgRC =
8804 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8805 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8806 return false;
8807
8808 // At this point, we know that we perform a cross-register-bank copy.
8809 // Check if it is expensive.
Eric Christopherf55d4712014-10-08 23:38:39 +00008810 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
Quentin Colombetde0e0622013-10-11 18:29:42 +00008811 // Assume bitcasts are cheap, unless both register classes do not
8812 // explicitly share a common sub class.
8813 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8814 return false;
8815
8816 // Check if it will be merged with the load.
8817 // 1. Check the alignment constraint.
8818 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8819 ResVT.getTypeForEVT(*DAG->getContext()));
8820
8821 if (RequiredAlignment > getAlignment())
8822 return false;
8823
8824 // 2. Check that the load is a legal operation for that type.
8825 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8826 return false;
8827
8828 // 3. Check that we do not have a zext in the way.
8829 if (Inst->getValueType(0) != getLoadedType())
8830 return false;
8831
8832 return true;
8833 }
8834};
8835}
8836
Quentin Colombetde0e0622013-10-11 18:29:42 +00008837/// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8838/// \p UsedBits looks like 0..0 1..1 0..0.
8839static bool areUsedBitsDense(const APInt &UsedBits) {
8840 // If all the bits are one, this is dense!
8841 if (UsedBits.isAllOnesValue())
8842 return true;
8843
8844 // Get rid of the unused bits on the right.
8845 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8846 // Get rid of the unused bits on the left.
8847 if (NarrowedUsedBits.countLeadingZeros())
8848 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8849 // Check that the chunk of bits is completely used.
8850 return NarrowedUsedBits.isAllOnesValue();
8851}
8852
8853/// \brief Check whether or not \p First and \p Second are next to each other
8854/// in memory. This means that there is no hole between the bits loaded
8855/// by \p First and the bits loaded by \p Second.
8856static bool areSlicesNextToEachOther(const LoadedSlice &First,
8857 const LoadedSlice &Second) {
8858 assert(First.Origin == Second.Origin && First.Origin &&
8859 "Unable to match different memory origins.");
8860 APInt UsedBits = First.getUsedBits();
8861 assert((UsedBits & Second.getUsedBits()) == 0 &&
8862 "Slices are not supposed to overlap.");
8863 UsedBits |= Second.getUsedBits();
8864 return areUsedBitsDense(UsedBits);
8865}
8866
8867/// \brief Adjust the \p GlobalLSCost according to the target
8868/// paring capabilities and the layout of the slices.
8869/// \pre \p GlobalLSCost should account for at least as many loads as
8870/// there is in the slices in \p LoadedSlices.
8871static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8872 LoadedSlice::Cost &GlobalLSCost) {
8873 unsigned NumberOfSlices = LoadedSlices.size();
8874 // If there is less than 2 elements, no pairing is possible.
8875 if (NumberOfSlices < 2)
8876 return;
8877
8878 // Sort the slices so that elements that are likely to be next to each
8879 // other in memory are next to each other in the list.
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00008880 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8881 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8882 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8883 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8884 });
Quentin Colombetde0e0622013-10-11 18:29:42 +00008885 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8886 // First (resp. Second) is the first (resp. Second) potentially candidate
8887 // to be placed in a paired load.
Craig Topperc0196b12014-04-14 00:51:57 +00008888 const LoadedSlice *First = nullptr;
8889 const LoadedSlice *Second = nullptr;
Quentin Colombetde0e0622013-10-11 18:29:42 +00008890 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8891 // Set the beginning of the pair.
8892 First = Second) {
8893
8894 Second = &LoadedSlices[CurrSlice];
8895
8896 // If First is NULL, it means we start a new pair.
8897 // Get to the next slice.
8898 if (!First)
8899 continue;
8900
8901 EVT LoadedType = First->getLoadedType();
8902
8903 // If the types of the slices are different, we cannot pair them.
8904 if (LoadedType != Second->getLoadedType())
8905 continue;
8906
8907 // Check if the target supplies paired loads for this type.
8908 unsigned RequiredAlignment = 0;
8909 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8910 // move to the next pair, this type is hopeless.
Craig Topperc0196b12014-04-14 00:51:57 +00008911 Second = nullptr;
Quentin Colombetde0e0622013-10-11 18:29:42 +00008912 continue;
8913 }
8914 // Check if we meet the alignment requirement.
8915 if (RequiredAlignment > First->getAlignment())
8916 continue;
8917
8918 // Check that both loads are next to each other in memory.
8919 if (!areSlicesNextToEachOther(*First, *Second))
8920 continue;
8921
8922 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8923 --GlobalLSCost.Loads;
8924 // Move to the next pair.
Craig Topperc0196b12014-04-14 00:51:57 +00008925 Second = nullptr;
Quentin Colombetde0e0622013-10-11 18:29:42 +00008926 }
8927}
8928
8929/// \brief Check the profitability of all involved LoadedSlice.
8930/// Currently, it is considered profitable if there is exactly two
8931/// involved slices (1) which are (2) next to each other in memory, and
8932/// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8933///
8934/// Note: The order of the elements in \p LoadedSlices may be modified, but not
8935/// the elements themselves.
8936///
8937/// FIXME: When the cost model will be mature enough, we can relax
8938/// constraints (1) and (2).
8939static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8940 const APInt &UsedBits, bool ForCodeSize) {
8941 unsigned NumberOfSlices = LoadedSlices.size();
8942 if (StressLoadSlicing)
8943 return NumberOfSlices > 1;
8944
8945 // Check (1).
8946 if (NumberOfSlices != 2)
8947 return false;
8948
8949 // Check (2).
8950 if (!areUsedBitsDense(UsedBits))
8951 return false;
8952
8953 // Check (3).
8954 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8955 // The original code has one big load.
8956 OrigCost.Loads = 1;
8957 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8958 const LoadedSlice &LS = LoadedSlices[CurrSlice];
8959 // Accumulate the cost of all the slices.
8960 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8961 GlobalSlicingCost += SliceCost;
8962
8963 // Account as cost in the original configuration the gain obtained
8964 // with the current slices.
8965 OrigCost.addSliceGain(LS);
8966 }
8967
8968 // If the target supports paired load, adjust the cost accordingly.
8969 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8970 return OrigCost > GlobalSlicingCost;
8971}
8972
8973/// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8974/// operations, split it in the various pieces being extracted.
8975///
8976/// This sort of thing is introduced by SROA.
8977/// This slicing takes care not to insert overlapping loads.
8978/// \pre LI is a simple load (i.e., not an atomic or volatile load).
8979bool DAGCombiner::SliceUpLoad(SDNode *N) {
8980 if (Level < AfterLegalizeDAG)
8981 return false;
8982
8983 LoadSDNode *LD = cast<LoadSDNode>(N);
8984 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8985 !LD->getValueType(0).isInteger())
8986 return false;
8987
8988 // Keep track of already used bits to detect overlapping values.
8989 // In that case, we will just abort the transformation.
8990 APInt UsedBits(LD->getValueSizeInBits(0), 0);
8991
8992 SmallVector<LoadedSlice, 4> LoadedSlices;
8993
8994 // Check if this load is used as several smaller chunks of bits.
8995 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8996 // of computation for each trunc.
8997 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8998 UI != UIEnd; ++UI) {
8999 // Skip the uses of the chain.
9000 if (UI.getUse().getResNo() != 0)
9001 continue;
9002
9003 SDNode *User = *UI;
9004 unsigned Shift = 0;
9005
9006 // Check if this is a trunc(lshr).
9007 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
9008 isa<ConstantSDNode>(User->getOperand(1))) {
9009 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
9010 User = *User->use_begin();
9011 }
9012
9013 // At this point, User is a Truncate, iff we encountered, trunc or
9014 // trunc(lshr).
9015 if (User->getOpcode() != ISD::TRUNCATE)
9016 return false;
9017
9018 // The width of the type must be a power of 2 and greater than 8-bits.
9019 // Otherwise the load cannot be represented in LLVM IR.
Alp Tokerf907b892013-12-05 05:44:44 +00009020 // Moreover, if we shifted with a non-8-bits multiple, the slice
Alp Tokercb402912014-01-24 17:20:08 +00009021 // will be across several bytes. We do not support that.
Quentin Colombetde0e0622013-10-11 18:29:42 +00009022 unsigned Width = User->getValueSizeInBits(0);
9023 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
9024 return 0;
9025
9026 // Build the slice for this chain of computations.
9027 LoadedSlice LS(User, LD, Shift, &DAG);
9028 APInt CurrentUsedBits = LS.getUsedBits();
9029
9030 // Check if this slice overlaps with another.
9031 if ((CurrentUsedBits & UsedBits) != 0)
9032 return false;
9033 // Update the bits used globally.
9034 UsedBits |= CurrentUsedBits;
9035
9036 // Check if the new slice would be legal.
9037 if (!LS.isLegal())
9038 return false;
9039
9040 // Record the slice.
9041 LoadedSlices.push_back(LS);
9042 }
9043
9044 // Abort slicing if it does not seem to be profitable.
9045 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
9046 return false;
9047
9048 ++SlicedLoads;
9049
9050 // Rewrite each chain to use an independent load.
9051 // By construction, each chain can be represented by a unique load.
9052
9053 // Prepare the argument for the new token factor for all the slices.
9054 SmallVector<SDValue, 8> ArgChains;
9055 for (SmallVectorImpl<LoadedSlice>::const_iterator
9056 LSIt = LoadedSlices.begin(),
9057 LSItEnd = LoadedSlices.end();
9058 LSIt != LSItEnd; ++LSIt) {
9059 SDValue SliceInst = LSIt->loadSlice();
9060 CombineTo(LSIt->Inst, SliceInst, true);
9061 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
9062 SliceInst = SliceInst.getOperand(0);
9063 assert(SliceInst->getOpcode() == ISD::LOAD &&
9064 "It takes more than a zext to get to the loaded slice!!");
9065 ArgChains.push_back(SliceInst.getValue(1));
9066 }
9067
9068 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
Craig Topper48d114b2014-04-26 18:35:24 +00009069 ArgChains);
Quentin Colombetde0e0622013-10-11 18:29:42 +00009070 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9071 return true;
9072}
9073
Sanjay Patel50cbfc52014-08-28 16:29:51 +00009074/// Check to see if V is (and load (ptr), imm), where the load is having
9075/// specific bytes cleared out. If so, return the byte size being masked out
9076/// and the shift amount.
Chris Lattner4041ab62010-04-15 04:48:01 +00009077static std::pair<unsigned, unsigned>
9078CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
9079 std::pair<unsigned, unsigned> Result(0, 0);
Wesley Peck527da1b2010-11-23 03:31:01 +00009080
Chris Lattner4041ab62010-04-15 04:48:01 +00009081 // Check for the structure we're looking for.
9082 if (V->getOpcode() != ISD::AND ||
9083 !isa<ConstantSDNode>(V->getOperand(1)) ||
9084 !ISD::isNormalLoad(V->getOperand(0).getNode()))
9085 return Result;
Wesley Peck527da1b2010-11-23 03:31:01 +00009086
Chris Lattner3245afd2010-04-15 06:10:49 +00009087 // Check the chain and pointer.
Chris Lattner4041ab62010-04-15 04:48:01 +00009088 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
Chris Lattner3245afd2010-04-15 06:10:49 +00009089 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
Wesley Peck527da1b2010-11-23 03:31:01 +00009090
Chris Lattner3245afd2010-04-15 06:10:49 +00009091 // The store should be chained directly to the load or be an operand of a
9092 // tokenfactor.
9093 if (LD == Chain.getNode())
9094 ; // ok.
9095 else if (Chain->getOpcode() != ISD::TokenFactor)
9096 return Result; // Fail.
9097 else {
9098 bool isOk = false;
9099 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
9100 if (Chain->getOperand(i).getNode() == LD) {
9101 isOk = true;
9102 break;
9103 }
9104 if (!isOk) return Result;
9105 }
Wesley Peck527da1b2010-11-23 03:31:01 +00009106
Chris Lattner4041ab62010-04-15 04:48:01 +00009107 // This only handles simple types.
9108 if (V.getValueType() != MVT::i16 &&
9109 V.getValueType() != MVT::i32 &&
9110 V.getValueType() != MVT::i64)
9111 return Result;
9112
9113 // Check the constant mask. Invert it so that the bits being masked out are
9114 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
9115 // follow the sign bit for uniformity.
9116 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00009117 unsigned NotMaskLZ = countLeadingZeros(NotMask);
Chris Lattner4041ab62010-04-15 04:48:01 +00009118 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00009119 unsigned NotMaskTZ = countTrailingZeros(NotMask);
Chris Lattner4041ab62010-04-15 04:48:01 +00009120 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
9121 if (NotMaskLZ == 64) return Result; // All zero mask.
Wesley Peck527da1b2010-11-23 03:31:01 +00009122
Chris Lattner4041ab62010-04-15 04:48:01 +00009123 // See if we have a continuous run of bits. If so, we have 0*1+0*
9124 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
9125 return Result;
9126
9127 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
9128 if (V.getValueType() != MVT::i64 && NotMaskLZ)
9129 NotMaskLZ -= 64-V.getValueSizeInBits();
Wesley Peck527da1b2010-11-23 03:31:01 +00009130
Chris Lattner4041ab62010-04-15 04:48:01 +00009131 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
9132 switch (MaskedBytes) {
Wesley Peck527da1b2010-11-23 03:31:01 +00009133 case 1:
9134 case 2:
Chris Lattner4041ab62010-04-15 04:48:01 +00009135 case 4: break;
9136 default: return Result; // All one mask, or 5-byte mask.
9137 }
Wesley Peck527da1b2010-11-23 03:31:01 +00009138
Chris Lattner4041ab62010-04-15 04:48:01 +00009139 // Verify that the first bit starts at a multiple of mask so that the access
9140 // is aligned the same as the access width.
9141 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
Wesley Peck527da1b2010-11-23 03:31:01 +00009142
Chris Lattner4041ab62010-04-15 04:48:01 +00009143 Result.first = MaskedBytes;
9144 Result.second = NotMaskTZ/8;
9145 return Result;
9146}
9147
9148
Sanjay Patel50cbfc52014-08-28 16:29:51 +00009149/// Check to see if IVal is something that provides a value as specified by
9150/// MaskInfo. If so, replace the specified store with a narrower store of
9151/// truncated IVal.
Chris Lattner4041ab62010-04-15 04:48:01 +00009152static SDNode *
9153ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
9154 SDValue IVal, StoreSDNode *St,
9155 DAGCombiner *DC) {
9156 unsigned NumBytes = MaskInfo.first;
9157 unsigned ByteShift = MaskInfo.second;
9158 SelectionDAG &DAG = DC->getDAG();
Wesley Peck527da1b2010-11-23 03:31:01 +00009159
Chris Lattner4041ab62010-04-15 04:48:01 +00009160 // Check to see if IVal is all zeros in the part being masked in by the 'or'
9161 // that uses this. If not, this is not a replacement.
9162 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
9163 ByteShift*8, (ByteShift+NumBytes)*8);
Craig Topperc0196b12014-04-14 00:51:57 +00009164 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
Wesley Peck527da1b2010-11-23 03:31:01 +00009165
Chris Lattner4041ab62010-04-15 04:48:01 +00009166 // Check that it is legal on the target to do this. It is legal if the new
9167 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
9168 // legalization.
9169 MVT VT = MVT::getIntegerVT(NumBytes*8);
9170 if (!DC->isTypeLegal(VT))
Craig Topperc0196b12014-04-14 00:51:57 +00009171 return nullptr;
Wesley Peck527da1b2010-11-23 03:31:01 +00009172
Chris Lattner4041ab62010-04-15 04:48:01 +00009173 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
9174 // shifted by ByteShift and truncated down to NumBytes.
9175 if (ByteShift)
Andrew Trickef9de2a2013-05-25 02:42:55 +00009176 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
Owen Andersonb2c80da2011-02-25 21:41:48 +00009177 DAG.getConstant(ByteShift*8,
9178 DC->getShiftAmountTy(IVal.getValueType())));
Chris Lattner4041ab62010-04-15 04:48:01 +00009179
9180 // Figure out the offset for the store and the alignment of the access.
9181 unsigned StOffset;
9182 unsigned NewAlign = St->getAlignment();
9183
9184 if (DAG.getTargetLoweringInfo().isLittleEndian())
9185 StOffset = ByteShift;
9186 else
9187 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
Wesley Peck527da1b2010-11-23 03:31:01 +00009188
Chris Lattner4041ab62010-04-15 04:48:01 +00009189 SDValue Ptr = St->getBasePtr();
9190 if (StOffset) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009191 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
Chris Lattner4041ab62010-04-15 04:48:01 +00009192 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
9193 NewAlign = MinAlign(NewAlign, StOffset);
9194 }
Wesley Peck527da1b2010-11-23 03:31:01 +00009195
Chris Lattner4041ab62010-04-15 04:48:01 +00009196 // Truncate down to the new size.
Andrew Trickef9de2a2013-05-25 02:42:55 +00009197 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
Wesley Peck527da1b2010-11-23 03:31:01 +00009198
Chris Lattner4041ab62010-04-15 04:48:01 +00009199 ++OpsNarrowed;
Andrew Trickef9de2a2013-05-25 02:42:55 +00009200 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
Chris Lattner676c61d2010-09-21 18:41:36 +00009201 St->getPointerInfo().getWithOffset(StOffset),
Chris Lattner4041ab62010-04-15 04:48:01 +00009202 false, false, NewAlign).getNode();
9203}
9204
Evan Chenga9cda8a2009-05-28 00:35:15 +00009205
Sanjay Patel50cbfc52014-08-28 16:29:51 +00009206/// Look for sequence of load / op / store where op is one of 'or', 'xor', and
9207/// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
9208/// narrowing the load and store if it would end up being a win for performance
9209/// or code size.
Evan Chenga9cda8a2009-05-28 00:35:15 +00009210SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
9211 StoreSDNode *ST = cast<StoreSDNode>(N);
Evan Cheng6673ff02009-05-28 18:41:02 +00009212 if (ST->isVolatile())
9213 return SDValue();
9214
Evan Chenga9cda8a2009-05-28 00:35:15 +00009215 SDValue Chain = ST->getChain();
9216 SDValue Value = ST->getValue();
9217 SDValue Ptr = ST->getBasePtr();
Owen Anderson53aa7a92009-08-10 22:56:29 +00009218 EVT VT = Value.getValueType();
Evan Chenga9cda8a2009-05-28 00:35:15 +00009219
9220 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
Evan Cheng6673ff02009-05-28 18:41:02 +00009221 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00009222
9223 unsigned Opc = Value.getOpcode();
Wesley Peck527da1b2010-11-23 03:31:01 +00009224
Chris Lattner4041ab62010-04-15 04:48:01 +00009225 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
9226 // is a byte mask indicating a consecutive number of bytes, check to see if
9227 // Y is known to provide just those bytes. If so, we try to replace the
9228 // load + replace + store sequence with a single (narrower) store, which makes
9229 // the load dead.
9230 if (Opc == ISD::OR) {
9231 std::pair<unsigned, unsigned> MaskedLoad;
9232 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
9233 if (MaskedLoad.first)
9234 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
9235 Value.getOperand(1), ST,this))
9236 return SDValue(NewST, 0);
Wesley Peck527da1b2010-11-23 03:31:01 +00009237
Chris Lattner4041ab62010-04-15 04:48:01 +00009238 // Or is commutative, so try swapping X and Y.
9239 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
9240 if (MaskedLoad.first)
9241 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
9242 Value.getOperand(0), ST,this))
9243 return SDValue(NewST, 0);
9244 }
Wesley Peck527da1b2010-11-23 03:31:01 +00009245
Evan Chenga9cda8a2009-05-28 00:35:15 +00009246 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
9247 Value.getOperand(1).getOpcode() != ISD::Constant)
Evan Cheng6673ff02009-05-28 18:41:02 +00009248 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00009249
9250 SDValue N0 = Value.getOperand(0);
Dan Gohman3c9b5f32010-09-02 21:18:42 +00009251 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
9252 Chain == SDValue(N0.getNode(), 1)) {
Evan Chenga9cda8a2009-05-28 00:35:15 +00009253 LoadSDNode *LD = cast<LoadSDNode>(N0);
Chris Lattnerf72c3c02010-09-21 16:08:50 +00009254 if (LD->getBasePtr() != Ptr ||
9255 LD->getPointerInfo().getAddrSpace() !=
9256 ST->getPointerInfo().getAddrSpace())
Evan Cheng6673ff02009-05-28 18:41:02 +00009257 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00009258
9259 // Find the type to narrow it the load / op / store to.
9260 SDValue N1 = Value.getOperand(1);
9261 unsigned BitWidth = N1.getValueSizeInBits();
9262 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
9263 if (Opc == ISD::AND)
9264 Imm ^= APInt::getAllOnesValue(BitWidth);
Evan Cheng86cdb4b2009-05-28 23:52:18 +00009265 if (Imm == 0 || Imm.isAllOnesValue())
9266 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00009267 unsigned ShAmt = Imm.countTrailingZeros();
9268 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
9269 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
Owen Anderson117c9e82009-08-12 00:36:31 +00009270 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
Evan Chenga9cda8a2009-05-28 00:35:15 +00009271 while (NewBW < BitWidth &&
Evan Cheng6673ff02009-05-28 18:41:02 +00009272 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
Evan Chenga9cda8a2009-05-28 00:35:15 +00009273 TLI.isNarrowingProfitable(VT, NewVT))) {
9274 NewBW = NextPowerOf2(NewBW);
Owen Anderson117c9e82009-08-12 00:36:31 +00009275 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
Evan Chenga9cda8a2009-05-28 00:35:15 +00009276 }
Evan Cheng6673ff02009-05-28 18:41:02 +00009277 if (NewBW >= BitWidth)
9278 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00009279
9280 // If the lsb changed does not start at the type bitwidth boundary,
9281 // start at the previous one.
9282 if (ShAmt % NewBW)
9283 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
Manman Ren82751a12012-12-12 01:13:50 +00009284 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
9285 std::min(BitWidth, ShAmt + NewBW));
Evan Chenga9cda8a2009-05-28 00:35:15 +00009286 if ((Imm & Mask) == Imm) {
9287 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
9288 if (Opc == ISD::AND)
9289 NewImm ^= APInt::getAllOnesValue(NewBW);
9290 uint64_t PtrOff = ShAmt / 8;
9291 // For big endian targets, we need to adjust the offset to the pointer to
9292 // load the correct bytes.
9293 if (TLI.isBigEndian())
Evan Cheng6673ff02009-05-28 18:41:02 +00009294 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
Evan Chenga9cda8a2009-05-28 00:35:15 +00009295
9296 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
Chris Lattner229907c2011-07-18 04:54:35 +00009297 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
Micah Villmowcdfe20b2012-10-08 16:38:25 +00009298 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
Evan Cheng6673ff02009-05-28 18:41:02 +00009299 return SDValue();
9300
Andrew Trickef9de2a2013-05-25 02:42:55 +00009301 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
Evan Chenga9cda8a2009-05-28 00:35:15 +00009302 Ptr.getValueType(), Ptr,
9303 DAG.getConstant(PtrOff, Ptr.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +00009304 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
Evan Chenga9cda8a2009-05-28 00:35:15 +00009305 LD->getChain(), NewPtr,
Chris Lattnerf72c3c02010-09-21 16:08:50 +00009306 LD->getPointerInfo().getWithOffset(PtrOff),
David Greene39c6d012010-02-15 17:00:31 +00009307 LD->isVolatile(), LD->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009308 LD->isInvariant(), NewAlign,
Hal Finkelcc39b672014-07-24 12:16:19 +00009309 LD->getAAInfo());
Andrew Trickef9de2a2013-05-25 02:42:55 +00009310 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
Evan Chenga9cda8a2009-05-28 00:35:15 +00009311 DAG.getConstant(NewImm, NewVT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00009312 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
Evan Chenga9cda8a2009-05-28 00:35:15 +00009313 NewVal, NewPtr,
Chris Lattnerf72c3c02010-09-21 16:08:50 +00009314 ST->getPointerInfo().getWithOffset(PtrOff),
David Greene39c6d012010-02-15 17:00:31 +00009315 false, false, NewAlign);
Evan Chenga9cda8a2009-05-28 00:35:15 +00009316
Chandler Carruth3c0012b2014-07-21 08:56:44 +00009317 AddToWorklist(NewPtr.getNode());
9318 AddToWorklist(NewLD.getNode());
9319 AddToWorklist(NewVal.getNode());
9320 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00009321 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
Evan Chenga9cda8a2009-05-28 00:35:15 +00009322 ++OpsNarrowed;
9323 return NewST;
9324 }
9325 }
9326
Evan Cheng6673ff02009-05-28 18:41:02 +00009327 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00009328}
9329
Sanjay Patel50cbfc52014-08-28 16:29:51 +00009330/// For a given floating point load / store pair, if the load value isn't used
9331/// by any other operations, then consider transforming the pair to integer
9332/// load / store operations if the target deems the transformation profitable.
Evan Chengd42641c2011-02-02 01:06:55 +00009333SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
9334 StoreSDNode *ST = cast<StoreSDNode>(N);
9335 SDValue Chain = ST->getChain();
9336 SDValue Value = ST->getValue();
9337 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
9338 Value.hasOneUse() &&
9339 Chain == SDValue(Value.getNode(), 1)) {
9340 LoadSDNode *LD = cast<LoadSDNode>(Value);
9341 EVT VT = LD->getMemoryVT();
9342 if (!VT.isFloatingPoint() ||
9343 VT != ST->getMemoryVT() ||
9344 LD->isNonTemporal() ||
9345 ST->isNonTemporal() ||
9346 LD->getPointerInfo().getAddrSpace() != 0 ||
9347 ST->getPointerInfo().getAddrSpace() != 0)
9348 return SDValue();
9349
9350 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
9351 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
9352 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
9353 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
9354 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
9355 return SDValue();
9356
9357 unsigned LDAlign = LD->getAlignment();
9358 unsigned STAlign = ST->getAlignment();
Chris Lattner229907c2011-07-18 04:54:35 +00009359 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
Micah Villmowcdfe20b2012-10-08 16:38:25 +00009360 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
Evan Chengd42641c2011-02-02 01:06:55 +00009361 if (LDAlign < ABIAlign || STAlign < ABIAlign)
9362 return SDValue();
9363
Andrew Trickef9de2a2013-05-25 02:42:55 +00009364 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
Evan Chengd42641c2011-02-02 01:06:55 +00009365 LD->getChain(), LD->getBasePtr(),
9366 LD->getPointerInfo(),
Pete Cooper82cd9e82011-11-08 18:42:53 +00009367 false, false, false, LDAlign);
Evan Chengd42641c2011-02-02 01:06:55 +00009368
Andrew Trickef9de2a2013-05-25 02:42:55 +00009369 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
Evan Chengd42641c2011-02-02 01:06:55 +00009370 NewLD, ST->getBasePtr(),
9371 ST->getPointerInfo(),
9372 false, false, STAlign);
9373
Chandler Carruth3c0012b2014-07-21 08:56:44 +00009374 AddToWorklist(NewLD.getNode());
9375 AddToWorklist(NewST.getNode());
9376 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00009377 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
Evan Chengd42641c2011-02-02 01:06:55 +00009378 ++LdStFP2Int;
9379 return NewST;
9380 }
9381
9382 return SDValue();
9383}
9384
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009385/// Helper struct to parse and store a memory address as base + index + offset.
9386/// We ignore sign extensions when it is safe to do so.
9387/// The following two expressions are not equivalent. To differentiate we need
9388/// to store whether there was a sign extension involved in the index
9389/// computation.
9390/// (load (i64 add (i64 copyfromreg %c)
9391/// (i64 signextend (add (i8 load %index)
9392/// (i8 1))))
9393/// vs
9394///
9395/// (load (i64 add (i64 copyfromreg %c)
9396/// (i64 signextend (i32 add (i32 signextend (i8 load %index))
9397/// (i32 1)))))
9398struct BaseIndexOffset {
9399 SDValue Base;
9400 SDValue Index;
9401 int64_t Offset;
9402 bool IsIndexSignExt;
9403
9404 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
9405
9406 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
9407 bool IsIndexSignExt) :
9408 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
9409
9410 bool equalBaseIndex(const BaseIndexOffset &Other) {
9411 return Other.Base == Base && Other.Index == Index &&
9412 Other.IsIndexSignExt == IsIndexSignExt;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009413 }
9414
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009415 /// Parses tree in Ptr for base, index, offset addresses.
9416 static BaseIndexOffset match(SDValue Ptr) {
9417 bool IsIndexSignExt = false;
9418
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00009419 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
9420 // instruction, then it could be just the BASE or everything else we don't
9421 // know how to handle. Just use Ptr as BASE and give up.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009422 if (Ptr->getOpcode() != ISD::ADD)
9423 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9424
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00009425 // We know that we have at least an ADD instruction. Try to pattern match
9426 // the simple case of BASE + OFFSET.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009427 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
9428 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
9429 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
9430 IsIndexSignExt);
9431 }
9432
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00009433 // Inside a loop the current BASE pointer is calculated using an ADD and a
Juergen Ributzka11c52c62013-08-28 22:33:58 +00009434 // MUL instruction. In this case Ptr is the actual BASE pointer.
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00009435 // (i64 add (i64 %array_ptr)
9436 // (i64 mul (i64 %induction_var)
9437 // (i64 %element_size)))
Juergen Ributzka11c52c62013-08-28 22:33:58 +00009438 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00009439 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00009440
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009441 // Look at Base + Index + Offset cases.
9442 SDValue Base = Ptr->getOperand(0);
9443 SDValue IndexOffset = Ptr->getOperand(1);
9444
9445 // Skip signextends.
9446 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
9447 IndexOffset = IndexOffset->getOperand(0);
9448 IsIndexSignExt = true;
9449 }
9450
9451 // Either the case of Base + Index (no offset) or something else.
9452 if (IndexOffset->getOpcode() != ISD::ADD)
9453 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
9454
9455 // Now we have the case of Base + Index + offset.
9456 SDValue Index = IndexOffset->getOperand(0);
9457 SDValue Offset = IndexOffset->getOperand(1);
9458
9459 if (!isa<ConstantSDNode>(Offset))
9460 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9461
9462 // Ignore signextends.
9463 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
9464 Index = Index->getOperand(0);
9465 IsIndexSignExt = true;
9466 } else IsIndexSignExt = false;
9467
9468 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
9469 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
9470 }
9471};
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009472
9473/// Holds a pointer to an LSBaseSDNode as well as information on where it
9474/// is located in a sequence of memory operations connected by a chain.
9475struct MemOpLink {
9476 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
9477 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
9478 // Ptr to the mem node.
9479 LSBaseSDNode *MemNode;
9480 // Offset from the base ptr.
9481 int64_t OffsetFromBase;
9482 // What is the sequence number of this mem node.
9483 // Lowest mem operand in the DAG starts at zero.
9484 unsigned SequenceNum;
9485};
9486
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009487bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
9488 EVT MemVT = St->getMemoryVT();
9489 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
Nadav Rotem495b1a42013-02-14 18:28:52 +00009490 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
9491 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009492
9493 // Don't merge vectors into wider inputs.
9494 if (MemVT.isVector() || !MemVT.isSimple())
9495 return false;
9496
9497 // Perform an early exit check. Do not bother looking at stored values that
9498 // are not constants or loads.
9499 SDValue StoredVal = St->getValue();
9500 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
9501 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
9502 !IsLoadSrc)
9503 return false;
9504
9505 // Only look at ends of store sequences.
Chandler Carruth94bd5532014-07-25 07:23:23 +00009506 SDValue Chain = SDValue(St, 0);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009507 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9508 return false;
9509
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009510 // This holds the base pointer, index, and the offset in bytes from the base
9511 // pointer.
9512 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009513
9514 // We must have a base and an offset.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009515 if (!BasePtr.Base.getNode())
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009516 return false;
9517
9518 // Do not handle stores to undef base pointers.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009519 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009520 return false;
9521
Nadav Rotem307d7672012-11-29 00:00:08 +00009522 // Save the LoadSDNodes that we find in the chain.
9523 // We need to make sure that these nodes do not interfere with
9524 // any of the store nodes.
9525 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9526
9527 // Save the StoreSDNodes that we find in the chain.
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009528 SmallVector<MemOpLink, 8> StoreNodes;
Nadav Rotem307d7672012-11-29 00:00:08 +00009529
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009530 // Walk up the chain and look for nodes with offsets from the same
9531 // base pointer. Stop when reaching an instruction with a different kind
9532 // or instruction which has a different base pointer.
9533 unsigned Seq = 0;
9534 StoreSDNode *Index = St;
9535 while (Index) {
9536 // If the chain has more than one use, then we can't reorder the mem ops.
Matt Arsenault197a1e22014-07-25 07:56:42 +00009537 if (Index != St && !SDValue(Index, 0)->hasOneUse())
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009538 break;
9539
9540 // Find the base pointer and offset for this memory node.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009541 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009542
9543 // Check that the base pointer is the same as the original one.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009544 if (!Ptr.equalBaseIndex(BasePtr))
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009545 break;
9546
9547 // Check that the alignment is the same.
9548 if (Index->getAlignment() != St->getAlignment())
9549 break;
9550
9551 // The memory operands must not be volatile.
9552 if (Index->isVolatile() || Index->isIndexed())
9553 break;
9554
9555 // No truncation.
9556 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9557 if (St->isTruncatingStore())
9558 break;
9559
9560 // The stored memory type must be the same.
9561 if (Index->getMemoryVT() != MemVT)
9562 break;
9563
9564 // We do not allow unaligned stores because we want to prevent overriding
9565 // stores.
9566 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9567 break;
9568
9569 // We found a potential memory operand to merge.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009570 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009571
Nadav Rotem307d7672012-11-29 00:00:08 +00009572 // Find the next memory operand in the chain. If the next operand in the
9573 // chain is a store then move up and continue the scan with the next
9574 // memory operand. If the next operand is a load save it and use alias
9575 // information to check if it interferes with anything.
9576 SDNode *NextInChain = Index->getChain().getNode();
9577 while (1) {
Nadav Rotemac450eb2012-12-06 17:34:13 +00009578 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
Nadav Rotem307d7672012-11-29 00:00:08 +00009579 // We found a store node. Use it for the next iteration.
Nadav Rotemac450eb2012-12-06 17:34:13 +00009580 Index = STn;
Nadav Rotem307d7672012-11-29 00:00:08 +00009581 break;
9582 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
Bill Wendling9200bb02013-11-25 18:05:22 +00009583 if (Ldn->isVolatile()) {
Craig Topperc0196b12014-04-14 00:51:57 +00009584 Index = nullptr;
Bill Wendling9200bb02013-11-25 18:05:22 +00009585 break;
9586 }
9587
Nadav Rotem307d7672012-11-29 00:00:08 +00009588 // Save the load node for later. Continue the scan.
9589 AliasLoadNodes.push_back(Ldn);
9590 NextInChain = Ldn->getChain().getNode();
9591 continue;
9592 } else {
Craig Topperc0196b12014-04-14 00:51:57 +00009593 Index = nullptr;
Nadav Rotem307d7672012-11-29 00:00:08 +00009594 break;
9595 }
9596 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009597 }
9598
9599 // Check if there is anything to merge.
9600 if (StoreNodes.size() < 2)
9601 return false;
9602
9603 // Sort the memory operands according to their distance from the base pointer.
9604 std::sort(StoreNodes.begin(), StoreNodes.end(),
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00009605 [](MemOpLink LHS, MemOpLink RHS) {
9606 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9607 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9608 LHS.SequenceNum > RHS.SequenceNum);
9609 });
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009610
9611 // Scan the memory operations on the chain and find the first non-consecutive
9612 // store memory address.
9613 unsigned LastConsecutiveStore = 0;
9614 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
Nadav Rotemac450eb2012-12-06 17:34:13 +00009615 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9616
9617 // Check that the addresses are consecutive starting from the second
9618 // element in the list of stores.
9619 if (i > 0) {
9620 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9621 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9622 break;
9623 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009624
Nadav Rotem307d7672012-11-29 00:00:08 +00009625 bool Alias = false;
9626 // Check if this store interferes with any of the loads that we found.
9627 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9628 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9629 Alias = true;
9630 break;
9631 }
Nadav Rotem307d7672012-11-29 00:00:08 +00009632 // We found a load that alias with this store. Stop the sequence.
9633 if (Alias)
9634 break;
9635
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009636 // Mark this node as useful.
9637 LastConsecutiveStore = i;
9638 }
9639
9640 // The node with the lowest store address.
9641 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9642
9643 // Store the constants into memory as one consecutive store.
9644 if (!IsLoadSrc) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009645 unsigned LastLegalType = 0;
Nadav Rotemb27777f2012-10-04 22:35:15 +00009646 unsigned LastLegalVectorType = 0;
9647 bool NonZero = false;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009648 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9649 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9650 SDValue StoredVal = St->getValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +00009651
9652 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
Benjamin Kramer62f7fb92012-10-05 18:19:44 +00009653 NonZero |= !C->isNullValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +00009654 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
Benjamin Kramer62f7fb92012-10-05 18:19:44 +00009655 NonZero |= !C->getConstantFPValue()->isNullValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +00009656 } else {
Alp Tokerf907b892013-12-05 05:44:44 +00009657 // Non-constant.
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009658 break;
Nadav Rotemb27777f2012-10-04 22:35:15 +00009659 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009660
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009661 // Find a legal type for the constant store.
9662 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9663 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9664 if (TLI.isTypeLegal(StoreTy))
9665 LastLegalType = i+1;
Arnold Schwaighoferd6c6e862013-04-02 15:58:51 +00009666 // Or check whether a truncstore is legal.
9667 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9668 TargetLowering::TypePromoteInteger) {
9669 EVT LegalizedStoredValueTy =
9670 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9671 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9672 LastLegalType = i+1;
9673 }
Nadav Rotemb27777f2012-10-04 22:35:15 +00009674
9675 // Find a legal type for the vector store.
9676 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9677 if (TLI.isTypeLegal(Ty))
9678 LastLegalVectorType = i + 1;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009679 }
9680
Bob Wilson3365b802012-12-20 01:36:20 +00009681 // We only use vectors if the constant is known to be zero and the
9682 // function is not marked with the noimplicitfloat attribute.
Nadav Rotem495b1a42013-02-14 18:28:52 +00009683 if (NonZero || NoVectors)
Nadav Rotemb27777f2012-10-04 22:35:15 +00009684 LastLegalVectorType = 0;
9685
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009686 // Check if we found a legal integer type to store.
Nadav Rotemb27777f2012-10-04 22:35:15 +00009687 if (LastLegalType == 0 && LastLegalVectorType == 0)
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009688 return false;
9689
Nadav Rotem495b1a42013-02-14 18:28:52 +00009690 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
Nadav Rotemb27777f2012-10-04 22:35:15 +00009691 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9692
9693 // Make sure we have something to merge.
9694 if (NumElem < 2)
9695 return false;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009696
9697 unsigned EarliestNodeUsed = 0;
9698 for (unsigned i=0; i < NumElem; ++i) {
9699 // Find a chain for the new wide-store operand. Notice that some
9700 // of the store nodes that we found may not be selected for inclusion
9701 // in the wide store. The chain we use needs to be the chain of the
9702 // earliest store node which is *used* and replaced by the wide store.
9703 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9704 EarliestNodeUsed = i;
9705 }
9706
9707 // The earliest Node in the DAG.
9708 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
Andrew Trickef9de2a2013-05-25 02:42:55 +00009709 SDLoc DL(StoreNodes[0].MemNode);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009710
Nadav Rotemb27777f2012-10-04 22:35:15 +00009711 SDValue StoredVal;
9712 if (UseVector) {
9713 // Find a legal type for the vector store.
9714 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9715 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9716 StoredVal = DAG.getConstant(0, Ty);
9717 } else {
9718 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9719 APInt StoreInt(StoreBW, 0);
9720
9721 // Construct a single integer constant which is made of the smaller
9722 // constant inputs.
9723 bool IsLE = TLI.isLittleEndian();
9724 for (unsigned i = 0; i < NumElem ; ++i) {
9725 unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9726 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9727 SDValue Val = St->getValue();
9728 StoreInt<<=ElementSizeBytes*8;
9729 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9730 StoreInt|=C->getAPIntValue().zext(StoreBW);
9731 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9732 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9733 } else {
9734 assert(false && "Invalid constant element type");
9735 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009736 }
Nadav Rotemb27777f2012-10-04 22:35:15 +00009737
9738 // Create the new Load and Store operations.
9739 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9740 StoredVal = DAG.getConstant(StoreInt, StoreTy);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009741 }
9742
Nadav Rotemb27777f2012-10-04 22:35:15 +00009743 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009744 FirstInChain->getBasePtr(),
9745 FirstInChain->getPointerInfo(),
9746 false, false,
9747 FirstInChain->getAlignment());
9748
9749 // Replace the first store with the new store
9750 CombineTo(EarliestOp, NewStore);
9751 // Erase all other stores.
9752 for (unsigned i = 0; i < NumElem ; ++i) {
9753 if (StoreNodes[i].MemNode == EarliestOp)
9754 continue;
9755 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
Rafael Espindolac79532d2012-11-14 05:08:56 +00009756 // ReplaceAllUsesWith will replace all uses that existed when it was
9757 // called, but graph optimizations may cause new ones to appear. For
9758 // example, the case in pr14333 looks like
9759 //
9760 // St's chain -> St -> another store -> X
9761 //
9762 // And the only difference from St to the other store is the chain.
9763 // When we change it's chain to be St's chain they become identical,
9764 // get CSEed and the net result is that X is now a use of St.
9765 // Since we know that St is redundant, just iterate.
9766 while (!St->use_empty())
9767 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
Chandler Carruth18066972014-08-02 10:02:07 +00009768 deleteAndRecombine(St);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009769 }
9770
9771 return true;
9772 }
9773
9774 // Below we handle the case of multiple consecutive stores that
9775 // come from multiple consecutive loads. We merge them into a single
9776 // wide load and a single wide store.
9777
9778 // Look for load nodes which are used by the stored values.
9779 SmallVector<MemOpLink, 8> LoadNodes;
9780
9781 // Find acceptable loads. Loads need to have the same chain (token factor),
9782 // must not be zext, volatile, indexed, and they must be consecutive.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009783 BaseIndexOffset LdBasePtr;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009784 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9785 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9786 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9787 if (!Ld) break;
9788
9789 // Loads must only have one use.
9790 if (!Ld->hasNUsesOfValue(1, 0))
9791 break;
9792
9793 // Check that the alignment is the same as the stores.
9794 if (Ld->getAlignment() != St->getAlignment())
9795 break;
9796
9797 // The memory operands must not be volatile.
9798 if (Ld->isVolatile() || Ld->isIndexed())
9799 break;
9800
9801 // We do not accept ext loads.
9802 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9803 break;
9804
9805 // The stored memory type must be the same.
9806 if (Ld->getMemoryVT() != MemVT)
9807 break;
9808
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009809 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009810 // If this is not the first ptr that we check.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009811 if (LdBasePtr.Base.getNode()) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009812 // The base ptr must be the same.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009813 if (!LdPtr.equalBaseIndex(LdBasePtr))
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009814 break;
9815 } else {
9816 // Check that all other base pointers are the same as this one.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009817 LdBasePtr = LdPtr;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009818 }
9819
9820 // We found a potential memory operand to merge.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009821 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009822 }
9823
9824 if (LoadNodes.size() < 2)
9825 return false;
9826
James Molloyce45be02014-08-02 14:51:24 +00009827 // If we have load/store pair instructions and we only have two values,
9828 // don't bother.
9829 unsigned RequiredAlignment;
9830 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
9831 St->getAlignment() >= RequiredAlignment)
9832 return false;
9833
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009834 // Scan the memory operations on the chain and find the first non-consecutive
9835 // load memory address. These variables hold the index in the store node
9836 // array.
9837 unsigned LastConsecutiveLoad = 0;
9838 // This variable refers to the size and not index in the array.
9839 unsigned LastLegalVectorType = 0;
9840 unsigned LastLegalIntegerType = 0;
9841 StartAddress = LoadNodes[0].OffsetFromBase;
Nadav Rotemac920662012-10-03 19:30:31 +00009842 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9843 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9844 // All loads much share the same chain.
9845 if (LoadNodes[i].MemNode->getChain() != FirstChain)
9846 break;
Nadav Rotem495b1a42013-02-14 18:28:52 +00009847
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009848 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9849 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9850 break;
9851 LastConsecutiveLoad = i;
9852
9853 // Find a legal type for the vector store.
9854 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9855 if (TLI.isTypeLegal(StoreTy))
9856 LastLegalVectorType = i + 1;
9857
9858 // Find a legal type for the integer store.
9859 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9860 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9861 if (TLI.isTypeLegal(StoreTy))
9862 LastLegalIntegerType = i + 1;
Arnold Schwaighoferd6c6e862013-04-02 15:58:51 +00009863 // Or check whether a truncstore and extload is legal.
9864 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9865 TargetLowering::TypePromoteInteger) {
9866 EVT LegalizedStoredValueTy =
9867 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9868 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9869 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9870 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9871 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9872 LastLegalIntegerType = i+1;
9873 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009874 }
9875
9876 // Only use vector types if the vector type is larger than the integer type.
9877 // If they are the same, use integers.
Nadav Rotem495b1a42013-02-14 18:28:52 +00009878 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009879 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9880
9881 // We add +1 here because the LastXXX variables refer to location while
9882 // the NumElem refers to array/index size.
9883 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9884 NumElem = std::min(LastLegalType, NumElem);
9885
9886 if (NumElem < 2)
9887 return false;
9888
9889 // The earliest Node in the DAG.
9890 unsigned EarliestNodeUsed = 0;
9891 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9892 for (unsigned i=1; i<NumElem; ++i) {
9893 // Find a chain for the new wide-store operand. Notice that some
9894 // of the store nodes that we found may not be selected for inclusion
9895 // in the wide store. The chain we use needs to be the chain of the
9896 // earliest store node which is *used* and replaced by the wide store.
9897 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9898 EarliestNodeUsed = i;
9899 }
9900
9901 // Find if it is better to use vectors or integers to load and store
9902 // to memory.
9903 EVT JointMemOpVT;
9904 if (UseVectorTy) {
9905 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9906 } else {
9907 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9908 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9909 }
9910
Andrew Trickef9de2a2013-05-25 02:42:55 +00009911 SDLoc LoadDL(LoadNodes[0].MemNode);
9912 SDLoc StoreDL(StoreNodes[0].MemNode);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009913
9914 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9915 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9916 FirstLoad->getChain(),
9917 FirstLoad->getBasePtr(),
9918 FirstLoad->getPointerInfo(),
9919 false, false, false,
9920 FirstLoad->getAlignment());
9921
9922 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9923 FirstInChain->getBasePtr(),
9924 FirstInChain->getPointerInfo(), false, false,
9925 FirstInChain->getAlignment());
9926
Nadav Rotemac920662012-10-03 19:30:31 +00009927 // Replace one of the loads with the new load.
9928 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9929 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9930 SDValue(NewLoad.getNode(), 1));
9931
9932 // Remove the rest of the load chains.
9933 for (unsigned i = 1; i < NumElem ; ++i) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009934 // Replace all chain users of the old load nodes with the chain of the new
9935 // load node.
9936 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
Nadav Rotemac920662012-10-03 19:30:31 +00009937 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9938 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009939
Nadav Rotemac920662012-10-03 19:30:31 +00009940 // Replace the first store with the new store.
9941 CombineTo(EarliestOp, NewStore);
9942 // Erase all other stores.
9943 for (unsigned i = 0; i < NumElem ; ++i) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009944 // Remove all Store nodes.
9945 if (StoreNodes[i].MemNode == EarliestOp)
9946 continue;
9947 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9948 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
Chandler Carruth18066972014-08-02 10:02:07 +00009949 deleteAndRecombine(St);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009950 }
9951
9952 return true;
9953}
9954
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009955SDValue DAGCombiner::visitSTORE(SDNode *N) {
Evan Chengab51cf22006-10-13 21:14:26 +00009956 StoreSDNode *ST = cast<StoreSDNode>(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009957 SDValue Chain = ST->getChain();
9958 SDValue Value = ST->getValue();
9959 SDValue Ptr = ST->getBasePtr();
Scott Michelcf0da6c2009-02-17 22:15:04 +00009960
Evan Chenga4cf58a2007-05-07 21:27:48 +00009961 // If this is a store of a bit convert, store the input value if the
Evan Chengf325c2a2007-05-09 21:49:47 +00009962 // resultant store does not need a higher alignment than the original.
Wesley Peck527da1b2010-11-23 03:31:01 +00009963 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009964 ST->isUnindexed()) {
Dan Gohmane7fe80f2009-02-20 23:29:13 +00009965 unsigned OrigAlign = ST->getAlignment();
Owen Anderson53aa7a92009-08-10 22:56:29 +00009966 EVT SVT = Value.getOperand(0).getValueType();
Micah Villmowcdfe20b2012-10-08 16:38:25 +00009967 unsigned Align = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +00009968 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
Duncan Sands8651e9c2008-06-13 19:07:40 +00009969 if (Align <= OrigAlign &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00009970 ((!LegalOperations && !ST->isVolatile()) ||
Dan Gohman4aa18462009-01-28 17:46:25 +00009971 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00009972 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
Chris Lattner676c61d2010-09-21 18:41:36 +00009973 Ptr, ST->getPointerInfo(), ST->isVolatile(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009974 ST->isNonTemporal(), OrigAlign,
Hal Finkelcc39b672014-07-24 12:16:19 +00009975 ST->getAAInfo());
Jim Laskeyd07be232006-09-25 16:29:54 +00009976 }
Owen Andersona5192842011-04-14 17:30:49 +00009977
Chris Lattner41c80e82011-04-09 02:32:02 +00009978 // Turn 'store undef, Ptr' -> nothing.
9979 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9980 return Chain;
Duncan Sands8651e9c2008-06-13 19:07:40 +00009981
Nate Begeman8e20c762006-12-11 02:23:46 +00009982 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
Nate Begeman8e20c762006-12-11 02:23:46 +00009983 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
Duncan Sands8651e9c2008-06-13 19:07:40 +00009984 // NOTE: If the original store is volatile, this transform must not increase
9985 // the number of stores. For example, on x86-32 an f64 can be stored in one
9986 // processor operation but an i64 (which is not legal) requires two. So the
9987 // transform should not be done in this case.
Evan Cheng21836982006-12-11 17:25:19 +00009988 if (Value.getOpcode() != ISD::TargetConstantFP) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009989 SDValue Tmp;
Craig Topperd9c27832013-08-15 02:44:19 +00009990 switch (CFP->getSimpleValueType(0).SimpleTy) {
Torok Edwinfbcc6632009-07-14 16:55:14 +00009991 default: llvm_unreachable("Unknown FP type");
Pete Cooper5b614222012-06-21 18:00:39 +00009992 case MVT::f16: // We don't do this for these yet.
9993 case MVT::f80:
Owen Anderson9f944592009-08-11 20:47:22 +00009994 case MVT::f128:
9995 case MVT::ppcf128:
Dale Johannesenaf12b572007-09-18 18:36:59 +00009996 break;
Owen Anderson9f944592009-08-11 20:47:22 +00009997 case MVT::f32:
Chris Lattner4041ab62010-04-15 04:48:01 +00009998 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
Owen Anderson9f944592009-08-11 20:47:22 +00009999 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
Dale Johannesen028084e2007-09-12 03:30:33 +000010000 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
Owen Anderson9f944592009-08-11 20:47:22 +000010001 bitcastToAPInt().getZExtValue(), MVT::i32);
Andrew Trickef9de2a2013-05-25 02:42:55 +000010002 return DAG.getStore(Chain, SDLoc(N), Tmp,
Richard Sandiford39c1ce42013-10-28 11:17:59 +000010003 Ptr, ST->getMemOperand());
Chris Lattnerb7524b62006-12-12 04:16:14 +000010004 }
10005 break;
Owen Anderson9f944592009-08-11 20:47:22 +000010006 case MVT::f64:
Chris Lattner4041ab62010-04-15 04:48:01 +000010007 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
Dan Gohman4aa18462009-01-28 17:46:25 +000010008 !ST->isVolatile()) ||
Owen Anderson9f944592009-08-11 20:47:22 +000010009 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
Dale Johannesen54306fe2008-10-09 18:53:47 +000010010 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
Owen Anderson9f944592009-08-11 20:47:22 +000010011 getZExtValue(), MVT::i64);
Andrew Trickef9de2a2013-05-25 02:42:55 +000010012 return DAG.getStore(Chain, SDLoc(N), Tmp,
Richard Sandiford39c1ce42013-10-28 11:17:59 +000010013 Ptr, ST->getMemOperand());
Chris Lattner41c80e82011-04-09 02:32:02 +000010014 }
Owen Andersona5192842011-04-14 17:30:49 +000010015
Chris Lattner41c80e82011-04-09 02:32:02 +000010016 if (!ST->isVolatile() &&
10017 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
Duncan Sands1826ded2007-10-28 12:59:45 +000010018 // Many FP stores are not made apparent until after legalize, e.g. for
Chris Lattnerb7524b62006-12-12 04:16:14 +000010019 // argument passing. Since this is so common, custom legalize the
10020 // 64-bit integer store into two 32-bit stores.
Dale Johannesen54306fe2008-10-09 18:53:47 +000010021 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
Owen Anderson9f944592009-08-11 20:47:22 +000010022 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
10023 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
Duncan Sands7377f5f2008-02-11 10:37:04 +000010024 if (TLI.isBigEndian()) std::swap(Lo, Hi);
Chris Lattnerb7524b62006-12-12 04:16:14 +000010025
Dan Gohman2af30632007-07-09 22:18:38 +000010026 unsigned Alignment = ST->getAlignment();
10027 bool isVolatile = ST->isVolatile();
David Greene39c6d012010-02-15 17:00:31 +000010028 bool isNonTemporal = ST->isNonTemporal();
Hal Finkelcc39b672014-07-24 12:16:19 +000010029 AAMDNodes AAInfo = ST->getAAInfo();
Dan Gohman2af30632007-07-09 22:18:38 +000010030
Andrew Trickef9de2a2013-05-25 02:42:55 +000010031 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
Chris Lattner676c61d2010-09-21 18:41:36 +000010032 Ptr, ST->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +000010033 isVolatile, isNonTemporal,
Hal Finkelcc39b672014-07-24 12:16:19 +000010034 ST->getAlignment(), AAInfo);
Andrew Trickef9de2a2013-05-25 02:42:55 +000010035 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
Chris Lattnerb7524b62006-12-12 04:16:14 +000010036 DAG.getConstant(4, Ptr.getValueType()));
Duncan Sands1826ded2007-10-28 12:59:45 +000010037 Alignment = MinAlign(Alignment, 4U);
Andrew Trickef9de2a2013-05-25 02:42:55 +000010038 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
Chris Lattner676c61d2010-09-21 18:41:36 +000010039 Ptr, ST->getPointerInfo().getWithOffset(4),
10040 isVolatile, isNonTemporal,
Hal Finkelcc39b672014-07-24 12:16:19 +000010041 Alignment, AAInfo);
Andrew Trickef9de2a2013-05-25 02:42:55 +000010042 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
Bill Wendling27d9dd42009-01-30 23:36:47 +000010043 St0, St1);
Chris Lattnerb7524b62006-12-12 04:16:14 +000010044 }
Bill Wendling27d9dd42009-01-30 23:36:47 +000010045
Chris Lattnerb7524b62006-12-12 04:16:14 +000010046 break;
Evan Cheng21836982006-12-11 17:25:19 +000010047 }
Nate Begeman8e20c762006-12-11 02:23:46 +000010048 }
Nate Begeman8e20c762006-12-11 02:23:46 +000010049 }
10050
Evan Cheng43cd9e32010-04-01 06:04:33 +000010051 // Try to infer better alignment information than the store already has.
10052 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
Evan Cheng4a5b2042011-11-28 22:37:34 +000010053 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
10054 if (Align > ST->getAlignment())
Andrew Trickef9de2a2013-05-25 02:42:55 +000010055 return DAG.getTruncStore(Chain, SDLoc(N), Value,
Evan Cheng4a5b2042011-11-28 22:37:34 +000010056 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +000010057 ST->isVolatile(), ST->isNonTemporal(), Align,
Hal Finkelcc39b672014-07-24 12:16:19 +000010058 ST->getAAInfo());
Evan Cheng43cd9e32010-04-01 06:04:33 +000010059 }
10060 }
10061
Evan Chengd42641c2011-02-02 01:06:55 +000010062 // Try transforming a pair floating point load / store ops to integer
10063 // load / store ops.
10064 SDValue NewST = TransformFPLoadStorePair(N);
10065 if (NewST.getNode())
10066 return NewST;
10067
Eric Christopherf55d4712014-10-08 23:38:39 +000010068 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
10069 : DAG.getSubtarget().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +000010070#ifndef NDEBUG
10071 if (CombinerAAOnlyFunc.getNumOccurrences() &&
10072 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
10073 UseAA = false;
10074#endif
Hal Finkelccc18e12014-01-24 18:25:26 +000010075 if (UseAA && ST->isUnindexed()) {
Jim Laskeyd07be232006-09-25 16:29:54 +000010076 // Walk up chain skipping non-aliasing memory nodes.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010077 SDValue BetterChain = FindBetterChain(N, Chain);
Scott Michelcf0da6c2009-02-17 22:15:04 +000010078
Jim Laskey708d0db2006-10-04 16:53:27 +000010079 // If there is a better chain.
Jim Laskeyd07be232006-09-25 16:29:54 +000010080 if (Chain != BetterChain) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010081 SDValue ReplStore;
Nate Begeman879d8f12009-09-15 00:18:30 +000010082
10083 // Replace the chain to avoid dependency.
Jim Laskey3bf4f3b2006-10-14 12:14:27 +000010084 if (ST->isTruncatingStore()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010085 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
Richard Sandiford39c1ce42013-10-28 11:17:59 +000010086 ST->getMemoryVT(), ST->getMemOperand());
Jim Laskey3bf4f3b2006-10-14 12:14:27 +000010087 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010088 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
Richard Sandiford39c1ce42013-10-28 11:17:59 +000010089 ST->getMemOperand());
Jim Laskey3bf4f3b2006-10-14 12:14:27 +000010090 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010091
Jim Laskeyd07be232006-09-25 16:29:54 +000010092 // Create token to keep both nodes around.
Andrew Trickef9de2a2013-05-25 02:42:55 +000010093 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
Owen Anderson9f944592009-08-11 20:47:22 +000010094 MVT::Other, Chain, ReplStore);
Bill Wendling27d9dd42009-01-30 23:36:47 +000010095
Nate Begeman879d8f12009-09-15 00:18:30 +000010096 // Make sure the new and old chains are cleaned up.
Chandler Carruth3c0012b2014-07-21 08:56:44 +000010097 AddToWorklist(Token.getNode());
Nate Begeman879d8f12009-09-15 00:18:30 +000010098
Jim Laskeydcf983c2006-10-13 23:32:28 +000010099 // Don't add users to work list.
10100 return CombineTo(N, Token, false);
Jim Laskeyd07be232006-09-25 16:29:54 +000010101 }
Jim Laskey5d19d592006-09-21 16:28:59 +000010102 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010103
Evan Cheng33157702006-11-05 09:31:14 +000010104 // Try transforming N to an indexed store.
Evan Cheng60c68462006-11-07 09:03:05 +000010105 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010106 return SDValue(N, 0);
Evan Cheng33157702006-11-05 09:31:14 +000010107
Chris Lattner3f9c6a72007-12-29 06:26:16 +000010108 // FIXME: is there such a thing as a truncating indexed store?
Chris Lattner1ea55cf2008-01-17 19:59:44 +000010109 if (ST->isTruncatingStore() && ST->isUnindexed() &&
Nadav Rotemd2d9bdb2011-06-15 11:19:12 +000010110 Value.getValueType().isInteger()) {
Chris Lattner5e6fe052007-10-13 06:35:54 +000010111 // See if we can simplify the input to this truncstore with knowledge that
10112 // only the low bits are being used. For example:
10113 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
Scott Michelcf0da6c2009-02-17 22:15:04 +000010114 SDValue Shorter =
Dan Gohman1f372ed2008-02-25 21:11:39 +000010115 GetDemandedBits(Value,
Nadav Rotemd2d9bdb2011-06-15 11:19:12 +000010116 APInt::getLowBitsSet(
10117 Value.getValueType().getScalarType().getSizeInBits(),
10118 ST->getMemoryVT().getScalarType().getSizeInBits()));
Chandler Carruth3c0012b2014-07-21 08:56:44 +000010119 AddToWorklist(Value.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +000010120 if (Shorter.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +000010121 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
Richard Sandiford39c1ce42013-10-28 11:17:59 +000010122 Ptr, ST->getMemoryVT(), ST->getMemOperand());
Scott Michelcf0da6c2009-02-17 22:15:04 +000010123
Chris Lattnerf47e3062007-10-13 06:58:48 +000010124 // Otherwise, see if we can simplify the operation with
10125 // SimplifyDemandedBits, which only works if the value has a single use.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +000010126 if (SimplifyDemandedBits(Value,
Eric Christopherd9e8eac2010-12-09 04:48:06 +000010127 APInt::getLowBitsSet(
10128 Value.getValueType().getScalarType().getSizeInBits(),
10129 ST->getMemoryVT().getScalarType().getSizeInBits())))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010130 return SDValue(N, 0);
Chris Lattner5e6fe052007-10-13 06:35:54 +000010131 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010132
Chris Lattner3f9c6a72007-12-29 06:26:16 +000010133 // If this is a load followed by a store to the same location, then the store
10134 // is dead/noop.
10135 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
Dan Gohman47a7d6f2008-01-30 00:15:11 +000010136 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +000010137 ST->isUnindexed() && !ST->isVolatile() &&
Chris Lattner51b01bf2008-01-08 23:08:06 +000010138 // There can't be any side effects between the load and store, such as
10139 // a call or store.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010140 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
Chris Lattner3f9c6a72007-12-29 06:26:16 +000010141 // The store is dead, remove it.
10142 return Chain;
10143 }
10144 }
Duncan Sands8651e9c2008-06-13 19:07:40 +000010145
James Molloy463db9a2014-09-27 17:02:54 +000010146 // If this is a store followed by a store with the same value to the same
10147 // location, then the store is dead/noop.
10148 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
10149 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
10150 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
10151 ST1->isUnindexed() && !ST1->isVolatile()) {
10152 // The store is dead, remove it.
10153 return Chain;
10154 }
10155 }
10156
Chris Lattner1ea55cf2008-01-17 19:59:44 +000010157 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
10158 // truncating store. We can do this even if this is already a truncstore.
10159 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
Gabor Greiff304a7a2008-08-28 21:40:38 +000010160 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +000010161 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
Dan Gohman47a7d6f2008-01-30 00:15:11 +000010162 ST->getMemoryVT())) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010163 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
Richard Sandiford39c1ce42013-10-28 11:17:59 +000010164 Ptr, ST->getMemoryVT(), ST->getMemOperand());
Chris Lattner1ea55cf2008-01-17 19:59:44 +000010165 }
Duncan Sands8651e9c2008-06-13 19:07:40 +000010166
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010167 // Only perform this optimization before the types are legal, because we
Nadav Rotemb27777f2012-10-04 22:35:15 +000010168 // don't want to perform this optimization on every DAGCombine invocation.
Nadav Rotem1157e142012-12-02 17:14:09 +000010169 if (!LegalTypes) {
10170 bool EverChanged = false;
10171
10172 do {
10173 // There can be multiple store sequences on the same chain.
10174 // Keep trying to merge store sequences until we are unable to do so
10175 // or until we merge the last store on the chain.
10176 bool Changed = MergeConsecutiveStores(ST);
10177 EverChanged |= Changed;
10178 if (!Changed) break;
10179 } while (ST->getOpcode() != ISD::DELETED_NODE);
10180
10181 if (EverChanged)
10182 return SDValue(N, 0);
10183 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010184
Evan Chenga9cda8a2009-05-28 00:35:15 +000010185 return ReduceLoadOpStoreWidth(N);
Chris Lattner04c73702005-10-10 22:31:19 +000010186}
10187
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010188SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
10189 SDValue InVec = N->getOperand(0);
10190 SDValue InVal = N->getOperand(1);
10191 SDValue EltNo = N->getOperand(2);
Andrew Trickef9de2a2013-05-25 02:42:55 +000010192 SDLoc dl(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +000010193
Bob Wilson42603952010-05-19 23:42:58 +000010194 // If the inserted element is an UNDEF, just use the input vector.
10195 if (InVal.getOpcode() == ISD::UNDEF)
10196 return InVec;
10197
Nadav Rotemdb2f5482011-02-12 14:40:33 +000010198 EVT VT = InVec.getValueType();
10199
Owen Andersonb2c80da2011-02-25 21:41:48 +000010200 // If we can't generate a legal BUILD_VECTOR, exit
Nadav Rotemdb2f5482011-02-12 14:40:33 +000010201 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
10202 return SDValue();
10203
Eli Friedmanb7910b72011-09-09 21:04:06 +000010204 // Check that we know which element is being inserted
10205 if (!isa<ConstantSDNode>(EltNo))
10206 return SDValue();
10207 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +000010208
Andrea Di Biagiof99dd642014-06-09 16:54:41 +000010209 // Canonicalize insert_vector_elt dag nodes.
10210 // Example:
10211 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
10212 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
10213 //
10214 // Do this only if the child insert_vector node has one use; also
10215 // do this only if indices are both constants and Idx1 < Idx0.
10216 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
10217 && isa<ConstantSDNode>(InVec.getOperand(2))) {
10218 unsigned OtherElt =
10219 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
10220 if (Elt < OtherElt) {
10221 // Swap nodes.
10222 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
10223 InVec.getOperand(0), InVal, EltNo);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000010224 AddToWorklist(NewOp.getNode());
Andrea Di Biagiof99dd642014-06-09 16:54:41 +000010225 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
10226 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
10227 }
10228 }
10229
Eli Friedmanb7910b72011-09-09 21:04:06 +000010230 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
10231 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
10232 // vector elements.
10233 SmallVector<SDValue, 8> Ops;
Quentin Colombet6bf4baa2013-07-30 00:24:09 +000010234 // Do not combine these two vectors if the output vector will not replace
10235 // the input vector.
10236 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
Eli Friedmanb7910b72011-09-09 21:04:06 +000010237 Ops.append(InVec.getNode()->op_begin(),
10238 InVec.getNode()->op_end());
10239 } else if (InVec.getOpcode() == ISD::UNDEF) {
10240 unsigned NElts = VT.getVectorNumElements();
10241 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
10242 } else {
10243 return SDValue();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010244 }
Eli Friedmanb7910b72011-09-09 21:04:06 +000010245
10246 // Insert the element
10247 if (Elt < Ops.size()) {
10248 // All the operands of BUILD_VECTOR must have the same type;
10249 // we enforce that here.
10250 EVT OpVT = Ops[0].getValueType();
10251 if (InVal.getValueType() != OpVT)
10252 InVal = OpVT.bitsGT(InVal.getValueType()) ?
10253 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
10254 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
10255 Ops[Elt] = InVal;
10256 }
10257
10258 // Return the new vector
Craig Topper48d114b2014-04-26 18:35:24 +000010259 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
Chris Lattner5336a592006-03-19 01:27:56 +000010260}
10261
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +000010262SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
10263 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
10264 EVT ResultVT = EVE->getValueType(0);
10265 EVT VecEltVT = InVecVT.getVectorElementType();
10266 unsigned Align = OriginalLoad->getAlignment();
10267 unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
10268 VecEltVT.getTypeForEVT(*DAG.getContext()));
10269
10270 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
10271 return SDValue();
10272
10273 Align = NewAlign;
10274
10275 SDValue NewPtr = OriginalLoad->getBasePtr();
10276 SDValue Offset;
10277 EVT PtrType = NewPtr.getValueType();
10278 MachinePointerInfo MPI;
10279 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
10280 int Elt = ConstEltNo->getZExtValue();
10281 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
10282 if (TLI.isBigEndian())
10283 PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
10284 Offset = DAG.getConstant(PtrOff, PtrType);
10285 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
10286 } else {
10287 Offset = DAG.getNode(
10288 ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo,
10289 DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType()));
10290 if (TLI.isBigEndian())
10291 Offset = DAG.getNode(
10292 ISD::SUB, SDLoc(EVE), EltNo.getValueType(),
10293 DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset);
10294 MPI = OriginalLoad->getPointerInfo();
10295 }
10296 NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset);
10297
10298 // The replacement we need to do here is a little tricky: we need to
10299 // replace an extractelement of a load with a load.
10300 // Use ReplaceAllUsesOfValuesWith to do the replacement.
10301 // Note that this replacement assumes that the extractvalue is the only
10302 // use of the load; that's okay because we don't want to perform this
10303 // transformation in other cases anyway.
10304 SDValue Load;
10305 SDValue Chain;
10306 if (ResultVT.bitsGT(VecEltVT)) {
10307 // If the result type of vextract is wider than the load, then issue an
10308 // extending load instead.
10309 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, VecEltVT)
10310 ? ISD::ZEXTLOAD
10311 : ISD::EXTLOAD;
10312 Load = DAG.getExtLoad(
10313 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
10314 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10315 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10316 Chain = Load.getValue(1);
10317 } else {
10318 Load = DAG.getLoad(
10319 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
10320 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10321 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10322 Chain = Load.getValue(1);
10323 if (ResultVT.bitsLT(VecEltVT))
10324 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
10325 else
10326 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
10327 }
10328 WorklistRemover DeadNodes(*this);
10329 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
10330 SDValue To[] = { Load, Chain };
10331 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10332 // Since we're explicitly calling ReplaceAllUses, add the new node to the
10333 // worklist explicitly as well.
10334 AddToWorklist(Load.getNode());
10335 AddUsersToWorklist(Load.getNode()); // Add users too
10336 // Make sure to revisit this node to clean it up; it will usually be dead.
10337 AddToWorklist(EVE);
10338 ++OpsNarrowed;
10339 return SDValue(EVE, 0);
10340}
10341
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010342SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
Mon P Wangca6d6de2009-01-17 00:07:25 +000010343 // (vextract (scalar_to_vector val, 0) -> val
10344 SDValue InVec = N->getOperand(0);
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000010345 EVT VT = InVec.getValueType();
10346 EVT NVT = N->getValueType(0);
Mon P Wangca6d6de2009-01-17 00:07:25 +000010347
Duncan Sands6be291a2011-05-09 08:03:33 +000010348 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
10349 // Check if the result type doesn't match the inserted element type. A
10350 // SCALAR_TO_VECTOR may truncate the inserted element and the
10351 // EXTRACT_VECTOR_ELT may widen the extracted vector.
10352 SDValue InOp = InVec.getOperand(0);
Duncan Sands6be291a2011-05-09 08:03:33 +000010353 if (InOp.getValueType() != NVT) {
10354 assert(InOp.getValueType().isInteger() && NVT.isInteger());
Andrew Trickef9de2a2013-05-25 02:42:55 +000010355 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
Duncan Sands6be291a2011-05-09 08:03:33 +000010356 }
10357 return InOp;
10358 }
Evan Cheng1120279a2008-05-13 08:35:03 +000010359
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000010360 SDValue EltNo = N->getOperand(1);
10361 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
10362
10363 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
10364 // We only perform this optimization before the op legalization phase because
Nadav Rotem841c9a82012-09-20 08:53:31 +000010365 // we may introduce new vector instructions which are not backed by TD
10366 // patterns. For example on AVX, extracting elements from a wide vector
Hal Finkel02807592014-03-31 11:43:19 +000010367 // without using extract_subvector. However, if we can find an underlying
10368 // scalar value, then we can always use that.
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000010369 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
Hal Finkel02807592014-03-31 11:43:19 +000010370 && ConstEltNo) {
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000010371 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10372 int NumElem = VT.getVectorNumElements();
10373 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
10374 // Find the new index to extract from.
10375 int OrigElt = SVOp->getMaskElt(Elt);
10376
10377 // Extracting an undef index is undef.
10378 if (OrigElt == -1)
10379 return DAG.getUNDEF(NVT);
10380
10381 // Select the right vector half to extract from.
Hal Finkel02807592014-03-31 11:43:19 +000010382 SDValue SVInVec;
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000010383 if (OrigElt < NumElem) {
Hal Finkel02807592014-03-31 11:43:19 +000010384 SVInVec = InVec->getOperand(0);
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000010385 } else {
Hal Finkel02807592014-03-31 11:43:19 +000010386 SVInVec = InVec->getOperand(1);
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000010387 OrigElt -= NumElem;
10388 }
10389
Hal Finkel02807592014-03-31 11:43:19 +000010390 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
10391 SDValue InOp = SVInVec.getOperand(OrigElt);
10392 if (InOp.getValueType() != NVT) {
10393 assert(InOp.getValueType().isInteger() && NVT.isInteger());
10394 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
10395 }
10396
10397 return InOp;
10398 }
10399
10400 // FIXME: We should handle recursing on other vector shuffles and
10401 // scalar_to_vector here as well.
10402
10403 if (!LegalOperations) {
10404 EVT IndexTy = TLI.getVectorIdxTy();
10405 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
10406 SVInVec, DAG.getConstant(OrigElt, IndexTy));
10407 }
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000010408 }
10409
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +000010410 bool BCNumEltsChanged = false;
10411 EVT ExtVT = VT.getVectorElementType();
10412 EVT LVT = ExtVT;
10413
10414 // If the result of load has to be truncated, then it's not necessarily
10415 // profitable.
10416 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
10417 return SDValue();
10418
10419 if (InVec.getOpcode() == ISD::BITCAST) {
10420 // Don't duplicate a load with other uses.
10421 if (!InVec.hasOneUse())
10422 return SDValue();
10423
10424 EVT BCVT = InVec.getOperand(0).getValueType();
10425 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
10426 return SDValue();
10427 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
10428 BCNumEltsChanged = true;
10429 InVec = InVec.getOperand(0);
10430 ExtVT = BCVT.getVectorElementType();
10431 }
10432
10433 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
10434 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
10435 ISD::isNormalLoad(InVec.getNode()) &&
10436 !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
10437 SDValue Index = N->getOperand(1);
10438 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
10439 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
10440 OrigLoad);
10441 }
10442
Evan Cheng1120279a2008-05-13 08:35:03 +000010443 // Perform only after legalization to ensure build_vector / vector_shuffle
10444 // optimizations have already been done.
Duncan Sandsdc2dac12008-11-24 14:53:14 +000010445 if (!LegalOperations) return SDValue();
Evan Cheng1120279a2008-05-13 08:35:03 +000010446
Mon P Wangca6d6de2009-01-17 00:07:25 +000010447 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
10448 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
10449 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
Evan Cheng0de312d2007-10-06 08:19:55 +000010450
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000010451 if (ConstEltNo) {
Eric Christopherfcc9e682010-11-03 09:36:40 +000010452 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Evan Cheng0de312d2007-10-06 08:19:55 +000010453
Craig Topperc0196b12014-04-14 00:51:57 +000010454 LoadSDNode *LN0 = nullptr;
10455 const ShuffleVectorSDNode *SVN = nullptr;
Bill Wendling27d9dd42009-01-30 23:36:47 +000010456 if (ISD::isNormalLoad(InVec.getNode())) {
Evan Cheng1120279a2008-05-13 08:35:03 +000010457 LN0 = cast<LoadSDNode>(InVec);
Bill Wendling27d9dd42009-01-30 23:36:47 +000010458 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
Owen Anderson53aa7a92009-08-10 22:56:29 +000010459 InVec.getOperand(0).getValueType() == ExtVT &&
Bill Wendling27d9dd42009-01-30 23:36:47 +000010460 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
Eli Friedmane96286c2011-12-26 22:49:32 +000010461 // Don't duplicate a load with other uses.
10462 if (!InVec.hasOneUse())
10463 return SDValue();
10464
Evan Cheng1120279a2008-05-13 08:35:03 +000010465 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
Nate Begeman5f829d82009-04-29 05:20:52 +000010466 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
Evan Cheng1120279a2008-05-13 08:35:03 +000010467 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
10468 // =>
10469 // (load $addr+1*size)
Scott Michelcf0da6c2009-02-17 22:15:04 +000010470
Eli Friedmane96286c2011-12-26 22:49:32 +000010471 // Don't duplicate a load with other uses.
10472 if (!InVec.hasOneUse())
10473 return SDValue();
10474
Mon P Wangb5eb7202008-12-11 00:26:16 +000010475 // If the bit convert changed the number of elements, it is unsafe
10476 // to examine the mask.
10477 if (BCNumEltsChanged)
10478 return SDValue();
Nate Begeman5f829d82009-04-29 05:20:52 +000010479
10480 // Select the input vector, guarding against out of range extract vector.
10481 unsigned NumElems = VT.getVectorNumElements();
Eric Christopherfcc9e682010-11-03 09:36:40 +000010482 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
Nate Begeman5f829d82009-04-29 05:20:52 +000010483 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
10484
Eli Friedmane96286c2011-12-26 22:49:32 +000010485 if (InVec.getOpcode() == ISD::BITCAST) {
10486 // Don't duplicate a load with other uses.
10487 if (!InVec.hasOneUse())
10488 return SDValue();
10489
Evan Cheng1120279a2008-05-13 08:35:03 +000010490 InVec = InVec.getOperand(0);
Eli Friedmane96286c2011-12-26 22:49:32 +000010491 }
Gabor Greiff304a7a2008-08-28 21:40:38 +000010492 if (ISD::isNormalLoad(InVec.getNode())) {
Evan Cheng1120279a2008-05-13 08:35:03 +000010493 LN0 = cast<LoadSDNode>(InVec);
Ted Kremenekd87bd772010-04-08 18:49:30 +000010494 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +000010495 EltNo = DAG.getConstant(Elt, EltNo.getValueType());
Evan Cheng0de312d2007-10-06 08:19:55 +000010496 }
10497 }
Bill Wendling27d9dd42009-01-30 23:36:47 +000010498
Eli Friedmane96286c2011-12-26 22:49:32 +000010499 // Make sure we found a non-volatile load and the extractelement is
10500 // the only use.
Nadav Rotem8a7beb82011-05-11 14:40:50 +000010501 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010502 return SDValue();
Evan Cheng1120279a2008-05-13 08:35:03 +000010503
Eric Christopherc6418b12010-11-03 20:44:42 +000010504 // If Idx was -1 above, Elt is going to be -1, so just return undef.
10505 if (Elt == -1)
Eli Friedmancbd3ba92011-07-25 22:25:42 +000010506 return DAG.getUNDEF(LVT);
Eric Christopherc6418b12010-11-03 20:44:42 +000010507
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +000010508 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
Evan Cheng0de312d2007-10-06 08:19:55 +000010509 }
Bill Wendling27d9dd42009-01-30 23:36:47 +000010510
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010511 return SDValue();
Evan Cheng0de312d2007-10-06 08:19:55 +000010512}
Evan Cheng0de312d2007-10-06 08:19:55 +000010513
Michael Liao6d106b72012-10-23 23:06:52 +000010514// Simplify (build_vec (ext )) to (bitcast (build_vec ))
10515SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
10516 // We perform this optimization post type-legalization because
10517 // the type-legalizer often scalarizes integer-promoted vectors.
10518 // Performing this optimization before may create bit-casts which
10519 // will be type-legalized to complex code sequences.
10520 // We perform this optimization only before the operation legalizer because we
10521 // may introduce illegal operations.
10522 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
10523 return SDValue();
10524
Dan Gohmana8665142007-06-25 16:23:39 +000010525 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +000010526 SDLoc dl(N);
Owen Anderson53aa7a92009-08-10 22:56:29 +000010527 EVT VT = N->getValueType(0);
Nadav Rotema62368c2012-07-15 08:38:23 +000010528
Nadav Rotembf6568b2011-10-29 21:23:04 +000010529 // Check to see if this is a BUILD_VECTOR of a bunch of values
10530 // which come from any_extend or zero_extend nodes. If so, we can create
10531 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
Nadav Rotemf3103612011-10-31 20:08:25 +000010532 // optimizations. We do not handle sign-extend because we can't fill the sign
10533 // using shuffles.
Nadav Rotembf6568b2011-10-29 21:23:04 +000010534 EVT SourceType = MVT::Other;
Craig Topper02cb0fb2012-01-17 09:09:48 +000010535 bool AllAnyExt = true;
Nadav Rotema62368c2012-07-15 08:38:23 +000010536
Craig Topper02cb0fb2012-01-17 09:09:48 +000010537 for (unsigned i = 0; i != NumInScalars; ++i) {
Nadav Rotembf6568b2011-10-29 21:23:04 +000010538 SDValue In = N->getOperand(i);
10539 // Ignore undef inputs.
10540 if (In.getOpcode() == ISD::UNDEF) continue;
10541
10542 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
10543 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
10544
Nadav Rotemf3103612011-10-31 20:08:25 +000010545 // Abort if the element is not an extension.
Nadav Rotembf6568b2011-10-29 21:23:04 +000010546 if (!ZeroExt && !AnyExt) {
Nadav Rotemf3103612011-10-31 20:08:25 +000010547 SourceType = MVT::Other;
Nadav Rotembf6568b2011-10-29 21:23:04 +000010548 break;
10549 }
10550
10551 // The input is a ZeroExt or AnyExt. Check the original type.
10552 EVT InTy = In.getOperand(0).getValueType();
10553
10554 // Check that all of the widened source types are the same.
10555 if (SourceType == MVT::Other)
Nadav Rotemf3103612011-10-31 20:08:25 +000010556 // First time.
Nadav Rotembf6568b2011-10-29 21:23:04 +000010557 SourceType = InTy;
10558 else if (InTy != SourceType) {
10559 // Multiple income types. Abort.
Nadav Rotemf3103612011-10-31 20:08:25 +000010560 SourceType = MVT::Other;
Nadav Rotembf6568b2011-10-29 21:23:04 +000010561 break;
10562 }
10563
10564 // Check if all of the extends are ANY_EXTENDs.
Craig Topper02cb0fb2012-01-17 09:09:48 +000010565 AllAnyExt &= AnyExt;
Nadav Rotembf6568b2011-10-29 21:23:04 +000010566 }
10567
Nadav Rotemf3103612011-10-31 20:08:25 +000010568 // In order to have valid types, all of the inputs must be extended from the
10569 // same source type and all of the inputs must be any or zero extend.
10570 // Scalar sizes must be a power of two.
Michael Liao6d106b72012-10-23 23:06:52 +000010571 EVT OutScalarTy = VT.getScalarType();
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010572 bool ValidTypes = SourceType != MVT::Other &&
Nadav Rotemf3103612011-10-31 20:08:25 +000010573 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10574 isPowerOf2_32(SourceType.getSizeInBits());
10575
Nadav Rotem6fd1d322012-03-15 08:49:06 +000010576 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10577 // turn into a single shuffle instruction.
Michael Liao6d106b72012-10-23 23:06:52 +000010578 if (!ValidTypes)
10579 return SDValue();
Nadav Rotembf6568b2011-10-29 21:23:04 +000010580
Michael Liao6d106b72012-10-23 23:06:52 +000010581 bool isLE = TLI.isLittleEndian();
10582 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10583 assert(ElemRatio > 1 && "Invalid element size ratio");
10584 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10585 DAG.getConstant(0, SourceType);
Nadav Rotembf6568b2011-10-29 21:23:04 +000010586
Michael Liao6d106b72012-10-23 23:06:52 +000010587 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10588 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
Nadav Rotembf6568b2011-10-29 21:23:04 +000010589
Michael Liao6d106b72012-10-23 23:06:52 +000010590 // Populate the new build_vector
Jakub Staszaka6addc22012-10-24 00:38:25 +000010591 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
Michael Liao6d106b72012-10-23 23:06:52 +000010592 SDValue Cast = N->getOperand(i);
10593 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10594 Cast.getOpcode() == ISD::ZERO_EXTEND ||
10595 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10596 SDValue In;
10597 if (Cast.getOpcode() == ISD::UNDEF)
10598 In = DAG.getUNDEF(SourceType);
10599 else
10600 In = Cast->getOperand(0);
10601 unsigned Index = isLE ? (i * ElemRatio) :
10602 (i * ElemRatio + (ElemRatio - 1));
Nadav Rotembf6568b2011-10-29 21:23:04 +000010603
Michael Liao6d106b72012-10-23 23:06:52 +000010604 assert(Index < Ops.size() && "Invalid index");
10605 Ops[Index] = In;
Nadav Rotembf6568b2011-10-29 21:23:04 +000010606 }
Chris Lattner5336a592006-03-19 01:27:56 +000010607
Michael Liao6d106b72012-10-23 23:06:52 +000010608 // The type of the new BUILD_VECTOR node.
10609 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10610 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10611 "Invalid vector size");
10612 // Check if the new vector type is legal.
10613 if (!isTypeLegal(VecVT)) return SDValue();
10614
10615 // Make the new BUILD_VECTOR.
Craig Topper48d114b2014-04-26 18:35:24 +000010616 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
Michael Liao6d106b72012-10-23 23:06:52 +000010617
10618 // The new BUILD_VECTOR node has the potential to be further optimized.
Chandler Carruth3c0012b2014-07-21 08:56:44 +000010619 AddToWorklist(BV.getNode());
Michael Liao6d106b72012-10-23 23:06:52 +000010620 // Bitcast to the desired type.
10621 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10622}
10623
Michael Liao59229792012-10-24 04:14:18 +000010624SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10625 EVT VT = N->getValueType(0);
10626
10627 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +000010628 SDLoc dl(N);
Michael Liao59229792012-10-24 04:14:18 +000010629
10630 EVT SrcVT = MVT::Other;
10631 unsigned Opcode = ISD::DELETED_NODE;
10632 unsigned NumDefs = 0;
10633
10634 for (unsigned i = 0; i != NumInScalars; ++i) {
10635 SDValue In = N->getOperand(i);
10636 unsigned Opc = In.getOpcode();
10637
10638 if (Opc == ISD::UNDEF)
10639 continue;
10640
10641 // If all scalar values are floats and converted from integers.
10642 if (Opcode == ISD::DELETED_NODE &&
10643 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10644 Opcode = Opc;
Michael Liao59229792012-10-24 04:14:18 +000010645 }
Tom Stellard567f8862013-01-02 22:13:01 +000010646
Michael Liao59229792012-10-24 04:14:18 +000010647 if (Opc != Opcode)
10648 return SDValue();
10649
10650 EVT InVT = In.getOperand(0).getValueType();
10651
10652 // If all scalar values are typed differently, bail out. It's chosen to
10653 // simplify BUILD_VECTOR of integer types.
10654 if (SrcVT == MVT::Other)
10655 SrcVT = InVT;
10656 if (SrcVT != InVT)
10657 return SDValue();
10658 NumDefs++;
10659 }
10660
10661 // If the vector has just one element defined, it's not worth to fold it into
10662 // a vectorized one.
10663 if (NumDefs < 2)
10664 return SDValue();
10665
10666 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10667 && "Should only handle conversion from integer to float.");
10668 assert(SrcVT != MVT::Other && "Cannot determine source type!");
10669
10670 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
Tom Stellard567f8862013-01-02 22:13:01 +000010671
10672 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10673 return SDValue();
10674
Michael Liao59229792012-10-24 04:14:18 +000010675 SmallVector<SDValue, 8> Opnds;
10676 for (unsigned i = 0; i != NumInScalars; ++i) {
10677 SDValue In = N->getOperand(i);
10678
10679 if (In.getOpcode() == ISD::UNDEF)
10680 Opnds.push_back(DAG.getUNDEF(SrcVT));
10681 else
10682 Opnds.push_back(In.getOperand(0));
10683 }
Craig Topper48d114b2014-04-26 18:35:24 +000010684 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000010685 AddToWorklist(BV.getNode());
Michael Liao59229792012-10-24 04:14:18 +000010686
10687 return DAG.getNode(Opcode, dl, VT, BV);
10688}
10689
Michael Liao6d106b72012-10-23 23:06:52 +000010690SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10691 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +000010692 SDLoc dl(N);
Michael Liao6d106b72012-10-23 23:06:52 +000010693 EVT VT = N->getValueType(0);
10694
10695 // A vector built entirely of undefs is undef.
10696 if (ISD::allOperandsUndef(N))
10697 return DAG.getUNDEF(VT);
10698
10699 SDValue V = reduceBuildVecExtToExtBuildVec(N);
10700 if (V.getNode())
10701 return V;
10702
Michael Liao59229792012-10-24 04:14:18 +000010703 V = reduceBuildVecConvertToConvertBuildVec(N);
10704 if (V.getNode())
10705 return V;
10706
Dan Gohmana8665142007-06-25 16:23:39 +000010707 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10708 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10709 // at most two distinct vectors, turn this into a shuffle node.
Duncan Sands3fb2fc62012-03-19 15:35:44 +000010710
Andrea Di Biagioc7c52412014-09-30 15:30:22 +000010711 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10712 if (!isTypeLegal(VT))
10713 return SDValue();
10714
Duncan Sands3fb2fc62012-03-19 15:35:44 +000010715 // May only combine to shuffle after legalize if shuffle is legal.
Owen Anderson3eb910b2014-08-28 17:49:58 +000010716 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
Duncan Sands3fb2fc62012-03-19 15:35:44 +000010717 return SDValue();
10718
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010719 SDValue VecIn1, VecIn2;
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000010720 bool UsesZeroVector = false;
Chris Lattnerc9992542006-03-28 20:28:38 +000010721 for (unsigned i = 0; i != NumInScalars; ++i) {
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000010722 SDValue Op = N->getOperand(i);
Chris Lattnerc9992542006-03-28 20:28:38 +000010723 // Ignore undef inputs.
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000010724 if (Op.getOpcode() == ISD::UNDEF) continue;
10725
10726 // See if we can combine this build_vector into a blend with a zero vector.
10727 if (!VecIn2.getNode() && ((Op.getOpcode() == ISD::Constant &&
10728 cast<ConstantSDNode>(Op.getNode())->isNullValue()) ||
10729 (Op.getOpcode() == ISD::ConstantFP &&
10730 cast<ConstantFPSDNode>(Op.getNode())->getValueAPF().isZero()))) {
10731 UsesZeroVector = true;
10732 continue;
10733 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010734
Dan Gohmana8665142007-06-25 16:23:39 +000010735 // If this input is something other than a EXTRACT_VECTOR_ELT with a
Chris Lattnerc9992542006-03-28 20:28:38 +000010736 // constant index, bail out.
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000010737 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10738 !isa<ConstantSDNode>(Op.getOperand(1))) {
Craig Topperc0196b12014-04-14 00:51:57 +000010739 VecIn1 = VecIn2 = SDValue(nullptr, 0);
Chris Lattnerc9992542006-03-28 20:28:38 +000010740 break;
10741 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010742
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010743 // We allow up to two distinct input vectors.
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000010744 SDValue ExtractedFromVec = Op.getOperand(0);
Chris Lattnerc9992542006-03-28 20:28:38 +000010745 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10746 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +000010747
Craig Topperc0196b12014-04-14 00:51:57 +000010748 if (!VecIn1.getNode()) {
Chris Lattnerc9992542006-03-28 20:28:38 +000010749 VecIn1 = ExtractedFromVec;
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000010750 } else if (!VecIn2.getNode() && !UsesZeroVector) {
Chris Lattnerc9992542006-03-28 20:28:38 +000010751 VecIn2 = ExtractedFromVec;
10752 } else {
10753 // Too many inputs.
Craig Topperc0196b12014-04-14 00:51:57 +000010754 VecIn1 = VecIn2 = SDValue(nullptr, 0);
Chris Lattnerc9992542006-03-28 20:28:38 +000010755 break;
10756 }
10757 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010758
Jim Grosbach2eb60fd2014-04-29 22:41:50 +000010759 // If everything is good, we can make a shuffle operation.
Gabor Greiff304a7a2008-08-28 21:40:38 +000010760 if (VecIn1.getNode()) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010761 SmallVector<int, 8> Mask;
Chris Lattnerc9992542006-03-28 20:28:38 +000010762 for (unsigned i = 0; i != NumInScalars; ++i) {
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000010763 unsigned Opcode = N->getOperand(i).getOpcode();
10764 if (Opcode == ISD::UNDEF) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010765 Mask.push_back(-1);
Chris Lattnerc9992542006-03-28 20:28:38 +000010766 continue;
10767 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010768
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000010769 // Operands can also be zero.
10770 if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
10771 assert(UsesZeroVector &&
10772 (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
10773 "Unexpected node found!");
10774 Mask.push_back(NumInScalars+i);
10775 continue;
10776 }
10777
Rafael Espindolab93db662009-04-24 12:40:33 +000010778 // If extracting from the first vector, just use the index directly.
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010779 SDValue Extract = N->getOperand(i);
Mon P Wang523c0852009-03-17 06:33:10 +000010780 SDValue ExtVal = Extract.getOperand(1);
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000010781 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
Chris Lattnerc9992542006-03-28 20:28:38 +000010782 if (Extract.getOperand(0) == VecIn1) {
Nate Begeman5f829d82009-04-29 05:20:52 +000010783 if (ExtIndex > VT.getVectorNumElements())
10784 return SDValue();
Wesley Peck527da1b2010-11-23 03:31:01 +000010785
Nate Begeman5f829d82009-04-29 05:20:52 +000010786 Mask.push_back(ExtIndex);
Chris Lattnerc9992542006-03-28 20:28:38 +000010787 continue;
10788 }
10789
10790 // Otherwise, use InIdx + VecSize
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000010791 Mask.push_back(NumInScalars+ExtIndex);
Chris Lattnerc9992542006-03-28 20:28:38 +000010792 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010793
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000010794 // Avoid introducing illegal shuffles with zero.
10795 if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
10796 return SDValue();
10797
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010798 // We can't generate a shuffle node with mismatched input and output types.
10799 // Attempt to transform a single input vector to the correct type.
10800 if ((VT != VecIn1.getValueType())) {
10801 // We don't support shuffeling between TWO values of different types.
Craig Topperc0196b12014-04-14 00:51:57 +000010802 if (VecIn2.getNode())
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010803 return SDValue();
10804
10805 // We only support widening of vectors which are half the size of the
10806 // output registers. For example XMM->YMM widening on X86 with AVX.
10807 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10808 return SDValue();
10809
James Molloy1e5c6112012-09-10 14:01:21 +000010810 // If the input vector type has a different base type to the output
10811 // vector type, bail out.
10812 if (VecIn1.getValueType().getVectorElementType() !=
10813 VT.getVectorElementType())
10814 return SDValue();
10815
Stepan Dyatkovskiy99120e02012-08-22 09:33:55 +000010816 // Widen the input vector by adding undef values.
Michael Liao6d106b72012-10-23 23:06:52 +000010817 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
Stepan Dyatkovskiy99120e02012-08-22 09:33:55 +000010818 VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010819 }
10820
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000010821 if (UsesZeroVector)
10822 VecIn2 = VT.isInteger() ? DAG.getConstant(0, VT) :
10823 DAG.getConstantFP(0.0, VT);
10824 else
10825 // If VecIn2 is unused then change it to undef.
10826 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010827
Nadav Rotem841c9a82012-09-20 08:53:31 +000010828 // Check that we were able to transform all incoming values to the same
10829 // type.
Nadav Rotem0c650642012-02-13 12:42:26 +000010830 if (VecIn2.getValueType() != VecIn1.getValueType() ||
10831 VecIn1.getValueType() != VT)
10832 return SDValue();
10833
Dan Gohmana8665142007-06-25 16:23:39 +000010834 // Return the new VECTOR_SHUFFLE node.
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010835 SDValue Ops[2];
Chris Lattnerc24a1d32006-08-08 02:23:42 +000010836 Ops[0] = VecIn1;
Nadav Rotem34ca89a2012-02-12 15:05:31 +000010837 Ops[1] = VecIn2;
Michael Liao6d106b72012-10-23 23:06:52 +000010838 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
Chris Lattnerc9992542006-03-28 20:28:38 +000010839 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010840
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010841 return SDValue();
Chris Lattnerc9992542006-03-28 20:28:38 +000010842}
10843
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010844SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
Dan Gohmana8665142007-06-25 16:23:39 +000010845 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10846 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
10847 // inputs come from at most two distinct vectors, turn this into a shuffle
10848 // node.
10849
10850 // If we only have one input vector, we don't need to do any concatenation.
Bill Wendling27d9dd42009-01-30 23:36:47 +000010851 if (N->getNumOperands() == 1)
Dan Gohmana8665142007-06-25 16:23:39 +000010852 return N->getOperand(0);
Dan Gohmana8665142007-06-25 16:23:39 +000010853
Nadav Rotem01892102012-07-14 21:30:27 +000010854 // Check if all of the operands are undefs.
Nadav Rotemd369d4b2013-10-25 06:41:18 +000010855 EVT VT = N->getValueType(0);
Nadav Rotema62368c2012-07-15 08:38:23 +000010856 if (ISD::allOperandsUndef(N))
Nadav Rotemd369d4b2013-10-25 06:41:18 +000010857 return DAG.getUNDEF(VT);
10858
10859 // Optimize concat_vectors where one of the vectors is undef.
10860 if (N->getNumOperands() == 2 &&
10861 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10862 SDValue In = N->getOperand(0);
Nadav Rotem6eee0802013-12-10 01:13:59 +000010863 assert(In.getValueType().isVector() && "Must concat vectors");
Nadav Rotemd369d4b2013-10-25 06:41:18 +000010864
10865 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10866 if (In->getOpcode() == ISD::BITCAST &&
10867 !In->getOperand(0)->getValueType(0).isVector()) {
10868 SDValue Scalar = In->getOperand(0);
10869 EVT SclTy = Scalar->getValueType(0);
10870
10871 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10872 return SDValue();
10873
10874 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10875 VT.getSizeInBits() / SclTy.getSizeInBits());
10876 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10877 return SDValue();
10878
10879 SDLoc dl = SDLoc(N);
10880 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10881 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10882 }
10883 }
Nadav Rotem01892102012-07-14 21:30:27 +000010884
Robert Lougher7d9084f2014-02-11 15:42:46 +000010885 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10886 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10887 if (N->getNumOperands() == 2 &&
10888 N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10889 N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10890 EVT VT = N->getValueType(0);
10891 SDValue N0 = N->getOperand(0);
10892 SDValue N1 = N->getOperand(1);
10893 SmallVector<SDValue, 8> Opnds;
10894 unsigned BuildVecNumElts = N0.getNumOperands();
10895
Hao Liu71224b02014-07-10 03:41:50 +000010896 EVT SclTy0 = N0.getOperand(0)->getValueType(0);
10897 EVT SclTy1 = N1.getOperand(0)->getValueType(0);
10898 if (SclTy0.isFloatingPoint()) {
10899 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10900 Opnds.push_back(N0.getOperand(i));
10901 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10902 Opnds.push_back(N1.getOperand(i));
10903 } else {
10904 // If BUILD_VECTOR are from built from integer, they may have different
10905 // operand types. Get the smaller type and truncate all operands to it.
10906 EVT MinTy = SclTy0.bitsLE(SclTy1) ? SclTy0 : SclTy1;
10907 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10908 Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10909 N0.getOperand(i)));
10910 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10911 Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10912 N1.getOperand(i)));
10913 }
Robert Lougher7d9084f2014-02-11 15:42:46 +000010914
Craig Topper48d114b2014-04-26 18:35:24 +000010915 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
Robert Lougher7d9084f2014-02-11 15:42:46 +000010916 }
10917
Nadav Roteme5a2dda2013-05-01 19:18:51 +000010918 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10919 // nodes often generate nop CONCAT_VECTOR nodes.
10920 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10921 // place the incoming vectors at the exact same location.
10922 SDValue SingleSource = SDValue();
10923 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10924
10925 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10926 SDValue Op = N->getOperand(i);
10927
10928 if (Op.getOpcode() == ISD::UNDEF)
10929 continue;
10930
10931 // Check if this is the identity extract:
10932 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10933 return SDValue();
10934
10935 // Find the single incoming vector for the extract_subvector.
10936 if (SingleSource.getNode()) {
10937 if (Op.getOperand(0) != SingleSource)
10938 return SDValue();
10939 } else {
10940 SingleSource = Op.getOperand(0);
Michael Kupersteinac868752013-05-06 08:06:13 +000010941
10942 // Check the source type is the same as the type of the result.
10943 // If not, this concat may extend the vector, so we can not
10944 // optimize it away.
10945 if (SingleSource.getValueType() != N->getValueType(0))
10946 return SDValue();
Nadav Roteme5a2dda2013-05-01 19:18:51 +000010947 }
10948
10949 unsigned IdentityIndex = i * PartNumElem;
10950 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10951 // The extract index must be constant.
10952 if (!CS)
10953 return SDValue();
Stephen Lincfe7f352013-07-08 00:37:03 +000010954
Nadav Roteme5a2dda2013-05-01 19:18:51 +000010955 // Check that we are reading from the identity index.
10956 if (CS->getZExtValue() != IdentityIndex)
10957 return SDValue();
10958 }
10959
10960 if (SingleSource.getNode())
10961 return SingleSource;
Stephen Lincfe7f352013-07-08 00:37:03 +000010962
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010963 return SDValue();
Dan Gohmana8665142007-06-25 16:23:39 +000010964}
10965
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +000010966SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10967 EVT NVT = N->getValueType(0);
10968 SDValue V = N->getOperand(0);
10969
Michael Liao7a442c802012-10-17 20:48:33 +000010970 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10971 // Combine:
10972 // (extract_subvec (concat V1, V2, ...), i)
10973 // Into:
10974 // Vi if possible
Jack Carterd4e96152013-10-17 01:34:33 +000010975 // Only operand 0 is checked as 'concat' assumes all inputs of the same
10976 // type.
Michael Liao2c235802012-10-19 03:17:00 +000010977 if (V->getOperand(0).getValueType() != NVT)
10978 return SDValue();
Michael Liao7a442c802012-10-17 20:48:33 +000010979 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10980 unsigned NumElems = NVT.getVectorNumElements();
10981 assert((Idx % NumElems) == 0 &&
10982 "IDX in concat is not a multiple of the result vector length.");
10983 return V->getOperand(Idx / NumElems);
10984 }
10985
Michael Liaobb05a1d2013-03-25 23:47:35 +000010986 // Skip bitcasting
10987 if (V->getOpcode() == ISD::BITCAST)
10988 V = V.getOperand(0);
10989
10990 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010991 SDLoc dl(N);
Michael Liaobb05a1d2013-03-25 23:47:35 +000010992 // Handle only simple case where vector being inserted and vector
10993 // being extracted are of same type, and are half size of larger vectors.
10994 EVT BigVT = V->getOperand(0).getValueType();
10995 EVT SmallVT = V->getOperand(1).getValueType();
10996 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10997 return SDValue();
10998
10999 // Only handle cases where both indexes are constants with the same type.
11000 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
11001 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
11002
11003 if (InsIdx && ExtIdx &&
11004 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
11005 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
11006 // Combine:
11007 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
11008 // Into:
11009 // indices are equal or bit offsets are equal => V1
11010 // otherwise => (extract_subvec V1, ExtIdx)
11011 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
11012 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
11013 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
11014 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
11015 DAG.getNode(ISD::BITCAST, dl,
11016 N->getOperand(0).getValueType(),
11017 V->getOperand(0)), N->getOperand(1));
11018 }
11019 }
11020
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +000011021 return SDValue();
11022}
11023
Chandler Carruthdaa1ff92014-10-05 19:14:34 +000011024static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
11025 SDValue V, SelectionDAG &DAG) {
11026 SDLoc DL(V);
11027 EVT VT = V.getValueType();
11028
11029 switch (V.getOpcode()) {
11030 default:
11031 return V;
11032
11033 case ISD::CONCAT_VECTORS: {
11034 EVT OpVT = V->getOperand(0).getValueType();
11035 int OpSize = OpVT.getVectorNumElements();
11036 SmallBitVector OpUsedElements(OpSize, false);
11037 bool FoundSimplification = false;
11038 SmallVector<SDValue, 4> NewOps;
11039 NewOps.reserve(V->getNumOperands());
11040 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
11041 SDValue Op = V->getOperand(i);
11042 bool OpUsed = false;
11043 for (int j = 0; j < OpSize; ++j)
11044 if (UsedElements[i * OpSize + j]) {
11045 OpUsedElements[j] = true;
11046 OpUsed = true;
11047 }
11048 NewOps.push_back(
11049 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
11050 : DAG.getUNDEF(OpVT));
11051 FoundSimplification |= Op == NewOps.back();
11052 OpUsedElements.reset();
11053 }
11054 if (FoundSimplification)
11055 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
11056 return V;
11057 }
11058
11059 case ISD::INSERT_SUBVECTOR: {
11060 SDValue BaseV = V->getOperand(0);
11061 SDValue SubV = V->getOperand(1);
11062 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
11063 if (!IdxN)
11064 return V;
11065
11066 int SubSize = SubV.getValueType().getVectorNumElements();
11067 int Idx = IdxN->getZExtValue();
11068 bool SubVectorUsed = false;
11069 SmallBitVector SubUsedElements(SubSize, false);
11070 for (int i = 0; i < SubSize; ++i)
11071 if (UsedElements[i + Idx]) {
11072 SubVectorUsed = true;
11073 SubUsedElements[i] = true;
11074 UsedElements[i + Idx] = false;
11075 }
11076
11077 // Now recurse on both the base and sub vectors.
11078 SDValue SimplifiedSubV =
11079 SubVectorUsed
11080 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
11081 : DAG.getUNDEF(SubV.getValueType());
11082 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
11083 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
11084 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
11085 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
11086 return V;
11087 }
11088 }
11089}
11090
11091static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
11092 SDValue N1, SelectionDAG &DAG) {
11093 EVT VT = SVN->getValueType(0);
11094 int NumElts = VT.getVectorNumElements();
11095 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
11096 for (int M : SVN->getMask())
11097 if (M >= 0 && M < NumElts)
11098 N0UsedElements[M] = true;
11099 else if (M >= NumElts)
11100 N1UsedElements[M - NumElts] = true;
11101
11102 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
11103 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
11104 if (S0 == N0 && S1 == N1)
11105 return SDValue();
11106
11107 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
11108}
11109
Benjamin Kramerbbae9912013-04-09 17:41:43 +000011110// Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
11111static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
11112 EVT VT = N->getValueType(0);
11113 unsigned NumElts = VT.getVectorNumElements();
11114
11115 SDValue N0 = N->getOperand(0);
11116 SDValue N1 = N->getOperand(1);
11117 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
11118
11119 SmallVector<SDValue, 4> Ops;
11120 EVT ConcatVT = N0.getOperand(0).getValueType();
11121 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
11122 unsigned NumConcats = NumElts / NumElemsPerConcat;
11123
11124 // Look at every vector that's inserted. We're looking for exact
11125 // subvector-sized copies from a concatenated vector
11126 for (unsigned I = 0; I != NumConcats; ++I) {
11127 // Make sure we're dealing with a copy.
11128 unsigned Begin = I * NumElemsPerConcat;
Hao Liubc601962013-05-13 02:07:05 +000011129 bool AllUndef = true, NoUndef = true;
11130 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
11131 if (SVN->getMaskElt(J) >= 0)
11132 AllUndef = false;
11133 else
11134 NoUndef = false;
Benjamin Kramerbbae9912013-04-09 17:41:43 +000011135 }
11136
Hao Liubc601962013-05-13 02:07:05 +000011137 if (NoUndef) {
Hao Liubc601962013-05-13 02:07:05 +000011138 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
11139 return SDValue();
11140
11141 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
11142 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
11143 return SDValue();
11144
11145 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
11146 if (FirstElt < N0.getNumOperands())
11147 Ops.push_back(N0.getOperand(FirstElt));
11148 else
11149 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
11150
11151 } else if (AllUndef) {
11152 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
11153 } else { // Mixed with general masks and undefs, can't do optimization.
11154 return SDValue();
11155 }
Benjamin Kramerbbae9912013-04-09 17:41:43 +000011156 }
11157
Craig Topper48d114b2014-04-26 18:35:24 +000011158 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
Benjamin Kramerbbae9912013-04-09 17:41:43 +000011159}
11160
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011161SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000011162 EVT VT = N->getValueType(0);
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011163 unsigned NumElts = VT.getVectorNumElements();
Chris Lattner39dcf1a2006-03-31 22:16:43 +000011164
Mon P Wang25f01062008-11-10 04:46:22 +000011165 SDValue N0 = N->getOperand(0);
Craig Topper279c77b2012-01-04 08:07:43 +000011166 SDValue N1 = N->getOperand(1);
Mon P Wang25f01062008-11-10 04:46:22 +000011167
Craig Topper5894fe42012-04-09 05:16:56 +000011168 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
Mon P Wang25f01062008-11-10 04:46:22 +000011169
Craig Topper279c77b2012-01-04 08:07:43 +000011170 // Canonicalize shuffle undef, undef -> undef
11171 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
11172 return DAG.getUNDEF(VT);
11173
11174 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
11175
11176 // Canonicalize shuffle v, v -> v, undef
11177 if (N0 == N1) {
11178 SmallVector<int, 8> NewMask;
11179 for (unsigned i = 0; i != NumElts; ++i) {
11180 int Idx = SVN->getMaskElt(i);
11181 if (Idx >= (int)NumElts) Idx -= NumElts;
11182 NewMask.push_back(Idx);
11183 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000011184 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
Craig Topper279c77b2012-01-04 08:07:43 +000011185 &NewMask[0]);
11186 }
11187
11188 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
11189 if (N0.getOpcode() == ISD::UNDEF) {
11190 SmallVector<int, 8> NewMask;
11191 for (unsigned i = 0; i != NumElts; ++i) {
11192 int Idx = SVN->getMaskElt(i);
Craig Toppere3ad4832012-04-09 05:55:33 +000011193 if (Idx >= 0) {
Craig Topper309dfef2013-08-08 07:38:55 +000011194 if (Idx >= (int)NumElts)
Craig Toppere3ad4832012-04-09 05:55:33 +000011195 Idx -= NumElts;
Craig Topper309dfef2013-08-08 07:38:55 +000011196 else
11197 Idx = -1; // remove reference to lhs
Craig Toppere3ad4832012-04-09 05:55:33 +000011198 }
11199 NewMask.push_back(Idx);
Craig Topper279c77b2012-01-04 08:07:43 +000011200 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000011201 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
Craig Topper279c77b2012-01-04 08:07:43 +000011202 &NewMask[0]);
11203 }
11204
11205 // Remove references to rhs if it is undef
11206 if (N1.getOpcode() == ISD::UNDEF) {
11207 bool Changed = false;
11208 SmallVector<int, 8> NewMask;
11209 for (unsigned i = 0; i != NumElts; ++i) {
11210 int Idx = SVN->getMaskElt(i);
11211 if (Idx >= (int)NumElts) {
11212 Idx = -1;
11213 Changed = true;
11214 }
11215 NewMask.push_back(Idx);
11216 }
11217 if (Changed)
Andrew Trickef9de2a2013-05-25 02:42:55 +000011218 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
Craig Topper279c77b2012-01-04 08:07:43 +000011219 }
Evan Cheng8472e0c2006-07-20 22:44:41 +000011220
Bob Wilsonf63da122010-10-28 17:06:14 +000011221 // If it is a splat, check if the argument vector is another splat or a
11222 // build_vector with all scalar elements the same.
Bob Wilsonf63da122010-10-28 17:06:14 +000011223 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
Gabor Greiff304a7a2008-08-28 21:40:38 +000011224 SDNode *V = N0.getNode();
Evan Cheng7c970b92006-07-21 08:25:53 +000011225
Dan Gohmana8665142007-06-25 16:23:39 +000011226 // If this is a bit convert that changes the element type of the vector but
Evan Chengf3ae00a2006-10-16 22:49:37 +000011227 // not the number of vector elements, look through it. Be careful not to
11228 // look though conversions that change things like v4f32 to v2f64.
Wesley Peck527da1b2010-11-23 03:31:01 +000011229 if (V->getOpcode() == ISD::BITCAST) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011230 SDValue ConvInput = V->getOperand(0);
Evan Chengb8ff2232008-07-22 20:42:56 +000011231 if (ConvInput.getValueType().isVector() &&
11232 ConvInput.getValueType().getVectorNumElements() == NumElts)
Gabor Greiff304a7a2008-08-28 21:40:38 +000011233 V = ConvInput.getNode();
Evan Chengf3ae00a2006-10-16 22:49:37 +000011234 }
11235
Dan Gohmana8665142007-06-25 16:23:39 +000011236 if (V->getOpcode() == ISD::BUILD_VECTOR) {
Bob Wilsonf63da122010-10-28 17:06:14 +000011237 assert(V->getNumOperands() == NumElts &&
11238 "BUILD_VECTOR has wrong number of operands");
11239 SDValue Base;
11240 bool AllSame = true;
11241 for (unsigned i = 0; i != NumElts; ++i) {
11242 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
11243 Base = V->getOperand(i);
11244 break;
Evan Cheng7c970b92006-07-21 08:25:53 +000011245 }
Evan Cheng7c970b92006-07-21 08:25:53 +000011246 }
Bob Wilsonf63da122010-10-28 17:06:14 +000011247 // Splat of <u, u, u, u>, return <u, u, u, u>
11248 if (!Base.getNode())
11249 return N0;
11250 for (unsigned i = 0; i != NumElts; ++i) {
11251 if (V->getOperand(i) != Base) {
11252 AllSame = false;
11253 break;
11254 }
11255 }
11256 // Splat of <x, x, x, x>, return <x, x, x, x>
11257 if (AllSame)
11258 return N0;
Evan Cheng7c970b92006-07-21 08:25:53 +000011259 }
11260 }
Nadav Rotemb0783502012-04-01 19:31:22 +000011261
Chandler Carruthdaa1ff92014-10-05 19:14:34 +000011262 // There are various patterns used to build up a vector from smaller vectors,
11263 // subvectors, or elements. Scan chains of these and replace unused insertions
11264 // or components with undef.
11265 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
11266 return S;
11267
Benjamin Kramerbbae9912013-04-09 17:41:43 +000011268 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11269 Level < AfterLegalizeVectorOps &&
11270 (N1.getOpcode() == ISD::UNDEF ||
11271 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
11272 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
11273 SDValue V = partitionShuffleOfConcats(N, DAG);
11274
11275 if (V.getNode())
11276 return V;
11277 }
11278
Andrea Di Biagio0fb20132014-07-21 07:30:54 +000011279 // Canonicalize shuffles according to rules:
11280 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
11281 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
11282 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000011283 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
Andrea Di Biagio0fb20132014-07-21 07:30:54 +000011284 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
11285 TLI.isTypeLegal(VT)) {
11286 // The incoming shuffle must be of the same type as the result of the
11287 // current shuffle.
11288 assert(N1->getOperand(0).getValueType() == VT &&
11289 "Shuffle types don't match");
11290
11291 SDValue SV0 = N1->getOperand(0);
11292 SDValue SV1 = N1->getOperand(1);
11293 bool HasSameOp0 = N0 == SV0;
11294 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
11295 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
11296 // Commute the operands of this shuffle so that next rule
11297 // will trigger.
11298 return DAG.getCommutedVectorShuffle(*SVN);
11299 }
11300
Andrea Di Biagio3960a952014-07-14 22:46:26 +000011301 // Try to fold according to rules:
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000011302 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
11303 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
11304 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
Andrea Di Biagio3960a952014-07-14 22:46:26 +000011305 // Don't try to fold shuffles with illegal type.
11306 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000011307 TLI.isTypeLegal(VT)) {
Andrea Di Biagio3960a952014-07-14 22:46:26 +000011308 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
11309
11310 // The incoming shuffle must be of the same type as the result of the
11311 // current shuffle.
11312 assert(OtherSV->getOperand(0).getValueType() == VT &&
11313 "Shuffle types don't match");
11314
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000011315 SDValue SV0, SV1;
Andrea Di Biagio3960a952014-07-14 22:46:26 +000011316 SmallVector<int, 4> Mask;
11317 // Compute the combined shuffle mask for a shuffle with SV0 as the first
11318 // operand, and SV1 as the second operand.
11319 for (unsigned i = 0; i != NumElts; ++i) {
11320 int Idx = SVN->getMaskElt(i);
11321 if (Idx < 0) {
11322 // Propagate Undef.
11323 Mask.push_back(Idx);
11324 continue;
11325 }
11326
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000011327 SDValue CurrentVec;
Andrea Di Biagiobd5555c2014-07-15 13:26:28 +000011328 if (Idx < (int)NumElts) {
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000011329 // This shuffle index refers to the inner shuffle N0. Lookup the inner
11330 // shuffle mask to identify which vector is actually referenced.
Andrea Di Biagio3960a952014-07-14 22:46:26 +000011331 Idx = OtherSV->getMaskElt(Idx);
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000011332 if (Idx < 0) {
11333 // Propagate Undef.
11334 Mask.push_back(Idx);
11335 continue;
11336 }
Andrea Di Biagio3960a952014-07-14 22:46:26 +000011337
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000011338 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
11339 : OtherSV->getOperand(1);
11340 } else {
11341 // This shuffle index references an element within N1.
11342 CurrentVec = N1;
11343 }
11344
11345 // Simple case where 'CurrentVec' is UNDEF.
11346 if (CurrentVec.getOpcode() == ISD::UNDEF) {
11347 Mask.push_back(-1);
11348 continue;
11349 }
11350
11351 // Canonicalize the shuffle index. We don't know yet if CurrentVec
11352 // will be the first or second operand of the combined shuffle.
11353 Idx = Idx % NumElts;
11354 if (!SV0.getNode() || SV0 == CurrentVec) {
11355 // Ok. CurrentVec is the left hand side.
11356 // Update the mask accordingly.
11357 SV0 = CurrentVec;
11358 Mask.push_back(Idx);
11359 continue;
11360 }
11361
11362 // Bail out if we cannot convert the shuffle pair into a single shuffle.
11363 if (SV1.getNode() && SV1 != CurrentVec)
11364 return SDValue();
11365
11366 // Ok. CurrentVec is the right hand side.
11367 // Update the mask accordingly.
11368 SV1 = CurrentVec;
11369 Mask.push_back(Idx + NumElts);
Andrea Di Biagio3960a952014-07-14 22:46:26 +000011370 }
11371
Andrea Di Biagiob23bad12014-08-16 00:29:44 +000011372 // Check if all indices in Mask are Undef. In case, propagate Undef.
11373 bool isUndefMask = true;
11374 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
11375 isUndefMask &= Mask[i] < 0;
11376
11377 if (isUndefMask)
11378 return DAG.getUNDEF(VT);
11379
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000011380 if (!SV0.getNode())
11381 SV0 = DAG.getUNDEF(VT);
11382 if (!SV1.getNode())
11383 SV1 = DAG.getUNDEF(VT);
11384
Andrea Di Biagio3960a952014-07-14 22:46:26 +000011385 // Avoid introducing shuffles with illegal mask.
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000011386 if (!TLI.isShuffleMaskLegal(Mask, VT)) {
11387 // Compute the commuted shuffle mask and test again.
11388 for (unsigned i = 0; i != NumElts; ++i) {
11389 int idx = Mask[i];
11390 if (idx < 0)
11391 continue;
11392 else if (idx < (int)NumElts)
11393 Mask[i] = idx + NumElts;
11394 else
11395 Mask[i] = idx - NumElts;
11396 }
11397
11398 if (!TLI.isShuffleMaskLegal(Mask, VT))
11399 return SDValue();
11400
11401 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
11402 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
11403 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
11404 std::swap(SV0, SV1);
Andrea Di Biagiobd5555c2014-07-15 13:26:28 +000011405 }
Andrea Di Biagioe13a0b82014-11-15 22:56:25 +000011406
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000011407 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
11408 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
11409 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
11410 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
Andrea Di Biagio3960a952014-07-14 22:46:26 +000011411 }
11412
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011413 return SDValue();
Chris Lattner39dcf1a2006-03-31 22:16:43 +000011414}
11415
Manman Ren413a6cb2014-01-31 01:10:35 +000011416SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
11417 SDValue N0 = N->getOperand(0);
11418 SDValue N2 = N->getOperand(2);
11419
11420 // If the input vector is a concatenation, and the insert replaces
11421 // one of the halves, we can optimize into a single concat_vectors.
11422 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11423 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
11424 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
11425 EVT VT = N->getValueType(0);
11426
11427 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11428 // (concat_vectors Z, Y)
11429 if (InsIdx == 0)
11430 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11431 N->getOperand(1), N0.getOperand(1));
11432
11433 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11434 // (concat_vectors X, Z)
11435 if (InsIdx == VT.getVectorNumElements()/2)
11436 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11437 N0.getOperand(0), N->getOperand(1));
11438 }
11439
11440 return SDValue();
11441}
11442
Sanjay Patel50cbfc52014-08-28 16:29:51 +000011443/// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
11444/// with the destination vector and a zero vector.
Dan Gohmana8665142007-06-25 16:23:39 +000011445/// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
Evan Chenga320abc2006-04-20 08:56:16 +000011446/// vector_shuffle V, Zero, <0, 4, 2, 4>
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011447SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000011448 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +000011449 SDLoc dl(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011450 SDValue LHS = N->getOperand(0);
11451 SDValue RHS = N->getOperand(1);
Dan Gohmana8665142007-06-25 16:23:39 +000011452 if (N->getOpcode() == ISD::AND) {
Wesley Peck527da1b2010-11-23 03:31:01 +000011453 if (RHS.getOpcode() == ISD::BITCAST)
Evan Chenga320abc2006-04-20 08:56:16 +000011454 RHS = RHS.getOperand(0);
Dan Gohmana8665142007-06-25 16:23:39 +000011455 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011456 SmallVector<int, 8> Indices;
11457 unsigned NumElts = RHS.getNumOperands();
Evan Chenga320abc2006-04-20 08:56:16 +000011458 for (unsigned i = 0; i != NumElts; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011459 SDValue Elt = RHS.getOperand(i);
Evan Chenga320abc2006-04-20 08:56:16 +000011460 if (!isa<ConstantSDNode>(Elt))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011461 return SDValue();
Craig Toppere5893f62012-04-09 05:59:53 +000011462
11463 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011464 Indices.push_back(i);
Evan Chenga320abc2006-04-20 08:56:16 +000011465 else if (cast<ConstantSDNode>(Elt)->isNullValue())
Andrea Di Biagioce46b972014-11-05 13:04:14 +000011466 Indices.push_back(NumElts+i);
Evan Chenga320abc2006-04-20 08:56:16 +000011467 else
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011468 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000011469 }
11470
11471 // Let's see if the target supports this vector_shuffle.
Owen Anderson53aa7a92009-08-10 22:56:29 +000011472 EVT RVT = RHS.getValueType();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011473 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011474 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000011475
Dan Gohmana8665142007-06-25 16:23:39 +000011476 // Return the new VECTOR_SHUFFLE node.
Dan Gohman08c0a952009-09-23 21:02:20 +000011477 EVT EltVT = RVT.getVectorElementType();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011478 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
Dan Gohman08c0a952009-09-23 21:02:20 +000011479 DAG.getConstant(0, EltVT));
Craig Topper48d114b2014-04-26 18:35:24 +000011480 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
Wesley Peck527da1b2010-11-23 03:31:01 +000011481 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011482 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
Wesley Peck527da1b2010-11-23 03:31:01 +000011483 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
Evan Chenga320abc2006-04-20 08:56:16 +000011484 }
11485 }
Bill Wendling31b50992009-01-30 23:59:18 +000011486
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011487 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000011488}
11489
Sanjay Patel50cbfc52014-08-28 16:29:51 +000011490/// Visit a binary vector operation, like ADD.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011491SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
Bob Wilson54081442010-12-17 23:06:49 +000011492 assert(N->getValueType(0).isVector() &&
11493 "SimplifyVBinOp only works on vectors!");
Dan Gohmana8665142007-06-25 16:23:39 +000011494
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011495 SDValue LHS = N->getOperand(0);
11496 SDValue RHS = N->getOperand(1);
11497 SDValue Shuffle = XformToShuffleWithZero(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +000011498 if (Shuffle.getNode()) return Shuffle;
Evan Chenga320abc2006-04-20 08:56:16 +000011499
Dan Gohmana8665142007-06-25 16:23:39 +000011500 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
Chris Lattner0442a182006-04-02 03:25:57 +000011501 // this operation.
Scott Michelcf0da6c2009-02-17 22:15:04 +000011502 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
Dan Gohmana8665142007-06-25 16:23:39 +000011503 RHS.getOpcode() == ISD::BUILD_VECTOR) {
Juergen Ributzka73844052014-01-13 20:51:35 +000011504 // Check if both vectors are constants. If not bail out.
Andrea Di Biagiod7c03ec2014-01-15 19:51:32 +000011505 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
11506 cast<BuildVectorSDNode>(RHS)->isConstant()))
Juergen Ributzka73844052014-01-13 20:51:35 +000011507 return SDValue();
11508
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011509 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +000011510 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011511 SDValue LHSOp = LHS.getOperand(i);
11512 SDValue RHSOp = RHS.getOperand(i);
Bill Wendling31b50992009-01-30 23:59:18 +000011513
Evan Cheng64d28462006-05-31 06:08:35 +000011514 // Can't fold divide by zero.
Dan Gohmana8665142007-06-25 16:23:39 +000011515 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
11516 N->getOpcode() == ISD::FDIV) {
Evan Cheng64d28462006-05-31 06:08:35 +000011517 if ((RHSOp.getOpcode() == ISD::Constant &&
Gabor Greiff304a7a2008-08-28 21:40:38 +000011518 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
Evan Cheng64d28462006-05-31 06:08:35 +000011519 (RHSOp.getOpcode() == ISD::ConstantFP &&
Gabor Greiff304a7a2008-08-28 21:40:38 +000011520 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
Evan Cheng64d28462006-05-31 06:08:35 +000011521 break;
11522 }
Bill Wendling31b50992009-01-30 23:59:18 +000011523
Bob Wilson54081442010-12-17 23:06:49 +000011524 EVT VT = LHSOp.getValueType();
Bob Wilson68156192011-10-18 17:34:47 +000011525 EVT RVT = RHSOp.getValueType();
11526 if (RVT != VT) {
11527 // Integer BUILD_VECTOR operands may have types larger than the element
11528 // size (e.g., when the element type is not legal). Prior to type
11529 // legalization, the types may not match between the two BUILD_VECTORS.
11530 // Truncate one of the operands to make them match.
11531 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011532 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
Bob Wilson68156192011-10-18 17:34:47 +000011533 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011534 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
Bob Wilson68156192011-10-18 17:34:47 +000011535 VT = RVT;
11536 }
11537 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000011538 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
Evan Cheng48f0de92010-05-18 00:03:40 +000011539 LHSOp, RHSOp);
11540 if (FoldOp.getOpcode() != ISD::UNDEF &&
11541 FoldOp.getOpcode() != ISD::Constant &&
11542 FoldOp.getOpcode() != ISD::ConstantFP)
11543 break;
11544 Ops.push_back(FoldOp);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011545 AddToWorklist(FoldOp.getNode());
Chris Lattner0442a182006-04-02 03:25:57 +000011546 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011547
Bob Wilson54081442010-12-17 23:06:49 +000011548 if (Ops.size() == LHS.getNumOperands())
Craig Topper48d114b2014-04-26 18:35:24 +000011549 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
Chris Lattner0442a182006-04-02 03:25:57 +000011550 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011551
Andrea Di Biagio446a5272014-05-30 23:17:53 +000011552 // Type legalization might introduce new shuffles in the DAG.
11553 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
11554 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
11555 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
11556 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
11557 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
11558 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
11559 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
11560 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
11561
11562 if (SVN0->getMask().equals(SVN1->getMask())) {
11563 EVT VT = N->getValueType(0);
11564 SDValue UndefVector = LHS.getOperand(1);
11565 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
11566 LHS.getOperand(0), RHS.getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011567 AddUsersToWorklist(N);
Andrea Di Biagio446a5272014-05-30 23:17:53 +000011568 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
11569 &SVN0->getMask()[0]);
11570 }
11571 }
11572
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011573 return SDValue();
Chris Lattner0442a182006-04-02 03:25:57 +000011574}
11575
Sanjay Patel50cbfc52014-08-28 16:29:51 +000011576/// Visit a binary vector operation, like FABS/FNEG.
Craig Topper82384612012-09-11 01:45:21 +000011577SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
Craig Topper82384612012-09-11 01:45:21 +000011578 assert(N->getValueType(0).isVector() &&
11579 "SimplifyVUnaryOp only works on vectors!");
11580
11581 SDValue N0 = N->getOperand(0);
11582
11583 if (N0.getOpcode() != ISD::BUILD_VECTOR)
11584 return SDValue();
11585
11586 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
11587 SmallVector<SDValue, 8> Ops;
11588 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
11589 SDValue Op = N0.getOperand(i);
11590 if (Op.getOpcode() != ISD::UNDEF &&
11591 Op.getOpcode() != ISD::ConstantFP)
11592 break;
11593 EVT EltVT = Op.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +000011594 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
Craig Topper82384612012-09-11 01:45:21 +000011595 if (FoldOp.getOpcode() != ISD::UNDEF &&
11596 FoldOp.getOpcode() != ISD::ConstantFP)
11597 break;
11598 Ops.push_back(FoldOp);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011599 AddToWorklist(FoldOp.getNode());
Craig Topper82384612012-09-11 01:45:21 +000011600 }
11601
11602 if (Ops.size() != N0.getNumOperands())
11603 return SDValue();
11604
Craig Topper48d114b2014-04-26 18:35:24 +000011605 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
Craig Topper82384612012-09-11 01:45:21 +000011606}
11607
Andrew Trickef9de2a2013-05-25 02:42:55 +000011608SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
Bill Wendling31b50992009-01-30 23:59:18 +000011609 SDValue N1, SDValue N2){
Nate Begeman2042aa52005-10-08 00:29:44 +000011610 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
Scott Michelcf0da6c2009-02-17 22:15:04 +000011611
Bill Wendling31b50992009-01-30 23:59:18 +000011612 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
Nate Begeman2042aa52005-10-08 00:29:44 +000011613 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Bill Wendling31b50992009-01-30 23:59:18 +000011614
Nate Begeman2042aa52005-10-08 00:29:44 +000011615 // If we got a simplified select_cc node back from SimplifySelectCC, then
11616 // break it down into a new SETCC node, and a new SELECT node, and then return
11617 // the SELECT node, since we were called with a SELECT node.
Gabor Greiff304a7a2008-08-28 21:40:38 +000011618 if (SCC.getNode()) {
Nate Begeman2042aa52005-10-08 00:29:44 +000011619 // Check to see if we got a select_cc back (to turn into setcc/select).
11620 // Otherwise, just return whatever node we got back, like fabs.
11621 if (SCC.getOpcode() == ISD::SELECT_CC) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011622 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000011623 N0.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +000011624 SCC.getOperand(0), SCC.getOperand(1),
Bill Wendling31b50992009-01-30 23:59:18 +000011625 SCC.getOperand(4));
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011626 AddToWorklist(SETCC.getNode());
Chandler Carruth40dbd382014-08-04 21:29:59 +000011627 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
11628 SCC.getOperand(2), SCC.getOperand(3));
Nate Begeman2042aa52005-10-08 00:29:44 +000011629 }
Bill Wendling31b50992009-01-30 23:59:18 +000011630
Nate Begeman2042aa52005-10-08 00:29:44 +000011631 return SCC;
11632 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011633 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +000011634}
11635
Sanjay Patel50cbfc52014-08-28 16:29:51 +000011636/// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
11637/// being selected between, see if we can simplify the select. Callers of this
11638/// should assume that TheSelect is deleted if this returns true. As such, they
11639/// should return the appropriate thing (e.g. the node) back to the top-level of
11640/// the DAG combiner loop to avoid it being looked at.
Scott Michelcf0da6c2009-02-17 22:15:04 +000011641bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011642 SDValue RHS) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000011643
Nadav Rotema49a02a2011-02-11 19:57:47 +000011644 // Cannot simplify select with vector condition
11645 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
11646
Chris Lattner6c14c352005-10-18 06:04:22 +000011647 // If this is a select from two identical things, try to pull the operation
11648 // through the select.
Chris Lattner254c4452010-09-21 15:46:59 +000011649 if (LHS.getOpcode() != RHS.getOpcode() ||
11650 !LHS.hasOneUse() || !RHS.hasOneUse())
11651 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000011652
Chris Lattner254c4452010-09-21 15:46:59 +000011653 // If this is a load and the token chain is identical, replace the select
11654 // of two loads with a load through a select of the address to load from.
11655 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
11656 // constants have been dropped into the constant pool.
11657 if (LHS.getOpcode() == ISD::LOAD) {
11658 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
11659 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
Wesley Peck527da1b2010-11-23 03:31:01 +000011660
Chris Lattner254c4452010-09-21 15:46:59 +000011661 // Token chains must be identical.
11662 if (LHS.getOperand(0) != RHS.getOperand(0) ||
Duncan Sands8651e9c2008-06-13 19:07:40 +000011663 // Do not let this transformation reduce the number of volatile loads.
Chris Lattner254c4452010-09-21 15:46:59 +000011664 LLD->isVolatile() || RLD->isVolatile() ||
11665 // If this is an EXTLOAD, the VT's must match.
11666 LLD->getMemoryVT() != RLD->getMemoryVT() ||
Duncan Sands12f3b3b2010-11-18 20:05:18 +000011667 // If this is an EXTLOAD, the kind of extension must match.
11668 (LLD->getExtensionType() != RLD->getExtensionType() &&
11669 // The only exception is if one of the extensions is anyext.
11670 LLD->getExtensionType() != ISD::EXTLOAD &&
11671 RLD->getExtensionType() != ISD::EXTLOAD) ||
Dan Gohmanba8735d2009-10-31 14:14:04 +000011672 // FIXME: this discards src value information. This is
11673 // over-conservative. It would be beneficial to be able to remember
Mon P Wangec57c812010-01-11 20:12:49 +000011674 // both potential memory locations. Since we are discarding
11675 // src value info, don't do the transformation if the memory
11676 // locations are not in the default address space.
Chris Lattner254c4452010-09-21 15:46:59 +000011677 LLD->getPointerInfo().getAddrSpace() != 0 ||
Pete Cooper10a3ae72013-02-12 03:14:50 +000011678 RLD->getPointerInfo().getAddrSpace() != 0 ||
11679 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
11680 LLD->getBasePtr().getValueType()))
Chris Lattner254c4452010-09-21 15:46:59 +000011681 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000011682
Chris Lattnere3267522010-09-21 15:58:55 +000011683 // Check that the select condition doesn't reach either load. If so,
11684 // folding this will induce a cycle into the DAG. If not, this is safe to
11685 // xform, so create a select of the addresses.
Chris Lattner254c4452010-09-21 15:46:59 +000011686 SDValue Addr;
11687 if (TheSelect->getOpcode() == ISD::SELECT) {
Chris Lattnere3267522010-09-21 15:58:55 +000011688 SDNode *CondNode = TheSelect->getOperand(0).getNode();
11689 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
11690 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
11691 return false;
Nadav Rotemd5f88592012-10-18 18:06:48 +000011692 // The loads must not depend on one another.
11693 if (LLD->isPredecessorOf(RLD) ||
11694 RLD->isPredecessorOf(LLD))
11695 return false;
Matt Arsenaultd2f03322013-06-14 22:04:37 +000011696 Addr = DAG.getSelect(SDLoc(TheSelect),
11697 LLD->getBasePtr().getValueType(),
11698 TheSelect->getOperand(0), LLD->getBasePtr(),
11699 RLD->getBasePtr());
Chris Lattner254c4452010-09-21 15:46:59 +000011700 } else { // Otherwise SELECT_CC
Chris Lattnere3267522010-09-21 15:58:55 +000011701 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
11702 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
11703
11704 if ((LLD->hasAnyUseOfValue(1) &&
11705 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
Chris Lattner1cc25e82012-03-27 16:27:21 +000011706 (RLD->hasAnyUseOfValue(1) &&
11707 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
Chris Lattnere3267522010-09-21 15:58:55 +000011708 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000011709
Andrew Trickef9de2a2013-05-25 02:42:55 +000011710 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
Chris Lattnere3267522010-09-21 15:58:55 +000011711 LLD->getBasePtr().getValueType(),
11712 TheSelect->getOperand(0),
11713 TheSelect->getOperand(1),
11714 LLD->getBasePtr(), RLD->getBasePtr(),
11715 TheSelect->getOperand(4));
Chris Lattner254c4452010-09-21 15:46:59 +000011716 }
11717
Chris Lattnere3267522010-09-21 15:58:55 +000011718 SDValue Load;
Louis Gerbarg4fc09b32014-07-30 18:24:41 +000011719 // It is safe to replace the two loads if they have different alignments,
11720 // but the new load must be the minimum (most restrictive) alignment of the
11721 // inputs.
Louis Gerbarge8f9c782014-10-30 22:21:03 +000011722 bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
Louis Gerbarg09b8cde2014-07-31 22:57:46 +000011723 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
Chris Lattnere3267522010-09-21 15:58:55 +000011724 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
11725 Load = DAG.getLoad(TheSelect->getValueType(0),
Andrew Trickef9de2a2013-05-25 02:42:55 +000011726 SDLoc(TheSelect),
Hal Finkelcc39b672014-07-24 12:16:19 +000011727 // FIXME: Discards pointer and AA info.
Chris Lattnere3267522010-09-21 15:58:55 +000011728 LLD->getChain(), Addr, MachinePointerInfo(),
11729 LLD->isVolatile(), LLD->isNonTemporal(),
Louis Gerbarg67474e32014-07-31 21:45:05 +000011730 isInvariant, Alignment);
Chris Lattnere3267522010-09-21 15:58:55 +000011731 } else {
Duncan Sandsc92331b2010-11-18 21:16:28 +000011732 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
11733 RLD->getExtensionType() : LLD->getExtensionType(),
Andrew Trickef9de2a2013-05-25 02:42:55 +000011734 SDLoc(TheSelect),
Stuart Hastings81c43062011-02-16 16:23:55 +000011735 TheSelect->getValueType(0),
Hal Finkelcc39b672014-07-24 12:16:19 +000011736 // FIXME: Discards pointer and AA info.
Chris Lattnere3267522010-09-21 15:58:55 +000011737 LLD->getChain(), Addr, MachinePointerInfo(),
11738 LLD->getMemoryVT(), LLD->isVolatile(),
Louis Gerbarg67474e32014-07-31 21:45:05 +000011739 LLD->isNonTemporal(), isInvariant, Alignment);
Chris Lattner6c14c352005-10-18 06:04:22 +000011740 }
Chris Lattnere3267522010-09-21 15:58:55 +000011741
11742 // Users of the select now use the result of the load.
11743 CombineTo(TheSelect, Load);
11744
11745 // Users of the old loads now use the new load's chain. We know the
11746 // old-load value is dead now.
11747 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
11748 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
11749 return true;
Chris Lattner6c14c352005-10-18 06:04:22 +000011750 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011751
Chris Lattner6c14c352005-10-18 06:04:22 +000011752 return false;
11753}
11754
Sanjay Patel50cbfc52014-08-28 16:29:51 +000011755/// Simplify an expression of the form (N0 cond N1) ? N2 : N3
Chris Lattner43d63772009-03-11 05:08:08 +000011756/// where 'cond' is the comparison specified by CC.
Andrew Trickef9de2a2013-05-25 02:42:55 +000011757SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011758 SDValue N2, SDValue N3,
11759 ISD::CondCode CC, bool NotExtCompare) {
Chris Lattner43d63772009-03-11 05:08:08 +000011760 // (x ? y : y) -> y.
11761 if (N2 == N3) return N2;
Wesley Peck527da1b2010-11-23 03:31:01 +000011762
Owen Anderson53aa7a92009-08-10 22:56:29 +000011763 EVT VT = N2.getValueType();
Gabor Greiff304a7a2008-08-28 21:40:38 +000011764 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
11765 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
11766 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000011767
11768 // Determine if the condition we're dealing with is constant
Matt Arsenault758659232013-05-18 00:21:46 +000011769 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
Dale Johannesenf1163e92009-02-03 00:47:48 +000011770 N0, N1, CC, DL, false);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011771 if (SCC.getNode()) AddToWorklist(SCC.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +000011772 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000011773
11774 // fold select_cc true, x, y -> x
Dan Gohmanb72127a2008-03-13 22:13:53 +000011775 if (SCCC && !SCCC->isNullValue())
Nate Begeman2042aa52005-10-08 00:29:44 +000011776 return N2;
11777 // fold select_cc false, x, y -> y
Dan Gohmanb72127a2008-03-13 22:13:53 +000011778 if (SCCC && SCCC->isNullValue())
Nate Begeman2042aa52005-10-08 00:29:44 +000011779 return N3;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011780
Nate Begeman2042aa52005-10-08 00:29:44 +000011781 // Check to see if we can simplify the select into an fabs node
11782 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
11783 // Allow either -0.0 or 0.0
Dale Johannesen2cfcf702007-08-25 22:10:57 +000011784 if (CFP->getValueAPF().isZero()) {
Nate Begeman2042aa52005-10-08 00:29:44 +000011785 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
11786 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
11787 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
11788 N2 == N3.getOperand(0))
Bill Wendling31b50992009-01-30 23:59:18 +000011789 return DAG.getNode(ISD::FABS, DL, VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011790
Nate Begeman2042aa52005-10-08 00:29:44 +000011791 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
11792 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
11793 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
11794 N2.getOperand(0) == N3)
Bill Wendling31b50992009-01-30 23:59:18 +000011795 return DAG.getNode(ISD::FABS, DL, VT, N3);
Nate Begeman2042aa52005-10-08 00:29:44 +000011796 }
11797 }
Wesley Peck527da1b2010-11-23 03:31:01 +000011798
Chris Lattner43d63772009-03-11 05:08:08 +000011799 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
11800 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
11801 // in it. This is a win when the constant is not otherwise available because
11802 // it replaces two constant pool loads with one. We only do this if the FP
11803 // type is known to be legal, because if it isn't, then we are before legalize
11804 // types an we want the other legalization to happen first (e.g. to avoid
Mon P Wangc8671562009-03-14 00:25:19 +000011805 // messing with soft float) and if the ConstantFP is not legal, because if
11806 // it is legal, we may not need to store the FP constant in a constant pool.
Chris Lattner43d63772009-03-11 05:08:08 +000011807 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
11808 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
11809 if (TLI.isTypeLegal(N2.getValueType()) &&
Mon P Wangc8671562009-03-14 00:25:19 +000011810 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
Tim Northover863a7892014-04-16 09:03:09 +000011811 TargetLowering::Legal &&
11812 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
11813 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
Chris Lattner43d63772009-03-11 05:08:08 +000011814 // If both constants have multiple uses, then we won't need to do an
11815 // extra load, they are likely around in registers for other users.
11816 (TV->hasOneUse() || FV->hasOneUse())) {
11817 Constant *Elts[] = {
11818 const_cast<ConstantFP*>(FV->getConstantFPValue()),
11819 const_cast<ConstantFP*>(TV->getConstantFPValue())
11820 };
Chris Lattner229907c2011-07-18 04:54:35 +000011821 Type *FPTy = Elts[0]->getType();
Micah Villmowcdfe20b2012-10-08 16:38:25 +000011822 const DataLayout &TD = *TLI.getDataLayout();
Wesley Peck527da1b2010-11-23 03:31:01 +000011823
Chris Lattner43d63772009-03-11 05:08:08 +000011824 // Create a ConstantArray of the two constants.
Jay Foad83be3612011-06-22 09:24:39 +000011825 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
Chris Lattner43d63772009-03-11 05:08:08 +000011826 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
11827 TD.getPrefTypeAlignment(FPTy));
Evan Cheng1fb8aed2009-03-13 07:51:59 +000011828 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
Chris Lattner43d63772009-03-11 05:08:08 +000011829
11830 // Get the offsets to the 0 and 1 element of the array so that we can
11831 // select between them.
11832 SDValue Zero = DAG.getIntPtrConstant(0);
Duncan Sandsaf9eaa82009-05-09 07:06:46 +000011833 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
Chris Lattner43d63772009-03-11 05:08:08 +000011834 SDValue One = DAG.getIntPtrConstant(EltSize);
Wesley Peck527da1b2010-11-23 03:31:01 +000011835
Chris Lattner43d63772009-03-11 05:08:08 +000011836 SDValue Cond = DAG.getSetCC(DL,
Matt Arsenault758659232013-05-18 00:21:46 +000011837 getSetCCResultType(N0.getValueType()),
Chris Lattner43d63772009-03-11 05:08:08 +000011838 N0, N1, CC);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011839 AddToWorklist(Cond.getNode());
Matt Arsenaultd2f03322013-06-14 22:04:37 +000011840 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
11841 Cond, One, Zero);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011842 AddToWorklist(CstOffset.getNode());
Tom Stellard838e2342013-08-26 15:06:10 +000011843 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
Chris Lattner43d63772009-03-11 05:08:08 +000011844 CstOffset);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011845 AddToWorklist(CPIdx.getNode());
Chris Lattner43d63772009-03-11 05:08:08 +000011846 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
Chris Lattnera35499e2010-09-21 07:32:19 +000011847 MachinePointerInfo::getConstantPool(), false,
Pete Cooper82cd9e82011-11-08 18:42:53 +000011848 false, false, Alignment);
Chris Lattner43d63772009-03-11 05:08:08 +000011849
11850 }
Wesley Peck527da1b2010-11-23 03:31:01 +000011851 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011852
Nate Begeman2042aa52005-10-08 00:29:44 +000011853 // Check to see if we can perform the "gzip trick", transforming
Bill Wendling31b50992009-01-30 23:59:18 +000011854 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
Chris Lattnerc8cd62d2006-09-20 06:41:35 +000011855 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
Dan Gohmanb72127a2008-03-13 22:13:53 +000011856 (N1C->isNullValue() || // (a < 0) ? b : 0
11857 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
Owen Anderson53aa7a92009-08-10 22:56:29 +000011858 EVT XType = N0.getValueType();
11859 EVT AType = N2.getValueType();
Duncan Sands11dd4242008-06-08 20:54:56 +000011860 if (XType.bitsGE(AType)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +000011861 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
Nate Begeman6828ed92005-10-10 21:26:48 +000011862 // single-bit constant.
Dan Gohmanb72127a2008-03-13 22:13:53 +000011863 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11864 unsigned ShCtV = N2C->getAPIntValue().logBase2();
Duncan Sands13237ac2008-06-06 12:08:01 +000011865 ShCtV = XType.getSizeInBits()-ShCtV-1;
Owen Andersonb2c80da2011-02-25 21:41:48 +000011866 SDValue ShCt = DAG.getConstant(ShCtV,
11867 getShiftAmountTy(N0.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000011868 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000011869 XType, N0, ShCt);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011870 AddToWorklist(Shift.getNode());
Bill Wendling31b50992009-01-30 23:59:18 +000011871
Duncan Sands11dd4242008-06-08 20:54:56 +000011872 if (XType.bitsGT(AType)) {
Bill Wendling3b585af2009-01-31 03:12:48 +000011873 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011874 AddToWorklist(Shift.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000011875 }
Bill Wendling31b50992009-01-30 23:59:18 +000011876
11877 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
Nate Begeman2042aa52005-10-08 00:29:44 +000011878 }
Bill Wendling31b50992009-01-30 23:59:18 +000011879
Andrew Trickef9de2a2013-05-25 02:42:55 +000011880 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000011881 XType, N0,
11882 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000011883 getShiftAmountTy(N0.getValueType())));
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011884 AddToWorklist(Shift.getNode());
Bill Wendling31b50992009-01-30 23:59:18 +000011885
Duncan Sands11dd4242008-06-08 20:54:56 +000011886 if (XType.bitsGT(AType)) {
Bill Wendling3b585af2009-01-31 03:12:48 +000011887 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011888 AddToWorklist(Shift.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000011889 }
Bill Wendling31b50992009-01-30 23:59:18 +000011890
11891 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
Nate Begeman2042aa52005-10-08 00:29:44 +000011892 }
11893 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011894
Owen Anderson3231d132010-09-22 22:58:22 +000011895 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11896 // where y is has a single bit set.
11897 // A plaintext description would be, we can turn the SELECT_CC into an AND
11898 // when the condition can be materialized as an all-ones register. Any
11899 // single bit-test can be materialized as an all-ones register with
11900 // shift-left and shift-right-arith.
11901 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11902 N0->getValueType(0) == VT &&
Wesley Peck527da1b2010-11-23 03:31:01 +000011903 N1C && N1C->isNullValue() &&
Owen Anderson3231d132010-09-22 22:58:22 +000011904 N2C && N2C->isNullValue()) {
11905 SDValue AndLHS = N0->getOperand(0);
11906 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11907 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11908 // Shift the tested bit over the sign bit.
11909 APInt AndMask = ConstAndRHS->getAPIntValue();
11910 SDValue ShlAmt =
Owen Andersonb2c80da2011-02-25 21:41:48 +000011911 DAG.getConstant(AndMask.countLeadingZeros(),
11912 getShiftAmountTy(AndLHS.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000011913 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
Wesley Peck527da1b2010-11-23 03:31:01 +000011914
Owen Anderson3231d132010-09-22 22:58:22 +000011915 // Now arithmetic right shift it all the way over, so the result is either
11916 // all-ones, or zero.
11917 SDValue ShrAmt =
Owen Andersonb2c80da2011-02-25 21:41:48 +000011918 DAG.getConstant(AndMask.getBitWidth()-1,
11919 getShiftAmountTy(Shl.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000011920 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
Wesley Peck527da1b2010-11-23 03:31:01 +000011921
Owen Anderson3231d132010-09-22 22:58:22 +000011922 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11923 }
11924 }
11925
Nate Begeman6828ed92005-10-10 21:26:48 +000011926 // fold select C, 16, 0 -> shl C, 4
Dan Gohmanb72127a2008-03-13 22:13:53 +000011927 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
Daniel Sanderscbd44c52014-07-10 10:18:12 +000011928 TLI.getBooleanContents(N0.getValueType()) ==
11929 TargetLowering::ZeroOrOneBooleanContent) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000011930
Chris Lattnera083ffc2007-04-11 06:50:51 +000011931 // If the caller doesn't want us to simplify this into a zext of a compare,
11932 // don't do it.
Dan Gohmanb72127a2008-03-13 22:13:53 +000011933 if (NotExtCompare && N2C->getAPIntValue() == 1)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011934 return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +000011935
Nate Begeman6828ed92005-10-10 21:26:48 +000011936 // Get a SetCC of the condition
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011937 // NOTE: Don't create a SETCC if it's not legal on this target.
11938 if (!LegalOperations ||
11939 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault758659232013-05-18 00:21:46 +000011940 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011941 SDValue Temp, SCC;
11942 // cast from setcc result type to select result type
11943 if (LegalTypes) {
Matt Arsenault758659232013-05-18 00:21:46 +000011944 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011945 N0, N1, CC);
11946 if (N2.getValueType().bitsLT(SCC.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +000011947 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011948 N2.getValueType());
11949 else
Andrew Trickef9de2a2013-05-25 02:42:55 +000011950 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011951 N2.getValueType(), SCC);
11952 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011953 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11954 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
Bill Wendling31b50992009-01-30 23:59:18 +000011955 N2.getValueType(), SCC);
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011956 }
11957
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011958 AddToWorklist(SCC.getNode());
11959 AddToWorklist(Temp.getNode());
Owen Anderson15fd6ac2012-11-03 00:17:26 +000011960
11961 if (N2C->getAPIntValue() == 1)
11962 return Temp;
11963
11964 // shl setcc result by log2 n2c
Jack Carterd4e96152013-10-17 01:34:33 +000011965 return DAG.getNode(
11966 ISD::SHL, DL, N2.getValueType(), Temp,
11967 DAG.getConstant(N2C->getAPIntValue().logBase2(),
11968 getShiftAmountTy(Temp.getValueType())));
Nate Begemanabac6162006-02-18 02:40:58 +000011969 }
Nate Begeman6828ed92005-10-10 21:26:48 +000011970 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011971
Nate Begeman2042aa52005-10-08 00:29:44 +000011972 // Check to see if this is the equivalent of setcc
11973 // FIXME: Turn all of these into setcc if setcc if setcc is legal
11974 // otherwise, go ahead with the folds.
Dan Gohmanb72127a2008-03-13 22:13:53 +000011975 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000011976 EVT XType = N0.getValueType();
Duncan Sandsdc2dac12008-11-24 14:53:14 +000011977 if (!LegalOperations ||
Matt Arsenault758659232013-05-18 00:21:46 +000011978 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11979 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
Nate Begeman2042aa52005-10-08 00:29:44 +000011980 if (Res.getValueType() != VT)
Bill Wendling31b50992009-01-30 23:59:18 +000011981 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
Nate Begeman2042aa52005-10-08 00:29:44 +000011982 return Res;
11983 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011984
Bill Wendling31b50992009-01-30 23:59:18 +000011985 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
Scott Michelcf0da6c2009-02-17 22:15:04 +000011986 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +000011987 (!LegalOperations ||
Duncan Sandsb1bfff52008-06-14 17:48:34 +000011988 TLI.isOperationLegal(ISD::CTLZ, XType))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011989 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011990 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
Duncan Sands13237ac2008-06-06 12:08:01 +000011991 DAG.getConstant(Log2_32(XType.getSizeInBits()),
Owen Andersonb2c80da2011-02-25 21:41:48 +000011992 getShiftAmountTy(Ctlz.getValueType())));
Nate Begeman2042aa52005-10-08 00:29:44 +000011993 }
Bill Wendling31b50992009-01-30 23:59:18 +000011994 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
Scott Michelcf0da6c2009-02-17 22:15:04 +000011995 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011996 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000011997 XType, DAG.getConstant(0, XType), N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +000011998 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
Bill Wendling31b50992009-01-30 23:59:18 +000011999 return DAG.getNode(ISD::SRL, DL, XType,
Bill Wendlinga6c75ff2009-02-01 11:19:36 +000012000 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
Duncan Sands13237ac2008-06-06 12:08:01 +000012001 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000012002 getShiftAmountTy(XType)));
Nate Begeman2042aa52005-10-08 00:29:44 +000012003 }
Bill Wendling31b50992009-01-30 23:59:18 +000012004 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
Nate Begeman2042aa52005-10-08 00:29:44 +000012005 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000012006 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
Bill Wendling31b50992009-01-30 23:59:18 +000012007 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000012008 getShiftAmountTy(N0.getValueType())));
Bill Wendling31b50992009-01-30 23:59:18 +000012009 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
Nate Begeman2042aa52005-10-08 00:29:44 +000012010 }
12011 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000012012
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000012013 // Check to see if this is an integer abs.
12014 // select_cc setg[te] X, 0, X, -X ->
12015 // select_cc setgt X, -1, X, -X ->
12016 // select_cc setl[te] X, 0, -X, X ->
12017 // select_cc setlt X, 1, -X, X ->
Nate Begeman2042aa52005-10-08 00:29:44 +000012018 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000012019 if (N1C) {
Craig Topperc0196b12014-04-14 00:51:57 +000012020 ConstantSDNode *SubC = nullptr;
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000012021 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
12022 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
12023 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
12024 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
12025 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
12026 (N1C->isOne() && CC == ISD::SETLT)) &&
12027 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
12028 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
12029
Owen Anderson53aa7a92009-08-10 22:56:29 +000012030 EVT XType = N0.getValueType();
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000012031 if (SubC && SubC->isNullValue() && XType.isInteger()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000012032 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000012033 N0,
12034 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000012035 getShiftAmountTy(N0.getValueType())));
Andrew Trickef9de2a2013-05-25 02:42:55 +000012036 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000012037 XType, N0, Shift);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000012038 AddToWorklist(Shift.getNode());
12039 AddToWorklist(Add.getNode());
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000012040 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
Nate Begeman2042aa52005-10-08 00:29:44 +000012041 }
12042 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000012043
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012044 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +000012045}
12046
Sanjay Patel50cbfc52014-08-28 16:29:51 +000012047/// This is a stub for TargetLowering::SimplifySetCC.
Owen Anderson53aa7a92009-08-10 22:56:29 +000012048SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012049 SDValue N1, ISD::CondCode Cond,
Andrew Trickef9de2a2013-05-25 02:42:55 +000012050 SDLoc DL, bool foldBooleans) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000012051 TargetLowering::DAGCombinerInfo
Nadav Rotemb1dd5242012-12-27 06:47:41 +000012052 DagCombineInfo(DAG, Level, false, this);
Dale Johannesenf1163e92009-02-03 00:47:48 +000012053 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
Nate Begeman24a7eca2005-09-16 00:54:12 +000012054}
12055
Sanjay Patel50cbfc52014-08-28 16:29:51 +000012056/// Given an ISD::SDIV node expressing a divide by constant, return
Chad Rosier17020f92014-07-23 14:57:52 +000012057/// a DAG expression to select that will generate the same value by multiplying
Sanjay Patelbb292212014-09-15 19:47:44 +000012058/// by a magic number.
12059/// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012060SDValue DAGCombiner::BuildSDIV(SDNode *N) {
Benjamin Kramerda4841b2014-04-26 23:09:49 +000012061 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12062 if (!C)
12063 return SDValue();
Benjamin Kramer4dae5982014-04-26 12:06:28 +000012064
12065 // Avoid division by zero.
Benjamin Kramerda4841b2014-04-26 23:09:49 +000012066 if (!C->getAPIntValue())
Benjamin Kramer4dae5982014-04-26 12:06:28 +000012067 return SDValue();
12068
Andrew Lenharth0e57b2c2006-06-12 16:07:18 +000012069 std::vector<SDNode*> Built;
Benjamin Kramerda4841b2014-04-26 23:09:49 +000012070 SDValue S =
12071 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000012072
Benjamin Kramerda4841b2014-04-26 23:09:49 +000012073 for (SDNode *N : Built)
Chandler Carruth3c0012b2014-07-21 08:56:44 +000012074 AddToWorklist(N);
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000012075 return S;
Nate Begemanc6f067a2005-10-20 02:15:44 +000012076}
12077
Sanjay Patel50cbfc52014-08-28 16:29:51 +000012078/// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
12079/// DAG expression that will generate the same value by right shifting.
Chad Rosier17020f92014-07-23 14:57:52 +000012080SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
12081 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12082 if (!C)
12083 return SDValue();
12084
12085 // Avoid division by zero.
12086 if (!C->getAPIntValue())
12087 return SDValue();
12088
12089 std::vector<SDNode *> Built;
12090 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
12091
12092 for (SDNode *N : Built)
12093 AddToWorklist(N);
12094 return S;
12095}
12096
Sanjay Patel50cbfc52014-08-28 16:29:51 +000012097/// Given an ISD::UDIV node expressing a divide by constant, return a DAG
12098/// expression that will generate the same value by multiplying by a magic
Sanjay Patelbb292212014-09-15 19:47:44 +000012099/// number.
12100/// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012101SDValue DAGCombiner::BuildUDIV(SDNode *N) {
Benjamin Kramerda4841b2014-04-26 23:09:49 +000012102 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12103 if (!C)
12104 return SDValue();
Benjamin Kramer4dae5982014-04-26 12:06:28 +000012105
12106 // Avoid division by zero.
Benjamin Kramerda4841b2014-04-26 23:09:49 +000012107 if (!C->getAPIntValue())
Benjamin Kramer4dae5982014-04-26 12:06:28 +000012108 return SDValue();
12109
Andrew Lenharth0e57b2c2006-06-12 16:07:18 +000012110 std::vector<SDNode*> Built;
Benjamin Kramerda4841b2014-04-26 23:09:49 +000012111 SDValue S =
12112 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
Nate Begemanc6f067a2005-10-20 02:15:44 +000012113
Benjamin Kramerda4841b2014-04-26 23:09:49 +000012114 for (SDNode *N : Built)
Chandler Carruth3c0012b2014-07-21 08:56:44 +000012115 AddToWorklist(N);
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000012116 return S;
Nate Begemanc6f067a2005-10-20 02:15:44 +000012117}
12118
Sanjay Patelbdf1e382014-09-26 23:01:47 +000012119SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
12120 if (Level >= AfterLegalizeDAG)
12121 return SDValue();
12122
Sanjay Patelb67bd262014-09-21 15:19:15 +000012123 // Expose the DAG combiner to the target combiner implementations.
12124 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
Sanjay Patelb67bd262014-09-21 15:19:15 +000012125
Sanjay Patelab7f4602014-09-30 20:44:23 +000012126 unsigned Iterations = 0;
Sanjay Patel8fde95c2014-09-30 20:28:48 +000012127 if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
Sanjay Patelab7f4602014-09-30 20:44:23 +000012128 if (Iterations) {
12129 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12130 // For the reciprocal, we need to find the zero of the function:
12131 // F(X) = A X - 1 [which has a zero at X = 1/A]
12132 // =>
12133 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
12134 // does not require additional intermediate precision]
12135 EVT VT = Op.getValueType();
12136 SDLoc DL(Op);
12137 SDValue FPOne = DAG.getConstantFP(1.0, VT);
Sanjay Patelbdf1e382014-09-26 23:01:47 +000012138
Sanjay Patelbdf1e382014-09-26 23:01:47 +000012139 AddToWorklist(Est.getNode());
Sanjay Patelbdf1e382014-09-26 23:01:47 +000012140
Sanjay Patelab7f4602014-09-30 20:44:23 +000012141 // Newton iterations: Est = Est + Est (1 - Arg * Est)
12142 for (unsigned i = 0; i < Iterations; ++i) {
12143 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
12144 AddToWorklist(NewEst.getNode());
12145
12146 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
12147 AddToWorklist(NewEst.getNode());
12148
12149 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
12150 AddToWorklist(NewEst.getNode());
12151
12152 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
12153 AddToWorklist(Est.getNode());
12154 }
12155 }
Sanjay Patelbdf1e382014-09-26 23:01:47 +000012156 return Est;
12157 }
12158
12159 return SDValue();
12160}
12161
Sanjay Patel957efc232014-10-24 17:02:16 +000012162/// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12163/// For the reciprocal sqrt, we need to find the zero of the function:
12164/// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
12165/// =>
12166/// X_{i+1} = X_i (1.5 - A X_i^2 / 2)
12167/// As a result, we precompute A/2 prior to the iteration loop.
12168SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
12169 unsigned Iterations) {
12170 EVT VT = Arg.getValueType();
12171 SDLoc DL(Arg);
12172 SDValue ThreeHalves = DAG.getConstantFP(1.5, VT);
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +000012173
Sanjay Patel957efc232014-10-24 17:02:16 +000012174 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
12175 // this entire sequence requires only one FP constant.
12176 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
12177 AddToWorklist(HalfArg.getNode());
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +000012178
Sanjay Patel957efc232014-10-24 17:02:16 +000012179 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
12180 AddToWorklist(HalfArg.getNode());
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +000012181
Sanjay Patel957efc232014-10-24 17:02:16 +000012182 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
12183 for (unsigned i = 0; i < Iterations; ++i) {
12184 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
12185 AddToWorklist(NewEst.getNode());
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +000012186
Sanjay Patel957efc232014-10-24 17:02:16 +000012187 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
12188 AddToWorklist(NewEst.getNode());
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +000012189
Sanjay Patel957efc232014-10-24 17:02:16 +000012190 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
12191 AddToWorklist(NewEst.getNode());
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +000012192
Sanjay Patel957efc232014-10-24 17:02:16 +000012193 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
12194 AddToWorklist(Est.getNode());
12195 }
12196 return Est;
12197}
12198
12199/// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12200/// For the reciprocal sqrt, we need to find the zero of the function:
12201/// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
12202/// =>
12203/// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
12204SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
12205 unsigned Iterations) {
12206 EVT VT = Arg.getValueType();
12207 SDLoc DL(Arg);
12208 SDValue MinusThree = DAG.getConstantFP(-3.0, VT);
12209 SDValue MinusHalf = DAG.getConstantFP(-0.5, VT);
12210
12211 // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
12212 for (unsigned i = 0; i < Iterations; ++i) {
12213 SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
12214 AddToWorklist(HalfEst.getNode());
12215
12216 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
12217 AddToWorklist(Est.getNode());
12218
12219 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
12220 AddToWorklist(Est.getNode());
12221
12222 Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
12223 AddToWorklist(Est.getNode());
12224
12225 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
12226 AddToWorklist(Est.getNode());
12227 }
12228 return Est;
12229}
12230
Sanjay Patelbdf1e382014-09-26 23:01:47 +000012231SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
12232 if (Level >= AfterLegalizeDAG)
12233 return SDValue();
12234
12235 // Expose the DAG combiner to the target combiner implementations.
12236 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
Sanjay Patelab7f4602014-09-30 20:44:23 +000012237 unsigned Iterations = 0;
Sanjay Patel957efc232014-10-24 17:02:16 +000012238 bool UseOneConstNR = false;
12239 if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
12240 AddToWorklist(Est.getNode());
Sanjay Patelab7f4602014-09-30 20:44:23 +000012241 if (Iterations) {
Sanjay Patel957efc232014-10-24 17:02:16 +000012242 Est = UseOneConstNR ?
12243 BuildRsqrtNROneConst(Op, Est, Iterations) :
12244 BuildRsqrtNRTwoConst(Op, Est, Iterations);
Sanjay Patelab7f4602014-09-30 20:44:23 +000012245 }
Sanjay Patelbdf1e382014-09-26 23:01:47 +000012246 return Est;
Sanjay Patelb67bd262014-09-21 15:19:15 +000012247 }
12248
12249 return SDValue();
12250}
12251
Sanjay Patel50cbfc52014-08-28 16:29:51 +000012252/// Return true if base is a frame index, which is known not to alias with
12253/// anything but itself. Provides base object and offset as results.
Nate Begeman18150d52009-09-25 06:05:26 +000012254static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
Roman Divacky93383442012-09-05 22:15:49 +000012255 const GlobalValue *&GV, const void *&CV) {
Jim Laskey0463e082006-10-07 23:37:56 +000012256 // Assume it is a primitive operation.
Craig Topperc0196b12014-04-14 00:51:57 +000012257 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
Scott Michelcf0da6c2009-02-17 22:15:04 +000012258
Jim Laskey0463e082006-10-07 23:37:56 +000012259 // If it's an adding a simple constant then integrate the offset.
12260 if (Base.getOpcode() == ISD::ADD) {
12261 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
12262 Base = Base.getOperand(0);
Dan Gohmaneffb8942008-09-12 16:56:44 +000012263 Offset += C->getZExtValue();
Jim Laskey0463e082006-10-07 23:37:56 +000012264 }
12265 }
Wesley Peck527da1b2010-11-23 03:31:01 +000012266
Nate Begeman18150d52009-09-25 06:05:26 +000012267 // Return the underlying GlobalValue, and update the Offset. Return false
12268 // for GlobalAddressSDNode since the same GlobalAddress may be represented
12269 // by multiple nodes with different offsets.
12270 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
12271 GV = G->getGlobal();
12272 Offset += G->getOffset();
12273 return false;
12274 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000012275
Nate Begeman18150d52009-09-25 06:05:26 +000012276 // Return the underlying Constant value, and update the Offset. Return false
12277 // for ConstantSDNodes since the same constant pool entry may be represented
12278 // by multiple nodes with different offsets.
12279 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
Roman Divacky93383442012-09-05 22:15:49 +000012280 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
12281 : (const void *)C->getConstVal();
Nate Begeman18150d52009-09-25 06:05:26 +000012282 Offset += C->getOffset();
12283 return false;
12284 }
Jim Laskey0463e082006-10-07 23:37:56 +000012285 // If it's any of the following then it can't alias with anything but itself.
Nate Begeman18150d52009-09-25 06:05:26 +000012286 return isa<FrameIndexSDNode>(Base);
Jim Laskey0463e082006-10-07 23:37:56 +000012287}
12288
Sanjay Patel50cbfc52014-08-28 16:29:51 +000012289/// Return true if there is any possibility that the two addresses overlap.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000012290bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
Jim Laskey0463e082006-10-07 23:37:56 +000012291 // If they are the same then they must be aliases.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000012292 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
Scott Michelcf0da6c2009-02-17 22:15:04 +000012293
Richard Sandiford981fdeb2013-10-28 12:00:00 +000012294 // If they are both volatile then they cannot be reordered.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000012295 if (Op0->isVolatile() && Op1->isVolatile()) return true;
Richard Sandiford981fdeb2013-10-28 12:00:00 +000012296
Jim Laskey0463e082006-10-07 23:37:56 +000012297 // Gather base node and offset information.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012298 SDValue Base1, Base2;
Jim Laskey0463e082006-10-07 23:37:56 +000012299 int64_t Offset1, Offset2;
Dan Gohmanbcaf6812010-04-15 01:51:59 +000012300 const GlobalValue *GV1, *GV2;
Roman Divacky93383442012-09-05 22:15:49 +000012301 const void *CV1, *CV2;
Nick Lewyckyaad475b2014-04-15 07:22:52 +000012302 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
12303 Base1, Offset1, GV1, CV1);
12304 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
12305 Base2, Offset2, GV2, CV2);
Scott Michelcf0da6c2009-02-17 22:15:04 +000012306
Nate Begeman18150d52009-09-25 06:05:26 +000012307 // If they have a same base address then check to see if they overlap.
12308 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
Nick Lewyckyaad475b2014-04-15 07:22:52 +000012309 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
12310 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
Scott Michelcf0da6c2009-02-17 22:15:04 +000012311
Owen Anderson272ff942010-09-20 20:39:59 +000012312 // It is possible for different frame indices to alias each other, mostly
12313 // when tail call optimization reuses return address slots for arguments.
12314 // To catch this case, look up the actual index of frame indices to compute
12315 // the real alias relationship.
12316 if (isFrameIndex1 && isFrameIndex2) {
12317 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12318 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
12319 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
Nick Lewyckyaad475b2014-04-15 07:22:52 +000012320 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
12321 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
Owen Anderson272ff942010-09-20 20:39:59 +000012322 }
12323
Wesley Peck527da1b2010-11-23 03:31:01 +000012324 // Otherwise, if we know what the bases are, and they aren't identical, then
Owen Anderson272ff942010-09-20 20:39:59 +000012325 // we know they cannot alias.
Nate Begeman18150d52009-09-25 06:05:26 +000012326 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
12327 return false;
Jim Laskeya15b0eb2006-10-18 12:29:57 +000012328
Nate Begeman879d8f12009-09-15 00:18:30 +000012329 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
12330 // compared to the size and offset of the access, we may be able to prove they
12331 // do not alias. This check is conservative for now to catch cases created by
12332 // splitting vector types.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000012333 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
12334 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
12335 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
12336 Op1->getMemoryVT().getSizeInBits() >> 3) &&
12337 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
12338 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
12339 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
Wesley Peck527da1b2010-11-23 03:31:01 +000012340
Nate Begeman879d8f12009-09-15 00:18:30 +000012341 // There is no overlap between these relatively aligned accesses of similar
12342 // size, return no alias.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000012343 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
12344 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
Nate Begeman879d8f12009-09-15 00:18:30 +000012345 return false;
12346 }
Wesley Peck527da1b2010-11-23 03:31:01 +000012347
Eric Christopherf55d4712014-10-08 23:38:39 +000012348 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
12349 ? CombinerGlobalAA
12350 : DAG.getSubtarget().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +000012351#ifndef NDEBUG
12352 if (CombinerAAOnlyFunc.getNumOccurrences() &&
12353 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
12354 UseAA = false;
12355#endif
Nick Lewyckyaad475b2014-04-15 07:22:52 +000012356 if (UseAA &&
12357 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
Jim Laskey55e4dca2006-10-18 19:08:31 +000012358 // Use alias analysis information.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000012359 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
12360 Op1->getSrcValueOffset());
12361 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
12362 Op0->getSrcValueOffset() - MinOffset;
12363 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
12364 Op1->getSrcValueOffset() - MinOffset;
Scott Michelcf0da6c2009-02-17 22:15:04 +000012365 AliasAnalysis::AliasResult AAResult =
Nick Lewyckyaad475b2014-04-15 07:22:52 +000012366 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
12367 Overlap1,
Hal Finkelcc39b672014-07-24 12:16:19 +000012368 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
Nick Lewyckyaad475b2014-04-15 07:22:52 +000012369 AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
12370 Overlap2,
Hal Finkelcc39b672014-07-24 12:16:19 +000012371 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
Jim Laskey55e4dca2006-10-18 19:08:31 +000012372 if (AAResult == AliasAnalysis::NoAlias)
12373 return false;
12374 }
Jim Laskeya15b0eb2006-10-18 12:29:57 +000012375
12376 // Otherwise we have to assume they alias.
12377 return true;
Jim Laskey0463e082006-10-07 23:37:56 +000012378}
12379
Sanjay Patel50cbfc52014-08-28 16:29:51 +000012380/// Walk up chain skipping non-aliasing memory nodes,
Jim Laskey708d0db2006-10-04 16:53:27 +000012381/// looking for aliasing nodes and adding them to the Aliases vector.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012382void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
Craig Topperb94011f2013-07-14 04:42:23 +000012383 SmallVectorImpl<SDValue> &Aliases) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012384 SmallVector<SDValue, 8> Chains; // List of chains to visit.
Nate Begeman879d8f12009-09-15 00:18:30 +000012385 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
Scott Michelcf0da6c2009-02-17 22:15:04 +000012386
Jim Laskeyd07be232006-09-25 16:29:54 +000012387 // Get alias information for node.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000012388 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
Jim Laskeyd07be232006-09-25 16:29:54 +000012389
Jim Laskey708d0db2006-10-04 16:53:27 +000012390 // Starting off.
Jim Laskey6549d222006-10-05 15:07:25 +000012391 Chains.push_back(OriginalChain);
Nate Begemana3ed9ed2009-10-12 05:53:58 +000012392 unsigned Depth = 0;
Wesley Peck527da1b2010-11-23 03:31:01 +000012393
Jim Laskey6549d222006-10-05 15:07:25 +000012394 // Look at each chain and determine if it is an alias. If so, add it to the
12395 // aliases list. If not, then continue up the chain looking for the next
Scott Michelcf0da6c2009-02-17 22:15:04 +000012396 // candidate.
Jim Laskey6549d222006-10-05 15:07:25 +000012397 while (!Chains.empty()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012398 SDValue Chain = Chains.back();
Jim Laskey6549d222006-10-05 15:07:25 +000012399 Chains.pop_back();
Wesley Peck527da1b2010-11-23 03:31:01 +000012400
12401 // For TokenFactor nodes, look at each operand and only continue up the
12402 // chain until we find two aliases. If we've seen two aliases, assume we'll
Nate Begemana3ed9ed2009-10-12 05:53:58 +000012403 // find more and revert to original chain since the xform is unlikely to be
12404 // profitable.
Wesley Peck527da1b2010-11-23 03:31:01 +000012405 //
12406 // FIXME: The depth check could be made to return the last non-aliasing
Nate Begemana3ed9ed2009-10-12 05:53:58 +000012407 // chain we found before we hit a tokenfactor rather than the original
12408 // chain.
12409 if (Depth > 6 || Aliases.size() == 2) {
12410 Aliases.clear();
12411 Aliases.push_back(OriginalChain);
Hal Finkel51a98382014-01-24 20:12:02 +000012412 return;
Nate Begemana3ed9ed2009-10-12 05:53:58 +000012413 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000012414
Nate Begeman879d8f12009-09-15 00:18:30 +000012415 // Don't bother if we've been before.
David Blaikie70573dc2014-11-19 07:49:26 +000012416 if (!Visited.insert(Chain.getNode()).second)
Nate Begeman879d8f12009-09-15 00:18:30 +000012417 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +000012418
Jim Laskey6549d222006-10-05 15:07:25 +000012419 switch (Chain.getOpcode()) {
12420 case ISD::EntryToken:
12421 // Entry token is ideal chain operand, but handled in FindBetterChain.
12422 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +000012423
Jim Laskey6549d222006-10-05 15:07:25 +000012424 case ISD::LOAD:
12425 case ISD::STORE: {
12426 // Get alias information for Chain.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000012427 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
12428 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
Scott Michelcf0da6c2009-02-17 22:15:04 +000012429
Jim Laskey6549d222006-10-05 15:07:25 +000012430 // If chain is alias then stop here.
12431 if (!(IsLoad && IsOpLoad) &&
Nick Lewyckyaad475b2014-04-15 07:22:52 +000012432 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
Jim Laskey6549d222006-10-05 15:07:25 +000012433 Aliases.push_back(Chain);
12434 } else {
12435 // Look further up the chain.
Scott Michelcf0da6c2009-02-17 22:15:04 +000012436 Chains.push_back(Chain.getOperand(0));
Nate Begemana3ed9ed2009-10-12 05:53:58 +000012437 ++Depth;
Jim Laskeyd07be232006-09-25 16:29:54 +000012438 }
Jim Laskey6549d222006-10-05 15:07:25 +000012439 break;
12440 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000012441
Jim Laskey6549d222006-10-05 15:07:25 +000012442 case ISD::TokenFactor:
Nate Begeman879d8f12009-09-15 00:18:30 +000012443 // We have to check each of the operands of the token factor for "small"
12444 // token factors, so we queue them up. Adding the operands to the queue
12445 // (stack) in reverse order maintains the original order and increases the
12446 // likelihood that getNode will find a matching token factor (CSE.)
12447 if (Chain.getNumOperands() > 16) {
12448 Aliases.push_back(Chain);
12449 break;
12450 }
Jim Laskey6549d222006-10-05 15:07:25 +000012451 for (unsigned n = Chain.getNumOperands(); n;)
12452 Chains.push_back(Chain.getOperand(--n));
Nate Begemana3ed9ed2009-10-12 05:53:58 +000012453 ++Depth;
Jim Laskey6549d222006-10-05 15:07:25 +000012454 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +000012455
Jim Laskey6549d222006-10-05 15:07:25 +000012456 default:
12457 // For all other instructions we will just have to take what we can get.
12458 Aliases.push_back(Chain);
12459 break;
Jim Laskeyd07be232006-09-25 16:29:54 +000012460 }
12461 }
Hal Finkel51a98382014-01-24 20:12:02 +000012462
12463 // We need to be careful here to also search for aliases through the
12464 // value operand of a store, etc. Consider the following situation:
12465 // Token1 = ...
12466 // L1 = load Token1, %52
12467 // S1 = store Token1, L1, %51
12468 // L2 = load Token1, %52+8
12469 // S2 = store Token1, L2, %51+8
12470 // Token2 = Token(S1, S2)
12471 // L3 = load Token2, %53
12472 // S3 = store Token2, L3, %52
12473 // L4 = load Token2, %53+8
12474 // S4 = store Token2, L4, %52+8
12475 // If we search for aliases of S3 (which loads address %52), and we look
12476 // only through the chain, then we'll miss the trivial dependence on L1
12477 // (which also loads from %52). We then might change all loads and
12478 // stores to use Token1 as their chain operand, which could result in
12479 // copying %53 into %52 before copying %52 into %51 (which should
12480 // happen first).
12481 //
12482 // The problem is, however, that searching for such data dependencies
12483 // can become expensive, and the cost is not directly related to the
12484 // chain depth. Instead, we'll rule out such configurations here by
12485 // insisting that we've visited all chain users (except for users
12486 // of the original chain, which is not necessary). When doing this,
12487 // we need to look through nodes we don't care about (otherwise, things
12488 // like register copies will interfere with trivial cases).
12489
12490 SmallVector<const SDNode *, 16> Worklist;
Craig Topper46276792014-08-24 23:23:06 +000012491 for (const SDNode *N : Visited)
12492 if (N != OriginalChain.getNode())
12493 Worklist.push_back(N);
Hal Finkel51a98382014-01-24 20:12:02 +000012494
12495 while (!Worklist.empty()) {
12496 const SDNode *M = Worklist.pop_back_val();
12497
12498 // We have already visited M, and want to make sure we've visited any uses
12499 // of M that we care about. For uses that we've not visisted, and don't
12500 // care about, queue them to the worklist.
12501
12502 for (SDNode::use_iterator UI = M->use_begin(),
12503 UIE = M->use_end(); UI != UIE; ++UI)
David Blaikie70573dc2014-11-19 07:49:26 +000012504 if (UI.getUse().getValueType() == MVT::Other &&
12505 Visited.insert(*UI).second) {
Hal Finkel51a98382014-01-24 20:12:02 +000012506 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
12507 // We've not visited this use, and we care about it (it could have an
12508 // ordering dependency with the original node).
12509 Aliases.clear();
12510 Aliases.push_back(OriginalChain);
12511 return;
12512 }
12513
12514 // We've not visited this use, but we don't care about it. Mark it as
12515 // visited and enqueue it to the worklist.
12516 Worklist.push_back(*UI);
12517 }
12518 }
Jim Laskey708d0db2006-10-04 16:53:27 +000012519}
12520
Sanjay Patel50cbfc52014-08-28 16:29:51 +000012521/// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
12522/// (aliasing node.)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012523SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
12524 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +000012525
Jim Laskey708d0db2006-10-04 16:53:27 +000012526 // Accumulate all the aliases to this node.
12527 GatherAllAliases(N, OldChain, Aliases);
Scott Michelcf0da6c2009-02-17 22:15:04 +000012528
Dan Gohman4298df62011-05-17 22:20:36 +000012529 // If no operands then chain to entry token.
12530 if (Aliases.size() == 0)
Jim Laskey708d0db2006-10-04 16:53:27 +000012531 return DAG.getEntryNode();
Dan Gohman4298df62011-05-17 22:20:36 +000012532
12533 // If a single operand then chain to it. We don't need to revisit it.
12534 if (Aliases.size() == 1)
Jim Laskey708d0db2006-10-04 16:53:27 +000012535 return Aliases[0];
Wesley Peck527da1b2010-11-23 03:31:01 +000012536
Jim Laskey708d0db2006-10-04 16:53:27 +000012537 // Construct a custom tailored token factor.
Craig Topper48d114b2014-04-26 18:35:24 +000012538 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
Jim Laskeyd07be232006-09-25 16:29:54 +000012539}
12540
Sanjay Patel50cbfc52014-08-28 16:29:51 +000012541/// This is the entry point for the file.
Bill Wendling084669a2009-04-29 00:15:41 +000012542void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
Bill Wendling026e5d72009-04-29 23:29:43 +000012543 CodeGenOpt::Level OptLevel) {
Sanjay Patel50cbfc52014-08-28 16:29:51 +000012544 /// This is the main entry point to this class.
Bill Wendling084669a2009-04-29 00:15:41 +000012545 DAGCombiner(*this, AA, OptLevel).Run(Level);
Nate Begeman21158fc2005-09-01 00:19:25 +000012546}