blob: c4a1a1f64b7616d6193f02c9019f9e92ca96f974 [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 Carruthd9903882015-01-14 11:23:27 +000020#include "llvm/ADT/SetVector.h"
Chandler Carruthdaa1ff92014-10-05 19:14:34 +000021#include "llvm/ADT/SmallBitVector.h"
Chris Lattner48fb92f2007-05-16 06:37:59 +000022#include "llvm/ADT/SmallPtrSet.h"
23#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);
Ahmed Bougachae892d132015-02-05 18:31:02 +0000330 SDValue CombineExtLoad(SDNode *N);
Wesley Peck527da1b2010-11-23 03:31:01 +0000331 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000332 SDValue BuildSDIV(SDNode *N);
Chad Rosier17020f92014-07-23 14:57:52 +0000333 SDValue BuildSDIVPow2(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000334 SDValue BuildUDIV(SDNode *N);
Sanjay Patelbdf1e382014-09-26 23:01:47 +0000335 SDValue BuildReciprocalEstimate(SDValue Op);
336 SDValue BuildRsqrtEstimate(SDValue Op);
Sanjay Patel957efc232014-10-24 17:02:16 +0000337 SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations);
338 SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations);
Evan Cheng4c0bd962011-06-21 06:01:08 +0000339 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
340 bool DemandHighBits = true);
341 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
Richard Sandiford95c864d2014-01-08 15:40:47 +0000342 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
343 SDValue InnerPos, SDValue InnerNeg,
344 unsigned PosOpcode, unsigned NegOpcode,
345 SDLoc DL);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000346 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000347 SDValue ReduceLoadWidth(SDNode *N);
Evan Chenga9cda8a2009-05-28 00:35:15 +0000348 SDValue ReduceLoadOpStoreWidth(SDNode *N);
Evan Chengd42641c2011-02-02 01:06:55 +0000349 SDValue TransformFPLoadStorePair(SDNode *N);
Michael Liao6d106b72012-10-23 23:06:52 +0000350 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
Michael Liao59229792012-10-24 04:14:18 +0000351 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000352
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000353 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000354
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000355 /// Walk up chain skipping non-aliasing memory nodes,
Jim Laskey708d0db2006-10-04 16:53:27 +0000356 /// looking for aliasing nodes and adding them to the Aliases vector.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000357 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
Craig Topperb94011f2013-07-14 04:42:23 +0000358 SmallVectorImpl<SDValue> &Aliases);
Jim Laskey708d0db2006-10-04 16:53:27 +0000359
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000360 /// Return true if there is any possibility that the two addresses overlap.
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000361 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000362
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000363 /// Walk up chain skipping non-aliasing memory nodes, looking for a better
364 /// chain (aliasing node.)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000365 SDValue FindBetterChain(SDNode *N, SDValue Chain);
Duncan Sands41826032009-01-31 15:50:11 +0000366
Sanjay Patel37c41c12015-01-22 18:21:26 +0000367 /// Holds a pointer to an LSBaseSDNode as well as information on where it
368 /// is located in a sequence of memory operations connected by a chain.
369 struct MemOpLink {
370 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
371 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
372 // Ptr to the mem node.
373 LSBaseSDNode *MemNode;
374 // Offset from the base ptr.
375 int64_t OffsetFromBase;
376 // What is the sequence number of this mem node.
377 // Lowest mem operand in the DAG starts at zero.
378 unsigned SequenceNum;
379 };
380
381 /// This is a helper function for MergeConsecutiveStores. When the source
382 /// elements of the consecutive stores are all constants or all extracted
383 /// vector elements, try to merge them into one larger store.
384 /// \return True if a merged store was created.
385 bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
Quentin Colombet308b1712015-01-27 23:58:01 +0000386 EVT MemVT, unsigned NumElem,
Sanjay Patel37c41c12015-01-22 18:21:26 +0000387 bool IsConstantSrc, bool UseVector);
388
Nadav Rotem7cbc12a2012-10-03 16:11:15 +0000389 /// Merge consecutive store operations into a wide store.
390 /// This optimization uses wide integers or vectors when possible.
391 /// \return True if some memory operations were changed.
392 bool MergeConsecutiveStores(StoreSDNode *N);
393
Adam Nemet67483892014-03-04 23:28:31 +0000394 /// \brief Try to transform a truncation where C is a constant:
395 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
396 ///
397 /// \p N needs to be a truncation and its first operand an AND. Other
398 /// requirements are checked by the function (e.g. that trunc is
399 /// single-use) and if missed an empty SDValue is returned.
400 SDValue distributeTruncateThroughAnd(SDNode *N);
401
Chris Lattner4041ab62010-04-15 04:48:01 +0000402 public:
Bill Wendling026e5d72009-04-29 23:29:43 +0000403 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
Quentin Colombetde0e0622013-10-11 18:29:42 +0000404 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
405 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
Duncan P. N. Exon Smith70eb9c52015-02-14 01:44:41 +0000406 auto *F = DAG.getMachineFunction().getFunction();
407 ForCodeSize = F->hasFnAttribute(Attribute::OptimizeForSize) ||
408 F->hasFnAttribute(Attribute::MinSize);
Quentin Colombetde0e0622013-10-11 18:29:42 +0000409 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000410
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000411 /// Runs the dag combiner on all nodes in the work list
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000412 void Run(CombineLevel AtLevel);
Wesley Peck527da1b2010-11-23 03:31:01 +0000413
Chris Lattner4041ab62010-04-15 04:48:01 +0000414 SelectionDAG &getDAG() const { return DAG; }
Wesley Peck527da1b2010-11-23 03:31:01 +0000415
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000416 /// Returns a type large enough to hold any valid shift amount - before type
417 /// legalization these can be huge.
Owen Andersonb2c80da2011-02-25 21:41:48 +0000418 EVT getShiftAmountTy(EVT LHSTy) {
Elena Demikhovsky6769c502013-06-26 10:55:03 +0000419 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
420 if (LHSTy.isVector())
421 return LHSTy;
Jack Carterd4e96152013-10-17 01:34:33 +0000422 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
423 : TLI.getPointerTy();
Chris Lattner4041ab62010-04-15 04:48:01 +0000424 }
Wesley Peck527da1b2010-11-23 03:31:01 +0000425
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000426 /// This method returns true if we are running before type legalization or
427 /// if the specified VT is legal.
Chris Lattner4041ab62010-04-15 04:48:01 +0000428 bool isTypeLegal(const EVT &VT) {
429 if (!LegalTypes) return true;
430 return TLI.isTypeLegal(VT);
431 }
Matt Arsenault758659232013-05-18 00:21:46 +0000432
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000433 /// Convenience wrapper around TargetLowering::getSetCCResultType
Matt Arsenault758659232013-05-18 00:21:46 +0000434 EVT getSetCCResultType(EVT VT) const {
435 return TLI.getSetCCResultType(*DAG.getContext(), VT);
436 }
Nate Begeman21158fc2005-09-01 00:19:25 +0000437 };
438}
439
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000440
441namespace {
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000442/// This class is a DAGUpdateListener that removes any deleted
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000443/// nodes from the worklist.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000444class WorklistRemover : public SelectionDAG::DAGUpdateListener {
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000445 DAGCombiner &DC;
446public:
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000447 explicit WorklistRemover(DAGCombiner &dc)
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000448 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
Scott Michelcf0da6c2009-02-17 22:15:04 +0000449
Craig Topper7b883b32014-03-08 06:31:39 +0000450 void NodeDeleted(SDNode *N, SDNode *E) override {
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000451 DC.removeFromWorklist(N);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000452 }
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000453};
454}
455
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000456//===----------------------------------------------------------------------===//
457// TargetLowering::DAGCombinerInfo implementation
458//===----------------------------------------------------------------------===//
459
460void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000461 ((DAGCombiner*)DC)->AddToWorklist(N);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000462}
463
Cameron Zwarich8c7bbc02011-04-02 02:40:26 +0000464void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000465 ((DAGCombiner*)DC)->removeFromWorklist(N);
Cameron Zwarich8c7bbc02011-04-02 02:40:26 +0000466}
467
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000468SDValue TargetLowering::DAGCombinerInfo::
Evan Chengfd81c732009-03-28 05:57:29 +0000469CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
470 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000471}
472
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000473SDValue TargetLowering::DAGCombinerInfo::
Evan Chengfd81c732009-03-28 05:57:29 +0000474CombineTo(SDNode *N, SDValue Res, bool AddTo) {
475 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000476}
477
478
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000479SDValue TargetLowering::DAGCombinerInfo::
Evan Chengfd81c732009-03-28 05:57:29 +0000480CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
481 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000482}
483
Dan Gohmane58ab792009-01-29 01:59:02 +0000484void TargetLowering::DAGCombinerInfo::
485CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
486 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
487}
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000488
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000489//===----------------------------------------------------------------------===//
Chris Lattnere49c9742007-05-14 22:04:50 +0000490// Helper Functions
491//===----------------------------------------------------------------------===//
492
Chandler Carruth18066972014-08-02 10:02:07 +0000493void DAGCombiner::deleteAndRecombine(SDNode *N) {
494 removeFromWorklist(N);
495
496 // If the operands of this node are only used by the node, they will now be
497 // dead. Make sure to re-visit them and recursively delete dead nodes.
498 for (const SDValue &Op : N->ops())
Hal Finkel51e6fa22014-09-02 06:24:04 +0000499 // For an operand generating multiple values, one of the values may
500 // become dead allowing further simplification (e.g. split index
501 // arithmetic from an indexed load).
502 if (Op->hasOneUse() || Op->getNumValues() > 1)
Chandler Carruth18066972014-08-02 10:02:07 +0000503 AddToWorklist(Op.getNode());
504
505 DAG.DeleteNode(N);
506}
507
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000508/// Return 1 if we can compute the negated form of the specified expression for
509/// the same cost as the expression itself, or 2 if we can compute the negated
510/// form more cheaply than the expression itself.
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000511static char isNegatibleForFree(SDValue Op, bool LegalOperations,
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000512 const TargetLowering &TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000513 const TargetOptions *Options,
Chris Lattnere7c14012008-02-26 07:04:54 +0000514 unsigned Depth = 0) {
Chris Lattnere49c9742007-05-14 22:04:50 +0000515 // fneg is removable even if it has multiple uses.
516 if (Op.getOpcode() == ISD::FNEG) return 2;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000517
Chris Lattnere49c9742007-05-14 22:04:50 +0000518 // Don't allow anything with multiple uses.
519 if (!Op.hasOneUse()) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000520
Chris Lattner46980832007-05-25 02:19:06 +0000521 // Don't recurse exponentially.
522 if (Depth > 6) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000523
Chris Lattnere49c9742007-05-14 22:04:50 +0000524 switch (Op.getOpcode()) {
525 default: return false;
526 case ISD::ConstantFP:
Chris Lattnere7c14012008-02-26 07:04:54 +0000527 // Don't invert constant FP values after legalize. The negated constant
528 // isn't necessarily legal.
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000529 return LegalOperations ? 0 : 1;
Chris Lattnere49c9742007-05-14 22:04:50 +0000530 case ISD::FADD:
531 // FIXME: determine better conditions for this xform.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000532 if (!Options->UnsafeFPMath) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000533
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000534 // After operation legalization, it might not be legal to create new FSUBs.
535 if (LegalOperations &&
536 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
537 return 0;
538
Craig Topper03f39772012-09-09 22:58:45 +0000539 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000540 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
541 Options, Depth + 1))
Chris Lattnere49c9742007-05-14 22:04:50 +0000542 return V;
Bill Wendling6fbf5492009-01-30 23:10:18 +0000543 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000544 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000545 Depth + 1);
Chris Lattnere49c9742007-05-14 22:04:50 +0000546 case ISD::FSUB:
Scott Michelcf0da6c2009-02-17 22:15:04 +0000547 // We can't turn -(A-B) into B-A when we honor signed zeros.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000548 if (!Options->UnsafeFPMath) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000549
Bill Wendling6fbf5492009-01-30 23:10:18 +0000550 // fold (fneg (fsub A, B)) -> (fsub B, A)
Chris Lattnere49c9742007-05-14 22:04:50 +0000551 return 1;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000552
Chris Lattnere49c9742007-05-14 22:04:50 +0000553 case ISD::FMUL:
554 case ISD::FDIV:
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000555 if (Options->HonorSignDependentRoundingFPMath()) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000556
Bill Wendling6fbf5492009-01-30 23:10:18 +0000557 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000558 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
559 Options, Depth + 1))
Chris Lattnere49c9742007-05-14 22:04:50 +0000560 return V;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000561
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000562 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000563 Depth + 1);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000564
Chris Lattnere49c9742007-05-14 22:04:50 +0000565 case ISD::FP_EXTEND:
566 case ISD::FP_ROUND:
567 case ISD::FSIN:
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000568 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000569 Depth + 1);
Chris Lattnere49c9742007-05-14 22:04:50 +0000570 }
571}
572
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000573/// If isNegatibleForFree returns true, return the newly negated expression.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000574static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000575 bool LegalOperations, unsigned Depth = 0) {
Sanjay Patel78614bf2014-08-28 15:53:16 +0000576 const TargetOptions &Options = DAG.getTarget().Options;
Chris Lattnere49c9742007-05-14 22:04:50 +0000577 // fneg is removable even if it has multiple uses.
578 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000579
Chris Lattnere49c9742007-05-14 22:04:50 +0000580 // Don't allow anything with multiple uses.
581 assert(Op.hasOneUse() && "Unknown reuse!");
Scott Michelcf0da6c2009-02-17 22:15:04 +0000582
Chris Lattner46980832007-05-25 02:19:06 +0000583 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
Chris Lattnere49c9742007-05-14 22:04:50 +0000584 switch (Op.getOpcode()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000585 default: llvm_unreachable("Unknown code");
Dale Johannesen446b9002007-08-31 23:34:27 +0000586 case ISD::ConstantFP: {
587 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
588 V.changeSign();
589 return DAG.getConstantFP(V, Op.getValueType());
590 }
Chris Lattnere49c9742007-05-14 22:04:50 +0000591 case ISD::FADD:
592 // FIXME: determine better conditions for this xform.
Sanjay Patel78614bf2014-08-28 15:53:16 +0000593 assert(Options.UnsafeFPMath);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000594
Bill Wendling6fbf5492009-01-30 23:10:18 +0000595 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000596 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
Sanjay Patel78614bf2014-08-28 15:53:16 +0000597 DAG.getTargetLoweringInfo(), &Options, Depth+1))
Andrew Trickef9de2a2013-05-25 02:42:55 +0000598 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000599 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000600 LegalOperations, Depth+1),
Chris Lattnere49c9742007-05-14 22:04:50 +0000601 Op.getOperand(1));
Bill Wendling6fbf5492009-01-30 23:10:18 +0000602 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
Andrew Trickef9de2a2013-05-25 02:42:55 +0000603 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000604 GetNegatedExpression(Op.getOperand(1), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000605 LegalOperations, Depth+1),
Chris Lattnere49c9742007-05-14 22:04:50 +0000606 Op.getOperand(0));
607 case ISD::FSUB:
Scott Michelcf0da6c2009-02-17 22:15:04 +0000608 // We can't turn -(A-B) into B-A when we honor signed zeros.
Sanjay Patel78614bf2014-08-28 15:53:16 +0000609 assert(Options.UnsafeFPMath);
Dan Gohman9a708232007-07-02 15:48:56 +0000610
Bill Wendling6fbf5492009-01-30 23:10:18 +0000611 // fold (fneg (fsub 0, B)) -> B
Dan Gohman9a708232007-07-02 15:48:56 +0000612 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
Dale Johannesen446b9002007-08-31 23:34:27 +0000613 if (N0CFP->getValueAPF().isZero())
Dan Gohman9a708232007-07-02 15:48:56 +0000614 return Op.getOperand(1);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000615
Bill Wendling6fbf5492009-01-30 23:10:18 +0000616 // fold (fneg (fsub A, B)) -> (fsub B, A)
Andrew Trickef9de2a2013-05-25 02:42:55 +0000617 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000618 Op.getOperand(1), Op.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +0000619
Chris Lattnere49c9742007-05-14 22:04:50 +0000620 case ISD::FMUL:
621 case ISD::FDIV:
Sanjay Patel78614bf2014-08-28 15:53:16 +0000622 assert(!Options.HonorSignDependentRoundingFPMath());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000623
Bill Wendling6fbf5492009-01-30 23:10:18 +0000624 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000625 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
Sanjay Patel78614bf2014-08-28 15:53:16 +0000626 DAG.getTargetLoweringInfo(), &Options, Depth+1))
Andrew Trickef9de2a2013-05-25 02:42:55 +0000627 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000628 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000629 LegalOperations, Depth+1),
Chris Lattnere49c9742007-05-14 22:04:50 +0000630 Op.getOperand(1));
Scott Michelcf0da6c2009-02-17 22:15:04 +0000631
Bill Wendling6fbf5492009-01-30 23:10:18 +0000632 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
Andrew Trickef9de2a2013-05-25 02:42:55 +0000633 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Chris Lattnere49c9742007-05-14 22:04:50 +0000634 Op.getOperand(0),
Chris Lattnere7c14012008-02-26 07:04:54 +0000635 GetNegatedExpression(Op.getOperand(1), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000636 LegalOperations, Depth+1));
Scott Michelcf0da6c2009-02-17 22:15:04 +0000637
Chris Lattnere49c9742007-05-14 22:04:50 +0000638 case ISD::FP_EXTEND:
Chris Lattnere49c9742007-05-14 22:04:50 +0000639 case ISD::FSIN:
Andrew Trickef9de2a2013-05-25 02:42:55 +0000640 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000641 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000642 LegalOperations, Depth+1));
Chris Lattner72733e52008-01-17 07:00:52 +0000643 case ISD::FP_ROUND:
Andrew Trickef9de2a2013-05-25 02:42:55 +0000644 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000645 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000646 LegalOperations, Depth+1),
Chris Lattner72733e52008-01-17 07:00:52 +0000647 Op.getOperand(1));
Chris Lattnere49c9742007-05-14 22:04:50 +0000648 }
649}
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000650
Sanjay Patelf4b8deb2014-09-05 20:55:46 +0000651// Return true if this node is a setcc, or is a select_cc
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000652// that selects between the target values used for true and false, making it
653// equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
654// the appropriate nodes based on the type of node we are checking. This
655// simplifies life a bit for the callers.
656bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
657 SDValue &CC) const {
Nate Begeman7cea6ef2005-09-02 21:18:40 +0000658 if (N.getOpcode() == ISD::SETCC) {
659 LHS = N.getOperand(0);
660 RHS = N.getOperand(1);
661 CC = N.getOperand(2);
Nate Begeman2504fe22005-09-01 23:24:04 +0000662 return true;
Nate Begeman7cea6ef2005-09-02 21:18:40 +0000663 }
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000664
665 if (N.getOpcode() != ISD::SELECT_CC ||
666 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
667 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
668 return false;
669
Oliver Stannardd29db9b2014-11-17 10:49:31 +0000670 if (TLI.getBooleanContents(N.getValueType()) ==
671 TargetLowering::UndefinedBooleanContent)
672 return false;
673
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000674 LHS = N.getOperand(0);
675 RHS = N.getOperand(1);
676 CC = N.getOperand(4);
677 return true;
Nate Begeman21158fc2005-09-01 00:19:25 +0000678}
679
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000680/// Return true if this is a SetCC-equivalent operation with only one use.
681/// If this is true, it allows the users to invert the operation for free when
682/// it is profitable to do so.
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000683bool DAGCombiner::isOneUseSetCC(SDValue N) const {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000684 SDValue N0, N1, N2;
Gabor Greiff304a7a2008-08-28 21:40:38 +0000685 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
Nate Begeman2504fe22005-09-01 23:24:04 +0000686 return true;
687 return false;
688}
689
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000690/// Returns true if N is a BUILD_VECTOR node whose
Matt Arsenault985b9de2014-03-17 18:58:01 +0000691/// elements are all the same constant or undefined.
692static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
693 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
694 if (!C)
695 return false;
696
697 APInt SplatUndef;
698 unsigned SplatBitSize;
699 bool HasAnyUndefs;
700 EVT EltVT = N->getValueType(0).getVectorElementType();
701 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
702 HasAnyUndefs) &&
703 EltVT.getSizeInBits() >= SplatBitSize);
704}
705
706// \brief Returns the SDNode if it is a constant BuildVector or constant.
Juergen Ributzka68402822014-01-13 21:49:25 +0000707static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
708 if (isa<ConstantSDNode>(N))
709 return N.getNode();
710 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
Sanjay Patelf4b8deb2014-09-05 20:55:46 +0000711 if (BV && BV->isConstant())
Juergen Ributzka68402822014-01-13 21:49:25 +0000712 return BV;
Craig Topperc0196b12014-04-14 00:51:57 +0000713 return nullptr;
Juergen Ributzka68402822014-01-13 21:49:25 +0000714}
715
Matt Arsenault985b9de2014-03-17 18:58:01 +0000716// \brief Returns the SDNode if it is a constant splat BuildVector or constant
717// int.
718static ConstantSDNode *isConstOrConstSplat(SDValue N) {
719 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
720 return CN;
721
Chandler Carruthbeeacac2014-07-07 19:03:32 +0000722 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
Chandler Carruthf0a33b72014-07-09 00:41:34 +0000723 BitVector UndefElements;
724 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
Chandler Carruthbeeacac2014-07-07 19:03:32 +0000725
726 // BuildVectors can truncate their operands. Ignore that case here.
Chandler Carruthb844e722014-07-08 07:19:55 +0000727 // FIXME: We blindly ignore splats which include undef which is overly
728 // pessimistic.
Chandler Carruthf0a33b72014-07-09 00:41:34 +0000729 if (CN && UndefElements.none() &&
Chandler Carruthb844e722014-07-08 07:19:55 +0000730 CN->getValueType(0) == N.getValueType().getScalarType())
Chandler Carruthbeeacac2014-07-07 19:03:32 +0000731 return CN;
732 }
Matt Arsenault985b9de2014-03-17 18:58:01 +0000733
734 return nullptr;
735}
736
Matt Arsenault6cc00422014-08-16 10:14:19 +0000737// \brief Returns the SDNode if it is a constant splat BuildVector or constant
738// float.
739static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
740 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
741 return CN;
742
743 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
744 BitVector UndefElements;
745 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
746
Matt Arsenault965de302014-09-02 18:33:51 +0000747 if (CN && UndefElements.none())
Matt Arsenault6cc00422014-08-16 10:14:19 +0000748 return CN;
749 }
750
751 return nullptr;
752}
753
Andrew Trickef9de2a2013-05-25 02:42:55 +0000754SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000755 SDValue N0, SDValue N1) {
Owen Anderson53aa7a92009-08-10 22:56:29 +0000756 EVT VT = N0.getValueType();
Juergen Ributzka68402822014-01-13 21:49:25 +0000757 if (N0.getOpcode() == Opc) {
758 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
759 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
760 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
Matthias Braunf50ab432015-01-13 22:17:46 +0000761 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R))
762 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
763 return SDValue();
Juergen Ributzka73844052014-01-13 20:51:35 +0000764 }
Juergen Ributzka68402822014-01-13 21:49:25 +0000765 if (N0.hasOneUse()) {
766 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
767 // use
768 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
769 if (!OpNode.getNode())
770 return SDValue();
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000771 AddToWorklist(OpNode.getNode());
Juergen Ributzka68402822014-01-13 21:49:25 +0000772 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
Juergen Ributzka73844052014-01-13 20:51:35 +0000773 }
774 }
Nate Begeman22e251a2006-02-03 06:46:56 +0000775 }
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000776
Juergen Ributzka68402822014-01-13 21:49:25 +0000777 if (N1.getOpcode() == Opc) {
778 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
779 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
780 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
Matthias Braunf50ab432015-01-13 22:17:46 +0000781 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L))
782 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
783 return SDValue();
Juergen Ributzka68402822014-01-13 21:49:25 +0000784 }
785 if (N1.hasOneUse()) {
786 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
787 // use
788 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
789 if (!OpNode.getNode())
790 return SDValue();
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000791 AddToWorklist(OpNode.getNode());
Juergen Ributzka68402822014-01-13 21:49:25 +0000792 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
793 }
Nate Begeman22e251a2006-02-03 06:46:56 +0000794 }
795 }
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000796
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000797 return SDValue();
Nate Begeman22e251a2006-02-03 06:46:56 +0000798}
799
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000800SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
801 bool AddTo) {
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000802 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
803 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +0000804 DEBUG(dbgs() << "\nReplacing.1 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000805 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000806 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000807 To[0].getNode()->dump(&DAG);
Mehdi Aminid3892082014-12-23 18:59:02 +0000808 dbgs() << " and " << NumTo-1 << " other values\n");
809 for (unsigned i = 0, e = NumTo; i != e; ++i)
810 assert((!To[i].getNode() ||
811 N->getValueType(i) == To[i].getValueType()) &&
812 "Cannot combine value to value of different type!");
813
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000814 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000815 DAG.ReplaceAllUsesWith(N, To);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000816 if (AddTo) {
817 // Push the new nodes and any users onto the worklist
818 for (unsigned i = 0, e = NumTo; i != e; ++i) {
Chris Lattner4147f082009-03-12 06:52:53 +0000819 if (To[i].getNode()) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000820 AddToWorklist(To[i].getNode());
821 AddUsersToWorklist(To[i].getNode());
Chris Lattner4147f082009-03-12 06:52:53 +0000822 }
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000823 }
824 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000825
Dan Gohmancd0b1bf2009-01-19 21:44:21 +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 (N->use_empty())
830 deleteAndRecombine(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000831 return SDValue(N, 0);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000832}
833
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000834void DAGCombiner::
835CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
Scott Michelcf0da6c2009-02-17 22:15:04 +0000836 // Replace all uses. If any nodes become isomorphic to other nodes and
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000837 // are deleted, make sure to remove them from our worklist.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000838 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000839 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
Dan Gohmane58ab792009-01-29 01:59:02 +0000840
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000841 // Push the new node and any (possibly new) users onto the worklist.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000842 AddToWorklist(TLO.New.getNode());
843 AddUsersToWorklist(TLO.New.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000844
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000845 // Finally, if the node is now dead, remove it from the graph. The node
846 // may not be dead if the replacement process recursively simplified to
847 // something else needing this node.
Chandler Carruth18066972014-08-02 10:02:07 +0000848 if (TLO.Old.getNode()->use_empty())
849 deleteAndRecombine(TLO.Old.getNode());
Dan Gohmane58ab792009-01-29 01:59:02 +0000850}
851
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000852/// Check the specified integer node value to see if it can be simplified or if
853/// things it uses can be simplified by bit propagation. If so, return true.
Dan Gohmane58ab792009-01-29 01:59:02 +0000854bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000855 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
Dan Gohmane58ab792009-01-29 01:59:02 +0000856 APInt KnownZero, KnownOne;
857 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
858 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000859
Dan Gohmane58ab792009-01-29 01:59:02 +0000860 // Revisit the node.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000861 AddToWorklist(Op.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000862
Dan Gohmane58ab792009-01-29 01:59:02 +0000863 // Replace the old value with the new one.
864 ++NodesCombined;
Wesley Peck527da1b2010-11-23 03:31:01 +0000865 DEBUG(dbgs() << "\nReplacing.2 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000866 TLO.Old.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000867 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000868 TLO.New.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000869 dbgs() << '\n');
Scott Michelcf0da6c2009-02-17 22:15:04 +0000870
Dan Gohmane58ab792009-01-29 01:59:02 +0000871 CommitTargetLoweringOpt(TLO);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000872 return true;
873}
874
Evan Cheng0abb54d2010-04-24 04:43:44 +0000875void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
Andrew Trickef9de2a2013-05-25 02:42:55 +0000876 SDLoc dl(Load);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000877 EVT VT = Load->getValueType(0);
878 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
Evan Chenge19aa5c2010-04-19 19:29:22 +0000879
Evan Cheng0abb54d2010-04-24 04:43:44 +0000880 DEBUG(dbgs() << "\nReplacing.9 ";
881 Load->dump(&DAG);
882 dbgs() << "\nWith: ";
883 Trunc.getNode()->dump(&DAG);
884 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000885 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000886 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
887 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
Chandler Carruth18066972014-08-02 10:02:07 +0000888 deleteAndRecombine(Load);
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000889 AddToWorklist(Trunc.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000890}
891
892SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
893 Replace = false;
Andrew Trickef9de2a2013-05-25 02:42:55 +0000894 SDLoc dl(Op);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000895 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
Evan Chenge8136902010-04-27 19:48:13 +0000896 EVT MemVT = LD->getMemoryVT();
897 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000898 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
899 : ISD::EXTLOAD)
Evan Chenge8136902010-04-27 19:48:13 +0000900 : LD->getExtensionType();
Evan Cheng0abb54d2010-04-24 04:43:44 +0000901 Replace = true;
Stuart Hastings81c43062011-02-16 16:23:55 +0000902 return DAG.getExtLoad(ExtType, dl, PVT,
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000903 LD->getChain(), LD->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +0000904 MemVT, LD->getMemOperand());
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000905 }
906
Evan Chenge19aa5c2010-04-19 19:29:22 +0000907 unsigned Opc = Op.getOpcode();
Evan Chengb9ff1302010-04-23 19:10:30 +0000908 switch (Opc) {
909 default: break;
910 case ISD::AssertSext:
Evan Chenge19aa5c2010-04-19 19:29:22 +0000911 return DAG.getNode(ISD::AssertSext, dl, PVT,
Evan Cheng0abb54d2010-04-24 04:43:44 +0000912 SExtPromoteOperand(Op.getOperand(0), PVT),
Evan Chenge19aa5c2010-04-19 19:29:22 +0000913 Op.getOperand(1));
Evan Chengb9ff1302010-04-23 19:10:30 +0000914 case ISD::AssertZext:
Evan Chenge19aa5c2010-04-19 19:29:22 +0000915 return DAG.getNode(ISD::AssertZext, dl, PVT,
Evan Cheng0abb54d2010-04-24 04:43:44 +0000916 ZExtPromoteOperand(Op.getOperand(0), PVT),
Evan Chenge19aa5c2010-04-19 19:29:22 +0000917 Op.getOperand(1));
Evan Chengb9ff1302010-04-23 19:10:30 +0000918 case ISD::Constant: {
919 unsigned ExtOpc =
Evan Chenge19aa5c2010-04-19 19:29:22 +0000920 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
Evan Chengb9ff1302010-04-23 19:10:30 +0000921 return DAG.getNode(ExtOpc, dl, PVT, Op);
Wesley Peck527da1b2010-11-23 03:31:01 +0000922 }
Evan Chengb9ff1302010-04-23 19:10:30 +0000923 }
924
925 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000926 return SDValue();
Evan Chengb9ff1302010-04-23 19:10:30 +0000927 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
Evan Chengaf56fac2010-04-16 06:14:10 +0000928}
929
Evan Cheng0abb54d2010-04-24 04:43:44 +0000930SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000931 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
932 return SDValue();
933 EVT OldVT = Op.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +0000934 SDLoc dl(Op);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000935 bool Replace = false;
936 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
Craig Topperc0196b12014-04-14 00:51:57 +0000937 if (!NewOp.getNode())
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000938 return SDValue();
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000939 AddToWorklist(NewOp.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000940
941 if (Replace)
942 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
943 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000944 DAG.getValueType(OldVT));
945}
946
Evan Cheng0abb54d2010-04-24 04:43:44 +0000947SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000948 EVT OldVT = Op.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +0000949 SDLoc dl(Op);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000950 bool Replace = false;
951 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
Craig Topperc0196b12014-04-14 00:51:57 +0000952 if (!NewOp.getNode())
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000953 return SDValue();
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000954 AddToWorklist(NewOp.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000955
956 if (Replace)
957 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
958 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000959}
960
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000961/// Promote the specified integer binary operation if the target indicates it is
962/// beneficial. e.g. On x86, it's usually better to promote i16 operations to
963/// i32 since i16 instructions are longer.
Evan Chengaf56fac2010-04-16 06:14:10 +0000964SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
965 if (!LegalOperations)
966 return SDValue();
967
968 EVT VT = Op.getValueType();
969 if (VT.isVector() || !VT.isInteger())
970 return SDValue();
971
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000972 // If operation type is 'undesirable', e.g. i16 on x86, consider
973 // promoting it.
974 unsigned Opc = Op.getOpcode();
975 if (TLI.isTypeDesirableForOp(Opc, VT))
976 return SDValue();
977
Evan Chengaf56fac2010-04-16 06:14:10 +0000978 EVT PVT = VT;
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000979 // Consult target whether it is a good idea to promote this operation and
980 // what's the right type to promote it to.
981 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
Evan Chengaf56fac2010-04-16 06:14:10 +0000982 assert(PVT != VT && "Don't know what type to promote to!");
983
Evan Cheng0abb54d2010-04-24 04:43:44 +0000984 bool Replace0 = false;
985 SDValue N0 = Op.getOperand(0);
986 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
Craig Topperc0196b12014-04-14 00:51:57 +0000987 if (!NN0.getNode())
Evan Chengf1223bd2010-04-22 20:19:46 +0000988 return SDValue();
989
Evan Cheng0abb54d2010-04-24 04:43:44 +0000990 bool Replace1 = false;
991 SDValue N1 = Op.getOperand(1);
Evan Cheng02947a42010-05-10 19:03:57 +0000992 SDValue NN1;
993 if (N0 == N1)
994 NN1 = NN0;
995 else {
996 NN1 = PromoteOperand(N1, PVT, Replace1);
Craig Topperc0196b12014-04-14 00:51:57 +0000997 if (!NN1.getNode())
Evan Cheng02947a42010-05-10 19:03:57 +0000998 return SDValue();
999 }
Evan Chengf1223bd2010-04-22 20:19:46 +00001000
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001001 AddToWorklist(NN0.getNode());
Evan Cheng02947a42010-05-10 19:03:57 +00001002 if (NN1.getNode())
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001003 AddToWorklist(NN1.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +00001004
1005 if (Replace0)
1006 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1007 if (Replace1)
1008 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
Evan Chengf1223bd2010-04-22 20:19:46 +00001009
Evan Chenge8136902010-04-27 19:48:13 +00001010 DEBUG(dbgs() << "\nPromoting ";
1011 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +00001012 SDLoc dl(Op);
Evan Chengf1223bd2010-04-22 20:19:46 +00001013 return DAG.getNode(ISD::TRUNCATE, dl, VT,
Evan Cheng0abb54d2010-04-24 04:43:44 +00001014 DAG.getNode(Opc, dl, PVT, NN0, NN1));
Evan Chengf1223bd2010-04-22 20:19:46 +00001015 }
1016 return SDValue();
1017}
1018
Sanjay Patel50cbfc52014-08-28 16:29:51 +00001019/// Promote the specified integer shift operation if the target indicates it is
1020/// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1021/// i32 since i16 instructions are longer.
Evan Chengf1223bd2010-04-22 20:19:46 +00001022SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1023 if (!LegalOperations)
1024 return SDValue();
1025
1026 EVT VT = Op.getValueType();
1027 if (VT.isVector() || !VT.isInteger())
1028 return SDValue();
1029
1030 // If operation type is 'undesirable', e.g. i16 on x86, consider
1031 // promoting it.
1032 unsigned Opc = Op.getOpcode();
1033 if (TLI.isTypeDesirableForOp(Opc, VT))
1034 return SDValue();
1035
1036 EVT PVT = VT;
1037 // Consult target whether it is a good idea to promote this operation and
1038 // what's the right type to promote it to.
1039 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1040 assert(PVT != VT && "Don't know what type to promote to!");
1041
Evan Cheng0abb54d2010-04-24 04:43:44 +00001042 bool Replace = false;
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001043 SDValue N0 = Op.getOperand(0);
1044 if (Opc == ISD::SRA)
Evan Cheng0abb54d2010-04-24 04:43:44 +00001045 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001046 else if (Opc == ISD::SRL)
Evan Cheng0abb54d2010-04-24 04:43:44 +00001047 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001048 else
Evan Cheng0abb54d2010-04-24 04:43:44 +00001049 N0 = PromoteOperand(N0, PVT, Replace);
Craig Topperc0196b12014-04-14 00:51:57 +00001050 if (!N0.getNode())
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001051 return SDValue();
Evan Cheng0abb54d2010-04-24 04:43:44 +00001052
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001053 AddToWorklist(N0.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +00001054 if (Replace)
1055 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
Evan Chengaf56fac2010-04-16 06:14:10 +00001056
Evan Chenge8136902010-04-27 19:48:13 +00001057 DEBUG(dbgs() << "\nPromoting ";
1058 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +00001059 SDLoc dl(Op);
Evan Chengaf56fac2010-04-16 06:14:10 +00001060 return DAG.getNode(ISD::TRUNCATE, dl, VT,
Evan Chengf1223bd2010-04-22 20:19:46 +00001061 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
Evan Chengaf56fac2010-04-16 06:14:10 +00001062 }
1063 return SDValue();
1064}
1065
Evan Chenge19aa5c2010-04-19 19:29:22 +00001066SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1067 if (!LegalOperations)
1068 return SDValue();
1069
1070 EVT VT = Op.getValueType();
1071 if (VT.isVector() || !VT.isInteger())
1072 return SDValue();
1073
1074 // If operation type is 'undesirable', e.g. i16 on x86, consider
1075 // promoting it.
1076 unsigned Opc = Op.getOpcode();
1077 if (TLI.isTypeDesirableForOp(Opc, VT))
1078 return SDValue();
1079
1080 EVT PVT = VT;
1081 // Consult target whether it is a good idea to promote this operation and
1082 // what's the right type to promote it to.
1083 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1084 assert(PVT != VT && "Don't know what type to promote to!");
1085 // fold (aext (aext x)) -> (aext x)
1086 // fold (aext (zext x)) -> (zext x)
1087 // fold (aext (sext x)) -> (sext x)
Evan Chenge8136902010-04-27 19:48:13 +00001088 DEBUG(dbgs() << "\nPromoting ";
1089 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +00001090 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
Evan Chenge19aa5c2010-04-19 19:29:22 +00001091 }
1092 return SDValue();
1093}
1094
1095bool DAGCombiner::PromoteLoad(SDValue Op) {
1096 if (!LegalOperations)
1097 return false;
1098
1099 EVT VT = Op.getValueType();
1100 if (VT.isVector() || !VT.isInteger())
1101 return false;
1102
1103 // If operation type is 'undesirable', e.g. i16 on x86, consider
1104 // promoting it.
1105 unsigned Opc = Op.getOpcode();
1106 if (TLI.isTypeDesirableForOp(Opc, VT))
1107 return false;
1108
1109 EVT PVT = VT;
1110 // Consult target whether it is a good idea to promote this operation and
1111 // what's the right type to promote it to.
1112 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1113 assert(PVT != VT && "Don't know what type to promote to!");
1114
Andrew Trickef9de2a2013-05-25 02:42:55 +00001115 SDLoc dl(Op);
Evan Chenge19aa5c2010-04-19 19:29:22 +00001116 SDNode *N = Op.getNode();
1117 LoadSDNode *LD = cast<LoadSDNode>(N);
Evan Chenge8136902010-04-27 19:48:13 +00001118 EVT MemVT = LD->getMemoryVT();
1119 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00001120 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1121 : ISD::EXTLOAD)
Evan Chenge8136902010-04-27 19:48:13 +00001122 : LD->getExtensionType();
Stuart Hastings81c43062011-02-16 16:23:55 +00001123 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
Evan Chenge19aa5c2010-04-19 19:29:22 +00001124 LD->getChain(), LD->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00001125 MemVT, LD->getMemOperand());
Evan Chenge19aa5c2010-04-19 19:29:22 +00001126 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1127
Evan Cheng0abb54d2010-04-24 04:43:44 +00001128 DEBUG(dbgs() << "\nPromoting ";
Evan Chenge19aa5c2010-04-19 19:29:22 +00001129 N->dump(&DAG);
Evan Cheng0abb54d2010-04-24 04:43:44 +00001130 dbgs() << "\nTo: ";
Evan Chenge19aa5c2010-04-19 19:29:22 +00001131 Result.getNode()->dump(&DAG);
1132 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001133 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001134 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1135 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
Chandler Carruth18066972014-08-02 10:02:07 +00001136 deleteAndRecombine(N);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001137 AddToWorklist(Result.getNode());
Evan Chenge19aa5c2010-04-19 19:29:22 +00001138 return true;
1139 }
1140 return false;
1141}
1142
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001143/// \brief Recursively delete a node which has no uses and any operands for
1144/// which it is the only use.
1145///
1146/// Note that this both deletes the nodes and removes them from the worklist.
1147/// It also adds any nodes who have had a user deleted to the worklist as they
1148/// may now have only one use and subject to other combines.
1149bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1150 if (!N->use_empty())
1151 return false;
1152
1153 SmallSetVector<SDNode *, 16> Nodes;
1154 Nodes.insert(N);
1155 do {
1156 N = Nodes.pop_back_val();
1157 if (!N)
1158 continue;
1159
1160 if (N->use_empty()) {
1161 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1162 Nodes.insert(N->getOperand(i).getNode());
1163
1164 removeFromWorklist(N);
1165 DAG.DeleteNode(N);
1166 } else {
1167 AddToWorklist(N);
1168 }
1169 } while (!Nodes.empty());
1170 return true;
1171}
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001172
Chris Lattnere49c9742007-05-14 22:04:50 +00001173//===----------------------------------------------------------------------===//
1174// Main DAG Combiner implementation
1175//===----------------------------------------------------------------------===//
1176
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001177void DAGCombiner::Run(CombineLevel AtLevel) {
1178 // set the instance variables, so that the various visit routines may use it.
1179 Level = AtLevel;
Eli Friedman9d448e42011-11-12 00:35:34 +00001180 LegalOperations = Level >= AfterLegalizeVectorOps;
1181 LegalTypes = Level >= AfterLegalizeTypes;
Nate Begeman2504fe22005-09-01 23:24:04 +00001182
Paul Robinsonad06e432014-11-03 18:19:26 +00001183 // Early exit if this basic block is in an optnone function.
Duncan P. N. Exon Smith70eb9c52015-02-14 01:44:41 +00001184 if (DAG.getMachineFunction().getFunction()->hasFnAttribute(
1185 Attribute::OptimizeNone))
Paul Robinsonad06e432014-11-03 18:19:26 +00001186 return;
1187
Evan Cheng5e7658c2008-08-29 22:21:44 +00001188 // Add all the dag nodes to the worklist.
Evan Cheng5e7658c2008-08-29 22:21:44 +00001189 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1190 E = DAG.allnodes_end(); I != E; ++I)
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001191 AddToWorklist(I);
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001192
Evan Cheng5e7658c2008-08-29 22:21:44 +00001193 // Create a dummy node (which is not added to allnodes), that adds a reference
1194 // to the root node, preventing it from being deleted, and tracking any
1195 // changes of the root.
1196 HandleSDNode Dummy(DAG.getRoot());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001197
James Molloy67b6b112012-02-16 09:17:04 +00001198 // while the worklist isn't empty, find a node and
Evan Cheng5e7658c2008-08-29 22:21:44 +00001199 // try and combine it.
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001200 while (!WorklistMap.empty()) {
James Molloy67b6b112012-02-16 09:17:04 +00001201 SDNode *N;
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001202 // The Worklist holds the SDNodes in order, but it may contain null entries.
James Molloy67b6b112012-02-16 09:17:04 +00001203 do {
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001204 N = Worklist.pop_back_val();
1205 } while (!N);
1206
1207 bool GoodWorklistEntry = WorklistMap.erase(N);
1208 (void)GoodWorklistEntry;
1209 assert(GoodWorklistEntry &&
1210 "Found a worklist entry without a corresponding map entry!");
Scott Michelcf0da6c2009-02-17 22:15:04 +00001211
Evan Cheng5e7658c2008-08-29 22:21:44 +00001212 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1213 // N is deleted from the DAG, since they too may now be dead or may have a
1214 // reduced number of uses, allowing other xforms.
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001215 if (recursivelyDeleteUnusedNodes(N))
Evan Cheng5e7658c2008-08-29 22:21:44 +00001216 continue;
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001217
1218 WorklistRemover DeadNodes(*this);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001219
Chandler Carruth411fb402014-07-26 05:49:40 +00001220 // If this combine is running after legalizing the DAG, re-legalize any
1221 // nodes pulled off the worklist.
1222 if (Level == AfterLegalizeDAG) {
1223 SmallSetVector<SDNode *, 16> UpdatedNodes;
1224 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1225
1226 for (SDNode *LN : UpdatedNodes) {
1227 AddToWorklist(LN);
1228 AddUsersToWorklist(LN);
1229 }
1230 if (!NIsValid)
1231 continue;
1232 }
1233
Chandler Carruthb1432742014-07-28 17:55:07 +00001234 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1235
Chandler Carruthcde4eb52014-08-03 23:10:59 +00001236 // Add any operands of the new node which have not yet been combined to the
1237 // worklist as well. Because the worklist uniques things already, this
1238 // won't repeatedly process the same operand.
1239 CombinedNodes.insert(N);
1240 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1241 if (!CombinedNodes.count(N->getOperand(i).getNode()))
1242 AddToWorklist(N->getOperand(i).getNode());
1243
Evan Cheng5e7658c2008-08-29 22:21:44 +00001244 SDValue RV = combine(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001245
Craig Topperc0196b12014-04-14 00:51:57 +00001246 if (!RV.getNode())
Evan Cheng5e7658c2008-08-29 22:21:44 +00001247 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001248
Evan Cheng5e7658c2008-08-29 22:21:44 +00001249 ++NodesCombined;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001250
Evan Cheng5e7658c2008-08-29 22:21:44 +00001251 // If we get back the same node we passed in, rather than a new node or
1252 // zero, we know that the node must have defined multiple values and
Scott Michelcf0da6c2009-02-17 22:15:04 +00001253 // CombineTo was used. Since CombineTo takes care of the worklist
Evan Cheng5e7658c2008-08-29 22:21:44 +00001254 // mechanics for us, we have no work to do in this case.
1255 if (RV.getNode() == N)
1256 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001257
Evan Cheng5e7658c2008-08-29 22:21:44 +00001258 assert(N->getOpcode() != ISD::DELETED_NODE &&
1259 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1260 "Node was deleted but visit returned new node!");
Chris Lattner8f872d22006-05-27 00:43:02 +00001261
Chandler Carruth9f4530b2014-07-24 22:15:28 +00001262 DEBUG(dbgs() << " ... into: ";
1263 RV.getNode()->dump(&DAG));
Eric Christopherd6300d22011-07-14 01:12:15 +00001264
Devang Patelefec7712011-05-23 22:04:42 +00001265 // Transfer debug value.
1266 DAG.TransferDbgValues(SDValue(N, 0), RV);
Evan Cheng5e7658c2008-08-29 22:21:44 +00001267 if (N->getNumValues() == RV.getNode()->getNumValues())
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001268 DAG.ReplaceAllUsesWith(N, RV.getNode());
Evan Cheng5e7658c2008-08-29 22:21:44 +00001269 else {
1270 assert(N->getValueType(0) == RV.getValueType() &&
1271 N->getNumValues() == 1 && "Type mismatch");
1272 SDValue OpV = RV;
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001273 DAG.ReplaceAllUsesWith(N, &OpV);
Evan Cheng5e7658c2008-08-29 22:21:44 +00001274 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001275
Evan Cheng5e7658c2008-08-29 22:21:44 +00001276 // Push the new node and any users onto the worklist
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001277 AddToWorklist(RV.getNode());
1278 AddUsersToWorklist(RV.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001279
Dan Gohmancd0b1bf2009-01-19 21:44:21 +00001280 // Finally, if the node is now dead, remove it from the graph. The node
1281 // may not be dead if the replacement process recursively simplified to
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001282 // something else needing this node. This will also take care of adding any
1283 // operands which have lost a user to the worklist.
1284 recursivelyDeleteUnusedNodes(N);
Evan Cheng5e7658c2008-08-29 22:21:44 +00001285 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001286
Chris Lattner06f1d0f2005-10-05 06:35:28 +00001287 // If the root changed (e.g. it was a dead load, update the root).
1288 DAG.setRoot(Dummy.getValue());
Hal Finkele0cf6392012-04-16 03:33:22 +00001289 DAG.RemoveDeadNodes();
Nate Begeman21158fc2005-09-01 00:19:25 +00001290}
1291
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001292SDValue DAGCombiner::visit(SDNode *N) {
Evan Chengf1005572010-04-28 07:10:39 +00001293 switch (N->getOpcode()) {
Nate Begeman21158fc2005-09-01 00:19:25 +00001294 default: break;
Nate Begemane8f78d12005-09-01 00:33:32 +00001295 case ISD::TokenFactor: return visitTokenFactor(N);
Chris Lattneree322b42008-02-13 07:25:05 +00001296 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001297 case ISD::ADD: return visitADD(N);
1298 case ISD::SUB: return visitSUB(N);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001299 case ISD::ADDC: return visitADDC(N);
Craig Topper43a1bd62012-01-07 09:06:39 +00001300 case ISD::SUBC: return visitSUBC(N);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001301 case ISD::ADDE: return visitADDE(N);
Craig Topper43a1bd62012-01-07 09:06:39 +00001302 case ISD::SUBE: return visitSUBE(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001303 case ISD::MUL: return visitMUL(N);
1304 case ISD::SDIV: return visitSDIV(N);
1305 case ISD::UDIV: return visitUDIV(N);
1306 case ISD::SREM: return visitSREM(N);
1307 case ISD::UREM: return visitUREM(N);
1308 case ISD::MULHU: return visitMULHU(N);
1309 case ISD::MULHS: return visitMULHS(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001310 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1311 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00001312 case ISD::SMULO: return visitSMULO(N);
1313 case ISD::UMULO: return visitUMULO(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001314 case ISD::SDIVREM: return visitSDIVREM(N);
1315 case ISD::UDIVREM: return visitUDIVREM(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001316 case ISD::AND: return visitAND(N);
1317 case ISD::OR: return visitOR(N);
1318 case ISD::XOR: return visitXOR(N);
1319 case ISD::SHL: return visitSHL(N);
1320 case ISD::SRA: return visitSRA(N);
1321 case ISD::SRL: return visitSRL(N);
Adam Nemet7f928f12014-03-07 23:56:30 +00001322 case ISD::ROTR:
1323 case ISD::ROTL: return visitRotate(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001324 case ISD::CTLZ: return visitCTLZ(N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00001325 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001326 case ISD::CTTZ: return visitCTTZ(N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00001327 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001328 case ISD::CTPOP: return visitCTPOP(N);
Nate Begeman24a7eca2005-09-16 00:54:12 +00001329 case ISD::SELECT: return visitSELECT(N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00001330 case ISD::VSELECT: return visitVSELECT(N);
Nate Begeman24a7eca2005-09-16 00:54:12 +00001331 case ISD::SELECT_CC: return visitSELECT_CC(N);
1332 case ISD::SETCC: return visitSETCC(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001333 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1334 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
Chris Lattner812646a2006-05-05 05:58:59 +00001335 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001336 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1337 case ISD::TRUNCATE: return visitTRUNCATE(N);
Wesley Peck527da1b2010-11-23 03:31:01 +00001338 case ISD::BITCAST: return visitBITCAST(N);
Evan Chengb980f6f2008-05-12 23:04:07 +00001339 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
Chris Lattner6f3b5772005-09-28 22:28:18 +00001340 case ISD::FADD: return visitFADD(N);
1341 case ISD::FSUB: return visitFSUB(N);
1342 case ISD::FMUL: return visitFMUL(N);
Owen Anderson41b06652012-05-02 22:17:40 +00001343 case ISD::FMA: return visitFMA(N);
Chris Lattner6f3b5772005-09-28 22:28:18 +00001344 case ISD::FDIV: return visitFDIV(N);
1345 case ISD::FREM: return visitFREM(N);
Sanjay Patelbdf1e382014-09-26 23:01:47 +00001346 case ISD::FSQRT: return visitFSQRT(N);
Chris Lattner3bc40502006-03-05 05:30:57 +00001347 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001348 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1349 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1350 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1351 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1352 case ISD::FP_ROUND: return visitFP_ROUND(N);
1353 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1354 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1355 case ISD::FNEG: return visitFNEG(N);
1356 case ISD::FABS: return visitFABS(N);
Owen Andersona40319b2012-08-13 23:32:49 +00001357 case ISD::FFLOOR: return visitFFLOOR(N);
Matt Arsenault7c936902014-10-21 23:01:01 +00001358 case ISD::FMINNUM: return visitFMINNUM(N);
1359 case ISD::FMAXNUM: return visitFMAXNUM(N);
Owen Andersona40319b2012-08-13 23:32:49 +00001360 case ISD::FCEIL: return visitFCEIL(N);
1361 case ISD::FTRUNC: return visitFTRUNC(N);
Nate Begemanc760f802005-09-19 22:34:01 +00001362 case ISD::BRCOND: return visitBRCOND(N);
Nate Begemanc760f802005-09-19 22:34:01 +00001363 case ISD::BR_CC: return visitBR_CC(N);
Chris Lattnere260ed82005-10-10 22:04:48 +00001364 case ISD::LOAD: return visitLOAD(N);
Chris Lattner04c73702005-10-10 22:31:19 +00001365 case ISD::STORE: return visitSTORE(N);
Chris Lattner5336a592006-03-19 01:27:56 +00001366 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
Evan Cheng0de312d2007-10-06 08:19:55 +00001367 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
Dan Gohmana8665142007-06-25 16:23:39 +00001368 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1369 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +00001370 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
Chris Lattnera46dfe82006-03-28 22:11:53 +00001371 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
Manman Ren413a6cb2014-01-31 01:10:35 +00001372 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00001373 case ISD::MLOAD: return visitMLOAD(N);
1374 case ISD::MSTORE: return visitMSTORE(N);
Nate Begeman21158fc2005-09-01 00:19:25 +00001375 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001376 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001377}
1378
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001379SDValue DAGCombiner::combine(SDNode *N) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001380 SDValue RV = visit(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001381
1382 // If nothing happened, try a target-specific DAG combine.
Craig Topperc0196b12014-04-14 00:51:57 +00001383 if (!RV.getNode()) {
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001384 assert(N->getOpcode() != ISD::DELETED_NODE &&
1385 "Node was deleted but visit returned NULL!");
1386
1387 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1388 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1389
1390 // Expose the DAG combiner to the target combiner impls.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001391 TargetLowering::DAGCombinerInfo
Nadav Rotemb1dd5242012-12-27 06:47:41 +00001392 DagCombineInfo(DAG, Level, false, this);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001393
1394 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1395 }
1396 }
1397
Evan Chengf1005572010-04-28 07:10:39 +00001398 // If nothing happened still, try promoting the operation.
Craig Topperc0196b12014-04-14 00:51:57 +00001399 if (!RV.getNode()) {
Evan Chengf1005572010-04-28 07:10:39 +00001400 switch (N->getOpcode()) {
1401 default: break;
1402 case ISD::ADD:
1403 case ISD::SUB:
1404 case ISD::MUL:
1405 case ISD::AND:
1406 case ISD::OR:
1407 case ISD::XOR:
1408 RV = PromoteIntBinOp(SDValue(N, 0));
1409 break;
1410 case ISD::SHL:
1411 case ISD::SRA:
1412 case ISD::SRL:
1413 RV = PromoteIntShiftOp(SDValue(N, 0));
1414 break;
1415 case ISD::SIGN_EXTEND:
1416 case ISD::ZERO_EXTEND:
1417 case ISD::ANY_EXTEND:
1418 RV = PromoteExtend(SDValue(N, 0));
1419 break;
1420 case ISD::LOAD:
1421 if (PromoteLoad(SDValue(N, 0)))
1422 RV = SDValue(N, 0);
1423 break;
1424 }
1425 }
1426
Scott Michelcf0da6c2009-02-17 22:15:04 +00001427 // If N is a commutative binary node, try commuting it to enable more
Evan Cheng31604a62008-03-22 01:55:50 +00001428 // sdisel CSE.
Craig Topperc0196b12014-04-14 00:51:57 +00001429 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
Evan Cheng31604a62008-03-22 01:55:50 +00001430 N->getNumValues() == 1) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001431 SDValue N0 = N->getOperand(0);
1432 SDValue N1 = N->getOperand(1);
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001433
Evan Cheng31604a62008-03-22 01:55:50 +00001434 // Constant operands are canonicalized to RHS.
1435 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
Andrea Di Biagio4db1abe2014-06-09 12:32:53 +00001436 SDValue Ops[] = {N1, N0};
1437 SDNode *CSENode;
1438 if (const BinaryWithFlagsSDNode *BinNode =
1439 dyn_cast<BinaryWithFlagsSDNode>(N)) {
1440 CSENode = DAG.getNodeIfExists(
1441 N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1442 BinNode->hasNoSignedWrap(), BinNode->isExact());
1443 } else {
1444 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1445 }
Evan Chengfe7610f2008-03-24 23:55:16 +00001446 if (CSENode)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001447 return SDValue(CSENode, 0);
Evan Cheng31604a62008-03-22 01:55:50 +00001448 }
1449 }
1450
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001451 return RV;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001452}
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001453
Sanjay Patel50cbfc52014-08-28 16:29:51 +00001454/// Given a node, return its input chain if it has one, otherwise return a null
1455/// sd operand.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001456static SDValue getInputChainForNode(SDNode *N) {
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001457 if (unsigned NumOps = N->getNumOperands()) {
Owen Anderson9f944592009-08-11 20:47:22 +00001458 if (N->getOperand(0).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001459 return N->getOperand(0);
Stephen Lin8e8424e2013-07-09 00:44:49 +00001460 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001461 return N->getOperand(NumOps-1);
1462 for (unsigned i = 1; i < NumOps-1; ++i)
Owen Anderson9f944592009-08-11 20:47:22 +00001463 if (N->getOperand(i).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001464 return N->getOperand(i);
1465 }
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001466 return SDValue();
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001467}
1468
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001469SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001470 // If N has two operands, where one has an input chain equal to the other,
1471 // the 'other' chain is redundant.
1472 if (N->getNumOperands() == 2) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00001473 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001474 return N->getOperand(0);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001475 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001476 return N->getOperand(1);
1477 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001478
Chris Lattner48fb92f2007-05-16 06:37:59 +00001479 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001480 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001481 SmallPtrSet<SDNode*, 16> SeenOps;
Chris Lattner48fb92f2007-05-16 06:37:59 +00001482 bool Changed = false; // If we should replace this token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001483
Jim Laskey708d0db2006-10-04 16:53:27 +00001484 // Start out with this token factor.
Jim Laskeyd07be232006-09-25 16:29:54 +00001485 TFs.push_back(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001486
Jim Laskey0463e082006-10-07 23:37:56 +00001487 // Iterate through token factors. The TFs grows when new token factors are
Jim Laskey6549d222006-10-05 15:07:25 +00001488 // encountered.
1489 for (unsigned i = 0; i < TFs.size(); ++i) {
1490 SDNode *TF = TFs[i];
Scott Michelcf0da6c2009-02-17 22:15:04 +00001491
Jim Laskey708d0db2006-10-04 16:53:27 +00001492 // Check each of the operands.
1493 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001494 SDValue Op = TF->getOperand(i);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001495
Jim Laskey708d0db2006-10-04 16:53:27 +00001496 switch (Op.getOpcode()) {
1497 case ISD::EntryToken:
Jim Laskey6549d222006-10-05 15:07:25 +00001498 // Entry tokens don't need to be added to the list. They are
Jonas Paulssona25a3f42015-02-10 15:34:29 +00001499 // redundant.
Jim Laskey6549d222006-10-05 15:07:25 +00001500 Changed = true;
Jim Laskey708d0db2006-10-04 16:53:27 +00001501 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001502
Jim Laskey708d0db2006-10-04 16:53:27 +00001503 case ISD::TokenFactor:
Nate Begeman879d8f12009-09-15 00:18:30 +00001504 if (Op.hasOneUse() &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00001505 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
Jim Laskey708d0db2006-10-04 16:53:27 +00001506 // Queue up for processing.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001507 TFs.push_back(Op.getNode());
Jim Laskey708d0db2006-10-04 16:53:27 +00001508 // Clean up in case the token factor is removed.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001509 AddToWorklist(Op.getNode());
Jim Laskey708d0db2006-10-04 16:53:27 +00001510 Changed = true;
1511 break;
Jim Laskeyd07be232006-09-25 16:29:54 +00001512 }
Jim Laskey708d0db2006-10-04 16:53:27 +00001513 // Fall thru
Scott Michelcf0da6c2009-02-17 22:15:04 +00001514
Jim Laskey708d0db2006-10-04 16:53:27 +00001515 default:
Chris Lattner48fb92f2007-05-16 06:37:59 +00001516 // Only add if it isn't already in the list.
David Blaikie70573dc2014-11-19 07:49:26 +00001517 if (SeenOps.insert(Op.getNode()).second)
Jim Laskey6549d222006-10-05 15:07:25 +00001518 Ops.push_back(Op);
Chris Lattner48fb92f2007-05-16 06:37:59 +00001519 else
1520 Changed = true;
Jim Laskey708d0db2006-10-04 16:53:27 +00001521 break;
Jim Laskeyd07be232006-09-25 16:29:54 +00001522 }
1523 }
Jim Laskey708d0db2006-10-04 16:53:27 +00001524 }
Wesley Peck527da1b2010-11-23 03:31:01 +00001525
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001526 SDValue Result;
Jim Laskey708d0db2006-10-04 16:53:27 +00001527
Jonas Paulssona25a3f42015-02-10 15:34:29 +00001528 // If we've changed things around then replace token factor.
Jim Laskey708d0db2006-10-04 16:53:27 +00001529 if (Changed) {
Dan Gohman70de4cb2008-01-29 13:02:09 +00001530 if (Ops.empty()) {
Jim Laskey708d0db2006-10-04 16:53:27 +00001531 // The entry token is the only possible outcome.
1532 Result = DAG.getEntryNode();
1533 } else {
1534 // New and improved token factor.
Craig Topper48d114b2014-04-26 18:35:24 +00001535 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
Nate Begeman02b23c62005-10-13 03:11:28 +00001536 }
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001537
Jonas Paulssonbf8d0cc2015-02-11 16:10:31 +00001538 // Add users to worklist if AA is enabled, since it may introduce
1539 // a lot of new chained token factors while removing memory deps.
1540 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1541 : DAG.getSubtarget().useAA();
1542 return CombineTo(N, Result, UseAA /*add to worklist*/);
Nate Begeman02b23c62005-10-13 03:11:28 +00001543 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001544
Jim Laskey708d0db2006-10-04 16:53:27 +00001545 return Result;
Nate Begeman21158fc2005-09-01 00:19:25 +00001546}
1547
Chris Lattneree322b42008-02-13 07:25:05 +00001548/// MERGE_VALUES can always be eliminated.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001549SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001550 WorklistRemover DeadNodes(*this);
Dan Gohman9d26c852009-08-10 23:43:19 +00001551 // Replacing results may cause a different MERGE_VALUES to suddenly
1552 // be CSE'd with N, and carry its uses with it. Iterate until no
1553 // uses remain, to ensure that the node can be safely deleted.
Pete Cooperfe5b84b2012-06-20 19:35:43 +00001554 // First add the users of this node to the work list so that they
1555 // can be tried again once they have new operands.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001556 AddUsersToWorklist(N);
Dan Gohman9d26c852009-08-10 23:43:19 +00001557 do {
1558 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001559 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
Dan Gohman9d26c852009-08-10 23:43:19 +00001560 } while (!N->use_empty());
Chandler Carruth18066972014-08-02 10:02:07 +00001561 deleteAndRecombine(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001562 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattneree322b42008-02-13 07:25:05 +00001563}
1564
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001565SDValue DAGCombiner::visitADD(SDNode *N) {
1566 SDValue N0 = N->getOperand(0);
1567 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001568 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1569 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001570 EVT VT = N0.getValueType();
Dan Gohmana8665142007-06-25 16:23:39 +00001571
1572 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00001573 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001574 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001575 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topperd8005db2012-12-10 08:12:29 +00001576
1577 // fold (add x, 0) -> x, vector edition
1578 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1579 return N0;
1580 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1581 return N1;
Dan Gohman80f9f072007-07-13 20:03:40 +00001582 }
Bill Wendling0864a752008-12-10 22:36:00 +00001583
Dan Gohman06563a82007-07-03 14:03:57 +00001584 // fold (add x, undef) -> undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00001585 if (N0.getOpcode() == ISD::UNDEF)
1586 return N0;
1587 if (N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00001588 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00001589 // fold (add c1, c2) -> c1+c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001590 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00001591 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00001592 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00001593 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001594 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001595 // fold (add x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001596 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00001597 return N0;
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001598 // fold (add Sym, c) -> Sym+c
1599 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001600 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001601 GA->getOpcode() == ISD::GlobalAddress)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001602 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001603 GA->getOffset() +
1604 (uint64_t)N1C->getSExtValue());
Chris Lattner3470b5d2006-01-12 20:22:43 +00001605 // fold ((c1-A)+c2) -> (c1+c2)-A
1606 if (N1C && N0.getOpcode() == ISD::SUB)
1607 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001608 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Dan Gohmanb72127a2008-03-13 22:13:53 +00001609 DAG.getConstant(N1C->getAPIntValue()+
1610 N0C->getAPIntValue(), VT),
Chris Lattner3470b5d2006-01-12 20:22:43 +00001611 N0.getOperand(1));
Nate Begeman22e251a2006-02-03 06:46:56 +00001612 // reassociate add
Andrew Trickef9de2a2013-05-25 02:42:55 +00001613 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00001614 if (RADD.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00001615 return RADD;
Nate Begeman21158fc2005-09-01 00:19:25 +00001616 // fold ((0-A) + B) -> B-A
1617 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1618 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001619 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
Nate Begeman21158fc2005-09-01 00:19:25 +00001620 // fold (A + (0-B)) -> A-B
1621 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1622 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001623 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
Chris Lattner6f3b5772005-09-28 22:28:18 +00001624 // fold (A+(B-A)) -> B
1625 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
Nate Begemand23739d2005-09-06 04:43:02 +00001626 return N1.getOperand(0);
Dale Johannesen73bc0ba2008-11-27 00:43:21 +00001627 // fold ((B-A)+A) -> B
1628 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1629 return N0.getOperand(0);
Dale Johannesen8c766702008-12-02 01:30:54 +00001630 // fold (A+(B-(A+C))) to (B-C)
1631 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001632 N0 == N1.getOperand(1).getOperand(0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001633 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
Dale Johannesen8c766702008-12-02 01:30:54 +00001634 N1.getOperand(1).getOperand(1));
Dale Johannesen8c766702008-12-02 01:30:54 +00001635 // fold (A+(B-(C+A))) to (B-C)
1636 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001637 N0 == N1.getOperand(1).getOperand(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001638 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
Dale Johannesen8c766702008-12-02 01:30:54 +00001639 N1.getOperand(1).getOperand(0));
Dale Johannesenee573fc2008-12-23 23:47:22 +00001640 // fold (A+((B-A)+or-C)) to (B+or-C)
Dale Johannesen54bdec22008-12-02 18:40:40 +00001641 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1642 N1.getOperand(0).getOpcode() == ISD::SUB &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001643 N0 == N1.getOperand(0).getOperand(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001644 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
Bill Wendlingc4423482009-01-30 02:31:17 +00001645 N1.getOperand(0).getOperand(0), N1.getOperand(1));
Dale Johannesen54bdec22008-12-02 18:40:40 +00001646
Dale Johannesen8c766702008-12-02 01:30:54 +00001647 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1648 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1649 SDValue N00 = N0.getOperand(0);
1650 SDValue N01 = N0.getOperand(1);
1651 SDValue N10 = N1.getOperand(0);
1652 SDValue N11 = N1.getOperand(1);
Bill Wendlingc4423482009-01-30 02:31:17 +00001653
1654 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001655 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1656 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1657 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
Dale Johannesen8c766702008-12-02 01:30:54 +00001658 }
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001659
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001660 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1661 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001662
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001663 // fold (a+b) -> (a|b) iff a and b share no bits.
Duncan Sands13237ac2008-06-06 12:08:01 +00001664 if (VT.isInteger() && !VT.isVector()) {
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001665 APInt LHSZero, LHSOne;
1666 APInt RHSZero, RHSOne;
Jay Foada0653a32014-05-14 21:14:37 +00001667 DAG.computeKnownBits(N0, LHSZero, LHSOne);
Bill Wendlingc4423482009-01-30 02:31:17 +00001668
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001669 if (LHSZero.getBoolValue()) {
Jay Foada0653a32014-05-14 21:14:37 +00001670 DAG.computeKnownBits(N1, RHSZero, RHSOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001671
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001672 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1673 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
Owen Anderson60a46782014-01-31 00:51:43 +00001674 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1675 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1676 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1677 }
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001678 }
1679 }
Evan Chengeb99bd72006-11-06 08:14:30 +00001680
Dan Gohman954f4902010-01-19 23:30:49 +00001681 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1682 if (N1.getOpcode() == ISD::SHL &&
1683 N1.getOperand(0).getOpcode() == ISD::SUB)
1684 if (ConstantSDNode *C =
1685 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1686 if (C->getAPIntValue() == 0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001687 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1688 DAG.getNode(ISD::SHL, SDLoc(N), VT,
Dan Gohman954f4902010-01-19 23:30:49 +00001689 N1.getOperand(0).getOperand(1),
1690 N1.getOperand(1)));
1691 if (N0.getOpcode() == ISD::SHL &&
1692 N0.getOperand(0).getOpcode() == ISD::SUB)
1693 if (ConstantSDNode *C =
1694 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1695 if (C->getAPIntValue() == 0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001696 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1697 DAG.getNode(ISD::SHL, SDLoc(N), VT,
Dan Gohman954f4902010-01-19 23:30:49 +00001698 N0.getOperand(0).getOperand(1),
1699 N0.getOperand(1)));
1700
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001701 if (N1.getOpcode() == ISD::AND) {
1702 SDValue AndOp0 = N1.getOperand(0);
Wesley Peck527da1b2010-11-23 03:31:01 +00001703 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001704 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1705 unsigned DestBits = VT.getScalarType().getSizeInBits();
Wesley Peck527da1b2010-11-23 03:31:01 +00001706
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001707 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1708 // and similar xforms where the inner op is either ~0 or 0.
1709 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001710 SDLoc DL(N);
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001711 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1712 }
1713 }
1714
Benjamin Kramer1f4dfbb2010-12-22 23:17:45 +00001715 // add (sext i1), X -> sub X, (zext i1)
1716 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1717 N0.getOperand(0).getValueType() == MVT::i1 &&
1718 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001719 SDLoc DL(N);
Benjamin Kramer1f4dfbb2010-12-22 23:17:45 +00001720 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1721 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1722 }
1723
Jan Veselyaf62cf42014-10-17 14:45:25 +00001724 // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1725 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1726 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1727 if (TN->getVT() == MVT::i1) {
1728 SDLoc DL(N);
1729 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1730 DAG.getConstant(1, VT));
1731 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1732 }
1733 }
1734
Evan Chengf1005572010-04-28 07:10:39 +00001735 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001736}
1737
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001738SDValue DAGCombiner::visitADDC(SDNode *N) {
1739 SDValue N0 = N->getOperand(0);
1740 SDValue N1 = N->getOperand(1);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001741 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1742 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001743 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001744
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001745 // If the flag result is dead, turn this into an ADD.
Craig Topper0515cd42012-01-07 18:31:09 +00001746 if (!N->hasAnyUseOfValue(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001747 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
Dale Johannesen5234d372009-06-02 03:12:52 +00001748 DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001749 SDLoc(N), MVT::Glue));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001750
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001751 // canonicalize constant to RHS.
Dan Gohmanb4e26372008-06-23 15:29:14 +00001752 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001753 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001754
Chris Lattner47206662007-03-04 20:40:38 +00001755 // fold (addc x, 0) -> x + no carry out
1756 if (N1C && N1C->isNullValue())
Dale Johannesen5234d372009-06-02 03:12:52 +00001757 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001758 SDLoc(N), MVT::Glue));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001759
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001760 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001761 APInt LHSZero, LHSOne;
1762 APInt RHSZero, RHSOne;
Jay Foada0653a32014-05-14 21:14:37 +00001763 DAG.computeKnownBits(N0, LHSZero, LHSOne);
Bill Wendling61277572009-01-30 02:38:00 +00001764
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001765 if (LHSZero.getBoolValue()) {
Jay Foada0653a32014-05-14 21:14:37 +00001766 DAG.computeKnownBits(N1, RHSZero, RHSOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001767
Chris Lattner47206662007-03-04 20:40:38 +00001768 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1769 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001770 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001771 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
Dale Johannesen5234d372009-06-02 03:12:52 +00001772 DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001773 SDLoc(N), MVT::Glue));
Chris Lattner47206662007-03-04 20:40:38 +00001774 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001775
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001776 return SDValue();
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001777}
1778
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001779SDValue DAGCombiner::visitADDE(SDNode *N) {
1780 SDValue N0 = N->getOperand(0);
1781 SDValue N1 = N->getOperand(1);
1782 SDValue CarryIn = N->getOperand(2);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001783 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1784 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001785
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001786 // canonicalize constant to RHS
Dan Gohmanb4e26372008-06-23 15:29:14 +00001787 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001788 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
Bill Wendling61277572009-01-30 02:38:00 +00001789 N1, N0, CarryIn);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001790
Chris Lattner47206662007-03-04 20:40:38 +00001791 // fold (adde x, y, false) -> (addc x, y)
Dale Johannesen5234d372009-06-02 03:12:52 +00001792 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001793 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001794
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001795 return SDValue();
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001796}
1797
Eric Christophere5ca1e02011-02-16 04:50:12 +00001798// Since it may not be valid to emit a fold to zero for vector initializers
1799// check if we can before folding.
Andrew Trickef9de2a2013-05-25 02:42:55 +00001800static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
Hal Finkel6c29bd92013-07-09 17:02:45 +00001801 SelectionDAG &DAG,
1802 bool LegalOperations, bool LegalTypes) {
Stephen Lin8e8424e2013-07-09 00:44:49 +00001803 if (!VT.isVector())
Eric Christophere5ca1e02011-02-16 04:50:12 +00001804 return DAG.getConstant(0, VT);
Daniel Sandersb021c6f2013-11-25 11:14:43 +00001805 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1806 return DAG.getConstant(0, VT);
Eric Christophere5ca1e02011-02-16 04:50:12 +00001807 return SDValue();
1808}
1809
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001810SDValue DAGCombiner::visitSUB(SDNode *N) {
1811 SDValue N0 = N->getOperand(0);
1812 SDValue N1 = N->getOperand(1);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001813 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1814 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
Craig Topperc0196b12014-04-14 00:51:57 +00001815 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
Eric Christopherd6300d22011-07-14 01:12:15 +00001816 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
Owen Anderson53aa7a92009-08-10 22:56:29 +00001817 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001818
Dan Gohmana8665142007-06-25 16:23:39 +00001819 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00001820 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001821 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001822 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topperd8005db2012-12-10 08:12:29 +00001823
1824 // fold (sub x, 0) -> x, vector edition
1825 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1826 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00001827 }
Bill Wendling0864a752008-12-10 22:36:00 +00001828
Chris Lattnereeb2bda2005-10-17 01:07:11 +00001829 // fold (sub x, x) -> 0
Eric Christopheref721412011-02-16 01:10:03 +00001830 // FIXME: Refactor this and xor and other similar operations together.
Eric Christophere5ca1e02011-02-16 04:50:12 +00001831 if (N0 == N1)
Hal Finkel6c29bd92013-07-09 17:02:45 +00001832 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
Nate Begeman21158fc2005-09-01 00:19:25 +00001833 // fold (sub c1, c2) -> c1-c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001834 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00001835 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
Chris Lattnerc38fb8e2005-10-11 06:07:15 +00001836 // fold (sub x, c) -> (add x, -c)
1837 if (N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001838 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
Dan Gohmanb72127a2008-03-13 22:13:53 +00001839 DAG.getConstant(-N1C->getAPIntValue(), VT));
Evan Cheng88b65bc2010-01-18 21:38:44 +00001840 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1841 if (N0C && N0C->isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001842 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
Benjamin Kramer65bb14d2011-01-29 12:34:05 +00001843 // fold A-(A-B) -> B
1844 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1845 return N1.getOperand(1);
Nate Begeman21158fc2005-09-01 00:19:25 +00001846 // fold (A+B)-A -> B
Chris Lattner6f3b5772005-09-28 22:28:18 +00001847 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
Nate Begemand23739d2005-09-06 04:43:02 +00001848 return N0.getOperand(1);
Nate Begeman21158fc2005-09-01 00:19:25 +00001849 // fold (A+B)-B -> A
Chris Lattner6f3b5772005-09-28 22:28:18 +00001850 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
Scott Michelcf0da6c2009-02-17 22:15:04 +00001851 return N0.getOperand(0);
Eric Christopherd6300d22011-07-14 01:12:15 +00001852 // fold C2-(A+C1) -> (C2-C1)-A
1853 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
Nadav Rotem841c9a82012-09-20 08:53:31 +00001854 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1855 VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00001856 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
Bill Wendlingd1634052012-07-19 00:04:14 +00001857 N1.getOperand(0));
Eric Christopherd6300d22011-07-14 01:12:15 +00001858 }
Dale Johannesenee573fc2008-12-23 23:47:22 +00001859 // fold ((A+(B+or-C))-B) -> A+or-C
Dale Johannesenf51dcef2008-12-16 22:13:49 +00001860 if (N0.getOpcode() == ISD::ADD &&
Dale Johannesenacc84e52008-12-23 23:01:27 +00001861 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1862 N0.getOperand(1).getOpcode() == ISD::ADD) &&
Dale Johannesenf51dcef2008-12-16 22:13:49 +00001863 N0.getOperand(1).getOperand(0) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001864 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001865 N0.getOperand(0), N0.getOperand(1).getOperand(1));
Dale Johannesenacc84e52008-12-23 23:01:27 +00001866 // fold ((A+(C+B))-B) -> A+C
1867 if (N0.getOpcode() == ISD::ADD &&
1868 N0.getOperand(1).getOpcode() == ISD::ADD &&
1869 N0.getOperand(1).getOperand(1) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001870 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001871 N0.getOperand(0), N0.getOperand(1).getOperand(0));
Dale Johannesend2a46852008-12-23 01:59:54 +00001872 // fold ((A-(B-C))-C) -> A-B
1873 if (N0.getOpcode() == ISD::SUB &&
1874 N0.getOperand(1).getOpcode() == ISD::SUB &&
1875 N0.getOperand(1).getOperand(1) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001876 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001877 N0.getOperand(0), N0.getOperand(1).getOperand(0));
Bill Wendling48ff08e2009-01-30 02:42:10 +00001878
Dan Gohman06563a82007-07-03 14:03:57 +00001879 // If either operand of a sub is undef, the result is undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00001880 if (N0.getOpcode() == ISD::UNDEF)
1881 return N0;
1882 if (N1.getOpcode() == ISD::UNDEF)
1883 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00001884
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001885 // If the relocation model supports it, consider symbol offsets.
1886 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001887 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001888 // fold (sub Sym, c) -> Sym-c
1889 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001890 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001891 GA->getOffset() -
1892 (uint64_t)N1C->getSExtValue());
1893 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1894 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1895 if (GA->getGlobal() == GB->getGlobal())
1896 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1897 VT);
1898 }
1899
Jan Veselyaf62cf42014-10-17 14:45:25 +00001900 // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1901 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1902 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1903 if (TN->getVT() == MVT::i1) {
1904 SDLoc DL(N);
1905 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1906 DAG.getConstant(1, VT));
1907 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1908 }
1909 }
1910
Evan Chengf1005572010-04-28 07:10:39 +00001911 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001912}
1913
Craig Topper43a1bd62012-01-07 09:06:39 +00001914SDValue DAGCombiner::visitSUBC(SDNode *N) {
1915 SDValue N0 = N->getOperand(0);
1916 SDValue N1 = N->getOperand(1);
1917 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1918 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1919 EVT VT = N0.getValueType();
1920
1921 // If the flag result is dead, turn this into an SUB.
Craig Topper0515cd42012-01-07 18:31:09 +00001922 if (!N->hasAnyUseOfValue(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001923 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1924 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001925 MVT::Glue));
1926
1927 // fold (subc x, x) -> 0 + no borrow
1928 if (N0 == N1)
1929 return CombineTo(N, DAG.getConstant(0, VT),
Andrew Trickef9de2a2013-05-25 02:42:55 +00001930 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001931 MVT::Glue));
1932
1933 // fold (subc x, 0) -> x + no borrow
1934 if (N1C && N1C->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001935 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001936 MVT::Glue));
1937
1938 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1939 if (N0C && N0C->isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00001940 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1941 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001942 MVT::Glue));
1943
1944 return SDValue();
1945}
1946
1947SDValue DAGCombiner::visitSUBE(SDNode *N) {
1948 SDValue N0 = N->getOperand(0);
1949 SDValue N1 = N->getOperand(1);
1950 SDValue CarryIn = N->getOperand(2);
1951
1952 // fold (sube x, y, false) -> (subc x, y)
1953 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001954 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
Craig Topper43a1bd62012-01-07 09:06:39 +00001955
1956 return SDValue();
1957}
1958
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001959SDValue DAGCombiner::visitMUL(SDNode *N) {
1960 SDValue N0 = N->getOperand(0);
1961 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001962 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001963
Dan Gohman06563a82007-07-03 14:03:57 +00001964 // fold (mul x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00001965 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00001966 return DAG.getConstant(0, VT);
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001967
1968 bool N0IsConst = false;
1969 bool N1IsConst = false;
1970 APInt ConstValue0, ConstValue1;
1971 // fold vector ops
1972 if (VT.isVector()) {
1973 SDValue FoldedVOp = SimplifyVBinOp(N);
1974 if (FoldedVOp.getNode()) return FoldedVOp;
1975
1976 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1977 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1978 } else {
Craig Topperc0196b12014-04-14 00:51:57 +00001979 N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
Jack Carterd4e96152013-10-17 01:34:33 +00001980 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1981 : APInt();
Craig Topperc0196b12014-04-14 00:51:57 +00001982 N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
Jack Carterd4e96152013-10-17 01:34:33 +00001983 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1984 : APInt();
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001985 }
1986
Nate Begeman21158fc2005-09-01 00:19:25 +00001987 // fold (mul c1, c2) -> c1*c2
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001988 if (N0IsConst && N1IsConst)
1989 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1990
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00001991 // canonicalize constant to RHS
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001992 if (N0IsConst && !N1IsConst)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001993 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001994 // fold (mul x, 0) -> 0
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001995 if (N1IsConst && ConstValue1 == 0)
Nate Begemand23739d2005-09-06 04:43:02 +00001996 return N1;
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00001997 // We require a splat of the entire scalar bit width for non-contiguous
1998 // bit patterns.
1999 bool IsFullSplat =
2000 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002001 // fold (mul x, 1) -> x
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00002002 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002003 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00002004 // fold (mul x, -1) -> 0-x
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002005 if (N1IsConst && ConstValue1.isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00002006 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002007 DAG.getConstant(0, VT), N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00002008 // fold (mul x, (1 << c)) -> x << c
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00002009 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002010 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002011 DAG.getConstant(ConstValue1.logBase2(),
Owen Andersonb2c80da2011-02-25 21:41:48 +00002012 getShiftAmountTy(N0.getValueType())));
Chris Lattnera70878d2005-10-30 06:41:49 +00002013 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00002014 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002015 unsigned Log2Val = (-ConstValue1).logBase2();
Scott Michelcf0da6c2009-02-17 22:15:04 +00002016 // FIXME: If the input is something that is easily negated (e.g. a
Chris Lattnera70878d2005-10-30 06:41:49 +00002017 // single-use add), we should put the negate there.
Andrew Trickef9de2a2013-05-25 02:42:55 +00002018 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002019 DAG.getConstant(0, VT),
Andrew Trickef9de2a2013-05-25 02:42:55 +00002020 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002021 DAG.getConstant(Log2Val,
2022 getShiftAmountTy(N0.getValueType()))));
Chris Lattner4249b9a2009-03-09 20:22:18 +00002023 }
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002024
2025 APInt Val;
Chris Lattner324871e2006-03-01 03:44:24 +00002026 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
Stephen Lincfe7f352013-07-08 00:37:03 +00002027 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002028 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2029 isa<ConstantSDNode>(N0.getOperand(1)))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002030 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002031 N1, N0.getOperand(1));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002032 AddToWorklist(C3.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002033 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002034 N0.getOperand(0), C3);
Chris Lattner324871e2006-03-01 03:44:24 +00002035 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002036
Chris Lattner324871e2006-03-01 03:44:24 +00002037 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2038 // use.
2039 {
Craig Topperc0196b12014-04-14 00:51:57 +00002040 SDValue Sh(nullptr,0), Y(nullptr,0);
Chris Lattner324871e2006-03-01 03:44:24 +00002041 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
Stephen Lincfe7f352013-07-08 00:37:03 +00002042 if (N0.getOpcode() == ISD::SHL &&
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002043 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2044 isa<ConstantSDNode>(N0.getOperand(1))) &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00002045 N0.getNode()->hasOneUse()) {
Chris Lattner324871e2006-03-01 03:44:24 +00002046 Sh = N0; Y = N1;
Scott Michelcf0da6c2009-02-17 22:15:04 +00002047 } else if (N1.getOpcode() == ISD::SHL &&
Gabor Greife12264b2008-08-30 19:29:20 +00002048 isa<ConstantSDNode>(N1.getOperand(1)) &&
2049 N1.getNode()->hasOneUse()) {
Chris Lattner324871e2006-03-01 03:44:24 +00002050 Sh = N1; Y = N0;
2051 }
Bill Wendlingb48dcf62009-01-30 02:49:26 +00002052
Gabor Greiff304a7a2008-08-28 21:40:38 +00002053 if (Sh.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002054 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002055 Sh.getOperand(0), Y);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002056 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002057 Mul, Sh.getOperand(1));
Chris Lattner324871e2006-03-01 03:44:24 +00002058 }
2059 }
Bill Wendlingb48dcf62009-01-30 02:49:26 +00002060
Chris Lattnerf29f5202006-03-04 23:33:26 +00002061 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002062 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2063 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2064 isa<ConstantSDNode>(N0.getOperand(1))))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002065 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2066 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002067 N0.getOperand(0), N1),
Andrew Trickef9de2a2013-05-25 02:42:55 +00002068 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002069 N0.getOperand(1), N1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00002070
Nate Begeman22e251a2006-02-03 06:46:56 +00002071 // reassociate mul
Andrew Trickef9de2a2013-05-25 02:42:55 +00002072 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00002073 if (RMUL.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00002074 return RMUL;
Dan Gohmana8665142007-06-25 16:23:39 +00002075
Evan Chengf1005572010-04-28 07:10:39 +00002076 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002077}
2078
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002079SDValue DAGCombiner::visitSDIV(SDNode *N) {
2080 SDValue N0 = N->getOperand(0);
2081 SDValue N1 = N->getOperand(1);
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002082 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2083 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002084 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00002085
Dan Gohmana8665142007-06-25 16:23:39 +00002086 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00002087 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002088 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002089 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00002090 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002091
Nate Begeman21158fc2005-09-01 00:19:25 +00002092 // fold (sdiv c1, c2) -> c1/c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002093 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002094 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
Nate Begeman4dd38312005-10-21 00:02:42 +00002095 // fold (sdiv X, 1) -> X
Eli Friedmane9e356a2011-10-27 02:06:39 +00002096 if (N1C && N1C->getAPIntValue() == 1LL)
Nate Begeman4dd38312005-10-21 00:02:42 +00002097 return N0;
2098 // fold (sdiv X, -1) -> 0-X
2099 if (N1C && N1C->isAllOnesValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00002100 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling5b663e72009-01-30 02:52:17 +00002101 DAG.getConstant(0, VT), N0);
Chris Lattner5bcd0dd82005-10-07 06:10:46 +00002102 // If we know the sign bits of both operands are zero, strength reduce to a
2103 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
Duncan Sands13237ac2008-06-06 12:08:01 +00002104 if (!VT.isVector()) {
Dan Gohman1f372ed2008-02-25 21:11:39 +00002105 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002106 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
Bill Wendling5b663e72009-01-30 02:52:17 +00002107 N0, N1);
Chris Lattner2ee91f42008-01-27 23:32:17 +00002108 }
Benjamin Kramerad016872014-04-26 13:00:53 +00002109
Nate Begeman57b35672006-02-17 07:26:20 +00002110 // fold (sdiv X, pow2) -> simple ops after legalize
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002111 if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2112 (-N1C->getAPIntValue()).isPowerOf2())) {
Nate Begeman4dd38312005-10-21 00:02:42 +00002113 // If dividing by powers of two is cheap, then don't perform the following
2114 // fold.
Sanjay Patel2cdea4c2014-08-21 22:31:48 +00002115 if (TLI.isPow2SDivCheap())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002116 return SDValue();
Bill Wendling5b663e72009-01-30 02:52:17 +00002117
Chad Rosier17020f92014-07-23 14:57:52 +00002118 // Target-specific implementation of sdiv x, pow2.
2119 SDValue Res = BuildSDIVPow2(N);
2120 if (Res.getNode())
2121 return Res;
2122
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002123 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
Bill Wendling5b663e72009-01-30 02:52:17 +00002124
Chris Lattner471627c2006-02-16 08:02:36 +00002125 // Splat the sign bit into the register
Benjamin Kramerad016872014-04-26 13:00:53 +00002126 SDValue SGN =
2127 DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2128 DAG.getConstant(VT.getScalarSizeInBits() - 1,
2129 getShiftAmountTy(N0.getValueType())));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002130 AddToWorklist(SGN.getNode());
Bill Wendling5b663e72009-01-30 02:52:17 +00002131
Chris Lattner471627c2006-02-16 08:02:36 +00002132 // Add (N0 < 0) ? abs2 - 1 : 0;
Benjamin Kramerad016872014-04-26 13:00:53 +00002133 SDValue SRL =
2134 DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2135 DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2136 getShiftAmountTy(SGN.getValueType())));
Andrew Trickef9de2a2013-05-25 02:42:55 +00002137 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002138 AddToWorklist(SRL.getNode());
2139 AddToWorklist(ADD.getNode()); // Divide by pow2
Andrew Trickef9de2a2013-05-25 02:42:55 +00002140 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002141 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
Bill Wendling5b663e72009-01-30 02:52:17 +00002142
Nate Begeman4dd38312005-10-21 00:02:42 +00002143 // If we're dividing by a positive value, we're done. Otherwise, we must
2144 // negate the result.
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002145 if (N1C->getAPIntValue().isNonNegative())
Nate Begeman4dd38312005-10-21 00:02:42 +00002146 return SRA;
Bill Wendling5b663e72009-01-30 02:52:17 +00002147
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002148 AddToWorklist(SRA.getNode());
Benjamin Kramerad016872014-04-26 13:00:53 +00002149 return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
Nate Begeman4dd38312005-10-21 00:02:42 +00002150 }
Bill Wendling5b663e72009-01-30 02:52:17 +00002151
Nate Begemanc6f067a2005-10-20 02:15:44 +00002152 // if integer divide is expensive and we satisfy the requirements, emit an
2153 // alternate sequence.
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002154 if (N1C && !TLI.isIntDivCheap()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002155 SDValue Op = BuildSDIV(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002156 if (Op.getNode()) return Op;
Nate Begemanc6f067a2005-10-20 02:15:44 +00002157 }
Dan Gohmana8665142007-06-25 16:23:39 +00002158
Dan Gohman06563a82007-07-03 14:03:57 +00002159 // undef / X -> 0
2160 if (N0.getOpcode() == ISD::UNDEF)
2161 return DAG.getConstant(0, VT);
2162 // X / undef -> undef
2163 if (N1.getOpcode() == ISD::UNDEF)
2164 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002165
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002166 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002167}
2168
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002169SDValue DAGCombiner::visitUDIV(SDNode *N) {
2170 SDValue N0 = N->getOperand(0);
2171 SDValue N1 = N->getOperand(1);
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002172 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2173 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002174 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002175
Dan Gohmana8665142007-06-25 16:23:39 +00002176 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00002177 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002178 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002179 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00002180 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002181
Nate Begeman21158fc2005-09-01 00:19:25 +00002182 // fold (udiv c1, c2) -> c1/c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002183 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002184 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00002185 // fold (udiv x, (1 << c)) -> x >>u c
Dan Gohmanb72127a2008-03-13 22:13:53 +00002186 if (N1C && N1C->getAPIntValue().isPowerOf2())
Andrew Trickef9de2a2013-05-25 02:42:55 +00002187 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
Dan Gohmanb72127a2008-03-13 22:13:53 +00002188 DAG.getConstant(N1C->getAPIntValue().logBase2(),
Owen Andersonb2c80da2011-02-25 21:41:48 +00002189 getShiftAmountTy(N0.getValueType())));
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002190 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
Nate Begeman25d178b2006-02-05 07:20:23 +00002191 if (N1.getOpcode() == ISD::SHL) {
2192 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
Dan Gohmanb72127a2008-03-13 22:13:53 +00002193 if (SHC->getAPIntValue().isPowerOf2()) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00002194 EVT ADDVT = N1.getOperand(1).getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00002195 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
Bill Wendlingaff3e032009-01-30 02:55:25 +00002196 N1.getOperand(1),
2197 DAG.getConstant(SHC->getAPIntValue()
2198 .logBase2(),
2199 ADDVT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002200 AddToWorklist(Add.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002201 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
Nate Begeman25d178b2006-02-05 07:20:23 +00002202 }
2203 }
2204 }
Nate Begemanc6f067a2005-10-20 02:15:44 +00002205 // fold (udiv x, c) -> alternate
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002206 if (N1C && !TLI.isIntDivCheap()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002207 SDValue Op = BuildUDIV(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002208 if (Op.getNode()) return Op;
Chris Lattner9faa5b72005-10-22 18:50:15 +00002209 }
Dan Gohmana8665142007-06-25 16:23:39 +00002210
Dan Gohman06563a82007-07-03 14:03:57 +00002211 // undef / X -> 0
2212 if (N0.getOpcode() == ISD::UNDEF)
2213 return DAG.getConstant(0, VT);
2214 // X / undef -> undef
2215 if (N1.getOpcode() == ISD::UNDEF)
2216 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002217
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002218 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002219}
2220
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002221SDValue DAGCombiner::visitSREM(SDNode *N) {
2222 SDValue N0 = N->getOperand(0);
2223 SDValue N1 = N->getOperand(1);
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002224 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2225 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002226 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002227
Nate Begeman21158fc2005-09-01 00:19:25 +00002228 // fold (srem c1, c2) -> c1%c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002229 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002230 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
Nate Begeman6828ed92005-10-10 21:26:48 +00002231 // If we know the sign bits of both operands are zero, strength reduce to a
2232 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
Duncan Sands13237ac2008-06-06 12:08:01 +00002233 if (!VT.isVector()) {
Dan Gohman1f372ed2008-02-25 21:11:39 +00002234 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002235 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
Chris Lattnerd0496d02008-01-27 23:21:58 +00002236 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002237
Dan Gohman9a693412007-11-26 23:46:11 +00002238 // If X/C can be simplified by the division-by-constant logic, lower
2239 // X%C to the equivalent of X-X/C*C.
Chris Lattnerd0620d22006-10-12 20:58:32 +00002240 if (N1C && !N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002241 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002242 AddToWorklist(Div.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002243 SDValue OptimizedDiv = combine(Div.getNode());
2244 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002245 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendlingd033af02009-01-30 02:57:00 +00002246 OptimizedDiv, N1);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002247 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002248 AddToWorklist(Mul.getNode());
Dan Gohman9a693412007-11-26 23:46:11 +00002249 return Sub;
2250 }
Chris Lattnerd0620d22006-10-12 20:58:32 +00002251 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002252
Dan Gohman06563a82007-07-03 14:03:57 +00002253 // undef % X -> 0
2254 if (N0.getOpcode() == ISD::UNDEF)
2255 return DAG.getConstant(0, VT);
2256 // X % undef -> undef
2257 if (N1.getOpcode() == ISD::UNDEF)
2258 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002259
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002260 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002261}
2262
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002263SDValue DAGCombiner::visitUREM(SDNode *N) {
2264 SDValue N0 = N->getOperand(0);
2265 SDValue N1 = N->getOperand(1);
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002266 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2267 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002268 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002269
Nate Begeman21158fc2005-09-01 00:19:25 +00002270 // fold (urem c1, c2) -> c1%c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002271 if (N0C && N1C && !N1C->isNullValue())
Bill Wendlingdea91302008-09-24 10:25:02 +00002272 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
Nate Begeman6828ed92005-10-10 21:26:48 +00002273 // fold (urem x, pow2) -> (and x, pow2-1)
Dan Gohmanb72127a2008-03-13 22:13:53 +00002274 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
Andrew Trickef9de2a2013-05-25 02:42:55 +00002275 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
Dan Gohmanb72127a2008-03-13 22:13:53 +00002276 DAG.getConstant(N1C->getAPIntValue()-1,VT));
Nate Begemanc89fdf12006-02-05 07:36:48 +00002277 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2278 if (N1.getOpcode() == ISD::SHL) {
2279 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
Dan Gohmanb72127a2008-03-13 22:13:53 +00002280 if (SHC->getAPIntValue().isPowerOf2()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002281 SDValue Add =
Andrew Trickef9de2a2013-05-25 02:42:55 +00002282 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
Duncan Sands13237ac2008-06-06 12:08:01 +00002283 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
Dan Gohmanb72127a2008-03-13 22:13:53 +00002284 VT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002285 AddToWorklist(Add.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002286 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
Nate Begemanc89fdf12006-02-05 07:36:48 +00002287 }
2288 }
2289 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002290
Dan Gohman9a693412007-11-26 23:46:11 +00002291 // If X/C can be simplified by the division-by-constant logic, lower
2292 // X%C to the equivalent of X-X/C*C.
Chris Lattnerd0620d22006-10-12 20:58:32 +00002293 if (N1C && !N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002294 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002295 AddToWorklist(Div.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002296 SDValue OptimizedDiv = combine(Div.getNode());
2297 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002298 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendlingd033af02009-01-30 02:57:00 +00002299 OptimizedDiv, N1);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002300 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002301 AddToWorklist(Mul.getNode());
Dan Gohman9a693412007-11-26 23:46:11 +00002302 return Sub;
2303 }
Chris Lattnerd0620d22006-10-12 20:58:32 +00002304 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002305
Dan Gohman06563a82007-07-03 14:03:57 +00002306 // undef % X -> 0
2307 if (N0.getOpcode() == ISD::UNDEF)
2308 return DAG.getConstant(0, VT);
2309 // X % undef -> undef
2310 if (N1.getOpcode() == ISD::UNDEF)
2311 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002312
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002313 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002314}
2315
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002316SDValue DAGCombiner::visitMULHS(SDNode *N) {
2317 SDValue N0 = N->getOperand(0);
2318 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002319 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002320 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002321 SDLoc DL(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002322
Nate Begeman21158fc2005-09-01 00:19:25 +00002323 // fold (mulhs x, 0) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002324 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002325 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00002326 // fold (mulhs x, 1) -> (sra x, size(x)-1)
Dan Gohmanb72127a2008-03-13 22:13:53 +00002327 if (N1C && N1C->getAPIntValue() == 1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002328 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
Bill Wendlingfaed0652009-01-30 03:00:18 +00002329 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002330 getShiftAmountTy(N0.getValueType())));
Dan Gohman06563a82007-07-03 14:03:57 +00002331 // fold (mulhs x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002332 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00002333 return DAG.getConstant(0, VT);
Dan Gohmana8665142007-06-25 16:23:39 +00002334
Chris Lattner10bd29f2010-12-13 08:39:01 +00002335 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2336 // plus a shift.
2337 if (VT.isSimple() && !VT.isVector()) {
2338 MVT Simple = VT.getSimpleVT();
2339 unsigned SimpleSize = Simple.getSizeInBits();
2340 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2341 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2342 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2343 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2344 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
Chris Lattnerb86dcee2010-12-15 05:51:39 +00002345 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002346 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
Chris Lattner10bd29f2010-12-13 08:39:01 +00002347 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2348 }
2349 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002350
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002351 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002352}
2353
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002354SDValue DAGCombiner::visitMULHU(SDNode *N) {
2355 SDValue N0 = N->getOperand(0);
2356 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002357 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002358 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002359 SDLoc DL(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002360
Nate Begeman21158fc2005-09-01 00:19:25 +00002361 // fold (mulhu x, 0) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002362 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002363 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00002364 // fold (mulhu x, 1) -> 0
Dan Gohmanb72127a2008-03-13 22:13:53 +00002365 if (N1C && N1C->getAPIntValue() == 1)
Nate Begemand23739d2005-09-06 04:43:02 +00002366 return DAG.getConstant(0, N0.getValueType());
Dan Gohman06563a82007-07-03 14:03:57 +00002367 // fold (mulhu x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002368 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00002369 return DAG.getConstant(0, VT);
Dan Gohmana8665142007-06-25 16:23:39 +00002370
Chris Lattner10bd29f2010-12-13 08:39:01 +00002371 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2372 // plus a shift.
2373 if (VT.isSimple() && !VT.isVector()) {
2374 MVT Simple = VT.getSimpleVT();
2375 unsigned SimpleSize = Simple.getSizeInBits();
2376 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2377 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2378 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2379 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2380 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2381 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002382 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
Chris Lattner10bd29f2010-12-13 08:39:01 +00002383 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2384 }
2385 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002386
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002387 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002388}
2389
Sanjay Patel50cbfc52014-08-28 16:29:51 +00002390/// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2391/// give the opcodes for the two computations that are being performed. Return
2392/// true if a simplification was made.
Scott Michelcf0da6c2009-02-17 22:15:04 +00002393SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002394 unsigned HiOp) {
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002395 // If the high half is not needed, just compute the low half.
Evan Chengece4c682007-11-08 09:25:29 +00002396 bool HiExists = N->hasAnyUseOfValue(1);
2397 if (!HiExists &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002398 (!LegalOperations ||
Owen Andersonfb00d5b2014-01-20 18:41:34 +00002399 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
Craig Toppere1d12942014-08-27 05:25:25 +00002400 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
Chris Lattner31e9edc2008-01-26 01:09:19 +00002401 return CombineTo(N, Res, Res);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002402 }
2403
2404 // If the low half is not needed, just compute the high half.
Evan Chengece4c682007-11-08 09:25:29 +00002405 bool LoExists = N->hasAnyUseOfValue(0);
2406 if (!LoExists &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002407 (!LegalOperations ||
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002408 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
Craig Toppere1d12942014-08-27 05:25:25 +00002409 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
Chris Lattner31e9edc2008-01-26 01:09:19 +00002410 return CombineTo(N, Res, Res);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002411 }
2412
Evan Chengece4c682007-11-08 09:25:29 +00002413 // If both halves are used, return as it is.
2414 if (LoExists && HiExists)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002415 return SDValue();
Evan Chengece4c682007-11-08 09:25:29 +00002416
2417 // If the two computed results can be simplified separately, separate them.
Evan Chengece4c682007-11-08 09:25:29 +00002418 if (LoExists) {
Craig Toppere1d12942014-08-27 05:25:25 +00002419 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002420 AddToWorklist(Lo.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002421 SDValue LoOpt = combine(Lo.getNode());
2422 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002423 (!LegalOperations ||
Duncan Sands8651e9c2008-06-13 19:07:40 +00002424 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
Chris Lattner31e9edc2008-01-26 01:09:19 +00002425 return CombineTo(N, LoOpt, LoOpt);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002426 }
2427
Evan Chengece4c682007-11-08 09:25:29 +00002428 if (HiExists) {
Craig Toppere1d12942014-08-27 05:25:25 +00002429 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002430 AddToWorklist(Hi.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002431 SDValue HiOpt = combine(Hi.getNode());
2432 if (HiOpt.getNode() && HiOpt != Hi &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002433 (!LegalOperations ||
Duncan Sands8651e9c2008-06-13 19:07:40 +00002434 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
Chris Lattner31e9edc2008-01-26 01:09:19 +00002435 return CombineTo(N, HiOpt, HiOpt);
Evan Chengece4c682007-11-08 09:25:29 +00002436 }
Bill Wendling9b3407e2009-01-30 03:08:40 +00002437
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002438 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002439}
2440
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002441SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2442 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002443 if (Res.getNode()) return Res;
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002444
Chris Lattner15090e12010-12-15 06:04:19 +00002445 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002446 SDLoc DL(N);
Chris Lattner15090e12010-12-15 06:04:19 +00002447
2448 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2449 // plus a shift.
2450 if (VT.isSimple() && !VT.isVector()) {
2451 MVT Simple = VT.getSimpleVT();
2452 unsigned SimpleSize = Simple.getSizeInBits();
2453 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2454 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2455 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2456 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2457 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2458 // Compute the high part as N1.
2459 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002460 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
Chris Lattner15090e12010-12-15 06:04:19 +00002461 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2462 // Compute the low part as N0.
2463 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2464 return CombineTo(N, Lo, Hi);
2465 }
2466 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002467
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002468 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002469}
2470
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002471SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2472 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002473 if (Res.getNode()) return Res;
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002474
Chris Lattner15090e12010-12-15 06:04:19 +00002475 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002476 SDLoc DL(N);
Owen Andersonb2c80da2011-02-25 21:41:48 +00002477
Chris Lattner15090e12010-12-15 06:04:19 +00002478 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2479 // plus a shift.
2480 if (VT.isSimple() && !VT.isVector()) {
2481 MVT Simple = VT.getSimpleVT();
2482 unsigned SimpleSize = Simple.getSizeInBits();
2483 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2484 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2485 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2486 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2487 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2488 // Compute the high part as N1.
2489 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002490 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
Chris Lattner15090e12010-12-15 06:04:19 +00002491 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2492 // Compute the low part as N0.
2493 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2494 return CombineTo(N, Lo, Hi);
2495 }
2496 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002497
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002498 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002499}
2500
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002501SDValue DAGCombiner::visitSMULO(SDNode *N) {
2502 // (smulo x, 2) -> (saddo x, x)
2503 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2504 if (C2->getAPIntValue() == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002505 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002506 N->getOperand(0), N->getOperand(0));
2507
2508 return SDValue();
2509}
2510
2511SDValue DAGCombiner::visitUMULO(SDNode *N) {
2512 // (umulo x, 2) -> (uaddo x, x)
2513 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2514 if (C2->getAPIntValue() == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002515 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002516 N->getOperand(0), N->getOperand(0));
2517
2518 return SDValue();
2519}
2520
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002521SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2522 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002523 if (Res.getNode()) return Res;
Scott Michelcf0da6c2009-02-17 22:15:04 +00002524
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002525 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002526}
2527
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002528SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2529 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002530 if (Res.getNode()) return Res;
Scott Michelcf0da6c2009-02-17 22:15:04 +00002531
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002532 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002533}
2534
Sanjay Patel50cbfc52014-08-28 16:29:51 +00002535/// If this is a binary operator with two operands of the same opcode, try to
2536/// simplify it.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002537SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2538 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002539 EVT VT = N0.getValueType();
Chris Lattner8d6fc202006-05-05 05:51:50 +00002540 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
Scott Michelcf0da6c2009-02-17 22:15:04 +00002541
Dan Gohmandd5286d2010-01-14 03:08:49 +00002542 // Bail early if none of these transforms apply.
2543 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2544
Chris Lattner002ee912006-05-05 06:31:05 +00002545 // For each of OP in AND/OR/XOR:
2546 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2547 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2548 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00002549 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
Dan Gohman600f62b2010-06-24 14:30:44 +00002550 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
Nate Begeman9655f842009-12-03 07:11:29 +00002551 //
2552 // do not sink logical op inside of a vector extend, since it may combine
2553 // into a vsetcc.
Evan Cheng166a4e62010-01-06 19:38:29 +00002554 EVT Op0VT = N0.getOperand(0).getValueType();
2555 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
Dan Gohmanad3e5492009-04-08 00:15:30 +00002556 N0.getOpcode() == ISD::SIGN_EXTEND ||
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00002557 N0.getOpcode() == ISD::BSWAP ||
Evan Chengf1bd5fc2010-04-17 06:13:15 +00002558 // Avoid infinite looping with PromoteIntBinOp.
2559 (N0.getOpcode() == ISD::ANY_EXTEND &&
2560 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
Dan Gohman600f62b2010-06-24 14:30:44 +00002561 (N0.getOpcode() == ISD::TRUNCATE &&
2562 (!TLI.isZExtFree(VT, Op0VT) ||
2563 !TLI.isTruncateFree(Op0VT, VT)) &&
2564 TLI.isTypeLegal(Op0VT))) &&
Nate Begeman9655f842009-12-03 07:11:29 +00002565 !VT.isVector() &&
Evan Cheng166a4e62010-01-06 19:38:29 +00002566 Op0VT == N1.getOperand(0).getValueType() &&
2567 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002568 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
Bill Wendling781db7a2009-01-30 19:25:47 +00002569 N0.getOperand(0).getValueType(),
2570 N0.getOperand(0), N1.getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002571 AddToWorklist(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002572 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
Chris Lattner8d6fc202006-05-05 05:51:50 +00002573 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002574
Chris Lattner5ac42932006-05-05 06:10:43 +00002575 // For each of OP in SHL/SRL/SRA/AND...
2576 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2577 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2578 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
Chris Lattner8d6fc202006-05-05 05:51:50 +00002579 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
Chris Lattner5ac42932006-05-05 06:10:43 +00002580 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
Chris Lattner8d6fc202006-05-05 05:51:50 +00002581 N0.getOperand(1) == N1.getOperand(1)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002582 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
Bill Wendling781db7a2009-01-30 19:25:47 +00002583 N0.getOperand(0).getValueType(),
2584 N0.getOperand(0), N1.getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002585 AddToWorklist(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002586 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Bill Wendling781db7a2009-01-30 19:25:47 +00002587 ORNode, N0.getOperand(1));
Chris Lattner8d6fc202006-05-05 05:51:50 +00002588 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002589
Nadav Rotemb0783502012-04-01 19:31:22 +00002590 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2591 // Only perform this optimization after type legalization and before
2592 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2593 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2594 // we don't want to undo this promotion.
2595 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2596 // on scalars.
Nadav Rotem841c9a82012-09-20 08:53:31 +00002597 if ((N0.getOpcode() == ISD::BITCAST ||
2598 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2599 Level == AfterLegalizeTypes) {
Nadav Rotemb0783502012-04-01 19:31:22 +00002600 SDValue In0 = N0.getOperand(0);
2601 SDValue In1 = N1.getOperand(0);
2602 EVT In0Ty = In0.getValueType();
2603 EVT In1Ty = In1.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00002604 SDLoc DL(N);
Nadav Rotem841c9a82012-09-20 08:53:31 +00002605 // If both incoming values are integers, and the original types are the
2606 // same.
Nadav Rotemb0783502012-04-01 19:31:22 +00002607 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
Nadav Rotem841c9a82012-09-20 08:53:31 +00002608 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2609 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002610 AddToWorklist(Op.getNode());
Nadav Rotemb0783502012-04-01 19:31:22 +00002611 return BC;
2612 }
2613 }
2614
2615 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2616 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2617 // If both shuffles use the same mask, and both shuffle within a single
2618 // vector, then it is worthwhile to move the swizzle after the operation.
2619 // The type-legalizer generates this pattern when loading illegal
2620 // vector types from memory. In many cases this allows additional shuffle
2621 // optimizations.
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002622 // There are other cases where moving the shuffle after the xor/and/or
2623 // is profitable even if shuffles don't perform a swizzle.
2624 // If both shuffles use the same mask, and both shuffles have the same first
2625 // or second operand, then it might still be profitable to move the shuffle
2626 // after the xor/and/or operation.
2627 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
Nadav Rotemb0783502012-04-01 19:31:22 +00002628 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2629 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
Craig Topper9c3da312012-04-09 07:19:09 +00002630
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002631 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
Craig Topper9c3da312012-04-09 07:19:09 +00002632 "Inputs to shuffles are not the same type");
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00002633
Nadav Rotemb0783502012-04-01 19:31:22 +00002634 // Check that both shuffles use the same mask. The masks are known to be of
2635 // the same length because the result vector type is the same.
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002636 // Check also that shuffles have only one use to avoid introducing extra
2637 // instructions.
2638 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2639 SVN0->getMask().equals(SVN1->getMask())) {
2640 SDValue ShOp = N0->getOperand(1);
Nadav Rotemb0783502012-04-01 19:31:22 +00002641
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002642 // Don't try to fold this node if it requires introducing a
2643 // build vector of all zeros that might be illegal at this stage.
2644 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2645 if (!LegalTypes)
2646 ShOp = DAG.getConstant(0, VT);
2647 else
2648 ShOp = SDValue();
2649 }
2650
2651 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2652 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2653 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2654 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2655 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2656 N0->getOperand(0), N1->getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002657 AddToWorklist(NewNode.getNode());
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002658 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2659 &SVN0->getMask()[0]);
2660 }
2661
2662 // Don't try to fold this node if it requires introducing a
2663 // build vector of all zeros that might be illegal at this stage.
2664 ShOp = N0->getOperand(0);
2665 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2666 if (!LegalTypes)
2667 ShOp = DAG.getConstant(0, VT);
2668 else
2669 ShOp = SDValue();
2670 }
2671
2672 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2673 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2674 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2675 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2676 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2677 N0->getOperand(1), N1->getOperand(1));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002678 AddToWorklist(NewNode.getNode());
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002679 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2680 &SVN0->getMask()[0]);
2681 }
Nadav Rotemb0783502012-04-01 19:31:22 +00002682 }
2683 }
Craig Topper9c3da312012-04-09 07:19:09 +00002684
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002685 return SDValue();
Chris Lattner8d6fc202006-05-05 05:51:50 +00002686}
2687
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002688SDValue DAGCombiner::visitAND(SDNode *N) {
2689 SDValue N0 = N->getOperand(0);
2690 SDValue N1 = N->getOperand(1);
2691 SDValue LL, LR, RL, RR, CC0, CC1;
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002692 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2693 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002694 EVT VT = N1.getValueType();
Dan Gohmane14c4082010-03-04 00:23:16 +00002695 unsigned BitWidth = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00002696
Dan Gohmana8665142007-06-25 16:23:39 +00002697 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00002698 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002699 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002700 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00002701
2702 // fold (and x, 0) -> 0, vector edition
2703 if (ISD::isBuildVectorAllZeros(N0.getNode()))
David Xuf7aff682014-09-11 05:10:28 +00002704 // do not return N0, because undef node may exist in N0
2705 return DAG.getConstant(
2706 APInt::getNullValue(
2707 N0.getValueType().getScalarType().getSizeInBits()),
2708 N0.getValueType());
Craig Toppera183ddb2012-12-08 22:49:19 +00002709 if (ISD::isBuildVectorAllZeros(N1.getNode()))
David Xuf7aff682014-09-11 05:10:28 +00002710 // do not return N1, because undef node may exist in N1
2711 return DAG.getConstant(
2712 APInt::getNullValue(
2713 N1.getValueType().getScalarType().getSizeInBits()),
2714 N1.getValueType());
Craig Toppera183ddb2012-12-08 22:49:19 +00002715
2716 // fold (and x, -1) -> x, vector edition
2717 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2718 return N1;
2719 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2720 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00002721 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002722
Dan Gohman06563a82007-07-03 14:03:57 +00002723 // fold (and x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002724 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00002725 return DAG.getConstant(0, VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00002726 // fold (and c1, c2) -> c1&c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002727 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00002728 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00002729 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00002730 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002731 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00002732 // fold (and x, -1) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002733 if (N1C && N1C->isAllOnesValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002734 return N0;
2735 // if (and x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002736 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1f372ed2008-02-25 21:11:39 +00002737 APInt::getAllOnesValue(BitWidth)))
Nate Begemand23739d2005-09-06 04:43:02 +00002738 return DAG.getConstant(0, VT);
Nate Begeman22e251a2006-02-03 06:46:56 +00002739 // reassociate and
Andrew Trickef9de2a2013-05-25 02:42:55 +00002740 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00002741 if (RAND.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00002742 return RAND;
Bill Wendlingaf13d822010-03-03 00:35:56 +00002743 // fold (and (or x, C), D) -> D if (C & D) == D
Nate Begemanee065282005-11-02 18:42:59 +00002744 if (N1C && N0.getOpcode() == ISD::OR)
Nate Begeman21158fc2005-09-01 00:19:25 +00002745 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
Dan Gohmanb72127a2008-03-13 22:13:53 +00002746 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002747 return N1;
Chris Lattner49beaf42006-02-02 07:17:31 +00002748 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2749 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002750 SDValue N0Op0 = N0.getOperand(0);
Dan Gohman1f372ed2008-02-25 21:11:39 +00002751 APInt Mask = ~N1C->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00002752 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
Dan Gohman1f372ed2008-02-25 21:11:39 +00002753 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002754 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
Bill Wendling86171912009-01-30 20:43:18 +00002755 N0.getValueType(), N0Op0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002756
Chris Lattner0db2f2c2006-03-01 21:47:21 +00002757 // Replace uses of the AND with uses of the Zero extend node.
2758 CombineTo(N, Zext);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002759
Chris Lattner49beaf42006-02-02 07:17:31 +00002760 // We actually want to replace all uses of the any_extend with the
2761 // zero_extend, to avoid duplicating things. This will later cause this
2762 // AND to be folded.
Gabor Greiff304a7a2008-08-28 21:40:38 +00002763 CombineTo(N0.getNode(), Zext);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002764 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattner49beaf42006-02-02 07:17:31 +00002765 }
2766 }
Stephen Lincfe7f352013-07-08 00:37:03 +00002767 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
James Molloy862fe492012-02-20 12:02:38 +00002768 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2769 // already be zero by virtue of the width of the base type of the load.
2770 //
2771 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2772 // more cases.
2773 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2774 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2775 N0.getOpcode() == ISD::LOAD) {
2776 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2777 N0 : N0.getOperand(0) );
2778
2779 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2780 // This can be a pure constant or a vector splat, in which case we treat the
2781 // vector as a scalar and use the splat value.
2782 APInt Constant = APInt::getNullValue(1);
2783 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2784 Constant = C->getAPIntValue();
2785 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2786 APInt SplatValue, SplatUndef;
2787 unsigned SplatBitSize;
2788 bool HasAnyUndefs;
2789 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2790 SplatBitSize, HasAnyUndefs);
2791 if (IsSplat) {
2792 // Undef bits can contribute to a possible optimisation if set, so
2793 // set them.
2794 SplatValue |= SplatUndef;
2795
2796 // The splat value may be something like "0x00FFFFFF", which means 0 for
2797 // the first vector value and FF for the rest, repeating. We need a mask
2798 // that will apply equally to all members of the vector, so AND all the
2799 // lanes of the constant together.
2800 EVT VT = Vector->getValueType(0);
2801 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
Silviu Baranga3f40d872012-09-05 08:57:21 +00002802
2803 // If the splat value has been compressed to a bitlength lower
2804 // than the size of the vector lane, we need to re-expand it to
2805 // the lane size.
2806 if (BitWidth > SplatBitSize)
2807 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2808 SplatBitSize < BitWidth;
2809 SplatBitSize = SplatBitSize * 2)
2810 SplatValue |= SplatValue.shl(SplatBitSize);
2811
James Molloy862fe492012-02-20 12:02:38 +00002812 Constant = APInt::getAllOnesValue(BitWidth);
Silviu Baranga3f40d872012-09-05 08:57:21 +00002813 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
James Molloy862fe492012-02-20 12:02:38 +00002814 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2815 }
2816 }
2817
2818 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2819 // actually legal and isn't going to get expanded, else this is a false
2820 // optimisation.
2821 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00002822 Load->getValueType(0),
James Molloy862fe492012-02-20 12:02:38 +00002823 Load->getMemoryVT());
2824
2825 // Resize the constant to the same size as the original memory access before
2826 // extension. If it is still the AllOnesValue then this AND is completely
2827 // unneeded.
2828 Constant =
2829 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2830
2831 bool B;
2832 switch (Load->getExtensionType()) {
2833 default: B = false; break;
2834 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2835 case ISD::ZEXTLOAD:
2836 case ISD::NON_EXTLOAD: B = true; break;
2837 }
2838
2839 if (B && Constant.isAllOnesValue()) {
2840 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2841 // preserve semantics once we get rid of the AND.
2842 SDValue NewLoad(Load, 0);
2843 if (Load->getExtensionType() == ISD::EXTLOAD) {
2844 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
Andrew Trickef9de2a2013-05-25 02:42:55 +00002845 Load->getValueType(0), SDLoc(Load),
James Molloy862fe492012-02-20 12:02:38 +00002846 Load->getChain(), Load->getBasePtr(),
2847 Load->getOffset(), Load->getMemoryVT(),
2848 Load->getMemOperand());
2849 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
Hal Finkel8a311382012-06-20 15:42:48 +00002850 if (Load->getNumValues() == 3) {
2851 // PRE/POST_INC loads have 3 values.
2852 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2853 NewLoad.getValue(2) };
2854 CombineTo(Load, To, 3, true);
2855 } else {
2856 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2857 }
James Molloy862fe492012-02-20 12:02:38 +00002858 }
2859
2860 // Fold the AND away, taking care not to fold to the old load node if we
2861 // replaced it.
2862 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2863
2864 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2865 }
2866 }
Nate Begeman049b7482005-09-09 19:49:52 +00002867 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2868 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2869 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2870 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
Scott Michelcf0da6c2009-02-17 22:15:04 +00002871
Tom Stellard7783b0a2014-06-12 16:04:47 +00002872 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
Duncan Sands13237ac2008-06-06 12:08:01 +00002873 LL.getValueType().isInteger()) {
Bill Wendling86171912009-01-30 20:43:18 +00002874 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
Tom Stellard7783b0a2014-06-12 16:04:47 +00002875 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002876 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
Bill Wendling86171912009-01-30 20:43:18 +00002877 LR.getValueType(), LL, RL);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002878 AddToWorklist(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002879 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00002880 }
Bill Wendling86171912009-01-30 20:43:18 +00002881 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
Tom Stellard7783b0a2014-06-12 16:04:47 +00002882 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002883 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
Bill Wendling86171912009-01-30 20:43:18 +00002884 LR.getValueType(), LL, RL);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002885 AddToWorklist(ANDNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002886 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00002887 }
Bill Wendling86171912009-01-30 20:43:18 +00002888 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
Tom Stellard7783b0a2014-06-12 16:04:47 +00002889 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002890 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
Bill Wendling86171912009-01-30 20:43:18 +00002891 LR.getValueType(), LL, RL);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002892 AddToWorklist(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002893 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00002894 }
2895 }
Jim Grosbach327ccc72013-08-13 21:30:58 +00002896 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2897 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2898 Op0 == Op1 && LL.getValueType().isInteger() &&
2899 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2900 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2901 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2902 cast<ConstantSDNode>(RR)->isNullValue()))) {
2903 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2904 LL, DAG.getConstant(1, LL.getValueType()));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002905 AddToWorklist(ADDNode.getNode());
Jim Grosbach327ccc72013-08-13 21:30:58 +00002906 return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2907 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2908 }
Nate Begeman049b7482005-09-09 19:49:52 +00002909 // canonicalize equivalent to ll == rl
2910 if (LL == RR && LR == RL) {
2911 Op1 = ISD::getSetCCSwappedOperands(Op1);
2912 std::swap(RL, RR);
2913 }
2914 if (LL == RL && LR == RR) {
Duncan Sands13237ac2008-06-06 12:08:01 +00002915 bool isInteger = LL.getValueType().isInteger();
Nate Begeman049b7482005-09-09 19:49:52 +00002916 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
Chris Lattner5fa10402008-10-28 07:11:07 +00002917 if (Result != ISD::SETCC_INVALID &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00002918 (!LegalOperations ||
Owen Andersoncc068992013-02-14 09:07:33 +00002919 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2920 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault758659232013-05-18 00:21:46 +00002921 getSetCCResultType(N0.getSimpleValueType())))))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002922 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
Bill Wendling86171912009-01-30 20:43:18 +00002923 LL, LR, Result);
Nate Begeman049b7482005-09-09 19:49:52 +00002924 }
2925 }
Chris Lattner8d6fc202006-05-05 05:51:50 +00002926
Bill Wendling86171912009-01-30 20:43:18 +00002927 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
Chris Lattner8d6fc202006-05-05 05:51:50 +00002928 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002929 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002930 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00002931 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002932
Nate Begemandc7bba92006-02-03 22:24:05 +00002933 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2934 // fold (and (sra)) -> (and (srl)) when possible.
Duncan Sands13237ac2008-06-06 12:08:01 +00002935 if (!VT.isVector() &&
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002936 SimplifyDemandedBits(SDValue(N, 0)))
2937 return SDValue(N, 0);
Evan Cheng166a4e62010-01-06 19:38:29 +00002938
Nate Begeman02b23c62005-10-13 03:11:28 +00002939 // fold (zext_inreg (extload x)) -> (zextload x)
Gabor Greiff304a7a2008-08-28 21:40:38 +00002940 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00002941 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00002942 EVT MemVT = LN0->getMemoryVT();
Nate Begeman8e022b32005-10-13 18:34:58 +00002943 // If we zero all the possible extended bits, then we can turn this into
2944 // a zextload if we are running before legalize or the operation is legal.
Dan Gohmane14c4082010-03-04 00:23:16 +00002945 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
Dan Gohman1f372ed2008-02-25 21:11:39 +00002946 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
Dan Gohmane14c4082010-03-04 00:23:16 +00002947 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002948 ((!LegalOperations && !LN0->isVolatile()) ||
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00002949 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002950 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
Bill Wendling86171912009-01-30 20:43:18 +00002951 LN0->getChain(), LN0->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002952 MemVT, LN0->getMemOperand());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002953 AddToWorklist(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002954 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002955 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00002956 }
2957 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002958 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
Gabor Greiff304a7a2008-08-28 21:40:38 +00002959 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Cheng8a1d09d2007-03-07 08:07:03 +00002960 N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00002961 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00002962 EVT MemVT = LN0->getMemoryVT();
Nate Begeman8e022b32005-10-13 18:34:58 +00002963 // If we zero all the possible extended bits, then we can turn this into
2964 // a zextload if we are running before legalize or the operation is legal.
Dan Gohmane14c4082010-03-04 00:23:16 +00002965 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
Dan Gohman1f372ed2008-02-25 21:11:39 +00002966 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
Dan Gohmane14c4082010-03-04 00:23:16 +00002967 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002968 ((!LegalOperations && !LN0->isVolatile()) ||
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00002969 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002970 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00002971 LN0->getChain(), LN0->getBasePtr(),
2972 MemVT, LN0->getMemOperand());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002973 AddToWorklist(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002974 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002975 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00002976 }
2977 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002978
Chris Lattnerf0032b32006-02-28 06:49:37 +00002979 // fold (and (load x), 255) -> (zextload x, i8)
2980 // fold (and (extload x, i16), 255) -> (zextload x, i8)
Evan Cheng166a4e62010-01-06 19:38:29 +00002981 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2982 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2983 (N0.getOpcode() == ISD::ANY_EXTEND &&
2984 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2985 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2986 LoadSDNode *LN0 = HasAnyExt
2987 ? cast<LoadSDNode>(N0.getOperand(0))
2988 : cast<LoadSDNode>(N0);
Evan Chenge71fe34d2006-10-09 20:57:25 +00002989 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
Tim Northover68239002013-07-02 09:58:53 +00002990 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
Duncan Sands93b66092008-06-09 11:32:28 +00002991 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
Evan Cheng166a4e62010-01-06 19:38:29 +00002992 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2993 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2994 EVT LoadedVT = LN0->getMemoryVT();
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00002995 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
Duncan Sands93b66092008-06-09 11:32:28 +00002996
Evan Cheng166a4e62010-01-06 19:38:29 +00002997 if (ExtVT == LoadedVT &&
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00002998 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
2999 ExtVT))) {
Wesley Peck527da1b2010-11-23 03:31:01 +00003000
3001 SDValue NewLoad =
Andrew Trickef9de2a2013-05-25 02:42:55 +00003002 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00003003 LN0->getChain(), LN0->getBasePtr(), ExtVT,
3004 LN0->getMemOperand());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003005 AddToWorklist(N);
Chris Lattner88de3842010-01-07 21:53:27 +00003006 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3007 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3008 }
Wesley Peck527da1b2010-11-23 03:31:01 +00003009
Chris Lattner88de3842010-01-07 21:53:27 +00003010 // Do not change the width of a volatile load.
3011 // Do not generate loads of non-round integer types since these can
3012 // be expensive (and would be wrong if the type is not byte sized).
3013 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00003014 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3015 ExtVT))) {
Chris Lattner88de3842010-01-07 21:53:27 +00003016 EVT PtrType = LN0->getOperand(1).getValueType();
Bill Wendling86171912009-01-30 20:43:18 +00003017
Chris Lattner88de3842010-01-07 21:53:27 +00003018 unsigned Alignment = LN0->getAlignment();
3019 SDValue NewPtr = LN0->getBasePtr();
3020
3021 // For big endian targets, we need to add an offset to the pointer
3022 // to load the correct bytes. For little endian systems, we merely
3023 // need to read fewer bytes from the same pointer.
3024 if (TLI.isBigEndian()) {
Evan Cheng166a4e62010-01-06 19:38:29 +00003025 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3026 unsigned EVTStoreBytes = ExtVT.getStoreSize();
3027 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
Andrew Trickef9de2a2013-05-25 02:42:55 +00003028 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
Chris Lattner88de3842010-01-07 21:53:27 +00003029 NewPtr, DAG.getConstant(PtrOff, PtrType));
3030 Alignment = MinAlign(Alignment, PtrOff);
Evan Cheng166a4e62010-01-06 19:38:29 +00003031 }
Chris Lattner88de3842010-01-07 21:53:27 +00003032
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003033 AddToWorklist(NewPtr.getNode());
Wesley Peck527da1b2010-11-23 03:31:01 +00003034
Chris Lattner88de3842010-01-07 21:53:27 +00003035 SDValue Load =
Andrew Trickef9de2a2013-05-25 02:42:55 +00003036 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
Chris Lattner88de3842010-01-07 21:53:27 +00003037 LN0->getChain(), NewPtr,
Chris Lattner3d178ed2010-09-21 17:04:51 +00003038 LN0->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +00003039 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
Louis Gerbarg67474e32014-07-31 21:45:05 +00003040 LN0->isInvariant(), Alignment, LN0->getAAInfo());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003041 AddToWorklist(N);
Chris Lattner88de3842010-01-07 21:53:27 +00003042 CombineTo(LN0, Load, Load.getValue(1));
3043 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Duncan Sands1826ded2007-10-28 12:59:45 +00003044 }
Evan Chenge71fe34d2006-10-09 20:57:25 +00003045 }
Chris Lattnerbdbc4472006-02-28 06:35:35 +00003046 }
3047 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003048
Evan Chenge6a3b032012-07-17 18:54:11 +00003049 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
3050 VT.getSizeInBits() <= 64) {
3051 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3052 APInt ADDC = ADDI->getAPIntValue();
3053 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3054 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
3055 // immediate for an add, but it is legal if its top c2 bits are set,
3056 // transform the ADD so the immediate doesn't need to be materialized
3057 // in a register.
3058 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
3059 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3060 SRLI->getZExtValue());
3061 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
3062 ADDC |= Mask;
3063 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3064 SDValue NewAdd =
Andrew Trickef9de2a2013-05-25 02:42:55 +00003065 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
Evan Chenge6a3b032012-07-17 18:54:11 +00003066 N0.getOperand(0), DAG.getConstant(ADDC, VT));
3067 CombineTo(N0.getNode(), NewAdd);
3068 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3069 }
3070 }
3071 }
3072 }
3073 }
3074 }
Evan Chenge6a3b032012-07-17 18:54:11 +00003075
Tim Northover819bfb52013-08-27 13:46:45 +00003076 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3077 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3078 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3079 N0.getOperand(1), false);
3080 if (BSwap.getNode())
3081 return BSwap;
3082 }
3083
Evan Chengf1005572010-04-28 07:10:39 +00003084 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00003085}
3086
Sanjay Patel50cbfc52014-08-28 16:29:51 +00003087/// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
Evan Cheng4c0bd962011-06-21 06:01:08 +00003088SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3089 bool DemandHighBits) {
3090 if (!LegalOperations)
3091 return SDValue();
3092
3093 EVT VT = N->getValueType(0);
3094 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3095 return SDValue();
3096 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3097 return SDValue();
3098
3099 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3100 bool LookPassAnd0 = false;
3101 bool LookPassAnd1 = false;
3102 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3103 std::swap(N0, N1);
3104 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3105 std::swap(N0, N1);
3106 if (N0.getOpcode() == ISD::AND) {
3107 if (!N0.getNode()->hasOneUse())
3108 return SDValue();
3109 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3110 if (!N01C || N01C->getZExtValue() != 0xFF00)
3111 return SDValue();
3112 N0 = N0.getOperand(0);
3113 LookPassAnd0 = true;
3114 }
3115
3116 if (N1.getOpcode() == ISD::AND) {
3117 if (!N1.getNode()->hasOneUse())
3118 return SDValue();
3119 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3120 if (!N11C || N11C->getZExtValue() != 0xFF)
3121 return SDValue();
3122 N1 = N1.getOperand(0);
3123 LookPassAnd1 = true;
3124 }
3125
3126 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3127 std::swap(N0, N1);
3128 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3129 return SDValue();
3130 if (!N0.getNode()->hasOneUse() ||
3131 !N1.getNode()->hasOneUse())
3132 return SDValue();
3133
3134 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3135 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3136 if (!N01C || !N11C)
3137 return SDValue();
3138 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3139 return SDValue();
3140
3141 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3142 SDValue N00 = N0->getOperand(0);
3143 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3144 if (!N00.getNode()->hasOneUse())
3145 return SDValue();
3146 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3147 if (!N001C || N001C->getZExtValue() != 0xFF)
3148 return SDValue();
3149 N00 = N00.getOperand(0);
3150 LookPassAnd0 = true;
3151 }
3152
3153 SDValue N10 = N1->getOperand(0);
3154 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3155 if (!N10.getNode()->hasOneUse())
3156 return SDValue();
3157 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3158 if (!N101C || N101C->getZExtValue() != 0xFF00)
3159 return SDValue();
3160 N10 = N10.getOperand(0);
3161 LookPassAnd1 = true;
3162 }
3163
3164 if (N00 != N10)
3165 return SDValue();
3166
Tim Northover819bfb52013-08-27 13:46:45 +00003167 // Make sure everything beyond the low halfword gets set to zero since the SRL
3168 // 16 will clear the top bits.
Evan Cheng4c0bd962011-06-21 06:01:08 +00003169 unsigned OpSizeInBits = VT.getSizeInBits();
Tim Northover819bfb52013-08-27 13:46:45 +00003170 if (DemandHighBits && OpSizeInBits > 16) {
3171 // If the left-shift isn't masked out then the only way this is a bswap is
3172 // if all bits beyond the low 8 are 0. In that case the entire pattern
3173 // reduces to a left shift anyway: leave it for other parts of the combiner.
3174 if (!LookPassAnd0)
3175 return SDValue();
3176
3177 // However, if the right shift isn't masked out then it might be because
3178 // it's not needed. See if we can spot that too.
3179 if (!LookPassAnd1 &&
3180 !DAG.MaskedValueIsZero(
3181 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3182 return SDValue();
3183 }
Eric Christopherd6300d22011-07-14 01:12:15 +00003184
Andrew Trickef9de2a2013-05-25 02:42:55 +00003185 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
Evan Cheng4c0bd962011-06-21 06:01:08 +00003186 if (OpSizeInBits > 16)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003187 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
Evan Cheng4c0bd962011-06-21 06:01:08 +00003188 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3189 return Res;
3190}
3191
Sanjay Patel50cbfc52014-08-28 16:29:51 +00003192/// Return true if the specified node is an element that makes up a 32-bit
3193/// packed halfword byteswap.
3194/// ((x & 0x000000ff) << 8) |
3195/// ((x & 0x0000ff00) >> 8) |
3196/// ((x & 0x00ff0000) << 8) |
3197/// ((x & 0xff000000) >> 8)
Benjamin Kramer7ad22402014-10-22 19:55:26 +00003198static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
Evan Cheng4c0bd962011-06-21 06:01:08 +00003199 if (!N.getNode()->hasOneUse())
3200 return false;
3201
3202 unsigned Opc = N.getOpcode();
3203 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3204 return false;
3205
3206 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3207 if (!N1C)
3208 return false;
3209
3210 unsigned Num;
3211 switch (N1C->getZExtValue()) {
3212 default:
3213 return false;
3214 case 0xFF: Num = 0; break;
3215 case 0xFF00: Num = 1; break;
3216 case 0xFF0000: Num = 2; break;
3217 case 0xFF000000: Num = 3; break;
3218 }
3219
3220 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3221 SDValue N0 = N.getOperand(0);
3222 if (Opc == ISD::AND) {
3223 if (Num == 0 || Num == 2) {
3224 // (x >> 8) & 0xff
3225 // (x >> 8) & 0xff0000
3226 if (N0.getOpcode() != ISD::SRL)
3227 return false;
3228 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3229 if (!C || C->getZExtValue() != 8)
3230 return false;
3231 } else {
3232 // (x << 8) & 0xff00
3233 // (x << 8) & 0xff000000
3234 if (N0.getOpcode() != ISD::SHL)
3235 return false;
3236 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3237 if (!C || C->getZExtValue() != 8)
3238 return false;
3239 }
3240 } else if (Opc == ISD::SHL) {
3241 // (x & 0xff) << 8
3242 // (x & 0xff0000) << 8
3243 if (Num != 0 && Num != 2)
3244 return false;
3245 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3246 if (!C || C->getZExtValue() != 8)
3247 return false;
3248 } else { // Opc == ISD::SRL
3249 // (x & 0xff00) >> 8
3250 // (x & 0xff000000) >> 8
3251 if (Num != 1 && Num != 3)
3252 return false;
3253 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3254 if (!C || C->getZExtValue() != 8)
3255 return false;
3256 }
3257
3258 if (Parts[Num])
3259 return false;
3260
3261 Parts[Num] = N0.getOperand(0).getNode();
3262 return true;
3263}
3264
Sanjay Patel50cbfc52014-08-28 16:29:51 +00003265/// Match a 32-bit packed halfword bswap. That is
3266/// ((x & 0x000000ff) << 8) |
3267/// ((x & 0x0000ff00) >> 8) |
3268/// ((x & 0x00ff0000) << 8) |
3269/// ((x & 0xff000000) >> 8)
Evan Cheng4c0bd962011-06-21 06:01:08 +00003270/// => (rotl (bswap x), 16)
3271SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3272 if (!LegalOperations)
3273 return SDValue();
3274
3275 EVT VT = N->getValueType(0);
3276 if (VT != MVT::i32)
3277 return SDValue();
3278 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3279 return SDValue();
3280
Evan Cheng4c0bd962011-06-21 06:01:08 +00003281 // Look for either
3282 // (or (or (and), (and)), (or (and), (and)))
3283 // (or (or (or (and), (and)), (and)), (and))
3284 if (N0.getOpcode() != ISD::OR)
3285 return SDValue();
3286 SDValue N00 = N0.getOperand(0);
3287 SDValue N01 = N0.getOperand(1);
Benjamin Kramer7ad22402014-10-22 19:55:26 +00003288 SDNode *Parts[4] = {};
Evan Cheng4c0bd962011-06-21 06:01:08 +00003289
Evan Chengbf0baa92012-12-13 01:34:32 +00003290 if (N1.getOpcode() == ISD::OR &&
3291 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
Evan Cheng4c0bd962011-06-21 06:01:08 +00003292 // (or (or (and), (and)), (or (and), (and)))
3293 SDValue N000 = N00.getOperand(0);
3294 if (!isBSwapHWordElement(N000, Parts))
3295 return SDValue();
3296
3297 SDValue N001 = N00.getOperand(1);
3298 if (!isBSwapHWordElement(N001, Parts))
3299 return SDValue();
3300 SDValue N010 = N01.getOperand(0);
3301 if (!isBSwapHWordElement(N010, Parts))
3302 return SDValue();
3303 SDValue N011 = N01.getOperand(1);
3304 if (!isBSwapHWordElement(N011, Parts))
3305 return SDValue();
3306 } else {
3307 // (or (or (or (and), (and)), (and)), (and))
3308 if (!isBSwapHWordElement(N1, Parts))
3309 return SDValue();
3310 if (!isBSwapHWordElement(N01, Parts))
3311 return SDValue();
3312 if (N00.getOpcode() != ISD::OR)
3313 return SDValue();
3314 SDValue N000 = N00.getOperand(0);
3315 if (!isBSwapHWordElement(N000, Parts))
3316 return SDValue();
3317 SDValue N001 = N00.getOperand(1);
3318 if (!isBSwapHWordElement(N001, Parts))
3319 return SDValue();
3320 }
3321
3322 // Make sure the parts are all coming from the same node.
3323 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3324 return SDValue();
3325
Andrew Trickef9de2a2013-05-25 02:42:55 +00003326 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
Evan Cheng4c0bd962011-06-21 06:01:08 +00003327 SDValue(Parts[0],0));
3328
Kay Tiong Khoo9195a5b2013-09-23 18:43:51 +00003329 // Result of the bswap should be rotated by 16. If it's not legal, then
Evan Cheng4c0bd962011-06-21 06:01:08 +00003330 // do (x << 16) | (x >> 16).
3331 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3332 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003333 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
Craig Topper5f9791f2012-09-29 07:18:53 +00003334 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003335 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3336 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3337 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3338 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
Evan Cheng4c0bd962011-06-21 06:01:08 +00003339}
3340
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003341SDValue DAGCombiner::visitOR(SDNode *N) {
3342 SDValue N0 = N->getOperand(0);
3343 SDValue N1 = N->getOperand(1);
3344 SDValue LL, LR, RL, RR, CC0, CC1;
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003345 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3346 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00003347 EVT VT = N1.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003348
Dan Gohmana8665142007-06-25 16:23:39 +00003349 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00003350 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003351 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003352 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00003353
3354 // fold (or x, 0) -> x, vector edition
3355 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3356 return N1;
3357 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3358 return N0;
3359
3360 // fold (or x, -1) -> -1, vector edition
3361 if (ISD::isBuildVectorAllOnes(N0.getNode()))
David Xuf7aff682014-09-11 05:10:28 +00003362 // do not return N0, because undef node may exist in N0
3363 return DAG.getConstant(
3364 APInt::getAllOnesValue(
3365 N0.getValueType().getScalarType().getSizeInBits()),
3366 N0.getValueType());
Craig Toppera183ddb2012-12-08 22:49:19 +00003367 if (ISD::isBuildVectorAllOnes(N1.getNode()))
David Xuf7aff682014-09-11 05:10:28 +00003368 // do not return N1, because undef node may exist in N1
3369 return DAG.getConstant(
3370 APInt::getAllOnesValue(
3371 N1.getValueType().getScalarType().getSizeInBits()),
3372 N1.getValueType());
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003373
3374 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3375 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3376 // Do this only if the resulting shuffle is legal.
3377 if (isa<ShuffleVectorSDNode>(N0) &&
3378 isa<ShuffleVectorSDNode>(N1) &&
Andrea Di Biagio2152a6c2014-07-15 00:02:32 +00003379 // Avoid folding a node with illegal type.
3380 TLI.isTypeLegal(VT) &&
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003381 N0->getOperand(1) == N1->getOperand(1) &&
3382 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3383 bool CanFold = true;
3384 unsigned NumElts = VT.getVectorNumElements();
3385 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3386 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3387 // We construct two shuffle masks:
3388 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3389 // and N1 as the second operand.
3390 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3391 // and N0 as the second operand.
3392 // We do this because OR is commutable and therefore there might be
3393 // two ways to fold this node into a shuffle.
3394 SmallVector<int,4> Mask1;
3395 SmallVector<int,4> Mask2;
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00003396
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003397 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3398 int M0 = SV0->getMaskElt(i);
3399 int M1 = SV1->getMaskElt(i);
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00003400
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003401 // Both shuffle indexes are undef. Propagate Undef.
3402 if (M0 < 0 && M1 < 0) {
3403 Mask1.push_back(M0);
3404 Mask2.push_back(M0);
3405 continue;
3406 }
3407
3408 if (M0 < 0 || M1 < 0 ||
3409 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3410 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3411 CanFold = false;
3412 break;
3413 }
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00003414
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003415 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3416 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3417 }
3418
3419 if (CanFold) {
3420 // Fold this sequence only if the resulting shuffle is 'legal'.
3421 if (TLI.isShuffleMaskLegal(Mask1, VT))
3422 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3423 N1->getOperand(0), &Mask1[0]);
3424 if (TLI.isShuffleMaskLegal(Mask2, VT))
3425 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3426 N0->getOperand(0), &Mask2[0]);
3427 }
3428 }
Dan Gohman80f9f072007-07-13 20:03:40 +00003429 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003430
Dan Gohman06563a82007-07-03 14:03:57 +00003431 // fold (or x, undef) -> -1
Bob Wilson269a89f2010-06-28 23:40:25 +00003432 if (!LegalOperations &&
3433 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
Nate Begeman9655f842009-12-03 07:11:29 +00003434 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3435 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3436 }
Nate Begeman21158fc2005-09-01 00:19:25 +00003437 // fold (or c1, c2) -> c1|c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003438 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00003439 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003440 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00003441 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003442 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00003443 // fold (or x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003444 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003445 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00003446 // fold (or x, -1) -> -1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003447 if (N1C && N1C->isAllOnesValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003448 return N1;
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003449 // fold (or x, c) -> c iff (x & ~c) == 0
Dan Gohman1f372ed2008-02-25 21:11:39 +00003450 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
Nate Begemand23739d2005-09-06 04:43:02 +00003451 return N1;
Evan Cheng4c0bd962011-06-21 06:01:08 +00003452
3453 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3454 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003455 if (BSwap.getNode())
Evan Cheng4c0bd962011-06-21 06:01:08 +00003456 return BSwap;
3457 BSwap = MatchBSwapHWordLow(N, N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003458 if (BSwap.getNode())
Evan Cheng4c0bd962011-06-21 06:01:08 +00003459 return BSwap;
3460
Nate Begeman22e251a2006-02-03 06:46:56 +00003461 // reassociate or
Andrew Trickef9de2a2013-05-25 02:42:55 +00003462 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003463 if (ROR.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00003464 return ROR;
3465 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003466 // iff (c1 & c2) == 0.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003467 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
Chris Lattnerd8c5c062005-10-27 05:06:38 +00003468 isa<ConstantSDNode>(N0.getOperand(1))) {
Chris Lattnerd8c5c062005-10-27 05:06:38 +00003469 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
Juergen Ributzkaf26beda2014-01-25 02:02:55 +00003470 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
Matthias Braunf50ab432015-01-13 22:17:46 +00003471 if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1))
3472 return DAG.getNode(
3473 ISD::AND, SDLoc(N), VT,
3474 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3475 return SDValue();
Juergen Ributzkaf26beda2014-01-25 02:02:55 +00003476 }
Nate Begeman85c1cc42005-09-08 20:18:10 +00003477 }
Nate Begeman049b7482005-09-09 19:49:52 +00003478 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3479 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3480 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3481 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003482
Nate Begeman049b7482005-09-09 19:49:52 +00003483 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
Duncan Sands13237ac2008-06-06 12:08:01 +00003484 LL.getValueType().isInteger()) {
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003485 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3486 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
Scott Michelcf0da6c2009-02-17 22:15:04 +00003487 if (cast<ConstantSDNode>(LR)->isNullValue() &&
Nate Begeman049b7482005-09-09 19:49:52 +00003488 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003489 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003490 LR.getValueType(), LL, RL);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003491 AddToWorklist(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003492 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00003493 }
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003494 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3495 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
Scott Michelcf0da6c2009-02-17 22:15:04 +00003496 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
Nate Begeman049b7482005-09-09 19:49:52 +00003497 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003498 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003499 LR.getValueType(), LL, RL);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003500 AddToWorklist(ANDNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003501 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
Nate Begeman049b7482005-09-09 19:49:52 +00003502 }
3503 }
3504 // canonicalize equivalent to ll == rl
3505 if (LL == RR && LR == RL) {
3506 Op1 = ISD::getSetCCSwappedOperands(Op1);
3507 std::swap(RL, RR);
3508 }
3509 if (LL == RL && LR == RR) {
Duncan Sands13237ac2008-06-06 12:08:01 +00003510 bool isInteger = LL.getValueType().isInteger();
Nate Begeman049b7482005-09-09 19:49:52 +00003511 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
Chris Lattner5fa10402008-10-28 07:11:07 +00003512 if (Result != ISD::SETCC_INVALID &&
Patrik Hagglundffd057a2012-12-19 10:19:55 +00003513 (!LegalOperations ||
Owen Andersoncc068992013-02-14 09:07:33 +00003514 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3515 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault758659232013-05-18 00:21:46 +00003516 getSetCCResultType(N0.getValueType())))))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003517 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003518 LL, LR, Result);
Nate Begeman049b7482005-09-09 19:49:52 +00003519 }
3520 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003521
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003522 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
Chris Lattner8d6fc202006-05-05 05:51:50 +00003523 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003524 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003525 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00003526 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003527
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003528 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
Chris Lattner46d710e2006-09-14 21:11:37 +00003529 if (N0.getOpcode() == ISD::AND &&
3530 N1.getOpcode() == ISD::AND &&
3531 N0.getOperand(1).getOpcode() == ISD::Constant &&
3532 N1.getOperand(1).getOpcode() == ISD::Constant &&
3533 // Don't increase # computations.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003534 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
Chris Lattner46d710e2006-09-14 21:11:37 +00003535 // We can only do this xform if we know that bits from X that are set in C2
3536 // but not in C1 are already zero. Likewise for Y.
Dan Gohman1f372ed2008-02-25 21:11:39 +00003537 const APInt &LHSMask =
3538 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3539 const APInt &RHSMask =
3540 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003541
Dan Gohman309d3d52007-06-22 14:59:07 +00003542 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3543 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00003544 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003545 N0.getOperand(0), N1.getOperand(0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00003546 return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003547 DAG.getConstant(LHSMask | RHSMask, VT));
Chris Lattner46d710e2006-09-14 21:11:37 +00003548 }
3549 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003550
Tim Northover3007ba02015-01-21 23:17:19 +00003551 // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3552 if (N0.getOpcode() == ISD::AND &&
3553 N1.getOpcode() == ISD::AND &&
3554 N0.getOperand(0) == N1.getOperand(0) &&
3555 // Don't increase # computations.
3556 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3557 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3558 N0.getOperand(1), N1.getOperand(1));
3559 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0), X);
3560 }
3561
Chris Lattner97614c82006-09-14 20:50:57 +00003562 // See if this is some rotate idiom.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003563 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003564 return SDValue(Rot, 0);
Chris Lattner8d6fc202006-05-05 05:51:50 +00003565
Dan Gohman600f62b2010-06-24 14:30:44 +00003566 // Simplify the operands using demanded-bits information.
3567 if (!VT.isVector() &&
3568 SimplifyDemandedBits(SDValue(N, 0)))
3569 return SDValue(N, 0);
3570
Evan Chengf1005572010-04-28 07:10:39 +00003571 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00003572}
3573
Sanjay Patel50cbfc52014-08-28 16:29:51 +00003574/// Match "(X shl/srl V1) & V2" where V2 may not be present.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003575static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
Chris Lattner97614c82006-09-14 20:50:57 +00003576 if (Op.getOpcode() == ISD::AND) {
Reid Spencerde46e482006-11-02 20:25:50 +00003577 if (isa<ConstantSDNode>(Op.getOperand(1))) {
Chris Lattner97614c82006-09-14 20:50:57 +00003578 Mask = Op.getOperand(1);
3579 Op = Op.getOperand(0);
3580 } else {
3581 return false;
3582 }
3583 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003584
Chris Lattner97614c82006-09-14 20:50:57 +00003585 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3586 Shift = Op;
3587 return true;
3588 }
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003589
Scott Michelcf0da6c2009-02-17 22:15:04 +00003590 return false;
Chris Lattner97614c82006-09-14 20:50:57 +00003591}
3592
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003593// Return true if we can prove that, whenever Neg and Pos are both in the
3594// range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
Richard Sandiford0f264db2014-01-09 10:49:40 +00003595// for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3596//
3597// (or (shift1 X, Neg), (shift2 X, Pos))
3598//
Adam Nemetc6553a82014-03-07 23:56:24 +00003599// reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3600// in direction shift1 by Neg. The range [0, OpSize) means that we only need
3601// to consider shift amounts with defined behavior.
Richard Sandiford0f264db2014-01-09 10:49:40 +00003602static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003603 // If OpSize is a power of 2 then:
3604 //
3605 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3606 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3607 //
3608 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3609 // for the stronger condition:
3610 //
3611 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3612 //
3613 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3614 // we can just replace Neg with Neg' for the rest of the function.
3615 //
3616 // In other cases we check for the even stronger condition:
3617 //
3618 // Neg == OpSize - Pos [B]
3619 //
3620 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3621 // behavior if Pos == 0 (and consequently Neg == OpSize).
Adam Nemetc6553a82014-03-07 23:56:24 +00003622 //
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003623 // We could actually use [A] whenever OpSize is a power of 2, but the
3624 // only extra cases that it would match are those uninteresting ones
3625 // where Neg and Pos are never in range at the same time. E.g. for
3626 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3627 // as well as (sub 32, Pos), but:
3628 //
3629 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3630 //
3631 // always invokes undefined behavior for 32-bit X.
3632 //
3633 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
Adam Nemetc6553a82014-03-07 23:56:24 +00003634 unsigned MaskLoBits = 0;
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003635 if (Neg.getOpcode() == ISD::AND &&
3636 isPowerOf2_64(OpSize) &&
3637 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3638 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3639 Neg = Neg.getOperand(0);
Adam Nemetc6553a82014-03-07 23:56:24 +00003640 MaskLoBits = Log2_64(OpSize);
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003641 }
3642
Richard Sandiford0f264db2014-01-09 10:49:40 +00003643 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3644 if (Neg.getOpcode() != ISD::SUB)
3645 return 0;
3646 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3647 if (!NegC)
3648 return 0;
3649 SDValue NegOp1 = Neg.getOperand(1);
3650
Adam Nemet5117f5d2014-03-07 23:56:28 +00003651 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3652 // Pos'. The truncation is redundant for the purpose of the equality.
3653 if (MaskLoBits &&
3654 Pos.getOpcode() == ISD::AND &&
3655 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3656 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3657 Pos = Pos.getOperand(0);
3658
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003659 // The condition we need is now:
3660 //
3661 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3662 //
3663 // If NegOp1 == Pos then we need:
3664 //
3665 // OpSize & Mask == NegC & Mask
3666 //
3667 // (because "x & Mask" is a truncation and distributes through subtraction).
3668 APInt Width;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003669 if (Pos == NegOp1)
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003670 Width = NegC->getAPIntValue();
Richard Sandiford0f264db2014-01-09 10:49:40 +00003671 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3672 // Then the condition we want to prove becomes:
Richard Sandiford0f264db2014-01-09 10:49:40 +00003673 //
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003674 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3675 //
3676 // which, again because "x & Mask" is a truncation, becomes:
3677 //
3678 // NegC & Mask == (OpSize - PosC) & Mask
3679 // OpSize & Mask == (NegC + PosC) & Mask
3680 else if (Pos.getOpcode() == ISD::ADD &&
3681 Pos.getOperand(0) == NegOp1 &&
3682 Pos.getOperand(1).getOpcode() == ISD::Constant)
3683 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3684 NegC->getAPIntValue());
3685 else
3686 return false;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003687
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003688 // Now we just need to check that OpSize & Mask == Width & Mask.
Adam Nemetc6553a82014-03-07 23:56:24 +00003689 if (MaskLoBits)
3690 // Opsize & Mask is 0 since Mask is Opsize - 1.
3691 return Width.getLoBits(MaskLoBits) == 0;
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003692 return Width == OpSize;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003693}
3694
Richard Sandiford95c864d2014-01-08 15:40:47 +00003695// A subroutine of MatchRotate used once we have found an OR of two opposite
3696// shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3697// to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3698// former being preferred if supported. InnerPos and InnerNeg are Pos and
3699// Neg with outer conversions stripped away.
3700SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3701 SDValue Neg, SDValue InnerPos,
3702 SDValue InnerNeg, unsigned PosOpcode,
3703 unsigned NegOpcode, SDLoc DL) {
Richard Sandiford95c864d2014-01-08 15:40:47 +00003704 // fold (or (shl x, (*ext y)),
3705 // (srl x, (*ext (sub 32, y)))) ->
3706 // (rotl x, y) or (rotr x, (sub 32, y))
3707 //
3708 // fold (or (shl x, (*ext (sub 32, y))),
3709 // (srl x, (*ext y))) ->
3710 // (rotr x, y) or (rotl x, (sub 32, y))
3711 EVT VT = Shifted.getValueType();
Richard Sandiford0f264db2014-01-09 10:49:40 +00003712 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
Richard Sandiford95c864d2014-01-08 15:40:47 +00003713 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3714 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3715 HasPos ? Pos : Neg).getNode();
3716 }
3717
Craig Topperc0196b12014-04-14 00:51:57 +00003718 return nullptr;
Richard Sandiford95c864d2014-01-08 15:40:47 +00003719}
3720
Chris Lattner97614c82006-09-14 20:50:57 +00003721// MatchRotate - Handle an 'or' of two operands. If this is one of the many
3722// idioms for rotate, and if the target supports rotation instructions, generate
3723// a rot[lr].
Andrew Trickef9de2a2013-05-25 02:42:55 +00003724SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
Duncan Sands8651e9c2008-06-13 19:07:40 +00003725 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
Owen Anderson53aa7a92009-08-10 22:56:29 +00003726 EVT VT = LHS.getValueType();
Craig Topperc0196b12014-04-14 00:51:57 +00003727 if (!TLI.isTypeLegal(VT)) return nullptr;
Chris Lattner97614c82006-09-14 20:50:57 +00003728
3729 // The target must have at least one rotate flavor.
Dan Gohman4aa18462009-01-28 17:46:25 +00003730 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3731 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
Craig Topperc0196b12014-04-14 00:51:57 +00003732 if (!HasROTL && !HasROTR) return nullptr;
Duncan Sands8651e9c2008-06-13 19:07:40 +00003733
Chris Lattner97614c82006-09-14 20:50:57 +00003734 // Match "(X shl/srl V1) & V2" where V2 may not be present.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003735 SDValue LHSShift; // The shift.
3736 SDValue LHSMask; // AND value if any.
Chris Lattner97614c82006-09-14 20:50:57 +00003737 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
Craig Topperc0196b12014-04-14 00:51:57 +00003738 return nullptr; // Not part of a rotate.
Chris Lattner97614c82006-09-14 20:50:57 +00003739
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003740 SDValue RHSShift; // The shift.
3741 SDValue RHSMask; // AND value if any.
Chris Lattner97614c82006-09-14 20:50:57 +00003742 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
Craig Topperc0196b12014-04-14 00:51:57 +00003743 return nullptr; // Not part of a rotate.
Scott Michelcf0da6c2009-02-17 22:15:04 +00003744
Chris Lattner97614c82006-09-14 20:50:57 +00003745 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
Craig Topperc0196b12014-04-14 00:51:57 +00003746 return nullptr; // Not shifting the same value.
Chris Lattner97614c82006-09-14 20:50:57 +00003747
3748 if (LHSShift.getOpcode() == RHSShift.getOpcode())
Craig Topperc0196b12014-04-14 00:51:57 +00003749 return nullptr; // Shifts must disagree.
Scott Michelcf0da6c2009-02-17 22:15:04 +00003750
Chris Lattner97614c82006-09-14 20:50:57 +00003751 // Canonicalize shl to left side in a shl/srl pair.
3752 if (RHSShift.getOpcode() == ISD::SHL) {
3753 std::swap(LHS, RHS);
3754 std::swap(LHSShift, RHSShift);
3755 std::swap(LHSMask , RHSMask );
3756 }
3757
Duncan Sands13237ac2008-06-06 12:08:01 +00003758 unsigned OpSizeInBits = VT.getSizeInBits();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003759 SDValue LHSShiftArg = LHSShift.getOperand(0);
3760 SDValue LHSShiftAmt = LHSShift.getOperand(1);
Kai Nacked09bb462013-09-19 23:00:28 +00003761 SDValue RHSShiftArg = RHSShift.getOperand(0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003762 SDValue RHSShiftAmt = RHSShift.getOperand(1);
Chris Lattner97614c82006-09-14 20:50:57 +00003763
3764 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3765 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
Scott Michel16627a52007-04-02 21:36:32 +00003766 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3767 RHSShiftAmt.getOpcode() == ISD::Constant) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00003768 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3769 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
Chris Lattner97614c82006-09-14 20:50:57 +00003770 if ((LShVal + RShVal) != OpSizeInBits)
Craig Topperc0196b12014-04-14 00:51:57 +00003771 return nullptr;
Chris Lattner97614c82006-09-14 20:50:57 +00003772
Craig Topper65161fa2012-09-29 06:54:22 +00003773 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3774 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003775
Chris Lattner97614c82006-09-14 20:50:57 +00003776 // If there is an AND of either shifted operand, apply it to the result.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003777 if (LHSMask.getNode() || RHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003778 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003779
Gabor Greiff304a7a2008-08-28 21:40:38 +00003780 if (LHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003781 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3782 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
Chris Lattner97614c82006-09-14 20:50:57 +00003783 }
Gabor Greiff304a7a2008-08-28 21:40:38 +00003784 if (RHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003785 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3786 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
Chris Lattner97614c82006-09-14 20:50:57 +00003787 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003788
Bill Wendling35972a92009-01-30 21:14:50 +00003789 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
Chris Lattner97614c82006-09-14 20:50:57 +00003790 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003791
Gabor Greiff304a7a2008-08-28 21:40:38 +00003792 return Rot.getNode();
Chris Lattner97614c82006-09-14 20:50:57 +00003793 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003794
Chris Lattner97614c82006-09-14 20:50:57 +00003795 // If there is a mask here, and we have a variable shift, we can't be sure
3796 // that we're masking out the right stuff.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003797 if (LHSMask.getNode() || RHSMask.getNode())
Craig Topperc0196b12014-04-14 00:51:57 +00003798 return nullptr;
Scott Michelcf0da6c2009-02-17 22:15:04 +00003799
Benjamin Kramer64bdb292013-09-24 14:21:28 +00003800 // If the shift amount is sign/zext/any-extended just peel it off.
3801 SDValue LExtOp0 = LHSShiftAmt;
3802 SDValue RExtOp0 = RHSShiftAmt;
Craig Topper5f9791f2012-09-29 07:18:53 +00003803 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3804 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3805 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3806 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3807 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3808 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3809 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3810 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
Benjamin Kramer64bdb292013-09-24 14:21:28 +00003811 LExtOp0 = LHSShiftAmt.getOperand(0);
3812 RExtOp0 = RHSShiftAmt.getOperand(0);
3813 }
3814
Richard Sandiford95c864d2014-01-08 15:40:47 +00003815 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3816 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3817 if (TryL)
3818 return TryL;
3819
3820 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3821 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3822 if (TryR)
3823 return TryR;
Scott Michelcf0da6c2009-02-17 22:15:04 +00003824
Craig Topperc0196b12014-04-14 00:51:57 +00003825 return nullptr;
Chris Lattner97614c82006-09-14 20:50:57 +00003826}
3827
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003828SDValue DAGCombiner::visitXOR(SDNode *N) {
3829 SDValue N0 = N->getOperand(0);
3830 SDValue N1 = N->getOperand(1);
3831 SDValue LHS, RHS, CC;
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003832 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3833 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00003834 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003835
Dan Gohmana8665142007-06-25 16:23:39 +00003836 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00003837 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003838 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003839 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00003840
3841 // fold (xor x, 0) -> x, vector edition
3842 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3843 return N1;
3844 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3845 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00003846 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003847
Evan Chengdf1690d2008-03-25 20:08:07 +00003848 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3849 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3850 return DAG.getConstant(0, VT);
Dan Gohman06563a82007-07-03 14:03:57 +00003851 // fold (xor x, undef) -> undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00003852 if (N0.getOpcode() == ISD::UNDEF)
3853 return N0;
3854 if (N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00003855 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00003856 // fold (xor c1, c2) -> c1^c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003857 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00003858 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003859 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00003860 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003861 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00003862 // fold (xor x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003863 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00003864 return N0;
Nate Begeman22e251a2006-02-03 06:46:56 +00003865 // reassociate xor
Andrew Trickef9de2a2013-05-25 02:42:55 +00003866 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003867 if (RXOR.getNode())
Nate Begeman22e251a2006-02-03 06:46:56 +00003868 return RXOR;
Bill Wendling49a5ce82008-11-11 08:25:46 +00003869
Nate Begeman21158fc2005-09-01 00:19:25 +00003870 // fold !(x cc y) -> (x !cc y)
Oliver Stannardd29db9b2014-11-17 10:49:31 +00003871 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
Duncan Sands13237ac2008-06-06 12:08:01 +00003872 bool isInt = LHS.getValueType().isInteger();
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003873 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3874 isInt);
Bill Wendling49a5ce82008-11-11 08:25:46 +00003875
Patrik Hagglundffd057a2012-12-19 10:19:55 +00003876 if (!LegalOperations ||
3877 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
Bill Wendling49a5ce82008-11-11 08:25:46 +00003878 switch (N0.getOpcode()) {
3879 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +00003880 llvm_unreachable("Unhandled SetCC Equivalent!");
Bill Wendling49a5ce82008-11-11 08:25:46 +00003881 case ISD::SETCC:
Andrew Trickef9de2a2013-05-25 02:42:55 +00003882 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
Bill Wendling49a5ce82008-11-11 08:25:46 +00003883 case ISD::SELECT_CC:
Andrew Trickef9de2a2013-05-25 02:42:55 +00003884 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
Bill Wendling49a5ce82008-11-11 08:25:46 +00003885 N0.getOperand(3), NotCC);
3886 }
3887 }
Nate Begeman21158fc2005-09-01 00:19:25 +00003888 }
Bill Wendling49a5ce82008-11-11 08:25:46 +00003889
Chris Lattner58c227b2007-09-10 21:39:07 +00003890 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
Dan Gohmanb72127a2008-03-13 22:13:53 +00003891 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
Gabor Greife12264b2008-08-30 19:29:20 +00003892 N0.getNode()->hasOneUse() &&
3893 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003894 SDValue V = N0.getOperand(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003895 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
Duncan Sands56ab90d2007-10-10 09:54:50 +00003896 DAG.getConstant(1, V.getValueType()));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003897 AddToWorklist(V.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003898 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
Chris Lattner58c227b2007-09-10 21:39:07 +00003899 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003900
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003901 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
Owen Anderson9f944592009-08-11 20:47:22 +00003902 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003903 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003904 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003905 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3906 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
Andrew Trickef9de2a2013-05-25 02:42:55 +00003907 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3908 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003909 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003910 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
Nate Begeman21158fc2005-09-01 00:19:25 +00003911 }
3912 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003913 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
Scott Michelcf0da6c2009-02-17 22:15:04 +00003914 if (N1C && N1C->isAllOnesValue() &&
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003915 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003916 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003917 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3918 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
Andrew Trickef9de2a2013-05-25 02:42:55 +00003919 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3920 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003921 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003922 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
Nate Begeman21158fc2005-09-01 00:19:25 +00003923 }
3924 }
David Majnemer386ab7f2013-05-08 06:44:42 +00003925 // fold (xor (and x, y), y) -> (and (not x), y)
3926 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
Benjamin Kramerbb1dd732013-11-17 10:40:03 +00003927 N0->getOperand(1) == N1) {
David Majnemer386ab7f2013-05-08 06:44:42 +00003928 SDValue X = N0->getOperand(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00003929 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003930 AddToWorklist(NotX.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003931 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
David Majnemer386ab7f2013-05-08 06:44:42 +00003932 }
Bill Wendling35972a92009-01-30 21:14:50 +00003933 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
Nate Begeman85c1cc42005-09-08 20:18:10 +00003934 if (N1C && N0.getOpcode() == ISD::XOR) {
3935 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3936 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3937 if (N00C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003938 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
Bill Wendling35972a92009-01-30 21:14:50 +00003939 DAG.getConstant(N1C->getAPIntValue() ^
Dan Gohmanb72127a2008-03-13 22:13:53 +00003940 N00C->getAPIntValue(), VT));
Nate Begeman85c1cc42005-09-08 20:18:10 +00003941 if (N01C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00003942 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
Bill Wendling35972a92009-01-30 21:14:50 +00003943 DAG.getConstant(N1C->getAPIntValue() ^
Dan Gohmanb72127a2008-03-13 22:13:53 +00003944 N01C->getAPIntValue(), VT));
Nate Begeman85c1cc42005-09-08 20:18:10 +00003945 }
3946 // fold (xor x, x) -> 0
Eric Christophere5ca1e02011-02-16 04:50:12 +00003947 if (N0 == N1)
Hal Finkel6c29bd92013-07-09 17:02:45 +00003948 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003949
Chris Lattner8d6fc202006-05-05 05:51:50 +00003950 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3951 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003952 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003953 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00003954 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003955
Chris Lattner098c01e2006-04-08 04:15:24 +00003956 // Simplify the expression using non-local knowledge.
Duncan Sands13237ac2008-06-06 12:08:01 +00003957 if (!VT.isVector() &&
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003958 SimplifyDemandedBits(SDValue(N, 0)))
3959 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003960
Evan Chengf1005572010-04-28 07:10:39 +00003961 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00003962}
3963
Sanjay Patel50cbfc52014-08-28 16:29:51 +00003964/// Handle transforms common to the three shifts, when the shift amount is a
3965/// constant.
Matt Arsenault985b9de2014-03-17 18:58:01 +00003966SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003967 // We can't and shouldn't fold opaque constants.
Matt Arsenault985b9de2014-03-17 18:58:01 +00003968 if (Amt->isOpaque())
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003969 return SDValue();
3970
Gabor Greiff304a7a2008-08-28 21:40:38 +00003971 SDNode *LHS = N->getOperand(0).getNode();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003972 if (!LHS->hasOneUse()) return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003973
Chris Lattner7c709a52007-12-06 07:33:36 +00003974 // We want to pull some binops through shifts, so that we have (and (shift))
3975 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3976 // thing happens with address calculations, so it's important to canonicalize
3977 // it.
3978 bool HighBitSet = false; // Can we transform this if the high bit is set?
Scott Michelcf0da6c2009-02-17 22:15:04 +00003979
Chris Lattner7c709a52007-12-06 07:33:36 +00003980 switch (LHS->getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003981 default: return SDValue();
Chris Lattner7c709a52007-12-06 07:33:36 +00003982 case ISD::OR:
3983 case ISD::XOR:
3984 HighBitSet = false; // We can only transform sra if the high bit is clear.
3985 break;
3986 case ISD::AND:
3987 HighBitSet = true; // We can only transform sra if the high bit is set.
3988 break;
3989 case ISD::ADD:
Scott Michelcf0da6c2009-02-17 22:15:04 +00003990 if (N->getOpcode() != ISD::SHL)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003991 return SDValue(); // only shl(add) not sr[al](add).
Chris Lattner7c709a52007-12-06 07:33:36 +00003992 HighBitSet = false; // We can only transform sra if the high bit is clear.
3993 break;
3994 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003995
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003996 // We require the RHS of the binop to be a constant and not opaque as well.
Chris Lattner7c709a52007-12-06 07:33:36 +00003997 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00003998 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00003999
4000 // FIXME: disable this unless the input to the binop is a shift by a constant.
4001 // If it is not a shift, it pessimizes some common cases like:
Chris Lattnereedaf922007-12-06 07:47:55 +00004002 //
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004003 // void foo(int *X, int i) { X[i & 1235] = 1; }
4004 // int bar(int *X, int i) { return X[i & 255]; }
Gabor Greiff304a7a2008-08-28 21:40:38 +00004005 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004006 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
Chris Lattnereedaf922007-12-06 07:47:55 +00004007 BinOpLHSVal->getOpcode() != ISD::SRA &&
4008 BinOpLHSVal->getOpcode() != ISD::SRL) ||
4009 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004010 return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004011
Owen Anderson53aa7a92009-08-10 22:56:29 +00004012 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004013
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004014 // If this is a signed shift right, and the high bit is modified by the
4015 // logical operation, do not perform the transformation. The highBitSet
4016 // boolean indicates the value of the high bit of the constant which would
4017 // cause it to be modified for this operation.
Chris Lattner7c709a52007-12-06 07:33:36 +00004018 if (N->getOpcode() == ISD::SRA) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00004019 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4020 if (BinOpRHSSignSet != HighBitSet)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004021 return SDValue();
Chris Lattner7c709a52007-12-06 07:33:36 +00004022 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004023
Weiming Zhao7f6daf12014-04-30 21:07:24 +00004024 if (!TLI.isDesirableToCommuteWithShift(LHS))
4025 return SDValue();
4026
Chris Lattner7c709a52007-12-06 07:33:36 +00004027 // Fold the constants, shifting the binop RHS by the shift amount.
Andrew Trickef9de2a2013-05-25 02:42:55 +00004028 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004029 N->getValueType(0),
4030 LHS->getOperand(1), N->getOperand(1));
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00004031 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
Chris Lattner7c709a52007-12-06 07:33:36 +00004032
4033 // Create the new shift.
Eric Christopherd9e8eac2010-12-09 04:48:06 +00004034 SDValue NewShift = DAG.getNode(N->getOpcode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00004035 SDLoc(LHS->getOperand(0)),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004036 VT, LHS->getOperand(0), N->getOperand(1));
Chris Lattner7c709a52007-12-06 07:33:36 +00004037
4038 // Create the new binop.
Andrew Trickef9de2a2013-05-25 02:42:55 +00004039 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
Chris Lattner7c709a52007-12-06 07:33:36 +00004040}
4041
Adam Nemet67483892014-03-04 23:28:31 +00004042SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4043 assert(N->getOpcode() == ISD::TRUNCATE);
4044 assert(N->getOperand(0).getOpcode() == ISD::AND);
4045
4046 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4047 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4048 SDValue N01 = N->getOperand(0).getOperand(1);
4049
Matt Arsenault985b9de2014-03-17 18:58:01 +00004050 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
Adam Nemet67483892014-03-04 23:28:31 +00004051 EVT TruncVT = N->getValueType(0);
4052 SDValue N00 = N->getOperand(0).getOperand(0);
4053 APInt TruncC = N01C->getAPIntValue();
Matt Arsenault985b9de2014-03-17 18:58:01 +00004054 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
Adam Nemet67483892014-03-04 23:28:31 +00004055
4056 return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
4057 DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
4058 DAG.getConstant(TruncC, TruncVT));
4059 }
4060 }
4061
4062 return SDValue();
4063}
Adam Nemet7f928f12014-03-07 23:56:30 +00004064
4065SDValue DAGCombiner::visitRotate(SDNode *N) {
4066 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4067 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4068 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4069 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4070 if (NewOp1.getNode())
4071 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4072 N->getOperand(0), NewOp1);
4073 }
4074 return SDValue();
4075}
4076
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004077SDValue DAGCombiner::visitSHL(SDNode *N) {
4078 SDValue N0 = N->getOperand(0);
4079 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004080 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4081 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004082 EVT VT = N0.getValueType();
Matt Arsenault985b9de2014-03-17 18:58:01 +00004083 unsigned OpSizeInBits = VT.getScalarSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004084
Daniel Sandersa1840d22013-11-11 17:23:41 +00004085 // fold vector ops
4086 if (VT.isVector()) {
4087 SDValue FoldedVOp = SimplifyVBinOp(N);
4088 if (FoldedVOp.getNode()) return FoldedVOp;
Quentin Colombet4db08df2014-02-21 23:42:41 +00004089
4090 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4091 // If setcc produces all-one true value then:
4092 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
Matt Arsenault985b9de2014-03-17 18:58:01 +00004093 if (N1CV && N1CV->isConstant()) {
Daniel Sanderscbd44c52014-07-10 10:18:12 +00004094 if (N0.getOpcode() == ISD::AND) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004095 SDValue N00 = N0->getOperand(0);
4096 SDValue N01 = N0->getOperand(1);
4097 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
Quentin Colombet4db08df2014-02-21 23:42:41 +00004098
Daniel Sanderscbd44c52014-07-10 10:18:12 +00004099 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4100 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4101 TargetLowering::ZeroOrNegativeOneBooleanContent) {
Matthias Braunf50ab432015-01-13 22:17:46 +00004102 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV))
Matt Arsenault985b9de2014-03-17 18:58:01 +00004103 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4104 }
4105 } else {
4106 N1C = isConstOrConstSplat(N1);
Quentin Colombet4db08df2014-02-21 23:42:41 +00004107 }
4108 }
Daniel Sandersa1840d22013-11-11 17:23:41 +00004109 }
4110
Nate Begeman21158fc2005-09-01 00:19:25 +00004111 // fold (shl c1, c2) -> c1<<c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004112 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00004113 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00004114 // fold (shl 0, x) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004115 if (N0C && N0C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004116 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004117 // fold (shl x, c >= size(x)) -> undef
Dan Gohmaneffb8942008-09-12 16:56:44 +00004118 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00004119 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004120 // fold (shl x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004121 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004122 return N0;
Chad Rosier818e1162011-06-14 22:29:10 +00004123 // fold (shl undef, x) -> 0
4124 if (N0.getOpcode() == ISD::UNDEF)
4125 return DAG.getConstant(0, VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004126 // if (shl x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004127 if (DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1d459e42009-12-11 21:31:27 +00004128 APInt::getAllOnesValue(OpSizeInBits)))
Nate Begemand23739d2005-09-06 04:43:02 +00004129 return DAG.getConstant(0, VT);
Duncan Sands3ed76882009-02-01 18:06:53 +00004130 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004131 if (N1.getOpcode() == ISD::TRUNCATE &&
Adam Nemet67483892014-03-04 23:28:31 +00004132 N1.getOperand(0).getOpcode() == ISD::AND) {
4133 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4134 if (NewOp1.getNode())
4135 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004136 }
4137
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004138 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4139 return SDValue(N, 0);
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004140
4141 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
Matt Arsenault985b9de2014-03-17 18:58:01 +00004142 if (N1C && N0.getOpcode() == ISD::SHL) {
4143 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4144 uint64_t c1 = N0C1->getZExtValue();
4145 uint64_t c2 = N1C->getZExtValue();
4146 if (c1 + c2 >= OpSizeInBits)
4147 return DAG.getConstant(0, VT);
4148 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4149 DAG.getConstant(c1 + c2, N1.getValueType()));
4150 }
Nate Begeman21158fc2005-09-01 00:19:25 +00004151 }
Dale Johannesena94e36b2010-12-21 21:55:50 +00004152
4153 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4154 // For this to be valid, the second form must not preserve any of the bits
4155 // that are shifted out by the inner shift in the first form. This means
4156 // the outer shift size must be >= the number of bits added by the ext.
4157 // As a corollary, we don't care what kind of ext it is.
4158 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4159 N0.getOpcode() == ISD::ANY_EXTEND ||
4160 N0.getOpcode() == ISD::SIGN_EXTEND) &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004161 N0.getOperand(0).getOpcode() == ISD::SHL) {
4162 SDValue N0Op0 = N0.getOperand(0);
4163 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4164 uint64_t c1 = N0Op0C1->getZExtValue();
4165 uint64_t c2 = N1C->getZExtValue();
4166 EVT InnerShiftVT = N0Op0.getValueType();
4167 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4168 if (c2 >= OpSizeInBits - InnerShiftSize) {
4169 if (c1 + c2 >= OpSizeInBits)
4170 return DAG.getConstant(0, VT);
4171 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4172 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4173 N0Op0->getOperand(0)),
4174 DAG.getConstant(c1 + c2, N1.getValueType()));
4175 }
Dale Johannesena94e36b2010-12-21 21:55:50 +00004176 }
4177 }
4178
Andrea Di Biagio56ce9c42013-09-27 11:37:05 +00004179 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4180 // Only fold this if the inner zext has no other uses to avoid increasing
4181 // the total number of instructions.
4182 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004183 N0.getOperand(0).getOpcode() == ISD::SRL) {
4184 SDValue N0Op0 = N0.getOperand(0);
4185 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4186 uint64_t c1 = N0Op0C1->getZExtValue();
4187 if (c1 < VT.getScalarSizeInBits()) {
4188 uint64_t c2 = N1C->getZExtValue();
4189 if (c1 == c2) {
4190 SDValue NewOp0 = N0.getOperand(0);
4191 EVT CountVT = NewOp0.getOperand(1).getValueType();
4192 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4193 NewOp0, DAG.getConstant(c2, CountVT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004194 AddToWorklist(NewSHL.getNode());
Matt Arsenault985b9de2014-03-17 18:58:01 +00004195 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4196 }
Andrea Di Biagio56ce9c42013-09-27 11:37:05 +00004197 }
4198 }
4199 }
4200
Eli Friedman1877ac92011-06-09 22:14:44 +00004201 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4202 // (and (srl x, (sub c1, c2), MASK)
Chandler Carruthe041a302012-01-05 11:05:55 +00004203 // Only fold this if the inner shift has no other uses -- if it does, folding
4204 // this will increase the total number of instructions.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004205 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4206 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4207 uint64_t c1 = N0C1->getZExtValue();
4208 if (c1 < OpSizeInBits) {
4209 uint64_t c2 = N1C->getZExtValue();
4210 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4211 SDValue Shift;
4212 if (c2 > c1) {
4213 Mask = Mask.shl(c2 - c1);
4214 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4215 DAG.getConstant(c2 - c1, N1.getValueType()));
4216 } else {
4217 Mask = Mask.lshr(c1 - c2);
4218 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4219 DAG.getConstant(c1 - c2, N1.getValueType()));
4220 }
4221 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4222 DAG.getConstant(Mask, VT));
Eli Friedman1877ac92011-06-09 22:14:44 +00004223 }
Evan Chenga7bb55e2009-07-21 05:40:15 +00004224 }
Nate Begeman21158fc2005-09-01 00:19:25 +00004225 }
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004226 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
Dan Gohman5758e1e2009-08-06 09:18:59 +00004227 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004228 unsigned BitSize = VT.getScalarSizeInBits();
Dan Gohman5758e1e2009-08-06 09:18:59 +00004229 SDValue HiBitsMask =
Matt Arsenault985b9de2014-03-17 18:58:01 +00004230 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4231 BitSize - N1C->getZExtValue()), VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004232 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
Dan Gohman5758e1e2009-08-06 09:18:59 +00004233 HiBitsMask);
4234 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004235
Matt Arsenault8239eaa2014-09-11 17:34:19 +00004236 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4237 // Variant of version done on multiply, except mul by a power of 2 is turned
4238 // into a shift.
4239 APInt Val;
4240 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4241 (isa<ConstantSDNode>(N0.getOperand(1)) ||
4242 isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4243 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4244 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4245 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4246 }
4247
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004248 if (N1C) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004249 SDValue NewSHL = visitShiftByConstant(N, N1C);
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004250 if (NewSHL.getNode())
4251 return NewSHL;
4252 }
4253
Evan Chengf1005572010-04-28 07:10:39 +00004254 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004255}
4256
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004257SDValue DAGCombiner::visitSRA(SDNode *N) {
4258 SDValue N0 = N->getOperand(0);
4259 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004260 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4261 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004262 EVT VT = N0.getValueType();
Dan Gohman1d459e42009-12-11 21:31:27 +00004263 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004264
Daniel Sandersa1840d22013-11-11 17:23:41 +00004265 // fold vector ops
4266 if (VT.isVector()) {
4267 SDValue FoldedVOp = SimplifyVBinOp(N);
4268 if (FoldedVOp.getNode()) return FoldedVOp;
Matt Arsenault985b9de2014-03-17 18:58:01 +00004269
4270 N1C = isConstOrConstSplat(N1);
Daniel Sandersa1840d22013-11-11 17:23:41 +00004271 }
4272
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004273 // fold (sra c1, c2) -> (sra c1, c2)
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004274 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00004275 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00004276 // fold (sra 0, x) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004277 if (N0C && N0C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004278 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004279 // fold (sra -1, x) -> -1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004280 if (N0C && N0C->isAllOnesValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004281 return N0;
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004282 // fold (sra x, (setge c, size(x))) -> undef
Dan Gohman1d459e42009-12-11 21:31:27 +00004283 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00004284 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004285 // fold (sra x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004286 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004287 return N0;
Nate Begemanfb5dbad2006-02-17 19:54:08 +00004288 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4289 // sext_inreg.
4290 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
Dan Gohman1d459e42009-12-11 21:31:27 +00004291 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004292 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4293 if (VT.isVector())
4294 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4295 ExtVT, VT.getVectorNumElements());
4296 if ((!LegalOperations ||
4297 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004298 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004299 N0.getOperand(0), DAG.getValueType(ExtVT));
Nate Begemanfb5dbad2006-02-17 19:54:08 +00004300 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00004301
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004302 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
Chris Lattner0f8a7272006-02-28 06:23:04 +00004303 if (N1C && N0.getOpcode() == ISD::SRA) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004304 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00004305 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
Matt Arsenault985b9de2014-03-17 18:58:01 +00004306 if (Sum >= OpSizeInBits)
4307 Sum = OpSizeInBits - 1;
Andrew Trickef9de2a2013-05-25 02:42:55 +00004308 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
Matt Arsenault985b9de2014-03-17 18:58:01 +00004309 DAG.getConstant(Sum, N1.getValueType()));
Chris Lattner0f8a7272006-02-28 06:23:04 +00004310 }
4311 }
Christopher Lamb8fe91092008-03-19 08:30:06 +00004312
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004313 // fold (sra (shl X, m), (sub result_size, n))
4314 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
Scott Michelcf0da6c2009-02-17 22:15:04 +00004315 // result_size - n != m.
4316 // If truncate is free for the target sext(shl) is likely to result in better
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004317 // code.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004318 if (N0.getOpcode() == ISD::SHL && N1C) {
Christopher Lamb8fe91092008-03-19 08:30:06 +00004319 // Get the two constanst of the shifts, CN0 = m, CN = n.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004320 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4321 if (N01C) {
4322 LLVMContext &Ctx = *DAG.getContext();
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004323 // Determine what the truncate's result bitsize and type would be.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004324 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4325
4326 if (VT.isVector())
4327 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4328
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004329 // Determine the residual right-shift amount.
Torok Edwinbe6a9a12009-05-23 17:29:48 +00004330 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
Duncan Sands8651e9c2008-06-13 19:07:40 +00004331
Scott Michelcf0da6c2009-02-17 22:15:04 +00004332 // If the shift is not a no-op (in which case this should be just a sign
4333 // extend already), the truncated to type is legal, sign_extend is legal
Dan Gohman4a618822010-02-10 16:03:48 +00004334 // on that type, and the truncate to that type is both legal and free,
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004335 // perform the transform.
Torok Edwinbe6a9a12009-05-23 17:29:48 +00004336 if ((ShiftAmt > 0) &&
Dan Gohman4aa18462009-01-28 17:46:25 +00004337 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4338 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
Evan Cheng7a3e7502008-03-20 02:18:41 +00004339 TLI.isTruncateFree(VT, TruncVT)) {
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004340
Owen Andersonb2c80da2011-02-25 21:41:48 +00004341 SDValue Amt = DAG.getConstant(ShiftAmt,
4342 getShiftAmountTy(N0.getOperand(0).getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004343 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004344 N0.getOperand(0), Amt);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004345 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004346 Shift);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004347 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004348 N->getValueType(0), Trunc);
Christopher Lamb8fe91092008-03-19 08:30:06 +00004349 }
4350 }
4351 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004352
Duncan Sands3ed76882009-02-01 18:06:53 +00004353 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004354 if (N1.getOpcode() == ISD::TRUNCATE &&
Adam Nemet67483892014-03-04 23:28:31 +00004355 N1.getOperand(0).getOpcode() == ISD::AND) {
4356 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4357 if (NewOp1.getNode())
4358 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004359 }
4360
Matt Arsenault985b9de2014-03-17 18:58:01 +00004361 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
Benjamin Kramer946e1522011-01-30 16:38:43 +00004362 // if c1 is equal to the number of bits the trunc removes
4363 if (N0.getOpcode() == ISD::TRUNCATE &&
4364 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4365 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4366 N0.getOperand(0).hasOneUse() &&
4367 N0.getOperand(0).getOperand(1).hasOneUse() &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004368 N1C) {
4369 SDValue N0Op0 = N0.getOperand(0);
4370 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4371 unsigned LargeShiftVal = LargeShift->getZExtValue();
4372 EVT LargeVT = N0Op0.getValueType();
Benjamin Kramer946e1522011-01-30 16:38:43 +00004373
Matt Arsenault985b9de2014-03-17 18:58:01 +00004374 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4375 SDValue Amt =
4376 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4377 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4378 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4379 N0Op0.getOperand(0), Amt);
4380 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4381 }
Benjamin Kramer946e1522011-01-30 16:38:43 +00004382 }
4383 }
4384
Scott Michelcf0da6c2009-02-17 22:15:04 +00004385 // Simplify, based on bits shifted out of the LHS.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004386 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4387 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004388
4389
Nate Begeman21158fc2005-09-01 00:19:25 +00004390 // If the sign bit is known to be zero, switch this to a SRL.
Dan Gohman1f372ed2008-02-25 21:11:39 +00004391 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004392 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
Chris Lattner7c709a52007-12-06 07:33:36 +00004393
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004394 if (N1C) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004395 SDValue NewSRA = visitShiftByConstant(N, N1C);
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004396 if (NewSRA.getNode())
4397 return NewSRA;
4398 }
4399
Evan Chengf1005572010-04-28 07:10:39 +00004400 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004401}
4402
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004403SDValue DAGCombiner::visitSRL(SDNode *N) {
4404 SDValue N0 = N->getOperand(0);
4405 SDValue N1 = N->getOperand(1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004406 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4407 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004408 EVT VT = N0.getValueType();
Dan Gohman1d459e42009-12-11 21:31:27 +00004409 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004410
Daniel Sandersa1840d22013-11-11 17:23:41 +00004411 // fold vector ops
4412 if (VT.isVector()) {
4413 SDValue FoldedVOp = SimplifyVBinOp(N);
4414 if (FoldedVOp.getNode()) return FoldedVOp;
Matt Arsenault985b9de2014-03-17 18:58:01 +00004415
4416 N1C = isConstOrConstSplat(N1);
Daniel Sandersa1840d22013-11-11 17:23:41 +00004417 }
4418
Nate Begeman21158fc2005-09-01 00:19:25 +00004419 // fold (srl c1, c2) -> c1 >>u c2
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004420 if (N0C && N1C)
Bill Wendlingdea91302008-09-24 10:25:02 +00004421 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00004422 // fold (srl 0, x) -> 0
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004423 if (N0C && N0C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004424 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004425 // fold (srl x, c >= size(x)) -> undef
Dan Gohmaneffb8942008-09-12 16:56:44 +00004426 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00004427 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004428 // fold (srl x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004429 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004430 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004431 // if (srl x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004432 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1f372ed2008-02-25 21:11:39 +00004433 APInt::getAllOnesValue(OpSizeInBits)))
Nate Begemand23739d2005-09-06 04:43:02 +00004434 return DAG.getConstant(0, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004435
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004436 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
Matt Arsenault985b9de2014-03-17 18:58:01 +00004437 if (N1C && N0.getOpcode() == ISD::SRL) {
4438 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4439 uint64_t c1 = N01C->getZExtValue();
4440 uint64_t c2 = N1C->getZExtValue();
4441 if (c1 + c2 >= OpSizeInBits)
4442 return DAG.getConstant(0, VT);
4443 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4444 DAG.getConstant(c1 + c2, N1.getValueType()));
4445 }
Nate Begeman21158fc2005-09-01 00:19:25 +00004446 }
Wesley Peck527da1b2010-11-23 03:31:01 +00004447
Dale Johannesencd538af2010-12-17 21:45:49 +00004448 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
Dale Johannesencd538af2010-12-17 21:45:49 +00004449 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4450 N0.getOperand(0).getOpcode() == ISD::SRL &&
Dale Johannesen0a291a32010-12-20 20:10:50 +00004451 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
Owen Andersonb2c80da2011-02-25 21:41:48 +00004452 uint64_t c1 =
Dale Johannesencd538af2010-12-17 21:45:49 +00004453 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4454 uint64_t c2 = N1C->getZExtValue();
Dale Johannesena94e36b2010-12-21 21:55:50 +00004455 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4456 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
Dale Johannesencd538af2010-12-17 21:45:49 +00004457 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
Dale Johannesen0a291a32010-12-20 20:10:50 +00004458 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
Dale Johannesencd538af2010-12-17 21:45:49 +00004459 if (c1 + OpSizeInBits == InnerShiftSize) {
4460 if (c1 + c2 >= InnerShiftSize)
4461 return DAG.getConstant(0, VT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004462 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4463 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
Dale Johannesencd538af2010-12-17 21:45:49 +00004464 N0.getOperand(0)->getOperand(0),
Dale Johannesena94e36b2010-12-21 21:55:50 +00004465 DAG.getConstant(c1 + c2, ShiftCountVT)));
Dale Johannesencd538af2010-12-17 21:45:49 +00004466 }
4467 }
4468
Chris Lattnerf9b2e3c2010-04-15 05:28:43 +00004469 // fold (srl (shl x, c), c) -> (and x, cst2)
Matt Arsenault985b9de2014-03-17 18:58:01 +00004470 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4471 unsigned BitSize = N0.getScalarValueSizeInBits();
4472 if (BitSize <= 64) {
4473 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4474 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4475 DAG.getConstant(~0ULL >> ShAmt, VT));
4476 }
Chris Lattnerf9b2e3c2010-04-15 05:28:43 +00004477 }
Wesley Peck527da1b2010-11-23 03:31:01 +00004478
Michael Liao62ebfd82013-06-21 18:45:27 +00004479 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004480 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4481 // Shifting in all undef bits?
Owen Anderson53aa7a92009-08-10 22:56:29 +00004482 EVT SmallVT = N0.getOperand(0).getValueType();
Matt Arsenault985b9de2014-03-17 18:58:01 +00004483 unsigned BitSize = SmallVT.getScalarSizeInBits();
4484 if (N1C->getZExtValue() >= BitSize)
Dale Johannesen84935752009-02-06 23:05:02 +00004485 return DAG.getUNDEF(VT);
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004486
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004487 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
Owen Andersona5192842011-04-14 17:30:49 +00004488 uint64_t ShiftAmt = N1C->getZExtValue();
Andrew Trickef9de2a2013-05-25 02:42:55 +00004489 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
Owen Andersona5192842011-04-14 17:30:49 +00004490 N0.getOperand(0),
4491 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004492 AddToWorklist(SmallShift.getNode());
Matt Arsenault985b9de2014-03-17 18:58:01 +00004493 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
Michael Liao62ebfd82013-06-21 18:45:27 +00004494 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4495 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4496 DAG.getConstant(Mask, VT));
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004497 }
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004498 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004499
Chris Lattner2e33fb42006-10-12 20:23:19 +00004500 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4501 // bit, which is unmodified by sra.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004502 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
Chris Lattner2e33fb42006-10-12 20:23:19 +00004503 if (N0.getOpcode() == ISD::SRA)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004504 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
Chris Lattner2e33fb42006-10-12 20:23:19 +00004505 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004506
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00004507 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
Scott Michelcf0da6c2009-02-17 22:15:04 +00004508 if (N1C && N0.getOpcode() == ISD::CTLZ &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004509 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004510 APInt KnownZero, KnownOne;
Jay Foada0653a32014-05-14 21:14:37 +00004511 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004512
Chris Lattner49932492006-04-02 06:11:11 +00004513 // If any of the input bits are KnownOne, then the input couldn't be all
4514 // zeros, thus the result of the srl will always be zero.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004515 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004516
Chris Lattner49932492006-04-02 06:11:11 +00004517 // If all of the bits input the to ctlz node are known to be zero, then
4518 // the result of the ctlz is "32" and the result of the shift is one.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00004519 APInt UnknownBits = ~KnownZero;
Chris Lattner49932492006-04-02 06:11:11 +00004520 if (UnknownBits == 0) return DAG.getConstant(1, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004521
Chris Lattner49932492006-04-02 06:11:11 +00004522 // Otherwise, check to see if there is exactly one bit input to the ctlz.
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004523 if ((UnknownBits & (UnknownBits - 1)) == 0) {
Chris Lattner49932492006-04-02 06:11:11 +00004524 // Okay, we know that only that the single bit specified by UnknownBits
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004525 // could be set on input to the CTLZ node. If this bit is set, the SRL
4526 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4527 // to an SRL/XOR pair, which is likely to simplify more.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004528 unsigned ShAmt = UnknownBits.countTrailingZeros();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004529 SDValue Op = N0.getOperand(0);
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004530
Chris Lattner49932492006-04-02 06:11:11 +00004531 if (ShAmt) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004532 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
Owen Andersonb2c80da2011-02-25 21:41:48 +00004533 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004534 AddToWorklist(Op.getNode());
Chris Lattner49932492006-04-02 06:11:11 +00004535 }
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004536
Andrew Trickef9de2a2013-05-25 02:42:55 +00004537 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004538 Op, DAG.getConstant(1, VT));
Chris Lattner49932492006-04-02 06:11:11 +00004539 }
4540 }
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004541
Duncan Sands3ed76882009-02-01 18:06:53 +00004542 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004543 if (N1.getOpcode() == ISD::TRUNCATE &&
Adam Nemet67483892014-03-04 23:28:31 +00004544 N1.getOperand(0).getOpcode() == ISD::AND) {
4545 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4546 if (NewOp1.getNode())
4547 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004548 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004549
Chris Lattnerf03c90b2007-04-18 03:06:49 +00004550 // fold operands of srl based on knowledge that the low bits are not
4551 // demanded.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004552 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4553 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004554
Evan Chengb175de62009-12-18 21:31:31 +00004555 if (N1C) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004556 SDValue NewSRL = visitShiftByConstant(N, N1C);
Evan Chengb175de62009-12-18 21:31:31 +00004557 if (NewSRL.getNode())
4558 return NewSRL;
4559 }
4560
Dan Gohman600f62b2010-06-24 14:30:44 +00004561 // Attempt to convert a srl of a load into a narrower zero-extending load.
4562 SDValue NarrowLoad = ReduceLoadWidth(N);
4563 if (NarrowLoad.getNode())
4564 return NarrowLoad;
4565
Evan Chengb175de62009-12-18 21:31:31 +00004566 // Here is a common situation. We want to optimize:
4567 //
4568 // %a = ...
4569 // %b = and i32 %a, 2
4570 // %c = srl i32 %b, 1
4571 // brcond i32 %c ...
4572 //
4573 // into
Wesley Peck527da1b2010-11-23 03:31:01 +00004574 //
Evan Chengb175de62009-12-18 21:31:31 +00004575 // %a = ...
4576 // %b = and %a, 2
4577 // %c = setcc eq %b, 0
4578 // brcond %c ...
4579 //
4580 // However when after the source operand of SRL is optimized into AND, the SRL
4581 // itself may not be optimized further. Look for it and add the BRCOND into
4582 // the worklist.
Evan Cheng166a4e62010-01-06 19:38:29 +00004583 if (N->hasOneUse()) {
4584 SDNode *Use = *N->use_begin();
4585 if (Use->getOpcode() == ISD::BRCOND)
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004586 AddToWorklist(Use);
Evan Cheng166a4e62010-01-06 19:38:29 +00004587 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4588 // Also look pass the truncate.
4589 Use = *Use->use_begin();
4590 if (Use->getOpcode() == ISD::BRCOND)
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004591 AddToWorklist(Use);
Evan Cheng166a4e62010-01-06 19:38:29 +00004592 }
4593 }
Evan Chengb175de62009-12-18 21:31:31 +00004594
Evan Chengf1005572010-04-28 07:10:39 +00004595 return SDValue();
Evan Chenge19aa5c2010-04-19 19:29:22 +00004596}
4597
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004598SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4599 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004600 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00004601
4602 // fold (ctlz c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004603 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004604 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004605 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004606}
4607
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004608SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4609 SDValue N0 = N->getOperand(0);
4610 EVT VT = N->getValueType(0);
4611
4612 // fold (ctlz_zero_undef c1) -> c2
4613 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004614 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004615 return SDValue();
4616}
4617
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004618SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4619 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004620 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004621
Nate Begeman21158fc2005-09-01 00:19:25 +00004622 // fold (cttz c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004623 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004624 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004625 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004626}
4627
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004628SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4629 SDValue N0 = N->getOperand(0);
4630 EVT VT = N->getValueType(0);
4631
4632 // fold (cttz_zero_undef c1) -> c2
4633 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004634 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004635 return SDValue();
4636}
4637
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004638SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4639 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004640 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004641
Nate Begeman21158fc2005-09-01 00:19:25 +00004642 // fold (ctpop c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004643 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004644 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004645 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004646}
4647
Matt Arsenaulta982e4f2015-01-13 00:43:00 +00004648
4649/// \brief Generate Min/Max node
4650static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4651 SDValue True, SDValue False,
4652 ISD::CondCode CC, const TargetLowering &TLI,
4653 SelectionDAG &DAG) {
4654 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4655 return SDValue();
4656
4657 switch (CC) {
4658 case ISD::SETOLT:
4659 case ISD::SETOLE:
4660 case ISD::SETLT:
4661 case ISD::SETLE:
4662 case ISD::SETULT:
4663 case ISD::SETULE: {
4664 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4665 if (TLI.isOperationLegal(Opcode, VT))
4666 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4667 return SDValue();
4668 }
4669 case ISD::SETOGT:
4670 case ISD::SETOGE:
4671 case ISD::SETGT:
4672 case ISD::SETGE:
4673 case ISD::SETUGT:
4674 case ISD::SETUGE: {
4675 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4676 if (TLI.isOperationLegal(Opcode, VT))
4677 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4678 return SDValue();
4679 }
4680 default:
4681 return SDValue();
4682 }
4683}
4684
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004685SDValue DAGCombiner::visitSELECT(SDNode *N) {
4686 SDValue N0 = N->getOperand(0);
4687 SDValue N1 = N->getOperand(1);
4688 SDValue N2 = N->getOperand(2);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004689 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4690 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4691 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004692 EVT VT = N->getValueType(0);
4693 EVT VT0 = N0.getValueType();
Nate Begemanc760f802005-09-19 22:34:01 +00004694
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004695 // fold (select C, X, X) -> X
Nate Begeman24a7eca2005-09-16 00:54:12 +00004696 if (N1 == N2)
4697 return N1;
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004698 // fold (select true, X, Y) -> X
Nate Begeman24a7eca2005-09-16 00:54:12 +00004699 if (N0C && !N0C->isNullValue())
4700 return N1;
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004701 // fold (select false, X, Y) -> Y
Nate Begeman24a7eca2005-09-16 00:54:12 +00004702 if (N0C && N0C->isNullValue())
4703 return N2;
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004704 // fold (select C, 1, X) -> (or C, X)
Owen Anderson9f944592009-08-11 20:47:22 +00004705 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004706 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004707 // fold (select C, 0, 1) -> (xor C, 1)
Daniel Sanderscbd44c52014-07-10 10:18:12 +00004708 // We can't do this reliably if integer based booleans have different contents
4709 // to floating point based booleans. This is because we can't tell whether we
4710 // have an integer-based boolean or a floating-point-based boolean unless we
4711 // can find the SETCC that produced it and inspect its operands. This is
4712 // fairly easy if C is the SETCC node, but it can potentially be
4713 // undiscoverable (or not reasonably discoverable). For example, it could be
4714 // in another basic block or it could require searching a complicated
4715 // expression.
Bob Wilsonc2dc7ee2009-01-22 22:05:48 +00004716 if (VT.isInteger() &&
Daniel Sanderscbd44c52014-07-10 10:18:12 +00004717 (VT0 == MVT::i1 || (VT0.isInteger() &&
4718 TLI.getBooleanContents(false, false) ==
4719 TLI.getBooleanContents(false, true) &&
4720 TLI.getBooleanContents(false, false) ==
4721 TargetLowering::ZeroOrOneBooleanContent)) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00004722 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004723 SDValue XORNode;
Evan Chengf5a23ab2007-08-18 05:57:05 +00004724 if (VT == VT0)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004725 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004726 N0, DAG.getConstant(1, VT0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004727 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004728 N0, DAG.getConstant(1, VT0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004729 AddToWorklist(XORNode.getNode());
Duncan Sands11dd4242008-06-08 20:54:56 +00004730 if (VT.bitsGT(VT0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004731 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4732 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
Evan Chengf5a23ab2007-08-18 05:57:05 +00004733 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004734 // fold (select C, 0, X) -> (and (not C), X)
Owen Anderson9f944592009-08-11 20:47:22 +00004735 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004736 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004737 AddToWorklist(NOTNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004738 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004739 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004740 // fold (select C, X, 1) -> (or (not C), X)
Owen Anderson9f944592009-08-11 20:47:22 +00004741 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004742 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004743 AddToWorklist(NOTNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004744 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004745 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004746 // fold (select C, X, 0) -> (and C, X)
Owen Anderson9f944592009-08-11 20:47:22 +00004747 if (VT == MVT::i1 && N2C && N2C->isNullValue())
Andrew Trickef9de2a2013-05-25 02:42:55 +00004748 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004749 // fold (select X, X, Y) -> (or X, Y)
4750 // fold (select X, 1, Y) -> (or X, Y)
Owen Anderson9f944592009-08-11 20:47:22 +00004751 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004752 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004753 // fold (select X, Y, X) -> (and X, Y)
4754 // fold (select X, Y, 0) -> (and X, Y)
Owen Anderson9f944592009-08-11 20:47:22 +00004755 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004756 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004757
Chris Lattner6c14c352005-10-18 06:04:22 +00004758 // If we can fold this based on the true/false value, do so.
4759 if (SimplifySelectOps(N, N1, N2))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004760 return SDValue(N, 0); // Don't revisit N.
Duncan Sands8651e9c2008-06-13 19:07:40 +00004761
Nate Begemanc760f802005-09-19 22:34:01 +00004762 // fold selects based on a setcc into other things, such as min/max/abs
Anton Korobeynikov035eaac2008-02-20 11:10:28 +00004763 if (N0.getOpcode() == ISD::SETCC) {
Matt Arsenaulta982e4f2015-01-13 00:43:00 +00004764 // select x, y (fcmp lt x, y) -> fminnum x, y
4765 // select x, y (fcmp gt x, y) -> fmaxnum x, y
4766 //
4767 // This is OK if we don't care about what happens if either operand is a
4768 // NaN.
4769 //
4770
4771 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
4772 // no signed zeros as well as no nans.
4773 const TargetOptions &Options = DAG.getTarget().Options;
4774 if (Options.UnsafeFPMath &&
4775 VT.isFloatingPoint() && N0.hasOneUse() &&
4776 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
4777 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4778
4779 SDValue FMinMax =
4780 combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), N0.getOperand(1),
4781 N1, N2, CC, TLI, DAG);
4782 if (FMinMax)
4783 return FMinMax;
4784 }
4785
Tom Stellard3787b122014-06-10 16:01:29 +00004786 if ((!LegalOperations &&
4787 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00004788 TLI.isOperationLegal(ISD::SELECT_CC, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004789 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004790 N0.getOperand(0), N0.getOperand(1),
Nate Begeman7e7f4392006-02-01 07:19:44 +00004791 N1, N2, N0.getOperand(2));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004792 return SimplifySelect(SDLoc(N), N0, N1, N2);
Anton Korobeynikov035eaac2008-02-20 11:10:28 +00004793 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004794
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004795 return SDValue();
Nate Begeman24a7eca2005-09-16 00:54:12 +00004796}
4797
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004798static
4799std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4800 SDLoc DL(N);
4801 EVT LoVT, HiVT;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +00004802 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004803
4804 // Split the inputs.
4805 SDValue Lo, Hi, LL, LH, RL, RH;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +00004806 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4807 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
Tom Stellard9cbd2c52013-11-22 00:39:23 +00004808
4809 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4810 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4811
4812 return std::make_pair(Lo, Hi);
4813}
4814
Filipe Cabecinhas82111f12014-05-30 23:03:11 +00004815// This function assumes all the vselect's arguments are CONCAT_VECTOR
4816// nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4817static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4818 SDLoc dl(N);
4819 SDValue Cond = N->getOperand(0);
4820 SDValue LHS = N->getOperand(1);
4821 SDValue RHS = N->getOperand(2);
Benjamin Kramerff8b8832014-08-21 13:28:02 +00004822 EVT VT = N->getValueType(0);
Filipe Cabecinhas82111f12014-05-30 23:03:11 +00004823 int NumElems = VT.getVectorNumElements();
4824 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4825 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4826 Cond.getOpcode() == ISD::BUILD_VECTOR);
4827
Benjamin Kramerff8b8832014-08-21 13:28:02 +00004828 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
4829 // binary ones here.
4830 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
4831 return SDValue();
4832
Filipe Cabecinhas82111f12014-05-30 23:03:11 +00004833 // We're sure we have an even number of elements due to the
4834 // concat_vectors we have as arguments to vselect.
4835 // Skip BV elements until we find one that's not an UNDEF
4836 // After we find an UNDEF element, keep looping until we get to half the
4837 // length of the BV and see if all the non-undef nodes are the same.
4838 ConstantSDNode *BottomHalf = nullptr;
4839 for (int i = 0; i < NumElems / 2; ++i) {
4840 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4841 continue;
4842
4843 if (BottomHalf == nullptr)
4844 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4845 else if (Cond->getOperand(i).getNode() != BottomHalf)
4846 return SDValue();
4847 }
4848
4849 // Do the same for the second half of the BuildVector
4850 ConstantSDNode *TopHalf = nullptr;
4851 for (int i = NumElems / 2; i < NumElems; ++i) {
4852 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4853 continue;
4854
4855 if (TopHalf == nullptr)
4856 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4857 else if (Cond->getOperand(i).getNode() != TopHalf)
4858 return SDValue();
4859 }
4860
4861 assert(TopHalf && BottomHalf &&
4862 "One half of the selector was all UNDEFs and the other was all the "
4863 "same value. This should have been addressed before this function.");
4864 return DAG.getNode(
4865 ISD::CONCAT_VECTORS, dl, VT,
4866 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4867 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4868}
4869
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00004870SDValue DAGCombiner::visitMSTORE(SDNode *N) {
4871
4872 if (Level >= AfterLegalizeTypes)
4873 return SDValue();
4874
4875 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
4876 SDValue Mask = MST->getMask();
Elena Demikhovsky150d9f32015-01-22 12:07:59 +00004877 SDValue Data = MST->getValue();
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00004878 SDLoc DL(N);
4879
4880 // If the MSTORE data type requires splitting and the mask is provided by a
4881 // SETCC, then split both nodes and its operands before legalization. This
4882 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4883 // and enables future optimizations (e.g. min/max pattern matching on X86).
4884 if (Mask.getOpcode() == ISD::SETCC) {
4885
4886 // Check if any splitting is required.
4887 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
4888 TargetLowering::TypeSplitVector)
4889 return SDValue();
4890
4891 SDValue MaskLo, MaskHi, Lo, Hi;
4892 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
4893
4894 EVT LoVT, HiVT;
4895 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
4896
4897 SDValue Chain = MST->getChain();
4898 SDValue Ptr = MST->getBasePtr();
4899
4900 EVT MemoryVT = MST->getMemoryVT();
4901 unsigned Alignment = MST->getOriginalAlignment();
4902
4903 // if Alignment is equal to the vector size,
4904 // take the half of it for the second part
4905 unsigned SecondHalfAlignment =
4906 (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
4907 Alignment/2 : Alignment;
4908
4909 EVT LoMemVT, HiMemVT;
4910 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
4911
4912 SDValue DataLo, DataHi;
4913 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
4914
4915 MachineMemOperand *MMO = DAG.getMachineFunction().
4916 getMachineMemOperand(MST->getPointerInfo(),
4917 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
4918 Alignment, MST->getAAInfo(), MST->getRanges());
4919
Elena Demikhovsky150d9f32015-01-22 12:07:59 +00004920 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
4921 MST->isTruncatingStore());
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00004922
4923 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
4924 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4925 DAG.getConstant(IncrementSize, Ptr.getValueType()));
4926
4927 MMO = DAG.getMachineFunction().
4928 getMachineMemOperand(MST->getPointerInfo(),
4929 MachineMemOperand::MOStore, HiMemVT.getStoreSize(),
4930 SecondHalfAlignment, MST->getAAInfo(),
4931 MST->getRanges());
4932
Elena Demikhovsky150d9f32015-01-22 12:07:59 +00004933 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
4934 MST->isTruncatingStore());
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00004935
4936 AddToWorklist(Lo.getNode());
4937 AddToWorklist(Hi.getNode());
4938
4939 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
4940 }
4941 return SDValue();
4942}
4943
4944SDValue DAGCombiner::visitMLOAD(SDNode *N) {
4945
4946 if (Level >= AfterLegalizeTypes)
4947 return SDValue();
4948
4949 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
4950 SDValue Mask = MLD->getMask();
4951 SDLoc DL(N);
4952
4953 // If the MLOAD result requires splitting and the mask is provided by a
4954 // SETCC, then split both nodes and its operands before legalization. This
4955 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4956 // and enables future optimizations (e.g. min/max pattern matching on X86).
4957
4958 if (Mask.getOpcode() == ISD::SETCC) {
4959 EVT VT = N->getValueType(0);
4960
4961 // Check if any splitting is required.
4962 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4963 TargetLowering::TypeSplitVector)
4964 return SDValue();
4965
4966 SDValue MaskLo, MaskHi, Lo, Hi;
4967 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
4968
4969 SDValue Src0 = MLD->getSrc0();
4970 SDValue Src0Lo, Src0Hi;
4971 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
4972
4973 EVT LoVT, HiVT;
4974 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
4975
4976 SDValue Chain = MLD->getChain();
4977 SDValue Ptr = MLD->getBasePtr();
4978 EVT MemoryVT = MLD->getMemoryVT();
4979 unsigned Alignment = MLD->getOriginalAlignment();
4980
4981 // if Alignment is equal to the vector size,
4982 // take the half of it for the second part
4983 unsigned SecondHalfAlignment =
4984 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
4985 Alignment/2 : Alignment;
4986
4987 EVT LoMemVT, HiMemVT;
4988 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
4989
4990 MachineMemOperand *MMO = DAG.getMachineFunction().
4991 getMachineMemOperand(MLD->getPointerInfo(),
4992 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
4993 Alignment, MLD->getAAInfo(), MLD->getRanges());
4994
Elena Demikhovsky150d9f32015-01-22 12:07:59 +00004995 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
4996 ISD::NON_EXTLOAD);
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00004997
4998 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
4999 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5000 DAG.getConstant(IncrementSize, Ptr.getValueType()));
5001
5002 MMO = DAG.getMachineFunction().
5003 getMachineMemOperand(MLD->getPointerInfo(),
5004 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(),
5005 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5006
Elena Demikhovsky150d9f32015-01-22 12:07:59 +00005007 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5008 ISD::NON_EXTLOAD);
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00005009
5010 AddToWorklist(Lo.getNode());
5011 AddToWorklist(Hi.getNode());
5012
5013 // Build a factor node to remember that this load is independent of the
5014 // other one.
5015 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5016 Hi.getValue(1));
5017
5018 // Legalized the chain result - switch anything that used the old chain to
5019 // use the new one.
5020 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5021
5022 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5023
5024 SDValue RetOps[] = { LoadRes, Chain };
5025 return DAG.getMergeValues(RetOps, DL);
5026 }
5027 return SDValue();
5028}
5029
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00005030SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5031 SDValue N0 = N->getOperand(0);
5032 SDValue N1 = N->getOperand(1);
5033 SDValue N2 = N->getOperand(2);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005034 SDLoc DL(N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00005035
5036 // Canonicalize integer abs.
5037 // vselect (setg[te] X, 0), X, -X ->
5038 // vselect (setgt X, -1), X, -X ->
5039 // vselect (setl[te] X, 0), -X, X ->
5040 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5041 if (N0.getOpcode() == ISD::SETCC) {
5042 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5043 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5044 bool isAbs = false;
5045 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5046
5047 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5048 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5049 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5050 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5051 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5052 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5053 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5054
5055 if (isAbs) {
5056 EVT VT = LHS.getValueType();
5057 SDValue Shift = DAG.getNode(
5058 ISD::SRA, DL, VT, LHS,
5059 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
5060 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005061 AddToWorklist(Shift.getNode());
5062 AddToWorklist(Add.getNode());
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00005063 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5064 }
5065 }
5066
Tom Stellard9cbd2c52013-11-22 00:39:23 +00005067 // If the VSELECT result requires splitting and the mask is provided by a
5068 // SETCC, then split both nodes and its operands before legalization. This
5069 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5070 // and enables future optimizations (e.g. min/max pattern matching on X86).
5071 if (N0.getOpcode() == ISD::SETCC) {
5072 EVT VT = N->getValueType(0);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00005073
Tom Stellard9cbd2c52013-11-22 00:39:23 +00005074 // Check if any splitting is required.
5075 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5076 TargetLowering::TypeSplitVector)
5077 return SDValue();
Juergen Ributzka34c652d2013-11-13 01:57:54 +00005078
Tom Stellard9cbd2c52013-11-22 00:39:23 +00005079 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +00005080 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5081 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5082 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00005083
Tom Stellard9cbd2c52013-11-22 00:39:23 +00005084 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5085 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00005086
Tom Stellard9cbd2c52013-11-22 00:39:23 +00005087 // Add the new VSELECT nodes to the work list in case they need to be split
5088 // again.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005089 AddToWorklist(Lo.getNode());
5090 AddToWorklist(Hi.getNode());
Tom Stellard9cbd2c52013-11-22 00:39:23 +00005091
5092 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00005093 }
5094
Andrea Di Biagio23df4e42014-01-08 18:33:04 +00005095 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5096 if (ISD::isBuildVectorAllOnes(N0.getNode()))
5097 return N1;
5098 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5099 if (ISD::isBuildVectorAllZeros(N0.getNode()))
5100 return N2;
5101
Filipe Cabecinhas82111f12014-05-30 23:03:11 +00005102 // The ConvertSelectToConcatVector function is assuming both the above
5103 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5104 // and addressed.
5105 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5106 N2.getOpcode() == ISD::CONCAT_VECTORS &&
5107 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5108 SDValue CV = ConvertSelectToConcatVector(N, DAG);
5109 if (CV.getNode())
5110 return CV;
5111 }
5112
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00005113 return SDValue();
5114}
5115
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005116SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5117 SDValue N0 = N->getOperand(0);
5118 SDValue N1 = N->getOperand(1);
5119 SDValue N2 = N->getOperand(2);
5120 SDValue N3 = N->getOperand(3);
5121 SDValue N4 = N->getOperand(4);
Nate Begemanc760f802005-09-19 22:34:01 +00005122 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
Scott Michelcf0da6c2009-02-17 22:15:04 +00005123
Nate Begemanc760f802005-09-19 22:34:01 +00005124 // fold select_cc lhs, rhs, x, x, cc -> x
5125 if (N2 == N3)
5126 return N2;
Scott Michelcf0da6c2009-02-17 22:15:04 +00005127
Chris Lattner8b68dec2006-09-20 06:19:26 +00005128 // Determine if the condition we're dealing with is constant
Matt Arsenault758659232013-05-18 00:21:46 +00005129 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005130 N0, N1, CC, SDLoc(N), false);
Stephen Lin605207f2013-06-15 04:03:33 +00005131 if (SCC.getNode()) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005132 AddToWorklist(SCC.getNode());
Chris Lattner8b68dec2006-09-20 06:19:26 +00005133
Stephen Lin605207f2013-06-15 04:03:33 +00005134 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5135 if (!SCCC->isNullValue())
5136 return N2; // cond always true -> true val
5137 else
5138 return N3; // cond always false -> false val
Mehdi Amini648eff12015-01-14 05:45:24 +00005139 } else if (SCC->getOpcode() == ISD::UNDEF) {
5140 // When the condition is UNDEF, just return the first operand. This is
5141 // coherent the DAG creation, no setcc node is created in this case
5142 return N2;
5143 } else if (SCC.getOpcode() == ISD::SETCC) {
5144 // Fold to a simpler select_cc
Stephen Lin605207f2013-06-15 04:03:33 +00005145 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5146 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5147 SCC.getOperand(2));
Mehdi Amini648eff12015-01-14 05:45:24 +00005148 }
Chris Lattner8b68dec2006-09-20 06:19:26 +00005149 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005150
Chris Lattner6c14c352005-10-18 06:04:22 +00005151 // If we can fold this based on the true/false value, do so.
5152 if (SimplifySelectOps(N, N2, N3))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005153 return SDValue(N, 0); // Don't revisit N.
Scott Michelcf0da6c2009-02-17 22:15:04 +00005154
Nate Begemanc760f802005-09-19 22:34:01 +00005155 // fold select_cc into other things, such as min/max/abs
Andrew Trickef9de2a2013-05-25 02:42:55 +00005156 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
Nate Begeman24a7eca2005-09-16 00:54:12 +00005157}
5158
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005159SDValue DAGCombiner::visitSETCC(SDNode *N) {
Nate Begeman24a7eca2005-09-16 00:54:12 +00005160 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
Dale Johannesenf1163e92009-02-03 00:47:48 +00005161 cast<CondCodeSDNode>(N->getOperand(2))->get(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005162 SDLoc(N));
Nate Begeman24a7eca2005-09-16 00:54:12 +00005163}
5164
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005165// tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
5166// dag node into a ConstantSDNode or a build_vector of constants.
5167// This function is called by the DAGCombiner when visiting sext/zext/aext
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00005168// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005169// Vector extends are not folded if operations are legal; this is to
5170// avoid introducing illegal build_vector dag nodes.
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005171static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5172 SelectionDAG &DAG, bool LegalTypes,
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005173 bool LegalOperations) {
5174 unsigned Opcode = N->getOpcode();
5175 SDValue N0 = N->getOperand(0);
5176 EVT VT = N->getValueType(0);
5177
5178 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5179 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
5180
5181 // fold (sext c1) -> c1
5182 // fold (zext c1) -> c1
5183 // fold (aext c1) -> c1
5184 if (isa<ConstantSDNode>(N0))
5185 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5186
5187 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5188 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5189 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005190 EVT SVT = VT.getScalarType();
5191 if (!(VT.isVector() &&
5192 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005193 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
Craig Topperc0196b12014-04-14 00:51:57 +00005194 return nullptr;
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00005195
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005196 // We can fold this node into a build_vector.
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005197 unsigned VTBits = SVT.getSizeInBits();
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005198 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5199 unsigned ShAmt = VTBits - EVTBits;
5200 SmallVector<SDValue, 8> Elts;
5201 unsigned NumElts = N0->getNumOperands();
5202 SDLoc DL(N);
5203
5204 for (unsigned i=0; i != NumElts; ++i) {
5205 SDValue Op = N0->getOperand(i);
5206 if (Op->getOpcode() == ISD::UNDEF) {
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005207 Elts.push_back(DAG.getUNDEF(SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005208 continue;
5209 }
5210
5211 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5212 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5213 if (Opcode == ISD::SIGN_EXTEND)
5214 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005215 SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005216 else
5217 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005218 SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005219 }
5220
Craig Topper48d114b2014-04-26 18:35:24 +00005221 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005222}
5223
Evan Chenge106e2f2007-10-29 19:58:20 +00005224// ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
Dan Gohman0e8d1992009-04-09 03:51:29 +00005225// "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
Evan Chenge106e2f2007-10-29 19:58:20 +00005226// transformation. Returns true if extension are possible and the above
Scott Michelcf0da6c2009-02-17 22:15:04 +00005227// mentioned transformation is profitable.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005228static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
Evan Chenge106e2f2007-10-29 19:58:20 +00005229 unsigned ExtOpc,
Craig Topperb94011f2013-07-14 04:42:23 +00005230 SmallVectorImpl<SDNode *> &ExtendNodes,
Dan Gohman619ef482009-01-15 19:20:50 +00005231 const TargetLowering &TLI) {
Evan Chenge106e2f2007-10-29 19:58:20 +00005232 bool HasCopyToRegUses = false;
5233 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
Gabor Greife12264b2008-08-30 19:29:20 +00005234 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5235 UE = N0.getNode()->use_end();
Evan Chenge106e2f2007-10-29 19:58:20 +00005236 UI != UE; ++UI) {
Dan Gohman91e5dcb2008-07-27 20:43:25 +00005237 SDNode *User = *UI;
Evan Chenge106e2f2007-10-29 19:58:20 +00005238 if (User == N)
5239 continue;
Dan Gohman0e8d1992009-04-09 03:51:29 +00005240 if (UI.getUse().getResNo() != N0.getResNo())
5241 continue;
Evan Chenge106e2f2007-10-29 19:58:20 +00005242 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
Dan Gohman0e8d1992009-04-09 03:51:29 +00005243 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
Evan Chenge106e2f2007-10-29 19:58:20 +00005244 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5245 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5246 // Sign bits will be lost after a zext.
5247 return false;
5248 bool Add = false;
5249 for (unsigned i = 0; i != 2; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005250 SDValue UseOp = User->getOperand(i);
Evan Chenge106e2f2007-10-29 19:58:20 +00005251 if (UseOp == N0)
5252 continue;
5253 if (!isa<ConstantSDNode>(UseOp))
5254 return false;
5255 Add = true;
5256 }
5257 if (Add)
5258 ExtendNodes.push_back(User);
Dan Gohman0e8d1992009-04-09 03:51:29 +00005259 continue;
Evan Chenge106e2f2007-10-29 19:58:20 +00005260 }
Dan Gohman0e8d1992009-04-09 03:51:29 +00005261 // If truncates aren't free and there are users we can't
5262 // extend, it isn't worthwhile.
5263 if (!isTruncFree)
5264 return false;
5265 // Remember if this value is live-out.
5266 if (User->getOpcode() == ISD::CopyToReg)
5267 HasCopyToRegUses = true;
Evan Chenge106e2f2007-10-29 19:58:20 +00005268 }
5269
5270 if (HasCopyToRegUses) {
5271 bool BothLiveOut = false;
5272 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5273 UI != UE; ++UI) {
Dan Gohman0e8d1992009-04-09 03:51:29 +00005274 SDUse &Use = UI.getUse();
5275 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5276 BothLiveOut = true;
5277 break;
Evan Chenge106e2f2007-10-29 19:58:20 +00005278 }
5279 }
5280 if (BothLiveOut)
5281 // Both unextended and extended values are live out. There had better be
Bob Wilsonf9b96c42010-11-28 06:51:19 +00005282 // a good reason for the transformation.
Evan Chenge106e2f2007-10-29 19:58:20 +00005283 return ExtendNodes.size();
5284 }
5285 return true;
5286}
5287
Craig Toppere0b71182013-07-13 07:43:40 +00005288void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
Andrew Trickef9de2a2013-05-25 02:42:55 +00005289 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005290 ISD::NodeType ExtType) {
5291 // Extend SetCC uses if necessary.
5292 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5293 SDNode *SetCC = SetCCs[i];
5294 SmallVector<SDValue, 4> Ops;
5295
5296 for (unsigned j = 0; j != 2; ++j) {
5297 SDValue SOp = SetCC->getOperand(j);
5298 if (SOp == Trunc)
5299 Ops.push_back(ExtLoad);
5300 else
5301 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5302 }
5303
5304 Ops.push_back(SetCC->getOperand(2));
Craig Topper48d114b2014-04-26 18:35:24 +00005305 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005306 }
5307}
5308
Ahmed Bougachae892d132015-02-05 18:31:02 +00005309// FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5310SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5311 SDValue N0 = N->getOperand(0);
5312 EVT DstVT = N->getValueType(0);
5313 EVT SrcVT = N0.getValueType();
5314
5315 assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5316 N->getOpcode() == ISD::ZERO_EXTEND) &&
5317 "Unexpected node type (not an extend)!");
5318
5319 // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5320 // For example, on a target with legal v4i32, but illegal v8i32, turn:
5321 // (v8i32 (sext (v8i16 (load x))))
5322 // into:
5323 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5324 // (v4i32 (sextload (x + 16)))))
5325 // Where uses of the original load, i.e.:
5326 // (v8i16 (load x))
5327 // are replaced with:
5328 // (v8i16 (truncate
5329 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5330 // (v4i32 (sextload (x + 16)))))))
5331 //
5332 // This combine is only applicable to illegal, but splittable, vectors.
5333 // All legal types, and illegal non-vector types, are handled elsewhere.
5334 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5335 //
5336 if (N0->getOpcode() != ISD::LOAD)
5337 return SDValue();
5338
5339 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5340
5341 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5342 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5343 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5344 return SDValue();
5345
5346 SmallVector<SDNode *, 4> SetCCs;
5347 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5348 return SDValue();
5349
5350 ISD::LoadExtType ExtType =
5351 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5352
5353 // Try to split the vector types to get down to legal types.
5354 EVT SplitSrcVT = SrcVT;
5355 EVT SplitDstVT = DstVT;
5356 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5357 SplitSrcVT.getVectorNumElements() > 1) {
5358 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5359 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5360 }
5361
5362 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5363 return SDValue();
5364
5365 SDLoc DL(N);
5366 const unsigned NumSplits =
5367 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5368 const unsigned Stride = SplitSrcVT.getStoreSize();
5369 SmallVector<SDValue, 4> Loads;
5370 SmallVector<SDValue, 4> Chains;
5371
5372 SDValue BasePtr = LN0->getBasePtr();
5373 for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5374 const unsigned Offset = Idx * Stride;
5375 const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5376
5377 SDValue SplitLoad = DAG.getExtLoad(
5378 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5379 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5380 LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5381 Align, LN0->getAAInfo());
5382
5383 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5384 DAG.getConstant(Stride, BasePtr.getValueType()));
5385
5386 Loads.push_back(SplitLoad.getValue(0));
5387 Chains.push_back(SplitLoad.getValue(1));
5388 }
5389
5390 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5391 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5392
5393 CombineTo(N, NewValue);
5394
5395 // Replace uses of the original load (before extension)
5396 // with a truncate of the concatenated sextloaded vectors.
5397 SDValue Trunc =
5398 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5399 CombineTo(N0.getNode(), Trunc, NewChain);
5400 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5401 (ISD::NodeType)N->getOpcode());
5402 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5403}
5404
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005405SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5406 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005407 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00005408
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005409 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5410 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005411 return SDValue(Res, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005412
Nadav Rotem9450fcf2013-01-20 08:35:56 +00005413 // fold (sext (sext x)) -> (sext x)
5414 // fold (sext (aext x)) -> (sext x)
5415 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005416 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
Nadav Rotem9450fcf2013-01-20 08:35:56 +00005417 N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00005418
Chris Lattnerfce448f2007-02-26 03:13:59 +00005419 if (N0.getOpcode() == ISD::TRUNCATE) {
Dan Gohmanc1a4e212008-05-20 20:56:33 +00005420 // fold (sext (truncate (load x))) -> (sext (smaller load x))
5421 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00005422 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5423 if (NarrowLoad.getNode()) {
Dale Johannesenff384ad2010-05-25 17:50:03 +00005424 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5425 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005426 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesenff384ad2010-05-25 17:50:03 +00005427 // CombineTo deleted the truncate, if needed, but not what's under it.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005428 AddToWorklist(oye);
Dale Johannesenff384ad2010-05-25 17:50:03 +00005429 }
Dan Gohmanbe36f5c2009-04-27 02:00:55 +00005430 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00005431 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005432
Dan Gohmanc1a4e212008-05-20 20:56:33 +00005433 // See if the value being truncated is already sign extended. If so, just
5434 // eliminate the trunc/sext pair.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005435 SDValue Op = N0.getOperand(0);
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005436 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
5437 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
5438 unsigned DestBits = VT.getScalarType().getSizeInBits();
Dan Gohman309d3d52007-06-22 14:59:07 +00005439 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005440
Chris Lattnerfce448f2007-02-26 03:13:59 +00005441 if (OpBits == DestBits) {
5442 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
5443 // bits, it is already ready.
5444 if (NumSignBits > DestBits-MidBits)
5445 return Op;
5446 } else if (OpBits < DestBits) {
5447 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
5448 // bits, just sext from i32.
5449 if (NumSignBits > OpBits-MidBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005450 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
Chris Lattnerfce448f2007-02-26 03:13:59 +00005451 } else {
5452 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
5453 // bits, just truncate to i32.
5454 if (NumSignBits > OpBits-MidBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005455 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chris Lattnera31f0a62006-09-21 06:00:20 +00005456 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005457
Chris Lattnerfce448f2007-02-26 03:13:59 +00005458 // fold (sext (truncate x)) -> (sextinreg x).
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005459 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5460 N0.getValueType())) {
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005461 if (OpBits < DestBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005462 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005463 else if (OpBits > DestBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005464 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5465 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005466 DAG.getValueType(N0.getValueType()));
Chris Lattnerfce448f2007-02-26 03:13:59 +00005467 }
Chris Lattnera31f0a62006-09-21 06:00:20 +00005468 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005469
Evan Chengbce7c472005-12-14 02:19:23 +00005470 // fold (sext (load x)) -> (sext (truncate (sextload x)))
Ahmed Bougachae892d132015-02-05 18:31:02 +00005471 // Only generate vector extloads when 1) they're legal, and 2) they are
5472 // deemed desirable by the target.
5473 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5474 ((!LegalOperations && !VT.isVector() &&
5475 !cast<LoadSDNode>(N0)->isVolatile()) ||
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00005476 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
Evan Chenge106e2f2007-10-29 19:58:20 +00005477 bool DoXform = true;
5478 SmallVector<SDNode*, 4> SetCCs;
5479 if (!N0.hasOneUse())
5480 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
Ahmed Bougachae892d132015-02-05 18:31:02 +00005481 if (VT.isVector())
5482 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
Evan Chenge106e2f2007-10-29 19:58:20 +00005483 if (DoXform) {
5484 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005485 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Dan Gohman0e8d1992009-04-09 03:51:29 +00005486 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005487 LN0->getBasePtr(), N0.getValueType(),
5488 LN0->getMemOperand());
Evan Chenge106e2f2007-10-29 19:58:20 +00005489 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005490 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00005491 N0.getValueType(), ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005492 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005493 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005494 ISD::SIGN_EXTEND);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005495 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenge106e2f2007-10-29 19:58:20 +00005496 }
Nate Begeman8caf81d2005-10-12 20:40:40 +00005497 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005498
Ahmed Bougachae892d132015-02-05 18:31:02 +00005499 // fold (sext (load x)) to multiple smaller sextloads.
5500 // Only on illegal but splittable vectors.
5501 if (SDValue ExtLoad = CombineExtLoad(N))
5502 return ExtLoad;
5503
Chris Lattner7dac1082005-12-14 19:05:06 +00005504 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5505 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00005506 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5507 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005508 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00005509 EVT MemVT = LN0->getMemoryVT();
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005510 if ((!LegalOperations && !LN0->isVolatile()) ||
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00005511 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005512 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005513 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005514 LN0->getBasePtr(), MemVT,
5515 LN0->getMemOperand());
Jim Laskey26df19a2006-12-15 21:38:30 +00005516 CombineTo(N, ExtLoad);
Gabor Greife12264b2008-08-30 19:29:20 +00005517 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005518 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00005519 N0.getValueType(), ExtLoad),
Jim Laskey26df19a2006-12-15 21:38:30 +00005520 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005521 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Jim Laskey26df19a2006-12-15 21:38:30 +00005522 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005523 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005524
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005525 // fold (sext (and/or/xor (load x), cst)) ->
5526 // (and/or/xor (sextload x), (sext cst))
5527 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5528 N0.getOpcode() == ISD::XOR) &&
5529 isa<LoadSDNode>(N0.getOperand(0)) &&
5530 N0.getOperand(1).getOpcode() == ISD::Constant &&
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00005531 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005532 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5533 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005534 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005535 bool DoXform = true;
5536 SmallVector<SDNode*, 4> SetCCs;
5537 if (!N0.hasOneUse())
5538 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5539 SetCCs, TLI);
5540 if (DoXform) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005541 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005542 LN0->getChain(), LN0->getBasePtr(),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005543 LN0->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005544 LN0->getMemOperand());
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005545 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5546 Mask = Mask.sext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005547 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005548 ExtLoad, DAG.getConstant(Mask, VT));
5549 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00005550 SDLoc(N0.getOperand(0)),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005551 N0.getOperand(0).getValueType(), ExtLoad);
5552 CombineTo(N, And);
5553 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005554 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005555 ISD::SIGN_EXTEND);
5556 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5557 }
5558 }
5559 }
5560
Chris Lattner65786b02007-04-11 05:32:27 +00005561 if (N0.getOpcode() == ISD::SETCC) {
Daniel Sanderscbd44c52014-07-10 10:18:12 +00005562 EVT N0VT = N0.getOperand(0).getValueType();
Chris Lattner4ac60732009-07-08 00:31:33 +00005563 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
Dan Gohmane82c25e2010-04-30 17:19:19 +00005564 // Only do this before legalize for now.
Owen Anderson2d4cca32013-04-23 18:09:28 +00005565 if (VT.isVector() && !LegalOperations &&
Daniel Sanderscbd44c52014-07-10 10:18:12 +00005566 TLI.getBooleanContents(N0VT) ==
5567 TargetLowering::ZeroOrNegativeOneBooleanContent) {
Nadav Rotem9d376b62012-04-11 08:26:11 +00005568 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5569 // of the same size as the compared operands. Only optimize sext(setcc())
5570 // if this is the case.
Matt Arsenault758659232013-05-18 00:21:46 +00005571 EVT SVT = getSetCCResultType(N0VT);
Nadav Rotem9d376b62012-04-11 08:26:11 +00005572
5573 // We know that the # elements of the results is the same as the
5574 // # elements of the compare (and the # elements of the compare result
5575 // for that matter). Check to see that they are the same size. If so,
5576 // we know that the element size of the sext'd result matches the
5577 // element size of the compare operands.
5578 if (VT.getSizeInBits() == SVT.getSizeInBits())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005579 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005580 N0.getOperand(1),
5581 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Matt Arsenault04126232013-05-17 21:43:43 +00005582
Dan Gohmane82c25e2010-04-30 17:19:19 +00005583 // If the desired elements are smaller or larger than the source
5584 // elements we can use a matching integer vector type and then
5585 // truncate/sign extend
Matt Arsenault04126232013-05-17 21:43:43 +00005586 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
Craig Topper5f9791f2012-09-29 07:18:53 +00005587 if (SVT == MatchingVectorType) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005588 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
Craig Topper5f9791f2012-09-29 07:18:53 +00005589 N0.getOperand(0), N0.getOperand(1),
5590 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005591 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
Dan Gohmane82c25e2010-04-30 17:19:19 +00005592 }
Chris Lattner4ac60732009-07-08 00:31:33 +00005593 }
Dan Gohmane82c25e2010-04-30 17:19:19 +00005594
Matt Arsenault5f2a92a2014-01-27 21:41:54 +00005595 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
Dan Gohman5544b0c2010-04-24 01:17:30 +00005596 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
Dan Gohman5758e1e2009-08-06 09:18:59 +00005597 SDValue NegOne =
Dan Gohman5544b0c2010-04-24 01:17:30 +00005598 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005599 SDValue SCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005600 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Dan Gohman5758e1e2009-08-06 09:18:59 +00005601 NegOne, DAG.getConstant(0, VT),
Chris Lattnera083ffc2007-04-11 06:50:51 +00005602 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005603 if (SCC.getNode()) return SCC;
Matt Arsenault5f2a92a2014-01-27 21:41:54 +00005604
5605 if (!VT.isVector()) {
5606 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5607 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5608 SDLoc DL(N);
5609 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
Hal Finkel98085952014-10-06 20:19:47 +00005610 SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
Matt Arsenault5f2a92a2014-01-27 21:41:54 +00005611 N0.getOperand(0), N0.getOperand(1), CC);
Hal Finkel98085952014-10-06 20:19:47 +00005612 return DAG.getSelect(DL, VT, SetCC,
Matt Arsenault5f2a92a2014-01-27 21:41:54 +00005613 NegOne, DAG.getConstant(0, VT));
Matt Arsenault5f2a92a2014-01-27 21:41:54 +00005614 }
Matt Arsenaultd2f03322013-06-14 22:04:37 +00005615 }
Wesley Peck527da1b2010-11-23 03:31:01 +00005616 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005617
Dan Gohman3eb10f72008-04-28 16:58:24 +00005618 // fold (sext x) -> (zext x) if the sign bit is known zero.
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005619 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
Dan Gohmanc968c1f2008-04-28 18:47:17 +00005620 DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005621 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005622
Evan Chengf1005572010-04-28 07:10:39 +00005623 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00005624}
5625
Rafael Espindola8f62b322012-04-09 16:06:03 +00005626// isTruncateOf - If N is a truncate of some other value, return true, record
5627// the value being truncated in Op and which of Op's bits are zero in KnownZero.
5628// This function computes KnownZero to avoid a duplicated call to
Jay Foada0653a32014-05-14 21:14:37 +00005629// computeKnownBits in the caller.
Rafael Espindola8f62b322012-04-09 16:06:03 +00005630static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5631 APInt &KnownZero) {
5632 APInt KnownOne;
5633 if (N->getOpcode() == ISD::TRUNCATE) {
5634 Op = N->getOperand(0);
Jay Foada0653a32014-05-14 21:14:37 +00005635 DAG.computeKnownBits(Op, KnownZero, KnownOne);
Rafael Espindola8f62b322012-04-09 16:06:03 +00005636 return true;
5637 }
5638
5639 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5640 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5641 return false;
5642
5643 SDValue Op0 = N->getOperand(0);
5644 SDValue Op1 = N->getOperand(1);
5645 assert(Op0.getValueType() == Op1.getValueType());
5646
5647 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5648 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
Rafael Espindola1d9672b2012-04-10 00:16:22 +00005649 if (COp0 && COp0->isNullValue())
Rafael Espindola8f62b322012-04-09 16:06:03 +00005650 Op = Op1;
Rafael Espindola1d9672b2012-04-10 00:16:22 +00005651 else if (COp1 && COp1->isNullValue())
Rafael Espindola8f62b322012-04-09 16:06:03 +00005652 Op = Op0;
5653 else
5654 return false;
5655
Jay Foada0653a32014-05-14 21:14:37 +00005656 DAG.computeKnownBits(Op, KnownZero, KnownOne);
Rafael Espindola8f62b322012-04-09 16:06:03 +00005657
5658 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5659 return false;
5660
5661 return true;
5662}
5663
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005664SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5665 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005666 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00005667
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005668 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5669 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005670 return SDValue(Res, 0);
5671
Nate Begeman21158fc2005-09-01 00:19:25 +00005672 // fold (zext (zext x)) -> (zext x)
Chris Lattner7e7bcf32006-05-06 23:06:26 +00005673 // fold (zext (aext x)) -> (zext x)
5674 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005675 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005676 N0.getOperand(0));
Chris Lattnera31f0a62006-09-21 06:00:20 +00005677
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005678 // fold (zext (truncate x)) -> (zext x) or
5679 // (zext (truncate x)) -> (truncate x)
5680 // This is valid when the truncated bits of x are already zero.
5681 // FIXME: We should extend this to work for vectors too.
Rafael Espindola8f62b322012-04-09 16:06:03 +00005682 SDValue Op;
5683 APInt KnownZero;
5684 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5685 APInt TruncatedBits =
5686 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5687 APInt(Op.getValueSizeInBits(), 0) :
5688 APInt::getBitsSet(Op.getValueSizeInBits(),
5689 N0.getValueSizeInBits(),
5690 std::min(Op.getValueSizeInBits(),
5691 VT.getSizeInBits()));
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00005692 if (TruncatedBits == (KnownZero & TruncatedBits)) {
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005693 if (VT.bitsGT(Op.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005694 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005695 if (VT.bitsLT(Op.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005696 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00005697
5698 return Op;
5699 }
5700 }
5701
Evan Cheng464dc9b2007-03-22 01:54:19 +00005702 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5703 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
Dale Johannesen4bbd2ee2007-03-30 21:38:07 +00005704 if (N0.getOpcode() == ISD::TRUNCATE) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005705 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5706 if (NarrowLoad.getNode()) {
Dale Johannesenff384ad2010-05-25 17:50:03 +00005707 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5708 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005709 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesenff384ad2010-05-25 17:50:03 +00005710 // CombineTo deleted the truncate, if needed, but not what's under it.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005711 AddToWorklist(oye);
Dale Johannesenff384ad2010-05-25 17:50:03 +00005712 }
Eli Friedman55b0acd2011-04-16 23:25:34 +00005713 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00005714 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005715 }
5716
Chris Lattnera31f0a62006-09-21 06:00:20 +00005717 // fold (zext (truncate x)) -> (and x, mask)
5718 if (N0.getOpcode() == ISD::TRUNCATE &&
Dan Gohman600f62b2010-06-24 14:30:44 +00005719 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
Dan Gohman68fb0042010-11-03 01:47:46 +00005720
5721 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5722 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5723 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5724 if (NarrowLoad.getNode()) {
5725 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5726 if (NarrowLoad.getNode() != N0.getNode()) {
5727 CombineTo(N0.getNode(), NarrowLoad);
5728 // CombineTo deleted the truncate, if needed, but not what's under it.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005729 AddToWorklist(oye);
Dan Gohman68fb0042010-11-03 01:47:46 +00005730 }
5731 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5732 }
5733
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005734 SDValue Op = N0.getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00005735 if (Op.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005736 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005737 AddToWorklist(Op.getNode());
Duncan Sands11dd4242008-06-08 20:54:56 +00005738 } else if (Op.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005739 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005740 AddToWorklist(Op.getNode());
Chris Lattnera31f0a62006-09-21 06:00:20 +00005741 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00005742 return DAG.getZeroExtendInReg(Op, SDLoc(N),
Dan Gohman1d459e42009-12-11 21:31:27 +00005743 N0.getValueType().getScalarType());
Chris Lattnera31f0a62006-09-21 06:00:20 +00005744 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005745
Dan Gohmanad3e5492009-04-08 00:15:30 +00005746 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5747 // if either of the casts is not free.
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00005748 if (N0.getOpcode() == ISD::AND &&
5749 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
Dan Gohmanad3e5492009-04-08 00:15:30 +00005750 N0.getOperand(1).getOpcode() == ISD::Constant &&
5751 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5752 N0.getValueType()) ||
5753 !TLI.isZExtFree(N0.getValueType(), VT))) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005754 SDValue X = N0.getOperand(0).getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00005755 if (X.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005756 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
Duncan Sands11dd4242008-06-08 20:54:56 +00005757 } else if (X.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005758 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00005759 }
Dan Gohmane1c4f992008-03-03 23:51:38 +00005760 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00005761 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005762 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005763 X, DAG.getConstant(Mask, VT));
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00005764 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005765
Evan Chengbce7c472005-12-14 02:19:23 +00005766 // fold (zext (load x)) -> (zext (truncate (zextload x)))
Ahmed Bougachae892d132015-02-05 18:31:02 +00005767 // Only generate vector extloads when 1) they're legal, and 2) they are
5768 // deemed desirable by the target.
5769 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5770 ((!LegalOperations && !VT.isVector() &&
5771 !cast<LoadSDNode>(N0)->isVolatile()) ||
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00005772 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
Evan Chenge106e2f2007-10-29 19:58:20 +00005773 bool DoXform = true;
5774 SmallVector<SDNode*, 4> SetCCs;
5775 if (!N0.hasOneUse())
5776 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
Ahmed Bougachae892d132015-02-05 18:31:02 +00005777 if (VT.isVector())
5778 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
Evan Chenge106e2f2007-10-29 19:58:20 +00005779 if (DoXform) {
5780 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005781 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005782 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005783 LN0->getBasePtr(), N0.getValueType(),
5784 LN0->getMemOperand());
Evan Chenge106e2f2007-10-29 19:58:20 +00005785 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005786 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00005787 N0.getValueType(), ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005788 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Bill Wendlingc4093182009-01-30 22:23:15 +00005789
Andrew Trickef9de2a2013-05-25 02:42:55 +00005790 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005791 ISD::ZERO_EXTEND);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005792 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenge106e2f2007-10-29 19:58:20 +00005793 }
Evan Chengbce7c472005-12-14 02:19:23 +00005794 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005795
Ahmed Bougachae892d132015-02-05 18:31:02 +00005796 // fold (zext (load x)) to multiple smaller zextloads.
5797 // Only on illegal but splittable vectors.
5798 if (SDValue ExtLoad = CombineExtLoad(N))
5799 return ExtLoad;
5800
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005801 // fold (zext (and/or/xor (load x), cst)) ->
5802 // (and/or/xor (zextload x), (zext cst))
5803 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5804 N0.getOpcode() == ISD::XOR) &&
5805 isa<LoadSDNode>(N0.getOperand(0)) &&
5806 N0.getOperand(1).getOpcode() == ISD::Constant &&
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00005807 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005808 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5809 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005810 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005811 bool DoXform = true;
5812 SmallVector<SDNode*, 4> SetCCs;
5813 if (!N0.hasOneUse())
5814 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5815 SetCCs, TLI);
5816 if (DoXform) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005817 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005818 LN0->getChain(), LN0->getBasePtr(),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005819 LN0->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005820 LN0->getMemOperand());
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005821 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5822 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005823 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005824 ExtLoad, DAG.getConstant(Mask, VT));
5825 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00005826 SDLoc(N0.getOperand(0)),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005827 N0.getOperand(0).getValueType(), ExtLoad);
5828 CombineTo(N, And);
5829 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005830 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005831 ISD::ZERO_EXTEND);
5832 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5833 }
5834 }
5835 }
5836
Chris Lattner7dac1082005-12-14 19:05:06 +00005837 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5838 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00005839 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5840 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005841 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00005842 EVT MemVT = LN0->getMemoryVT();
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005843 if ((!LegalOperations && !LN0->isVolatile()) ||
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00005844 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005845 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005846 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005847 LN0->getBasePtr(), MemVT,
5848 LN0->getMemOperand());
Duncan Sands8651e9c2008-06-13 19:07:40 +00005849 CombineTo(N, ExtLoad);
Gabor Greife12264b2008-08-30 19:29:20 +00005850 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005851 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
Bill Wendlingc4093182009-01-30 22:23:15 +00005852 ExtLoad),
Duncan Sands8651e9c2008-06-13 19:07:40 +00005853 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005854 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Duncan Sands8651e9c2008-06-13 19:07:40 +00005855 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005856 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005857
Chris Lattner65786b02007-04-11 05:32:27 +00005858 if (N0.getOpcode() == ISD::SETCC) {
Kevin Qinede9ce12013-12-30 02:05:13 +00005859 if (!LegalOperations && VT.isVector() &&
5860 N0.getValueType().getVectorElementType() == MVT::i1) {
Elena Demikhovsky9d56f1e2014-01-22 12:26:19 +00005861 EVT N0VT = N0.getOperand(0).getValueType();
5862 if (getSetCCResultType(N0VT) == N0.getValueType())
5863 return SDValue();
5864
Evan Chengabd0ad52010-05-19 01:08:17 +00005865 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5866 // Only do this before legalize for now.
Evan Chengabd0ad52010-05-19 01:08:17 +00005867 EVT EltVT = VT.getVectorElementType();
5868 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5869 DAG.getConstant(1, EltVT));
Dan Gohman4298df62011-05-17 22:20:36 +00005870 if (VT.getSizeInBits() == N0VT.getSizeInBits())
Evan Chengabd0ad52010-05-19 01:08:17 +00005871 // We know that the # elements of the results is the same as the
5872 // # elements of the compare (and the # elements of the compare result
5873 // for that matter). Check to see that they are the same size. If so,
5874 // we know that the element size of the sext'd result matches the
5875 // element size of the compare operands.
Andrew Trickef9de2a2013-05-25 02:42:55 +00005876 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5877 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Evan Chengabd0ad52010-05-19 01:08:17 +00005878 N0.getOperand(1),
5879 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005880 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
Craig Topper48d114b2014-04-26 18:35:24 +00005881 OneOps));
Dan Gohman4298df62011-05-17 22:20:36 +00005882
5883 // If the desired elements are smaller or larger than the source
5884 // elements we can use a matching integer vector type and then
5885 // truncate/sign extend
5886 EVT MatchingElementType =
5887 EVT::getIntegerVT(*DAG.getContext(),
5888 N0VT.getScalarType().getSizeInBits());
5889 EVT MatchingVectorType =
5890 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5891 N0VT.getVectorNumElements());
5892 SDValue VsetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005893 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
Dan Gohman4298df62011-05-17 22:20:36 +00005894 N0.getOperand(1),
5895 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005896 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5897 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
Craig Topper48d114b2014-04-26 18:35:24 +00005898 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
Evan Chengabd0ad52010-05-19 01:08:17 +00005899 }
5900
5901 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
Scott Michelcf0da6c2009-02-17 22:15:04 +00005902 SDValue SCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00005903 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Chris Lattner65786b02007-04-11 05:32:27 +00005904 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
Chris Lattnera083ffc2007-04-11 06:50:51 +00005905 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005906 if (SCC.getNode()) return SCC;
Chris Lattner65786b02007-04-11 05:32:27 +00005907 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005908
Evan Cheng852c4862009-12-15 03:00:32 +00005909 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
Evan Chengca7c6902009-12-15 00:41:36 +00005910 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
Evan Cheng852c4862009-12-15 03:00:32 +00005911 isa<ConstantSDNode>(N0.getOperand(1)) &&
Evan Chengca7c6902009-12-15 00:41:36 +00005912 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5913 N0.hasOneUse()) {
Chris Lattnere95d1952011-02-13 19:09:16 +00005914 SDValue ShAmt = N0.getOperand(1);
5915 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
Evan Cheng852c4862009-12-15 03:00:32 +00005916 if (N0.getOpcode() == ISD::SHL) {
Chris Lattnere95d1952011-02-13 19:09:16 +00005917 SDValue InnerZExt = N0.getOperand(0);
Evan Cheng852c4862009-12-15 03:00:32 +00005918 // If the original shl may be shifting out bits, do not perform this
5919 // transformation.
Chris Lattnere95d1952011-02-13 19:09:16 +00005920 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5921 InnerZExt.getOperand(0).getValueType().getSizeInBits();
5922 if (ShAmtVal > KnownZeroBits)
Evan Cheng852c4862009-12-15 03:00:32 +00005923 return SDValue();
5924 }
Chris Lattnere95d1952011-02-13 19:09:16 +00005925
Andrew Trickef9de2a2013-05-25 02:42:55 +00005926 SDLoc DL(N);
Owen Andersonb2c80da2011-02-25 21:41:48 +00005927
5928 // Ensure that the shift amount is wide enough for the shifted value.
Chris Lattnere95d1952011-02-13 19:09:16 +00005929 if (VT.getSizeInBits() >= 256)
5930 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
Owen Andersonb2c80da2011-02-25 21:41:48 +00005931
Chris Lattnere95d1952011-02-13 19:09:16 +00005932 return DAG.getNode(N0.getOpcode(), DL, VT,
5933 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5934 ShAmt);
Evan Chengca7c6902009-12-15 00:41:36 +00005935 }
5936
Evan Chengf1005572010-04-28 07:10:39 +00005937 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00005938}
5939
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005940SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5941 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005942 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005943
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005944 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5945 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005946 return SDValue(Res, 0);
5947
Chris Lattner812646a2006-05-05 05:58:59 +00005948 // fold (aext (aext x)) -> (aext x)
5949 // fold (aext (zext x)) -> (zext x)
5950 // fold (aext (sext x)) -> (sext x)
5951 if (N0.getOpcode() == ISD::ANY_EXTEND ||
5952 N0.getOpcode() == ISD::ZERO_EXTEND ||
5953 N0.getOpcode() == ISD::SIGN_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005954 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00005955
Evan Cheng464dc9b2007-03-22 01:54:19 +00005956 // fold (aext (truncate (load x))) -> (aext (smaller load x))
5957 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5958 if (N0.getOpcode() == ISD::TRUNCATE) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005959 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5960 if (NarrowLoad.getNode()) {
Dale Johannesen60fe2cd2010-05-25 18:47:23 +00005961 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5962 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005963 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesen60fe2cd2010-05-25 18:47:23 +00005964 // CombineTo deleted the truncate, if needed, but not what's under it.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005965 AddToWorklist(oye);
Dale Johannesen60fe2cd2010-05-25 18:47:23 +00005966 }
Eli Friedman55b0acd2011-04-16 23:25:34 +00005967 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00005968 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005969 }
5970
Chris Lattner8746e2c2006-09-20 06:29:17 +00005971 // fold (aext (truncate x))
5972 if (N0.getOpcode() == ISD::TRUNCATE) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005973 SDValue TruncOp = N0.getOperand(0);
Chris Lattner8746e2c2006-09-20 06:29:17 +00005974 if (TruncOp.getValueType() == VT)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00005975 return TruncOp; // x iff x size == zext size.
Duncan Sands11dd4242008-06-08 20:54:56 +00005976 if (TruncOp.getValueType().bitsGT(VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005977 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5978 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
Chris Lattner8746e2c2006-09-20 06:29:17 +00005979 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005980
Dan Gohmanad3e5492009-04-08 00:15:30 +00005981 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5982 // if the trunc is not free.
Chris Lattner082db3f2006-09-21 06:40:43 +00005983 if (N0.getOpcode() == ISD::AND &&
5984 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
Dan Gohmanad3e5492009-04-08 00:15:30 +00005985 N0.getOperand(1).getOpcode() == ISD::Constant &&
5986 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5987 N0.getValueType())) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005988 SDValue X = N0.getOperand(0).getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00005989 if (X.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005990 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
Duncan Sands11dd4242008-06-08 20:54:56 +00005991 } else if (X.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005992 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
Chris Lattner082db3f2006-09-21 06:40:43 +00005993 }
Dan Gohmane1c4f992008-03-03 23:51:38 +00005994 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00005995 Mask = Mask.zext(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005996 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendling9b3dc8d2009-01-30 22:27:33 +00005997 X, DAG.getConstant(Mask, VT));
Chris Lattner082db3f2006-09-21 06:40:43 +00005998 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005999
Chris Lattner812646a2006-05-05 05:58:59 +00006000 // fold (aext (load x)) -> (aext (truncate (extload x)))
Nadav Rotem502f1b92011-02-24 21:01:34 +00006001 // None of the supported targets knows how to perform load and any_ext
Nadav Rotemb0091302011-02-27 07:40:43 +00006002 // on vectors in one instruction. We only perform this transformation on
6003 // scalars.
Nadav Rotem502f1b92011-02-24 21:01:34 +00006004 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Quentin Colombet0b1a5582014-04-09 20:03:05 +00006005 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00006006 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
Dan Gohman0e8d1992009-04-09 03:51:29 +00006007 bool DoXform = true;
6008 SmallVector<SDNode*, 4> SetCCs;
6009 if (!N0.hasOneUse())
6010 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6011 if (DoXform) {
6012 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006013 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
Dan Gohman0e8d1992009-04-09 03:51:29 +00006014 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00006015 LN0->getBasePtr(), N0.getValueType(),
6016 LN0->getMemOperand());
Dan Gohman0e8d1992009-04-09 03:51:29 +00006017 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006018 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Dan Gohman0e8d1992009-04-09 03:51:29 +00006019 N0.getValueType(), ExtLoad);
6020 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006021 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00006022 ISD::ANY_EXTEND);
Dan Gohman0e8d1992009-04-09 03:51:29 +00006023 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6024 }
Chris Lattner812646a2006-05-05 05:58:59 +00006025 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006026
Chris Lattner812646a2006-05-05 05:58:59 +00006027 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6028 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6029 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
Evan Cheng8a1d09d2007-03-07 08:07:03 +00006030 if (N0.getOpcode() == ISD::LOAD &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00006031 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Chenge71fe34d2006-10-09 20:57:25 +00006032 N0.hasOneUse()) {
6033 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Matt Arsenaultaaf96232014-04-08 21:40:37 +00006034 ISD::LoadExtType ExtType = LN0->getExtensionType();
Dan Gohman08c0a952009-09-23 21:02:20 +00006035 EVT MemVT = LN0->getMemoryVT();
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00006036 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
Matt Arsenaultaaf96232014-04-08 21:40:37 +00006037 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6038 VT, LN0->getChain(), LN0->getBasePtr(),
6039 MemVT, LN0->getMemOperand());
6040 CombineTo(N, ExtLoad);
6041 CombineTo(N0.getNode(),
6042 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6043 N0.getValueType(), ExtLoad),
6044 ExtLoad.getValue(1));
6045 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6046 }
Chris Lattner812646a2006-05-05 05:58:59 +00006047 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006048
Chris Lattner65786b02007-04-11 05:32:27 +00006049 if (N0.getOpcode() == ISD::SETCC) {
Hao Liuc636d152014-04-22 09:57:06 +00006050 // For vectors:
6051 // aext(setcc) -> vsetcc
6052 // aext(setcc) -> truncate(vsetcc)
6053 // aext(setcc) -> aext(vsetcc)
Evan Chengabd0ad52010-05-19 01:08:17 +00006054 // Only do this before legalize for now.
6055 if (VT.isVector() && !LegalOperations) {
6056 EVT N0VT = N0.getOperand(0).getValueType();
6057 // We know that the # elements of the results is the same as the
6058 // # elements of the compare (and the # elements of the compare result
6059 // for that matter). Check to see that they are the same size. If so,
6060 // we know that the element size of the sext'd result matches the
6061 // element size of the compare operands.
6062 if (VT.getSizeInBits() == N0VT.getSizeInBits())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006063 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00006064 N0.getOperand(1),
6065 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Evan Chengabd0ad52010-05-19 01:08:17 +00006066 // If the desired elements are smaller or larger than the source
6067 // elements we can use a matching integer vector type and then
Hao Liuc636d152014-04-22 09:57:06 +00006068 // truncate/any extend
Evan Chengabd0ad52010-05-19 01:08:17 +00006069 else {
Hao Liuc636d152014-04-22 09:57:06 +00006070 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
Duncan Sands41b4a6b2010-07-12 08:16:59 +00006071 SDValue VsetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00006072 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00006073 N0.getOperand(1),
6074 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Hao Liuc636d152014-04-22 09:57:06 +00006075 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
Evan Chengabd0ad52010-05-19 01:08:17 +00006076 }
6077 }
6078
6079 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
Scott Michelcf0da6c2009-02-17 22:15:04 +00006080 SDValue SCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00006081 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
Chris Lattnera083ffc2007-04-11 06:50:51 +00006082 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
Chris Lattner18e4ac42007-04-11 16:51:53 +00006083 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006084 if (SCC.getNode())
Chris Lattnerc5f85d32007-04-11 06:43:25 +00006085 return SCC;
Chris Lattner65786b02007-04-11 05:32:27 +00006086 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006087
Evan Chengf1005572010-04-28 07:10:39 +00006088 return SDValue();
Chris Lattner812646a2006-05-05 05:58:59 +00006089}
6090
Sanjay Patel50cbfc52014-08-28 16:29:51 +00006091/// See if the specified operand can be simplified with the knowledge that only
6092/// the bits specified by Mask are used. If so, return the simpler operand,
6093/// otherwise return a null SDValue.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006094SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
Chris Lattner5e6fe052007-10-13 06:35:54 +00006095 switch (V.getOpcode()) {
6096 default: break;
Lang Hamesb85fcd02011-11-08 18:56:23 +00006097 case ISD::Constant: {
6098 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
Craig Topperc0196b12014-04-14 00:51:57 +00006099 assert(CV && "Const value should be ConstSDNode.");
Lang Hamesb85fcd02011-11-08 18:56:23 +00006100 const APInt &CVal = CV->getAPIntValue();
6101 APInt NewVal = CVal & Mask;
Stephen Lin8e8424e2013-07-09 00:44:49 +00006102 if (NewVal != CVal)
Lang Hamesb85fcd02011-11-08 18:56:23 +00006103 return DAG.getConstant(NewVal, V.getValueType());
Lang Hamesb85fcd02011-11-08 18:56:23 +00006104 break;
6105 }
Chris Lattner5e6fe052007-10-13 06:35:54 +00006106 case ISD::OR:
6107 case ISD::XOR:
6108 // If the LHS or RHS don't contribute bits to the or, drop them.
6109 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6110 return V.getOperand(1);
6111 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6112 return V.getOperand(0);
6113 break;
Chris Lattnerf47e3062007-10-13 06:58:48 +00006114 case ISD::SRL:
6115 // Only look at single-use SRLs.
Gabor Greiff304a7a2008-08-28 21:40:38 +00006116 if (!V.getNode()->hasOneUse())
Chris Lattnerf47e3062007-10-13 06:58:48 +00006117 break;
6118 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
6119 // See if we can recursively simplify the LHS.
Dan Gohmaneffb8942008-09-12 16:56:44 +00006120 unsigned Amt = RHSC->getZExtValue();
Bill Wendling7bfa43b2009-01-30 22:33:24 +00006121
Dan Gohmanb9fa1d22009-01-03 19:22:06 +00006122 // Watch out for shift count overflow though.
6123 if (Amt >= Mask.getBitWidth()) break;
Dan Gohman1f372ed2008-02-25 21:11:39 +00006124 APInt NewMask = Mask << Amt;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006125 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
Bill Wendling7bfa43b2009-01-30 22:33:24 +00006126 if (SimplifyLHS.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006127 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
Chris Lattnerf47e3062007-10-13 06:58:48 +00006128 SimplifyLHS, V.getOperand(1));
Chris Lattnerf47e3062007-10-13 06:58:48 +00006129 }
Chris Lattner5e6fe052007-10-13 06:35:54 +00006130 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006131 return SDValue();
Chris Lattner5e6fe052007-10-13 06:35:54 +00006132}
6133
Sanjay Patel50cbfc52014-08-28 16:29:51 +00006134/// If the result of a wider load is shifted to right of N bits and then
6135/// truncated to a narrower type and where N is a multiple of number of bits of
6136/// the narrower type, transform it to a narrower load from address + N / num of
6137/// bits of new type. If the result is to be extended, also fold the extension
6138/// to form a extending load.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006139SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
Evan Cheng464dc9b2007-03-22 01:54:19 +00006140 unsigned Opc = N->getOpcode();
Dan Gohman600f62b2010-06-24 14:30:44 +00006141
Evan Cheng464dc9b2007-03-22 01:54:19 +00006142 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006143 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006144 EVT VT = N->getValueType(0);
6145 EVT ExtVT = VT;
Evan Cheng464dc9b2007-03-22 01:54:19 +00006146
Dan Gohman550c9af2008-08-14 20:04:46 +00006147 // This transformation isn't valid for vector loads.
6148 if (VT.isVector())
6149 return SDValue();
6150
Dan Gohman6bd3ef82010-01-09 02:13:55 +00006151 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
Evan Chenga883b582007-03-23 22:13:36 +00006152 // extended to VT.
Evan Cheng464dc9b2007-03-22 01:54:19 +00006153 if (Opc == ISD::SIGN_EXTEND_INREG) {
6154 ExtType = ISD::SEXTLOAD;
Owen Anderson53aa7a92009-08-10 22:56:29 +00006155 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
Dan Gohman600f62b2010-06-24 14:30:44 +00006156 } else if (Opc == ISD::SRL) {
Chris Lattner2a7ff992010-12-21 18:05:22 +00006157 // Another special-case: SRL is basically zero-extending a narrower value.
Dan Gohman600f62b2010-06-24 14:30:44 +00006158 ExtType = ISD::ZEXTLOAD;
6159 N0 = SDValue(N, 0);
6160 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6161 if (!N01) return SDValue();
6162 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6163 VT.getSizeInBits() - N01->getZExtValue());
Evan Cheng464dc9b2007-03-22 01:54:19 +00006164 }
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00006165 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
Richard Osborne272e0842011-01-31 17:41:44 +00006166 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00006167
Owen Anderson53aa7a92009-08-10 22:56:29 +00006168 unsigned EVTBits = ExtVT.getSizeInBits();
Owen Andersonb2c80da2011-02-25 21:41:48 +00006169
Chris Lattner9a499e92010-12-22 08:01:44 +00006170 // Do not generate loads of non-round integer types since these can
6171 // be expensive (and would be wrong if the type is not byte sized).
6172 if (!ExtVT.isRound())
6173 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00006174
Evan Cheng464dc9b2007-03-22 01:54:19 +00006175 unsigned ShAmt = 0;
Chris Lattner9a499e92010-12-22 08:01:44 +00006176 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
Evan Cheng464dc9b2007-03-22 01:54:19 +00006177 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00006178 ShAmt = N01->getZExtValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00006179 // Is the shift amount a multiple of size of VT?
6180 if ((ShAmt & (EVTBits-1)) == 0) {
6181 N0 = N0.getOperand(0);
Eli Friedman1e008c12009-08-19 08:46:10 +00006182 // Is the load width a multiple of size of VT?
6183 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006184 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00006185 }
Wesley Peck527da1b2010-11-23 03:31:01 +00006186
Chris Lattnercafc1e62010-12-22 08:02:57 +00006187 // At this point, we must have a load or else we can't do the transform.
6188 if (!isa<LoadSDNode>(N0)) return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00006189
Chandler Carruthb27041c2012-12-11 00:36:57 +00006190 // Because a SRL must be assumed to *need* to zero-extend the high bits
6191 // (as opposed to anyext the high bits), we can't combine the zextload
6192 // lowering of SRL and an sextload.
6193 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6194 return SDValue();
6195
Chris Lattnera2050552010-10-01 05:36:09 +00006196 // If the shift amount is larger than the input type then we're not
6197 // accessing any of the loaded bytes. If the load was a zextload/extload
6198 // then the result of the shift+trunc is zero/undef (handled elsewhere).
Chris Lattnercafc1e62010-12-22 08:02:57 +00006199 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
Chris Lattnera2050552010-10-01 05:36:09 +00006200 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00006201 }
6202 }
6203
Dan Gohman68fb0042010-11-03 01:47:46 +00006204 // If the load is shifted left (and the result isn't shifted back right),
6205 // we can fold the truncate through the shift.
6206 unsigned ShLeftAmt = 0;
6207 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
Chris Lattner222374d2010-12-22 07:36:50 +00006208 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
Dan Gohman68fb0042010-11-03 01:47:46 +00006209 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6210 ShLeftAmt = N01->getZExtValue();
6211 N0 = N0.getOperand(0);
6212 }
6213 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00006214
Chris Lattner222374d2010-12-22 07:36:50 +00006215 // If we haven't found a load, we can't narrow it. Don't transform one with
6216 // multiple uses, this would require adding a new load.
Bill Schmidtd006c692013-01-14 22:04:38 +00006217 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6218 return SDValue();
6219
6220 // Don't change the width of a volatile load.
6221 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6222 if (LN0->isVolatile())
Chris Lattner222374d2010-12-22 07:36:50 +00006223 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00006224
Chris Lattner9a499e92010-12-22 08:01:44 +00006225 // Verify that we are actually reducing a load width here.
Bill Schmidtd006c692013-01-14 22:04:38 +00006226 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
Chris Lattner222374d2010-12-22 07:36:50 +00006227 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00006228
Bill Schmidtd006c692013-01-14 22:04:38 +00006229 // For the transform to be legal, the load must produce only two values
6230 // (the value loaded and the chain). Don't transform a pre-increment
Stephen Lincfe7f352013-07-08 00:37:03 +00006231 // load, for example, which produces an extra value. Otherwise the
Bill Schmidtd006c692013-01-14 22:04:38 +00006232 // transformation is not equivalent, and the downstream logic to replace
6233 // uses gets things wrong.
6234 if (LN0->getNumValues() > 2)
6235 return SDValue();
6236
Benjamin Kramerc7332b22013-07-06 14:05:09 +00006237 // If the load that we're shrinking is an extload and we're not just
6238 // discarding the extension we can't simply shrink the load. Bail.
6239 // TODO: It would be possible to merge the extensions in some cases.
6240 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6241 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6242 return SDValue();
6243
Matt Arsenault810cb622014-12-12 00:00:24 +00006244 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6245 return SDValue();
6246
Chris Lattner222374d2010-12-22 07:36:50 +00006247 EVT PtrType = N0.getOperand(1).getValueType();
Bill Wendling7bfa43b2009-01-30 22:33:24 +00006248
Evan Cheng4c6f9172012-06-26 01:19:33 +00006249 if (PtrType == MVT::Untyped || PtrType.isExtended())
6250 // It's not possible to generate a constant of extended or untyped type.
6251 return SDValue();
6252
Chris Lattner222374d2010-12-22 07:36:50 +00006253 // For big endian targets, we need to adjust the offset to the pointer to
6254 // load the correct bytes.
6255 if (TLI.isBigEndian()) {
6256 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6257 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6258 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
Evan Cheng464dc9b2007-03-22 01:54:19 +00006259 }
6260
Chris Lattner222374d2010-12-22 07:36:50 +00006261 uint64_t PtrOff = ShAmt / 8;
6262 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006263 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
Chris Lattner222374d2010-12-22 07:36:50 +00006264 PtrType, LN0->getBasePtr(),
6265 DAG.getConstant(PtrOff, PtrType));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006266 AddToWorklist(NewPtr.getNode());
Chris Lattner222374d2010-12-22 07:36:50 +00006267
Chris Lattner9a499e92010-12-22 08:01:44 +00006268 SDValue Load;
6269 if (ExtType == ISD::NON_EXTLOAD)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006270 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
Chris Lattner9a499e92010-12-22 08:01:44 +00006271 LN0->getPointerInfo().getWithOffset(PtrOff),
Pete Cooper82cd9e82011-11-08 18:42:53 +00006272 LN0->isVolatile(), LN0->isNonTemporal(),
Hal Finkelcc39b672014-07-24 12:16:19 +00006273 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
Chris Lattner9a499e92010-12-22 08:01:44 +00006274 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00006275 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
Chris Lattner9a499e92010-12-22 08:01:44 +00006276 LN0->getPointerInfo().getWithOffset(PtrOff),
6277 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
Louis Gerbarg67474e32014-07-31 21:45:05 +00006278 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
Chris Lattner222374d2010-12-22 07:36:50 +00006279
6280 // Replace the old load's chain with the new load's chain.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006281 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00006282 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
Chris Lattner222374d2010-12-22 07:36:50 +00006283
6284 // Shift the result left, if we've swallowed a left shift.
6285 SDValue Result = Load;
6286 if (ShLeftAmt != 0) {
Owen Andersonb2c80da2011-02-25 21:41:48 +00006287 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
Chris Lattner222374d2010-12-22 07:36:50 +00006288 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6289 ShImmTy = VT;
Paul Redmond288604e2013-02-12 15:21:21 +00006290 // If the shift amount is as large as the result size (but, presumably,
6291 // no larger than the source) then the useful bits of the result are
6292 // zero; we can't simply return the shortened shift, because the result
6293 // of that operation is undefined.
6294 if (ShLeftAmt >= VT.getSizeInBits())
6295 Result = DAG.getConstant(0, VT);
6296 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00006297 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
Paul Redmond288604e2013-02-12 15:21:21 +00006298 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
Chris Lattner222374d2010-12-22 07:36:50 +00006299 }
6300
6301 // Return the new loaded value.
6302 return Result;
Evan Cheng464dc9b2007-03-22 01:54:19 +00006303}
6304
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006305SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6306 SDValue N0 = N->getOperand(0);
6307 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006308 EVT VT = N->getValueType(0);
6309 EVT EVT = cast<VTSDNode>(N1)->getVT();
Dan Gohman1d459e42009-12-11 21:31:27 +00006310 unsigned VTBits = VT.getScalarType().getSizeInBits();
Dan Gohman6bd3ef82010-01-09 02:13:55 +00006311 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006312
Nate Begeman21158fc2005-09-01 00:19:25 +00006313 // fold (sext_in_reg c1) -> c1
Chris Lattner29062da2006-05-08 20:59:41 +00006314 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006315 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006316
Chris Lattner2a4d7b82006-05-06 22:43:44 +00006317 // If the input is already sign extended, just drop the extension.
Dan Gohman1d459e42009-12-11 21:31:27 +00006318 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
Chris Lattner1ecb2a22006-05-06 09:30:03 +00006319 return N0;
Scott Michelcf0da6c2009-02-17 22:15:04 +00006320
Nate Begeman7cea6ef2005-09-02 21:18:40 +00006321 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6322 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006323 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006324 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00006325 N0.getOperand(0), N1);
Chris Lattner446e1ef2006-05-08 21:18:59 +00006326
Dan Gohman345d63c2008-07-31 00:50:31 +00006327 // fold (sext_in_reg (sext x)) -> (sext x)
6328 // fold (sext_in_reg (aext x)) -> (sext x)
6329 // if x is small enough.
6330 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6331 SDValue N00 = N0.getOperand(0);
Evan Chengf037f872010-04-16 22:26:19 +00006332 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6333 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006334 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
Dan Gohman345d63c2008-07-31 00:50:31 +00006335 }
6336
Chris Lattner9ad59152007-04-17 19:03:21 +00006337 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
Dan Gohman1f372ed2008-02-25 21:11:39 +00006338 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006339 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006340
Chris Lattner9ad59152007-04-17 19:03:21 +00006341 // fold operands of sext_in_reg based on knowledge that the top bits are not
6342 // demanded.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006343 if (SimplifyDemandedBits(SDValue(N, 0)))
6344 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006345
Evan Cheng464dc9b2007-03-22 01:54:19 +00006346 // fold (sext_in_reg (load x)) -> (smaller sextload x)
6347 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006348 SDValue NarrowLoad = ReduceLoadWidth(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006349 if (NarrowLoad.getNode())
Evan Cheng464dc9b2007-03-22 01:54:19 +00006350 return NarrowLoad;
6351
Bill Wendling7bfa43b2009-01-30 22:33:24 +00006352 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00006353 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
Chris Lattner446e1ef2006-05-08 21:18:59 +00006354 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6355 if (N0.getOpcode() == ISD::SRL) {
6356 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
Dan Gohman1d459e42009-12-11 21:31:27 +00006357 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00006358 // We can turn this into an SRA iff the input to the SRL is already sign
Chris Lattner446e1ef2006-05-08 21:18:59 +00006359 // extended enough.
Dan Gohman309d3d52007-06-22 14:59:07 +00006360 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
Dan Gohman1d459e42009-12-11 21:31:27 +00006361 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006362 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00006363 N0.getOperand(0), N0.getOperand(1));
Chris Lattner446e1ef2006-05-08 21:18:59 +00006364 }
6365 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00006366
Nate Begeman02b23c62005-10-13 03:11:28 +00006367 // fold (sext_inreg (extload x)) -> (sextload x)
Scott Michelcf0da6c2009-02-17 22:15:04 +00006368 if (ISD::isEXTLoad(N0.getNode()) &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00006369 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Dan Gohman47a7d6f2008-01-30 00:15:11 +00006370 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006371 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00006372 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00006373 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006374 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00006375 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00006376 LN0->getBasePtr(), EVT,
6377 LN0->getMemOperand());
Chris Lattnerd39c60f2005-12-14 19:25:30 +00006378 CombineTo(N, ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006379 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006380 AddToWorklist(ExtLoad.getNode());
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006381 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00006382 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00006383 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
Gabor Greiff304a7a2008-08-28 21:40:38 +00006384 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Cheng8a1d09d2007-03-07 08:07:03 +00006385 N0.hasOneUse() &&
Dan Gohman47a7d6f2008-01-30 00:15:11 +00006386 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006387 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00006388 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00006389 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006390 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00006391 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00006392 LN0->getBasePtr(), EVT,
6393 LN0->getMemOperand());
Chris Lattnerd39c60f2005-12-14 19:25:30 +00006394 CombineTo(N, ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006395 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006396 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00006397 }
Evan Cheng4c0bd962011-06-21 06:01:08 +00006398
6399 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6400 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6401 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6402 N0.getOperand(1), false);
Craig Topperc0196b12014-04-14 00:51:57 +00006403 if (BSwap.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006404 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Evan Cheng4c0bd962011-06-21 06:01:08 +00006405 BSwap, N1);
6406 }
6407
Andrea Di Biagio46dcddb2013-12-27 20:20:28 +00006408 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6409 // into a build_vector.
6410 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6411 SmallVector<SDValue, 8> Elts;
6412 unsigned NumElts = N0->getNumOperands();
6413 unsigned ShAmt = VTBits - EVTBits;
6414
6415 for (unsigned i = 0; i != NumElts; ++i) {
6416 SDValue Op = N0->getOperand(i);
6417 if (Op->getOpcode() == ISD::UNDEF) {
6418 Elts.push_back(Op);
6419 continue;
6420 }
6421
6422 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
Kevin Qin5cd73c92014-01-06 02:26:10 +00006423 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6424 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
Andrea Di Biagio46dcddb2013-12-27 20:20:28 +00006425 Op.getValueType()));
6426 }
6427
Craig Topper48d114b2014-04-26 18:35:24 +00006428 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
Andrea Di Biagio46dcddb2013-12-27 20:20:28 +00006429 }
6430
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006431 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00006432}
6433
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006434SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6435 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006436 EVT VT = N->getValueType(0);
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006437 bool isLE = TLI.isLittleEndian();
Nate Begeman21158fc2005-09-01 00:19:25 +00006438
6439 // noop truncate
6440 if (N0.getValueType() == N->getValueType(0))
Nate Begemand23739d2005-09-06 04:43:02 +00006441 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00006442 // fold (truncate c1) -> c1
Chris Lattner7e7bcf32006-05-06 23:06:26 +00006443 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006444 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00006445 // fold (truncate (truncate x)) -> (truncate x)
6446 if (N0.getOpcode() == ISD::TRUNCATE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006447 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
Nate Begeman21158fc2005-09-01 00:19:25 +00006448 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
Chris Lattner6855d622010-04-07 18:13:33 +00006449 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6450 N0.getOpcode() == ISD::SIGN_EXTEND ||
Chris Lattner907e3922006-05-05 22:56:26 +00006451 N0.getOpcode() == ISD::ANY_EXTEND) {
Duncan Sands11dd4242008-06-08 20:54:56 +00006452 if (N0.getOperand(0).getValueType().bitsLT(VT))
Nate Begeman21158fc2005-09-01 00:19:25 +00006453 // if the source is smaller than the dest, we still need an extend
Andrew Trickef9de2a2013-05-25 02:42:55 +00006454 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006455 N0.getOperand(0));
Craig Topper5f9791f2012-09-29 07:18:53 +00006456 if (N0.getOperand(0).getValueType().bitsGT(VT))
Nate Begeman21158fc2005-09-01 00:19:25 +00006457 // if the source is larger than the dest, than we just need the truncate
Andrew Trickef9de2a2013-05-25 02:42:55 +00006458 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
Craig Topper5f9791f2012-09-29 07:18:53 +00006459 // if the source and dest are the same type, we can drop both the extend
6460 // and the truncate.
6461 return N0.getOperand(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00006462 }
Evan Chengd63baea2007-03-21 20:14:05 +00006463
Nadav Rotem4f4546b2012-02-05 11:39:23 +00006464 // Fold extract-and-trunc into a narrow extract. For example:
6465 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6466 // i32 y = TRUNCATE(i64 x)
6467 // -- becomes --
6468 // v16i8 b = BITCAST (v2i64 val)
6469 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6470 //
6471 // Note: We only run this optimization after type legalization (which often
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006472 // creates this pattern) and before operation legalization after which
6473 // we need to be more careful about the vector instructions that we generate.
6474 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
Hal Finkelab51ecd2014-02-28 00:26:45 +00006475 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006476
6477 EVT VecTy = N0.getOperand(0).getValueType();
6478 EVT ExTy = N0.getValueType();
6479 EVT TrTy = N->getValueType(0);
6480
6481 unsigned NumElem = VecTy.getVectorNumElements();
6482 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6483
6484 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6485 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6486
6487 SDValue EltNo = N0->getOperand(1);
6488 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6489 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Tom Stellardd42c5942013-08-05 22:22:01 +00006490 EVT IndexTy = TLI.getVectorIdxTy();
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006491 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6492
Andrew Trickef9de2a2013-05-25 02:42:55 +00006493 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006494 NVT, N0.getOperand(0));
6495
6496 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
Andrew Trickef9de2a2013-05-25 02:42:55 +00006497 SDLoc(N), TrTy, V,
Jim Grosbach92f6adc2012-05-08 20:56:07 +00006498 DAG.getConstant(Index, IndexTy));
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006499 }
6500 }
6501
Matt Arsenault3332b702014-07-10 18:21:04 +00006502 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6503 if (N0.getOpcode() == ISD::SELECT) {
6504 EVT SrcVT = N0.getValueType();
6505 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6506 TLI.isTruncateFree(SrcVT, VT)) {
6507 SDLoc SL(N0);
6508 SDValue Cond = N0.getOperand(0);
6509 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6510 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6511 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6512 }
6513 }
6514
Arnold Schwaighofer3f9568e2013-02-20 21:33:32 +00006515 // Fold a series of buildvector, bitcast, and truncate if possible.
6516 // For example fold
6517 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6518 // (2xi32 (buildvector x, y)).
6519 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6520 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6521 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6522 N0.getOperand(0).hasOneUse()) {
6523
6524 SDValue BuildVect = N0.getOperand(0);
6525 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6526 EVT TruncVecEltTy = VT.getVectorElementType();
6527
6528 // Check that the element types match.
6529 if (BuildVectEltTy == TruncVecEltTy) {
6530 // Now we only need to compute the offset of the truncated elements.
6531 unsigned BuildVecNumElts = BuildVect.getNumOperands();
6532 unsigned TruncVecNumElts = VT.getVectorNumElements();
6533 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6534
6535 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6536 "Invalid number of elements");
6537
6538 SmallVector<SDValue, 8> Opnds;
6539 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6540 Opnds.push_back(BuildVect.getOperand(i));
6541
Craig Topper48d114b2014-04-26 18:35:24 +00006542 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
Arnold Schwaighofer3f9568e2013-02-20 21:33:32 +00006543 }
6544 }
6545
Chris Lattner5e6fe052007-10-13 06:35:54 +00006546 // See if we can simplify the input to this truncate through knowledge that
Nadav Rotem502f1b92011-02-24 21:01:34 +00006547 // only the low bits are being used.
6548 // For example "trunc (or (shl x, 8), y)" // -> trunc y
Nadav Rotemb0091302011-02-27 07:40:43 +00006549 // Currently we only perform this optimization on scalars because vectors
Nadav Rotem502f1b92011-02-24 21:01:34 +00006550 // may have different active low bits.
6551 if (!VT.isVector()) {
6552 SDValue Shorter =
6553 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6554 VT.getSizeInBits()));
6555 if (Shorter.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006556 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
Nadav Rotem502f1b92011-02-24 21:01:34 +00006557 }
Nate Begeman8caf81d2005-10-12 20:40:40 +00006558 // fold (truncate (load x)) -> (smaller load x)
Evan Chengd63baea2007-03-21 20:14:05 +00006559 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
Dan Gohman600f62b2010-06-24 14:30:44 +00006560 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6561 SDValue Reduced = ReduceLoadWidth(N);
6562 if (Reduced.getNode())
6563 return Reduced;
Richard Sandifordd1093632013-12-11 11:37:27 +00006564 // Handle the case where the load remains an extending load even
6565 // after truncation.
6566 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6567 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6568 if (!LN0->isVolatile() &&
6569 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6570 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6571 VT, LN0->getChain(), LN0->getBasePtr(),
6572 LN0->getMemoryVT(),
6573 LN0->getMemOperand());
6574 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6575 return NewLoad;
6576 }
6577 }
Dan Gohman600f62b2010-06-24 14:30:44 +00006578 }
Michael Liao3ac82012012-10-17 23:45:54 +00006579 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6580 // where ... are all 'undef'.
6581 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6582 SmallVector<EVT, 8> VTs;
6583 SDValue V;
6584 unsigned Idx = 0;
6585 unsigned NumDefs = 0;
6586
6587 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6588 SDValue X = N0.getOperand(i);
6589 if (X.getOpcode() != ISD::UNDEF) {
6590 V = X;
6591 Idx = i;
6592 NumDefs++;
6593 }
6594 // Stop if more than one members are non-undef.
6595 if (NumDefs > 1)
6596 break;
6597 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6598 VT.getVectorElementType(),
6599 X.getValueType().getVectorNumElements()));
6600 }
6601
6602 if (NumDefs == 0)
6603 return DAG.getUNDEF(VT);
6604
6605 if (NumDefs == 1) {
6606 assert(V.getNode() && "The single defined operand is empty!");
6607 SmallVector<SDValue, 8> Opnds;
6608 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6609 if (i != Idx) {
6610 Opnds.push_back(DAG.getUNDEF(VTs[i]));
6611 continue;
6612 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00006613 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006614 AddToWorklist(NV.getNode());
Michael Liao3ac82012012-10-17 23:45:54 +00006615 Opnds.push_back(NV);
6616 }
Craig Topper48d114b2014-04-26 18:35:24 +00006617 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
Michael Liao3ac82012012-10-17 23:45:54 +00006618 }
6619 }
Dan Gohman600f62b2010-06-24 14:30:44 +00006620
6621 // Simplify the operands using demanded-bits information.
6622 if (!VT.isVector() &&
6623 SimplifyDemandedBits(SDValue(N, 0)))
6624 return SDValue(N, 0);
6625
Evan Chengf1bd5fc2010-04-17 06:13:15 +00006626 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00006627}
6628
Evan Chengb980f6f2008-05-12 23:04:07 +00006629static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006630 SDValue Elt = N->getOperand(i);
Evan Chengb980f6f2008-05-12 23:04:07 +00006631 if (Elt.getOpcode() != ISD::MERGE_VALUES)
Gabor Greiff304a7a2008-08-28 21:40:38 +00006632 return Elt.getNode();
6633 return Elt.getOperand(Elt.getResNo()).getNode();
Evan Chengb980f6f2008-05-12 23:04:07 +00006634}
6635
Sanjay Patel50cbfc52014-08-28 16:29:51 +00006636/// build_pair (load, load) -> load
Scott Michelcf0da6c2009-02-17 22:15:04 +00006637/// if load locations are consecutive.
Owen Anderson53aa7a92009-08-10 22:56:29 +00006638SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
Evan Chengb980f6f2008-05-12 23:04:07 +00006639 assert(N->getOpcode() == ISD::BUILD_PAIR);
6640
Nate Begeman624690c2009-06-05 21:37:30 +00006641 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6642 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
Chris Lattnerf72c3c02010-09-21 16:08:50 +00006643 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
Matt Arsenault58a76392014-02-24 21:01:15 +00006644 LD1->getAddressSpace() != LD2->getAddressSpace())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006645 return SDValue();
Owen Anderson53aa7a92009-08-10 22:56:29 +00006646 EVT LD1VT = LD1->getValueType(0);
Bill Wendling4e0a6152009-01-30 22:44:24 +00006647
Evan Chengb980f6f2008-05-12 23:04:07 +00006648 if (ISD::isNON_EXTLoad(LD2) &&
6649 LD2->hasOneUse() &&
Duncan Sands8651e9c2008-06-13 19:07:40 +00006650 // If both are volatile this would reduce the number of volatile loads.
6651 // If one is volatile it might be ok, but play conservative and bail out.
Nate Begeman624690c2009-06-05 21:37:30 +00006652 !LD1->isVolatile() &&
6653 !LD2->isVolatile() &&
Evan Chengf5938d52009-12-09 01:36:00 +00006654 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
Nate Begeman624690c2009-06-05 21:37:30 +00006655 unsigned Align = LD1->getAlignment();
Micah Villmowcdfe20b2012-10-08 16:38:25 +00006656 unsigned NewAlign = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +00006657 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
Bill Wendling4e0a6152009-01-30 22:44:24 +00006658
Duncan Sands8651e9c2008-06-13 19:07:40 +00006659 if (NewAlign <= Align &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006660 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006661 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
Chris Lattnerf72c3c02010-09-21 16:08:50 +00006662 LD1->getBasePtr(), LD1->getPointerInfo(),
Pete Cooper82cd9e82011-11-08 18:42:53 +00006663 false, false, false, Align);
Evan Chengb980f6f2008-05-12 23:04:07 +00006664 }
Bill Wendling4e0a6152009-01-30 22:44:24 +00006665
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006666 return SDValue();
Evan Chengb980f6f2008-05-12 23:04:07 +00006667}
6668
Wesley Peck527da1b2010-11-23 03:31:01 +00006669SDValue DAGCombiner::visitBITCAST(SDNode *N) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006670 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006671 EVT VT = N->getValueType(0);
Chris Lattnera1874602005-12-23 05:30:37 +00006672
Dan Gohmana8665142007-06-25 16:23:39 +00006673 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6674 // Only do this before legalize, since afterward the target may be depending
6675 // on the bitconvert.
6676 // First check to see if this is all constant.
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006677 if (!LegalTypes &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00006678 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
Duncan Sands13237ac2008-06-06 12:08:01 +00006679 VT.isVector()) {
Juergen Ributzka73844052014-01-13 20:51:35 +00006680 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006681
Owen Anderson53aa7a92009-08-10 22:56:29 +00006682 EVT DestEltVT = N->getValueType(0).getVectorElementType();
Duncan Sands13237ac2008-06-06 12:08:01 +00006683 assert(!DestEltVT.isVector() &&
Dan Gohmana8665142007-06-25 16:23:39 +00006684 "Element type of vector ValueType must not be vector!");
Bill Wendling4e0a6152009-01-30 22:44:24 +00006685 if (isSimple)
Wesley Peck527da1b2010-11-23 03:31:01 +00006686 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
Dan Gohmana8665142007-06-25 16:23:39 +00006687 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006688
Dan Gohman921ddd62008-09-05 01:58:21 +00006689 // If the input is a constant, let getNode fold it.
Chris Lattnera1874602005-12-23 05:30:37 +00006690 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
Chandler Carruthb65d61a2015-02-10 02:25:56 +00006691 // If we can't allow illegal operations, we need to check that this is just
6692 // a fp -> int or int -> conversion and that the resulting operation will
6693 // be legal.
6694 if (!LegalOperations ||
6695 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
6696 TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
6697 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
6698 TLI.isOperationLegal(ISD::Constant, VT)))
6699 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
Chris Lattnera1874602005-12-23 05:30:37 +00006700 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006701
Bill Wendling4e0a6152009-01-30 22:44:24 +00006702 // (conv (conv x, t1), t2) -> (conv x, t2)
Wesley Peck527da1b2010-11-23 03:31:01 +00006703 if (N0.getOpcode() == ISD::BITCAST)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006704 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006705 N0.getOperand(0));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006706
Chris Lattner54560f62005-12-23 05:44:41 +00006707 // fold (conv (load x)) -> (load (conv*)x)
Evan Cheng0de312d2007-10-06 08:19:55 +00006708 // If the resultant load doesn't need a higher alignment than the original!
Gabor Greiff304a7a2008-08-28 21:40:38 +00006709 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Duncan Sands8651e9c2008-06-13 19:07:40 +00006710 // Do not change the width of a volatile load.
6711 !cast<LoadSDNode>(N0)->isVolatile() &&
Ulrich Weigandf236bb12014-07-03 15:06:47 +00006712 // Do not remove the cast if the types differ in endian layout.
6713 TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6714 TLI.hasBigEndianPartOrdering(VT) &&
Matt Arsenaultc5559bb2013-11-15 04:42:23 +00006715 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6716 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00006717 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Micah Villmowcdfe20b2012-10-08 16:38:25 +00006718 unsigned Align = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +00006719 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
Evan Chenga4cf58a2007-05-07 21:27:48 +00006720 unsigned OrigAlign = LN0->getAlignment();
Bill Wendling4e0a6152009-01-30 22:44:24 +00006721
Evan Chenga4cf58a2007-05-07 21:27:48 +00006722 if (Align <= OrigAlign) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006723 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
Chris Lattnerf72c3c02010-09-21 16:08:50 +00006724 LN0->getBasePtr(), LN0->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +00006725 LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00006726 LN0->isInvariant(), OrigAlign,
Hal Finkelcc39b672014-07-24 12:16:19 +00006727 LN0->getAAInfo());
Chandler Carruth7cd15be2014-08-14 08:18:34 +00006728 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
Evan Chenga4cf58a2007-05-07 21:27:48 +00006729 return Load;
6730 }
Chris Lattner54560f62005-12-23 05:44:41 +00006731 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00006732
Bill Wendling4e0a6152009-01-30 22:44:24 +00006733 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6734 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
Chris Lattner888560d2008-01-27 17:42:27 +00006735 // This often reduces constant pool loads.
Tom Stellardc54731a2013-07-23 23:55:03 +00006736 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6737 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
Nadav Rotem24a822a2012-09-13 14:54:28 +00006738 N0.getNode()->hasOneUse() && VT.isInteger() &&
6739 !VT.isVector() && !N0.getValueType().isVector()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006740 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006741 N0.getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006742 AddToWorklist(NewConv.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +00006743
Duncan Sands13237ac2008-06-06 12:08:01 +00006744 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
Chris Lattner888560d2008-01-27 17:42:27 +00006745 if (N0.getOpcode() == ISD::FNEG)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006746 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006747 NewConv, DAG.getConstant(SignBit, VT));
Chris Lattner888560d2008-01-27 17:42:27 +00006748 assert(N0.getOpcode() == ISD::FABS);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006749 return DAG.getNode(ISD::AND, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006750 NewConv, DAG.getConstant(~SignBit, VT));
Chris Lattner888560d2008-01-27 17:42:27 +00006751 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006752
Bill Wendling4e0a6152009-01-30 22:44:24 +00006753 // fold (bitconvert (fcopysign cst, x)) ->
6754 // (or (and (bitconvert x), sign), (and cst, (not sign)))
6755 // Note that we don't handle (copysign x, cst) because this can always be
6756 // folded to an fneg or fabs.
Gabor Greiff304a7a2008-08-28 21:40:38 +00006757 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
Chris Lattner2ee91f42008-01-27 23:32:17 +00006758 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
Duncan Sands13237ac2008-06-06 12:08:01 +00006759 VT.isInteger() && !VT.isVector()) {
6760 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
Owen Anderson117c9e82009-08-12 00:36:31 +00006761 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
Chris Lattner4041ab62010-04-15 04:48:01 +00006762 if (isTypeLegal(IntXVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006763 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006764 IntXVT, N0.getOperand(1));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006765 AddToWorklist(X.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00006766
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006767 // If X has a different width than the result/lhs, sext it or truncate it.
6768 unsigned VTWidth = VT.getSizeInBits();
6769 if (OrigXWidth < VTWidth) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006770 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006771 AddToWorklist(X.getNode());
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006772 } else if (OrigXWidth > VTWidth) {
6773 // To get the sign bit in the right place, we have to shift it right
6774 // before truncating.
Andrew Trickef9de2a2013-05-25 02:42:55 +00006775 X = DAG.getNode(ISD::SRL, SDLoc(X),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006776 X.getValueType(), X,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006777 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006778 AddToWorklist(X.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00006779 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006780 AddToWorklist(X.getNode());
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006781 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006782
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006783 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00006784 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006785 X, DAG.getConstant(SignBit, VT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006786 AddToWorklist(X.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00006787
Andrew Trickef9de2a2013-05-25 02:42:55 +00006788 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling4e0a6152009-01-30 22:44:24 +00006789 VT, N0.getOperand(0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006790 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006791 Cst, DAG.getConstant(~SignBit, VT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006792 AddToWorklist(Cst.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00006793
Andrew Trickef9de2a2013-05-25 02:42:55 +00006794 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006795 }
Chris Lattner888560d2008-01-27 17:42:27 +00006796 }
Evan Chengb980f6f2008-05-12 23:04:07 +00006797
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00006798 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
Evan Chengb980f6f2008-05-12 23:04:07 +00006799 if (N0.getOpcode() == ISD::BUILD_PAIR) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00006800 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6801 if (CombineLD.getNode())
Evan Chengb980f6f2008-05-12 23:04:07 +00006802 return CombineLD;
6803 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006804
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006805 return SDValue();
Chris Lattnera1874602005-12-23 05:30:37 +00006806}
6807
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006808SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00006809 EVT VT = N->getValueType(0);
Evan Chengb980f6f2008-05-12 23:04:07 +00006810 return CombineConsecutiveLoads(N, VT);
6811}
6812
Sanjay Patel50cbfc52014-08-28 16:29:51 +00006813/// We know that BV is a build_vector node with Constant, ConstantFP or Undef
6814/// operands. DstEltVT indicates the destination element value type.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006815SDValue DAGCombiner::
Wesley Peck527da1b2010-11-23 03:31:01 +00006816ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00006817 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006818
Chris Lattnere4e64b62006-04-02 02:53:43 +00006819 // If this is already the right type, we're done.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006820 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006821
Duncan Sands13237ac2008-06-06 12:08:01 +00006822 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6823 unsigned DstBitSize = DstEltVT.getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006824
Chris Lattnere4e64b62006-04-02 02:53:43 +00006825 // If this is a conversion of N elements of one type to N elements of another
6826 // type, convert each element. This handles FP<->INT cases.
6827 if (SrcBitSize == DstBitSize) {
Nate Begeman317b9692010-07-27 18:02:18 +00006828 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6829 BV->getValueType(0).getVectorNumElements());
6830
6831 // Due to the FP element handling below calling this routine recursively,
6832 // we can end up with a scalar-to-vector node here.
6833 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006834 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6835 DAG.getNode(ISD::BITCAST, SDLoc(BV),
Nate Begeman317b9692010-07-27 18:02:18 +00006836 DstEltVT, BV->getOperand(0)));
Wesley Peck527da1b2010-11-23 03:31:01 +00006837
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006838 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +00006839 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
Bob Wilson59dbbb22009-04-13 22:05:19 +00006840 SDValue Op = BV->getOperand(i);
6841 // If the vector element type is not legal, the BUILD_VECTOR operands
6842 // are promoted and implicitly truncated. Make that explicit here.
Bob Wilsonda188eb2009-04-20 17:27:09 +00006843 if (Op.getValueType() != SrcEltVT)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006844 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6845 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
Bob Wilson59dbbb22009-04-13 22:05:19 +00006846 DstEltVT, Op));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006847 AddToWorklist(Ops.back().getNode());
Chris Lattner098c01e2006-04-08 04:15:24 +00006848 }
Craig Topper48d114b2014-04-26 18:35:24 +00006849 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006850 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006851
Chris Lattnere4e64b62006-04-02 02:53:43 +00006852 // Otherwise, we're growing or shrinking the elements. To avoid having to
6853 // handle annoying details of growing/shrinking FP values, we convert them to
6854 // int first.
Duncan Sands13237ac2008-06-06 12:08:01 +00006855 if (SrcEltVT.isFloatingPoint()) {
Chris Lattnere4e64b62006-04-02 02:53:43 +00006856 // Convert the input float vector to a int vector where the elements are the
6857 // same sizes.
Owen Anderson117c9e82009-08-12 00:36:31 +00006858 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
Wesley Peck527da1b2010-11-23 03:31:01 +00006859 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
Chris Lattnere4e64b62006-04-02 02:53:43 +00006860 SrcEltVT = IntVT;
6861 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006862
Chris Lattnere4e64b62006-04-02 02:53:43 +00006863 // Now we know the input is an integer vector. If the output is a FP type,
6864 // convert to integer first, then to FP of the right size.
Duncan Sands13237ac2008-06-06 12:08:01 +00006865 if (DstEltVT.isFloatingPoint()) {
Owen Anderson117c9e82009-08-12 00:36:31 +00006866 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
Wesley Peck527da1b2010-11-23 03:31:01 +00006867 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006868
Chris Lattnere4e64b62006-04-02 02:53:43 +00006869 // Next, convert to FP elements of the same size.
Wesley Peck527da1b2010-11-23 03:31:01 +00006870 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006871 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006872
Chris Lattnere4e64b62006-04-02 02:53:43 +00006873 // Okay, we know the src/dst types are both integers of differing types.
6874 // Handling growing first.
Duncan Sands13237ac2008-06-06 12:08:01 +00006875 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
Chris Lattnere4e64b62006-04-02 02:53:43 +00006876 if (SrcBitSize < DstBitSize) {
6877 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
Scott Michelcf0da6c2009-02-17 22:15:04 +00006878
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006879 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +00006880 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
Chris Lattnere4e64b62006-04-02 02:53:43 +00006881 i += NumInputsPerOutput) {
6882 bool isLE = TLI.isLittleEndian();
Dan Gohmane1c4f992008-03-03 23:51:38 +00006883 APInt NewBits = APInt(DstBitSize, 0);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006884 bool EltIsUndef = true;
6885 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6886 // Shift the previously computed bits over.
6887 NewBits <<= SrcBitSize;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006888 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006889 if (Op.getOpcode() == ISD::UNDEF) continue;
6890 EltIsUndef = false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00006891
Jay Foad583abbc2010-12-07 08:25:19 +00006892 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
Dan Gohmanecd40a32010-04-12 02:24:01 +00006893 zextOrTrunc(SrcBitSize).zext(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006894 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006895
Chris Lattnere4e64b62006-04-02 02:53:43 +00006896 if (EltIsUndef)
Dale Johannesen84935752009-02-06 23:05:02 +00006897 Ops.push_back(DAG.getUNDEF(DstEltVT));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006898 else
6899 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6900 }
6901
Owen Anderson117c9e82009-08-12 00:36:31 +00006902 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
Craig Topper48d114b2014-04-26 18:35:24 +00006903 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006904 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006905
Chris Lattnere4e64b62006-04-02 02:53:43 +00006906 // Finally, this must be the case where we are shrinking elements: each input
6907 // turns into multiple outputs.
Evan Cheng6200c222008-02-18 23:04:32 +00006908 bool isS2V = ISD::isScalarToVector(BV);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006909 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
Owen Anderson117c9e82009-08-12 00:36:31 +00006910 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6911 NumOutputsPerInput*BV->getNumOperands());
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006912 SmallVector<SDValue, 8> Ops;
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006913
Dan Gohmana8665142007-06-25 16:23:39 +00006914 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
Chris Lattnere4e64b62006-04-02 02:53:43 +00006915 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6916 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
Dale Johannesen84935752009-02-06 23:05:02 +00006917 Ops.push_back(DAG.getUNDEF(DstEltVT));
Chris Lattnere4e64b62006-04-02 02:53:43 +00006918 continue;
6919 }
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006920
Jay Foad583abbc2010-12-07 08:25:19 +00006921 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6922 getAPIntValue().zextOrTrunc(SrcBitSize);
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006923
Chris Lattnere4e64b62006-04-02 02:53:43 +00006924 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
Jay Foad583abbc2010-12-07 08:25:19 +00006925 APInt ThisVal = OpVal.trunc(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006926 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
Jay Foad583abbc2010-12-07 08:25:19 +00006927 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
Evan Cheng6200c222008-02-18 23:04:32 +00006928 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
Andrew Trickef9de2a2013-05-25 02:42:55 +00006929 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006930 Ops[0]);
Dan Gohmane1c4f992008-03-03 23:51:38 +00006931 OpVal = OpVal.lshr(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006932 }
6933
6934 // For big endian targets, swap the order of the pieces of each element.
Duncan Sands7377f5f2008-02-11 10:37:04 +00006935 if (TLI.isBigEndian())
Chris Lattnere4e64b62006-04-02 02:53:43 +00006936 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6937 }
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006938
Craig Topper48d114b2014-04-26 18:35:24 +00006939 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
Chris Lattnere4e64b62006-04-02 02:53:43 +00006940}
6941
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006942SDValue DAGCombiner::visitFADD(SDNode *N) {
6943 SDValue N0 = N->getOperand(0);
6944 SDValue N1 = N->getOperand(1);
Nate Begeman418c6e42005-10-18 00:28:13 +00006945 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6946 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006947 EVT VT = N->getValueType(0);
Sanjay Patel78614bf2014-08-28 15:53:16 +00006948 const TargetOptions &Options = DAG.getTarget().Options;
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00006949
Dan Gohmana8665142007-06-25 16:23:39 +00006950 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00006951 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006952 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006953 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00006954 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006955
Lang Hamesa33db652012-06-14 20:37:15 +00006956 // fold (fadd c1, c2) -> c1 + c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00006957 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006958 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
Sanjay Patel8170dea2014-09-08 17:32:19 +00006959
Nate Begeman418c6e42005-10-18 00:28:13 +00006960 // canonicalize constant to RHS
6961 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006962 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
Sanjay Patel8170dea2014-09-08 17:32:19 +00006963
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006964 // fold (fadd A, (fneg B)) -> (fsub A, B)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006965 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
Sanjay Patel8170dea2014-09-08 17:32:19 +00006966 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006967 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006968 GetNegatedExpression(N1, DAG, LegalOperations));
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00006969
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00006970 // fold (fadd (fneg A), B) -> (fsub B, A)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00006971 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
Sanjay Patel8170dea2014-09-08 17:32:19 +00006972 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006973 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006974 GetNegatedExpression(N0, DAG, LegalOperations));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006975
Sanjay Patel8170dea2014-09-08 17:32:19 +00006976 // If 'unsafe math' is enabled, fold lots of things.
6977 if (Options.UnsafeFPMath) {
6978 // No FP constant should be created after legalization as Instruction
6979 // Selection pass has a hard time dealing with FP constants.
6980 bool AllowNewConst = (Level < AfterLegalizeDAG);
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00006981
Sanjay Patel8170dea2014-09-08 17:32:19 +00006982 // fold (fadd A, 0) -> A
6983 if (N1CFP && N1CFP->getValueAPF().isZero())
6984 return N0;
Scott Michelcf0da6c2009-02-17 22:15:04 +00006985
Sanjay Patel8170dea2014-09-08 17:32:19 +00006986 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6987 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6988 isa<ConstantFPSDNode>(N0.getOperand(1)))
6989 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6990 DAG.getNode(ISD::FADD, SDLoc(N), VT,
6991 N0.getOperand(1), N1));
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00006992
Sanjay Patel8170dea2014-09-08 17:32:19 +00006993 // If allowed, fold (fadd (fneg x), x) -> 0.0
6994 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6995 return DAG.getConstantFP(0.0, VT);
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00006996
Sanjay Patel8170dea2014-09-08 17:32:19 +00006997 // If allowed, fold (fadd x, (fneg x)) -> 0.0
6998 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6999 return DAG.getConstantFP(0.0, VT);
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007000
Sanjay Patel8170dea2014-09-08 17:32:19 +00007001 // We can fold chains of FADD's of the same value into multiplications.
7002 // This transform is not safe in general because we are reducing the number
7003 // of rounding steps.
Sanjay Patel8170dea2014-09-08 17:32:19 +00007004 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
7005 if (N0.getOpcode() == ISD::FMUL) {
7006 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7007 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007008
Sanjay Patel8170dea2014-09-08 17:32:19 +00007009 // (fadd (fmul x, c), x) -> (fmul x, c+1)
7010 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
7011 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7012 SDValue(CFP01, 0),
7013 DAG.getConstantFP(1.0, VT));
7014 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, NewCFP);
7015 }
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007016
Sanjay Patel8170dea2014-09-08 17:32:19 +00007017 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
7018 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
7019 N1.getOperand(0) == N1.getOperand(1) &&
7020 N0.getOperand(0) == N1.getOperand(0)) {
7021 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7022 SDValue(CFP01, 0),
7023 DAG.getConstantFP(2.0, VT));
7024 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7025 N0.getOperand(0), NewCFP);
7026 }
Owen Andersoncc61f872012-08-30 23:35:16 +00007027 }
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007028
Sanjay Patel8170dea2014-09-08 17:32:19 +00007029 if (N1.getOpcode() == ISD::FMUL) {
7030 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7031 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007032
Sanjay Patel8170dea2014-09-08 17:32:19 +00007033 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
7034 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
7035 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7036 SDValue(CFP11, 0),
7037 DAG.getConstantFP(1.0, VT));
7038 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, NewCFP);
7039 }
Sanjay Patelf4b7a6b2014-09-08 18:22:51 +00007040
Sanjay Patel8170dea2014-09-08 17:32:19 +00007041 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
7042 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
7043 N0.getOperand(0) == N0.getOperand(1) &&
7044 N1.getOperand(0) == N0.getOperand(0)) {
7045 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
7046 SDValue(CFP11, 0),
7047 DAG.getConstantFP(2.0, VT));
7048 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1.getOperand(0), NewCFP);
7049 }
Owen Andersoncc61f872012-08-30 23:35:16 +00007050 }
Sanjay Patelf4b7a6b2014-09-08 18:22:51 +00007051
Sanjay Patel8170dea2014-09-08 17:32:19 +00007052 if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
7053 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7054 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
7055 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
7056 (N0.getOperand(0) == N1))
7057 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7058 N1, DAG.getConstantFP(3.0, VT));
Owen Andersoncc61f872012-08-30 23:35:16 +00007059 }
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007060
Sanjay Patel8170dea2014-09-08 17:32:19 +00007061 if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
7062 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7063 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
7064 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
7065 N1.getOperand(0) == N0)
7066 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7067 N0, DAG.getConstantFP(3.0, VT));
Owen Andersoncc61f872012-08-30 23:35:16 +00007068 }
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007069
Sanjay Patel8170dea2014-09-08 17:32:19 +00007070 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
7071 if (AllowNewConst &&
7072 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
Stephen Line31f2d22013-06-14 18:17:35 +00007073 N0.getOperand(0) == N0.getOperand(1) &&
Sanjay Patel8170dea2014-09-08 17:32:19 +00007074 N1.getOperand(0) == N1.getOperand(1) &&
7075 N0.getOperand(0) == N1.getOperand(0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007076 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Sanjay Patel8170dea2014-09-08 17:32:19 +00007077 N0.getOperand(0), DAG.getConstantFP(4.0, VT));
Owen Andersoncc61f872012-08-30 23:35:16 +00007078 }
Sanjay Patel8170dea2014-09-08 17:32:19 +00007079 } // enable-unsafe-fp-math
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007080
Lang Hames39fb1d02012-06-19 22:51:23 +00007081 // FADD -> FMA combines:
Sanjay Patel78614bf2014-08-28 15:53:16 +00007082 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
Eric Christopherf55d4712014-10-08 23:38:39 +00007083 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
Stephen Lin73de7bf2013-07-09 18:16:56 +00007084 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
Lang Hames39fb1d02012-06-19 22:51:23 +00007085
7086 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
Hal Finkel62ac7362014-09-19 11:42:56 +00007087 if (N0.getOpcode() == ISD::FMUL &&
7088 (N0->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007089 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00007090 N0.getOperand(0), N0.getOperand(1), N1);
Owen Andersoncc61f872012-08-30 23:35:16 +00007091
Michael Liaoec3850122012-09-01 04:09:16 +00007092 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
Lang Hames39fb1d02012-06-19 22:51:23 +00007093 // Note: Commutes FADD operands.
Hal Finkel62ac7362014-09-19 11:42:56 +00007094 if (N1.getOpcode() == ISD::FMUL &&
7095 (N1->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007096 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00007097 N1.getOperand(0), N1.getOperand(1), N0);
Olivier Sallenave04515322015-01-07 20:54:17 +00007098
Olivier Sallenave32509692015-01-13 15:06:36 +00007099 // When FP_EXTEND nodes are free on the target, and there is an opportunity
7100 // to combine into FMA, arrange such nodes accordingly.
7101 if (TLI.isFPExtFree(VT)) {
7102
7103 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7104 if (N0.getOpcode() == ISD::FP_EXTEND) {
7105 SDValue N00 = N0.getOperand(0);
7106 if (N00.getOpcode() == ISD::FMUL)
7107 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7108 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7109 N00.getOperand(0)),
7110 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7111 N00.getOperand(1)), N1);
7112 }
7113
7114 // fold (fadd x, (fpext (fmul y, z)), z) -> (fma (fpext y), (fpext z), x)
7115 // Note: Commutes FADD operands.
7116 if (N1.getOpcode() == ISD::FP_EXTEND) {
7117 SDValue N10 = N1.getOperand(0);
7118 if (N10.getOpcode() == ISD::FMUL)
7119 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7120 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7121 N10.getOperand(0)),
7122 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7123 N10.getOperand(1)), N0);
7124 }
7125 }
7126
Hal Finkel33ead6f2015-01-09 00:45:54 +00007127 // More folding opportunities when target permits.
7128 if (TLI.enableAggressiveFMAFusion(VT)) {
Olivier Sallenave32509692015-01-13 15:06:36 +00007129
Hal Finkel33ead6f2015-01-09 00:45:54 +00007130 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7131 if (N0.getOpcode() == ISD::FMA &&
7132 N0.getOperand(2).getOpcode() == ISD::FMUL)
Olivier Sallenave04515322015-01-07 20:54:17 +00007133 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
Hal Finkel33ead6f2015-01-09 00:45:54 +00007134 N0.getOperand(0), N0.getOperand(1),
7135 DAG.getNode(ISD::FMA, SDLoc(N), VT,
7136 N0.getOperand(2).getOperand(0),
7137 N0.getOperand(2).getOperand(1),
7138 N1));
Olivier Sallenave04515322015-01-07 20:54:17 +00007139
Hal Finkel33ead6f2015-01-09 00:45:54 +00007140 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7141 if (N1->getOpcode() == ISD::FMA &&
7142 N1.getOperand(2).getOpcode() == ISD::FMUL)
Olivier Sallenave04515322015-01-07 20:54:17 +00007143 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
Hal Finkel33ead6f2015-01-09 00:45:54 +00007144 N1.getOperand(0), N1.getOperand(1),
7145 DAG.getNode(ISD::FMA, SDLoc(N), VT,
7146 N1.getOperand(2).getOperand(0),
7147 N1.getOperand(2).getOperand(1),
7148 N0));
Olivier Sallenave04515322015-01-07 20:54:17 +00007149 }
7150 }
7151
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007152 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00007153}
7154
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007155SDValue DAGCombiner::visitFSUB(SDNode *N) {
7156 SDValue N0 = N->getOperand(0);
7157 SDValue N1 = N->getOperand(1);
Sanjay Patel75cc90e2014-09-05 22:26:22 +00007158 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7159 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007160 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007161 SDLoc dl(N);
Sanjay Patel78614bf2014-08-28 15:53:16 +00007162 const TargetOptions &Options = DAG.getTarget().Options;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007163
Dan Gohmana8665142007-06-25 16:23:39 +00007164 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00007165 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007166 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00007167 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00007168 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007169
Nate Begeman418c6e42005-10-18 00:28:13 +00007170 // fold (fsub c1, c2) -> c1-c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007171 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007172 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
Sanjay Patelae402a32014-08-27 20:57:52 +00007173
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00007174 // fold (fsub A, (fneg B)) -> (fadd A, B)
Sanjay Patel78614bf2014-08-28 15:53:16 +00007175 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00007176 return DAG.getNode(ISD::FADD, dl, VT, N0,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007177 GetNegatedExpression(N1, DAG, LegalOperations));
Scott Michelcf0da6c2009-02-17 22:15:04 +00007178
Sanjay Patelae402a32014-08-27 20:57:52 +00007179 // If 'unsafe math' is enabled, fold lots of things.
Sanjay Patel78614bf2014-08-28 15:53:16 +00007180 if (Options.UnsafeFPMath) {
Sanjay Patelae402a32014-08-27 20:57:52 +00007181 // (fsub A, 0) -> A
7182 if (N1CFP && N1CFP->getValueAPF().isZero())
7183 return N0;
7184
7185 // (fsub 0, B) -> -B
7186 if (N0CFP && N0CFP->getValueAPF().isZero()) {
Sanjay Patel78614bf2014-08-28 15:53:16 +00007187 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
Sanjay Patelae402a32014-08-27 20:57:52 +00007188 return GetNegatedExpression(N1, DAG, LegalOperations);
7189 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7190 return DAG.getNode(ISD::FNEG, dl, VT, N1);
7191 }
7192
7193 // (fsub x, x) -> 0.0
Owen Andersonab63d842012-05-07 20:51:25 +00007194 if (N0 == N1)
7195 return DAG.getConstantFP(0.0f, VT);
7196
Sanjay Patelae402a32014-08-27 20:57:52 +00007197 // (fsub x, (fadd x, y)) -> (fneg y)
7198 // (fsub x, (fadd y, x)) -> (fneg y)
Bill Wendlingdf170db2012-03-15 05:12:00 +00007199 if (N1.getOpcode() == ISD::FADD) {
7200 SDValue N10 = N1->getOperand(0);
7201 SDValue N11 = N1->getOperand(1);
7202
Sanjay Patel78614bf2014-08-28 15:53:16 +00007203 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
Bill Wendlingdf170db2012-03-15 05:12:00 +00007204 return GetNegatedExpression(N11, DAG, LegalOperations);
Stephen Lin10947502013-07-10 20:47:39 +00007205
Sanjay Patel78614bf2014-08-28 15:53:16 +00007206 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
Bill Wendlingdf170db2012-03-15 05:12:00 +00007207 return GetNegatedExpression(N10, DAG, LegalOperations);
7208 }
7209 }
7210
Lang Hames39fb1d02012-06-19 22:51:23 +00007211 // FSUB -> FMA combines:
Sanjay Patel78614bf2014-08-28 15:53:16 +00007212 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
Eric Christopherf55d4712014-10-08 23:38:39 +00007213 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
Stephen Lin73de7bf2013-07-09 18:16:56 +00007214 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
Lang Hames39fb1d02012-06-19 22:51:23 +00007215
7216 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
Hal Finkel62ac7362014-09-19 11:42:56 +00007217 if (N0.getOpcode() == ISD::FMUL &&
7218 (N0->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00007219 return DAG.getNode(ISD::FMA, dl, VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00007220 N0.getOperand(0), N0.getOperand(1),
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00007221 DAG.getNode(ISD::FNEG, dl, VT, N1));
Lang Hames39fb1d02012-06-19 22:51:23 +00007222
7223 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7224 // Note: Commutes FSUB operands.
Hal Finkel62ac7362014-09-19 11:42:56 +00007225 if (N1.getOpcode() == ISD::FMUL &&
7226 (N1->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00007227 return DAG.getNode(ISD::FMA, dl, VT,
7228 DAG.getNode(ISD::FNEG, dl, VT,
Lang Hames39fb1d02012-06-19 22:51:23 +00007229 N1.getOperand(0)),
7230 N1.getOperand(1), N0);
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00007231
Stephen Lin8e8424e2013-07-09 00:44:49 +00007232 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
Stephen Lincfe7f352013-07-08 00:37:03 +00007233 if (N0.getOpcode() == ISD::FNEG &&
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00007234 N0.getOperand(0).getOpcode() == ISD::FMUL &&
Hal Finkel62ac7362014-09-19 11:42:56 +00007235 ((N0->hasOneUse() && N0.getOperand(0).hasOneUse()) ||
7236 TLI.enableAggressiveFMAFusion(VT))) {
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00007237 SDValue N00 = N0.getOperand(0).getOperand(0);
7238 SDValue N01 = N0.getOperand(0).getOperand(1);
7239 return DAG.getNode(ISD::FMA, dl, VT,
7240 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
7241 DAG.getNode(ISD::FNEG, dl, VT, N1));
7242 }
Olivier Sallenave04515322015-01-07 20:54:17 +00007243
Olivier Sallenave32509692015-01-13 15:06:36 +00007244 // When FP_EXTEND nodes are free on the target, and there is an opportunity
7245 // to combine into FMA, arrange such nodes accordingly.
7246 if (TLI.isFPExtFree(VT)) {
7247
7248 // fold (fsub (fpext (fmul x, y)), z)
7249 // -> (fma (fpext x), (fpext y), (fneg z))
7250 if (N0.getOpcode() == ISD::FP_EXTEND) {
7251 SDValue N00 = N0.getOperand(0);
7252 if (N00.getOpcode() == ISD::FMUL)
7253 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7254 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7255 N00.getOperand(0)),
7256 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7257 N00.getOperand(1)),
7258 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N1));
7259 }
7260
7261 // fold (fsub x, (fpext (fmul y, z)))
7262 // -> (fma (fneg (fpext y)), (fpext z), x)
7263 // Note: Commutes FSUB operands.
7264 if (N1.getOpcode() == ISD::FP_EXTEND) {
7265 SDValue N10 = N1.getOperand(0);
7266 if (N10.getOpcode() == ISD::FMUL)
7267 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7268 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7269 DAG.getNode(ISD::FP_EXTEND, SDLoc(N),
7270 VT, N10.getOperand(0))),
7271 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7272 N10.getOperand(1)),
7273 N0);
7274 }
7275
7276 // fold (fsub (fpext (fneg (fmul, x, y))), z)
7277 // -> (fma (fneg (fpext x)), (fpext y), (fneg z))
7278 if (N0.getOpcode() == ISD::FP_EXTEND) {
7279 SDValue N00 = N0.getOperand(0);
7280 if (N00.getOpcode() == ISD::FNEG) {
7281 SDValue N000 = N00.getOperand(0);
7282 if (N000.getOpcode() == ISD::FMUL) {
7283 return DAG.getNode(ISD::FMA, dl, VT,
7284 DAG.getNode(ISD::FNEG, dl, VT,
7285 DAG.getNode(ISD::FP_EXTEND, SDLoc(N),
7286 VT, N000.getOperand(0))),
7287 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7288 N000.getOperand(1)),
7289 DAG.getNode(ISD::FNEG, dl, VT, N1));
7290 }
7291 }
7292 }
7293
7294 // fold (fsub (fneg (fpext (fmul, x, y))), z)
7295 // -> (fma (fneg (fpext x)), (fpext y), (fneg z))
7296 if (N0.getOpcode() == ISD::FNEG) {
7297 SDValue N00 = N0.getOperand(0);
7298 if (N00.getOpcode() == ISD::FP_EXTEND) {
7299 SDValue N000 = N00.getOperand(0);
7300 if (N000.getOpcode() == ISD::FMUL) {
7301 return DAG.getNode(ISD::FMA, dl, VT,
7302 DAG.getNode(ISD::FNEG, dl, VT,
7303 DAG.getNode(ISD::FP_EXTEND, SDLoc(N),
7304 VT, N000.getOperand(0))),
7305 DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7306 N000.getOperand(1)),
7307 DAG.getNode(ISD::FNEG, dl, VT, N1));
7308 }
7309 }
7310 }
7311 }
7312
Olivier Sallenave04515322015-01-07 20:54:17 +00007313 // More folding opportunities when target permits.
7314 if (TLI.enableAggressiveFMAFusion(VT)) {
7315
7316 // fold (fsub (fma x, y, (fmul u, v)), z)
7317 // -> (fma x, y (fma u, v, (fneg z)))
7318 if (N0.getOpcode() == ISD::FMA &&
7319 N0.getOperand(2).getOpcode() == ISD::FMUL)
7320 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7321 N0.getOperand(0), N0.getOperand(1),
7322 DAG.getNode(ISD::FMA, SDLoc(N), VT,
7323 N0.getOperand(2).getOperand(0),
7324 N0.getOperand(2).getOperand(1),
7325 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7326 N1)));
7327
7328 // fold (fsub x, (fma y, z, (fmul u, v)))
7329 // -> (fma (fneg y), z, (fma (fneg u), v, x))
7330 if (N1.getOpcode() == ISD::FMA &&
7331 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7332 SDValue N20 = N1.getOperand(2).getOperand(0);
7333 SDValue N21 = N1.getOperand(2).getOperand(1);
7334 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7335 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7336 N1.getOperand(0)),
7337 N1.getOperand(1),
7338 DAG.getNode(ISD::FMA, SDLoc(N), VT,
7339 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7340 N20),
7341 N21, N0));
7342 }
7343 }
Lang Hames39fb1d02012-06-19 22:51:23 +00007344 }
7345
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007346 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00007347}
7348
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007349SDValue DAGCombiner::visitFMUL(SDNode *N) {
7350 SDValue N0 = N->getOperand(0);
7351 SDValue N1 = N->getOperand(1);
Matt Arsenault6cc00422014-08-16 10:14:19 +00007352 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7353 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007354 EVT VT = N->getValueType(0);
Sanjay Patel78614bf2014-08-28 15:53:16 +00007355 const TargetOptions &Options = DAG.getTarget().Options;
Chris Lattner6f3b5772005-09-28 22:28:18 +00007356
Dan Gohmana8665142007-06-25 16:23:39 +00007357 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00007358 if (VT.isVector()) {
Sanjay Patel7bd228a2014-09-11 15:45:27 +00007359 // This just handles C1 * C2 for vectors. Other vector folds are below.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007360 SDValue FoldedVOp = SimplifyVBinOp(N);
Sanjay Patel7bd228a2014-09-11 15:45:27 +00007361 if (FoldedVOp.getNode())
7362 return FoldedVOp;
7363 // Canonicalize vector constant to RHS.
7364 if (N0.getOpcode() == ISD::BUILD_VECTOR &&
7365 N1.getOpcode() != ISD::BUILD_VECTOR)
7366 if (auto *BV0 = dyn_cast<BuildVectorSDNode>(N0))
7367 if (BV0->isConstant())
7368 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
Dan Gohman80f9f072007-07-13 20:03:40 +00007369 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007370
Nate Begemanec48a1b2005-10-17 20:40:11 +00007371 // fold (fmul c1, c2) -> c1*c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007372 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007373 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
Sanjay Patel394c3332014-09-08 20:16:42 +00007374
Nate Begemanec48a1b2005-10-17 20:40:11 +00007375 // canonicalize constant to RHS
Nate Begeman418c6e42005-10-18 00:28:13 +00007376 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007377 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
Sanjay Patel394c3332014-09-08 20:16:42 +00007378
Owen Andersonb5f167c2012-05-02 21:32:35 +00007379 // fold (fmul A, 1.0) -> A
7380 if (N1CFP && N1CFP->isExactlyValue(1.0))
7381 return N0;
Matt Arsenault6cc00422014-08-16 10:14:19 +00007382
Sanjay Patel394c3332014-09-08 20:16:42 +00007383 if (Options.UnsafeFPMath) {
7384 // fold (fmul A, 0) -> 0
7385 if (N1CFP && N1CFP->getValueAPF().isZero())
7386 return N1;
7387
7388 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
Sanjay Patel7bd228a2014-09-11 15:45:27 +00007389 if (N0.getOpcode() == ISD::FMUL) {
7390 // Fold scalars or any vector constants (not just splats).
7391 // This fold is done in general by InstCombine, but extra fmul insts
7392 // may have been generated during lowering.
7393 SDValue N01 = N0.getOperand(1);
7394 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
7395 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
7396 if ((N1CFP && isConstOrConstSplatFP(N01)) ||
7397 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
7398 SDLoc SL(N);
7399 SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, N01, N1);
7400 return DAG.getNode(ISD::FMUL, SL, VT, N0.getOperand(0), MulConsts);
7401 }
Matt Arsenaultc1a71212014-09-02 19:02:53 +00007402 }
7403
Sanjay Patel394c3332014-09-08 20:16:42 +00007404 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
Matt Arsenaultc1a71212014-09-02 19:02:53 +00007405 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
7406 // during an early run of DAGCombiner can prevent folding with fmuls
7407 // inserted during lowering.
7408 if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
7409 SDLoc SL(N);
7410 const SDValue Two = DAG.getConstantFP(2.0, VT);
7411 SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, Two, N1);
7412 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), MulConsts);
7413 }
7414 }
7415
Nate Begemanec48a1b2005-10-17 20:40:11 +00007416 // fold (fmul X, 2.0) -> (fadd X, X)
7417 if (N1CFP && N1CFP->isExactlyValue(+2.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007418 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
Sanjay Patel394c3332014-09-08 20:16:42 +00007419
Dan Gohmanb7170912009-08-10 16:50:32 +00007420 // fold (fmul X, -1.0) -> (fneg X)
Chris Lattnere49c9742007-05-14 22:04:50 +00007421 if (N1CFP && N1CFP->isExactlyValue(-1.0))
Dan Gohman1f3411d2009-01-22 21:58:43 +00007422 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007423 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007424
Bill Wendling3dc5d242009-01-30 22:57:07 +00007425 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
Sanjay Patel78614bf2014-08-28 15:53:16 +00007426 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7427 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
Chris Lattnere49c9742007-05-14 22:04:50 +00007428 // Both can be negated for free, check to see if at least one is cheaper
7429 // negated.
7430 if (LHSNeg == 2 || RHSNeg == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007431 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007432 GetNegatedExpression(N0, DAG, LegalOperations),
7433 GetNegatedExpression(N1, DAG, LegalOperations));
Chris Lattnere49c9742007-05-14 22:04:50 +00007434 }
7435 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007436
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007437 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00007438}
7439
Owen Anderson41b06652012-05-02 22:17:40 +00007440SDValue DAGCombiner::visitFMA(SDNode *N) {
7441 SDValue N0 = N->getOperand(0);
7442 SDValue N1 = N->getOperand(1);
7443 SDValue N2 = N->getOperand(2);
7444 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7445 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7446 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007447 SDLoc dl(N);
Sanjay Patel78614bf2014-08-28 15:53:16 +00007448 const TargetOptions &Options = DAG.getTarget().Options;
Owen Anderson9d5a8c22014-08-02 08:45:33 +00007449
7450 // Constant fold FMA.
7451 if (isa<ConstantFPSDNode>(N0) &&
7452 isa<ConstantFPSDNode>(N1) &&
7453 isa<ConstantFPSDNode>(N2)) {
7454 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
7455 }
7456
Sanjay Patel78614bf2014-08-28 15:53:16 +00007457 if (Options.UnsafeFPMath) {
Owen Andersonb351c8d2012-11-01 02:00:53 +00007458 if (N0CFP && N0CFP->isZero())
7459 return N2;
7460 if (N1CFP && N1CFP->isZero())
7461 return N2;
7462 }
Owen Anderson41b06652012-05-02 22:17:40 +00007463 if (N0CFP && N0CFP->isExactlyValue(1.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007464 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
Owen Anderson41b06652012-05-02 22:17:40 +00007465 if (N1CFP && N1CFP->isExactlyValue(1.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007466 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
Owen Anderson41b06652012-05-02 22:17:40 +00007467
Owen Andersonc7aaf522012-05-30 18:50:39 +00007468 // Canonicalize (fma c, x, y) -> (fma x, c, y)
Owen Anderson0eda3e12012-05-30 18:54:50 +00007469 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007470 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
Owen Andersonc7aaf522012-05-30 18:50:39 +00007471
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007472 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
Sanjay Patel78614bf2014-08-28 15:53:16 +00007473 if (Options.UnsafeFPMath && N1CFP &&
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007474 N2.getOpcode() == ISD::FMUL &&
7475 N0 == N2.getOperand(0) &&
7476 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
7477 return DAG.getNode(ISD::FMUL, dl, VT, N0,
7478 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
7479 }
7480
7481
7482 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
Sanjay Patel78614bf2014-08-28 15:53:16 +00007483 if (Options.UnsafeFPMath &&
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007484 N0.getOpcode() == ISD::FMUL && N1CFP &&
7485 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
7486 return DAG.getNode(ISD::FMA, dl, VT,
7487 N0.getOperand(0),
7488 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
7489 N2);
7490 }
7491
7492 // (fma x, 1, y) -> (fadd x, y)
7493 // (fma x, -1, y) -> (fadd (fneg x), y)
7494 if (N1CFP) {
7495 if (N1CFP->isExactlyValue(1.0))
7496 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
7497
7498 if (N1CFP->isExactlyValue(-1.0) &&
7499 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
7500 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007501 AddToWorklist(RHSNeg.getNode());
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007502 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
7503 }
7504 }
7505
7506 // (fma x, c, x) -> (fmul x, (c+1))
Sanjay Patel78614bf2014-08-28 15:53:16 +00007507 if (Options.UnsafeFPMath && N1CFP && N0 == N2)
Stephen Lin8e8424e2013-07-09 00:44:49 +00007508 return DAG.getNode(ISD::FMUL, dl, VT, N0,
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007509 DAG.getNode(ISD::FADD, dl, VT,
7510 N1, DAG.getConstantFP(1.0, VT)));
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007511
7512 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
Sanjay Patel78614bf2014-08-28 15:53:16 +00007513 if (Options.UnsafeFPMath && N1CFP &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00007514 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
7515 return DAG.getNode(ISD::FMUL, dl, VT, N0,
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007516 DAG.getNode(ISD::FADD, dl, VT,
7517 N1, DAG.getConstantFP(-1.0, VT)));
Owen Anderson90e0eaf2012-09-01 06:04:27 +00007518
7519
Owen Anderson41b06652012-05-02 22:17:40 +00007520 return SDValue();
7521}
7522
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007523SDValue DAGCombiner::visitFDIV(SDNode *N) {
7524 SDValue N0 = N->getOperand(0);
7525 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00007526 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7527 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007528 EVT VT = N->getValueType(0);
Sanjay Patelbdf1e382014-09-26 23:01:47 +00007529 SDLoc DL(N);
Sanjay Patel78614bf2014-08-28 15:53:16 +00007530 const TargetOptions &Options = DAG.getTarget().Options;
Chris Lattner6f3b5772005-09-28 22:28:18 +00007531
Dan Gohmana8665142007-06-25 16:23:39 +00007532 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00007533 if (VT.isVector()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007534 SDValue FoldedVOp = SimplifyVBinOp(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00007535 if (FoldedVOp.getNode()) return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00007536 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007537
Nate Begeman569c4392006-01-18 22:35:16 +00007538 // fold (fdiv c1, c2) -> c1/c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007539 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007540 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007541
Sanjay Patelb67bd262014-09-21 15:19:15 +00007542 if (Options.UnsafeFPMath) {
7543 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
7544 if (N1CFP) {
7545 // Compute the reciprocal 1.0 / c2.
7546 APFloat N1APF = N1CFP->getValueAPF();
7547 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
7548 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
7549 // Only do the transform if the reciprocal is a legal fp immediate that
7550 // isn't too nasty (eg NaN, denormal, ...).
7551 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
7552 (!LegalOperations ||
7553 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
7554 // backend)... we should handle this gracefully after Legalize.
7555 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
7556 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
7557 TLI.isFPImmLegal(Recip, VT)))
7558 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
7559 DAG.getConstantFP(Recip, VT));
7560 }
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007561
Sanjay Patelb67bd262014-09-21 15:19:15 +00007562 // If this FDIV is part of a reciprocal square root, it may be folded
7563 // into a target-specific square root estimate instruction.
Sanjay Patelbdf1e382014-09-26 23:01:47 +00007564 if (N1.getOpcode() == ISD::FSQRT) {
7565 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
Sanjay Patelbdf1e382014-09-26 23:01:47 +00007566 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7567 }
7568 } else if (N1.getOpcode() == ISD::FP_EXTEND &&
7569 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7570 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
Sanjay Patelbdf1e382014-09-26 23:01:47 +00007571 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
7572 AddToWorklist(RV.getNode());
7573 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7574 }
7575 } else if (N1.getOpcode() == ISD::FP_ROUND &&
7576 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7577 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
Sanjay Patelbdf1e382014-09-26 23:01:47 +00007578 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
7579 AddToWorklist(RV.getNode());
7580 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7581 }
Sanjay Patel7bc91852014-10-06 19:31:18 +00007582 } else if (N1.getOpcode() == ISD::FMUL) {
7583 // Look through an FMUL. Even though this won't remove the FDIV directly,
7584 // it's still worthwhile to get rid of the FSQRT if possible.
7585 SDValue SqrtOp;
7586 SDValue OtherOp;
7587 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7588 SqrtOp = N1.getOperand(0);
7589 OtherOp = N1.getOperand(1);
7590 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
7591 SqrtOp = N1.getOperand(1);
7592 OtherOp = N1.getOperand(0);
7593 }
7594 if (SqrtOp.getNode()) {
7595 // We found a FSQRT, so try to make this fold:
7596 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
7597 if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
Sanjay Patel7bc91852014-10-06 19:31:18 +00007598 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
7599 AddToWorklist(RV.getNode());
7600 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7601 }
7602 }
Sanjay Patelbdf1e382014-09-26 23:01:47 +00007603 }
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007604
Sanjay Patelbdf1e382014-09-26 23:01:47 +00007605 // Fold into a reciprocal estimate and multiply instead of a real divide.
7606 if (SDValue RV = BuildReciprocalEstimate(N1)) {
7607 AddToWorklist(RV.getNode());
7608 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7609 }
Duncan Sands5f8397a2012-04-07 20:04:00 +00007610 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007611
Bill Wendling3dc5d242009-01-30 22:57:07 +00007612 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
Sanjay Patel78614bf2014-08-28 15:53:16 +00007613 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7614 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
Chris Lattnere49c9742007-05-14 22:04:50 +00007615 // Both can be negated for free, check to see if at least one is cheaper
7616 // negated.
7617 if (LHSNeg == 2 || RHSNeg == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007618 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007619 GetNegatedExpression(N0, DAG, LegalOperations),
7620 GetNegatedExpression(N1, DAG, LegalOperations));
Chris Lattnere49c9742007-05-14 22:04:50 +00007621 }
7622 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007623
Hao Liu44e5d7a2014-11-21 06:39:58 +00007624 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
7625 // reciprocal.
7626 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
7627 // Notice that this is not always beneficial. One reason is different target
7628 // may have different costs for FDIV and FMUL, so sometimes the cost of two
7629 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
7630 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
7631 if (Options.UnsafeFPMath) {
7632 // Skip if current node is a reciprocal.
7633 if (N0CFP && N0CFP->isExactlyValue(1.0))
7634 return SDValue();
7635
7636 SmallVector<SDNode *, 4> Users;
7637 // Find all FDIV users of the same divisor.
7638 for (SDNode::use_iterator UI = N1.getNode()->use_begin(),
7639 UE = N1.getNode()->use_end();
7640 UI != UE; ++UI) {
7641 SDNode *User = UI.getUse().getUser();
7642 if (User->getOpcode() == ISD::FDIV && User->getOperand(1) == N1)
7643 Users.push_back(User);
7644 }
7645
7646 if (TLI.combineRepeatedFPDivisors(Users.size())) {
7647 SDValue FPOne = DAG.getConstantFP(1.0, VT); // floating point 1.0
7648 SDValue Reciprocal = DAG.getNode(ISD::FDIV, SDLoc(N), VT, FPOne, N1);
7649
7650 // Dividend / Divisor -> Dividend * Reciprocal
7651 for (auto I = Users.begin(), E = Users.end(); I != E; ++I) {
7652 if ((*I)->getOperand(0) != FPOne) {
7653 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(*I), VT,
7654 (*I)->getOperand(0), Reciprocal);
7655 DAG.ReplaceAllUsesWith(*I, NewNode.getNode());
7656 }
7657 }
7658 return SDValue();
7659 }
7660 }
7661
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007662 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00007663}
7664
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007665SDValue DAGCombiner::visitFREM(SDNode *N) {
7666 SDValue N0 = N->getOperand(0);
7667 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00007668 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7669 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007670 EVT VT = N->getValueType(0);
Chris Lattner6f3b5772005-09-28 22:28:18 +00007671
Nate Begeman569c4392006-01-18 22:35:16 +00007672 // fold (frem c1, c2) -> fmod(c1,c2)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007673 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007674 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
Dan Gohmana8665142007-06-25 16:23:39 +00007675
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007676 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00007677}
7678
Sanjay Patelbdf1e382014-09-26 23:01:47 +00007679SDValue DAGCombiner::visitFSQRT(SDNode *N) {
Matt Arsenaultbf0db912015-01-13 20:53:23 +00007680 if (DAG.getTarget().Options.UnsafeFPMath &&
7681 !TLI.isFsqrtCheap()) {
Sanjay Patel3d497cd2014-10-09 21:26:35 +00007682 // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
Sanjay Patelbdf1e382014-09-26 23:01:47 +00007683 if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
Sanjay Patel3d497cd2014-10-09 21:26:35 +00007684 EVT VT = RV.getValueType();
7685 RV = DAG.getNode(ISD::FMUL, SDLoc(N), VT, N->getOperand(0), RV);
7686 AddToWorklist(RV.getNode());
Sanjay Patelbdf1e382014-09-26 23:01:47 +00007687
Sanjay Patel3d497cd2014-10-09 21:26:35 +00007688 // Unfortunately, RV is now NaN if the input was exactly 0.
7689 // Select out this case and force the answer to 0.
7690 SDValue Zero = DAG.getConstantFP(0.0, VT);
7691 SDValue ZeroCmp =
7692 DAG.getSetCC(SDLoc(N), TLI.getSetCCResultType(*DAG.getContext(), VT),
7693 N->getOperand(0), Zero, ISD::SETEQ);
7694 AddToWorklist(ZeroCmp.getNode());
7695 AddToWorklist(RV.getNode());
7696
7697 RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
7698 SDLoc(N), VT, ZeroCmp, Zero, RV);
7699 return RV;
Sanjay Patelbdf1e382014-09-26 23:01:47 +00007700 }
7701 }
7702 return SDValue();
7703}
7704
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007705SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
7706 SDValue N0 = N->getOperand(0);
7707 SDValue N1 = N->getOperand(1);
Chris Lattner3bc40502006-03-05 05:30:57 +00007708 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7709 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007710 EVT VT = N->getValueType(0);
Chris Lattner3bc40502006-03-05 05:30:57 +00007711
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007712 if (N0CFP && N1CFP) // Constant fold
Andrew Trickef9de2a2013-05-25 02:42:55 +00007713 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007714
Chris Lattner3bc40502006-03-05 05:30:57 +00007715 if (N1CFP) {
Dale Johannesenb6d2bec2007-08-26 01:18:27 +00007716 const APFloat& V = N1CFP->getValueAPF();
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00007717 // copysign(x, c1) -> fabs(x) iff ispos(c1)
7718 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
Dan Gohman1f3411d2009-01-22 21:58:43 +00007719 if (!V.isNegative()) {
7720 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007721 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Dan Gohman1f3411d2009-01-22 21:58:43 +00007722 } else {
7723 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007724 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7725 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
Dan Gohman1f3411d2009-01-22 21:58:43 +00007726 }
Chris Lattner3bc40502006-03-05 05:30:57 +00007727 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007728
Chris Lattner3bc40502006-03-05 05:30:57 +00007729 // copysign(fabs(x), y) -> copysign(x, y)
7730 // copysign(fneg(x), y) -> copysign(x, y)
7731 // copysign(copysign(x,z), y) -> copysign(x, y)
7732 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7733 N0.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007734 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007735 N0.getOperand(0), N1);
Chris Lattner3bc40502006-03-05 05:30:57 +00007736
7737 // copysign(x, abs(y)) -> abs(x)
7738 if (N1.getOpcode() == ISD::FABS)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007739 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007740
Chris Lattner3bc40502006-03-05 05:30:57 +00007741 // copysign(x, copysign(y,z)) -> copysign(x, z)
7742 if (N1.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007743 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007744 N0, N1.getOperand(1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00007745
Chris Lattner3bc40502006-03-05 05:30:57 +00007746 // copysign(x, fp_extend(y)) -> copysign(x, y)
7747 // copysign(x, fp_round(y)) -> copysign(x, y)
7748 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007749 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007750 N0, N1.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00007751
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007752 return SDValue();
Chris Lattner3bc40502006-03-05 05:30:57 +00007753}
7754
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007755SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7756 SDValue N0 = N->getOperand(0);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00007757 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007758 EVT VT = N->getValueType(0);
7759 EVT OpVT = N0.getValueType();
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007760
Nate Begeman21158fc2005-09-01 00:19:25 +00007761 // fold (sint_to_fp c1) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007762 if (N0C &&
Stuart Hastings6b4007d2011-03-02 19:36:30 +00007763 // ...but only if the target supports immediate floating-point values
Eli Friedman9d448e42011-11-12 00:35:34 +00007764 (!LegalOperations ||
Evan Cheng4c0bd962011-06-21 06:01:08 +00007765 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007766 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007767
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007768 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7769 // but UINT_TO_FP is legal on this target, try to convert.
Dan Gohman4aa18462009-01-28 17:46:25 +00007770 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7771 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
Scott Michelcf0da6c2009-02-17 22:15:04 +00007772 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007773 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007774 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007775 }
Bill Wendling0bd29742009-01-30 23:15:49 +00007776
Alp Tokercb402912014-01-24 17:20:08 +00007777 // The next optimizations are desirable only if SELECT_CC can be lowered.
Tom Stellard3787b122014-06-10 16:01:29 +00007778 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
Nadav Rotem90560762012-07-23 07:59:50 +00007779 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7780 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7781 !VT.isVector() &&
7782 (!LegalOperations ||
7783 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7784 SDValue Ops[] =
7785 { N0.getOperand(0), N0.getOperand(1),
7786 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7787 N0.getOperand(2) };
Craig Topper48d114b2014-04-26 18:35:24 +00007788 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
Nadav Rotem90560762012-07-23 07:59:50 +00007789 }
Owen Andersond4b841f2012-07-09 20:31:12 +00007790
Nadav Rotem90560762012-07-23 07:59:50 +00007791 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7792 // (select_cc x, y, 1.0, 0.0,, cc)
7793 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7794 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7795 (!LegalOperations ||
7796 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7797 SDValue Ops[] =
7798 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7799 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7800 N0.getOperand(0).getOperand(2) };
Craig Topper48d114b2014-04-26 18:35:24 +00007801 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
Nadav Rotem90560762012-07-23 07:59:50 +00007802 }
Owen Andersond4b841f2012-07-09 20:31:12 +00007803 }
7804
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007805 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007806}
7807
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007808SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7809 SDValue N0 = N->getOperand(0);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00007810 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007811 EVT VT = N->getValueType(0);
7812 EVT OpVT = N0.getValueType();
Nate Begeman569c4392006-01-18 22:35:16 +00007813
Nate Begeman21158fc2005-09-01 00:19:25 +00007814 // fold (uint_to_fp c1) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007815 if (N0C &&
Stuart Hastings6b4007d2011-03-02 19:36:30 +00007816 // ...but only if the target supports immediate floating-point values
Eli Friedman9d448e42011-11-12 00:35:34 +00007817 (!LegalOperations ||
Evan Cheng4c0bd962011-06-21 06:01:08 +00007818 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007819 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007820
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007821 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7822 // but SINT_TO_FP is legal on this target, try to convert.
Dan Gohman4aa18462009-01-28 17:46:25 +00007823 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7824 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
Scott Michelcf0da6c2009-02-17 22:15:04 +00007825 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007826 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007827 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00007828 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007829
Alp Tokercb402912014-01-24 17:20:08 +00007830 // The next optimizations are desirable only if SELECT_CC can be lowered.
Tom Stellard3787b122014-06-10 16:01:29 +00007831 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
Nadav Rotem90560762012-07-23 07:59:50 +00007832 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
Owen Andersond4b841f2012-07-09 20:31:12 +00007833
Nadav Rotem90560762012-07-23 07:59:50 +00007834 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7835 (!LegalOperations ||
7836 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7837 SDValue Ops[] =
7838 { N0.getOperand(0), N0.getOperand(1),
7839 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
7840 N0.getOperand(2) };
Craig Topper48d114b2014-04-26 18:35:24 +00007841 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
Nadav Rotem90560762012-07-23 07:59:50 +00007842 }
7843 }
Owen Andersond4b841f2012-07-09 20:31:12 +00007844
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007845 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007846}
7847
Mehdi Amini3e0023b2015-02-16 21:47:58 +00007848// Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
7849static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
7850 SDValue N0 = N->getOperand(0);
7851 EVT VT = N->getValueType(0);
7852
7853 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
7854 return SDValue();
7855
7856 SDValue Src = N0.getOperand(0);
7857 EVT SrcVT = Src.getValueType();
7858 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
7859 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
7860
7861 // We can safely assume the conversion won't overflow the output range,
7862 // because (for example) (uint8_t)18293.f is undefined behavior.
7863
7864 // Since we can assume the conversion won't overflow, our decision as to
7865 // whether the input will fit in the float should depend on the minimum
7866 // of the input range and output range.
7867
7868 // This means this is also safe for a signed input and unsigned output, since
7869 // a negative input would lead to undefined behavior.
7870 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
7871 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
7872 unsigned ActualSize = std::min(InputSize, OutputSize);
7873 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
7874
7875 // We can only fold away the float conversion if the input range can be
7876 // represented exactly in the float range.
7877 if (APFloat::semanticsPrecision(sem) >= ActualSize) {
7878 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
7879 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
7880 : ISD::ZERO_EXTEND;
7881 return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
7882 }
7883 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
7884 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
7885 if (SrcVT == VT)
7886 return Src;
7887 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
7888 }
7889 return SDValue();
7890}
7891
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007892SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7893 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007894 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007895 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007896
Nate Begeman21158fc2005-09-01 00:19:25 +00007897 // fold (fp_to_sint c1fp) -> c1
Nate Begeman7cea6ef2005-09-02 21:18:40 +00007898 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007899 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
Bill Wendling0bd29742009-01-30 23:15:49 +00007900
Mehdi Amini3e0023b2015-02-16 21:47:58 +00007901 return FoldIntToFPToInt(N, DAG);
Nate Begeman21158fc2005-09-01 00:19:25 +00007902}
7903
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007904SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7905 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007906 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007907 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007908
Nate Begeman21158fc2005-09-01 00:19:25 +00007909 // fold (fp_to_uint c1fp) -> c1
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007910 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007911 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
Bill Wendling0bd29742009-01-30 23:15:49 +00007912
Mehdi Amini3e0023b2015-02-16 21:47:58 +00007913 return FoldIntToFPToInt(N, DAG);
Nate Begeman21158fc2005-09-01 00:19:25 +00007914}
7915
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007916SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7917 SDValue N0 = N->getOperand(0);
7918 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00007919 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007920 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007921
Nate Begeman21158fc2005-09-01 00:19:25 +00007922 // fold (fp_round c1fp) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007923 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007924 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007925
Chris Lattner8bb6cb72006-03-13 06:26:26 +00007926 // fold (fp_round (fp_extend x)) -> x
7927 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7928 return N0.getOperand(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007929
Chris Lattner0feb1b02008-01-24 06:45:35 +00007930 // fold (fp_round (fp_round x)) -> (fp_round x)
7931 if (N0.getOpcode() == ISD::FP_ROUND) {
Ahmed Bougacha24433a72015-02-12 06:15:29 +00007932 const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
7933 const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
7934 // If the first fp_round isn't a value preserving truncation, it might
7935 // introduce a tie in the second fp_round, that wouldn't occur in the
7936 // single-step fp_round we want to fold to.
7937 // In other words, double rounding isn't the same as rounding.
7938 // Also, this is a value preserving truncation iff both fp_round's are.
7939 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc)
7940 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7941 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc));
Chris Lattner0feb1b02008-01-24 06:45:35 +00007942 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007943
Chris Lattner8bb6cb72006-03-13 06:26:26 +00007944 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
Gabor Greiff304a7a2008-08-28 21:40:38 +00007945 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007946 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007947 N0.getOperand(0), N1);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007948 AddToWorklist(Tmp.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00007949 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007950 Tmp, N0.getOperand(1));
Chris Lattner8bb6cb72006-03-13 06:26:26 +00007951 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007952
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007953 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007954}
7955
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007956SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7957 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007958 EVT VT = N->getValueType(0);
7959 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
Nate Begeman7cea6ef2005-09-02 21:18:40 +00007960 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007961
Nate Begeman21158fc2005-09-01 00:19:25 +00007962 // fold (fp_round_inreg c1fp) -> c1fp
Chris Lattner4041ab62010-04-15 04:48:01 +00007963 if (N0CFP && isTypeLegal(EVT)) {
Dan Gohmanec270fb2008-09-12 18:08:03 +00007964 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007965 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
Nate Begeman21158fc2005-09-01 00:19:25 +00007966 }
Bill Wendling0bd29742009-01-30 23:15:49 +00007967
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007968 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00007969}
7970
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007971SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7972 SDValue N0 = N->getOperand(0);
Nate Begeman569c4392006-01-18 22:35:16 +00007973 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007974 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007975
Chris Lattner5919b482007-12-29 06:55:23 +00007976 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
Scott Michelcf0da6c2009-02-17 22:15:04 +00007977 if (N->hasOneUse() &&
Dan Gohman8e4ac9b2009-01-26 04:35:06 +00007978 N->use_begin()->getOpcode() == ISD::FP_ROUND)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007979 return SDValue();
Chris Lattner72733e52008-01-17 07:00:52 +00007980
Nate Begeman21158fc2005-09-01 00:19:25 +00007981 // fold (fp_extend c1fp) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007982 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007983 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
Chris Lattner72733e52008-01-17 07:00:52 +00007984
7985 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7986 // value of X.
Gabor Greife12264b2008-08-30 19:29:20 +00007987 if (N0.getOpcode() == ISD::FP_ROUND
7988 && N0.getNode()->getConstantOperandVal(1) == 1) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007989 SDValue In = N0.getOperand(0);
Chris Lattner72733e52008-01-17 07:00:52 +00007990 if (In.getValueType() == VT) return In;
Duncan Sands11dd4242008-06-08 20:54:56 +00007991 if (VT.bitsLT(In.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007992 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00007993 In, N0.getOperand(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00007994 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
Chris Lattner72733e52008-01-17 07:00:52 +00007995 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007996
Chris Lattner72733e52008-01-17 07:00:52 +00007997 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
Hal Finkeldbc7a8a2013-10-04 22:18:12 +00007998 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00007999 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00008000 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00008001 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00008002 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00008003 LN0->getBasePtr(), N0.getValueType(),
8004 LN0->getMemOperand());
Chris Lattner3d265772006-05-05 21:34:35 +00008005 CombineTo(N, ExtLoad);
Bill Wendling0bd29742009-01-30 23:15:49 +00008006 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00008007 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
Bill Wendling0bd29742009-01-30 23:15:49 +00008008 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
Chris Lattner3d265772006-05-05 21:34:35 +00008009 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008010 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattner3d265772006-05-05 21:34:35 +00008011 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00008012
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008013 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00008014}
8015
Sanjay Patelccd26762014-08-28 21:51:37 +00008016SDValue DAGCombiner::visitFCEIL(SDNode *N) {
8017 SDValue N0 = N->getOperand(0);
8018 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8019 EVT VT = N->getValueType(0);
8020
8021 // fold (fceil c1) -> fceil(c1)
8022 if (N0CFP)
8023 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
8024
8025 return SDValue();
8026}
8027
8028SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
8029 SDValue N0 = N->getOperand(0);
8030 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8031 EVT VT = N->getValueType(0);
8032
8033 // fold (ftrunc c1) -> ftrunc(c1)
8034 if (N0CFP)
8035 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
8036
8037 return SDValue();
8038}
8039
8040SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
8041 SDValue N0 = N->getOperand(0);
8042 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8043 EVT VT = N->getValueType(0);
8044
8045 // fold (ffloor c1) -> ffloor(c1)
8046 if (N0CFP)
8047 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
8048
8049 return SDValue();
8050}
8051
8052// FIXME: FNEG and FABS have a lot in common; refactor.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008053SDValue DAGCombiner::visitFNEG(SDNode *N) {
8054 SDValue N0 = N->getOperand(0);
Anton Korobeynikova6faf602009-10-20 21:37:45 +00008055 EVT VT = N->getValueType(0);
Nate Begeman569c4392006-01-18 22:35:16 +00008056
Craig Topper82384612012-09-11 01:45:21 +00008057 if (VT.isVector()) {
8058 SDValue FoldedVOp = SimplifyVUnaryOp(N);
8059 if (FoldedVOp.getNode()) return FoldedVOp;
Craig Topper03f39772012-09-09 22:58:45 +00008060 }
8061
Sanjay Patelccd26762014-08-28 21:51:37 +00008062 // Constant fold FNEG.
8063 if (isa<ConstantFPSDNode>(N0))
8064 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N->getOperand(0));
8065
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00008066 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
8067 &DAG.getTarget().Options))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00008068 return GetNegatedExpression(N0, DAG, LegalOperations);
Dan Gohman9a708232007-07-02 15:48:56 +00008069
Sanjay Patel35d31332014-08-14 15:15:28 +00008070 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
Chris Lattner888560d2008-01-27 17:42:27 +00008071 // constant pool values.
Sanjay Patelccd26762014-08-28 21:51:37 +00008072 if (!TLI.isFNegFree(VT) &&
8073 N0.getOpcode() == ISD::BITCAST &&
Sanjay Patel35d31332014-08-14 15:15:28 +00008074 N0.getNode()->hasOneUse()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008075 SDValue Int = N0.getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00008076 EVT IntVT = Int.getValueType();
Duncan Sands13237ac2008-06-06 12:08:01 +00008077 if (IntVT.isInteger() && !IntVT.isVector()) {
Sanjay Patel35d31332014-08-14 15:15:28 +00008078 APInt SignMask;
8079 if (N0.getValueType().isVector()) {
8080 // For a vector, get a mask such as 0x80... per scalar element
8081 // and splat it.
8082 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8083 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8084 } else {
8085 // For a scalar, just generate 0x80...
8086 SignMask = APInt::getSignBit(IntVT.getSizeInBits());
8087 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00008088 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
Sanjay Patel35d31332014-08-14 15:15:28 +00008089 DAG.getConstant(SignMask, IntVT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008090 AddToWorklist(Int.getNode());
Sanjay Patel35d31332014-08-14 15:15:28 +00008091 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
Chris Lattner888560d2008-01-27 17:42:27 +00008092 }
8093 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00008094
Owen Anderson90e0eaf2012-09-01 06:04:27 +00008095 // (fneg (fmul c, x)) -> (fmul -c, x)
8096 if (N0.getOpcode() == ISD::FMUL) {
8097 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
Tim Northover820e0412014-05-02 17:25:02 +00008098 if (CFP1) {
8099 APFloat CVal = CFP1->getValueAPF();
8100 CVal.changeSign();
8101 if (Level >= AfterLegalizeDAG &&
8102 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
8103 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
8104 return DAG.getNode(
8105 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
8106 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
8107 }
Owen Anderson90e0eaf2012-09-01 06:04:27 +00008108 }
8109
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008110 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00008111}
8112
Matt Arsenault7c936902014-10-21 23:01:01 +00008113SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
8114 SDValue N0 = N->getOperand(0);
8115 SDValue N1 = N->getOperand(1);
8116 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8117 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8118
8119 if (N0CFP && N1CFP) {
8120 const APFloat &C0 = N0CFP->getValueAPF();
8121 const APFloat &C1 = N1CFP->getValueAPF();
8122 return DAG.getConstantFP(minnum(C0, C1), N->getValueType(0));
8123 }
8124
8125 if (N0CFP) {
8126 EVT VT = N->getValueType(0);
8127 // Canonicalize to constant on RHS.
8128 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
8129 }
8130
8131 return SDValue();
8132}
8133
8134SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
8135 SDValue N0 = N->getOperand(0);
8136 SDValue N1 = N->getOperand(1);
8137 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8138 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8139
8140 if (N0CFP && N1CFP) {
8141 const APFloat &C0 = N0CFP->getValueAPF();
8142 const APFloat &C1 = N1CFP->getValueAPF();
8143 return DAG.getConstantFP(maxnum(C0, C1), N->getValueType(0));
8144 }
8145
8146 if (N0CFP) {
8147 EVT VT = N->getValueType(0);
8148 // Canonicalize to constant on RHS.
8149 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
8150 }
8151
8152 return SDValue();
8153}
8154
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008155SDValue DAGCombiner::visitFABS(SDNode *N) {
8156 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00008157 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008158
Craig Topper82384612012-09-11 01:45:21 +00008159 if (VT.isVector()) {
8160 SDValue FoldedVOp = SimplifyVUnaryOp(N);
8161 if (FoldedVOp.getNode()) return FoldedVOp;
8162 }
8163
Nate Begeman21158fc2005-09-01 00:19:25 +00008164 // fold (fabs c1) -> fabs(c1)
Sanjay Patelccd26762014-08-28 21:51:37 +00008165 if (isa<ConstantFPSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00008166 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00008167
Nate Begeman21158fc2005-09-01 00:19:25 +00008168 // fold (fabs (fabs x)) -> (fabs x)
Chris Lattner3bc40502006-03-05 05:30:57 +00008169 if (N0.getOpcode() == ISD::FABS)
Nate Begemand23739d2005-09-06 04:43:02 +00008170 return N->getOperand(0);
Sanjay Patelccd26762014-08-28 21:51:37 +00008171
Nate Begeman21158fc2005-09-01 00:19:25 +00008172 // fold (fabs (fneg x)) -> (fabs x)
Chris Lattner3bc40502006-03-05 05:30:57 +00008173 // fold (fabs (fcopysign x, y)) -> (fabs x)
8174 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008175 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00008176
Sanjay Patel8e5beb62014-08-05 17:35:22 +00008177 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
Chris Lattner888560d2008-01-27 17:42:27 +00008178 // constant pool values.
Stephen Lincfe7f352013-07-08 00:37:03 +00008179 if (!TLI.isFAbsFree(VT) &&
Sanjay Patel8e5beb62014-08-05 17:35:22 +00008180 N0.getOpcode() == ISD::BITCAST &&
8181 N0.getNode()->hasOneUse()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008182 SDValue Int = N0.getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00008183 EVT IntVT = Int.getValueType();
Duncan Sands13237ac2008-06-06 12:08:01 +00008184 if (IntVT.isInteger() && !IntVT.isVector()) {
Sanjay Patel8e5beb62014-08-05 17:35:22 +00008185 APInt SignMask;
8186 if (N0.getValueType().isVector()) {
8187 // For a vector, get a mask such as 0x7f... per scalar element
8188 // and splat it.
8189 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8190 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8191 } else {
8192 // For a scalar, just generate 0x7f...
8193 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
8194 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00008195 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
Sanjay Patel8e5beb62014-08-05 17:35:22 +00008196 DAG.getConstant(SignMask, IntVT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008197 AddToWorklist(Int.getNode());
Sanjay Patel8e5beb62014-08-05 17:35:22 +00008198 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
Chris Lattner888560d2008-01-27 17:42:27 +00008199 }
8200 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00008201
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008202 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00008203}
8204
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008205SDValue DAGCombiner::visitBRCOND(SDNode *N) {
8206 SDValue Chain = N->getOperand(0);
8207 SDValue N1 = N->getOperand(1);
8208 SDValue N2 = N->getOperand(2);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008209
Dan Gohman82e80012009-11-17 00:47:23 +00008210 // If N is a constant we could fold this into a fallthrough or unconditional
8211 // branch. However that doesn't happen very often in normal code, because
8212 // Instcombine/SimplifyCFG should have handled the available opportunities.
8213 // If we did this folding here, it would be necessary to update the
8214 // MachineBasicBlock CFG, which is awkward.
8215
Nate Begeman7e7f4392006-02-01 07:19:44 +00008216 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
8217 // on the target.
Scott Michelcf0da6c2009-02-17 22:15:04 +00008218 if (N1.getOpcode() == ISD::SETCC &&
Tom Stellardb1588fc2013-03-08 15:36:57 +00008219 TLI.isOperationLegalOrCustom(ISD::BR_CC,
8220 N1.getOperand(0).getValueType())) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00008221 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
Bill Wendling306bfc22009-01-30 23:27:35 +00008222 Chain, N1.getOperand(2),
Nate Begeman7e7f4392006-02-01 07:19:44 +00008223 N1.getOperand(0), N1.getOperand(1), N2);
8224 }
Bill Wendling306bfc22009-01-30 23:27:35 +00008225
Evan Chengc8d6cfd2010-10-04 22:41:01 +00008226 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
8227 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
8228 (N1.getOperand(0).hasOneUse() &&
8229 N1.getOperand(0).getOpcode() == ISD::SRL))) {
Craig Topperc0196b12014-04-14 00:51:57 +00008230 SDNode *Trunc = nullptr;
Evan Chengc8d6cfd2010-10-04 22:41:01 +00008231 if (N1.getOpcode() == ISD::TRUNCATE) {
8232 // Look pass the truncate.
8233 Trunc = N1.getNode();
8234 N1 = N1.getOperand(0);
8235 }
Evan Cheng166a4e62010-01-06 19:38:29 +00008236
Bill Wendlingaa28be62009-03-26 06:14:09 +00008237 // Match this pattern so that we can generate simpler code:
8238 //
8239 // %a = ...
8240 // %b = and i32 %a, 2
8241 // %c = srl i32 %b, 1
8242 // brcond i32 %c ...
8243 //
8244 // into
Wesley Peck527da1b2010-11-23 03:31:01 +00008245 //
Bill Wendlingaa28be62009-03-26 06:14:09 +00008246 // %a = ...
Evan Cheng166a4e62010-01-06 19:38:29 +00008247 // %b = and i32 %a, 2
Bill Wendlingaa28be62009-03-26 06:14:09 +00008248 // %c = setcc eq %b, 0
8249 // brcond %c ...
8250 //
8251 // This applies only when the AND constant value has one bit set and the
8252 // SRL constant is equal to the log2 of the AND constant. The back-end is
8253 // smart enough to convert the result into a TEST/JMP sequence.
8254 SDValue Op0 = N1.getOperand(0);
8255 SDValue Op1 = N1.getOperand(1);
8256
8257 if (Op0.getOpcode() == ISD::AND &&
Bill Wendlingaa28be62009-03-26 06:14:09 +00008258 Op1.getOpcode() == ISD::Constant) {
Bill Wendlingaa28be62009-03-26 06:14:09 +00008259 SDValue AndOp1 = Op0.getOperand(1);
8260
8261 if (AndOp1.getOpcode() == ISD::Constant) {
8262 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
8263
8264 if (AndConst.isPowerOf2() &&
8265 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
8266 SDValue SetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00008267 DAG.getSetCC(SDLoc(N),
Matt Arsenault758659232013-05-18 00:21:46 +00008268 getSetCCResultType(Op0.getValueType()),
Bill Wendlingaa28be62009-03-26 06:14:09 +00008269 Op0, DAG.getConstant(0, Op0.getValueType()),
8270 ISD::SETNE);
8271
Andrew Trickef9de2a2013-05-25 02:42:55 +00008272 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng166a4e62010-01-06 19:38:29 +00008273 MVT::Other, Chain, SetCC, N2);
8274 // Don't add the new BRCond into the worklist or else SimplifySelectCC
8275 // will convert it back to (X & C1) >> C2.
8276 CombineTo(N, NewBRCond, false);
8277 // Truncate is dead.
Chandler Carruth18066972014-08-02 10:02:07 +00008278 if (Trunc)
8279 deleteAndRecombine(Trunc);
Bill Wendlingaa28be62009-03-26 06:14:09 +00008280 // Replace the uses of SRL with SETCC
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008281 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008282 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
Chandler Carruth18066972014-08-02 10:02:07 +00008283 deleteAndRecombine(N1.getNode());
Evan Cheng166a4e62010-01-06 19:38:29 +00008284 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Bill Wendlingaa28be62009-03-26 06:14:09 +00008285 }
8286 }
8287 }
Evan Chengc8d6cfd2010-10-04 22:41:01 +00008288
8289 if (Trunc)
8290 // Restore N1 if the above transformation doesn't match.
8291 N1 = N->getOperand(1);
Bill Wendlingaa28be62009-03-26 06:14:09 +00008292 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008293
Evan Cheng228c31f2010-02-27 07:36:59 +00008294 // Transform br(xor(x, y)) -> br(x != y)
8295 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
8296 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
8297 SDNode *TheXor = N1.getNode();
8298 SDValue Op0 = TheXor->getOperand(0);
8299 SDValue Op1 = TheXor->getOperand(1);
8300 if (Op0.getOpcode() == Op1.getOpcode()) {
8301 // Avoid missing important xor optimizations.
8302 SDValue Tmp = visitXOR(TheXor);
Evan Cheng5652a8d2013-01-09 20:56:40 +00008303 if (Tmp.getNode()) {
8304 if (Tmp.getNode() != TheXor) {
8305 DEBUG(dbgs() << "\nReplacing.8 ";
8306 TheXor->dump(&DAG);
8307 dbgs() << "\nWith: ";
8308 Tmp.getNode()->dump(&DAG);
8309 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008310 WorklistRemover DeadNodes(*this);
Evan Cheng5652a8d2013-01-09 20:56:40 +00008311 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
Chandler Carruth18066972014-08-02 10:02:07 +00008312 deleteAndRecombine(TheXor);
Andrew Trickef9de2a2013-05-25 02:42:55 +00008313 return DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng5652a8d2013-01-09 20:56:40 +00008314 MVT::Other, Chain, Tmp, N2);
8315 }
8316
Benjamin Kramer93354432013-03-30 21:28:18 +00008317 // visitXOR has changed XOR's operands or replaced the XOR completely,
8318 // bail out.
8319 return SDValue(N, 0);
Evan Cheng228c31f2010-02-27 07:36:59 +00008320 }
8321 }
8322
8323 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
8324 bool Equal = false;
8325 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
8326 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
8327 Op0.getOpcode() == ISD::XOR) {
8328 TheXor = Op0.getNode();
8329 Equal = true;
8330 }
8331
Evan Chengc8d6cfd2010-10-04 22:41:01 +00008332 EVT SetCCVT = N1.getValueType();
Evan Cheng228c31f2010-02-27 07:36:59 +00008333 if (LegalTypes)
Matt Arsenault758659232013-05-18 00:21:46 +00008334 SetCCVT = getSetCCResultType(SetCCVT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00008335 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
Evan Cheng228c31f2010-02-27 07:36:59 +00008336 SetCCVT,
8337 Op0, Op1,
8338 Equal ? ISD::SETEQ : ISD::SETNE);
8339 // Replace the uses of XOR with SETCC
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008340 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008341 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
Chandler Carruth18066972014-08-02 10:02:07 +00008342 deleteAndRecombine(N1.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00008343 return DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng228c31f2010-02-27 07:36:59 +00008344 MVT::Other, Chain, SetCC, N2);
8345 }
8346 }
Bill Wendlingaa28be62009-03-26 06:14:09 +00008347
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008348 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +00008349}
8350
Chris Lattnera49e16f2005-10-05 06:47:48 +00008351// Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
8352//
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008353SDValue DAGCombiner::visitBR_CC(SDNode *N) {
Chris Lattnera49e16f2005-10-05 06:47:48 +00008354 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008355 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008356
Dan Gohman82e80012009-11-17 00:47:23 +00008357 // If N is a constant we could fold this into a fallthrough or unconditional
8358 // branch. However that doesn't happen very often in normal code, because
8359 // Instcombine/SimplifyCFG should have handled the available opportunities.
8360 // If we did this folding here, it would be necessary to update the
8361 // MachineBasicBlock CFG, which is awkward.
8362
Duncan Sands93b66092008-06-09 11:32:28 +00008363 // Use SimplifySetCC to simplify SETCC's.
Matt Arsenault758659232013-05-18 00:21:46 +00008364 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00008365 CondLHS, CondRHS, CC->get(), SDLoc(N),
Dale Johannesenf1163e92009-02-03 00:47:48 +00008366 false);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008367 if (Simp.getNode()) AddToWorklist(Simp.getNode());
Chris Lattner6a1b2de2006-10-14 03:52:46 +00008368
Nate Begemanbd7df032005-10-05 21:43:42 +00008369 // fold to a simpler setcc
Gabor Greiff304a7a2008-08-28 21:40:38 +00008370 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008371 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
Bill Wendling306bfc22009-01-30 23:27:35 +00008372 N->getOperand(0), Simp.getOperand(2),
8373 Simp.getOperand(0), Simp.getOperand(1),
8374 N->getOperand(4));
8375
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008376 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +00008377}
8378
Sanjay Patel50cbfc52014-08-28 16:29:51 +00008379/// Return true if 'Use' is a load or a store that uses N as its base pointer
8380/// and that N may be folded in the load / store addressing mode.
Evan Chengfa832632012-01-13 01:37:24 +00008381static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
8382 SelectionDAG &DAG,
8383 const TargetLowering &TLI) {
8384 EVT VT;
8385 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
8386 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
8387 return false;
8388 VT = Use->getValueType(0);
8389 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
8390 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
8391 return false;
8392 VT = ST->getValue().getValueType();
8393 } else
8394 return false;
8395
Chandler Carruth95f83e02013-01-07 15:14:13 +00008396 TargetLowering::AddrMode AM;
Evan Chengfa832632012-01-13 01:37:24 +00008397 if (N->getOpcode() == ISD::ADD) {
8398 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
8399 if (Offset)
Evan Cheng80893ce2012-03-06 23:33:32 +00008400 // [reg +/- imm]
Evan Chengfa832632012-01-13 01:37:24 +00008401 AM.BaseOffs = Offset->getSExtValue();
8402 else
Evan Cheng80893ce2012-03-06 23:33:32 +00008403 // [reg +/- reg]
8404 AM.Scale = 1;
Evan Chengfa832632012-01-13 01:37:24 +00008405 } else if (N->getOpcode() == ISD::SUB) {
8406 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
8407 if (Offset)
Evan Cheng80893ce2012-03-06 23:33:32 +00008408 // [reg +/- imm]
Evan Chengfa832632012-01-13 01:37:24 +00008409 AM.BaseOffs = -Offset->getSExtValue();
8410 else
Evan Cheng80893ce2012-03-06 23:33:32 +00008411 // [reg +/- reg]
8412 AM.Scale = 1;
Evan Chengfa832632012-01-13 01:37:24 +00008413 } else
8414 return false;
8415
8416 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
8417}
8418
Sanjay Patel50cbfc52014-08-28 16:29:51 +00008419/// Try turning a load/store into a pre-indexed load/store when the base
8420/// pointer is an add or subtract and it has other uses besides the load/store.
8421/// After the transformation, the new indexed load/store has effectively folded
8422/// the add/subtract in and all of its other uses are redirected to the
8423/// new load/store.
Chris Lattnerffad2162006-11-11 00:39:41 +00008424bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
Eli Friedman9d448e42011-11-12 00:35:34 +00008425 if (Level < AfterLegalizeDAG)
Chris Lattnerffad2162006-11-11 00:39:41 +00008426 return false;
8427
8428 bool isLoad = true;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008429 SDValue Ptr;
Owen Anderson53aa7a92009-08-10 22:56:29 +00008430 EVT VT;
Chris Lattnerffad2162006-11-11 00:39:41 +00008431 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00008432 if (LD->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00008433 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00008434 VT = LD->getMemoryVT();
Evan Cheng8a1d09d2007-03-07 08:07:03 +00008435 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
Chris Lattnerffad2162006-11-11 00:39:41 +00008436 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
8437 return false;
8438 Ptr = LD->getBasePtr();
8439 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00008440 if (ST->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00008441 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00008442 VT = ST->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00008443 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
8444 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
8445 return false;
8446 Ptr = ST->getBasePtr();
8447 isLoad = false;
Bill Wendling306bfc22009-01-30 23:27:35 +00008448 } else {
Chris Lattnerffad2162006-11-11 00:39:41 +00008449 return false;
Bill Wendling306bfc22009-01-30 23:27:35 +00008450 }
Chris Lattnerffad2162006-11-11 00:39:41 +00008451
Chris Lattnereabc15c2006-11-11 00:56:29 +00008452 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
8453 // out. There is no reason to make this a preinc/predec.
8454 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
Gabor Greiff304a7a2008-08-28 21:40:38 +00008455 Ptr.getNode()->hasOneUse())
Chris Lattnereabc15c2006-11-11 00:56:29 +00008456 return false;
Chris Lattnerffad2162006-11-11 00:39:41 +00008457
Chris Lattnereabc15c2006-11-11 00:56:29 +00008458 // Ask the target to do addressing mode selection.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008459 SDValue BasePtr;
8460 SDValue Offset;
Chris Lattnereabc15c2006-11-11 00:56:29 +00008461 ISD::MemIndexedMode AM = ISD::UNINDEXED;
8462 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
8463 return false;
Hal Finkel25819052013-02-08 21:35:47 +00008464
8465 // Backends without true r+i pre-indexed forms may need to pass a
8466 // constant base with a variable offset so that constant coercion
8467 // will work with the patterns in canonical form.
8468 bool Swapped = false;
8469 if (isa<ConstantSDNode>(BasePtr)) {
8470 std::swap(BasePtr, Offset);
8471 Swapped = true;
8472 }
8473
Evan Cheng044a0a82007-05-03 23:52:19 +00008474 // Don't create a indexed load / store with zero offset.
8475 if (isa<ConstantSDNode>(Offset) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00008476 cast<ConstantSDNode>(Offset)->isNullValue())
Evan Cheng044a0a82007-05-03 23:52:19 +00008477 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00008478
Chris Lattnera0a80032006-11-11 01:00:15 +00008479 // Try turning it into a pre-indexed load / store except when:
Evan Chenga4d187b2007-05-24 02:35:39 +00008480 // 1) The new base ptr is a frame index.
8481 // 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 +00008482 // predecessor of the value being stored.
Evan Chenga4d187b2007-05-24 02:35:39 +00008483 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
Chris Lattnereabc15c2006-11-11 00:56:29 +00008484 // that would create a cycle.
Evan Chenga4d187b2007-05-24 02:35:39 +00008485 // 4) All uses are load / store ops that use it as old base ptr.
Chris Lattnerffad2162006-11-11 00:39:41 +00008486
Chris Lattnera0a80032006-11-11 01:00:15 +00008487 // Check #1. Preinc'ing a frame index would require copying the stack pointer
8488 // (plus the implicit offset) to a register to preinc anyway.
Evan Chengcfc05132009-05-06 18:25:01 +00008489 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
Chris Lattnera0a80032006-11-11 01:00:15 +00008490 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00008491
Chris Lattnera0a80032006-11-11 01:00:15 +00008492 // Check #2.
Chris Lattnereabc15c2006-11-11 00:56:29 +00008493 if (!isLoad) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008494 SDValue Val = cast<StoreSDNode>(N)->getValue();
Gabor Greiff304a7a2008-08-28 21:40:38 +00008495 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
Chris Lattnereabc15c2006-11-11 00:56:29 +00008496 return false;
Chris Lattnerffad2162006-11-11 00:39:41 +00008497 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00008498
Hal Finkel25819052013-02-08 21:35:47 +00008499 // If the offset is a constant, there may be other adds of constants that
8500 // can be folded with this one. We should do this to avoid having to keep
8501 // a copy of the original base pointer.
8502 SmallVector<SDNode *, 16> OtherUses;
8503 if (isa<ConstantSDNode>(Offset))
Jim Grosbache8160032014-04-11 01:13:13 +00008504 for (SDNode *Use : BasePtr.getNode()->uses()) {
Hal Finkel25819052013-02-08 21:35:47 +00008505 if (Use == Ptr.getNode())
8506 continue;
8507
8508 if (Use->isPredecessorOf(N))
8509 continue;
8510
8511 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
8512 OtherUses.clear();
8513 break;
8514 }
8515
8516 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
8517 if (Op1.getNode() == BasePtr.getNode())
8518 std::swap(Op0, Op1);
8519 assert(Op0.getNode() == BasePtr.getNode() &&
8520 "Use of ADD/SUB but not an operand");
8521
8522 if (!isa<ConstantSDNode>(Op1)) {
8523 OtherUses.clear();
8524 break;
8525 }
8526
8527 // FIXME: In some cases, we can be smarter about this.
8528 if (Op1.getValueType() != Offset.getValueType()) {
8529 OtherUses.clear();
8530 break;
8531 }
8532
8533 OtherUses.push_back(Use);
8534 }
8535
8536 if (Swapped)
8537 std::swap(BasePtr, Offset);
8538
Evan Chenga4d187b2007-05-24 02:35:39 +00008539 // Now check for #3 and #4.
Chris Lattnereabc15c2006-11-11 00:56:29 +00008540 bool RealUse = false;
Lang Hames5a004992011-07-07 04:31:51 +00008541
8542 // Caches for hasPredecessorHelper
8543 SmallPtrSet<const SDNode *, 32> Visited;
8544 SmallVector<const SDNode *, 16> Worklist;
8545
Jim Grosbache8160032014-04-11 01:13:13 +00008546 for (SDNode *Use : Ptr.getNode()->uses()) {
Chris Lattnereabc15c2006-11-11 00:56:29 +00008547 if (Use == N)
8548 continue;
Lang Hames5a004992011-07-07 04:31:51 +00008549 if (N->hasPredecessorHelper(Use, Visited, Worklist))
Chris Lattnereabc15c2006-11-11 00:56:29 +00008550 return false;
8551
Evan Chengfa832632012-01-13 01:37:24 +00008552 // If Ptr may be folded in addressing mode of other use, then it's
8553 // not profitable to do this transformation.
8554 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
Chris Lattnereabc15c2006-11-11 00:56:29 +00008555 RealUse = true;
8556 }
Bill Wendling306bfc22009-01-30 23:27:35 +00008557
Chris Lattnereabc15c2006-11-11 00:56:29 +00008558 if (!RealUse)
8559 return false;
8560
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008561 SDValue Result;
Chris Lattnereabc15c2006-11-11 00:56:29 +00008562 if (isLoad)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008563 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00008564 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00008565 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00008566 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00008567 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00008568 ++PreIndexedNodes;
8569 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +00008570 DEBUG(dbgs() << "\nReplacing.4 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00008571 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00008572 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00008573 Result.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00008574 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008575 WorklistRemover DeadNodes(*this);
Chris Lattnereabc15c2006-11-11 00:56:29 +00008576 if (isLoad) {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008577 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8578 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
Chris Lattnereabc15c2006-11-11 00:56:29 +00008579 } else {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008580 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
Chris Lattnereabc15c2006-11-11 00:56:29 +00008581 }
8582
Chris Lattnereabc15c2006-11-11 00:56:29 +00008583 // Finally, since the node is now dead, remove it from the graph.
Chandler Carruth18066972014-08-02 10:02:07 +00008584 deleteAndRecombine(N);
Chris Lattnereabc15c2006-11-11 00:56:29 +00008585
Hal Finkel25819052013-02-08 21:35:47 +00008586 if (Swapped)
8587 std::swap(BasePtr, Offset);
8588
8589 // Replace other uses of BasePtr that can be updated to use Ptr
8590 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
8591 unsigned OffsetIdx = 1;
8592 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
8593 OffsetIdx = 0;
8594 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
8595 BasePtr.getNode() && "Expected BasePtr operand");
8596
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00008597 // We need to replace ptr0 in the following expression:
8598 // x0 * offset0 + y0 * ptr0 = t0
8599 // knowing that
8600 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
Stephen Lincfe7f352013-07-08 00:37:03 +00008601 //
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00008602 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
8603 // indexed load/store and the expresion that needs to be re-written.
8604 //
8605 // Therefore, we have:
8606 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
Hal Finkel25819052013-02-08 21:35:47 +00008607
8608 ConstantSDNode *CN =
8609 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00008610 int X0, X1, Y0, Y1;
8611 APInt Offset0 = CN->getAPIntValue();
8612 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
Hal Finkel25819052013-02-08 21:35:47 +00008613
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00008614 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
8615 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
8616 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
8617 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
Hal Finkel25819052013-02-08 21:35:47 +00008618
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00008619 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
8620
8621 APInt CNV = Offset0;
8622 if (X0 < 0) CNV = -CNV;
8623 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
8624 else CNV = CNV - Offset1;
8625
8626 // We can now generate the new expression.
8627 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
8628 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
8629
8630 SDValue NewUse = DAG.getNode(Opcode,
Andrew Trickef9de2a2013-05-25 02:42:55 +00008631 SDLoc(OtherUses[i]),
Hal Finkel25819052013-02-08 21:35:47 +00008632 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
8633 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
Chandler Carruth18066972014-08-02 10:02:07 +00008634 deleteAndRecombine(OtherUses[i]);
Hal Finkel25819052013-02-08 21:35:47 +00008635 }
8636
Chris Lattnereabc15c2006-11-11 00:56:29 +00008637 // Replace the uses of Ptr with uses of the updated base value.
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008638 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
Chandler Carruth18066972014-08-02 10:02:07 +00008639 deleteAndRecombine(Ptr.getNode());
Chris Lattnereabc15c2006-11-11 00:56:29 +00008640
8641 return true;
Chris Lattnerffad2162006-11-11 00:39:41 +00008642}
8643
Sanjay Patel50cbfc52014-08-28 16:29:51 +00008644/// Try to combine a load/store with a add/sub of the base pointer node into a
8645/// post-indexed load/store. The transformation folded the add/subtract into the
8646/// new indexed load/store effectively and all of its uses are redirected to the
8647/// new load/store.
Chris Lattnerffad2162006-11-11 00:39:41 +00008648bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
Eli Friedman9d448e42011-11-12 00:35:34 +00008649 if (Level < AfterLegalizeDAG)
Chris Lattnerffad2162006-11-11 00:39:41 +00008650 return false;
8651
8652 bool isLoad = true;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008653 SDValue Ptr;
Owen Anderson53aa7a92009-08-10 22:56:29 +00008654 EVT VT;
Chris Lattnerffad2162006-11-11 00:39:41 +00008655 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00008656 if (LD->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00008657 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00008658 VT = LD->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00008659 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
8660 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
8661 return false;
8662 Ptr = LD->getBasePtr();
8663 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00008664 if (ST->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00008665 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00008666 VT = ST->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00008667 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
8668 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
8669 return false;
8670 Ptr = ST->getBasePtr();
8671 isLoad = false;
Bill Wendling306bfc22009-01-30 23:27:35 +00008672 } else {
Chris Lattnerffad2162006-11-11 00:39:41 +00008673 return false;
Bill Wendling306bfc22009-01-30 23:27:35 +00008674 }
Chris Lattnerffad2162006-11-11 00:39:41 +00008675
Gabor Greiff304a7a2008-08-28 21:40:38 +00008676 if (Ptr.getNode()->hasOneUse())
Chris Lattnereabc15c2006-11-11 00:56:29 +00008677 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00008678
Jim Grosbache8160032014-04-11 01:13:13 +00008679 for (SDNode *Op : Ptr.getNode()->uses()) {
Chris Lattnereabc15c2006-11-11 00:56:29 +00008680 if (Op == N ||
8681 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
8682 continue;
8683
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008684 SDValue BasePtr;
8685 SDValue Offset;
Chris Lattnereabc15c2006-11-11 00:56:29 +00008686 ISD::MemIndexedMode AM = ISD::UNINDEXED;
8687 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
Evan Cheng044a0a82007-05-03 23:52:19 +00008688 // Don't create a indexed load / store with zero offset.
8689 if (isa<ConstantSDNode>(Offset) &&
Dan Gohmanb72127a2008-03-13 22:13:53 +00008690 cast<ConstantSDNode>(Offset)->isNullValue())
Evan Cheng044a0a82007-05-03 23:52:19 +00008691 continue;
Chris Lattnerffad2162006-11-11 00:39:41 +00008692
Chris Lattnereabc15c2006-11-11 00:56:29 +00008693 // Try turning it into a post-indexed load / store except when
Evan Chengfa832632012-01-13 01:37:24 +00008694 // 1) All uses are load / store ops that use it as base ptr (and
8695 // it may be folded as addressing mmode).
Chris Lattnereabc15c2006-11-11 00:56:29 +00008696 // 2) Op must be independent of N, i.e. Op is neither a predecessor
8697 // nor a successor of N. Otherwise, if Op is folded that would
8698 // create a cycle.
8699
Evan Chengcfc05132009-05-06 18:25:01 +00008700 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
8701 continue;
8702
Chris Lattnereabc15c2006-11-11 00:56:29 +00008703 // Check for #1.
8704 bool TryNext = false;
Jim Grosbache8160032014-04-11 01:13:13 +00008705 for (SDNode *Use : BasePtr.getNode()->uses()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00008706 if (Use == Ptr.getNode())
Chris Lattnerffad2162006-11-11 00:39:41 +00008707 continue;
8708
Chris Lattnereabc15c2006-11-11 00:56:29 +00008709 // If all the uses are load / store addresses, then don't do the
8710 // transformation.
8711 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
8712 bool RealUse = false;
Jim Grosbache8160032014-04-11 01:13:13 +00008713 for (SDNode *UseUse : Use->uses()) {
Stephen Lincfe7f352013-07-08 00:37:03 +00008714 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
Chris Lattnereabc15c2006-11-11 00:56:29 +00008715 RealUse = true;
8716 }
Chris Lattnerffad2162006-11-11 00:39:41 +00008717
Chris Lattnereabc15c2006-11-11 00:56:29 +00008718 if (!RealUse) {
8719 TryNext = true;
8720 break;
Chris Lattnerffad2162006-11-11 00:39:41 +00008721 }
8722 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00008723 }
Bill Wendling306bfc22009-01-30 23:27:35 +00008724
Chris Lattnereabc15c2006-11-11 00:56:29 +00008725 if (TryNext)
8726 continue;
Chris Lattnerffad2162006-11-11 00:39:41 +00008727
Chris Lattnereabc15c2006-11-11 00:56:29 +00008728 // Check for #2
Evan Cheng567d2e52008-03-04 00:41:45 +00008729 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008730 SDValue Result = isLoad
Andrew Trickef9de2a2013-05-25 02:42:55 +00008731 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00008732 BasePtr, Offset, AM)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008733 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00008734 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00008735 ++PostIndexedNodes;
8736 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +00008737 DEBUG(dbgs() << "\nReplacing.5 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00008738 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00008739 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00008740 Result.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00008741 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008742 WorklistRemover DeadNodes(*this);
Chris Lattnereabc15c2006-11-11 00:56:29 +00008743 if (isLoad) {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008744 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8745 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
Chris Lattnereabc15c2006-11-11 00:56:29 +00008746 } else {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008747 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
Chris Lattnerffad2162006-11-11 00:39:41 +00008748 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00008749
Chris Lattnereabc15c2006-11-11 00:56:29 +00008750 // Finally, since the node is now dead, remove it from the graph.
Chandler Carruth18066972014-08-02 10:02:07 +00008751 deleteAndRecombine(N);
Chris Lattnereabc15c2006-11-11 00:56:29 +00008752
8753 // Replace the uses of Use with uses of the updated base value.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008754 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008755 Result.getValue(isLoad ? 1 : 0));
Chandler Carruth18066972014-08-02 10:02:07 +00008756 deleteAndRecombine(Op);
Chris Lattnereabc15c2006-11-11 00:56:29 +00008757 return true;
Chris Lattnerffad2162006-11-11 00:39:41 +00008758 }
8759 }
8760 }
Bill Wendling306bfc22009-01-30 23:27:35 +00008761
Chris Lattnerffad2162006-11-11 00:39:41 +00008762 return false;
8763}
8764
Hal Finkel51e6fa22014-09-02 06:24:04 +00008765/// \brief Return the base-pointer arithmetic from an indexed \p LD.
8766SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
8767 ISD::MemIndexedMode AM = LD->getAddressingMode();
8768 assert(AM != ISD::UNINDEXED);
8769 SDValue BP = LD->getOperand(1);
8770 SDValue Inc = LD->getOperand(2);
Hal Finkele19006e2014-09-02 16:05:23 +00008771
8772 // Some backends use TargetConstants for load offsets, but don't expect
8773 // TargetConstants in general ADD nodes. We can convert these constants into
8774 // regular Constants (if the constant is not opaque).
8775 assert((Inc.getOpcode() != ISD::TargetConstant ||
8776 !cast<ConstantSDNode>(Inc)->isOpaque()) &&
8777 "Cannot split out indexing using opaque target constants");
8778 if (Inc.getOpcode() == ISD::TargetConstant) {
8779 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
8780 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(),
8781 ConstInc->getValueType(0));
8782 }
8783
Hal Finkel51e6fa22014-09-02 06:24:04 +00008784 unsigned Opc =
8785 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
8786 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
8787}
8788
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008789SDValue DAGCombiner::visitLOAD(SDNode *N) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00008790 LoadSDNode *LD = cast<LoadSDNode>(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008791 SDValue Chain = LD->getChain();
8792 SDValue Ptr = LD->getBasePtr();
Scott Michelcf0da6c2009-02-17 22:15:04 +00008793
Evan Chenga684cd22007-05-01 00:38:21 +00008794 // If load is not volatile and there are no uses of the loaded value (and
8795 // the updated indexed value in case of indexed loads), change uses of the
8796 // chain value into uses of the chain input (i.e. delete the dead load).
8797 if (!LD->isVolatile()) {
Owen Anderson9f944592009-08-11 20:47:22 +00008798 if (N->getValueType(1) == MVT::Other) {
Evan Chengb68343c2007-05-01 08:53:39 +00008799 // Unindexed loads.
Craig Topper0515cd42012-01-07 18:31:09 +00008800 if (!N->hasAnyUseOfValue(0)) {
Evan Cheng7be15282008-01-16 23:11:54 +00008801 // It's not safe to use the two value CombineTo variant here. e.g.
8802 // v1, chain2 = load chain1, loc
8803 // v2, chain3 = load chain2, loc
8804 // v3 = add v2, c
Chris Lattnere97fa8c2008-01-24 07:57:06 +00008805 // Now we replace use of chain2 with chain1. This makes the second load
8806 // isomorphic to the one we are deleting, and thus makes this load live.
David Greenefe5c3522010-01-05 01:25:00 +00008807 DEBUG(dbgs() << "\nReplacing.6 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00008808 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00008809 dbgs() << "\nWith chain: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00008810 Chain.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00008811 dbgs() << "\n");
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008812 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008813 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
Bill Wendling306bfc22009-01-30 23:27:35 +00008814
Chandler Carruth18066972014-08-02 10:02:07 +00008815 if (N->use_empty())
8816 deleteAndRecombine(N);
Bill Wendling306bfc22009-01-30 23:27:35 +00008817
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008818 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Cheng7be15282008-01-16 23:11:54 +00008819 }
Evan Chengb68343c2007-05-01 08:53:39 +00008820 } else {
8821 // Indexed loads.
Owen Anderson9f944592009-08-11 20:47:22 +00008822 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
Hal Finkel51e6fa22014-09-02 06:24:04 +00008823
Hal Finkele19006e2014-09-02 16:05:23 +00008824 // If this load has an opaque TargetConstant offset, then we cannot split
8825 // the indexing into an add/sub directly (that TargetConstant may not be
8826 // valid for a different type of node, and we cannot convert an opaque
8827 // target constant into a regular constant).
8828 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
8829 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
Hal Finkel51e6fa22014-09-02 06:24:04 +00008830
8831 if (!N->hasAnyUseOfValue(0) &&
Hal Finkele19006e2014-09-02 16:05:23 +00008832 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
Dale Johannesen84935752009-02-06 23:05:02 +00008833 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
Hal Finkel51e6fa22014-09-02 06:24:04 +00008834 SDValue Index;
Hal Finkele19006e2014-09-02 16:05:23 +00008835 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
Hal Finkel51e6fa22014-09-02 06:24:04 +00008836 Index = SplitIndexingFromLoad(LD);
8837 // Try to fold the base pointer arithmetic into subsequent loads and
8838 // stores.
8839 AddUsersToWorklist(N);
8840 } else
8841 Index = DAG.getUNDEF(N->getValueType(1));
Evan Cheng228c31f2010-02-27 07:36:59 +00008842 DEBUG(dbgs() << "\nReplacing.7 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00008843 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00008844 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00008845 Undef.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00008846 dbgs() << " and 2 other values\n");
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008847 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008848 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
Hal Finkel51e6fa22014-09-02 06:24:04 +00008849 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008850 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
Chandler Carruth18066972014-08-02 10:02:07 +00008851 deleteAndRecombine(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008852 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga684cd22007-05-01 00:38:21 +00008853 }
Evan Chenga684cd22007-05-01 00:38:21 +00008854 }
8855 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00008856
Chris Lattnere260ed82005-10-10 22:04:48 +00008857 // If this load is directly stored, replace the load value with the stored
8858 // value.
8859 // TODO: Handle store large -> read small portion.
Jim Laskey0f7c3282006-10-11 17:47:52 +00008860 // TODO: Handle TRUNCSTORE/LOADEXT
Evan Chengadb9c032011-03-11 00:48:56 +00008861 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00008862 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
Evan Chengab51cf22006-10-13 21:14:26 +00008863 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
8864 if (PrevST->getBasePtr() == Ptr &&
8865 PrevST->getValue().getValueType() == N->getValueType(0))
Jim Laskey0f7c3282006-10-11 17:47:52 +00008866 return CombineTo(N, Chain.getOperand(1), Chain);
Evan Chengab51cf22006-10-13 21:14:26 +00008867 }
Jim Laskey0f7c3282006-10-11 17:47:52 +00008868 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00008869
Evan Cheng43cd9e32010-04-01 06:04:33 +00008870 // Try to infer better alignment information than the load already has.
8871 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
Evan Cheng4a5b2042011-11-28 22:37:34 +00008872 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
Owen Andersonde89ecf2013-02-05 19:24:39 +00008873 if (Align > LD->getMemOperand()->getBaseAlignment()) {
8874 SDValue NewLoad =
Andrew Trickef9de2a2013-05-25 02:42:55 +00008875 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
Evan Cheng4a5b2042011-11-28 22:37:34 +00008876 LD->getValueType(0),
8877 Chain, Ptr, LD->getPointerInfo(),
8878 LD->getMemoryVT(),
Louis Gerbarg67474e32014-07-31 21:45:05 +00008879 LD->isVolatile(), LD->isNonTemporal(),
8880 LD->isInvariant(), Align, LD->getAAInfo());
Owen Andersonde89ecf2013-02-05 19:24:39 +00008881 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
8882 }
Evan Cheng43cd9e32010-04-01 06:04:33 +00008883 }
8884 }
8885
Eric Christopherf55d4712014-10-08 23:38:39 +00008886 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
8887 : DAG.getSubtarget().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +00008888#ifndef NDEBUG
8889 if (CombinerAAOnlyFunc.getNumOccurrences() &&
8890 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
8891 UseAA = false;
8892#endif
Hal Finkelccc18e12014-01-24 18:25:26 +00008893 if (UseAA && LD->isUnindexed()) {
Jim Laskeyd07be232006-09-25 16:29:54 +00008894 // Walk up chain skipping non-aliasing memory nodes.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008895 SDValue BetterChain = FindBetterChain(N, Chain);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008896
Jim Laskey708d0db2006-10-04 16:53:27 +00008897 // If there is a better chain.
Jim Laskeyd07be232006-09-25 16:29:54 +00008898 if (Chain != BetterChain) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008899 SDValue ReplLoad;
Jim Laskey0f7c3282006-10-11 17:47:52 +00008900
Jim Laskeyd07be232006-09-25 16:29:54 +00008901 // Replace the chain to void dependency.
Jim Laskey0f7c3282006-10-11 17:47:52 +00008902 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00008903 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00008904 BetterChain, Ptr, LD->getMemOperand());
Jim Laskey0f7c3282006-10-11 17:47:52 +00008905 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +00008906 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
Stuart Hastings81c43062011-02-16 16:23:55 +00008907 LD->getValueType(0),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00008908 BetterChain, Ptr, LD->getMemoryVT(),
8909 LD->getMemOperand());
Jim Laskey0f7c3282006-10-11 17:47:52 +00008910 }
Jim Laskeyd07be232006-09-25 16:29:54 +00008911
Jim Laskey708d0db2006-10-04 16:53:27 +00008912 // Create token factor to keep old chain connected.
Andrew Trickef9de2a2013-05-25 02:42:55 +00008913 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
Owen Anderson9f944592009-08-11 20:47:22 +00008914 MVT::Other, Chain, ReplLoad.getValue(1));
Wesley Peck527da1b2010-11-23 03:31:01 +00008915
Nate Begeman879d8f12009-09-15 00:18:30 +00008916 // Make sure the new and old chains are cleaned up.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008917 AddToWorklist(Token.getNode());
Wesley Peck527da1b2010-11-23 03:31:01 +00008918
Jim Laskeydcf983c2006-10-13 23:32:28 +00008919 // Replace uses with load result and token factor. Don't add users
8920 // to work list.
8921 return CombineTo(N, ReplLoad.getValue(0), Token, false);
Jim Laskeyd07be232006-09-25 16:29:54 +00008922 }
8923 }
8924
Evan Cheng357017f2006-11-03 03:06:21 +00008925 // Try transforming N to an indexed load.
Evan Cheng60c68462006-11-07 09:03:05 +00008926 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008927 return SDValue(N, 0);
Evan Cheng357017f2006-11-03 03:06:21 +00008928
Quentin Colombetde0e0622013-10-11 18:29:42 +00008929 // Try to slice up N to more direct loads if the slices are mapped to
8930 // different register banks or pairing can take place.
8931 if (SliceUpLoad(N))
8932 return SDValue(N, 0);
8933
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008934 return SDValue();
Chris Lattnere260ed82005-10-10 22:04:48 +00008935}
8936
Quentin Colombetde0e0622013-10-11 18:29:42 +00008937namespace {
8938/// \brief Helper structure used to slice a load in smaller loads.
8939/// Basically a slice is obtained from the following sequence:
8940/// Origin = load Ty1, Base
8941/// Shift = srl Ty1 Origin, CstTy Amount
8942/// Inst = trunc Shift to Ty2
8943///
8944/// Then, it will be rewriten into:
8945/// Slice = load SliceTy, Base + SliceOffset
8946/// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8947///
8948/// SliceTy is deduced from the number of bits that are actually used to
8949/// build Inst.
8950struct LoadedSlice {
8951 /// \brief Helper structure used to compute the cost of a slice.
8952 struct Cost {
8953 /// Are we optimizing for code size.
8954 bool ForCodeSize;
8955 /// Various cost.
8956 unsigned Loads;
8957 unsigned Truncates;
8958 unsigned CrossRegisterBanksCopies;
8959 unsigned ZExts;
8960 unsigned Shift;
8961
8962 Cost(bool ForCodeSize = false)
8963 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8964 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8965
8966 /// \brief Get the cost of one isolated slice.
8967 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8968 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8969 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8970 EVT TruncType = LS.Inst->getValueType(0);
8971 EVT LoadedType = LS.getLoadedType();
8972 if (TruncType != LoadedType &&
8973 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8974 ZExts = 1;
8975 }
8976
8977 /// \brief Account for slicing gain in the current cost.
8978 /// Slicing provide a few gains like removing a shift or a
8979 /// truncate. This method allows to grow the cost of the original
8980 /// load with the gain from this slice.
8981 void addSliceGain(const LoadedSlice &LS) {
8982 // Each slice saves a truncate.
8983 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8984 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8985 LS.Inst->getOperand(0).getValueType()))
8986 ++Truncates;
8987 // If there is a shift amount, this slice gets rid of it.
8988 if (LS.Shift)
8989 ++Shift;
8990 // If this slice can merge a cross register bank copy, account for it.
8991 if (LS.canMergeExpensiveCrossRegisterBankCopy())
8992 ++CrossRegisterBanksCopies;
8993 }
8994
8995 Cost &operator+=(const Cost &RHS) {
8996 Loads += RHS.Loads;
8997 Truncates += RHS.Truncates;
8998 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8999 ZExts += RHS.ZExts;
9000 Shift += RHS.Shift;
9001 return *this;
9002 }
9003
9004 bool operator==(const Cost &RHS) const {
9005 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9006 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9007 ZExts == RHS.ZExts && Shift == RHS.Shift;
9008 }
9009
9010 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
9011
9012 bool operator<(const Cost &RHS) const {
9013 // Assume cross register banks copies are as expensive as loads.
9014 // FIXME: Do we want some more target hooks?
9015 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
9016 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
9017 // Unless we are optimizing for code size, consider the
9018 // expensive operation first.
9019 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
9020 return ExpensiveOpsLHS < ExpensiveOpsRHS;
9021 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
9022 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
9023 }
9024
9025 bool operator>(const Cost &RHS) const { return RHS < *this; }
9026
9027 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
9028
9029 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
9030 };
9031 // The last instruction that represent the slice. This should be a
9032 // truncate instruction.
9033 SDNode *Inst;
9034 // The original load instruction.
9035 LoadSDNode *Origin;
9036 // The right shift amount in bits from the original load.
9037 unsigned Shift;
9038 // The DAG from which Origin came from.
9039 // This is used to get some contextual information about legal types, etc.
9040 SelectionDAG *DAG;
9041
Craig Topperc0196b12014-04-14 00:51:57 +00009042 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
9043 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
Quentin Colombetde0e0622013-10-11 18:29:42 +00009044 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
9045
9046 LoadedSlice(const LoadedSlice &LS)
9047 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
9048
9049 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
9050 /// \return Result is \p BitWidth and has used bits set to 1 and
9051 /// not used bits set to 0.
9052 APInt getUsedBits() const {
9053 // Reproduce the trunc(lshr) sequence:
9054 // - Start from the truncated value.
9055 // - Zero extend to the desired bit width.
9056 // - Shift left.
9057 assert(Origin && "No original load to compare against.");
9058 unsigned BitWidth = Origin->getValueSizeInBits(0);
9059 assert(Inst && "This slice is not bound to an instruction");
9060 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
9061 "Extracted slice is bigger than the whole type!");
9062 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
9063 UsedBits.setAllBits();
9064 UsedBits = UsedBits.zext(BitWidth);
9065 UsedBits <<= Shift;
9066 return UsedBits;
9067 }
9068
9069 /// \brief Get the size of the slice to be loaded in bytes.
9070 unsigned getLoadedSize() const {
9071 unsigned SliceSize = getUsedBits().countPopulation();
9072 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
9073 return SliceSize / 8;
9074 }
9075
9076 /// \brief Get the type that will be loaded for this slice.
9077 /// Note: This may not be the final type for the slice.
9078 EVT getLoadedType() const {
9079 assert(DAG && "Missing context");
9080 LLVMContext &Ctxt = *DAG->getContext();
9081 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
9082 }
9083
9084 /// \brief Get the alignment of the load used for this slice.
9085 unsigned getAlignment() const {
9086 unsigned Alignment = Origin->getAlignment();
9087 unsigned Offset = getOffsetFromBase();
9088 if (Offset != 0)
9089 Alignment = MinAlign(Alignment, Alignment + Offset);
9090 return Alignment;
9091 }
9092
9093 /// \brief Check if this slice can be rewritten with legal operations.
9094 bool isLegal() const {
9095 // An invalid slice is not legal.
9096 if (!Origin || !Inst || !DAG)
9097 return false;
9098
9099 // Offsets are for indexed load only, we do not handle that.
9100 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
9101 return false;
9102
9103 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9104
9105 // Check that the type is legal.
9106 EVT SliceType = getLoadedType();
9107 if (!TLI.isTypeLegal(SliceType))
9108 return false;
9109
9110 // Check that the load is legal for this type.
9111 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
9112 return false;
9113
9114 // Check that the offset can be computed.
9115 // 1. Check its type.
9116 EVT PtrType = Origin->getBasePtr().getValueType();
9117 if (PtrType == MVT::Untyped || PtrType.isExtended())
9118 return false;
9119
9120 // 2. Check that it fits in the immediate.
9121 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
9122 return false;
9123
9124 // 3. Check that the computation is legal.
9125 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
9126 return false;
9127
9128 // Check that the zext is legal if it needs one.
9129 EVT TruncateType = Inst->getValueType(0);
9130 if (TruncateType != SliceType &&
9131 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
9132 return false;
9133
9134 return true;
9135 }
9136
9137 /// \brief Get the offset in bytes of this slice in the original chunk of
9138 /// bits.
Craig Topperc0196b12014-04-14 00:51:57 +00009139 /// \pre DAG != nullptr.
Quentin Colombetde0e0622013-10-11 18:29:42 +00009140 uint64_t getOffsetFromBase() const {
9141 assert(DAG && "Missing context.");
9142 bool IsBigEndian =
9143 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
9144 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
9145 uint64_t Offset = Shift / 8;
9146 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
9147 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
9148 "The size of the original loaded type is not a multiple of a"
9149 " byte.");
9150 // If Offset is bigger than TySizeInBytes, it means we are loading all
9151 // zeros. This should have been optimized before in the process.
9152 assert(TySizeInBytes > Offset &&
9153 "Invalid shift amount for given loaded size");
9154 if (IsBigEndian)
9155 Offset = TySizeInBytes - Offset - getLoadedSize();
9156 return Offset;
9157 }
9158
9159 /// \brief Generate the sequence of instructions to load the slice
9160 /// represented by this object and redirect the uses of this slice to
9161 /// this new sequence of instructions.
9162 /// \pre this->Inst && this->Origin are valid Instructions and this
9163 /// object passed the legal check: LoadedSlice::isLegal returned true.
9164 /// \return The last instruction of the sequence used to load the slice.
9165 SDValue loadSlice() const {
9166 assert(Inst && Origin && "Unable to replace a non-existing slice.");
9167 const SDValue &OldBaseAddr = Origin->getBasePtr();
9168 SDValue BaseAddr = OldBaseAddr;
9169 // Get the offset in that chunk of bytes w.r.t. the endianess.
9170 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
9171 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
9172 if (Offset) {
9173 // BaseAddr = BaseAddr + Offset.
9174 EVT ArithType = BaseAddr.getValueType();
9175 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
9176 DAG->getConstant(Offset, ArithType));
9177 }
9178
9179 // Create the type of the loaded slice according to its size.
9180 EVT SliceType = getLoadedType();
9181
9182 // Create the load for the slice.
9183 SDValue LastInst = DAG->getLoad(
9184 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
9185 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
9186 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
9187 // If the final type is not the same as the loaded type, this means that
9188 // we have to pad with zero. Create a zero extend for that.
9189 EVT FinalType = Inst->getValueType(0);
9190 if (SliceType != FinalType)
9191 LastInst =
9192 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
9193 return LastInst;
9194 }
9195
9196 /// \brief Check if this slice can be merged with an expensive cross register
9197 /// bank copy. E.g.,
9198 /// i = load i32
9199 /// f = bitcast i32 i to float
9200 bool canMergeExpensiveCrossRegisterBankCopy() const {
9201 if (!Inst || !Inst->hasOneUse())
9202 return false;
9203 SDNode *Use = *Inst->use_begin();
9204 if (Use->getOpcode() != ISD::BITCAST)
9205 return false;
9206 assert(DAG && "Missing context");
9207 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9208 EVT ResVT = Use->getValueType(0);
9209 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
9210 const TargetRegisterClass *ArgRC =
9211 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
9212 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
9213 return false;
9214
9215 // At this point, we know that we perform a cross-register-bank copy.
9216 // Check if it is expensive.
Eric Christopherf55d4712014-10-08 23:38:39 +00009217 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
Quentin Colombetde0e0622013-10-11 18:29:42 +00009218 // Assume bitcasts are cheap, unless both register classes do not
9219 // explicitly share a common sub class.
9220 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
9221 return false;
9222
9223 // Check if it will be merged with the load.
9224 // 1. Check the alignment constraint.
9225 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
9226 ResVT.getTypeForEVT(*DAG->getContext()));
9227
9228 if (RequiredAlignment > getAlignment())
9229 return false;
9230
9231 // 2. Check that the load is a legal operation for that type.
9232 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
9233 return false;
9234
9235 // 3. Check that we do not have a zext in the way.
9236 if (Inst->getValueType(0) != getLoadedType())
9237 return false;
9238
9239 return true;
9240 }
9241};
9242}
9243
Quentin Colombetde0e0622013-10-11 18:29:42 +00009244/// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
9245/// \p UsedBits looks like 0..0 1..1 0..0.
9246static bool areUsedBitsDense(const APInt &UsedBits) {
9247 // If all the bits are one, this is dense!
9248 if (UsedBits.isAllOnesValue())
9249 return true;
9250
9251 // Get rid of the unused bits on the right.
9252 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
9253 // Get rid of the unused bits on the left.
9254 if (NarrowedUsedBits.countLeadingZeros())
9255 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
9256 // Check that the chunk of bits is completely used.
9257 return NarrowedUsedBits.isAllOnesValue();
9258}
9259
9260/// \brief Check whether or not \p First and \p Second are next to each other
9261/// in memory. This means that there is no hole between the bits loaded
9262/// by \p First and the bits loaded by \p Second.
9263static bool areSlicesNextToEachOther(const LoadedSlice &First,
9264 const LoadedSlice &Second) {
9265 assert(First.Origin == Second.Origin && First.Origin &&
9266 "Unable to match different memory origins.");
9267 APInt UsedBits = First.getUsedBits();
9268 assert((UsedBits & Second.getUsedBits()) == 0 &&
9269 "Slices are not supposed to overlap.");
9270 UsedBits |= Second.getUsedBits();
9271 return areUsedBitsDense(UsedBits);
9272}
9273
9274/// \brief Adjust the \p GlobalLSCost according to the target
9275/// paring capabilities and the layout of the slices.
9276/// \pre \p GlobalLSCost should account for at least as many loads as
9277/// there is in the slices in \p LoadedSlices.
9278static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9279 LoadedSlice::Cost &GlobalLSCost) {
9280 unsigned NumberOfSlices = LoadedSlices.size();
9281 // If there is less than 2 elements, no pairing is possible.
9282 if (NumberOfSlices < 2)
9283 return;
9284
9285 // Sort the slices so that elements that are likely to be next to each
9286 // other in memory are next to each other in the list.
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00009287 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
9288 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
9289 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
9290 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
9291 });
Quentin Colombetde0e0622013-10-11 18:29:42 +00009292 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
9293 // First (resp. Second) is the first (resp. Second) potentially candidate
9294 // to be placed in a paired load.
Craig Topperc0196b12014-04-14 00:51:57 +00009295 const LoadedSlice *First = nullptr;
9296 const LoadedSlice *Second = nullptr;
Quentin Colombetde0e0622013-10-11 18:29:42 +00009297 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
9298 // Set the beginning of the pair.
9299 First = Second) {
9300
9301 Second = &LoadedSlices[CurrSlice];
9302
9303 // If First is NULL, it means we start a new pair.
9304 // Get to the next slice.
9305 if (!First)
9306 continue;
9307
9308 EVT LoadedType = First->getLoadedType();
9309
9310 // If the types of the slices are different, we cannot pair them.
9311 if (LoadedType != Second->getLoadedType())
9312 continue;
9313
9314 // Check if the target supplies paired loads for this type.
9315 unsigned RequiredAlignment = 0;
9316 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
9317 // move to the next pair, this type is hopeless.
Craig Topperc0196b12014-04-14 00:51:57 +00009318 Second = nullptr;
Quentin Colombetde0e0622013-10-11 18:29:42 +00009319 continue;
9320 }
9321 // Check if we meet the alignment requirement.
9322 if (RequiredAlignment > First->getAlignment())
9323 continue;
9324
9325 // Check that both loads are next to each other in memory.
9326 if (!areSlicesNextToEachOther(*First, *Second))
9327 continue;
9328
9329 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
9330 --GlobalLSCost.Loads;
9331 // Move to the next pair.
Craig Topperc0196b12014-04-14 00:51:57 +00009332 Second = nullptr;
Quentin Colombetde0e0622013-10-11 18:29:42 +00009333 }
9334}
9335
9336/// \brief Check the profitability of all involved LoadedSlice.
9337/// Currently, it is considered profitable if there is exactly two
9338/// involved slices (1) which are (2) next to each other in memory, and
9339/// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
9340///
9341/// Note: The order of the elements in \p LoadedSlices may be modified, but not
9342/// the elements themselves.
9343///
9344/// FIXME: When the cost model will be mature enough, we can relax
9345/// constraints (1) and (2).
9346static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9347 const APInt &UsedBits, bool ForCodeSize) {
9348 unsigned NumberOfSlices = LoadedSlices.size();
9349 if (StressLoadSlicing)
9350 return NumberOfSlices > 1;
9351
9352 // Check (1).
9353 if (NumberOfSlices != 2)
9354 return false;
9355
9356 // Check (2).
9357 if (!areUsedBitsDense(UsedBits))
9358 return false;
9359
9360 // Check (3).
9361 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
9362 // The original code has one big load.
9363 OrigCost.Loads = 1;
9364 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
9365 const LoadedSlice &LS = LoadedSlices[CurrSlice];
9366 // Accumulate the cost of all the slices.
9367 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
9368 GlobalSlicingCost += SliceCost;
9369
9370 // Account as cost in the original configuration the gain obtained
9371 // with the current slices.
9372 OrigCost.addSliceGain(LS);
9373 }
9374
9375 // If the target supports paired load, adjust the cost accordingly.
9376 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
9377 return OrigCost > GlobalSlicingCost;
9378}
9379
9380/// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
9381/// operations, split it in the various pieces being extracted.
9382///
9383/// This sort of thing is introduced by SROA.
9384/// This slicing takes care not to insert overlapping loads.
9385/// \pre LI is a simple load (i.e., not an atomic or volatile load).
9386bool DAGCombiner::SliceUpLoad(SDNode *N) {
9387 if (Level < AfterLegalizeDAG)
9388 return false;
9389
9390 LoadSDNode *LD = cast<LoadSDNode>(N);
9391 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
9392 !LD->getValueType(0).isInteger())
9393 return false;
9394
9395 // Keep track of already used bits to detect overlapping values.
9396 // In that case, we will just abort the transformation.
9397 APInt UsedBits(LD->getValueSizeInBits(0), 0);
9398
9399 SmallVector<LoadedSlice, 4> LoadedSlices;
9400
9401 // Check if this load is used as several smaller chunks of bits.
9402 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
9403 // of computation for each trunc.
9404 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
9405 UI != UIEnd; ++UI) {
9406 // Skip the uses of the chain.
9407 if (UI.getUse().getResNo() != 0)
9408 continue;
9409
9410 SDNode *User = *UI;
9411 unsigned Shift = 0;
9412
9413 // Check if this is a trunc(lshr).
9414 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
9415 isa<ConstantSDNode>(User->getOperand(1))) {
9416 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
9417 User = *User->use_begin();
9418 }
9419
9420 // At this point, User is a Truncate, iff we encountered, trunc or
9421 // trunc(lshr).
9422 if (User->getOpcode() != ISD::TRUNCATE)
9423 return false;
9424
9425 // The width of the type must be a power of 2 and greater than 8-bits.
9426 // Otherwise the load cannot be represented in LLVM IR.
Alp Tokerf907b892013-12-05 05:44:44 +00009427 // Moreover, if we shifted with a non-8-bits multiple, the slice
Alp Tokercb402912014-01-24 17:20:08 +00009428 // will be across several bytes. We do not support that.
Quentin Colombetde0e0622013-10-11 18:29:42 +00009429 unsigned Width = User->getValueSizeInBits(0);
9430 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
9431 return 0;
9432
9433 // Build the slice for this chain of computations.
9434 LoadedSlice LS(User, LD, Shift, &DAG);
9435 APInt CurrentUsedBits = LS.getUsedBits();
9436
9437 // Check if this slice overlaps with another.
9438 if ((CurrentUsedBits & UsedBits) != 0)
9439 return false;
9440 // Update the bits used globally.
9441 UsedBits |= CurrentUsedBits;
9442
9443 // Check if the new slice would be legal.
9444 if (!LS.isLegal())
9445 return false;
9446
9447 // Record the slice.
9448 LoadedSlices.push_back(LS);
9449 }
9450
9451 // Abort slicing if it does not seem to be profitable.
9452 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
9453 return false;
9454
9455 ++SlicedLoads;
9456
9457 // Rewrite each chain to use an independent load.
9458 // By construction, each chain can be represented by a unique load.
9459
9460 // Prepare the argument for the new token factor for all the slices.
9461 SmallVector<SDValue, 8> ArgChains;
9462 for (SmallVectorImpl<LoadedSlice>::const_iterator
9463 LSIt = LoadedSlices.begin(),
9464 LSItEnd = LoadedSlices.end();
9465 LSIt != LSItEnd; ++LSIt) {
9466 SDValue SliceInst = LSIt->loadSlice();
9467 CombineTo(LSIt->Inst, SliceInst, true);
9468 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
9469 SliceInst = SliceInst.getOperand(0);
9470 assert(SliceInst->getOpcode() == ISD::LOAD &&
9471 "It takes more than a zext to get to the loaded slice!!");
9472 ArgChains.push_back(SliceInst.getValue(1));
9473 }
9474
9475 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
Craig Topper48d114b2014-04-26 18:35:24 +00009476 ArgChains);
Quentin Colombetde0e0622013-10-11 18:29:42 +00009477 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9478 return true;
9479}
9480
Sanjay Patel50cbfc52014-08-28 16:29:51 +00009481/// Check to see if V is (and load (ptr), imm), where the load is having
9482/// specific bytes cleared out. If so, return the byte size being masked out
9483/// and the shift amount.
Chris Lattner4041ab62010-04-15 04:48:01 +00009484static std::pair<unsigned, unsigned>
9485CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
9486 std::pair<unsigned, unsigned> Result(0, 0);
Wesley Peck527da1b2010-11-23 03:31:01 +00009487
Chris Lattner4041ab62010-04-15 04:48:01 +00009488 // Check for the structure we're looking for.
9489 if (V->getOpcode() != ISD::AND ||
9490 !isa<ConstantSDNode>(V->getOperand(1)) ||
9491 !ISD::isNormalLoad(V->getOperand(0).getNode()))
9492 return Result;
Wesley Peck527da1b2010-11-23 03:31:01 +00009493
Chris Lattner3245afd2010-04-15 06:10:49 +00009494 // Check the chain and pointer.
Chris Lattner4041ab62010-04-15 04:48:01 +00009495 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
Chris Lattner3245afd2010-04-15 06:10:49 +00009496 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
Wesley Peck527da1b2010-11-23 03:31:01 +00009497
Chris Lattner3245afd2010-04-15 06:10:49 +00009498 // The store should be chained directly to the load or be an operand of a
9499 // tokenfactor.
9500 if (LD == Chain.getNode())
9501 ; // ok.
9502 else if (Chain->getOpcode() != ISD::TokenFactor)
9503 return Result; // Fail.
9504 else {
9505 bool isOk = false;
9506 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
9507 if (Chain->getOperand(i).getNode() == LD) {
9508 isOk = true;
9509 break;
9510 }
9511 if (!isOk) return Result;
9512 }
Wesley Peck527da1b2010-11-23 03:31:01 +00009513
Chris Lattner4041ab62010-04-15 04:48:01 +00009514 // This only handles simple types.
9515 if (V.getValueType() != MVT::i16 &&
9516 V.getValueType() != MVT::i32 &&
9517 V.getValueType() != MVT::i64)
9518 return Result;
9519
9520 // Check the constant mask. Invert it so that the bits being masked out are
9521 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
9522 // follow the sign bit for uniformity.
9523 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00009524 unsigned NotMaskLZ = countLeadingZeros(NotMask);
Chris Lattner4041ab62010-04-15 04:48:01 +00009525 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00009526 unsigned NotMaskTZ = countTrailingZeros(NotMask);
Chris Lattner4041ab62010-04-15 04:48:01 +00009527 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
9528 if (NotMaskLZ == 64) return Result; // All zero mask.
Wesley Peck527da1b2010-11-23 03:31:01 +00009529
Chris Lattner4041ab62010-04-15 04:48:01 +00009530 // See if we have a continuous run of bits. If so, we have 0*1+0*
Benjamin Kramer5f6a9072015-02-12 15:35:40 +00009531 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
Chris Lattner4041ab62010-04-15 04:48:01 +00009532 return Result;
9533
9534 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
9535 if (V.getValueType() != MVT::i64 && NotMaskLZ)
9536 NotMaskLZ -= 64-V.getValueSizeInBits();
Wesley Peck527da1b2010-11-23 03:31:01 +00009537
Chris Lattner4041ab62010-04-15 04:48:01 +00009538 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
9539 switch (MaskedBytes) {
Wesley Peck527da1b2010-11-23 03:31:01 +00009540 case 1:
9541 case 2:
Chris Lattner4041ab62010-04-15 04:48:01 +00009542 case 4: break;
9543 default: return Result; // All one mask, or 5-byte mask.
9544 }
Wesley Peck527da1b2010-11-23 03:31:01 +00009545
Chris Lattner4041ab62010-04-15 04:48:01 +00009546 // Verify that the first bit starts at a multiple of mask so that the access
9547 // is aligned the same as the access width.
9548 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
Wesley Peck527da1b2010-11-23 03:31:01 +00009549
Chris Lattner4041ab62010-04-15 04:48:01 +00009550 Result.first = MaskedBytes;
9551 Result.second = NotMaskTZ/8;
9552 return Result;
9553}
9554
9555
Sanjay Patel50cbfc52014-08-28 16:29:51 +00009556/// Check to see if IVal is something that provides a value as specified by
9557/// MaskInfo. If so, replace the specified store with a narrower store of
9558/// truncated IVal.
Chris Lattner4041ab62010-04-15 04:48:01 +00009559static SDNode *
9560ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
9561 SDValue IVal, StoreSDNode *St,
9562 DAGCombiner *DC) {
9563 unsigned NumBytes = MaskInfo.first;
9564 unsigned ByteShift = MaskInfo.second;
9565 SelectionDAG &DAG = DC->getDAG();
Wesley Peck527da1b2010-11-23 03:31:01 +00009566
Chris Lattner4041ab62010-04-15 04:48:01 +00009567 // Check to see if IVal is all zeros in the part being masked in by the 'or'
9568 // that uses this. If not, this is not a replacement.
9569 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
9570 ByteShift*8, (ByteShift+NumBytes)*8);
Craig Topperc0196b12014-04-14 00:51:57 +00009571 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
Wesley Peck527da1b2010-11-23 03:31:01 +00009572
Chris Lattner4041ab62010-04-15 04:48:01 +00009573 // Check that it is legal on the target to do this. It is legal if the new
9574 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
9575 // legalization.
9576 MVT VT = MVT::getIntegerVT(NumBytes*8);
9577 if (!DC->isTypeLegal(VT))
Craig Topperc0196b12014-04-14 00:51:57 +00009578 return nullptr;
Wesley Peck527da1b2010-11-23 03:31:01 +00009579
Chris Lattner4041ab62010-04-15 04:48:01 +00009580 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
9581 // shifted by ByteShift and truncated down to NumBytes.
9582 if (ByteShift)
Andrew Trickef9de2a2013-05-25 02:42:55 +00009583 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
Owen Andersonb2c80da2011-02-25 21:41:48 +00009584 DAG.getConstant(ByteShift*8,
9585 DC->getShiftAmountTy(IVal.getValueType())));
Chris Lattner4041ab62010-04-15 04:48:01 +00009586
9587 // Figure out the offset for the store and the alignment of the access.
9588 unsigned StOffset;
9589 unsigned NewAlign = St->getAlignment();
9590
9591 if (DAG.getTargetLoweringInfo().isLittleEndian())
9592 StOffset = ByteShift;
9593 else
9594 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
Wesley Peck527da1b2010-11-23 03:31:01 +00009595
Chris Lattner4041ab62010-04-15 04:48:01 +00009596 SDValue Ptr = St->getBasePtr();
9597 if (StOffset) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009598 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
Chris Lattner4041ab62010-04-15 04:48:01 +00009599 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
9600 NewAlign = MinAlign(NewAlign, StOffset);
9601 }
Wesley Peck527da1b2010-11-23 03:31:01 +00009602
Chris Lattner4041ab62010-04-15 04:48:01 +00009603 // Truncate down to the new size.
Andrew Trickef9de2a2013-05-25 02:42:55 +00009604 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
Wesley Peck527da1b2010-11-23 03:31:01 +00009605
Chris Lattner4041ab62010-04-15 04:48:01 +00009606 ++OpsNarrowed;
Andrew Trickef9de2a2013-05-25 02:42:55 +00009607 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
Chris Lattner676c61d2010-09-21 18:41:36 +00009608 St->getPointerInfo().getWithOffset(StOffset),
Chris Lattner4041ab62010-04-15 04:48:01 +00009609 false, false, NewAlign).getNode();
9610}
9611
Evan Chenga9cda8a2009-05-28 00:35:15 +00009612
Sanjay Patel50cbfc52014-08-28 16:29:51 +00009613/// Look for sequence of load / op / store where op is one of 'or', 'xor', and
9614/// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
9615/// narrowing the load and store if it would end up being a win for performance
9616/// or code size.
Evan Chenga9cda8a2009-05-28 00:35:15 +00009617SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
9618 StoreSDNode *ST = cast<StoreSDNode>(N);
Evan Cheng6673ff02009-05-28 18:41:02 +00009619 if (ST->isVolatile())
9620 return SDValue();
9621
Evan Chenga9cda8a2009-05-28 00:35:15 +00009622 SDValue Chain = ST->getChain();
9623 SDValue Value = ST->getValue();
9624 SDValue Ptr = ST->getBasePtr();
Owen Anderson53aa7a92009-08-10 22:56:29 +00009625 EVT VT = Value.getValueType();
Evan Chenga9cda8a2009-05-28 00:35:15 +00009626
9627 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
Evan Cheng6673ff02009-05-28 18:41:02 +00009628 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00009629
9630 unsigned Opc = Value.getOpcode();
Wesley Peck527da1b2010-11-23 03:31:01 +00009631
Chris Lattner4041ab62010-04-15 04:48:01 +00009632 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
9633 // is a byte mask indicating a consecutive number of bytes, check to see if
9634 // Y is known to provide just those bytes. If so, we try to replace the
9635 // load + replace + store sequence with a single (narrower) store, which makes
9636 // the load dead.
9637 if (Opc == ISD::OR) {
9638 std::pair<unsigned, unsigned> MaskedLoad;
9639 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
9640 if (MaskedLoad.first)
9641 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
9642 Value.getOperand(1), ST,this))
9643 return SDValue(NewST, 0);
Wesley Peck527da1b2010-11-23 03:31:01 +00009644
Chris Lattner4041ab62010-04-15 04:48:01 +00009645 // Or is commutative, so try swapping X and Y.
9646 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
9647 if (MaskedLoad.first)
9648 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
9649 Value.getOperand(0), ST,this))
9650 return SDValue(NewST, 0);
9651 }
Wesley Peck527da1b2010-11-23 03:31:01 +00009652
Evan Chenga9cda8a2009-05-28 00:35:15 +00009653 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
9654 Value.getOperand(1).getOpcode() != ISD::Constant)
Evan Cheng6673ff02009-05-28 18:41:02 +00009655 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00009656
9657 SDValue N0 = Value.getOperand(0);
Dan Gohman3c9b5f32010-09-02 21:18:42 +00009658 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
9659 Chain == SDValue(N0.getNode(), 1)) {
Evan Chenga9cda8a2009-05-28 00:35:15 +00009660 LoadSDNode *LD = cast<LoadSDNode>(N0);
Chris Lattnerf72c3c02010-09-21 16:08:50 +00009661 if (LD->getBasePtr() != Ptr ||
9662 LD->getPointerInfo().getAddrSpace() !=
9663 ST->getPointerInfo().getAddrSpace())
Evan Cheng6673ff02009-05-28 18:41:02 +00009664 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00009665
9666 // Find the type to narrow it the load / op / store to.
9667 SDValue N1 = Value.getOperand(1);
9668 unsigned BitWidth = N1.getValueSizeInBits();
9669 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
9670 if (Opc == ISD::AND)
9671 Imm ^= APInt::getAllOnesValue(BitWidth);
Evan Cheng86cdb4b2009-05-28 23:52:18 +00009672 if (Imm == 0 || Imm.isAllOnesValue())
9673 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00009674 unsigned ShAmt = Imm.countTrailingZeros();
9675 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
9676 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
Owen Anderson117c9e82009-08-12 00:36:31 +00009677 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
Elena Demikhovsky150d9f32015-01-22 12:07:59 +00009678 // The narrowing should be profitable, the load/store operation should be
Elena Demikhovsky9c264622015-01-22 09:39:08 +00009679 // legal (or custom) and the store size should be equal to the NewVT width.
Evan Chenga9cda8a2009-05-28 00:35:15 +00009680 while (NewBW < BitWidth &&
Elena Demikhovsky9c264622015-01-22 09:39:08 +00009681 (NewVT.getStoreSizeInBits() != NewBW ||
9682 !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
9683 !TLI.isNarrowingProfitable(VT, NewVT))) {
Evan Chenga9cda8a2009-05-28 00:35:15 +00009684 NewBW = NextPowerOf2(NewBW);
Owen Anderson117c9e82009-08-12 00:36:31 +00009685 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
Evan Chenga9cda8a2009-05-28 00:35:15 +00009686 }
Evan Cheng6673ff02009-05-28 18:41:02 +00009687 if (NewBW >= BitWidth)
9688 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00009689
9690 // If the lsb changed does not start at the type bitwidth boundary,
9691 // start at the previous one.
9692 if (ShAmt % NewBW)
9693 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
Manman Ren82751a12012-12-12 01:13:50 +00009694 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
9695 std::min(BitWidth, ShAmt + NewBW));
Evan Chenga9cda8a2009-05-28 00:35:15 +00009696 if ((Imm & Mask) == Imm) {
9697 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
9698 if (Opc == ISD::AND)
9699 NewImm ^= APInt::getAllOnesValue(NewBW);
9700 uint64_t PtrOff = ShAmt / 8;
9701 // For big endian targets, we need to adjust the offset to the pointer to
9702 // load the correct bytes.
9703 if (TLI.isBigEndian())
Evan Cheng6673ff02009-05-28 18:41:02 +00009704 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
Evan Chenga9cda8a2009-05-28 00:35:15 +00009705
9706 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
Chris Lattner229907c2011-07-18 04:54:35 +00009707 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
Micah Villmowcdfe20b2012-10-08 16:38:25 +00009708 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
Evan Cheng6673ff02009-05-28 18:41:02 +00009709 return SDValue();
9710
Andrew Trickef9de2a2013-05-25 02:42:55 +00009711 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
Evan Chenga9cda8a2009-05-28 00:35:15 +00009712 Ptr.getValueType(), Ptr,
9713 DAG.getConstant(PtrOff, Ptr.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +00009714 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
Evan Chenga9cda8a2009-05-28 00:35:15 +00009715 LD->getChain(), NewPtr,
Chris Lattnerf72c3c02010-09-21 16:08:50 +00009716 LD->getPointerInfo().getWithOffset(PtrOff),
David Greene39c6d012010-02-15 17:00:31 +00009717 LD->isVolatile(), LD->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009718 LD->isInvariant(), NewAlign,
Hal Finkelcc39b672014-07-24 12:16:19 +00009719 LD->getAAInfo());
Andrew Trickef9de2a2013-05-25 02:42:55 +00009720 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
Evan Chenga9cda8a2009-05-28 00:35:15 +00009721 DAG.getConstant(NewImm, NewVT));
Andrew Trickef9de2a2013-05-25 02:42:55 +00009722 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
Evan Chenga9cda8a2009-05-28 00:35:15 +00009723 NewVal, NewPtr,
Chris Lattnerf72c3c02010-09-21 16:08:50 +00009724 ST->getPointerInfo().getWithOffset(PtrOff),
David Greene39c6d012010-02-15 17:00:31 +00009725 false, false, NewAlign);
Evan Chenga9cda8a2009-05-28 00:35:15 +00009726
Chandler Carruth3c0012b2014-07-21 08:56:44 +00009727 AddToWorklist(NewPtr.getNode());
9728 AddToWorklist(NewLD.getNode());
9729 AddToWorklist(NewVal.getNode());
9730 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00009731 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
Evan Chenga9cda8a2009-05-28 00:35:15 +00009732 ++OpsNarrowed;
9733 return NewST;
9734 }
9735 }
9736
Evan Cheng6673ff02009-05-28 18:41:02 +00009737 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +00009738}
9739
Sanjay Patel50cbfc52014-08-28 16:29:51 +00009740/// For a given floating point load / store pair, if the load value isn't used
9741/// by any other operations, then consider transforming the pair to integer
9742/// load / store operations if the target deems the transformation profitable.
Evan Chengd42641c2011-02-02 01:06:55 +00009743SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
9744 StoreSDNode *ST = cast<StoreSDNode>(N);
9745 SDValue Chain = ST->getChain();
9746 SDValue Value = ST->getValue();
9747 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
9748 Value.hasOneUse() &&
9749 Chain == SDValue(Value.getNode(), 1)) {
9750 LoadSDNode *LD = cast<LoadSDNode>(Value);
9751 EVT VT = LD->getMemoryVT();
9752 if (!VT.isFloatingPoint() ||
9753 VT != ST->getMemoryVT() ||
9754 LD->isNonTemporal() ||
9755 ST->isNonTemporal() ||
9756 LD->getPointerInfo().getAddrSpace() != 0 ||
9757 ST->getPointerInfo().getAddrSpace() != 0)
9758 return SDValue();
9759
9760 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
9761 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
9762 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
9763 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
9764 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
9765 return SDValue();
9766
9767 unsigned LDAlign = LD->getAlignment();
9768 unsigned STAlign = ST->getAlignment();
Chris Lattner229907c2011-07-18 04:54:35 +00009769 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
Micah Villmowcdfe20b2012-10-08 16:38:25 +00009770 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
Evan Chengd42641c2011-02-02 01:06:55 +00009771 if (LDAlign < ABIAlign || STAlign < ABIAlign)
9772 return SDValue();
9773
Andrew Trickef9de2a2013-05-25 02:42:55 +00009774 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
Evan Chengd42641c2011-02-02 01:06:55 +00009775 LD->getChain(), LD->getBasePtr(),
9776 LD->getPointerInfo(),
Pete Cooper82cd9e82011-11-08 18:42:53 +00009777 false, false, false, LDAlign);
Evan Chengd42641c2011-02-02 01:06:55 +00009778
Andrew Trickef9de2a2013-05-25 02:42:55 +00009779 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
Evan Chengd42641c2011-02-02 01:06:55 +00009780 NewLD, ST->getBasePtr(),
9781 ST->getPointerInfo(),
9782 false, false, STAlign);
9783
Chandler Carruth3c0012b2014-07-21 08:56:44 +00009784 AddToWorklist(NewLD.getNode());
9785 AddToWorklist(NewST.getNode());
9786 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00009787 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
Evan Chengd42641c2011-02-02 01:06:55 +00009788 ++LdStFP2Int;
9789 return NewST;
9790 }
9791
9792 return SDValue();
9793}
9794
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009795/// Helper struct to parse and store a memory address as base + index + offset.
9796/// We ignore sign extensions when it is safe to do so.
9797/// The following two expressions are not equivalent. To differentiate we need
9798/// to store whether there was a sign extension involved in the index
9799/// computation.
9800/// (load (i64 add (i64 copyfromreg %c)
9801/// (i64 signextend (add (i8 load %index)
9802/// (i8 1))))
9803/// vs
9804///
9805/// (load (i64 add (i64 copyfromreg %c)
9806/// (i64 signextend (i32 add (i32 signextend (i8 load %index))
9807/// (i32 1)))))
9808struct BaseIndexOffset {
9809 SDValue Base;
9810 SDValue Index;
9811 int64_t Offset;
9812 bool IsIndexSignExt;
9813
9814 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
9815
9816 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
9817 bool IsIndexSignExt) :
9818 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
9819
9820 bool equalBaseIndex(const BaseIndexOffset &Other) {
9821 return Other.Base == Base && Other.Index == Index &&
9822 Other.IsIndexSignExt == IsIndexSignExt;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009823 }
9824
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009825 /// Parses tree in Ptr for base, index, offset addresses.
9826 static BaseIndexOffset match(SDValue Ptr) {
9827 bool IsIndexSignExt = false;
9828
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00009829 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
9830 // instruction, then it could be just the BASE or everything else we don't
9831 // know how to handle. Just use Ptr as BASE and give up.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009832 if (Ptr->getOpcode() != ISD::ADD)
9833 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9834
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00009835 // We know that we have at least an ADD instruction. Try to pattern match
9836 // the simple case of BASE + OFFSET.
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009837 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
9838 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
9839 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
9840 IsIndexSignExt);
9841 }
9842
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00009843 // Inside a loop the current BASE pointer is calculated using an ADD and a
Juergen Ributzka11c52c62013-08-28 22:33:58 +00009844 // MUL instruction. In this case Ptr is the actual BASE pointer.
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00009845 // (i64 add (i64 %array_ptr)
9846 // (i64 mul (i64 %induction_var)
9847 // (i64 %element_size)))
Juergen Ributzka11c52c62013-08-28 22:33:58 +00009848 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00009849 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
Juergen Ributzka3db39dc2013-08-21 21:53:38 +00009850
Arnold Schwaighofer67523662013-04-01 18:12:58 +00009851 // Look at Base + Index + Offset cases.
9852 SDValue Base = Ptr->getOperand(0);
9853 SDValue IndexOffset = Ptr->getOperand(1);
9854
9855 // Skip signextends.
9856 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
9857 IndexOffset = IndexOffset->getOperand(0);
9858 IsIndexSignExt = true;
9859 }
9860
9861 // Either the case of Base + Index (no offset) or something else.
9862 if (IndexOffset->getOpcode() != ISD::ADD)
9863 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
9864
9865 // Now we have the case of Base + Index + offset.
9866 SDValue Index = IndexOffset->getOperand(0);
9867 SDValue Offset = IndexOffset->getOperand(1);
9868
9869 if (!isa<ConstantSDNode>(Offset))
9870 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9871
9872 // Ignore signextends.
9873 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
9874 Index = Index->getOperand(0);
9875 IsIndexSignExt = true;
9876 } else IsIndexSignExt = false;
9877
9878 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
9879 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
9880 }
9881};
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009882
Sanjay Patel37c41c12015-01-22 18:21:26 +00009883bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
9884 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
Quentin Colombet308b1712015-01-27 23:58:01 +00009885 unsigned NumElem, bool IsConstantSrc, bool UseVector) {
Sanjay Patel37c41c12015-01-22 18:21:26 +00009886 // Make sure we have something to merge.
Quentin Colombet308b1712015-01-27 23:58:01 +00009887 if (NumElem < 2)
Sanjay Patel37c41c12015-01-22 18:21:26 +00009888 return false;
9889
9890 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
9891 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9892 unsigned EarliestNodeUsed = 0;
9893
Quentin Colombet308b1712015-01-27 23:58:01 +00009894 for (unsigned i=0; i < NumElem; ++i) {
Sanjay Patel37c41c12015-01-22 18:21:26 +00009895 // Find a chain for the new wide-store operand. Notice that some
9896 // of the store nodes that we found may not be selected for inclusion
9897 // in the wide store. The chain we use needs to be the chain of the
9898 // earliest store node which is *used* and replaced by the wide store.
9899 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9900 EarliestNodeUsed = i;
9901 }
9902
9903 // The earliest Node in the DAG.
9904 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9905 SDLoc DL(StoreNodes[0].MemNode);
9906
9907 SDValue StoredVal;
9908 if (UseVector) {
Quentin Colombet308b1712015-01-27 23:58:01 +00009909 // Find a legal type for the vector store.
9910 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
Sanjay Patel37c41c12015-01-22 18:21:26 +00009911 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9912 if (IsConstantSrc) {
9913 // A vector store with a constant source implies that the constant is
9914 // zero; we only handle merging stores of constant zeros because the zero
9915 // can be materialized without a load.
9916 // It may be beneficial to loosen this restriction to allow non-zero
9917 // store merging.
9918 StoredVal = DAG.getConstant(0, Ty);
9919 } else {
9920 SmallVector<SDValue, 8> Ops;
Quentin Colombet308b1712015-01-27 23:58:01 +00009921 for (unsigned i = 0; i < NumElem ; ++i) {
Sanjay Patel37c41c12015-01-22 18:21:26 +00009922 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9923 SDValue Val = St->getValue();
Quentin Colombet308b1712015-01-27 23:58:01 +00009924 // All of the operands of a BUILD_VECTOR must have the same type.
Sanjay Patel37c41c12015-01-22 18:21:26 +00009925 if (Val.getValueType() != MemVT)
9926 return false;
9927 Ops.push_back(Val);
9928 }
Quentin Colombet308b1712015-01-27 23:58:01 +00009929
Sanjay Patel37c41c12015-01-22 18:21:26 +00009930 // Build the extracted vector elements back into a vector.
Quentin Colombet308b1712015-01-27 23:58:01 +00009931 StoredVal = DAG.getNode(ISD::BUILD_VECTOR, DL, Ty, Ops);
Sanjay Patel37c41c12015-01-22 18:21:26 +00009932 }
9933 } else {
9934 // We should always use a vector store when merging extracted vector
9935 // elements, so this path implies a store of constants.
9936 assert(IsConstantSrc && "Merged vector elements should use vector store");
9937
Quentin Colombet308b1712015-01-27 23:58:01 +00009938 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
Sanjay Patel37c41c12015-01-22 18:21:26 +00009939 APInt StoreInt(StoreBW, 0);
9940
9941 // Construct a single integer constant which is made of the smaller
9942 // constant inputs.
9943 bool IsLE = TLI.isLittleEndian();
Quentin Colombet308b1712015-01-27 23:58:01 +00009944 for (unsigned i = 0; i < NumElem ; ++i) {
9945 unsigned Idx = IsLE ? (NumElem - 1 - i) : i;
Sanjay Patel37c41c12015-01-22 18:21:26 +00009946 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9947 SDValue Val = St->getValue();
9948 StoreInt <<= ElementSizeBytes*8;
9949 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9950 StoreInt |= C->getAPIntValue().zext(StoreBW);
9951 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9952 StoreInt |= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9953 } else {
9954 llvm_unreachable("Invalid constant element type");
9955 }
9956 }
9957
9958 // Create the new Load and Store operations.
9959 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9960 StoredVal = DAG.getConstant(StoreInt, StoreTy);
9961 }
9962
9963 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9964 FirstInChain->getBasePtr(),
9965 FirstInChain->getPointerInfo(),
9966 false, false,
9967 FirstInChain->getAlignment());
9968
9969 // Replace the first store with the new store
9970 CombineTo(EarliestOp, NewStore);
9971 // Erase all other stores.
Quentin Colombet308b1712015-01-27 23:58:01 +00009972 for (unsigned i = 0; i < NumElem ; ++i) {
Sanjay Patel37c41c12015-01-22 18:21:26 +00009973 if (StoreNodes[i].MemNode == EarliestOp)
9974 continue;
9975 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9976 // ReplaceAllUsesWith will replace all uses that existed when it was
9977 // called, but graph optimizations may cause new ones to appear. For
9978 // example, the case in pr14333 looks like
9979 //
9980 // St's chain -> St -> another store -> X
9981 //
9982 // And the only difference from St to the other store is the chain.
9983 // When we change it's chain to be St's chain they become identical,
9984 // get CSEed and the net result is that X is now a use of St.
9985 // Since we know that St is redundant, just iterate.
9986 while (!St->use_empty())
9987 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9988 deleteAndRecombine(St);
9989 }
9990
9991 return true;
9992}
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009993
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009994bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
Quentin Colombet308b1712015-01-27 23:58:01 +00009995 EVT MemVT = St->getMemoryVT();
9996 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
Duncan P. N. Exon Smith70eb9c52015-02-14 01:44:41 +00009997 bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
9998 Attribute::NoImplicitFloat);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +00009999
Quentin Colombet308b1712015-01-27 23:58:01 +000010000 // Don't merge vectors into wider inputs.
10001 if (MemVT.isVector() || !MemVT.isSimple())
10002 return false;
10003
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010004 // Perform an early exit check. Do not bother looking at stored values that
Sanjay Patel37c41c12015-01-22 18:21:26 +000010005 // are not constants, loads, or extracted vector elements.
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010006 SDValue StoredVal = St->getValue();
10007 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
Sanjay Patel37c41c12015-01-22 18:21:26 +000010008 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
10009 isa<ConstantFPSDNode>(StoredVal);
Quentin Colombet308b1712015-01-27 23:58:01 +000010010 bool IsExtractVecEltSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT);
Sanjay Patel37c41c12015-01-22 18:21:26 +000010011
Quentin Colombet308b1712015-01-27 23:58:01 +000010012 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecEltSrc)
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010013 return false;
10014
10015 // Only look at ends of store sequences.
Chandler Carruth94bd5532014-07-25 07:23:23 +000010016 SDValue Chain = SDValue(St, 0);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010017 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
10018 return false;
10019
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010020 // This holds the base pointer, index, and the offset in bytes from the base
10021 // pointer.
10022 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010023
10024 // We must have a base and an offset.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010025 if (!BasePtr.Base.getNode())
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010026 return false;
10027
10028 // Do not handle stores to undef base pointers.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010029 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010030 return false;
10031
Nadav Rotem307d7672012-11-29 00:00:08 +000010032 // Save the LoadSDNodes that we find in the chain.
10033 // We need to make sure that these nodes do not interfere with
10034 // any of the store nodes.
10035 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
10036
10037 // Save the StoreSDNodes that we find in the chain.
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010038 SmallVector<MemOpLink, 8> StoreNodes;
Nadav Rotem307d7672012-11-29 00:00:08 +000010039
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010040 // Walk up the chain and look for nodes with offsets from the same
10041 // base pointer. Stop when reaching an instruction with a different kind
10042 // or instruction which has a different base pointer.
10043 unsigned Seq = 0;
10044 StoreSDNode *Index = St;
10045 while (Index) {
10046 // If the chain has more than one use, then we can't reorder the mem ops.
Matt Arsenault197a1e22014-07-25 07:56:42 +000010047 if (Index != St && !SDValue(Index, 0)->hasOneUse())
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010048 break;
10049
10050 // Find the base pointer and offset for this memory node.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010051 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010052
10053 // Check that the base pointer is the same as the original one.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010054 if (!Ptr.equalBaseIndex(BasePtr))
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010055 break;
10056
10057 // Check that the alignment is the same.
10058 if (Index->getAlignment() != St->getAlignment())
10059 break;
10060
10061 // The memory operands must not be volatile.
10062 if (Index->isVolatile() || Index->isIndexed())
10063 break;
10064
10065 // No truncation.
10066 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
10067 if (St->isTruncatingStore())
10068 break;
10069
10070 // The stored memory type must be the same.
10071 if (Index->getMemoryVT() != MemVT)
10072 break;
10073
10074 // We do not allow unaligned stores because we want to prevent overriding
10075 // stores.
10076 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
10077 break;
10078
10079 // We found a potential memory operand to merge.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010080 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010081
Nadav Rotem307d7672012-11-29 00:00:08 +000010082 // Find the next memory operand in the chain. If the next operand in the
10083 // chain is a store then move up and continue the scan with the next
10084 // memory operand. If the next operand is a load save it and use alias
10085 // information to check if it interferes with anything.
10086 SDNode *NextInChain = Index->getChain().getNode();
10087 while (1) {
Nadav Rotemac450eb2012-12-06 17:34:13 +000010088 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
Nadav Rotem307d7672012-11-29 00:00:08 +000010089 // We found a store node. Use it for the next iteration.
Nadav Rotemac450eb2012-12-06 17:34:13 +000010090 Index = STn;
Nadav Rotem307d7672012-11-29 00:00:08 +000010091 break;
10092 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
Bill Wendling9200bb02013-11-25 18:05:22 +000010093 if (Ldn->isVolatile()) {
Craig Topperc0196b12014-04-14 00:51:57 +000010094 Index = nullptr;
Bill Wendling9200bb02013-11-25 18:05:22 +000010095 break;
10096 }
10097
Nadav Rotem307d7672012-11-29 00:00:08 +000010098 // Save the load node for later. Continue the scan.
10099 AliasLoadNodes.push_back(Ldn);
10100 NextInChain = Ldn->getChain().getNode();
10101 continue;
10102 } else {
Craig Topperc0196b12014-04-14 00:51:57 +000010103 Index = nullptr;
Nadav Rotem307d7672012-11-29 00:00:08 +000010104 break;
10105 }
10106 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010107 }
10108
10109 // Check if there is anything to merge.
10110 if (StoreNodes.size() < 2)
10111 return false;
10112
10113 // Sort the memory operands according to their distance from the base pointer.
10114 std::sort(StoreNodes.begin(), StoreNodes.end(),
Benjamin Kramer3a377bc2014-03-01 11:47:00 +000010115 [](MemOpLink LHS, MemOpLink RHS) {
10116 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
10117 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
10118 LHS.SequenceNum > RHS.SequenceNum);
10119 });
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010120
10121 // Scan the memory operations on the chain and find the first non-consecutive
10122 // store memory address.
10123 unsigned LastConsecutiveStore = 0;
10124 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
Nadav Rotemac450eb2012-12-06 17:34:13 +000010125 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
10126
10127 // Check that the addresses are consecutive starting from the second
10128 // element in the list of stores.
10129 if (i > 0) {
10130 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
10131 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10132 break;
10133 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010134
Nadav Rotem307d7672012-11-29 00:00:08 +000010135 bool Alias = false;
10136 // Check if this store interferes with any of the loads that we found.
10137 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
10138 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
10139 Alias = true;
10140 break;
10141 }
Nadav Rotem307d7672012-11-29 00:00:08 +000010142 // We found a load that alias with this store. Stop the sequence.
10143 if (Alias)
10144 break;
10145
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010146 // Mark this node as useful.
10147 LastConsecutiveStore = i;
10148 }
10149
10150 // The node with the lowest store address.
10151 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10152
10153 // Store the constants into memory as one consecutive store.
Sanjay Patel37c41c12015-01-22 18:21:26 +000010154 if (IsConstantSrc) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010155 unsigned LastLegalType = 0;
Nadav Rotemb27777f2012-10-04 22:35:15 +000010156 unsigned LastLegalVectorType = 0;
10157 bool NonZero = false;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010158 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10159 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10160 SDValue StoredVal = St->getValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +000010161
10162 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
Benjamin Kramer62f7fb92012-10-05 18:19:44 +000010163 NonZero |= !C->isNullValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +000010164 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
Benjamin Kramer62f7fb92012-10-05 18:19:44 +000010165 NonZero |= !C->getConstantFPValue()->isNullValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +000010166 } else {
Alp Tokerf907b892013-12-05 05:44:44 +000010167 // Non-constant.
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010168 break;
Nadav Rotemb27777f2012-10-04 22:35:15 +000010169 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010170
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010171 // Find a legal type for the constant store.
10172 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10173 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10174 if (TLI.isTypeLegal(StoreTy))
10175 LastLegalType = i+1;
Arnold Schwaighoferd6c6e862013-04-02 15:58:51 +000010176 // Or check whether a truncstore is legal.
10177 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10178 TargetLowering::TypePromoteInteger) {
10179 EVT LegalizedStoredValueTy =
10180 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
10181 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
10182 LastLegalType = i+1;
10183 }
Nadav Rotemb27777f2012-10-04 22:35:15 +000010184
10185 // Find a legal type for the vector store.
10186 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10187 if (TLI.isTypeLegal(Ty))
10188 LastLegalVectorType = i + 1;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010189 }
10190
Bob Wilson3365b802012-12-20 01:36:20 +000010191 // We only use vectors if the constant is known to be zero and the
10192 // function is not marked with the noimplicitfloat attribute.
Nadav Rotem495b1a42013-02-14 18:28:52 +000010193 if (NonZero || NoVectors)
Nadav Rotemb27777f2012-10-04 22:35:15 +000010194 LastLegalVectorType = 0;
10195
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010196 // Check if we found a legal integer type to store.
Nadav Rotemb27777f2012-10-04 22:35:15 +000010197 if (LastLegalType == 0 && LastLegalVectorType == 0)
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010198 return false;
10199
Nadav Rotem495b1a42013-02-14 18:28:52 +000010200 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
Nadav Rotemb27777f2012-10-04 22:35:15 +000010201 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
10202
Sanjay Patel37c41c12015-01-22 18:21:26 +000010203 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10204 true, UseVector);
10205 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010206
Sanjay Patel37c41c12015-01-22 18:21:26 +000010207 // When extracting multiple vector elements, try to store them
10208 // in one vector store rather than a sequence of scalar stores.
Quentin Colombet308b1712015-01-27 23:58:01 +000010209 if (IsExtractVecEltSrc) {
10210 unsigned NumElem = 0;
Sanjay Patel37c41c12015-01-22 18:21:26 +000010211 for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
10212 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
Quentin Colombet308b1712015-01-27 23:58:01 +000010213 SDValue StoredVal = St->getValue();
Sanjay Patel37c41c12015-01-22 18:21:26 +000010214 // This restriction could be loosened.
10215 // Bail out if any stored values are not elements extracted from a vector.
10216 // It should be possible to handle mixed sources, but load sources need
10217 // more careful handling (see the block of code below that handles
10218 // consecutive loads).
Quentin Colombet308b1712015-01-27 23:58:01 +000010219 if (StoredVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
Sanjay Patel37c41c12015-01-22 18:21:26 +000010220 return false;
10221
Nadav Rotemb27777f2012-10-04 22:35:15 +000010222 // Find a legal type for the vector store.
Quentin Colombet308b1712015-01-27 23:58:01 +000010223 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10224 if (TLI.isTypeLegal(Ty))
10225 NumElem = i + 1;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010226 }
10227
Quentin Colombet308b1712015-01-27 23:58:01 +000010228 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
Sanjay Patel37c41c12015-01-22 18:21:26 +000010229 false, true);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010230 }
10231
10232 // Below we handle the case of multiple consecutive stores that
10233 // come from multiple consecutive loads. We merge them into a single
10234 // wide load and a single wide store.
10235
10236 // Look for load nodes which are used by the stored values.
10237 SmallVector<MemOpLink, 8> LoadNodes;
10238
10239 // Find acceptable loads. Loads need to have the same chain (token factor),
10240 // must not be zext, volatile, indexed, and they must be consecutive.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010241 BaseIndexOffset LdBasePtr;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010242 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10243 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10244 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
10245 if (!Ld) break;
10246
10247 // Loads must only have one use.
10248 if (!Ld->hasNUsesOfValue(1, 0))
10249 break;
10250
10251 // Check that the alignment is the same as the stores.
10252 if (Ld->getAlignment() != St->getAlignment())
10253 break;
10254
10255 // The memory operands must not be volatile.
10256 if (Ld->isVolatile() || Ld->isIndexed())
10257 break;
10258
10259 // We do not accept ext loads.
10260 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
10261 break;
10262
10263 // The stored memory type must be the same.
10264 if (Ld->getMemoryVT() != MemVT)
10265 break;
10266
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010267 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010268 // If this is not the first ptr that we check.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010269 if (LdBasePtr.Base.getNode()) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010270 // The base ptr must be the same.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010271 if (!LdPtr.equalBaseIndex(LdBasePtr))
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010272 break;
10273 } else {
10274 // Check that all other base pointers are the same as this one.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010275 LdBasePtr = LdPtr;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010276 }
10277
10278 // We found a potential memory operand to merge.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010279 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010280 }
10281
10282 if (LoadNodes.size() < 2)
10283 return false;
10284
James Molloyce45be02014-08-02 14:51:24 +000010285 // If we have load/store pair instructions and we only have two values,
10286 // don't bother.
10287 unsigned RequiredAlignment;
10288 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
10289 St->getAlignment() >= RequiredAlignment)
10290 return false;
10291
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010292 // Scan the memory operations on the chain and find the first non-consecutive
10293 // load memory address. These variables hold the index in the store node
10294 // array.
10295 unsigned LastConsecutiveLoad = 0;
10296 // This variable refers to the size and not index in the array.
10297 unsigned LastLegalVectorType = 0;
10298 unsigned LastLegalIntegerType = 0;
10299 StartAddress = LoadNodes[0].OffsetFromBase;
Nadav Rotemac920662012-10-03 19:30:31 +000010300 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
10301 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
10302 // All loads much share the same chain.
10303 if (LoadNodes[i].MemNode->getChain() != FirstChain)
10304 break;
Nadav Rotem495b1a42013-02-14 18:28:52 +000010305
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010306 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
10307 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10308 break;
10309 LastConsecutiveLoad = i;
10310
10311 // Find a legal type for the vector store.
10312 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10313 if (TLI.isTypeLegal(StoreTy))
10314 LastLegalVectorType = i + 1;
10315
10316 // Find a legal type for the integer store.
10317 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10318 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10319 if (TLI.isTypeLegal(StoreTy))
10320 LastLegalIntegerType = i + 1;
Arnold Schwaighoferd6c6e862013-04-02 15:58:51 +000010321 // Or check whether a truncstore and extload is legal.
10322 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10323 TargetLowering::TypePromoteInteger) {
10324 EVT LegalizedStoredValueTy =
10325 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
10326 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +000010327 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
10328 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
10329 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy))
Arnold Schwaighoferd6c6e862013-04-02 15:58:51 +000010330 LastLegalIntegerType = i+1;
10331 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010332 }
10333
10334 // Only use vector types if the vector type is larger than the integer type.
10335 // If they are the same, use integers.
Nadav Rotem495b1a42013-02-14 18:28:52 +000010336 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010337 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
10338
10339 // We add +1 here because the LastXXX variables refer to location while
10340 // the NumElem refers to array/index size.
10341 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
10342 NumElem = std::min(LastLegalType, NumElem);
10343
10344 if (NumElem < 2)
10345 return false;
10346
10347 // The earliest Node in the DAG.
10348 unsigned EarliestNodeUsed = 0;
10349 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
10350 for (unsigned i=1; i<NumElem; ++i) {
10351 // Find a chain for the new wide-store operand. Notice that some
10352 // of the store nodes that we found may not be selected for inclusion
10353 // in the wide store. The chain we use needs to be the chain of the
10354 // earliest store node which is *used* and replaced by the wide store.
10355 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
10356 EarliestNodeUsed = i;
10357 }
10358
10359 // Find if it is better to use vectors or integers to load and store
10360 // to memory.
10361 EVT JointMemOpVT;
10362 if (UseVectorTy) {
10363 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10364 } else {
10365 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
10366 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10367 }
10368
Andrew Trickef9de2a2013-05-25 02:42:55 +000010369 SDLoc LoadDL(LoadNodes[0].MemNode);
10370 SDLoc StoreDL(StoreNodes[0].MemNode);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010371
10372 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
10373 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
10374 FirstLoad->getChain(),
10375 FirstLoad->getBasePtr(),
10376 FirstLoad->getPointerInfo(),
10377 false, false, false,
10378 FirstLoad->getAlignment());
10379
10380 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
10381 FirstInChain->getBasePtr(),
10382 FirstInChain->getPointerInfo(), false, false,
10383 FirstInChain->getAlignment());
10384
Nadav Rotemac920662012-10-03 19:30:31 +000010385 // Replace one of the loads with the new load.
10386 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
10387 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
10388 SDValue(NewLoad.getNode(), 1));
10389
10390 // Remove the rest of the load chains.
10391 for (unsigned i = 1; i < NumElem ; ++i) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010392 // Replace all chain users of the old load nodes with the chain of the new
10393 // load node.
10394 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
Nadav Rotemac920662012-10-03 19:30:31 +000010395 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
10396 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010397
Nadav Rotemac920662012-10-03 19:30:31 +000010398 // Replace the first store with the new store.
10399 CombineTo(EarliestOp, NewStore);
10400 // Erase all other stores.
10401 for (unsigned i = 0; i < NumElem ; ++i) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010402 // Remove all Store nodes.
10403 if (StoreNodes[i].MemNode == EarliestOp)
10404 continue;
10405 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10406 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
Chandler Carruth18066972014-08-02 10:02:07 +000010407 deleteAndRecombine(St);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010408 }
10409
10410 return true;
10411}
10412
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010413SDValue DAGCombiner::visitSTORE(SDNode *N) {
Evan Chengab51cf22006-10-13 21:14:26 +000010414 StoreSDNode *ST = cast<StoreSDNode>(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010415 SDValue Chain = ST->getChain();
10416 SDValue Value = ST->getValue();
10417 SDValue Ptr = ST->getBasePtr();
Scott Michelcf0da6c2009-02-17 22:15:04 +000010418
Evan Chenga4cf58a2007-05-07 21:27:48 +000010419 // If this is a store of a bit convert, store the input value if the
Evan Chengf325c2a2007-05-09 21:49:47 +000010420 // resultant store does not need a higher alignment than the original.
Wesley Peck527da1b2010-11-23 03:31:01 +000010421 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +000010422 ST->isUnindexed()) {
Dan Gohmane7fe80f2009-02-20 23:29:13 +000010423 unsigned OrigAlign = ST->getAlignment();
Owen Anderson53aa7a92009-08-10 22:56:29 +000010424 EVT SVT = Value.getOperand(0).getValueType();
Micah Villmowcdfe20b2012-10-08 16:38:25 +000010425 unsigned Align = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +000010426 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
Duncan Sands8651e9c2008-06-13 19:07:40 +000010427 if (Align <= OrigAlign &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +000010428 ((!LegalOperations && !ST->isVolatile()) ||
Dan Gohman4aa18462009-01-28 17:46:25 +000010429 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +000010430 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
Chris Lattner676c61d2010-09-21 18:41:36 +000010431 Ptr, ST->getPointerInfo(), ST->isVolatile(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +000010432 ST->isNonTemporal(), OrigAlign,
Hal Finkelcc39b672014-07-24 12:16:19 +000010433 ST->getAAInfo());
Jim Laskeyd07be232006-09-25 16:29:54 +000010434 }
Owen Andersona5192842011-04-14 17:30:49 +000010435
Chris Lattner41c80e82011-04-09 02:32:02 +000010436 // Turn 'store undef, Ptr' -> nothing.
10437 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
10438 return Chain;
Duncan Sands8651e9c2008-06-13 19:07:40 +000010439
Nate Begeman8e20c762006-12-11 02:23:46 +000010440 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
Nate Begeman8e20c762006-12-11 02:23:46 +000010441 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
Duncan Sands8651e9c2008-06-13 19:07:40 +000010442 // NOTE: If the original store is volatile, this transform must not increase
10443 // the number of stores. For example, on x86-32 an f64 can be stored in one
10444 // processor operation but an i64 (which is not legal) requires two. So the
10445 // transform should not be done in this case.
Evan Cheng21836982006-12-11 17:25:19 +000010446 if (Value.getOpcode() != ISD::TargetConstantFP) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010447 SDValue Tmp;
Craig Topperd9c27832013-08-15 02:44:19 +000010448 switch (CFP->getSimpleValueType(0).SimpleTy) {
Torok Edwinfbcc6632009-07-14 16:55:14 +000010449 default: llvm_unreachable("Unknown FP type");
Pete Cooper5b614222012-06-21 18:00:39 +000010450 case MVT::f16: // We don't do this for these yet.
10451 case MVT::f80:
Owen Anderson9f944592009-08-11 20:47:22 +000010452 case MVT::f128:
10453 case MVT::ppcf128:
Dale Johannesenaf12b572007-09-18 18:36:59 +000010454 break;
Owen Anderson9f944592009-08-11 20:47:22 +000010455 case MVT::f32:
Chris Lattner4041ab62010-04-15 04:48:01 +000010456 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
Owen Anderson9f944592009-08-11 20:47:22 +000010457 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
Dale Johannesen028084e2007-09-12 03:30:33 +000010458 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
Owen Anderson9f944592009-08-11 20:47:22 +000010459 bitcastToAPInt().getZExtValue(), MVT::i32);
Andrew Trickef9de2a2013-05-25 02:42:55 +000010460 return DAG.getStore(Chain, SDLoc(N), Tmp,
Richard Sandiford39c1ce42013-10-28 11:17:59 +000010461 Ptr, ST->getMemOperand());
Chris Lattnerb7524b62006-12-12 04:16:14 +000010462 }
10463 break;
Owen Anderson9f944592009-08-11 20:47:22 +000010464 case MVT::f64:
Chris Lattner4041ab62010-04-15 04:48:01 +000010465 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
Dan Gohman4aa18462009-01-28 17:46:25 +000010466 !ST->isVolatile()) ||
Owen Anderson9f944592009-08-11 20:47:22 +000010467 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
Dale Johannesen54306fe2008-10-09 18:53:47 +000010468 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
Owen Anderson9f944592009-08-11 20:47:22 +000010469 getZExtValue(), MVT::i64);
Andrew Trickef9de2a2013-05-25 02:42:55 +000010470 return DAG.getStore(Chain, SDLoc(N), Tmp,
Richard Sandiford39c1ce42013-10-28 11:17:59 +000010471 Ptr, ST->getMemOperand());
Chris Lattner41c80e82011-04-09 02:32:02 +000010472 }
Owen Andersona5192842011-04-14 17:30:49 +000010473
Chris Lattner41c80e82011-04-09 02:32:02 +000010474 if (!ST->isVolatile() &&
10475 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
Duncan Sands1826ded2007-10-28 12:59:45 +000010476 // Many FP stores are not made apparent until after legalize, e.g. for
Chris Lattnerb7524b62006-12-12 04:16:14 +000010477 // argument passing. Since this is so common, custom legalize the
10478 // 64-bit integer store into two 32-bit stores.
Dale Johannesen54306fe2008-10-09 18:53:47 +000010479 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
Owen Anderson9f944592009-08-11 20:47:22 +000010480 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
10481 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
Duncan Sands7377f5f2008-02-11 10:37:04 +000010482 if (TLI.isBigEndian()) std::swap(Lo, Hi);
Chris Lattnerb7524b62006-12-12 04:16:14 +000010483
Dan Gohman2af30632007-07-09 22:18:38 +000010484 unsigned Alignment = ST->getAlignment();
10485 bool isVolatile = ST->isVolatile();
David Greene39c6d012010-02-15 17:00:31 +000010486 bool isNonTemporal = ST->isNonTemporal();
Hal Finkelcc39b672014-07-24 12:16:19 +000010487 AAMDNodes AAInfo = ST->getAAInfo();
Dan Gohman2af30632007-07-09 22:18:38 +000010488
Andrew Trickef9de2a2013-05-25 02:42:55 +000010489 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
Chris Lattner676c61d2010-09-21 18:41:36 +000010490 Ptr, ST->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +000010491 isVolatile, isNonTemporal,
Hal Finkelcc39b672014-07-24 12:16:19 +000010492 ST->getAlignment(), AAInfo);
Andrew Trickef9de2a2013-05-25 02:42:55 +000010493 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
Chris Lattnerb7524b62006-12-12 04:16:14 +000010494 DAG.getConstant(4, Ptr.getValueType()));
Duncan Sands1826ded2007-10-28 12:59:45 +000010495 Alignment = MinAlign(Alignment, 4U);
Andrew Trickef9de2a2013-05-25 02:42:55 +000010496 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
Chris Lattner676c61d2010-09-21 18:41:36 +000010497 Ptr, ST->getPointerInfo().getWithOffset(4),
10498 isVolatile, isNonTemporal,
Hal Finkelcc39b672014-07-24 12:16:19 +000010499 Alignment, AAInfo);
Andrew Trickef9de2a2013-05-25 02:42:55 +000010500 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
Bill Wendling27d9dd42009-01-30 23:36:47 +000010501 St0, St1);
Chris Lattnerb7524b62006-12-12 04:16:14 +000010502 }
Bill Wendling27d9dd42009-01-30 23:36:47 +000010503
Chris Lattnerb7524b62006-12-12 04:16:14 +000010504 break;
Evan Cheng21836982006-12-11 17:25:19 +000010505 }
Nate Begeman8e20c762006-12-11 02:23:46 +000010506 }
Nate Begeman8e20c762006-12-11 02:23:46 +000010507 }
10508
Evan Cheng43cd9e32010-04-01 06:04:33 +000010509 // Try to infer better alignment information than the store already has.
10510 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
Evan Cheng4a5b2042011-11-28 22:37:34 +000010511 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
10512 if (Align > ST->getAlignment())
Andrew Trickef9de2a2013-05-25 02:42:55 +000010513 return DAG.getTruncStore(Chain, SDLoc(N), Value,
Evan Cheng4a5b2042011-11-28 22:37:34 +000010514 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +000010515 ST->isVolatile(), ST->isNonTemporal(), Align,
Hal Finkelcc39b672014-07-24 12:16:19 +000010516 ST->getAAInfo());
Evan Cheng43cd9e32010-04-01 06:04:33 +000010517 }
10518 }
10519
Evan Chengd42641c2011-02-02 01:06:55 +000010520 // Try transforming a pair floating point load / store ops to integer
10521 // load / store ops.
10522 SDValue NewST = TransformFPLoadStorePair(N);
10523 if (NewST.getNode())
10524 return NewST;
10525
Eric Christopherf55d4712014-10-08 23:38:39 +000010526 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
10527 : DAG.getSubtarget().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +000010528#ifndef NDEBUG
10529 if (CombinerAAOnlyFunc.getNumOccurrences() &&
10530 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
10531 UseAA = false;
10532#endif
Hal Finkelccc18e12014-01-24 18:25:26 +000010533 if (UseAA && ST->isUnindexed()) {
Jim Laskeyd07be232006-09-25 16:29:54 +000010534 // Walk up chain skipping non-aliasing memory nodes.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010535 SDValue BetterChain = FindBetterChain(N, Chain);
Scott Michelcf0da6c2009-02-17 22:15:04 +000010536
Jim Laskey708d0db2006-10-04 16:53:27 +000010537 // If there is a better chain.
Jim Laskeyd07be232006-09-25 16:29:54 +000010538 if (Chain != BetterChain) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010539 SDValue ReplStore;
Nate Begeman879d8f12009-09-15 00:18:30 +000010540
10541 // Replace the chain to avoid dependency.
Jim Laskey3bf4f3b2006-10-14 12:14:27 +000010542 if (ST->isTruncatingStore()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010543 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
Richard Sandiford39c1ce42013-10-28 11:17:59 +000010544 ST->getMemoryVT(), ST->getMemOperand());
Jim Laskey3bf4f3b2006-10-14 12:14:27 +000010545 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010546 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
Richard Sandiford39c1ce42013-10-28 11:17:59 +000010547 ST->getMemOperand());
Jim Laskey3bf4f3b2006-10-14 12:14:27 +000010548 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010549
Jim Laskeyd07be232006-09-25 16:29:54 +000010550 // Create token to keep both nodes around.
Andrew Trickef9de2a2013-05-25 02:42:55 +000010551 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
Owen Anderson9f944592009-08-11 20:47:22 +000010552 MVT::Other, Chain, ReplStore);
Bill Wendling27d9dd42009-01-30 23:36:47 +000010553
Nate Begeman879d8f12009-09-15 00:18:30 +000010554 // Make sure the new and old chains are cleaned up.
Chandler Carruth3c0012b2014-07-21 08:56:44 +000010555 AddToWorklist(Token.getNode());
Nate Begeman879d8f12009-09-15 00:18:30 +000010556
Jim Laskeydcf983c2006-10-13 23:32:28 +000010557 // Don't add users to work list.
10558 return CombineTo(N, Token, false);
Jim Laskeyd07be232006-09-25 16:29:54 +000010559 }
Jim Laskey5d19d592006-09-21 16:28:59 +000010560 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010561
Evan Cheng33157702006-11-05 09:31:14 +000010562 // Try transforming N to an indexed store.
Evan Cheng60c68462006-11-07 09:03:05 +000010563 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010564 return SDValue(N, 0);
Evan Cheng33157702006-11-05 09:31:14 +000010565
Chris Lattner3f9c6a72007-12-29 06:26:16 +000010566 // FIXME: is there such a thing as a truncating indexed store?
Chris Lattner1ea55cf2008-01-17 19:59:44 +000010567 if (ST->isTruncatingStore() && ST->isUnindexed() &&
Nadav Rotemd2d9bdb2011-06-15 11:19:12 +000010568 Value.getValueType().isInteger()) {
Chris Lattner5e6fe052007-10-13 06:35:54 +000010569 // See if we can simplify the input to this truncstore with knowledge that
10570 // only the low bits are being used. For example:
10571 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
Scott Michelcf0da6c2009-02-17 22:15:04 +000010572 SDValue Shorter =
Dan Gohman1f372ed2008-02-25 21:11:39 +000010573 GetDemandedBits(Value,
Nadav Rotemd2d9bdb2011-06-15 11:19:12 +000010574 APInt::getLowBitsSet(
10575 Value.getValueType().getScalarType().getSizeInBits(),
10576 ST->getMemoryVT().getScalarType().getSizeInBits()));
Chandler Carruth3c0012b2014-07-21 08:56:44 +000010577 AddToWorklist(Value.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +000010578 if (Shorter.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +000010579 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
Richard Sandiford39c1ce42013-10-28 11:17:59 +000010580 Ptr, ST->getMemoryVT(), ST->getMemOperand());
Scott Michelcf0da6c2009-02-17 22:15:04 +000010581
Chris Lattnerf47e3062007-10-13 06:58:48 +000010582 // Otherwise, see if we can simplify the operation with
10583 // SimplifyDemandedBits, which only works if the value has a single use.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +000010584 if (SimplifyDemandedBits(Value,
Eric Christopherd9e8eac2010-12-09 04:48:06 +000010585 APInt::getLowBitsSet(
10586 Value.getValueType().getScalarType().getSizeInBits(),
10587 ST->getMemoryVT().getScalarType().getSizeInBits())))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010588 return SDValue(N, 0);
Chris Lattner5e6fe052007-10-13 06:35:54 +000010589 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000010590
Chris Lattner3f9c6a72007-12-29 06:26:16 +000010591 // If this is a load followed by a store to the same location, then the store
10592 // is dead/noop.
10593 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
Dan Gohman47a7d6f2008-01-30 00:15:11 +000010594 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +000010595 ST->isUnindexed() && !ST->isVolatile() &&
Chris Lattner51b01bf2008-01-08 23:08:06 +000010596 // There can't be any side effects between the load and store, such as
10597 // a call or store.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010598 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
Chris Lattner3f9c6a72007-12-29 06:26:16 +000010599 // The store is dead, remove it.
10600 return Chain;
10601 }
10602 }
Duncan Sands8651e9c2008-06-13 19:07:40 +000010603
James Molloy463db9a2014-09-27 17:02:54 +000010604 // If this is a store followed by a store with the same value to the same
10605 // location, then the store is dead/noop.
10606 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
10607 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
10608 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
10609 ST1->isUnindexed() && !ST1->isVolatile()) {
10610 // The store is dead, remove it.
10611 return Chain;
10612 }
10613 }
10614
Chris Lattner1ea55cf2008-01-17 19:59:44 +000010615 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
10616 // truncating store. We can do this even if this is already a truncstore.
10617 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
Gabor Greiff304a7a2008-08-28 21:40:38 +000010618 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +000010619 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
Dan Gohman47a7d6f2008-01-30 00:15:11 +000010620 ST->getMemoryVT())) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000010621 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
Richard Sandiford39c1ce42013-10-28 11:17:59 +000010622 Ptr, ST->getMemoryVT(), ST->getMemOperand());
Chris Lattner1ea55cf2008-01-17 19:59:44 +000010623 }
Duncan Sands8651e9c2008-06-13 19:07:40 +000010624
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010625 // Only perform this optimization before the types are legal, because we
Nadav Rotemb27777f2012-10-04 22:35:15 +000010626 // don't want to perform this optimization on every DAGCombine invocation.
Nadav Rotem1157e142012-12-02 17:14:09 +000010627 if (!LegalTypes) {
10628 bool EverChanged = false;
10629
10630 do {
10631 // There can be multiple store sequences on the same chain.
10632 // Keep trying to merge store sequences until we are unable to do so
10633 // or until we merge the last store on the chain.
10634 bool Changed = MergeConsecutiveStores(ST);
10635 EverChanged |= Changed;
10636 if (!Changed) break;
10637 } while (ST->getOpcode() != ISD::DELETED_NODE);
10638
10639 if (EverChanged)
10640 return SDValue(N, 0);
10641 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010642
Evan Chenga9cda8a2009-05-28 00:35:15 +000010643 return ReduceLoadOpStoreWidth(N);
Chris Lattner04c73702005-10-10 22:31:19 +000010644}
10645
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010646SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
10647 SDValue InVec = N->getOperand(0);
10648 SDValue InVal = N->getOperand(1);
10649 SDValue EltNo = N->getOperand(2);
Andrew Trickef9de2a2013-05-25 02:42:55 +000010650 SDLoc dl(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +000010651
Bob Wilson42603952010-05-19 23:42:58 +000010652 // If the inserted element is an UNDEF, just use the input vector.
10653 if (InVal.getOpcode() == ISD::UNDEF)
10654 return InVec;
10655
Nadav Rotemdb2f5482011-02-12 14:40:33 +000010656 EVT VT = InVec.getValueType();
10657
Owen Andersonb2c80da2011-02-25 21:41:48 +000010658 // If we can't generate a legal BUILD_VECTOR, exit
Nadav Rotemdb2f5482011-02-12 14:40:33 +000010659 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
10660 return SDValue();
10661
Eli Friedmanb7910b72011-09-09 21:04:06 +000010662 // Check that we know which element is being inserted
10663 if (!isa<ConstantSDNode>(EltNo))
10664 return SDValue();
10665 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +000010666
Andrea Di Biagiof99dd642014-06-09 16:54:41 +000010667 // Canonicalize insert_vector_elt dag nodes.
10668 // Example:
10669 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
10670 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
10671 //
10672 // Do this only if the child insert_vector node has one use; also
10673 // do this only if indices are both constants and Idx1 < Idx0.
10674 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
10675 && isa<ConstantSDNode>(InVec.getOperand(2))) {
10676 unsigned OtherElt =
10677 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
10678 if (Elt < OtherElt) {
10679 // Swap nodes.
10680 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
10681 InVec.getOperand(0), InVal, EltNo);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000010682 AddToWorklist(NewOp.getNode());
Andrea Di Biagiof99dd642014-06-09 16:54:41 +000010683 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
10684 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
10685 }
10686 }
10687
Eli Friedmanb7910b72011-09-09 21:04:06 +000010688 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
10689 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
10690 // vector elements.
10691 SmallVector<SDValue, 8> Ops;
Quentin Colombet6bf4baa2013-07-30 00:24:09 +000010692 // Do not combine these two vectors if the output vector will not replace
10693 // the input vector.
10694 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
Eli Friedmanb7910b72011-09-09 21:04:06 +000010695 Ops.append(InVec.getNode()->op_begin(),
10696 InVec.getNode()->op_end());
10697 } else if (InVec.getOpcode() == ISD::UNDEF) {
10698 unsigned NElts = VT.getVectorNumElements();
10699 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
10700 } else {
10701 return SDValue();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000010702 }
Eli Friedmanb7910b72011-09-09 21:04:06 +000010703
10704 // Insert the element
10705 if (Elt < Ops.size()) {
10706 // All the operands of BUILD_VECTOR must have the same type;
10707 // we enforce that here.
10708 EVT OpVT = Ops[0].getValueType();
10709 if (InVal.getValueType() != OpVT)
10710 InVal = OpVT.bitsGT(InVal.getValueType()) ?
10711 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
10712 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
10713 Ops[Elt] = InVal;
10714 }
10715
10716 // Return the new vector
Craig Topper48d114b2014-04-26 18:35:24 +000010717 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
Chris Lattner5336a592006-03-19 01:27:56 +000010718}
10719
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +000010720SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
10721 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
10722 EVT ResultVT = EVE->getValueType(0);
10723 EVT VecEltVT = InVecVT.getVectorElementType();
10724 unsigned Align = OriginalLoad->getAlignment();
10725 unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
10726 VecEltVT.getTypeForEVT(*DAG.getContext()));
10727
10728 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
10729 return SDValue();
10730
10731 Align = NewAlign;
10732
10733 SDValue NewPtr = OriginalLoad->getBasePtr();
10734 SDValue Offset;
10735 EVT PtrType = NewPtr.getValueType();
10736 MachinePointerInfo MPI;
10737 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
10738 int Elt = ConstEltNo->getZExtValue();
10739 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
10740 if (TLI.isBigEndian())
10741 PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
10742 Offset = DAG.getConstant(PtrOff, PtrType);
10743 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
10744 } else {
10745 Offset = DAG.getNode(
10746 ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo,
10747 DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType()));
10748 if (TLI.isBigEndian())
10749 Offset = DAG.getNode(
10750 ISD::SUB, SDLoc(EVE), EltNo.getValueType(),
10751 DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset);
10752 MPI = OriginalLoad->getPointerInfo();
10753 }
10754 NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset);
10755
10756 // The replacement we need to do here is a little tricky: we need to
10757 // replace an extractelement of a load with a load.
10758 // Use ReplaceAllUsesOfValuesWith to do the replacement.
10759 // Note that this replacement assumes that the extractvalue is the only
10760 // use of the load; that's okay because we don't want to perform this
10761 // transformation in other cases anyway.
10762 SDValue Load;
10763 SDValue Chain;
10764 if (ResultVT.bitsGT(VecEltVT)) {
10765 // If the result type of vextract is wider than the load, then issue an
10766 // extending load instead.
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +000010767 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
10768 VecEltVT)
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +000010769 ? ISD::ZEXTLOAD
10770 : ISD::EXTLOAD;
10771 Load = DAG.getExtLoad(
10772 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
10773 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10774 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10775 Chain = Load.getValue(1);
10776 } else {
10777 Load = DAG.getLoad(
10778 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
10779 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10780 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10781 Chain = Load.getValue(1);
10782 if (ResultVT.bitsLT(VecEltVT))
10783 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
10784 else
10785 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
10786 }
10787 WorklistRemover DeadNodes(*this);
10788 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
10789 SDValue To[] = { Load, Chain };
10790 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10791 // Since we're explicitly calling ReplaceAllUses, add the new node to the
10792 // worklist explicitly as well.
10793 AddToWorklist(Load.getNode());
10794 AddUsersToWorklist(Load.getNode()); // Add users too
10795 // Make sure to revisit this node to clean it up; it will usually be dead.
10796 AddToWorklist(EVE);
10797 ++OpsNarrowed;
10798 return SDValue(EVE, 0);
10799}
10800
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010801SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
Mon P Wangca6d6de2009-01-17 00:07:25 +000010802 // (vextract (scalar_to_vector val, 0) -> val
10803 SDValue InVec = N->getOperand(0);
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000010804 EVT VT = InVec.getValueType();
10805 EVT NVT = N->getValueType(0);
Mon P Wangca6d6de2009-01-17 00:07:25 +000010806
Duncan Sands6be291a2011-05-09 08:03:33 +000010807 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
10808 // Check if the result type doesn't match the inserted element type. A
10809 // SCALAR_TO_VECTOR may truncate the inserted element and the
10810 // EXTRACT_VECTOR_ELT may widen the extracted vector.
10811 SDValue InOp = InVec.getOperand(0);
Duncan Sands6be291a2011-05-09 08:03:33 +000010812 if (InOp.getValueType() != NVT) {
10813 assert(InOp.getValueType().isInteger() && NVT.isInteger());
Andrew Trickef9de2a2013-05-25 02:42:55 +000010814 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
Duncan Sands6be291a2011-05-09 08:03:33 +000010815 }
10816 return InOp;
10817 }
Evan Cheng1120279a2008-05-13 08:35:03 +000010818
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000010819 SDValue EltNo = N->getOperand(1);
10820 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
10821
10822 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
10823 // We only perform this optimization before the op legalization phase because
Nadav Rotem841c9a82012-09-20 08:53:31 +000010824 // we may introduce new vector instructions which are not backed by TD
10825 // patterns. For example on AVX, extracting elements from a wide vector
Hal Finkel02807592014-03-31 11:43:19 +000010826 // without using extract_subvector. However, if we can find an underlying
10827 // scalar value, then we can always use that.
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000010828 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
Hal Finkel02807592014-03-31 11:43:19 +000010829 && ConstEltNo) {
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000010830 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10831 int NumElem = VT.getVectorNumElements();
10832 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
10833 // Find the new index to extract from.
10834 int OrigElt = SVOp->getMaskElt(Elt);
10835
10836 // Extracting an undef index is undef.
10837 if (OrigElt == -1)
10838 return DAG.getUNDEF(NVT);
10839
10840 // Select the right vector half to extract from.
Hal Finkel02807592014-03-31 11:43:19 +000010841 SDValue SVInVec;
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000010842 if (OrigElt < NumElem) {
Hal Finkel02807592014-03-31 11:43:19 +000010843 SVInVec = InVec->getOperand(0);
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000010844 } else {
Hal Finkel02807592014-03-31 11:43:19 +000010845 SVInVec = InVec->getOperand(1);
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000010846 OrigElt -= NumElem;
10847 }
10848
Hal Finkel02807592014-03-31 11:43:19 +000010849 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
10850 SDValue InOp = SVInVec.getOperand(OrigElt);
10851 if (InOp.getValueType() != NVT) {
10852 assert(InOp.getValueType().isInteger() && NVT.isInteger());
10853 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
10854 }
10855
10856 return InOp;
10857 }
10858
10859 // FIXME: We should handle recursing on other vector shuffles and
10860 // scalar_to_vector here as well.
10861
10862 if (!LegalOperations) {
10863 EVT IndexTy = TLI.getVectorIdxTy();
10864 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
10865 SVInVec, DAG.getConstant(OrigElt, IndexTy));
10866 }
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000010867 }
10868
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +000010869 bool BCNumEltsChanged = false;
10870 EVT ExtVT = VT.getVectorElementType();
10871 EVT LVT = ExtVT;
10872
10873 // If the result of load has to be truncated, then it's not necessarily
10874 // profitable.
10875 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
10876 return SDValue();
10877
10878 if (InVec.getOpcode() == ISD::BITCAST) {
10879 // Don't duplicate a load with other uses.
10880 if (!InVec.hasOneUse())
10881 return SDValue();
10882
10883 EVT BCVT = InVec.getOperand(0).getValueType();
10884 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
10885 return SDValue();
10886 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
10887 BCNumEltsChanged = true;
10888 InVec = InVec.getOperand(0);
10889 ExtVT = BCVT.getVectorElementType();
10890 }
10891
10892 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
10893 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
10894 ISD::isNormalLoad(InVec.getNode()) &&
10895 !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
10896 SDValue Index = N->getOperand(1);
10897 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
10898 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
10899 OrigLoad);
10900 }
10901
Evan Cheng1120279a2008-05-13 08:35:03 +000010902 // Perform only after legalization to ensure build_vector / vector_shuffle
10903 // optimizations have already been done.
Duncan Sandsdc2dac12008-11-24 14:53:14 +000010904 if (!LegalOperations) return SDValue();
Evan Cheng1120279a2008-05-13 08:35:03 +000010905
Mon P Wangca6d6de2009-01-17 00:07:25 +000010906 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
10907 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
10908 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
Evan Cheng0de312d2007-10-06 08:19:55 +000010909
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000010910 if (ConstEltNo) {
Eric Christopherfcc9e682010-11-03 09:36:40 +000010911 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Evan Cheng0de312d2007-10-06 08:19:55 +000010912
Craig Topperc0196b12014-04-14 00:51:57 +000010913 LoadSDNode *LN0 = nullptr;
10914 const ShuffleVectorSDNode *SVN = nullptr;
Bill Wendling27d9dd42009-01-30 23:36:47 +000010915 if (ISD::isNormalLoad(InVec.getNode())) {
Evan Cheng1120279a2008-05-13 08:35:03 +000010916 LN0 = cast<LoadSDNode>(InVec);
Bill Wendling27d9dd42009-01-30 23:36:47 +000010917 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
Owen Anderson53aa7a92009-08-10 22:56:29 +000010918 InVec.getOperand(0).getValueType() == ExtVT &&
Bill Wendling27d9dd42009-01-30 23:36:47 +000010919 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
Eli Friedmane96286c2011-12-26 22:49:32 +000010920 // Don't duplicate a load with other uses.
10921 if (!InVec.hasOneUse())
10922 return SDValue();
10923
Evan Cheng1120279a2008-05-13 08:35:03 +000010924 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
Nate Begeman5f829d82009-04-29 05:20:52 +000010925 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
Evan Cheng1120279a2008-05-13 08:35:03 +000010926 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
10927 // =>
10928 // (load $addr+1*size)
Scott Michelcf0da6c2009-02-17 22:15:04 +000010929
Eli Friedmane96286c2011-12-26 22:49:32 +000010930 // Don't duplicate a load with other uses.
10931 if (!InVec.hasOneUse())
10932 return SDValue();
10933
Mon P Wangb5eb7202008-12-11 00:26:16 +000010934 // If the bit convert changed the number of elements, it is unsafe
10935 // to examine the mask.
10936 if (BCNumEltsChanged)
10937 return SDValue();
Nate Begeman5f829d82009-04-29 05:20:52 +000010938
10939 // Select the input vector, guarding against out of range extract vector.
10940 unsigned NumElems = VT.getVectorNumElements();
Eric Christopherfcc9e682010-11-03 09:36:40 +000010941 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
Nate Begeman5f829d82009-04-29 05:20:52 +000010942 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
10943
Eli Friedmane96286c2011-12-26 22:49:32 +000010944 if (InVec.getOpcode() == ISD::BITCAST) {
10945 // Don't duplicate a load with other uses.
10946 if (!InVec.hasOneUse())
10947 return SDValue();
10948
Evan Cheng1120279a2008-05-13 08:35:03 +000010949 InVec = InVec.getOperand(0);
Eli Friedmane96286c2011-12-26 22:49:32 +000010950 }
Gabor Greiff304a7a2008-08-28 21:40:38 +000010951 if (ISD::isNormalLoad(InVec.getNode())) {
Evan Cheng1120279a2008-05-13 08:35:03 +000010952 LN0 = cast<LoadSDNode>(InVec);
Ted Kremenekd87bd772010-04-08 18:49:30 +000010953 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +000010954 EltNo = DAG.getConstant(Elt, EltNo.getValueType());
Evan Cheng0de312d2007-10-06 08:19:55 +000010955 }
10956 }
Bill Wendling27d9dd42009-01-30 23:36:47 +000010957
Eli Friedmane96286c2011-12-26 22:49:32 +000010958 // Make sure we found a non-volatile load and the extractelement is
10959 // the only use.
Nadav Rotem8a7beb82011-05-11 14:40:50 +000010960 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010961 return SDValue();
Evan Cheng1120279a2008-05-13 08:35:03 +000010962
Eric Christopherc6418b12010-11-03 20:44:42 +000010963 // If Idx was -1 above, Elt is going to be -1, so just return undef.
10964 if (Elt == -1)
Eli Friedmancbd3ba92011-07-25 22:25:42 +000010965 return DAG.getUNDEF(LVT);
Eric Christopherc6418b12010-11-03 20:44:42 +000010966
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +000010967 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
Evan Cheng0de312d2007-10-06 08:19:55 +000010968 }
Bill Wendling27d9dd42009-01-30 23:36:47 +000010969
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000010970 return SDValue();
Evan Cheng0de312d2007-10-06 08:19:55 +000010971}
Evan Cheng0de312d2007-10-06 08:19:55 +000010972
Michael Liao6d106b72012-10-23 23:06:52 +000010973// Simplify (build_vec (ext )) to (bitcast (build_vec ))
10974SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
10975 // We perform this optimization post type-legalization because
10976 // the type-legalizer often scalarizes integer-promoted vectors.
10977 // Performing this optimization before may create bit-casts which
10978 // will be type-legalized to complex code sequences.
10979 // We perform this optimization only before the operation legalizer because we
10980 // may introduce illegal operations.
10981 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
10982 return SDValue();
10983
Dan Gohmana8665142007-06-25 16:23:39 +000010984 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +000010985 SDLoc dl(N);
Owen Anderson53aa7a92009-08-10 22:56:29 +000010986 EVT VT = N->getValueType(0);
Nadav Rotema62368c2012-07-15 08:38:23 +000010987
Nadav Rotembf6568b2011-10-29 21:23:04 +000010988 // Check to see if this is a BUILD_VECTOR of a bunch of values
10989 // which come from any_extend or zero_extend nodes. If so, we can create
10990 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
Nadav Rotemf3103612011-10-31 20:08:25 +000010991 // optimizations. We do not handle sign-extend because we can't fill the sign
10992 // using shuffles.
Nadav Rotembf6568b2011-10-29 21:23:04 +000010993 EVT SourceType = MVT::Other;
Craig Topper02cb0fb2012-01-17 09:09:48 +000010994 bool AllAnyExt = true;
Nadav Rotema62368c2012-07-15 08:38:23 +000010995
Craig Topper02cb0fb2012-01-17 09:09:48 +000010996 for (unsigned i = 0; i != NumInScalars; ++i) {
Nadav Rotembf6568b2011-10-29 21:23:04 +000010997 SDValue In = N->getOperand(i);
10998 // Ignore undef inputs.
10999 if (In.getOpcode() == ISD::UNDEF) continue;
11000
11001 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
11002 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
11003
Nadav Rotemf3103612011-10-31 20:08:25 +000011004 // Abort if the element is not an extension.
Nadav Rotembf6568b2011-10-29 21:23:04 +000011005 if (!ZeroExt && !AnyExt) {
Nadav Rotemf3103612011-10-31 20:08:25 +000011006 SourceType = MVT::Other;
Nadav Rotembf6568b2011-10-29 21:23:04 +000011007 break;
11008 }
11009
11010 // The input is a ZeroExt or AnyExt. Check the original type.
11011 EVT InTy = In.getOperand(0).getValueType();
11012
11013 // Check that all of the widened source types are the same.
11014 if (SourceType == MVT::Other)
Nadav Rotemf3103612011-10-31 20:08:25 +000011015 // First time.
Nadav Rotembf6568b2011-10-29 21:23:04 +000011016 SourceType = InTy;
11017 else if (InTy != SourceType) {
11018 // Multiple income types. Abort.
Nadav Rotemf3103612011-10-31 20:08:25 +000011019 SourceType = MVT::Other;
Nadav Rotembf6568b2011-10-29 21:23:04 +000011020 break;
11021 }
11022
11023 // Check if all of the extends are ANY_EXTENDs.
Craig Topper02cb0fb2012-01-17 09:09:48 +000011024 AllAnyExt &= AnyExt;
Nadav Rotembf6568b2011-10-29 21:23:04 +000011025 }
11026
Nadav Rotemf3103612011-10-31 20:08:25 +000011027 // In order to have valid types, all of the inputs must be extended from the
11028 // same source type and all of the inputs must be any or zero extend.
11029 // Scalar sizes must be a power of two.
Michael Liao6d106b72012-10-23 23:06:52 +000011030 EVT OutScalarTy = VT.getScalarType();
Nadav Rotem34ca89a2012-02-12 15:05:31 +000011031 bool ValidTypes = SourceType != MVT::Other &&
Nadav Rotemf3103612011-10-31 20:08:25 +000011032 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
11033 isPowerOf2_32(SourceType.getSizeInBits());
11034
Nadav Rotem6fd1d322012-03-15 08:49:06 +000011035 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
11036 // turn into a single shuffle instruction.
Michael Liao6d106b72012-10-23 23:06:52 +000011037 if (!ValidTypes)
11038 return SDValue();
Nadav Rotembf6568b2011-10-29 21:23:04 +000011039
Michael Liao6d106b72012-10-23 23:06:52 +000011040 bool isLE = TLI.isLittleEndian();
11041 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
11042 assert(ElemRatio > 1 && "Invalid element size ratio");
11043 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
11044 DAG.getConstant(0, SourceType);
Nadav Rotembf6568b2011-10-29 21:23:04 +000011045
Michael Liao6d106b72012-10-23 23:06:52 +000011046 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
11047 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
Nadav Rotembf6568b2011-10-29 21:23:04 +000011048
Michael Liao6d106b72012-10-23 23:06:52 +000011049 // Populate the new build_vector
Jakub Staszaka6addc22012-10-24 00:38:25 +000011050 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
Michael Liao6d106b72012-10-23 23:06:52 +000011051 SDValue Cast = N->getOperand(i);
11052 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
11053 Cast.getOpcode() == ISD::ZERO_EXTEND ||
11054 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
11055 SDValue In;
11056 if (Cast.getOpcode() == ISD::UNDEF)
11057 In = DAG.getUNDEF(SourceType);
11058 else
11059 In = Cast->getOperand(0);
11060 unsigned Index = isLE ? (i * ElemRatio) :
11061 (i * ElemRatio + (ElemRatio - 1));
Nadav Rotembf6568b2011-10-29 21:23:04 +000011062
Michael Liao6d106b72012-10-23 23:06:52 +000011063 assert(Index < Ops.size() && "Invalid index");
11064 Ops[Index] = In;
Nadav Rotembf6568b2011-10-29 21:23:04 +000011065 }
Chris Lattner5336a592006-03-19 01:27:56 +000011066
Michael Liao6d106b72012-10-23 23:06:52 +000011067 // The type of the new BUILD_VECTOR node.
11068 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
11069 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
11070 "Invalid vector size");
11071 // Check if the new vector type is legal.
11072 if (!isTypeLegal(VecVT)) return SDValue();
11073
11074 // Make the new BUILD_VECTOR.
Craig Topper48d114b2014-04-26 18:35:24 +000011075 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
Michael Liao6d106b72012-10-23 23:06:52 +000011076
11077 // The new BUILD_VECTOR node has the potential to be further optimized.
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011078 AddToWorklist(BV.getNode());
Michael Liao6d106b72012-10-23 23:06:52 +000011079 // Bitcast to the desired type.
11080 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
11081}
11082
Michael Liao59229792012-10-24 04:14:18 +000011083SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
11084 EVT VT = N->getValueType(0);
11085
11086 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +000011087 SDLoc dl(N);
Michael Liao59229792012-10-24 04:14:18 +000011088
11089 EVT SrcVT = MVT::Other;
11090 unsigned Opcode = ISD::DELETED_NODE;
11091 unsigned NumDefs = 0;
11092
11093 for (unsigned i = 0; i != NumInScalars; ++i) {
11094 SDValue In = N->getOperand(i);
11095 unsigned Opc = In.getOpcode();
11096
11097 if (Opc == ISD::UNDEF)
11098 continue;
11099
11100 // If all scalar values are floats and converted from integers.
11101 if (Opcode == ISD::DELETED_NODE &&
11102 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
11103 Opcode = Opc;
Michael Liao59229792012-10-24 04:14:18 +000011104 }
Tom Stellard567f8862013-01-02 22:13:01 +000011105
Michael Liao59229792012-10-24 04:14:18 +000011106 if (Opc != Opcode)
11107 return SDValue();
11108
11109 EVT InVT = In.getOperand(0).getValueType();
11110
11111 // If all scalar values are typed differently, bail out. It's chosen to
11112 // simplify BUILD_VECTOR of integer types.
11113 if (SrcVT == MVT::Other)
11114 SrcVT = InVT;
11115 if (SrcVT != InVT)
11116 return SDValue();
11117 NumDefs++;
11118 }
11119
11120 // If the vector has just one element defined, it's not worth to fold it into
11121 // a vectorized one.
11122 if (NumDefs < 2)
11123 return SDValue();
11124
11125 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
11126 && "Should only handle conversion from integer to float.");
11127 assert(SrcVT != MVT::Other && "Cannot determine source type!");
11128
11129 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
Tom Stellard567f8862013-01-02 22:13:01 +000011130
11131 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
11132 return SDValue();
11133
Michael Liao59229792012-10-24 04:14:18 +000011134 SmallVector<SDValue, 8> Opnds;
11135 for (unsigned i = 0; i != NumInScalars; ++i) {
11136 SDValue In = N->getOperand(i);
11137
11138 if (In.getOpcode() == ISD::UNDEF)
11139 Opnds.push_back(DAG.getUNDEF(SrcVT));
11140 else
11141 Opnds.push_back(In.getOperand(0));
11142 }
Craig Topper48d114b2014-04-26 18:35:24 +000011143 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011144 AddToWorklist(BV.getNode());
Michael Liao59229792012-10-24 04:14:18 +000011145
11146 return DAG.getNode(Opcode, dl, VT, BV);
11147}
11148
Michael Liao6d106b72012-10-23 23:06:52 +000011149SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
11150 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +000011151 SDLoc dl(N);
Michael Liao6d106b72012-10-23 23:06:52 +000011152 EVT VT = N->getValueType(0);
11153
11154 // A vector built entirely of undefs is undef.
11155 if (ISD::allOperandsUndef(N))
11156 return DAG.getUNDEF(VT);
11157
11158 SDValue V = reduceBuildVecExtToExtBuildVec(N);
11159 if (V.getNode())
11160 return V;
11161
Michael Liao59229792012-10-24 04:14:18 +000011162 V = reduceBuildVecConvertToConvertBuildVec(N);
11163 if (V.getNode())
11164 return V;
11165
Dan Gohmana8665142007-06-25 16:23:39 +000011166 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
11167 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
11168 // at most two distinct vectors, turn this into a shuffle node.
Duncan Sands3fb2fc62012-03-19 15:35:44 +000011169
Andrea Di Biagioc7c52412014-09-30 15:30:22 +000011170 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
11171 if (!isTypeLegal(VT))
11172 return SDValue();
11173
Duncan Sands3fb2fc62012-03-19 15:35:44 +000011174 // May only combine to shuffle after legalize if shuffle is legal.
Owen Anderson3eb910b2014-08-28 17:49:58 +000011175 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
Duncan Sands3fb2fc62012-03-19 15:35:44 +000011176 return SDValue();
11177
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011178 SDValue VecIn1, VecIn2;
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011179 bool UsesZeroVector = false;
Chris Lattnerc9992542006-03-28 20:28:38 +000011180 for (unsigned i = 0; i != NumInScalars; ++i) {
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011181 SDValue Op = N->getOperand(i);
Chris Lattnerc9992542006-03-28 20:28:38 +000011182 // Ignore undef inputs.
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011183 if (Op.getOpcode() == ISD::UNDEF) continue;
11184
11185 // See if we can combine this build_vector into a blend with a zero vector.
11186 if (!VecIn2.getNode() && ((Op.getOpcode() == ISD::Constant &&
11187 cast<ConstantSDNode>(Op.getNode())->isNullValue()) ||
11188 (Op.getOpcode() == ISD::ConstantFP &&
11189 cast<ConstantFPSDNode>(Op.getNode())->getValueAPF().isZero()))) {
11190 UsesZeroVector = true;
11191 continue;
11192 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011193
Dan Gohmana8665142007-06-25 16:23:39 +000011194 // If this input is something other than a EXTRACT_VECTOR_ELT with a
Chris Lattnerc9992542006-03-28 20:28:38 +000011195 // constant index, bail out.
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011196 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11197 !isa<ConstantSDNode>(Op.getOperand(1))) {
Craig Topperc0196b12014-04-14 00:51:57 +000011198 VecIn1 = VecIn2 = SDValue(nullptr, 0);
Chris Lattnerc9992542006-03-28 20:28:38 +000011199 break;
11200 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011201
Nadav Rotem34ca89a2012-02-12 15:05:31 +000011202 // We allow up to two distinct input vectors.
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011203 SDValue ExtractedFromVec = Op.getOperand(0);
Chris Lattnerc9992542006-03-28 20:28:38 +000011204 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
11205 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011206
Craig Topperc0196b12014-04-14 00:51:57 +000011207 if (!VecIn1.getNode()) {
Chris Lattnerc9992542006-03-28 20:28:38 +000011208 VecIn1 = ExtractedFromVec;
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011209 } else if (!VecIn2.getNode() && !UsesZeroVector) {
Chris Lattnerc9992542006-03-28 20:28:38 +000011210 VecIn2 = ExtractedFromVec;
11211 } else {
11212 // Too many inputs.
Craig Topperc0196b12014-04-14 00:51:57 +000011213 VecIn1 = VecIn2 = SDValue(nullptr, 0);
Chris Lattnerc9992542006-03-28 20:28:38 +000011214 break;
11215 }
11216 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011217
Jim Grosbach2eb60fd2014-04-29 22:41:50 +000011218 // If everything is good, we can make a shuffle operation.
Gabor Greiff304a7a2008-08-28 21:40:38 +000011219 if (VecIn1.getNode()) {
Michael Kupersteinf4536ea2014-12-23 08:59:45 +000011220 unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011221 SmallVector<int, 8> Mask;
Chris Lattnerc9992542006-03-28 20:28:38 +000011222 for (unsigned i = 0; i != NumInScalars; ++i) {
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011223 unsigned Opcode = N->getOperand(i).getOpcode();
11224 if (Opcode == ISD::UNDEF) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011225 Mask.push_back(-1);
Chris Lattnerc9992542006-03-28 20:28:38 +000011226 continue;
11227 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011228
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011229 // Operands can also be zero.
11230 if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
11231 assert(UsesZeroVector &&
11232 (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
11233 "Unexpected node found!");
11234 Mask.push_back(NumInScalars+i);
11235 continue;
11236 }
11237
Rafael Espindolab93db662009-04-24 12:40:33 +000011238 // If extracting from the first vector, just use the index directly.
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011239 SDValue Extract = N->getOperand(i);
Mon P Wang523c0852009-03-17 06:33:10 +000011240 SDValue ExtVal = Extract.getOperand(1);
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011241 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
Chris Lattnerc9992542006-03-28 20:28:38 +000011242 if (Extract.getOperand(0) == VecIn1) {
Nate Begeman5f829d82009-04-29 05:20:52 +000011243 Mask.push_back(ExtIndex);
Chris Lattnerc9992542006-03-28 20:28:38 +000011244 continue;
11245 }
11246
Michael Kupersteinf4536ea2014-12-23 08:59:45 +000011247 // Otherwise, use InIdx + InputVecSize
11248 Mask.push_back(InNumElements + ExtIndex);
Chris Lattnerc9992542006-03-28 20:28:38 +000011249 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011250
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011251 // Avoid introducing illegal shuffles with zero.
11252 if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
11253 return SDValue();
11254
Nadav Rotem34ca89a2012-02-12 15:05:31 +000011255 // We can't generate a shuffle node with mismatched input and output types.
11256 // Attempt to transform a single input vector to the correct type.
11257 if ((VT != VecIn1.getValueType())) {
James Molloy1e5c6112012-09-10 14:01:21 +000011258 // If the input vector type has a different base type to the output
11259 // vector type, bail out.
Michael Kupersteinf4536ea2014-12-23 08:59:45 +000011260 EVT VTElemType = VT.getVectorElementType();
11261 if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
11262 (VecIn2.getNode() &&
11263 (VecIn2.getValueType().getVectorElementType() != VTElemType)))
James Molloy1e5c6112012-09-10 14:01:21 +000011264 return SDValue();
11265
Michael Kuperstein047b1a02014-12-17 12:32:17 +000011266 // If the input vector is too small, widen it.
11267 // We only support widening of vectors which are half the size of the
11268 // output registers. For example XMM->YMM widening on X86 with AVX.
11269 EVT VecInT = VecIn1.getValueType();
11270 if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
Michael Kupersteinf4536ea2014-12-23 08:59:45 +000011271 // If we only have one small input, widen it by adding undef values.
11272 if (!VecIn2.getNode())
11273 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
11274 DAG.getUNDEF(VecIn1.getValueType()));
11275 else if (VecIn1.getValueType() == VecIn2.getValueType()) {
11276 // If we have two small inputs of the same type, try to concat them.
11277 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
11278 VecIn2 = SDValue(nullptr, 0);
11279 } else
11280 return SDValue();
Michael Kuperstein047b1a02014-12-17 12:32:17 +000011281 } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
11282 // If the input vector is too large, try to split it.
Michael Kupersteinf4536ea2014-12-23 08:59:45 +000011283 // We don't support having two input vectors that are too large.
11284 if (VecIn2.getNode())
11285 return SDValue();
11286
Michael Kuperstein047b1a02014-12-17 12:32:17 +000011287 if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
11288 return SDValue();
11289
11290 // Try to replace VecIn1 with two extract_subvectors
11291 // No need to update the masks, they should still be correct.
11292 VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11293 DAG.getConstant(VT.getVectorNumElements(), TLI.getVectorIdxTy()));
11294 VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11295 DAG.getConstant(0, TLI.getVectorIdxTy()));
11296 UsesZeroVector = false;
Michael Kupersteinf4536ea2014-12-23 08:59:45 +000011297 } else
Michael Kuperstein047b1a02014-12-17 12:32:17 +000011298 return SDValue();
Nadav Rotem34ca89a2012-02-12 15:05:31 +000011299 }
11300
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011301 if (UsesZeroVector)
11302 VecIn2 = VT.isInteger() ? DAG.getConstant(0, VT) :
11303 DAG.getConstantFP(0.0, VT);
11304 else
11305 // If VecIn2 is unused then change it to undef.
11306 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
Nadav Rotem34ca89a2012-02-12 15:05:31 +000011307
Nadav Rotem841c9a82012-09-20 08:53:31 +000011308 // Check that we were able to transform all incoming values to the same
11309 // type.
Nadav Rotem0c650642012-02-13 12:42:26 +000011310 if (VecIn2.getValueType() != VecIn1.getValueType() ||
11311 VecIn1.getValueType() != VT)
11312 return SDValue();
11313
Dan Gohmana8665142007-06-25 16:23:39 +000011314 // Return the new VECTOR_SHUFFLE node.
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011315 SDValue Ops[2];
Chris Lattnerc24a1d32006-08-08 02:23:42 +000011316 Ops[0] = VecIn1;
Nadav Rotem34ca89a2012-02-12 15:05:31 +000011317 Ops[1] = VecIn2;
Michael Liao6d106b72012-10-23 23:06:52 +000011318 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
Chris Lattnerc9992542006-03-28 20:28:38 +000011319 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011320
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011321 return SDValue();
Chris Lattnerc9992542006-03-28 20:28:38 +000011322}
11323
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011324SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
Dan Gohmana8665142007-06-25 16:23:39 +000011325 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
11326 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
11327 // inputs come from at most two distinct vectors, turn this into a shuffle
11328 // node.
11329
11330 // If we only have one input vector, we don't need to do any concatenation.
Bill Wendling27d9dd42009-01-30 23:36:47 +000011331 if (N->getNumOperands() == 1)
Dan Gohmana8665142007-06-25 16:23:39 +000011332 return N->getOperand(0);
Dan Gohmana8665142007-06-25 16:23:39 +000011333
Nadav Rotem01892102012-07-14 21:30:27 +000011334 // Check if all of the operands are undefs.
Nadav Rotemd369d4b2013-10-25 06:41:18 +000011335 EVT VT = N->getValueType(0);
Nadav Rotema62368c2012-07-15 08:38:23 +000011336 if (ISD::allOperandsUndef(N))
Nadav Rotemd369d4b2013-10-25 06:41:18 +000011337 return DAG.getUNDEF(VT);
11338
11339 // Optimize concat_vectors where one of the vectors is undef.
11340 if (N->getNumOperands() == 2 &&
11341 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
11342 SDValue In = N->getOperand(0);
Nadav Rotem6eee0802013-12-10 01:13:59 +000011343 assert(In.getValueType().isVector() && "Must concat vectors");
Nadav Rotemd369d4b2013-10-25 06:41:18 +000011344
11345 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
11346 if (In->getOpcode() == ISD::BITCAST &&
11347 !In->getOperand(0)->getValueType(0).isVector()) {
11348 SDValue Scalar = In->getOperand(0);
11349 EVT SclTy = Scalar->getValueType(0);
11350
11351 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
11352 return SDValue();
11353
11354 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
11355 VT.getSizeInBits() / SclTy.getSizeInBits());
11356 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
11357 return SDValue();
11358
11359 SDLoc dl = SDLoc(N);
11360 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
11361 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
11362 }
11363 }
Nadav Rotem01892102012-07-14 21:30:27 +000011364
Robert Lougher7d9084f2014-02-11 15:42:46 +000011365 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
11366 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
11367 if (N->getNumOperands() == 2 &&
11368 N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
11369 N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
11370 EVT VT = N->getValueType(0);
11371 SDValue N0 = N->getOperand(0);
11372 SDValue N1 = N->getOperand(1);
11373 SmallVector<SDValue, 8> Opnds;
11374 unsigned BuildVecNumElts = N0.getNumOperands();
11375
Hao Liu71224b02014-07-10 03:41:50 +000011376 EVT SclTy0 = N0.getOperand(0)->getValueType(0);
11377 EVT SclTy1 = N1.getOperand(0)->getValueType(0);
11378 if (SclTy0.isFloatingPoint()) {
11379 for (unsigned i = 0; i != BuildVecNumElts; ++i)
11380 Opnds.push_back(N0.getOperand(i));
11381 for (unsigned i = 0; i != BuildVecNumElts; ++i)
11382 Opnds.push_back(N1.getOperand(i));
11383 } else {
11384 // If BUILD_VECTOR are from built from integer, they may have different
11385 // operand types. Get the smaller type and truncate all operands to it.
11386 EVT MinTy = SclTy0.bitsLE(SclTy1) ? SclTy0 : SclTy1;
11387 for (unsigned i = 0; i != BuildVecNumElts; ++i)
11388 Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
11389 N0.getOperand(i)));
11390 for (unsigned i = 0; i != BuildVecNumElts; ++i)
11391 Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
11392 N1.getOperand(i)));
11393 }
Robert Lougher7d9084f2014-02-11 15:42:46 +000011394
Craig Topper48d114b2014-04-26 18:35:24 +000011395 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
Robert Lougher7d9084f2014-02-11 15:42:46 +000011396 }
11397
Nadav Roteme5a2dda2013-05-01 19:18:51 +000011398 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
11399 // nodes often generate nop CONCAT_VECTOR nodes.
11400 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
11401 // place the incoming vectors at the exact same location.
11402 SDValue SingleSource = SDValue();
11403 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
11404
11405 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11406 SDValue Op = N->getOperand(i);
11407
11408 if (Op.getOpcode() == ISD::UNDEF)
11409 continue;
11410
11411 // Check if this is the identity extract:
11412 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
11413 return SDValue();
11414
11415 // Find the single incoming vector for the extract_subvector.
11416 if (SingleSource.getNode()) {
11417 if (Op.getOperand(0) != SingleSource)
11418 return SDValue();
11419 } else {
11420 SingleSource = Op.getOperand(0);
Michael Kupersteinac868752013-05-06 08:06:13 +000011421
11422 // Check the source type is the same as the type of the result.
11423 // If not, this concat may extend the vector, so we can not
11424 // optimize it away.
11425 if (SingleSource.getValueType() != N->getValueType(0))
11426 return SDValue();
Nadav Roteme5a2dda2013-05-01 19:18:51 +000011427 }
11428
11429 unsigned IdentityIndex = i * PartNumElem;
11430 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
11431 // The extract index must be constant.
11432 if (!CS)
11433 return SDValue();
Stephen Lincfe7f352013-07-08 00:37:03 +000011434
Nadav Roteme5a2dda2013-05-01 19:18:51 +000011435 // Check that we are reading from the identity index.
11436 if (CS->getZExtValue() != IdentityIndex)
11437 return SDValue();
11438 }
11439
11440 if (SingleSource.getNode())
11441 return SingleSource;
Stephen Lincfe7f352013-07-08 00:37:03 +000011442
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011443 return SDValue();
Dan Gohmana8665142007-06-25 16:23:39 +000011444}
11445
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +000011446SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
11447 EVT NVT = N->getValueType(0);
11448 SDValue V = N->getOperand(0);
11449
Michael Liao7a442c802012-10-17 20:48:33 +000011450 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
11451 // Combine:
11452 // (extract_subvec (concat V1, V2, ...), i)
11453 // Into:
11454 // Vi if possible
Jack Carterd4e96152013-10-17 01:34:33 +000011455 // Only operand 0 is checked as 'concat' assumes all inputs of the same
11456 // type.
Michael Liao2c235802012-10-19 03:17:00 +000011457 if (V->getOperand(0).getValueType() != NVT)
11458 return SDValue();
Michael Liao7a442c802012-10-17 20:48:33 +000011459 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
11460 unsigned NumElems = NVT.getVectorNumElements();
11461 assert((Idx % NumElems) == 0 &&
11462 "IDX in concat is not a multiple of the result vector length.");
11463 return V->getOperand(Idx / NumElems);
11464 }
11465
Michael Liaobb05a1d2013-03-25 23:47:35 +000011466 // Skip bitcasting
11467 if (V->getOpcode() == ISD::BITCAST)
11468 V = V.getOperand(0);
11469
11470 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011471 SDLoc dl(N);
Michael Liaobb05a1d2013-03-25 23:47:35 +000011472 // Handle only simple case where vector being inserted and vector
11473 // being extracted are of same type, and are half size of larger vectors.
11474 EVT BigVT = V->getOperand(0).getValueType();
11475 EVT SmallVT = V->getOperand(1).getValueType();
11476 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
11477 return SDValue();
11478
11479 // Only handle cases where both indexes are constants with the same type.
11480 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
11481 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
11482
11483 if (InsIdx && ExtIdx &&
11484 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
11485 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
11486 // Combine:
11487 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
11488 // Into:
11489 // indices are equal or bit offsets are equal => V1
11490 // otherwise => (extract_subvec V1, ExtIdx)
11491 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
11492 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
11493 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
11494 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
11495 DAG.getNode(ISD::BITCAST, dl,
11496 N->getOperand(0).getValueType(),
11497 V->getOperand(0)), N->getOperand(1));
11498 }
11499 }
11500
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +000011501 return SDValue();
11502}
11503
Chandler Carruthdaa1ff92014-10-05 19:14:34 +000011504static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
11505 SDValue V, SelectionDAG &DAG) {
11506 SDLoc DL(V);
11507 EVT VT = V.getValueType();
11508
11509 switch (V.getOpcode()) {
11510 default:
11511 return V;
11512
11513 case ISD::CONCAT_VECTORS: {
11514 EVT OpVT = V->getOperand(0).getValueType();
11515 int OpSize = OpVT.getVectorNumElements();
11516 SmallBitVector OpUsedElements(OpSize, false);
11517 bool FoundSimplification = false;
11518 SmallVector<SDValue, 4> NewOps;
11519 NewOps.reserve(V->getNumOperands());
11520 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
11521 SDValue Op = V->getOperand(i);
11522 bool OpUsed = false;
11523 for (int j = 0; j < OpSize; ++j)
11524 if (UsedElements[i * OpSize + j]) {
11525 OpUsedElements[j] = true;
11526 OpUsed = true;
11527 }
11528 NewOps.push_back(
11529 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
11530 : DAG.getUNDEF(OpVT));
11531 FoundSimplification |= Op == NewOps.back();
11532 OpUsedElements.reset();
11533 }
11534 if (FoundSimplification)
11535 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
11536 return V;
11537 }
11538
11539 case ISD::INSERT_SUBVECTOR: {
11540 SDValue BaseV = V->getOperand(0);
11541 SDValue SubV = V->getOperand(1);
11542 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
11543 if (!IdxN)
11544 return V;
11545
11546 int SubSize = SubV.getValueType().getVectorNumElements();
11547 int Idx = IdxN->getZExtValue();
11548 bool SubVectorUsed = false;
11549 SmallBitVector SubUsedElements(SubSize, false);
11550 for (int i = 0; i < SubSize; ++i)
11551 if (UsedElements[i + Idx]) {
11552 SubVectorUsed = true;
11553 SubUsedElements[i] = true;
11554 UsedElements[i + Idx] = false;
11555 }
11556
11557 // Now recurse on both the base and sub vectors.
11558 SDValue SimplifiedSubV =
11559 SubVectorUsed
11560 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
11561 : DAG.getUNDEF(SubV.getValueType());
11562 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
11563 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
11564 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
11565 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
11566 return V;
11567 }
11568 }
11569}
11570
11571static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
11572 SDValue N1, SelectionDAG &DAG) {
11573 EVT VT = SVN->getValueType(0);
11574 int NumElts = VT.getVectorNumElements();
11575 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
11576 for (int M : SVN->getMask())
11577 if (M >= 0 && M < NumElts)
11578 N0UsedElements[M] = true;
11579 else if (M >= NumElts)
11580 N1UsedElements[M - NumElts] = true;
11581
11582 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
11583 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
11584 if (S0 == N0 && S1 == N1)
11585 return SDValue();
11586
11587 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
11588}
11589
Mehdi Amini37f316a2015-01-17 01:35:56 +000011590// Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
11591// or turn a shuffle of a single concat into simpler shuffle then concat.
Benjamin Kramerbbae9912013-04-09 17:41:43 +000011592static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
11593 EVT VT = N->getValueType(0);
11594 unsigned NumElts = VT.getVectorNumElements();
11595
11596 SDValue N0 = N->getOperand(0);
11597 SDValue N1 = N->getOperand(1);
11598 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
11599
11600 SmallVector<SDValue, 4> Ops;
11601 EVT ConcatVT = N0.getOperand(0).getValueType();
11602 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
11603 unsigned NumConcats = NumElts / NumElemsPerConcat;
11604
Mehdi Amini37f316a2015-01-17 01:35:56 +000011605 // Special case: shuffle(concat(A,B)) can be more efficiently represented
11606 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
11607 // half vector elements.
11608 if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
11609 std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
11610 SVN->getMask().end(), [](int i) { return i == -1; })) {
11611 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
11612 ArrayRef<int>(SVN->getMask().begin(), NumElemsPerConcat));
11613 N1 = DAG.getUNDEF(ConcatVT);
11614 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
11615 }
11616
Benjamin Kramerbbae9912013-04-09 17:41:43 +000011617 // Look at every vector that's inserted. We're looking for exact
11618 // subvector-sized copies from a concatenated vector
11619 for (unsigned I = 0; I != NumConcats; ++I) {
11620 // Make sure we're dealing with a copy.
11621 unsigned Begin = I * NumElemsPerConcat;
Hao Liubc601962013-05-13 02:07:05 +000011622 bool AllUndef = true, NoUndef = true;
11623 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
11624 if (SVN->getMaskElt(J) >= 0)
11625 AllUndef = false;
11626 else
11627 NoUndef = false;
Benjamin Kramerbbae9912013-04-09 17:41:43 +000011628 }
11629
Hao Liubc601962013-05-13 02:07:05 +000011630 if (NoUndef) {
Hao Liubc601962013-05-13 02:07:05 +000011631 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
11632 return SDValue();
11633
11634 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
11635 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
11636 return SDValue();
11637
11638 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
11639 if (FirstElt < N0.getNumOperands())
11640 Ops.push_back(N0.getOperand(FirstElt));
11641 else
11642 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
11643
11644 } else if (AllUndef) {
11645 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
11646 } else { // Mixed with general masks and undefs, can't do optimization.
11647 return SDValue();
11648 }
Benjamin Kramerbbae9912013-04-09 17:41:43 +000011649 }
11650
Craig Topper48d114b2014-04-26 18:35:24 +000011651 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
Benjamin Kramerbbae9912013-04-09 17:41:43 +000011652}
11653
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011654SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000011655 EVT VT = N->getValueType(0);
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011656 unsigned NumElts = VT.getVectorNumElements();
Chris Lattner39dcf1a2006-03-31 22:16:43 +000011657
Mon P Wang25f01062008-11-10 04:46:22 +000011658 SDValue N0 = N->getOperand(0);
Craig Topper279c77b2012-01-04 08:07:43 +000011659 SDValue N1 = N->getOperand(1);
Mon P Wang25f01062008-11-10 04:46:22 +000011660
Craig Topper5894fe42012-04-09 05:16:56 +000011661 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
Mon P Wang25f01062008-11-10 04:46:22 +000011662
Craig Topper279c77b2012-01-04 08:07:43 +000011663 // Canonicalize shuffle undef, undef -> undef
11664 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
11665 return DAG.getUNDEF(VT);
11666
11667 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
11668
11669 // Canonicalize shuffle v, v -> v, undef
11670 if (N0 == N1) {
11671 SmallVector<int, 8> NewMask;
11672 for (unsigned i = 0; i != NumElts; ++i) {
11673 int Idx = SVN->getMaskElt(i);
11674 if (Idx >= (int)NumElts) Idx -= NumElts;
11675 NewMask.push_back(Idx);
11676 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000011677 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
Craig Topper279c77b2012-01-04 08:07:43 +000011678 &NewMask[0]);
11679 }
11680
11681 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
11682 if (N0.getOpcode() == ISD::UNDEF) {
11683 SmallVector<int, 8> NewMask;
11684 for (unsigned i = 0; i != NumElts; ++i) {
11685 int Idx = SVN->getMaskElt(i);
Craig Toppere3ad4832012-04-09 05:55:33 +000011686 if (Idx >= 0) {
Craig Topper309dfef2013-08-08 07:38:55 +000011687 if (Idx >= (int)NumElts)
Craig Toppere3ad4832012-04-09 05:55:33 +000011688 Idx -= NumElts;
Craig Topper309dfef2013-08-08 07:38:55 +000011689 else
11690 Idx = -1; // remove reference to lhs
Craig Toppere3ad4832012-04-09 05:55:33 +000011691 }
11692 NewMask.push_back(Idx);
Craig Topper279c77b2012-01-04 08:07:43 +000011693 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000011694 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
Craig Topper279c77b2012-01-04 08:07:43 +000011695 &NewMask[0]);
11696 }
11697
11698 // Remove references to rhs if it is undef
11699 if (N1.getOpcode() == ISD::UNDEF) {
11700 bool Changed = false;
11701 SmallVector<int, 8> NewMask;
11702 for (unsigned i = 0; i != NumElts; ++i) {
11703 int Idx = SVN->getMaskElt(i);
11704 if (Idx >= (int)NumElts) {
11705 Idx = -1;
11706 Changed = true;
11707 }
11708 NewMask.push_back(Idx);
11709 }
11710 if (Changed)
Andrew Trickef9de2a2013-05-25 02:42:55 +000011711 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
Craig Topper279c77b2012-01-04 08:07:43 +000011712 }
Evan Cheng8472e0c2006-07-20 22:44:41 +000011713
Bob Wilsonf63da122010-10-28 17:06:14 +000011714 // If it is a splat, check if the argument vector is another splat or a
Michael Kuperstein25e34d12015-01-22 13:07:28 +000011715 // build_vector.
Bob Wilsonf63da122010-10-28 17:06:14 +000011716 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
Gabor Greiff304a7a2008-08-28 21:40:38 +000011717 SDNode *V = N0.getNode();
Evan Cheng7c970b92006-07-21 08:25:53 +000011718
Dan Gohmana8665142007-06-25 16:23:39 +000011719 // If this is a bit convert that changes the element type of the vector but
Evan Chengf3ae00a2006-10-16 22:49:37 +000011720 // not the number of vector elements, look through it. Be careful not to
11721 // look though conversions that change things like v4f32 to v2f64.
Wesley Peck527da1b2010-11-23 03:31:01 +000011722 if (V->getOpcode() == ISD::BITCAST) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011723 SDValue ConvInput = V->getOperand(0);
Evan Chengb8ff2232008-07-22 20:42:56 +000011724 if (ConvInput.getValueType().isVector() &&
11725 ConvInput.getValueType().getVectorNumElements() == NumElts)
Gabor Greiff304a7a2008-08-28 21:40:38 +000011726 V = ConvInput.getNode();
Evan Chengf3ae00a2006-10-16 22:49:37 +000011727 }
11728
Dan Gohmana8665142007-06-25 16:23:39 +000011729 if (V->getOpcode() == ISD::BUILD_VECTOR) {
Bob Wilsonf63da122010-10-28 17:06:14 +000011730 assert(V->getNumOperands() == NumElts &&
11731 "BUILD_VECTOR has wrong number of operands");
11732 SDValue Base;
11733 bool AllSame = true;
11734 for (unsigned i = 0; i != NumElts; ++i) {
11735 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
11736 Base = V->getOperand(i);
11737 break;
Evan Cheng7c970b92006-07-21 08:25:53 +000011738 }
Evan Cheng7c970b92006-07-21 08:25:53 +000011739 }
Bob Wilsonf63da122010-10-28 17:06:14 +000011740 // Splat of <u, u, u, u>, return <u, u, u, u>
11741 if (!Base.getNode())
11742 return N0;
11743 for (unsigned i = 0; i != NumElts; ++i) {
11744 if (V->getOperand(i) != Base) {
11745 AllSame = false;
11746 break;
11747 }
11748 }
11749 // Splat of <x, x, x, x>, return <x, x, x, x>
11750 if (AllSame)
11751 return N0;
Michael Kuperstein25e34d12015-01-22 13:07:28 +000011752
11753 // If the splatted element is a constant, just build the vector out of
11754 // constants directly.
11755 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
11756 if (isa<ConstantSDNode>(Splatted) || isa<ConstantFPSDNode>(Splatted)) {
11757 SmallVector<SDValue, 8> Ops;
11758 for (unsigned i = 0; i != NumElts; ++i) {
11759 Ops.push_back(Splatted);
11760 }
11761 SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
11762 V->getValueType(0), Ops);
11763
11764 // We may have jumped through bitcasts, so the type of the
11765 // BUILD_VECTOR may not match the type of the shuffle.
11766 if (V->getValueType(0) != VT)
11767 NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
11768 return NewBV;
11769 }
Evan Cheng7c970b92006-07-21 08:25:53 +000011770 }
11771 }
Nadav Rotemb0783502012-04-01 19:31:22 +000011772
Chandler Carruthdaa1ff92014-10-05 19:14:34 +000011773 // There are various patterns used to build up a vector from smaller vectors,
11774 // subvectors, or elements. Scan chains of these and replace unused insertions
11775 // or components with undef.
11776 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
11777 return S;
11778
Benjamin Kramerbbae9912013-04-09 17:41:43 +000011779 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11780 Level < AfterLegalizeVectorOps &&
11781 (N1.getOpcode() == ISD::UNDEF ||
11782 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
11783 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
11784 SDValue V = partitionShuffleOfConcats(N, DAG);
11785
11786 if (V.getNode())
11787 return V;
11788 }
11789
Andrea Di Biagio0fb20132014-07-21 07:30:54 +000011790 // Canonicalize shuffles according to rules:
11791 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
11792 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
11793 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000011794 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
Andrea Di Biagio0fb20132014-07-21 07:30:54 +000011795 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
11796 TLI.isTypeLegal(VT)) {
11797 // The incoming shuffle must be of the same type as the result of the
11798 // current shuffle.
11799 assert(N1->getOperand(0).getValueType() == VT &&
11800 "Shuffle types don't match");
11801
11802 SDValue SV0 = N1->getOperand(0);
11803 SDValue SV1 = N1->getOperand(1);
11804 bool HasSameOp0 = N0 == SV0;
11805 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
11806 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
11807 // Commute the operands of this shuffle so that next rule
11808 // will trigger.
11809 return DAG.getCommutedVectorShuffle(*SVN);
11810 }
11811
Andrea Di Biagio3960a952014-07-14 22:46:26 +000011812 // Try to fold according to rules:
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000011813 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
11814 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
11815 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
Andrea Di Biagio3960a952014-07-14 22:46:26 +000011816 // Don't try to fold shuffles with illegal type.
Chandler Carruth499d7332015-02-15 07:01:10 +000011817 // Only fold if this shuffle is the only user of the other shuffle.
11818 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
11819 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
Andrea Di Biagio3960a952014-07-14 22:46:26 +000011820 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
11821
11822 // The incoming shuffle must be of the same type as the result of the
11823 // current shuffle.
11824 assert(OtherSV->getOperand(0).getValueType() == VT &&
11825 "Shuffle types don't match");
11826
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000011827 SDValue SV0, SV1;
Andrea Di Biagio3960a952014-07-14 22:46:26 +000011828 SmallVector<int, 4> Mask;
11829 // Compute the combined shuffle mask for a shuffle with SV0 as the first
11830 // operand, and SV1 as the second operand.
11831 for (unsigned i = 0; i != NumElts; ++i) {
11832 int Idx = SVN->getMaskElt(i);
11833 if (Idx < 0) {
11834 // Propagate Undef.
11835 Mask.push_back(Idx);
11836 continue;
11837 }
11838
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000011839 SDValue CurrentVec;
Andrea Di Biagiobd5555c2014-07-15 13:26:28 +000011840 if (Idx < (int)NumElts) {
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000011841 // This shuffle index refers to the inner shuffle N0. Lookup the inner
11842 // shuffle mask to identify which vector is actually referenced.
Andrea Di Biagio3960a952014-07-14 22:46:26 +000011843 Idx = OtherSV->getMaskElt(Idx);
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000011844 if (Idx < 0) {
11845 // Propagate Undef.
11846 Mask.push_back(Idx);
11847 continue;
11848 }
Andrea Di Biagio3960a952014-07-14 22:46:26 +000011849
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000011850 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
11851 : OtherSV->getOperand(1);
11852 } else {
11853 // This shuffle index references an element within N1.
11854 CurrentVec = N1;
11855 }
11856
11857 // Simple case where 'CurrentVec' is UNDEF.
11858 if (CurrentVec.getOpcode() == ISD::UNDEF) {
11859 Mask.push_back(-1);
11860 continue;
11861 }
11862
11863 // Canonicalize the shuffle index. We don't know yet if CurrentVec
11864 // will be the first or second operand of the combined shuffle.
11865 Idx = Idx % NumElts;
11866 if (!SV0.getNode() || SV0 == CurrentVec) {
11867 // Ok. CurrentVec is the left hand side.
11868 // Update the mask accordingly.
11869 SV0 = CurrentVec;
11870 Mask.push_back(Idx);
11871 continue;
11872 }
11873
11874 // Bail out if we cannot convert the shuffle pair into a single shuffle.
11875 if (SV1.getNode() && SV1 != CurrentVec)
11876 return SDValue();
11877
11878 // Ok. CurrentVec is the right hand side.
11879 // Update the mask accordingly.
11880 SV1 = CurrentVec;
11881 Mask.push_back(Idx + NumElts);
Andrea Di Biagio3960a952014-07-14 22:46:26 +000011882 }
11883
Andrea Di Biagiob23bad12014-08-16 00:29:44 +000011884 // Check if all indices in Mask are Undef. In case, propagate Undef.
11885 bool isUndefMask = true;
11886 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
11887 isUndefMask &= Mask[i] < 0;
11888
11889 if (isUndefMask)
11890 return DAG.getUNDEF(VT);
11891
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000011892 if (!SV0.getNode())
11893 SV0 = DAG.getUNDEF(VT);
11894 if (!SV1.getNode())
11895 SV1 = DAG.getUNDEF(VT);
11896
Andrea Di Biagio3960a952014-07-14 22:46:26 +000011897 // Avoid introducing shuffles with illegal mask.
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000011898 if (!TLI.isShuffleMaskLegal(Mask, VT)) {
11899 // Compute the commuted shuffle mask and test again.
11900 for (unsigned i = 0; i != NumElts; ++i) {
11901 int idx = Mask[i];
11902 if (idx < 0)
11903 continue;
11904 else if (idx < (int)NumElts)
11905 Mask[i] = idx + NumElts;
11906 else
11907 Mask[i] = idx - NumElts;
11908 }
11909
11910 if (!TLI.isShuffleMaskLegal(Mask, VT))
11911 return SDValue();
11912
11913 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
11914 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
11915 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
11916 std::swap(SV0, SV1);
Andrea Di Biagiobd5555c2014-07-15 13:26:28 +000011917 }
Andrea Di Biagioe13a0b82014-11-15 22:56:25 +000011918
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000011919 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
11920 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
11921 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
11922 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
Andrea Di Biagio3960a952014-07-14 22:46:26 +000011923 }
11924
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011925 return SDValue();
Chris Lattner39dcf1a2006-03-31 22:16:43 +000011926}
11927
Manman Ren413a6cb2014-01-31 01:10:35 +000011928SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
11929 SDValue N0 = N->getOperand(0);
11930 SDValue N2 = N->getOperand(2);
11931
11932 // If the input vector is a concatenation, and the insert replaces
11933 // one of the halves, we can optimize into a single concat_vectors.
11934 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11935 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
11936 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
11937 EVT VT = N->getValueType(0);
11938
11939 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11940 // (concat_vectors Z, Y)
11941 if (InsIdx == 0)
11942 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11943 N->getOperand(1), N0.getOperand(1));
11944
11945 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11946 // (concat_vectors X, Z)
11947 if (InsIdx == VT.getVectorNumElements()/2)
11948 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11949 N0.getOperand(0), N->getOperand(1));
11950 }
11951
11952 return SDValue();
11953}
11954
Sanjay Patel50cbfc52014-08-28 16:29:51 +000011955/// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
11956/// with the destination vector and a zero vector.
Dan Gohmana8665142007-06-25 16:23:39 +000011957/// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
Evan Chenga320abc2006-04-20 08:56:16 +000011958/// vector_shuffle V, Zero, <0, 4, 2, 4>
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011959SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000011960 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +000011961 SDLoc dl(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011962 SDValue LHS = N->getOperand(0);
11963 SDValue RHS = N->getOperand(1);
Dan Gohmana8665142007-06-25 16:23:39 +000011964 if (N->getOpcode() == ISD::AND) {
Wesley Peck527da1b2010-11-23 03:31:01 +000011965 if (RHS.getOpcode() == ISD::BITCAST)
Evan Chenga320abc2006-04-20 08:56:16 +000011966 RHS = RHS.getOperand(0);
Dan Gohmana8665142007-06-25 16:23:39 +000011967 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011968 SmallVector<int, 8> Indices;
11969 unsigned NumElts = RHS.getNumOperands();
Evan Chenga320abc2006-04-20 08:56:16 +000011970 for (unsigned i = 0; i != NumElts; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011971 SDValue Elt = RHS.getOperand(i);
Evan Chenga320abc2006-04-20 08:56:16 +000011972 if (!isa<ConstantSDNode>(Elt))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011973 return SDValue();
Craig Toppere5893f62012-04-09 05:59:53 +000011974
11975 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011976 Indices.push_back(i);
Evan Chenga320abc2006-04-20 08:56:16 +000011977 else if (cast<ConstantSDNode>(Elt)->isNullValue())
Andrea Di Biagioce46b972014-11-05 13:04:14 +000011978 Indices.push_back(NumElts+i);
Evan Chenga320abc2006-04-20 08:56:16 +000011979 else
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011980 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000011981 }
11982
11983 // Let's see if the target supports this vector_shuffle.
Owen Anderson53aa7a92009-08-10 22:56:29 +000011984 EVT RVT = RHS.getValueType();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011985 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011986 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000011987
Dan Gohmana8665142007-06-25 16:23:39 +000011988 // Return the new VECTOR_SHUFFLE node.
Dan Gohman08c0a952009-09-23 21:02:20 +000011989 EVT EltVT = RVT.getVectorElementType();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011990 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
Dan Gohman08c0a952009-09-23 21:02:20 +000011991 DAG.getConstant(0, EltVT));
Craig Topper48d114b2014-04-26 18:35:24 +000011992 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
Wesley Peck527da1b2010-11-23 03:31:01 +000011993 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011994 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
Wesley Peck527da1b2010-11-23 03:31:01 +000011995 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
Evan Chenga320abc2006-04-20 08:56:16 +000011996 }
11997 }
Bill Wendling31b50992009-01-30 23:59:18 +000011998
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011999 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000012000}
12001
Sanjay Patel50cbfc52014-08-28 16:29:51 +000012002/// Visit a binary vector operation, like ADD.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012003SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
Bob Wilson54081442010-12-17 23:06:49 +000012004 assert(N->getValueType(0).isVector() &&
12005 "SimplifyVBinOp only works on vectors!");
Dan Gohmana8665142007-06-25 16:23:39 +000012006
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012007 SDValue LHS = N->getOperand(0);
12008 SDValue RHS = N->getOperand(1);
12009 SDValue Shuffle = XformToShuffleWithZero(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +000012010 if (Shuffle.getNode()) return Shuffle;
Evan Chenga320abc2006-04-20 08:56:16 +000012011
Dan Gohmana8665142007-06-25 16:23:39 +000012012 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
Chris Lattner0442a182006-04-02 03:25:57 +000012013 // this operation.
Scott Michelcf0da6c2009-02-17 22:15:04 +000012014 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
Dan Gohmana8665142007-06-25 16:23:39 +000012015 RHS.getOpcode() == ISD::BUILD_VECTOR) {
Juergen Ributzka73844052014-01-13 20:51:35 +000012016 // Check if both vectors are constants. If not bail out.
Andrea Di Biagiod7c03ec2014-01-15 19:51:32 +000012017 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
12018 cast<BuildVectorSDNode>(RHS)->isConstant()))
Juergen Ributzka73844052014-01-13 20:51:35 +000012019 return SDValue();
12020
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012021 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +000012022 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012023 SDValue LHSOp = LHS.getOperand(i);
12024 SDValue RHSOp = RHS.getOperand(i);
Bill Wendling31b50992009-01-30 23:59:18 +000012025
Evan Cheng64d28462006-05-31 06:08:35 +000012026 // Can't fold divide by zero.
Dan Gohmana8665142007-06-25 16:23:39 +000012027 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
12028 N->getOpcode() == ISD::FDIV) {
Evan Cheng64d28462006-05-31 06:08:35 +000012029 if ((RHSOp.getOpcode() == ISD::Constant &&
Gabor Greiff304a7a2008-08-28 21:40:38 +000012030 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
Evan Cheng64d28462006-05-31 06:08:35 +000012031 (RHSOp.getOpcode() == ISD::ConstantFP &&
Gabor Greiff304a7a2008-08-28 21:40:38 +000012032 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
Evan Cheng64d28462006-05-31 06:08:35 +000012033 break;
12034 }
Bill Wendling31b50992009-01-30 23:59:18 +000012035
Bob Wilson54081442010-12-17 23:06:49 +000012036 EVT VT = LHSOp.getValueType();
Bob Wilson68156192011-10-18 17:34:47 +000012037 EVT RVT = RHSOp.getValueType();
12038 if (RVT != VT) {
12039 // Integer BUILD_VECTOR operands may have types larger than the element
12040 // size (e.g., when the element type is not legal). Prior to type
12041 // legalization, the types may not match between the two BUILD_VECTORS.
12042 // Truncate one of the operands to make them match.
12043 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000012044 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
Bob Wilson68156192011-10-18 17:34:47 +000012045 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +000012046 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
Bob Wilson68156192011-10-18 17:34:47 +000012047 VT = RVT;
12048 }
12049 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000012050 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
Evan Cheng48f0de92010-05-18 00:03:40 +000012051 LHSOp, RHSOp);
12052 if (FoldOp.getOpcode() != ISD::UNDEF &&
12053 FoldOp.getOpcode() != ISD::Constant &&
12054 FoldOp.getOpcode() != ISD::ConstantFP)
12055 break;
12056 Ops.push_back(FoldOp);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000012057 AddToWorklist(FoldOp.getNode());
Chris Lattner0442a182006-04-02 03:25:57 +000012058 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000012059
Bob Wilson54081442010-12-17 23:06:49 +000012060 if (Ops.size() == LHS.getNumOperands())
Craig Topper48d114b2014-04-26 18:35:24 +000012061 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
Chris Lattner0442a182006-04-02 03:25:57 +000012062 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000012063
Andrea Di Biagio446a5272014-05-30 23:17:53 +000012064 // Type legalization might introduce new shuffles in the DAG.
12065 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
12066 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
12067 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
12068 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
12069 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
12070 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
12071 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
12072 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
12073
12074 if (SVN0->getMask().equals(SVN1->getMask())) {
12075 EVT VT = N->getValueType(0);
12076 SDValue UndefVector = LHS.getOperand(1);
12077 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
12078 LHS.getOperand(0), RHS.getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +000012079 AddUsersToWorklist(N);
Andrea Di Biagio446a5272014-05-30 23:17:53 +000012080 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
12081 &SVN0->getMask()[0]);
12082 }
12083 }
12084
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012085 return SDValue();
Chris Lattner0442a182006-04-02 03:25:57 +000012086}
12087
Sanjay Patel50cbfc52014-08-28 16:29:51 +000012088/// Visit a binary vector operation, like FABS/FNEG.
Craig Topper82384612012-09-11 01:45:21 +000012089SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
Craig Topper82384612012-09-11 01:45:21 +000012090 assert(N->getValueType(0).isVector() &&
12091 "SimplifyVUnaryOp only works on vectors!");
12092
12093 SDValue N0 = N->getOperand(0);
12094
12095 if (N0.getOpcode() != ISD::BUILD_VECTOR)
12096 return SDValue();
12097
12098 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
12099 SmallVector<SDValue, 8> Ops;
12100 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
12101 SDValue Op = N0.getOperand(i);
12102 if (Op.getOpcode() != ISD::UNDEF &&
12103 Op.getOpcode() != ISD::ConstantFP)
12104 break;
12105 EVT EltVT = Op.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +000012106 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
Craig Topper82384612012-09-11 01:45:21 +000012107 if (FoldOp.getOpcode() != ISD::UNDEF &&
12108 FoldOp.getOpcode() != ISD::ConstantFP)
12109 break;
12110 Ops.push_back(FoldOp);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000012111 AddToWorklist(FoldOp.getNode());
Craig Topper82384612012-09-11 01:45:21 +000012112 }
12113
12114 if (Ops.size() != N0.getNumOperands())
12115 return SDValue();
12116
Craig Topper48d114b2014-04-26 18:35:24 +000012117 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
Craig Topper82384612012-09-11 01:45:21 +000012118}
12119
Andrew Trickef9de2a2013-05-25 02:42:55 +000012120SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
Bill Wendling31b50992009-01-30 23:59:18 +000012121 SDValue N1, SDValue N2){
Nate Begeman2042aa52005-10-08 00:29:44 +000012122 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
Scott Michelcf0da6c2009-02-17 22:15:04 +000012123
Bill Wendling31b50992009-01-30 23:59:18 +000012124 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
Nate Begeman2042aa52005-10-08 00:29:44 +000012125 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Bill Wendling31b50992009-01-30 23:59:18 +000012126
Nate Begeman2042aa52005-10-08 00:29:44 +000012127 // If we got a simplified select_cc node back from SimplifySelectCC, then
12128 // break it down into a new SETCC node, and a new SELECT node, and then return
12129 // the SELECT node, since we were called with a SELECT node.
Gabor Greiff304a7a2008-08-28 21:40:38 +000012130 if (SCC.getNode()) {
Nate Begeman2042aa52005-10-08 00:29:44 +000012131 // Check to see if we got a select_cc back (to turn into setcc/select).
12132 // Otherwise, just return whatever node we got back, like fabs.
12133 if (SCC.getOpcode() == ISD::SELECT_CC) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000012134 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000012135 N0.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +000012136 SCC.getOperand(0), SCC.getOperand(1),
Bill Wendling31b50992009-01-30 23:59:18 +000012137 SCC.getOperand(4));
Chandler Carruth3c0012b2014-07-21 08:56:44 +000012138 AddToWorklist(SETCC.getNode());
Chandler Carruth40dbd382014-08-04 21:29:59 +000012139 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
12140 SCC.getOperand(2), SCC.getOperand(3));
Nate Begeman2042aa52005-10-08 00:29:44 +000012141 }
Bill Wendling31b50992009-01-30 23:59:18 +000012142
Nate Begeman2042aa52005-10-08 00:29:44 +000012143 return SCC;
12144 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012145 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +000012146}
12147
Sanjay Patel50cbfc52014-08-28 16:29:51 +000012148/// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
12149/// being selected between, see if we can simplify the select. Callers of this
12150/// should assume that TheSelect is deleted if this returns true. As such, they
12151/// should return the appropriate thing (e.g. the node) back to the top-level of
12152/// the DAG combiner loop to avoid it being looked at.
Scott Michelcf0da6c2009-02-17 22:15:04 +000012153bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012154 SDValue RHS) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000012155
Nadav Rotema49a02a2011-02-11 19:57:47 +000012156 // Cannot simplify select with vector condition
12157 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
12158
Chris Lattner6c14c352005-10-18 06:04:22 +000012159 // If this is a select from two identical things, try to pull the operation
12160 // through the select.
Chris Lattner254c4452010-09-21 15:46:59 +000012161 if (LHS.getOpcode() != RHS.getOpcode() ||
12162 !LHS.hasOneUse() || !RHS.hasOneUse())
12163 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000012164
Chris Lattner254c4452010-09-21 15:46:59 +000012165 // If this is a load and the token chain is identical, replace the select
12166 // of two loads with a load through a select of the address to load from.
12167 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
12168 // constants have been dropped into the constant pool.
12169 if (LHS.getOpcode() == ISD::LOAD) {
12170 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
12171 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
Wesley Peck527da1b2010-11-23 03:31:01 +000012172
Chris Lattner254c4452010-09-21 15:46:59 +000012173 // Token chains must be identical.
12174 if (LHS.getOperand(0) != RHS.getOperand(0) ||
Duncan Sands8651e9c2008-06-13 19:07:40 +000012175 // Do not let this transformation reduce the number of volatile loads.
Chris Lattner254c4452010-09-21 15:46:59 +000012176 LLD->isVolatile() || RLD->isVolatile() ||
12177 // If this is an EXTLOAD, the VT's must match.
12178 LLD->getMemoryVT() != RLD->getMemoryVT() ||
Duncan Sands12f3b3b2010-11-18 20:05:18 +000012179 // If this is an EXTLOAD, the kind of extension must match.
12180 (LLD->getExtensionType() != RLD->getExtensionType() &&
12181 // The only exception is if one of the extensions is anyext.
12182 LLD->getExtensionType() != ISD::EXTLOAD &&
12183 RLD->getExtensionType() != ISD::EXTLOAD) ||
Dan Gohmanba8735d2009-10-31 14:14:04 +000012184 // FIXME: this discards src value information. This is
12185 // over-conservative. It would be beneficial to be able to remember
Mon P Wangec57c812010-01-11 20:12:49 +000012186 // both potential memory locations. Since we are discarding
12187 // src value info, don't do the transformation if the memory
12188 // locations are not in the default address space.
Chris Lattner254c4452010-09-21 15:46:59 +000012189 LLD->getPointerInfo().getAddrSpace() != 0 ||
Pete Cooper10a3ae72013-02-12 03:14:50 +000012190 RLD->getPointerInfo().getAddrSpace() != 0 ||
12191 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
12192 LLD->getBasePtr().getValueType()))
Chris Lattner254c4452010-09-21 15:46:59 +000012193 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000012194
Chris Lattnere3267522010-09-21 15:58:55 +000012195 // Check that the select condition doesn't reach either load. If so,
12196 // folding this will induce a cycle into the DAG. If not, this is safe to
12197 // xform, so create a select of the addresses.
Chris Lattner254c4452010-09-21 15:46:59 +000012198 SDValue Addr;
12199 if (TheSelect->getOpcode() == ISD::SELECT) {
Chris Lattnere3267522010-09-21 15:58:55 +000012200 SDNode *CondNode = TheSelect->getOperand(0).getNode();
12201 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
12202 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
12203 return false;
Nadav Rotemd5f88592012-10-18 18:06:48 +000012204 // The loads must not depend on one another.
12205 if (LLD->isPredecessorOf(RLD) ||
12206 RLD->isPredecessorOf(LLD))
12207 return false;
Matt Arsenaultd2f03322013-06-14 22:04:37 +000012208 Addr = DAG.getSelect(SDLoc(TheSelect),
12209 LLD->getBasePtr().getValueType(),
12210 TheSelect->getOperand(0), LLD->getBasePtr(),
12211 RLD->getBasePtr());
Chris Lattner254c4452010-09-21 15:46:59 +000012212 } else { // Otherwise SELECT_CC
Chris Lattnere3267522010-09-21 15:58:55 +000012213 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
12214 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
12215
12216 if ((LLD->hasAnyUseOfValue(1) &&
12217 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
Chris Lattner1cc25e82012-03-27 16:27:21 +000012218 (RLD->hasAnyUseOfValue(1) &&
12219 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
Chris Lattnere3267522010-09-21 15:58:55 +000012220 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000012221
Andrew Trickef9de2a2013-05-25 02:42:55 +000012222 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
Chris Lattnere3267522010-09-21 15:58:55 +000012223 LLD->getBasePtr().getValueType(),
12224 TheSelect->getOperand(0),
12225 TheSelect->getOperand(1),
12226 LLD->getBasePtr(), RLD->getBasePtr(),
12227 TheSelect->getOperand(4));
Chris Lattner254c4452010-09-21 15:46:59 +000012228 }
12229
Chris Lattnere3267522010-09-21 15:58:55 +000012230 SDValue Load;
Louis Gerbarg4fc09b32014-07-30 18:24:41 +000012231 // It is safe to replace the two loads if they have different alignments,
12232 // but the new load must be the minimum (most restrictive) alignment of the
12233 // inputs.
Louis Gerbarge8f9c782014-10-30 22:21:03 +000012234 bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
Louis Gerbarg09b8cde2014-07-31 22:57:46 +000012235 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
Chris Lattnere3267522010-09-21 15:58:55 +000012236 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
12237 Load = DAG.getLoad(TheSelect->getValueType(0),
Andrew Trickef9de2a2013-05-25 02:42:55 +000012238 SDLoc(TheSelect),
Hal Finkelcc39b672014-07-24 12:16:19 +000012239 // FIXME: Discards pointer and AA info.
Chris Lattnere3267522010-09-21 15:58:55 +000012240 LLD->getChain(), Addr, MachinePointerInfo(),
12241 LLD->isVolatile(), LLD->isNonTemporal(),
Louis Gerbarg67474e32014-07-31 21:45:05 +000012242 isInvariant, Alignment);
Chris Lattnere3267522010-09-21 15:58:55 +000012243 } else {
Duncan Sandsc92331b2010-11-18 21:16:28 +000012244 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
12245 RLD->getExtensionType() : LLD->getExtensionType(),
Andrew Trickef9de2a2013-05-25 02:42:55 +000012246 SDLoc(TheSelect),
Stuart Hastings81c43062011-02-16 16:23:55 +000012247 TheSelect->getValueType(0),
Hal Finkelcc39b672014-07-24 12:16:19 +000012248 // FIXME: Discards pointer and AA info.
Chris Lattnere3267522010-09-21 15:58:55 +000012249 LLD->getChain(), Addr, MachinePointerInfo(),
12250 LLD->getMemoryVT(), LLD->isVolatile(),
Louis Gerbarg67474e32014-07-31 21:45:05 +000012251 LLD->isNonTemporal(), isInvariant, Alignment);
Chris Lattner6c14c352005-10-18 06:04:22 +000012252 }
Chris Lattnere3267522010-09-21 15:58:55 +000012253
12254 // Users of the select now use the result of the load.
12255 CombineTo(TheSelect, Load);
12256
12257 // Users of the old loads now use the new load's chain. We know the
12258 // old-load value is dead now.
12259 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
12260 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
12261 return true;
Chris Lattner6c14c352005-10-18 06:04:22 +000012262 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000012263
Chris Lattner6c14c352005-10-18 06:04:22 +000012264 return false;
12265}
12266
Sanjay Patel50cbfc52014-08-28 16:29:51 +000012267/// Simplify an expression of the form (N0 cond N1) ? N2 : N3
Chris Lattner43d63772009-03-11 05:08:08 +000012268/// where 'cond' is the comparison specified by CC.
Andrew Trickef9de2a2013-05-25 02:42:55 +000012269SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012270 SDValue N2, SDValue N3,
12271 ISD::CondCode CC, bool NotExtCompare) {
Chris Lattner43d63772009-03-11 05:08:08 +000012272 // (x ? y : y) -> y.
12273 if (N2 == N3) return N2;
Wesley Peck527da1b2010-11-23 03:31:01 +000012274
Owen Anderson53aa7a92009-08-10 22:56:29 +000012275 EVT VT = N2.getValueType();
Gabor Greiff304a7a2008-08-28 21:40:38 +000012276 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
12277 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
12278 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000012279
12280 // Determine if the condition we're dealing with is constant
Matt Arsenault758659232013-05-18 00:21:46 +000012281 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
Dale Johannesenf1163e92009-02-03 00:47:48 +000012282 N0, N1, CC, DL, false);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000012283 if (SCC.getNode()) AddToWorklist(SCC.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +000012284 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000012285
12286 // fold select_cc true, x, y -> x
Dan Gohmanb72127a2008-03-13 22:13:53 +000012287 if (SCCC && !SCCC->isNullValue())
Nate Begeman2042aa52005-10-08 00:29:44 +000012288 return N2;
12289 // fold select_cc false, x, y -> y
Dan Gohmanb72127a2008-03-13 22:13:53 +000012290 if (SCCC && SCCC->isNullValue())
Nate Begeman2042aa52005-10-08 00:29:44 +000012291 return N3;
Scott Michelcf0da6c2009-02-17 22:15:04 +000012292
Nate Begeman2042aa52005-10-08 00:29:44 +000012293 // Check to see if we can simplify the select into an fabs node
12294 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
12295 // Allow either -0.0 or 0.0
Dale Johannesen2cfcf702007-08-25 22:10:57 +000012296 if (CFP->getValueAPF().isZero()) {
Nate Begeman2042aa52005-10-08 00:29:44 +000012297 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
12298 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
12299 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
12300 N2 == N3.getOperand(0))
Bill Wendling31b50992009-01-30 23:59:18 +000012301 return DAG.getNode(ISD::FABS, DL, VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +000012302
Nate Begeman2042aa52005-10-08 00:29:44 +000012303 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
12304 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
12305 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
12306 N2.getOperand(0) == N3)
Bill Wendling31b50992009-01-30 23:59:18 +000012307 return DAG.getNode(ISD::FABS, DL, VT, N3);
Nate Begeman2042aa52005-10-08 00:29:44 +000012308 }
12309 }
Wesley Peck527da1b2010-11-23 03:31:01 +000012310
Chris Lattner43d63772009-03-11 05:08:08 +000012311 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
12312 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
12313 // in it. This is a win when the constant is not otherwise available because
12314 // it replaces two constant pool loads with one. We only do this if the FP
12315 // type is known to be legal, because if it isn't, then we are before legalize
12316 // types an we want the other legalization to happen first (e.g. to avoid
Mon P Wangc8671562009-03-14 00:25:19 +000012317 // messing with soft float) and if the ConstantFP is not legal, because if
12318 // it is legal, we may not need to store the FP constant in a constant pool.
Chris Lattner43d63772009-03-11 05:08:08 +000012319 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
12320 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
12321 if (TLI.isTypeLegal(N2.getValueType()) &&
Mon P Wangc8671562009-03-14 00:25:19 +000012322 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
Tim Northover863a7892014-04-16 09:03:09 +000012323 TargetLowering::Legal &&
12324 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
12325 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
Chris Lattner43d63772009-03-11 05:08:08 +000012326 // If both constants have multiple uses, then we won't need to do an
12327 // extra load, they are likely around in registers for other users.
12328 (TV->hasOneUse() || FV->hasOneUse())) {
12329 Constant *Elts[] = {
12330 const_cast<ConstantFP*>(FV->getConstantFPValue()),
12331 const_cast<ConstantFP*>(TV->getConstantFPValue())
12332 };
Chris Lattner229907c2011-07-18 04:54:35 +000012333 Type *FPTy = Elts[0]->getType();
Micah Villmowcdfe20b2012-10-08 16:38:25 +000012334 const DataLayout &TD = *TLI.getDataLayout();
Wesley Peck527da1b2010-11-23 03:31:01 +000012335
Chris Lattner43d63772009-03-11 05:08:08 +000012336 // Create a ConstantArray of the two constants.
Jay Foad83be3612011-06-22 09:24:39 +000012337 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
Chris Lattner43d63772009-03-11 05:08:08 +000012338 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
12339 TD.getPrefTypeAlignment(FPTy));
Evan Cheng1fb8aed2009-03-13 07:51:59 +000012340 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
Chris Lattner43d63772009-03-11 05:08:08 +000012341
12342 // Get the offsets to the 0 and 1 element of the array so that we can
12343 // select between them.
12344 SDValue Zero = DAG.getIntPtrConstant(0);
Duncan Sandsaf9eaa82009-05-09 07:06:46 +000012345 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
Chris Lattner43d63772009-03-11 05:08:08 +000012346 SDValue One = DAG.getIntPtrConstant(EltSize);
Wesley Peck527da1b2010-11-23 03:31:01 +000012347
Chris Lattner43d63772009-03-11 05:08:08 +000012348 SDValue Cond = DAG.getSetCC(DL,
Matt Arsenault758659232013-05-18 00:21:46 +000012349 getSetCCResultType(N0.getValueType()),
Chris Lattner43d63772009-03-11 05:08:08 +000012350 N0, N1, CC);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000012351 AddToWorklist(Cond.getNode());
Matt Arsenaultd2f03322013-06-14 22:04:37 +000012352 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
12353 Cond, One, Zero);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000012354 AddToWorklist(CstOffset.getNode());
Tom Stellard838e2342013-08-26 15:06:10 +000012355 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
Chris Lattner43d63772009-03-11 05:08:08 +000012356 CstOffset);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000012357 AddToWorklist(CPIdx.getNode());
Chris Lattner43d63772009-03-11 05:08:08 +000012358 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
Chris Lattnera35499e2010-09-21 07:32:19 +000012359 MachinePointerInfo::getConstantPool(), false,
Pete Cooper82cd9e82011-11-08 18:42:53 +000012360 false, false, Alignment);
Chris Lattner43d63772009-03-11 05:08:08 +000012361
12362 }
Wesley Peck527da1b2010-11-23 03:31:01 +000012363 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000012364
Nate Begeman2042aa52005-10-08 00:29:44 +000012365 // Check to see if we can perform the "gzip trick", transforming
Bill Wendling31b50992009-01-30 23:59:18 +000012366 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
Chris Lattnerc8cd62d2006-09-20 06:41:35 +000012367 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
Dan Gohmanb72127a2008-03-13 22:13:53 +000012368 (N1C->isNullValue() || // (a < 0) ? b : 0
12369 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
Owen Anderson53aa7a92009-08-10 22:56:29 +000012370 EVT XType = N0.getValueType();
12371 EVT AType = N2.getValueType();
Duncan Sands11dd4242008-06-08 20:54:56 +000012372 if (XType.bitsGE(AType)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +000012373 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
Nate Begeman6828ed92005-10-10 21:26:48 +000012374 // single-bit constant.
Dan Gohmanb72127a2008-03-13 22:13:53 +000012375 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
12376 unsigned ShCtV = N2C->getAPIntValue().logBase2();
Duncan Sands13237ac2008-06-06 12:08:01 +000012377 ShCtV = XType.getSizeInBits()-ShCtV-1;
Owen Andersonb2c80da2011-02-25 21:41:48 +000012378 SDValue ShCt = DAG.getConstant(ShCtV,
12379 getShiftAmountTy(N0.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000012380 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000012381 XType, N0, ShCt);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000012382 AddToWorklist(Shift.getNode());
Bill Wendling31b50992009-01-30 23:59:18 +000012383
Duncan Sands11dd4242008-06-08 20:54:56 +000012384 if (XType.bitsGT(AType)) {
Bill Wendling3b585af2009-01-31 03:12:48 +000012385 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000012386 AddToWorklist(Shift.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000012387 }
Bill Wendling31b50992009-01-30 23:59:18 +000012388
12389 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
Nate Begeman2042aa52005-10-08 00:29:44 +000012390 }
Bill Wendling31b50992009-01-30 23:59:18 +000012391
Andrew Trickef9de2a2013-05-25 02:42:55 +000012392 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000012393 XType, N0,
12394 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000012395 getShiftAmountTy(N0.getValueType())));
Chandler Carruth3c0012b2014-07-21 08:56:44 +000012396 AddToWorklist(Shift.getNode());
Bill Wendling31b50992009-01-30 23:59:18 +000012397
Duncan Sands11dd4242008-06-08 20:54:56 +000012398 if (XType.bitsGT(AType)) {
Bill Wendling3b585af2009-01-31 03:12:48 +000012399 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000012400 AddToWorklist(Shift.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000012401 }
Bill Wendling31b50992009-01-30 23:59:18 +000012402
12403 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
Nate Begeman2042aa52005-10-08 00:29:44 +000012404 }
12405 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000012406
Owen Anderson3231d132010-09-22 22:58:22 +000012407 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
12408 // where y is has a single bit set.
12409 // A plaintext description would be, we can turn the SELECT_CC into an AND
12410 // when the condition can be materialized as an all-ones register. Any
12411 // single bit-test can be materialized as an all-ones register with
12412 // shift-left and shift-right-arith.
12413 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
12414 N0->getValueType(0) == VT &&
Wesley Peck527da1b2010-11-23 03:31:01 +000012415 N1C && N1C->isNullValue() &&
Owen Anderson3231d132010-09-22 22:58:22 +000012416 N2C && N2C->isNullValue()) {
12417 SDValue AndLHS = N0->getOperand(0);
12418 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
12419 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
12420 // Shift the tested bit over the sign bit.
12421 APInt AndMask = ConstAndRHS->getAPIntValue();
12422 SDValue ShlAmt =
Owen Andersonb2c80da2011-02-25 21:41:48 +000012423 DAG.getConstant(AndMask.countLeadingZeros(),
12424 getShiftAmountTy(AndLHS.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000012425 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
Wesley Peck527da1b2010-11-23 03:31:01 +000012426
Owen Anderson3231d132010-09-22 22:58:22 +000012427 // Now arithmetic right shift it all the way over, so the result is either
12428 // all-ones, or zero.
12429 SDValue ShrAmt =
Owen Andersonb2c80da2011-02-25 21:41:48 +000012430 DAG.getConstant(AndMask.getBitWidth()-1,
12431 getShiftAmountTy(Shl.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000012432 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
Wesley Peck527da1b2010-11-23 03:31:01 +000012433
Owen Anderson3231d132010-09-22 22:58:22 +000012434 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
12435 }
12436 }
12437
Nate Begeman6828ed92005-10-10 21:26:48 +000012438 // fold select C, 16, 0 -> shl C, 4
Dan Gohmanb72127a2008-03-13 22:13:53 +000012439 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
Daniel Sanderscbd44c52014-07-10 10:18:12 +000012440 TLI.getBooleanContents(N0.getValueType()) ==
12441 TargetLowering::ZeroOrOneBooleanContent) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000012442
Chris Lattnera083ffc2007-04-11 06:50:51 +000012443 // If the caller doesn't want us to simplify this into a zext of a compare,
12444 // don't do it.
Dan Gohmanb72127a2008-03-13 22:13:53 +000012445 if (NotExtCompare && N2C->getAPIntValue() == 1)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012446 return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +000012447
Nate Begeman6828ed92005-10-10 21:26:48 +000012448 // Get a SetCC of the condition
Owen Anderson15fd6ac2012-11-03 00:17:26 +000012449 // NOTE: Don't create a SETCC if it's not legal on this target.
12450 if (!LegalOperations ||
12451 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault758659232013-05-18 00:21:46 +000012452 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
Owen Anderson15fd6ac2012-11-03 00:17:26 +000012453 SDValue Temp, SCC;
12454 // cast from setcc result type to select result type
12455 if (LegalTypes) {
Matt Arsenault758659232013-05-18 00:21:46 +000012456 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000012457 N0, N1, CC);
12458 if (N2.getValueType().bitsLT(SCC.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +000012459 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000012460 N2.getValueType());
12461 else
Andrew Trickef9de2a2013-05-25 02:42:55 +000012462 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000012463 N2.getValueType(), SCC);
12464 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +000012465 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
12466 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
Bill Wendling31b50992009-01-30 23:59:18 +000012467 N2.getValueType(), SCC);
Owen Anderson15fd6ac2012-11-03 00:17:26 +000012468 }
12469
Chandler Carruth3c0012b2014-07-21 08:56:44 +000012470 AddToWorklist(SCC.getNode());
12471 AddToWorklist(Temp.getNode());
Owen Anderson15fd6ac2012-11-03 00:17:26 +000012472
12473 if (N2C->getAPIntValue() == 1)
12474 return Temp;
12475
12476 // shl setcc result by log2 n2c
Jack Carterd4e96152013-10-17 01:34:33 +000012477 return DAG.getNode(
12478 ISD::SHL, DL, N2.getValueType(), Temp,
12479 DAG.getConstant(N2C->getAPIntValue().logBase2(),
12480 getShiftAmountTy(Temp.getValueType())));
Nate Begemanabac6162006-02-18 02:40:58 +000012481 }
Nate Begeman6828ed92005-10-10 21:26:48 +000012482 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000012483
Nate Begeman2042aa52005-10-08 00:29:44 +000012484 // Check to see if this is the equivalent of setcc
12485 // FIXME: Turn all of these into setcc if setcc if setcc is legal
12486 // otherwise, go ahead with the folds.
Dan Gohmanb72127a2008-03-13 22:13:53 +000012487 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000012488 EVT XType = N0.getValueType();
Duncan Sandsdc2dac12008-11-24 14:53:14 +000012489 if (!LegalOperations ||
Matt Arsenault758659232013-05-18 00:21:46 +000012490 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
12491 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
Nate Begeman2042aa52005-10-08 00:29:44 +000012492 if (Res.getValueType() != VT)
Bill Wendling31b50992009-01-30 23:59:18 +000012493 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
Nate Begeman2042aa52005-10-08 00:29:44 +000012494 return Res;
12495 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000012496
Bill Wendling31b50992009-01-30 23:59:18 +000012497 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
Scott Michelcf0da6c2009-02-17 22:15:04 +000012498 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +000012499 (!LegalOperations ||
Duncan Sandsb1bfff52008-06-14 17:48:34 +000012500 TLI.isOperationLegal(ISD::CTLZ, XType))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000012501 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +000012502 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
Duncan Sands13237ac2008-06-06 12:08:01 +000012503 DAG.getConstant(Log2_32(XType.getSizeInBits()),
Owen Andersonb2c80da2011-02-25 21:41:48 +000012504 getShiftAmountTy(Ctlz.getValueType())));
Nate Begeman2042aa52005-10-08 00:29:44 +000012505 }
Bill Wendling31b50992009-01-30 23:59:18 +000012506 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
Scott Michelcf0da6c2009-02-17 22:15:04 +000012507 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000012508 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000012509 XType, DAG.getConstant(0, XType), N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +000012510 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
Bill Wendling31b50992009-01-30 23:59:18 +000012511 return DAG.getNode(ISD::SRL, DL, XType,
Bill Wendlinga6c75ff2009-02-01 11:19:36 +000012512 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
Duncan Sands13237ac2008-06-06 12:08:01 +000012513 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000012514 getShiftAmountTy(XType)));
Nate Begeman2042aa52005-10-08 00:29:44 +000012515 }
Bill Wendling31b50992009-01-30 23:59:18 +000012516 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
Nate Begeman2042aa52005-10-08 00:29:44 +000012517 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000012518 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
Bill Wendling31b50992009-01-30 23:59:18 +000012519 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000012520 getShiftAmountTy(N0.getValueType())));
Bill Wendling31b50992009-01-30 23:59:18 +000012521 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
Nate Begeman2042aa52005-10-08 00:29:44 +000012522 }
12523 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000012524
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000012525 // Check to see if this is an integer abs.
12526 // select_cc setg[te] X, 0, X, -X ->
12527 // select_cc setgt X, -1, X, -X ->
12528 // select_cc setl[te] X, 0, -X, X ->
12529 // select_cc setlt X, 1, -X, X ->
Nate Begeman2042aa52005-10-08 00:29:44 +000012530 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000012531 if (N1C) {
Craig Topperc0196b12014-04-14 00:51:57 +000012532 ConstantSDNode *SubC = nullptr;
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000012533 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
12534 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
12535 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
12536 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
12537 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
12538 (N1C->isOne() && CC == ISD::SETLT)) &&
12539 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
12540 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
12541
Owen Anderson53aa7a92009-08-10 22:56:29 +000012542 EVT XType = N0.getValueType();
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000012543 if (SubC && SubC->isNullValue() && XType.isInteger()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000012544 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000012545 N0,
12546 DAG.getConstant(XType.getSizeInBits()-1,
Owen Andersonb2c80da2011-02-25 21:41:48 +000012547 getShiftAmountTy(N0.getValueType())));
Andrew Trickef9de2a2013-05-25 02:42:55 +000012548 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000012549 XType, N0, Shift);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000012550 AddToWorklist(Shift.getNode());
12551 AddToWorklist(Add.getNode());
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000012552 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
Nate Begeman2042aa52005-10-08 00:29:44 +000012553 }
12554 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000012555
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012556 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +000012557}
12558
Sanjay Patel50cbfc52014-08-28 16:29:51 +000012559/// This is a stub for TargetLowering::SimplifySetCC.
Owen Anderson53aa7a92009-08-10 22:56:29 +000012560SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012561 SDValue N1, ISD::CondCode Cond,
Andrew Trickef9de2a2013-05-25 02:42:55 +000012562 SDLoc DL, bool foldBooleans) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000012563 TargetLowering::DAGCombinerInfo
Nadav Rotemb1dd5242012-12-27 06:47:41 +000012564 DagCombineInfo(DAG, Level, false, this);
Dale Johannesenf1163e92009-02-03 00:47:48 +000012565 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
Nate Begeman24a7eca2005-09-16 00:54:12 +000012566}
12567
Sanjay Patel50cbfc52014-08-28 16:29:51 +000012568/// Given an ISD::SDIV node expressing a divide by constant, return
Chad Rosier17020f92014-07-23 14:57:52 +000012569/// a DAG expression to select that will generate the same value by multiplying
Sanjay Patelbb292212014-09-15 19:47:44 +000012570/// by a magic number.
12571/// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012572SDValue DAGCombiner::BuildSDIV(SDNode *N) {
Benjamin Kramerda4841b2014-04-26 23:09:49 +000012573 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12574 if (!C)
12575 return SDValue();
Benjamin Kramer4dae5982014-04-26 12:06:28 +000012576
12577 // Avoid division by zero.
Benjamin Kramerda4841b2014-04-26 23:09:49 +000012578 if (!C->getAPIntValue())
Benjamin Kramer4dae5982014-04-26 12:06:28 +000012579 return SDValue();
12580
Andrew Lenharth0e57b2c2006-06-12 16:07:18 +000012581 std::vector<SDNode*> Built;
Benjamin Kramerda4841b2014-04-26 23:09:49 +000012582 SDValue S =
12583 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000012584
Benjamin Kramerda4841b2014-04-26 23:09:49 +000012585 for (SDNode *N : Built)
Chandler Carruth3c0012b2014-07-21 08:56:44 +000012586 AddToWorklist(N);
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000012587 return S;
Nate Begemanc6f067a2005-10-20 02:15:44 +000012588}
12589
Sanjay Patel50cbfc52014-08-28 16:29:51 +000012590/// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
12591/// DAG expression that will generate the same value by right shifting.
Chad Rosier17020f92014-07-23 14:57:52 +000012592SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
12593 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12594 if (!C)
12595 return SDValue();
12596
12597 // Avoid division by zero.
12598 if (!C->getAPIntValue())
12599 return SDValue();
12600
12601 std::vector<SDNode *> Built;
12602 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
12603
12604 for (SDNode *N : Built)
12605 AddToWorklist(N);
12606 return S;
12607}
12608
Sanjay Patel50cbfc52014-08-28 16:29:51 +000012609/// Given an ISD::UDIV node expressing a divide by constant, return a DAG
12610/// expression that will generate the same value by multiplying by a magic
Sanjay Patelbb292212014-09-15 19:47:44 +000012611/// number.
12612/// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012613SDValue DAGCombiner::BuildUDIV(SDNode *N) {
Benjamin Kramerda4841b2014-04-26 23:09:49 +000012614 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12615 if (!C)
12616 return SDValue();
Benjamin Kramer4dae5982014-04-26 12:06:28 +000012617
12618 // Avoid division by zero.
Benjamin Kramerda4841b2014-04-26 23:09:49 +000012619 if (!C->getAPIntValue())
Benjamin Kramer4dae5982014-04-26 12:06:28 +000012620 return SDValue();
12621
Andrew Lenharth0e57b2c2006-06-12 16:07:18 +000012622 std::vector<SDNode*> Built;
Benjamin Kramerda4841b2014-04-26 23:09:49 +000012623 SDValue S =
12624 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
Nate Begemanc6f067a2005-10-20 02:15:44 +000012625
Benjamin Kramerda4841b2014-04-26 23:09:49 +000012626 for (SDNode *N : Built)
Chandler Carruth3c0012b2014-07-21 08:56:44 +000012627 AddToWorklist(N);
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000012628 return S;
Nate Begemanc6f067a2005-10-20 02:15:44 +000012629}
12630
Sanjay Patelbdf1e382014-09-26 23:01:47 +000012631SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
12632 if (Level >= AfterLegalizeDAG)
12633 return SDValue();
12634
Sanjay Patelb67bd262014-09-21 15:19:15 +000012635 // Expose the DAG combiner to the target combiner implementations.
12636 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
Sanjay Patelb67bd262014-09-21 15:19:15 +000012637
Sanjay Patelab7f4602014-09-30 20:44:23 +000012638 unsigned Iterations = 0;
Sanjay Patel8fde95c2014-09-30 20:28:48 +000012639 if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
Sanjay Patelab7f4602014-09-30 20:44:23 +000012640 if (Iterations) {
12641 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12642 // For the reciprocal, we need to find the zero of the function:
12643 // F(X) = A X - 1 [which has a zero at X = 1/A]
12644 // =>
12645 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
12646 // does not require additional intermediate precision]
12647 EVT VT = Op.getValueType();
12648 SDLoc DL(Op);
12649 SDValue FPOne = DAG.getConstantFP(1.0, VT);
Sanjay Patelbdf1e382014-09-26 23:01:47 +000012650
Sanjay Patelbdf1e382014-09-26 23:01:47 +000012651 AddToWorklist(Est.getNode());
Sanjay Patelbdf1e382014-09-26 23:01:47 +000012652
Sanjay Patelab7f4602014-09-30 20:44:23 +000012653 // Newton iterations: Est = Est + Est (1 - Arg * Est)
12654 for (unsigned i = 0; i < Iterations; ++i) {
12655 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
12656 AddToWorklist(NewEst.getNode());
12657
12658 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
12659 AddToWorklist(NewEst.getNode());
12660
12661 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
12662 AddToWorklist(NewEst.getNode());
12663
12664 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
12665 AddToWorklist(Est.getNode());
12666 }
12667 }
Sanjay Patelbdf1e382014-09-26 23:01:47 +000012668 return Est;
12669 }
12670
12671 return SDValue();
12672}
12673
Sanjay Patel957efc232014-10-24 17:02:16 +000012674/// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12675/// For the reciprocal sqrt, we need to find the zero of the function:
12676/// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
12677/// =>
12678/// X_{i+1} = X_i (1.5 - A X_i^2 / 2)
12679/// As a result, we precompute A/2 prior to the iteration loop.
12680SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
12681 unsigned Iterations) {
12682 EVT VT = Arg.getValueType();
12683 SDLoc DL(Arg);
12684 SDValue ThreeHalves = DAG.getConstantFP(1.5, VT);
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +000012685
Sanjay Patel957efc232014-10-24 17:02:16 +000012686 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
12687 // this entire sequence requires only one FP constant.
12688 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
12689 AddToWorklist(HalfArg.getNode());
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +000012690
Sanjay Patel957efc232014-10-24 17:02:16 +000012691 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
12692 AddToWorklist(HalfArg.getNode());
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +000012693
Sanjay Patel957efc232014-10-24 17:02:16 +000012694 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
12695 for (unsigned i = 0; i < Iterations; ++i) {
12696 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
12697 AddToWorklist(NewEst.getNode());
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +000012698
Sanjay Patel957efc232014-10-24 17:02:16 +000012699 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
12700 AddToWorklist(NewEst.getNode());
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +000012701
Sanjay Patel957efc232014-10-24 17:02:16 +000012702 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
12703 AddToWorklist(NewEst.getNode());
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +000012704
Sanjay Patel957efc232014-10-24 17:02:16 +000012705 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
12706 AddToWorklist(Est.getNode());
12707 }
12708 return Est;
12709}
12710
12711/// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12712/// For the reciprocal sqrt, we need to find the zero of the function:
12713/// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
12714/// =>
12715/// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
12716SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
12717 unsigned Iterations) {
12718 EVT VT = Arg.getValueType();
12719 SDLoc DL(Arg);
12720 SDValue MinusThree = DAG.getConstantFP(-3.0, VT);
12721 SDValue MinusHalf = DAG.getConstantFP(-0.5, VT);
12722
12723 // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
12724 for (unsigned i = 0; i < Iterations; ++i) {
12725 SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
12726 AddToWorklist(HalfEst.getNode());
12727
12728 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
12729 AddToWorklist(Est.getNode());
12730
12731 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
12732 AddToWorklist(Est.getNode());
12733
12734 Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
12735 AddToWorklist(Est.getNode());
12736
12737 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
12738 AddToWorklist(Est.getNode());
12739 }
12740 return Est;
12741}
12742
Sanjay Patelbdf1e382014-09-26 23:01:47 +000012743SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
12744 if (Level >= AfterLegalizeDAG)
12745 return SDValue();
12746
12747 // Expose the DAG combiner to the target combiner implementations.
12748 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
Sanjay Patelab7f4602014-09-30 20:44:23 +000012749 unsigned Iterations = 0;
Sanjay Patel957efc232014-10-24 17:02:16 +000012750 bool UseOneConstNR = false;
12751 if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
12752 AddToWorklist(Est.getNode());
Sanjay Patelab7f4602014-09-30 20:44:23 +000012753 if (Iterations) {
Sanjay Patel957efc232014-10-24 17:02:16 +000012754 Est = UseOneConstNR ?
12755 BuildRsqrtNROneConst(Op, Est, Iterations) :
12756 BuildRsqrtNRTwoConst(Op, Est, Iterations);
Sanjay Patelab7f4602014-09-30 20:44:23 +000012757 }
Sanjay Patelbdf1e382014-09-26 23:01:47 +000012758 return Est;
Sanjay Patelb67bd262014-09-21 15:19:15 +000012759 }
12760
12761 return SDValue();
12762}
12763
Sanjay Patel50cbfc52014-08-28 16:29:51 +000012764/// Return true if base is a frame index, which is known not to alias with
12765/// anything but itself. Provides base object and offset as results.
Nate Begeman18150d52009-09-25 06:05:26 +000012766static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
Roman Divacky93383442012-09-05 22:15:49 +000012767 const GlobalValue *&GV, const void *&CV) {
Jim Laskey0463e082006-10-07 23:37:56 +000012768 // Assume it is a primitive operation.
Craig Topperc0196b12014-04-14 00:51:57 +000012769 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
Scott Michelcf0da6c2009-02-17 22:15:04 +000012770
Jim Laskey0463e082006-10-07 23:37:56 +000012771 // If it's an adding a simple constant then integrate the offset.
12772 if (Base.getOpcode() == ISD::ADD) {
12773 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
12774 Base = Base.getOperand(0);
Dan Gohmaneffb8942008-09-12 16:56:44 +000012775 Offset += C->getZExtValue();
Jim Laskey0463e082006-10-07 23:37:56 +000012776 }
12777 }
Wesley Peck527da1b2010-11-23 03:31:01 +000012778
Nate Begeman18150d52009-09-25 06:05:26 +000012779 // Return the underlying GlobalValue, and update the Offset. Return false
12780 // for GlobalAddressSDNode since the same GlobalAddress may be represented
12781 // by multiple nodes with different offsets.
12782 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
12783 GV = G->getGlobal();
12784 Offset += G->getOffset();
12785 return false;
12786 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000012787
Nate Begeman18150d52009-09-25 06:05:26 +000012788 // Return the underlying Constant value, and update the Offset. Return false
12789 // for ConstantSDNodes since the same constant pool entry may be represented
12790 // by multiple nodes with different offsets.
12791 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
Roman Divacky93383442012-09-05 22:15:49 +000012792 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
12793 : (const void *)C->getConstVal();
Nate Begeman18150d52009-09-25 06:05:26 +000012794 Offset += C->getOffset();
12795 return false;
12796 }
Jim Laskey0463e082006-10-07 23:37:56 +000012797 // If it's any of the following then it can't alias with anything but itself.
Nate Begeman18150d52009-09-25 06:05:26 +000012798 return isa<FrameIndexSDNode>(Base);
Jim Laskey0463e082006-10-07 23:37:56 +000012799}
12800
Sanjay Patel50cbfc52014-08-28 16:29:51 +000012801/// Return true if there is any possibility that the two addresses overlap.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000012802bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
Jim Laskey0463e082006-10-07 23:37:56 +000012803 // If they are the same then they must be aliases.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000012804 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
Scott Michelcf0da6c2009-02-17 22:15:04 +000012805
Richard Sandiford981fdeb2013-10-28 12:00:00 +000012806 // If they are both volatile then they cannot be reordered.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000012807 if (Op0->isVolatile() && Op1->isVolatile()) return true;
Richard Sandiford981fdeb2013-10-28 12:00:00 +000012808
Jim Laskey0463e082006-10-07 23:37:56 +000012809 // Gather base node and offset information.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012810 SDValue Base1, Base2;
Jim Laskey0463e082006-10-07 23:37:56 +000012811 int64_t Offset1, Offset2;
Dan Gohmanbcaf6812010-04-15 01:51:59 +000012812 const GlobalValue *GV1, *GV2;
Roman Divacky93383442012-09-05 22:15:49 +000012813 const void *CV1, *CV2;
Nick Lewyckyaad475b2014-04-15 07:22:52 +000012814 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
12815 Base1, Offset1, GV1, CV1);
12816 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
12817 Base2, Offset2, GV2, CV2);
Scott Michelcf0da6c2009-02-17 22:15:04 +000012818
Nate Begeman18150d52009-09-25 06:05:26 +000012819 // If they have a same base address then check to see if they overlap.
12820 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
Nick Lewyckyaad475b2014-04-15 07:22:52 +000012821 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
12822 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
Scott Michelcf0da6c2009-02-17 22:15:04 +000012823
Owen Anderson272ff942010-09-20 20:39:59 +000012824 // It is possible for different frame indices to alias each other, mostly
12825 // when tail call optimization reuses return address slots for arguments.
12826 // To catch this case, look up the actual index of frame indices to compute
12827 // the real alias relationship.
12828 if (isFrameIndex1 && isFrameIndex2) {
12829 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12830 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
12831 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
Nick Lewyckyaad475b2014-04-15 07:22:52 +000012832 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
12833 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
Owen Anderson272ff942010-09-20 20:39:59 +000012834 }
12835
Wesley Peck527da1b2010-11-23 03:31:01 +000012836 // Otherwise, if we know what the bases are, and they aren't identical, then
Owen Anderson272ff942010-09-20 20:39:59 +000012837 // we know they cannot alias.
Nate Begeman18150d52009-09-25 06:05:26 +000012838 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
12839 return false;
Jim Laskeya15b0eb2006-10-18 12:29:57 +000012840
Nate Begeman879d8f12009-09-15 00:18:30 +000012841 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
12842 // compared to the size and offset of the access, we may be able to prove they
12843 // do not alias. This check is conservative for now to catch cases created by
12844 // splitting vector types.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000012845 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
12846 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
12847 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
12848 Op1->getMemoryVT().getSizeInBits() >> 3) &&
12849 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
12850 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
12851 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
Wesley Peck527da1b2010-11-23 03:31:01 +000012852
Nate Begeman879d8f12009-09-15 00:18:30 +000012853 // There is no overlap between these relatively aligned accesses of similar
12854 // size, return no alias.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000012855 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
12856 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
Nate Begeman879d8f12009-09-15 00:18:30 +000012857 return false;
12858 }
Wesley Peck527da1b2010-11-23 03:31:01 +000012859
Eric Christopherf55d4712014-10-08 23:38:39 +000012860 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
12861 ? CombinerGlobalAA
12862 : DAG.getSubtarget().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +000012863#ifndef NDEBUG
12864 if (CombinerAAOnlyFunc.getNumOccurrences() &&
12865 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
12866 UseAA = false;
12867#endif
Nick Lewyckyaad475b2014-04-15 07:22:52 +000012868 if (UseAA &&
12869 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
Jim Laskey55e4dca2006-10-18 19:08:31 +000012870 // Use alias analysis information.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000012871 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
12872 Op1->getSrcValueOffset());
12873 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
12874 Op0->getSrcValueOffset() - MinOffset;
12875 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
12876 Op1->getSrcValueOffset() - MinOffset;
Scott Michelcf0da6c2009-02-17 22:15:04 +000012877 AliasAnalysis::AliasResult AAResult =
Nick Lewyckyaad475b2014-04-15 07:22:52 +000012878 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
12879 Overlap1,
Hal Finkelcc39b672014-07-24 12:16:19 +000012880 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
Nick Lewyckyaad475b2014-04-15 07:22:52 +000012881 AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
12882 Overlap2,
Hal Finkelcc39b672014-07-24 12:16:19 +000012883 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
Jim Laskey55e4dca2006-10-18 19:08:31 +000012884 if (AAResult == AliasAnalysis::NoAlias)
12885 return false;
12886 }
Jim Laskeya15b0eb2006-10-18 12:29:57 +000012887
12888 // Otherwise we have to assume they alias.
12889 return true;
Jim Laskey0463e082006-10-07 23:37:56 +000012890}
12891
Sanjay Patel50cbfc52014-08-28 16:29:51 +000012892/// Walk up chain skipping non-aliasing memory nodes,
Jim Laskey708d0db2006-10-04 16:53:27 +000012893/// looking for aliasing nodes and adding them to the Aliases vector.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012894void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
Craig Topperb94011f2013-07-14 04:42:23 +000012895 SmallVectorImpl<SDValue> &Aliases) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012896 SmallVector<SDValue, 8> Chains; // List of chains to visit.
Nate Begeman879d8f12009-09-15 00:18:30 +000012897 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
Scott Michelcf0da6c2009-02-17 22:15:04 +000012898
Jim Laskeyd07be232006-09-25 16:29:54 +000012899 // Get alias information for node.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000012900 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
Jim Laskeyd07be232006-09-25 16:29:54 +000012901
Jim Laskey708d0db2006-10-04 16:53:27 +000012902 // Starting off.
Jim Laskey6549d222006-10-05 15:07:25 +000012903 Chains.push_back(OriginalChain);
Nate Begemana3ed9ed2009-10-12 05:53:58 +000012904 unsigned Depth = 0;
Wesley Peck527da1b2010-11-23 03:31:01 +000012905
Jim Laskey6549d222006-10-05 15:07:25 +000012906 // Look at each chain and determine if it is an alias. If so, add it to the
12907 // aliases list. If not, then continue up the chain looking for the next
Scott Michelcf0da6c2009-02-17 22:15:04 +000012908 // candidate.
Jim Laskey6549d222006-10-05 15:07:25 +000012909 while (!Chains.empty()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012910 SDValue Chain = Chains.back();
Jim Laskey6549d222006-10-05 15:07:25 +000012911 Chains.pop_back();
Wesley Peck527da1b2010-11-23 03:31:01 +000012912
12913 // For TokenFactor nodes, look at each operand and only continue up the
12914 // chain until we find two aliases. If we've seen two aliases, assume we'll
Nate Begemana3ed9ed2009-10-12 05:53:58 +000012915 // find more and revert to original chain since the xform is unlikely to be
12916 // profitable.
Wesley Peck527da1b2010-11-23 03:31:01 +000012917 //
12918 // FIXME: The depth check could be made to return the last non-aliasing
Nate Begemana3ed9ed2009-10-12 05:53:58 +000012919 // chain we found before we hit a tokenfactor rather than the original
12920 // chain.
12921 if (Depth > 6 || Aliases.size() == 2) {
12922 Aliases.clear();
12923 Aliases.push_back(OriginalChain);
Hal Finkel51a98382014-01-24 20:12:02 +000012924 return;
Nate Begemana3ed9ed2009-10-12 05:53:58 +000012925 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000012926
Nate Begeman879d8f12009-09-15 00:18:30 +000012927 // Don't bother if we've been before.
David Blaikie70573dc2014-11-19 07:49:26 +000012928 if (!Visited.insert(Chain.getNode()).second)
Nate Begeman879d8f12009-09-15 00:18:30 +000012929 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +000012930
Jim Laskey6549d222006-10-05 15:07:25 +000012931 switch (Chain.getOpcode()) {
12932 case ISD::EntryToken:
12933 // Entry token is ideal chain operand, but handled in FindBetterChain.
12934 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +000012935
Jim Laskey6549d222006-10-05 15:07:25 +000012936 case ISD::LOAD:
12937 case ISD::STORE: {
12938 // Get alias information for Chain.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000012939 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
12940 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
Scott Michelcf0da6c2009-02-17 22:15:04 +000012941
Jim Laskey6549d222006-10-05 15:07:25 +000012942 // If chain is alias then stop here.
12943 if (!(IsLoad && IsOpLoad) &&
Nick Lewyckyaad475b2014-04-15 07:22:52 +000012944 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
Jim Laskey6549d222006-10-05 15:07:25 +000012945 Aliases.push_back(Chain);
12946 } else {
12947 // Look further up the chain.
Scott Michelcf0da6c2009-02-17 22:15:04 +000012948 Chains.push_back(Chain.getOperand(0));
Nate Begemana3ed9ed2009-10-12 05:53:58 +000012949 ++Depth;
Jim Laskeyd07be232006-09-25 16:29:54 +000012950 }
Jim Laskey6549d222006-10-05 15:07:25 +000012951 break;
12952 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000012953
Jim Laskey6549d222006-10-05 15:07:25 +000012954 case ISD::TokenFactor:
Nate Begeman879d8f12009-09-15 00:18:30 +000012955 // We have to check each of the operands of the token factor for "small"
12956 // token factors, so we queue them up. Adding the operands to the queue
12957 // (stack) in reverse order maintains the original order and increases the
12958 // likelihood that getNode will find a matching token factor (CSE.)
12959 if (Chain.getNumOperands() > 16) {
12960 Aliases.push_back(Chain);
12961 break;
12962 }
Jim Laskey6549d222006-10-05 15:07:25 +000012963 for (unsigned n = Chain.getNumOperands(); n;)
12964 Chains.push_back(Chain.getOperand(--n));
Nate Begemana3ed9ed2009-10-12 05:53:58 +000012965 ++Depth;
Jim Laskey6549d222006-10-05 15:07:25 +000012966 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +000012967
Jim Laskey6549d222006-10-05 15:07:25 +000012968 default:
12969 // For all other instructions we will just have to take what we can get.
12970 Aliases.push_back(Chain);
12971 break;
Jim Laskeyd07be232006-09-25 16:29:54 +000012972 }
12973 }
Hal Finkel51a98382014-01-24 20:12:02 +000012974
12975 // We need to be careful here to also search for aliases through the
12976 // value operand of a store, etc. Consider the following situation:
12977 // Token1 = ...
12978 // L1 = load Token1, %52
12979 // S1 = store Token1, L1, %51
12980 // L2 = load Token1, %52+8
12981 // S2 = store Token1, L2, %51+8
12982 // Token2 = Token(S1, S2)
12983 // L3 = load Token2, %53
12984 // S3 = store Token2, L3, %52
12985 // L4 = load Token2, %53+8
12986 // S4 = store Token2, L4, %52+8
12987 // If we search for aliases of S3 (which loads address %52), and we look
12988 // only through the chain, then we'll miss the trivial dependence on L1
12989 // (which also loads from %52). We then might change all loads and
12990 // stores to use Token1 as their chain operand, which could result in
12991 // copying %53 into %52 before copying %52 into %51 (which should
12992 // happen first).
12993 //
12994 // The problem is, however, that searching for such data dependencies
12995 // can become expensive, and the cost is not directly related to the
12996 // chain depth. Instead, we'll rule out such configurations here by
12997 // insisting that we've visited all chain users (except for users
12998 // of the original chain, which is not necessary). When doing this,
12999 // we need to look through nodes we don't care about (otherwise, things
13000 // like register copies will interfere with trivial cases).
13001
13002 SmallVector<const SDNode *, 16> Worklist;
Craig Topper46276792014-08-24 23:23:06 +000013003 for (const SDNode *N : Visited)
13004 if (N != OriginalChain.getNode())
13005 Worklist.push_back(N);
Hal Finkel51a98382014-01-24 20:12:02 +000013006
13007 while (!Worklist.empty()) {
13008 const SDNode *M = Worklist.pop_back_val();
13009
13010 // We have already visited M, and want to make sure we've visited any uses
13011 // of M that we care about. For uses that we've not visisted, and don't
13012 // care about, queue them to the worklist.
13013
13014 for (SDNode::use_iterator UI = M->use_begin(),
13015 UIE = M->use_end(); UI != UIE; ++UI)
David Blaikie70573dc2014-11-19 07:49:26 +000013016 if (UI.getUse().getValueType() == MVT::Other &&
13017 Visited.insert(*UI).second) {
Hal Finkel51a98382014-01-24 20:12:02 +000013018 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
13019 // We've not visited this use, and we care about it (it could have an
13020 // ordering dependency with the original node).
13021 Aliases.clear();
13022 Aliases.push_back(OriginalChain);
13023 return;
13024 }
13025
13026 // We've not visited this use, but we don't care about it. Mark it as
13027 // visited and enqueue it to the worklist.
13028 Worklist.push_back(*UI);
13029 }
13030 }
Jim Laskey708d0db2006-10-04 16:53:27 +000013031}
13032
Sanjay Patel50cbfc52014-08-28 16:29:51 +000013033/// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
13034/// (aliasing node.)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000013035SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
13036 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +000013037
Jim Laskey708d0db2006-10-04 16:53:27 +000013038 // Accumulate all the aliases to this node.
13039 GatherAllAliases(N, OldChain, Aliases);
Scott Michelcf0da6c2009-02-17 22:15:04 +000013040
Dan Gohman4298df62011-05-17 22:20:36 +000013041 // If no operands then chain to entry token.
13042 if (Aliases.size() == 0)
Jim Laskey708d0db2006-10-04 16:53:27 +000013043 return DAG.getEntryNode();
Dan Gohman4298df62011-05-17 22:20:36 +000013044
13045 // If a single operand then chain to it. We don't need to revisit it.
13046 if (Aliases.size() == 1)
Jim Laskey708d0db2006-10-04 16:53:27 +000013047 return Aliases[0];
Wesley Peck527da1b2010-11-23 03:31:01 +000013048
Jim Laskey708d0db2006-10-04 16:53:27 +000013049 // Construct a custom tailored token factor.
Craig Topper48d114b2014-04-26 18:35:24 +000013050 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
Jim Laskeyd07be232006-09-25 16:29:54 +000013051}
13052
Sanjay Patel50cbfc52014-08-28 16:29:51 +000013053/// This is the entry point for the file.
Bill Wendling084669a2009-04-29 00:15:41 +000013054void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
Bill Wendling026e5d72009-04-29 23:29:43 +000013055 CodeGenOpt::Level OptLevel) {
Sanjay Patel50cbfc52014-08-28 16:29:51 +000013056 /// This is the main entry point to this class.
Bill Wendling084669a2009-04-29 00:15:41 +000013057 DAGCombiner(*this, AA, OptLevel).Run(Level);
Nate Begeman21158fc2005-09-01 00:19:25 +000013058}