blob: 8e1dff8023ee93a8d4510603ef67a1fdfbbf2c5f [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);
Matthias Braun3ecb5572015-03-06 19:49:06 +0000249 SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000250 SDValue visitOR(SDNode *N);
Matthias Braun3ecb5572015-03-06 19:49:06 +0000251 SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000252 SDValue visitXOR(SDNode *N);
253 SDValue SimplifyVBinOp(SDNode *N);
254 SDValue visitSHL(SDNode *N);
255 SDValue visitSRA(SDNode *N);
256 SDValue visitSRL(SDNode *N);
Adam Nemet7f928f12014-03-07 23:56:30 +0000257 SDValue visitRotate(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000258 SDValue visitCTLZ(SDNode *N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +0000259 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000260 SDValue visitCTTZ(SDNode *N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +0000261 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000262 SDValue visitCTPOP(SDNode *N);
263 SDValue visitSELECT(SDNode *N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +0000264 SDValue visitVSELECT(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000265 SDValue visitSELECT_CC(SDNode *N);
266 SDValue visitSETCC(SDNode *N);
267 SDValue visitSIGN_EXTEND(SDNode *N);
268 SDValue visitZERO_EXTEND(SDNode *N);
269 SDValue visitANY_EXTEND(SDNode *N);
270 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
271 SDValue visitTRUNCATE(SDNode *N);
Wesley Peck527da1b2010-11-23 03:31:01 +0000272 SDValue visitBITCAST(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000273 SDValue visitBUILD_PAIR(SDNode *N);
274 SDValue visitFADD(SDNode *N);
275 SDValue visitFSUB(SDNode *N);
276 SDValue visitFMUL(SDNode *N);
Owen Anderson41b06652012-05-02 22:17:40 +0000277 SDValue visitFMA(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000278 SDValue visitFDIV(SDNode *N);
279 SDValue visitFREM(SDNode *N);
Sanjay Patelbdf1e382014-09-26 23:01:47 +0000280 SDValue visitFSQRT(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000281 SDValue visitFCOPYSIGN(SDNode *N);
282 SDValue visitSINT_TO_FP(SDNode *N);
283 SDValue visitUINT_TO_FP(SDNode *N);
284 SDValue visitFP_TO_SINT(SDNode *N);
285 SDValue visitFP_TO_UINT(SDNode *N);
286 SDValue visitFP_ROUND(SDNode *N);
287 SDValue visitFP_ROUND_INREG(SDNode *N);
288 SDValue visitFP_EXTEND(SDNode *N);
289 SDValue visitFNEG(SDNode *N);
290 SDValue visitFABS(SDNode *N);
Owen Andersona40319b2012-08-13 23:32:49 +0000291 SDValue visitFCEIL(SDNode *N);
292 SDValue visitFTRUNC(SDNode *N);
293 SDValue visitFFLOOR(SDNode *N);
Matt Arsenault7c936902014-10-21 23:01:01 +0000294 SDValue visitFMINNUM(SDNode *N);
295 SDValue visitFMAXNUM(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000296 SDValue visitBRCOND(SDNode *N);
297 SDValue visitBR_CC(SDNode *N);
298 SDValue visitLOAD(SDNode *N);
299 SDValue visitSTORE(SDNode *N);
300 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
301 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
302 SDValue visitBUILD_VECTOR(SDNode *N);
303 SDValue visitCONCAT_VECTORS(SDNode *N);
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +0000304 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000305 SDValue visitVECTOR_SHUFFLE(SDNode *N);
Simon Pilgrimbede80a2015-03-07 05:52:42 +0000306 SDValue visitSCALAR_TO_VECTOR(SDNode *N);
Manman Ren413a6cb2014-01-31 01:10:35 +0000307 SDValue visitINSERT_SUBVECTOR(SDNode *N);
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +0000308 SDValue visitMLOAD(SDNode *N);
309 SDValue visitMSTORE(SDNode *N);
Elena Demikhovskye1eda8a2015-04-30 08:38:48 +0000310 SDValue visitMGATHER(SDNode *N);
311 SDValue visitMSCATTER(SDNode *N);
Pirama Arumuga Nainardb7c07e22015-04-17 18:36:25 +0000312 SDValue visitFP_TO_FP16(SDNode *N);
Chris Lattnere260ed82005-10-10 22:04:48 +0000313
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +0000314 SDValue visitFADDForFMACombine(SDNode *N);
315 SDValue visitFSUBForFMACombine(SDNode *N);
316
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000317 SDValue XformToShuffleWithZero(SDNode *N);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000318 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000319
Matt Arsenault985b9de2014-03-17 18:58:01 +0000320 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
Chris Lattner7c709a52007-12-06 07:33:36 +0000321
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000322 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
323 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000324 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
325 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
Scott Michelcf0da6c2009-02-17 22:15:04 +0000326 SDValue N3, ISD::CondCode CC,
Bill Wendling31b50992009-01-30 23:59:18 +0000327 bool NotExtCompare = false);
Owen Anderson53aa7a92009-08-10 22:56:29 +0000328 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
Andrew Trickef9de2a2013-05-25 02:42:55 +0000329 SDLoc DL, bool foldBooleans = true);
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000330
331 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
332 SDValue &CC) const;
333 bool isOneUseSetCC(SDValue N) const;
334
Scott Michelcf0da6c2009-02-17 22:15:04 +0000335 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
Chris Lattner31e9edc2008-01-26 01:09:19 +0000336 unsigned HiOp);
Owen Anderson53aa7a92009-08-10 22:56:29 +0000337 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
Ahmed Bougachae892d132015-02-05 18:31:02 +0000338 SDValue CombineExtLoad(SDNode *N);
Wesley Peck527da1b2010-11-23 03:31:01 +0000339 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000340 SDValue BuildSDIV(SDNode *N);
Chad Rosier17020f92014-07-23 14:57:52 +0000341 SDValue BuildSDIVPow2(SDNode *N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000342 SDValue BuildUDIV(SDNode *N);
Sanjay Patelbdf1e382014-09-26 23:01:47 +0000343 SDValue BuildReciprocalEstimate(SDValue Op);
344 SDValue BuildRsqrtEstimate(SDValue Op);
Sanjay Patel957efc232014-10-24 17:02:16 +0000345 SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations);
346 SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations);
Evan Cheng4c0bd962011-06-21 06:01:08 +0000347 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
348 bool DemandHighBits = true);
349 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
Richard Sandiford95c864d2014-01-08 15:40:47 +0000350 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
351 SDValue InnerPos, SDValue InnerNeg,
352 unsigned PosOpcode, unsigned NegOpcode,
353 SDLoc DL);
Andrew Trickef9de2a2013-05-25 02:42:55 +0000354 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000355 SDValue ReduceLoadWidth(SDNode *N);
Evan Chenga9cda8a2009-05-28 00:35:15 +0000356 SDValue ReduceLoadOpStoreWidth(SDNode *N);
Evan Chengd42641c2011-02-02 01:06:55 +0000357 SDValue TransformFPLoadStorePair(SDNode *N);
Michael Liao6d106b72012-10-23 23:06:52 +0000358 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
Michael Liao59229792012-10-24 04:14:18 +0000359 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000360
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000361 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000362
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000363 /// Walk up chain skipping non-aliasing memory nodes,
Jim Laskey708d0db2006-10-04 16:53:27 +0000364 /// looking for aliasing nodes and adding them to the Aliases vector.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000365 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
Craig Topperb94011f2013-07-14 04:42:23 +0000366 SmallVectorImpl<SDValue> &Aliases);
Jim Laskey708d0db2006-10-04 16:53:27 +0000367
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000368 /// Return true if there is any possibility that the two addresses overlap.
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000369 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000370
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000371 /// Walk up chain skipping non-aliasing memory nodes, looking for a better
372 /// chain (aliasing node.)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000373 SDValue FindBetterChain(SDNode *N, SDValue Chain);
Duncan Sands41826032009-01-31 15:50:11 +0000374
Sanjay Patel37c41c12015-01-22 18:21:26 +0000375 /// Holds a pointer to an LSBaseSDNode as well as information on where it
376 /// is located in a sequence of memory operations connected by a chain.
377 struct MemOpLink {
378 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
379 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
380 // Ptr to the mem node.
381 LSBaseSDNode *MemNode;
382 // Offset from the base ptr.
383 int64_t OffsetFromBase;
384 // What is the sequence number of this mem node.
385 // Lowest mem operand in the DAG starts at zero.
386 unsigned SequenceNum;
387 };
388
389 /// This is a helper function for MergeConsecutiveStores. When the source
390 /// elements of the consecutive stores are all constants or all extracted
391 /// vector elements, try to merge them into one larger store.
392 /// \return True if a merged store was created.
393 bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
Quentin Colombet308b1712015-01-27 23:58:01 +0000394 EVT MemVT, unsigned NumElem,
Sanjay Patel37c41c12015-01-22 18:21:26 +0000395 bool IsConstantSrc, bool UseVector);
Simon Pilgrimd8820ae2015-02-24 22:08:56 +0000396
Nadav Rotem7cbc12a2012-10-03 16:11:15 +0000397 /// Merge consecutive store operations into a wide store.
398 /// This optimization uses wide integers or vectors when possible.
399 /// \return True if some memory operations were changed.
400 bool MergeConsecutiveStores(StoreSDNode *N);
401
Adam Nemet67483892014-03-04 23:28:31 +0000402 /// \brief Try to transform a truncation where C is a constant:
403 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
404 ///
405 /// \p N needs to be a truncation and its first operand an AND. Other
406 /// requirements are checked by the function (e.g. that trunc is
407 /// single-use) and if missed an empty SDValue is returned.
408 SDValue distributeTruncateThroughAnd(SDNode *N);
409
Chris Lattner4041ab62010-04-15 04:48:01 +0000410 public:
Bill Wendling026e5d72009-04-29 23:29:43 +0000411 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
Quentin Colombetde0e0622013-10-11 18:29:42 +0000412 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
413 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
Duncan P. N. Exon Smith70eb9c52015-02-14 01:44:41 +0000414 auto *F = DAG.getMachineFunction().getFunction();
415 ForCodeSize = F->hasFnAttribute(Attribute::OptimizeForSize) ||
416 F->hasFnAttribute(Attribute::MinSize);
Quentin Colombetde0e0622013-10-11 18:29:42 +0000417 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000418
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000419 /// Runs the dag combiner on all nodes in the work list
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000420 void Run(CombineLevel AtLevel);
Wesley Peck527da1b2010-11-23 03:31:01 +0000421
Chris Lattner4041ab62010-04-15 04:48:01 +0000422 SelectionDAG &getDAG() const { return DAG; }
Wesley Peck527da1b2010-11-23 03:31:01 +0000423
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000424 /// Returns a type large enough to hold any valid shift amount - before type
425 /// legalization these can be huge.
Owen Andersonb2c80da2011-02-25 21:41:48 +0000426 EVT getShiftAmountTy(EVT LHSTy) {
Elena Demikhovsky6769c502013-06-26 10:55:03 +0000427 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
428 if (LHSTy.isVector())
429 return LHSTy;
Jack Carterd4e96152013-10-17 01:34:33 +0000430 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
431 : TLI.getPointerTy();
Chris Lattner4041ab62010-04-15 04:48:01 +0000432 }
Wesley Peck527da1b2010-11-23 03:31:01 +0000433
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000434 /// This method returns true if we are running before type legalization or
435 /// if the specified VT is legal.
Chris Lattner4041ab62010-04-15 04:48:01 +0000436 bool isTypeLegal(const EVT &VT) {
437 if (!LegalTypes) return true;
438 return TLI.isTypeLegal(VT);
439 }
Matt Arsenault758659232013-05-18 00:21:46 +0000440
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000441 /// Convenience wrapper around TargetLowering::getSetCCResultType
Matt Arsenault758659232013-05-18 00:21:46 +0000442 EVT getSetCCResultType(EVT VT) const {
443 return TLI.getSetCCResultType(*DAG.getContext(), VT);
444 }
Nate Begeman21158fc2005-09-01 00:19:25 +0000445 };
446}
447
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000448
449namespace {
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000450/// This class is a DAGUpdateListener that removes any deleted
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000451/// nodes from the worklist.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000452class WorklistRemover : public SelectionDAG::DAGUpdateListener {
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000453 DAGCombiner &DC;
454public:
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000455 explicit WorklistRemover(DAGCombiner &dc)
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000456 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
Scott Michelcf0da6c2009-02-17 22:15:04 +0000457
Craig Topper7b883b32014-03-08 06:31:39 +0000458 void NodeDeleted(SDNode *N, SDNode *E) override {
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000459 DC.removeFromWorklist(N);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000460 }
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000461};
462}
463
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000464//===----------------------------------------------------------------------===//
465// TargetLowering::DAGCombinerInfo implementation
466//===----------------------------------------------------------------------===//
467
468void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000469 ((DAGCombiner*)DC)->AddToWorklist(N);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000470}
471
Cameron Zwarich8c7bbc02011-04-02 02:40:26 +0000472void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000473 ((DAGCombiner*)DC)->removeFromWorklist(N);
Cameron Zwarich8c7bbc02011-04-02 02:40:26 +0000474}
475
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000476SDValue TargetLowering::DAGCombinerInfo::
Ahmed Bougacha4c2b0782015-02-19 23:13:10 +0000477CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
Evan Chengfd81c732009-03-28 05:57:29 +0000478 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000479}
480
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000481SDValue TargetLowering::DAGCombinerInfo::
Evan Chengfd81c732009-03-28 05:57:29 +0000482CombineTo(SDNode *N, SDValue Res, bool AddTo) {
483 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000484}
485
486
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000487SDValue TargetLowering::DAGCombinerInfo::
Evan Chengfd81c732009-03-28 05:57:29 +0000488CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
489 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000490}
491
Dan Gohmane58ab792009-01-29 01:59:02 +0000492void TargetLowering::DAGCombinerInfo::
493CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
494 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
495}
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000496
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000497//===----------------------------------------------------------------------===//
Chris Lattnere49c9742007-05-14 22:04:50 +0000498// Helper Functions
499//===----------------------------------------------------------------------===//
500
Chandler Carruth18066972014-08-02 10:02:07 +0000501void DAGCombiner::deleteAndRecombine(SDNode *N) {
502 removeFromWorklist(N);
503
504 // If the operands of this node are only used by the node, they will now be
505 // dead. Make sure to re-visit them and recursively delete dead nodes.
506 for (const SDValue &Op : N->ops())
Hal Finkel51e6fa22014-09-02 06:24:04 +0000507 // For an operand generating multiple values, one of the values may
508 // become dead allowing further simplification (e.g. split index
509 // arithmetic from an indexed load).
510 if (Op->hasOneUse() || Op->getNumValues() > 1)
Chandler Carruth18066972014-08-02 10:02:07 +0000511 AddToWorklist(Op.getNode());
512
513 DAG.DeleteNode(N);
514}
515
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000516/// Return 1 if we can compute the negated form of the specified expression for
517/// the same cost as the expression itself, or 2 if we can compute the negated
518/// form more cheaply than the expression itself.
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000519static char isNegatibleForFree(SDValue Op, bool LegalOperations,
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000520 const TargetLowering &TLI,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000521 const TargetOptions *Options,
Chris Lattnere7c14012008-02-26 07:04:54 +0000522 unsigned Depth = 0) {
Chris Lattnere49c9742007-05-14 22:04:50 +0000523 // fneg is removable even if it has multiple uses.
524 if (Op.getOpcode() == ISD::FNEG) return 2;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000525
Chris Lattnere49c9742007-05-14 22:04:50 +0000526 // Don't allow anything with multiple uses.
527 if (!Op.hasOneUse()) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000528
Chris Lattner46980832007-05-25 02:19:06 +0000529 // Don't recurse exponentially.
530 if (Depth > 6) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000531
Chris Lattnere49c9742007-05-14 22:04:50 +0000532 switch (Op.getOpcode()) {
533 default: return false;
534 case ISD::ConstantFP:
Chris Lattnere7c14012008-02-26 07:04:54 +0000535 // Don't invert constant FP values after legalize. The negated constant
536 // isn't necessarily legal.
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000537 return LegalOperations ? 0 : 1;
Chris Lattnere49c9742007-05-14 22:04:50 +0000538 case ISD::FADD:
539 // FIXME: determine better conditions for this xform.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000540 if (!Options->UnsafeFPMath) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000541
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000542 // After operation legalization, it might not be legal to create new FSUBs.
543 if (LegalOperations &&
544 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
545 return 0;
546
Craig Topper03f39772012-09-09 22:58:45 +0000547 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000548 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
549 Options, Depth + 1))
Chris Lattnere49c9742007-05-14 22:04:50 +0000550 return V;
Bill Wendling6fbf5492009-01-30 23:10:18 +0000551 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000552 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000553 Depth + 1);
Chris Lattnere49c9742007-05-14 22:04:50 +0000554 case ISD::FSUB:
Scott Michelcf0da6c2009-02-17 22:15:04 +0000555 // We can't turn -(A-B) into B-A when we honor signed zeros.
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000556 if (!Options->UnsafeFPMath) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000557
Bill Wendling6fbf5492009-01-30 23:10:18 +0000558 // fold (fneg (fsub A, B)) -> (fsub B, A)
Chris Lattnere49c9742007-05-14 22:04:50 +0000559 return 1;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000560
Chris Lattnere49c9742007-05-14 22:04:50 +0000561 case ISD::FMUL:
562 case ISD::FDIV:
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000563 if (Options->HonorSignDependentRoundingFPMath()) return 0;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000564
Bill Wendling6fbf5492009-01-30 23:10:18 +0000565 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000566 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
567 Options, Depth + 1))
Chris Lattnere49c9742007-05-14 22:04:50 +0000568 return V;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000569
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000570 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000571 Depth + 1);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000572
Chris Lattnere49c9742007-05-14 22:04:50 +0000573 case ISD::FP_EXTEND:
574 case ISD::FP_ROUND:
575 case ISD::FSIN:
Owen Anderson2ee7c4d2012-03-06 00:29:31 +0000576 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000577 Depth + 1);
Chris Lattnere49c9742007-05-14 22:04:50 +0000578 }
579}
580
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000581/// If isNegatibleForFree returns true, return the newly negated expression.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000582static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000583 bool LegalOperations, unsigned Depth = 0) {
Sanjay Patel78614bf2014-08-28 15:53:16 +0000584 const TargetOptions &Options = DAG.getTarget().Options;
Chris Lattnere49c9742007-05-14 22:04:50 +0000585 // fneg is removable even if it has multiple uses.
586 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000587
Chris Lattnere49c9742007-05-14 22:04:50 +0000588 // Don't allow anything with multiple uses.
589 assert(Op.hasOneUse() && "Unknown reuse!");
Scott Michelcf0da6c2009-02-17 22:15:04 +0000590
Chris Lattner46980832007-05-25 02:19:06 +0000591 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
Chris Lattnere49c9742007-05-14 22:04:50 +0000592 switch (Op.getOpcode()) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000593 default: llvm_unreachable("Unknown code");
Dale Johannesen446b9002007-08-31 23:34:27 +0000594 case ISD::ConstantFP: {
595 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
596 V.changeSign();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000597 return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
Dale Johannesen446b9002007-08-31 23:34:27 +0000598 }
Chris Lattnere49c9742007-05-14 22:04:50 +0000599 case ISD::FADD:
600 // FIXME: determine better conditions for this xform.
Sanjay Patel78614bf2014-08-28 15:53:16 +0000601 assert(Options.UnsafeFPMath);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000602
Bill Wendling6fbf5492009-01-30 23:10:18 +0000603 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000604 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
Sanjay Patel78614bf2014-08-28 15:53:16 +0000605 DAG.getTargetLoweringInfo(), &Options, Depth+1))
Andrew Trickef9de2a2013-05-25 02:42:55 +0000606 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000607 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000608 LegalOperations, Depth+1),
Chris Lattnere49c9742007-05-14 22:04:50 +0000609 Op.getOperand(1));
Bill Wendling6fbf5492009-01-30 23:10:18 +0000610 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
Andrew Trickef9de2a2013-05-25 02:42:55 +0000611 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000612 GetNegatedExpression(Op.getOperand(1), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000613 LegalOperations, Depth+1),
Chris Lattnere49c9742007-05-14 22:04:50 +0000614 Op.getOperand(0));
615 case ISD::FSUB:
Scott Michelcf0da6c2009-02-17 22:15:04 +0000616 // We can't turn -(A-B) into B-A when we honor signed zeros.
Sanjay Patel78614bf2014-08-28 15:53:16 +0000617 assert(Options.UnsafeFPMath);
Dan Gohman9a708232007-07-02 15:48:56 +0000618
Bill Wendling6fbf5492009-01-30 23:10:18 +0000619 // fold (fneg (fsub 0, B)) -> B
Dan Gohman9a708232007-07-02 15:48:56 +0000620 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
Dale Johannesen446b9002007-08-31 23:34:27 +0000621 if (N0CFP->getValueAPF().isZero())
Dan Gohman9a708232007-07-02 15:48:56 +0000622 return Op.getOperand(1);
Scott Michelcf0da6c2009-02-17 22:15:04 +0000623
Bill Wendling6fbf5492009-01-30 23:10:18 +0000624 // fold (fneg (fsub A, B)) -> (fsub B, A)
Andrew Trickef9de2a2013-05-25 02:42:55 +0000625 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000626 Op.getOperand(1), Op.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +0000627
Chris Lattnere49c9742007-05-14 22:04:50 +0000628 case ISD::FMUL:
629 case ISD::FDIV:
Sanjay Patel78614bf2014-08-28 15:53:16 +0000630 assert(!Options.HonorSignDependentRoundingFPMath());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000631
Bill Wendling6fbf5492009-01-30 23:10:18 +0000632 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000633 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
Sanjay Patel78614bf2014-08-28 15:53:16 +0000634 DAG.getTargetLoweringInfo(), &Options, Depth+1))
Andrew Trickef9de2a2013-05-25 02:42:55 +0000635 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000636 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000637 LegalOperations, Depth+1),
Chris Lattnere49c9742007-05-14 22:04:50 +0000638 Op.getOperand(1));
Scott Michelcf0da6c2009-02-17 22:15:04 +0000639
Bill Wendling6fbf5492009-01-30 23:10:18 +0000640 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
Andrew Trickef9de2a2013-05-25 02:42:55 +0000641 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Chris Lattnere49c9742007-05-14 22:04:50 +0000642 Op.getOperand(0),
Chris Lattnere7c14012008-02-26 07:04:54 +0000643 GetNegatedExpression(Op.getOperand(1), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000644 LegalOperations, Depth+1));
Scott Michelcf0da6c2009-02-17 22:15:04 +0000645
Chris Lattnere49c9742007-05-14 22:04:50 +0000646 case ISD::FP_EXTEND:
Chris Lattnere49c9742007-05-14 22:04:50 +0000647 case ISD::FSIN:
Andrew Trickef9de2a2013-05-25 02:42:55 +0000648 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000649 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000650 LegalOperations, Depth+1));
Chris Lattner72733e52008-01-17 07:00:52 +0000651 case ISD::FP_ROUND:
Andrew Trickef9de2a2013-05-25 02:42:55 +0000652 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +0000653 GetNegatedExpression(Op.getOperand(0), DAG,
Duncan Sandsdc2dac12008-11-24 14:53:14 +0000654 LegalOperations, Depth+1),
Chris Lattner72733e52008-01-17 07:00:52 +0000655 Op.getOperand(1));
Chris Lattnere49c9742007-05-14 22:04:50 +0000656 }
657}
Chris Lattnerbc1c85b2006-03-01 04:53:38 +0000658
Sanjay Patelf4b8deb2014-09-05 20:55:46 +0000659// Return true if this node is a setcc, or is a select_cc
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000660// that selects between the target values used for true and false, making it
661// equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
662// the appropriate nodes based on the type of node we are checking. This
663// simplifies life a bit for the callers.
664bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
665 SDValue &CC) const {
Nate Begeman7cea6ef2005-09-02 21:18:40 +0000666 if (N.getOpcode() == ISD::SETCC) {
667 LHS = N.getOperand(0);
668 RHS = N.getOperand(1);
669 CC = N.getOperand(2);
Nate Begeman2504fe22005-09-01 23:24:04 +0000670 return true;
Nate Begeman7cea6ef2005-09-02 21:18:40 +0000671 }
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000672
673 if (N.getOpcode() != ISD::SELECT_CC ||
674 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
675 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
676 return false;
677
Oliver Stannardd29db9b2014-11-17 10:49:31 +0000678 if (TLI.getBooleanContents(N.getValueType()) ==
679 TargetLowering::UndefinedBooleanContent)
680 return false;
681
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000682 LHS = N.getOperand(0);
683 RHS = N.getOperand(1);
684 CC = N.getOperand(4);
685 return true;
Nate Begeman21158fc2005-09-01 00:19:25 +0000686}
687
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000688/// Return true if this is a SetCC-equivalent operation with only one use.
689/// If this is true, it allows the users to invert the operation for free when
690/// it is profitable to do so.
Matt Arsenaulte407ae92014-04-01 18:13:26 +0000691bool DAGCombiner::isOneUseSetCC(SDValue N) const {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000692 SDValue N0, N1, N2;
Gabor Greiff304a7a2008-08-28 21:40:38 +0000693 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
Nate Begeman2504fe22005-09-01 23:24:04 +0000694 return true;
695 return false;
696}
697
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000698/// Returns true if N is a BUILD_VECTOR node whose
Matt Arsenault985b9de2014-03-17 18:58:01 +0000699/// elements are all the same constant or undefined.
700static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
701 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
702 if (!C)
703 return false;
704
705 APInt SplatUndef;
706 unsigned SplatBitSize;
707 bool HasAnyUndefs;
708 EVT EltVT = N->getValueType(0).getVectorElementType();
709 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
710 HasAnyUndefs) &&
711 EltVT.getSizeInBits() >= SplatBitSize);
712}
713
Simon Pilgrim7fdcc302015-03-28 18:31:31 +0000714// \brief Returns the SDNode if it is a constant integer BuildVector
715// or constant integer.
Simon Pilgrim09f3ff92015-03-25 22:30:31 +0000716static SDNode *isConstantIntBuildVectorOrConstantInt(SDValue N) {
717 if (isa<ConstantSDNode>(N))
718 return N.getNode();
719 if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
720 return N.getNode();
721 return nullptr;
722}
723
Simon Pilgrim7fdcc302015-03-28 18:31:31 +0000724// \brief Returns the SDNode if it is a constant float BuildVector
725// or constant float.
Simon Pilgrim09f3ff92015-03-25 22:30:31 +0000726static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
727 if (isa<ConstantFPSDNode>(N))
728 return N.getNode();
729 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
730 return N.getNode();
731 return nullptr;
732}
733
Matt Arsenault985b9de2014-03-17 18:58:01 +0000734// \brief Returns the SDNode if it is a constant splat BuildVector or constant
735// int.
736static ConstantSDNode *isConstOrConstSplat(SDValue N) {
737 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
738 return CN;
739
Chandler Carruthbeeacac2014-07-07 19:03:32 +0000740 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
Chandler Carruthf0a33b72014-07-09 00:41:34 +0000741 BitVector UndefElements;
742 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
Chandler Carruthbeeacac2014-07-07 19:03:32 +0000743
744 // BuildVectors can truncate their operands. Ignore that case here.
Chandler Carruthb844e722014-07-08 07:19:55 +0000745 // FIXME: We blindly ignore splats which include undef which is overly
746 // pessimistic.
Chandler Carruthf0a33b72014-07-09 00:41:34 +0000747 if (CN && UndefElements.none() &&
Chandler Carruthb844e722014-07-08 07:19:55 +0000748 CN->getValueType(0) == N.getValueType().getScalarType())
Chandler Carruthbeeacac2014-07-07 19:03:32 +0000749 return CN;
750 }
Matt Arsenault985b9de2014-03-17 18:58:01 +0000751
752 return nullptr;
753}
754
Matt Arsenault6cc00422014-08-16 10:14:19 +0000755// \brief Returns the SDNode if it is a constant splat BuildVector or constant
756// float.
757static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
758 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
759 return CN;
760
761 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
762 BitVector UndefElements;
763 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
764
Matt Arsenault965de302014-09-02 18:33:51 +0000765 if (CN && UndefElements.none())
Matt Arsenault6cc00422014-08-16 10:14:19 +0000766 return CN;
767 }
768
769 return nullptr;
770}
771
Andrew Trickef9de2a2013-05-25 02:42:55 +0000772SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000773 SDValue N0, SDValue N1) {
Owen Anderson53aa7a92009-08-10 22:56:29 +0000774 EVT VT = N0.getValueType();
Juergen Ributzka68402822014-01-13 21:49:25 +0000775 if (N0.getOpcode() == Opc) {
Simon Pilgrim7fdcc302015-03-28 18:31:31 +0000776 if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
777 if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1)) {
Juergen Ributzka68402822014-01-13 21:49:25 +0000778 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000779 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
Matthias Braunf50ab432015-01-13 22:17:46 +0000780 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
781 return SDValue();
Juergen Ributzka73844052014-01-13 20:51:35 +0000782 }
Juergen Ributzka68402822014-01-13 21:49:25 +0000783 if (N0.hasOneUse()) {
784 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
785 // use
786 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
787 if (!OpNode.getNode())
788 return SDValue();
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000789 AddToWorklist(OpNode.getNode());
Juergen Ributzka68402822014-01-13 21:49:25 +0000790 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
Juergen Ributzka73844052014-01-13 20:51:35 +0000791 }
792 }
Nate Begeman22e251a2006-02-03 06:46:56 +0000793 }
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000794
Juergen Ributzka68402822014-01-13 21:49:25 +0000795 if (N1.getOpcode() == Opc) {
Simon Pilgrim7fdcc302015-03-28 18:31:31 +0000796 if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
797 if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0)) {
Juergen Ributzka68402822014-01-13 21:49:25 +0000798 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +0000799 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
Matthias Braunf50ab432015-01-13 22:17:46 +0000800 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
801 return SDValue();
Juergen Ributzka68402822014-01-13 21:49:25 +0000802 }
803 if (N1.hasOneUse()) {
804 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
805 // use
806 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
807 if (!OpNode.getNode())
808 return SDValue();
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000809 AddToWorklist(OpNode.getNode());
Juergen Ributzka68402822014-01-13 21:49:25 +0000810 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
811 }
Nate Begeman22e251a2006-02-03 06:46:56 +0000812 }
813 }
Bill Wendlingf6d0aff2009-01-30 00:45:56 +0000814
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000815 return SDValue();
Nate Begeman22e251a2006-02-03 06:46:56 +0000816}
817
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000818SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
819 bool AddTo) {
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000820 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
821 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +0000822 DEBUG(dbgs() << "\nReplacing.1 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000823 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000824 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000825 To[0].getNode()->dump(&DAG);
Mehdi Aminid3892082014-12-23 18:59:02 +0000826 dbgs() << " and " << NumTo-1 << " other values\n");
827 for (unsigned i = 0, e = NumTo; i != e; ++i)
828 assert((!To[i].getNode() ||
829 N->getValueType(i) == To[i].getValueType()) &&
830 "Cannot combine value to value of different type!");
831
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000832 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000833 DAG.ReplaceAllUsesWith(N, To);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000834 if (AddTo) {
835 // Push the new nodes and any users onto the worklist
836 for (unsigned i = 0, e = NumTo; i != e; ++i) {
Chris Lattner4147f082009-03-12 06:52:53 +0000837 if (To[i].getNode()) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000838 AddToWorklist(To[i].getNode());
839 AddUsersToWorklist(To[i].getNode());
Chris Lattner4147f082009-03-12 06:52:53 +0000840 }
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000841 }
842 }
Scott Michelcf0da6c2009-02-17 22:15:04 +0000843
Dan Gohmancd0b1bf2009-01-19 21:44:21 +0000844 // Finally, if the node is now dead, remove it from the graph. The node
845 // may not be dead if the replacement process recursively simplified to
846 // something else needing this node.
Chandler Carruth18066972014-08-02 10:02:07 +0000847 if (N->use_empty())
848 deleteAndRecombine(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +0000849 return SDValue(N, 0);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000850}
851
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000852void DAGCombiner::
853CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
Scott Michelcf0da6c2009-02-17 22:15:04 +0000854 // Replace all uses. If any nodes become isomorphic to other nodes and
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000855 // are deleted, make sure to remove them from our worklist.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000856 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000857 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
Dan Gohmane58ab792009-01-29 01:59:02 +0000858
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000859 // Push the new node and any (possibly new) users onto the worklist.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000860 AddToWorklist(TLO.New.getNode());
861 AddUsersToWorklist(TLO.New.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000862
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000863 // Finally, if the node is now dead, remove it from the graph. The node
864 // may not be dead if the replacement process recursively simplified to
865 // something else needing this node.
Chandler Carruth18066972014-08-02 10:02:07 +0000866 if (TLO.Old.getNode()->use_empty())
867 deleteAndRecombine(TLO.Old.getNode());
Dan Gohmane58ab792009-01-29 01:59:02 +0000868}
869
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000870/// Check the specified integer node value to see if it can be simplified or if
871/// things it uses can be simplified by bit propagation. If so, return true.
Dan Gohmane58ab792009-01-29 01:59:02 +0000872bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000873 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
Dan Gohmane58ab792009-01-29 01:59:02 +0000874 APInt KnownZero, KnownOne;
875 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
876 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +0000877
Dan Gohmane58ab792009-01-29 01:59:02 +0000878 // Revisit the node.
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000879 AddToWorklist(Op.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +0000880
Dan Gohmane58ab792009-01-29 01:59:02 +0000881 // Replace the old value with the new one.
882 ++NodesCombined;
Wesley Peck527da1b2010-11-23 03:31:01 +0000883 DEBUG(dbgs() << "\nReplacing.2 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000884 TLO.Old.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000885 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +0000886 TLO.New.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +0000887 dbgs() << '\n');
Scott Michelcf0da6c2009-02-17 22:15:04 +0000888
Dan Gohmane58ab792009-01-29 01:59:02 +0000889 CommitTargetLoweringOpt(TLO);
Chris Lattnerb2b9d6f2008-02-03 06:49:24 +0000890 return true;
891}
892
Evan Cheng0abb54d2010-04-24 04:43:44 +0000893void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
Andrew Trickef9de2a2013-05-25 02:42:55 +0000894 SDLoc dl(Load);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000895 EVT VT = Load->getValueType(0);
896 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
Evan Chenge19aa5c2010-04-19 19:29:22 +0000897
Evan Cheng0abb54d2010-04-24 04:43:44 +0000898 DEBUG(dbgs() << "\nReplacing.9 ";
899 Load->dump(&DAG);
900 dbgs() << "\nWith: ";
901 Trunc.getNode()->dump(&DAG);
902 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000903 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +0000904 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
905 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
Chandler Carruth18066972014-08-02 10:02:07 +0000906 deleteAndRecombine(Load);
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000907 AddToWorklist(Trunc.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000908}
909
910SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
911 Replace = false;
Andrew Trickef9de2a2013-05-25 02:42:55 +0000912 SDLoc dl(Op);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000913 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
Evan Chenge8136902010-04-27 19:48:13 +0000914 EVT MemVT = LD->getMemoryVT();
915 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000916 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
917 : ISD::EXTLOAD)
Evan Chenge8136902010-04-27 19:48:13 +0000918 : LD->getExtensionType();
Evan Cheng0abb54d2010-04-24 04:43:44 +0000919 Replace = true;
Stuart Hastings81c43062011-02-16 16:23:55 +0000920 return DAG.getExtLoad(ExtType, dl, PVT,
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000921 LD->getChain(), LD->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +0000922 MemVT, LD->getMemOperand());
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000923 }
924
Evan Chenge19aa5c2010-04-19 19:29:22 +0000925 unsigned Opc = Op.getOpcode();
Evan Chengb9ff1302010-04-23 19:10:30 +0000926 switch (Opc) {
927 default: break;
928 case ISD::AssertSext:
Evan Chenge19aa5c2010-04-19 19:29:22 +0000929 return DAG.getNode(ISD::AssertSext, dl, PVT,
Evan Cheng0abb54d2010-04-24 04:43:44 +0000930 SExtPromoteOperand(Op.getOperand(0), PVT),
Evan Chenge19aa5c2010-04-19 19:29:22 +0000931 Op.getOperand(1));
Evan Chengb9ff1302010-04-23 19:10:30 +0000932 case ISD::AssertZext:
Evan Chenge19aa5c2010-04-19 19:29:22 +0000933 return DAG.getNode(ISD::AssertZext, dl, PVT,
Evan Cheng0abb54d2010-04-24 04:43:44 +0000934 ZExtPromoteOperand(Op.getOperand(0), PVT),
Evan Chenge19aa5c2010-04-19 19:29:22 +0000935 Op.getOperand(1));
Evan Chengb9ff1302010-04-23 19:10:30 +0000936 case ISD::Constant: {
937 unsigned ExtOpc =
Evan Chenge19aa5c2010-04-19 19:29:22 +0000938 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
Evan Chengb9ff1302010-04-23 19:10:30 +0000939 return DAG.getNode(ExtOpc, dl, PVT, Op);
Wesley Peck527da1b2010-11-23 03:31:01 +0000940 }
Evan Chengb9ff1302010-04-23 19:10:30 +0000941 }
942
943 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000944 return SDValue();
Evan Chengb9ff1302010-04-23 19:10:30 +0000945 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
Evan Chengaf56fac2010-04-16 06:14:10 +0000946}
947
Evan Cheng0abb54d2010-04-24 04:43:44 +0000948SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000949 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
950 return SDValue();
951 EVT OldVT = Op.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +0000952 SDLoc dl(Op);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000953 bool Replace = false;
954 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
Craig Topperc0196b12014-04-14 00:51:57 +0000955 if (!NewOp.getNode())
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000956 return SDValue();
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000957 AddToWorklist(NewOp.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000958
959 if (Replace)
960 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
961 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000962 DAG.getValueType(OldVT));
963}
964
Evan Cheng0abb54d2010-04-24 04:43:44 +0000965SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000966 EVT OldVT = Op.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +0000967 SDLoc dl(Op);
Evan Cheng0abb54d2010-04-24 04:43:44 +0000968 bool Replace = false;
969 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
Craig Topperc0196b12014-04-14 00:51:57 +0000970 if (!NewOp.getNode())
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000971 return SDValue();
Chandler Carruth3c0012b2014-07-21 08:56:44 +0000972 AddToWorklist(NewOp.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +0000973
974 if (Replace)
975 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
976 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000977}
978
Sanjay Patel50cbfc52014-08-28 16:29:51 +0000979/// Promote the specified integer binary operation if the target indicates it is
980/// beneficial. e.g. On x86, it's usually better to promote i16 operations to
981/// i32 since i16 instructions are longer.
Evan Chengaf56fac2010-04-16 06:14:10 +0000982SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
983 if (!LegalOperations)
984 return SDValue();
985
986 EVT VT = Op.getValueType();
987 if (VT.isVector() || !VT.isInteger())
988 return SDValue();
989
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000990 // If operation type is 'undesirable', e.g. i16 on x86, consider
991 // promoting it.
992 unsigned Opc = Op.getOpcode();
993 if (TLI.isTypeDesirableForOp(Opc, VT))
994 return SDValue();
995
Evan Chengaf56fac2010-04-16 06:14:10 +0000996 EVT PVT = VT;
Evan Chengf1bd5fc2010-04-17 06:13:15 +0000997 // Consult target whether it is a good idea to promote this operation and
998 // what's the right type to promote it to.
999 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
Evan Chengaf56fac2010-04-16 06:14:10 +00001000 assert(PVT != VT && "Don't know what type to promote to!");
1001
Evan Cheng0abb54d2010-04-24 04:43:44 +00001002 bool Replace0 = false;
1003 SDValue N0 = Op.getOperand(0);
1004 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
Craig Topperc0196b12014-04-14 00:51:57 +00001005 if (!NN0.getNode())
Evan Chengf1223bd2010-04-22 20:19:46 +00001006 return SDValue();
1007
Evan Cheng0abb54d2010-04-24 04:43:44 +00001008 bool Replace1 = false;
1009 SDValue N1 = Op.getOperand(1);
Evan Cheng02947a42010-05-10 19:03:57 +00001010 SDValue NN1;
1011 if (N0 == N1)
1012 NN1 = NN0;
1013 else {
1014 NN1 = PromoteOperand(N1, PVT, Replace1);
Craig Topperc0196b12014-04-14 00:51:57 +00001015 if (!NN1.getNode())
Evan Cheng02947a42010-05-10 19:03:57 +00001016 return SDValue();
1017 }
Evan Chengf1223bd2010-04-22 20:19:46 +00001018
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001019 AddToWorklist(NN0.getNode());
Evan Cheng02947a42010-05-10 19:03:57 +00001020 if (NN1.getNode())
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001021 AddToWorklist(NN1.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +00001022
1023 if (Replace0)
1024 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1025 if (Replace1)
1026 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
Evan Chengf1223bd2010-04-22 20:19:46 +00001027
Evan Chenge8136902010-04-27 19:48:13 +00001028 DEBUG(dbgs() << "\nPromoting ";
1029 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +00001030 SDLoc dl(Op);
Evan Chengf1223bd2010-04-22 20:19:46 +00001031 return DAG.getNode(ISD::TRUNCATE, dl, VT,
Evan Cheng0abb54d2010-04-24 04:43:44 +00001032 DAG.getNode(Opc, dl, PVT, NN0, NN1));
Evan Chengf1223bd2010-04-22 20:19:46 +00001033 }
1034 return SDValue();
1035}
1036
Sanjay Patel50cbfc52014-08-28 16:29:51 +00001037/// Promote the specified integer shift operation if the target indicates it is
1038/// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1039/// i32 since i16 instructions are longer.
Evan Chengf1223bd2010-04-22 20:19:46 +00001040SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1041 if (!LegalOperations)
1042 return SDValue();
1043
1044 EVT VT = Op.getValueType();
1045 if (VT.isVector() || !VT.isInteger())
1046 return SDValue();
1047
1048 // If operation type is 'undesirable', e.g. i16 on x86, consider
1049 // promoting it.
1050 unsigned Opc = Op.getOpcode();
1051 if (TLI.isTypeDesirableForOp(Opc, VT))
1052 return SDValue();
1053
1054 EVT PVT = VT;
1055 // Consult target whether it is a good idea to promote this operation and
1056 // what's the right type to promote it to.
1057 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1058 assert(PVT != VT && "Don't know what type to promote to!");
1059
Evan Cheng0abb54d2010-04-24 04:43:44 +00001060 bool Replace = false;
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001061 SDValue N0 = Op.getOperand(0);
1062 if (Opc == ISD::SRA)
Evan Cheng0abb54d2010-04-24 04:43:44 +00001063 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001064 else if (Opc == ISD::SRL)
Evan Cheng0abb54d2010-04-24 04:43:44 +00001065 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001066 else
Evan Cheng0abb54d2010-04-24 04:43:44 +00001067 N0 = PromoteOperand(N0, PVT, Replace);
Craig Topperc0196b12014-04-14 00:51:57 +00001068 if (!N0.getNode())
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001069 return SDValue();
Evan Cheng0abb54d2010-04-24 04:43:44 +00001070
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001071 AddToWorklist(N0.getNode());
Evan Cheng0abb54d2010-04-24 04:43:44 +00001072 if (Replace)
1073 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
Evan Chengaf56fac2010-04-16 06:14:10 +00001074
Evan Chenge8136902010-04-27 19:48:13 +00001075 DEBUG(dbgs() << "\nPromoting ";
1076 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +00001077 SDLoc dl(Op);
Evan Chengaf56fac2010-04-16 06:14:10 +00001078 return DAG.getNode(ISD::TRUNCATE, dl, VT,
Evan Chengf1223bd2010-04-22 20:19:46 +00001079 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
Evan Chengaf56fac2010-04-16 06:14:10 +00001080 }
1081 return SDValue();
1082}
1083
Evan Chenge19aa5c2010-04-19 19:29:22 +00001084SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1085 if (!LegalOperations)
1086 return SDValue();
1087
1088 EVT VT = Op.getValueType();
1089 if (VT.isVector() || !VT.isInteger())
1090 return SDValue();
1091
1092 // If operation type is 'undesirable', e.g. i16 on x86, consider
1093 // promoting it.
1094 unsigned Opc = Op.getOpcode();
1095 if (TLI.isTypeDesirableForOp(Opc, VT))
1096 return SDValue();
1097
1098 EVT PVT = VT;
1099 // Consult target whether it is a good idea to promote this operation and
1100 // what's the right type to promote it to.
1101 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1102 assert(PVT != VT && "Don't know what type to promote to!");
1103 // fold (aext (aext x)) -> (aext x)
1104 // fold (aext (zext x)) -> (zext x)
1105 // fold (aext (sext x)) -> (sext x)
Evan Chenge8136902010-04-27 19:48:13 +00001106 DEBUG(dbgs() << "\nPromoting ";
1107 Op.getNode()->dump(&DAG));
Andrew Trickef9de2a2013-05-25 02:42:55 +00001108 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
Evan Chenge19aa5c2010-04-19 19:29:22 +00001109 }
1110 return SDValue();
1111}
1112
1113bool DAGCombiner::PromoteLoad(SDValue Op) {
1114 if (!LegalOperations)
1115 return false;
1116
1117 EVT VT = Op.getValueType();
1118 if (VT.isVector() || !VT.isInteger())
1119 return false;
1120
1121 // If operation type is 'undesirable', e.g. i16 on x86, consider
1122 // promoting it.
1123 unsigned Opc = Op.getOpcode();
1124 if (TLI.isTypeDesirableForOp(Opc, VT))
1125 return false;
1126
1127 EVT PVT = VT;
1128 // Consult target whether it is a good idea to promote this operation and
1129 // what's the right type to promote it to.
1130 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1131 assert(PVT != VT && "Don't know what type to promote to!");
1132
Andrew Trickef9de2a2013-05-25 02:42:55 +00001133 SDLoc dl(Op);
Evan Chenge19aa5c2010-04-19 19:29:22 +00001134 SDNode *N = Op.getNode();
1135 LoadSDNode *LD = cast<LoadSDNode>(N);
Evan Chenge8136902010-04-27 19:48:13 +00001136 EVT MemVT = LD->getMemoryVT();
1137 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00001138 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1139 : ISD::EXTLOAD)
Evan Chenge8136902010-04-27 19:48:13 +00001140 : LD->getExtensionType();
Stuart Hastings81c43062011-02-16 16:23:55 +00001141 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
Evan Chenge19aa5c2010-04-19 19:29:22 +00001142 LD->getChain(), LD->getBasePtr(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00001143 MemVT, LD->getMemOperand());
Evan Chenge19aa5c2010-04-19 19:29:22 +00001144 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1145
Evan Cheng0abb54d2010-04-24 04:43:44 +00001146 DEBUG(dbgs() << "\nPromoting ";
Evan Chenge19aa5c2010-04-19 19:29:22 +00001147 N->dump(&DAG);
Evan Cheng0abb54d2010-04-24 04:43:44 +00001148 dbgs() << "\nTo: ";
Evan Chenge19aa5c2010-04-19 19:29:22 +00001149 Result.getNode()->dump(&DAG);
1150 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001151 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001152 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1153 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
Chandler Carruth18066972014-08-02 10:02:07 +00001154 deleteAndRecombine(N);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001155 AddToWorklist(Result.getNode());
Evan Chenge19aa5c2010-04-19 19:29:22 +00001156 return true;
1157 }
1158 return false;
1159}
1160
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001161/// \brief Recursively delete a node which has no uses and any operands for
1162/// which it is the only use.
1163///
1164/// Note that this both deletes the nodes and removes them from the worklist.
1165/// It also adds any nodes who have had a user deleted to the worklist as they
1166/// may now have only one use and subject to other combines.
1167bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1168 if (!N->use_empty())
1169 return false;
1170
1171 SmallSetVector<SDNode *, 16> Nodes;
1172 Nodes.insert(N);
1173 do {
1174 N = Nodes.pop_back_val();
1175 if (!N)
1176 continue;
1177
1178 if (N->use_empty()) {
1179 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1180 Nodes.insert(N->getOperand(i).getNode());
1181
1182 removeFromWorklist(N);
1183 DAG.DeleteNode(N);
1184 } else {
1185 AddToWorklist(N);
1186 }
1187 } while (!Nodes.empty());
1188 return true;
1189}
Evan Chengf1bd5fc2010-04-17 06:13:15 +00001190
Chris Lattnere49c9742007-05-14 22:04:50 +00001191//===----------------------------------------------------------------------===//
1192// Main DAG Combiner implementation
1193//===----------------------------------------------------------------------===//
1194
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001195void DAGCombiner::Run(CombineLevel AtLevel) {
1196 // set the instance variables, so that the various visit routines may use it.
1197 Level = AtLevel;
Eli Friedman9d448e42011-11-12 00:35:34 +00001198 LegalOperations = Level >= AfterLegalizeVectorOps;
1199 LegalTypes = Level >= AfterLegalizeTypes;
Nate Begeman2504fe22005-09-01 23:24:04 +00001200
Evan Cheng5e7658c2008-08-29 22:21:44 +00001201 // Add all the dag nodes to the worklist.
Evan Cheng5e7658c2008-08-29 22:21:44 +00001202 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1203 E = DAG.allnodes_end(); I != E; ++I)
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001204 AddToWorklist(I);
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001205
Evan Cheng5e7658c2008-08-29 22:21:44 +00001206 // Create a dummy node (which is not added to allnodes), that adds a reference
1207 // to the root node, preventing it from being deleted, and tracking any
1208 // changes of the root.
1209 HandleSDNode Dummy(DAG.getRoot());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001210
James Molloy67b6b112012-02-16 09:17:04 +00001211 // while the worklist isn't empty, find a node and
Evan Cheng5e7658c2008-08-29 22:21:44 +00001212 // try and combine it.
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001213 while (!WorklistMap.empty()) {
James Molloy67b6b112012-02-16 09:17:04 +00001214 SDNode *N;
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001215 // The Worklist holds the SDNodes in order, but it may contain null entries.
James Molloy67b6b112012-02-16 09:17:04 +00001216 do {
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001217 N = Worklist.pop_back_val();
1218 } while (!N);
1219
1220 bool GoodWorklistEntry = WorklistMap.erase(N);
1221 (void)GoodWorklistEntry;
1222 assert(GoodWorklistEntry &&
1223 "Found a worklist entry without a corresponding map entry!");
Scott Michelcf0da6c2009-02-17 22:15:04 +00001224
Evan Cheng5e7658c2008-08-29 22:21:44 +00001225 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1226 // N is deleted from the DAG, since they too may now be dead or may have a
1227 // reduced number of uses, allowing other xforms.
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001228 if (recursivelyDeleteUnusedNodes(N))
Evan Cheng5e7658c2008-08-29 22:21:44 +00001229 continue;
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001230
1231 WorklistRemover DeadNodes(*this);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001232
Chandler Carruth411fb402014-07-26 05:49:40 +00001233 // If this combine is running after legalizing the DAG, re-legalize any
1234 // nodes pulled off the worklist.
1235 if (Level == AfterLegalizeDAG) {
1236 SmallSetVector<SDNode *, 16> UpdatedNodes;
1237 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1238
1239 for (SDNode *LN : UpdatedNodes) {
1240 AddToWorklist(LN);
1241 AddUsersToWorklist(LN);
1242 }
1243 if (!NIsValid)
1244 continue;
1245 }
1246
Chandler Carruthb1432742014-07-28 17:55:07 +00001247 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1248
Chandler Carruthcde4eb52014-08-03 23:10:59 +00001249 // Add any operands of the new node which have not yet been combined to the
1250 // worklist as well. Because the worklist uniques things already, this
1251 // won't repeatedly process the same operand.
1252 CombinedNodes.insert(N);
1253 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1254 if (!CombinedNodes.count(N->getOperand(i).getNode()))
1255 AddToWorklist(N->getOperand(i).getNode());
1256
Evan Cheng5e7658c2008-08-29 22:21:44 +00001257 SDValue RV = combine(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001258
Craig Topperc0196b12014-04-14 00:51:57 +00001259 if (!RV.getNode())
Evan Cheng5e7658c2008-08-29 22:21:44 +00001260 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001261
Evan Cheng5e7658c2008-08-29 22:21:44 +00001262 ++NodesCombined;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001263
Evan Cheng5e7658c2008-08-29 22:21:44 +00001264 // If we get back the same node we passed in, rather than a new node or
1265 // zero, we know that the node must have defined multiple values and
Scott Michelcf0da6c2009-02-17 22:15:04 +00001266 // CombineTo was used. Since CombineTo takes care of the worklist
Evan Cheng5e7658c2008-08-29 22:21:44 +00001267 // mechanics for us, we have no work to do in this case.
1268 if (RV.getNode() == N)
1269 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001270
Evan Cheng5e7658c2008-08-29 22:21:44 +00001271 assert(N->getOpcode() != ISD::DELETED_NODE &&
1272 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1273 "Node was deleted but visit returned new node!");
Chris Lattner8f872d22006-05-27 00:43:02 +00001274
Chandler Carruth9f4530b2014-07-24 22:15:28 +00001275 DEBUG(dbgs() << " ... into: ";
1276 RV.getNode()->dump(&DAG));
Eric Christopherd6300d22011-07-14 01:12:15 +00001277
Devang Patelefec7712011-05-23 22:04:42 +00001278 // Transfer debug value.
1279 DAG.TransferDbgValues(SDValue(N, 0), RV);
Evan Cheng5e7658c2008-08-29 22:21:44 +00001280 if (N->getNumValues() == RV.getNode()->getNumValues())
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001281 DAG.ReplaceAllUsesWith(N, RV.getNode());
Evan Cheng5e7658c2008-08-29 22:21:44 +00001282 else {
1283 assert(N->getValueType(0) == RV.getValueType() &&
1284 N->getNumValues() == 1 && "Type mismatch");
1285 SDValue OpV = RV;
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001286 DAG.ReplaceAllUsesWith(N, &OpV);
Evan Cheng5e7658c2008-08-29 22:21:44 +00001287 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001288
Evan Cheng5e7658c2008-08-29 22:21:44 +00001289 // Push the new node and any users onto the worklist
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001290 AddToWorklist(RV.getNode());
1291 AddUsersToWorklist(RV.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +00001292
Dan Gohmancd0b1bf2009-01-19 21:44:21 +00001293 // Finally, if the node is now dead, remove it from the graph. The node
1294 // may not be dead if the replacement process recursively simplified to
Chandler Carruth9a0051c2014-07-23 07:08:53 +00001295 // something else needing this node. This will also take care of adding any
1296 // operands which have lost a user to the worklist.
1297 recursivelyDeleteUnusedNodes(N);
Evan Cheng5e7658c2008-08-29 22:21:44 +00001298 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001299
Chris Lattner06f1d0f2005-10-05 06:35:28 +00001300 // If the root changed (e.g. it was a dead load, update the root).
1301 DAG.setRoot(Dummy.getValue());
Hal Finkele0cf6392012-04-16 03:33:22 +00001302 DAG.RemoveDeadNodes();
Nate Begeman21158fc2005-09-01 00:19:25 +00001303}
1304
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001305SDValue DAGCombiner::visit(SDNode *N) {
Evan Chengf1005572010-04-28 07:10:39 +00001306 switch (N->getOpcode()) {
Nate Begeman21158fc2005-09-01 00:19:25 +00001307 default: break;
Nate Begemane8f78d12005-09-01 00:33:32 +00001308 case ISD::TokenFactor: return visitTokenFactor(N);
Chris Lattneree322b42008-02-13 07:25:05 +00001309 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001310 case ISD::ADD: return visitADD(N);
1311 case ISD::SUB: return visitSUB(N);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001312 case ISD::ADDC: return visitADDC(N);
Craig Topper43a1bd62012-01-07 09:06:39 +00001313 case ISD::SUBC: return visitSUBC(N);
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001314 case ISD::ADDE: return visitADDE(N);
Craig Topper43a1bd62012-01-07 09:06:39 +00001315 case ISD::SUBE: return visitSUBE(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001316 case ISD::MUL: return visitMUL(N);
1317 case ISD::SDIV: return visitSDIV(N);
1318 case ISD::UDIV: return visitUDIV(N);
1319 case ISD::SREM: return visitSREM(N);
1320 case ISD::UREM: return visitUREM(N);
1321 case ISD::MULHU: return visitMULHU(N);
1322 case ISD::MULHS: return visitMULHS(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001323 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1324 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00001325 case ISD::SMULO: return visitSMULO(N);
1326 case ISD::UMULO: return visitUMULO(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001327 case ISD::SDIVREM: return visitSDIVREM(N);
1328 case ISD::UDIVREM: return visitUDIVREM(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001329 case ISD::AND: return visitAND(N);
1330 case ISD::OR: return visitOR(N);
1331 case ISD::XOR: return visitXOR(N);
1332 case ISD::SHL: return visitSHL(N);
1333 case ISD::SRA: return visitSRA(N);
1334 case ISD::SRL: return visitSRL(N);
Adam Nemet7f928f12014-03-07 23:56:30 +00001335 case ISD::ROTR:
1336 case ISD::ROTL: return visitRotate(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001337 case ISD::CTLZ: return visitCTLZ(N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00001338 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001339 case ISD::CTTZ: return visitCTTZ(N);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00001340 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001341 case ISD::CTPOP: return visitCTPOP(N);
Nate Begeman24a7eca2005-09-16 00:54:12 +00001342 case ISD::SELECT: return visitSELECT(N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00001343 case ISD::VSELECT: return visitVSELECT(N);
Nate Begeman24a7eca2005-09-16 00:54:12 +00001344 case ISD::SELECT_CC: return visitSELECT_CC(N);
1345 case ISD::SETCC: return visitSETCC(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001346 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1347 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
Chris Lattner812646a2006-05-05 05:58:59 +00001348 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001349 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1350 case ISD::TRUNCATE: return visitTRUNCATE(N);
Wesley Peck527da1b2010-11-23 03:31:01 +00001351 case ISD::BITCAST: return visitBITCAST(N);
Evan Chengb980f6f2008-05-12 23:04:07 +00001352 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
Chris Lattner6f3b5772005-09-28 22:28:18 +00001353 case ISD::FADD: return visitFADD(N);
1354 case ISD::FSUB: return visitFSUB(N);
1355 case ISD::FMUL: return visitFMUL(N);
Owen Anderson41b06652012-05-02 22:17:40 +00001356 case ISD::FMA: return visitFMA(N);
Chris Lattner6f3b5772005-09-28 22:28:18 +00001357 case ISD::FDIV: return visitFDIV(N);
1358 case ISD::FREM: return visitFREM(N);
Sanjay Patelbdf1e382014-09-26 23:01:47 +00001359 case ISD::FSQRT: return visitFSQRT(N);
Chris Lattner3bc40502006-03-05 05:30:57 +00001360 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001361 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1362 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1363 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1364 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1365 case ISD::FP_ROUND: return visitFP_ROUND(N);
1366 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1367 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1368 case ISD::FNEG: return visitFNEG(N);
1369 case ISD::FABS: return visitFABS(N);
Owen Andersona40319b2012-08-13 23:32:49 +00001370 case ISD::FFLOOR: return visitFFLOOR(N);
Matt Arsenault7c936902014-10-21 23:01:01 +00001371 case ISD::FMINNUM: return visitFMINNUM(N);
1372 case ISD::FMAXNUM: return visitFMAXNUM(N);
Owen Andersona40319b2012-08-13 23:32:49 +00001373 case ISD::FCEIL: return visitFCEIL(N);
1374 case ISD::FTRUNC: return visitFTRUNC(N);
Nate Begemanc760f802005-09-19 22:34:01 +00001375 case ISD::BRCOND: return visitBRCOND(N);
Nate Begemanc760f802005-09-19 22:34:01 +00001376 case ISD::BR_CC: return visitBR_CC(N);
Chris Lattnere260ed82005-10-10 22:04:48 +00001377 case ISD::LOAD: return visitLOAD(N);
Chris Lattner04c73702005-10-10 22:31:19 +00001378 case ISD::STORE: return visitSTORE(N);
Chris Lattner5336a592006-03-19 01:27:56 +00001379 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
Evan Cheng0de312d2007-10-06 08:19:55 +00001380 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
Dan Gohmana8665142007-06-25 16:23:39 +00001381 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1382 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +00001383 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
Chris Lattnera46dfe82006-03-28 22:11:53 +00001384 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
Simon Pilgrimbede80a2015-03-07 05:52:42 +00001385 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N);
Manman Ren413a6cb2014-01-31 01:10:35 +00001386 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
Elena Demikhovskye1eda8a2015-04-30 08:38:48 +00001387 case ISD::MGATHER: return visitMGATHER(N);
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00001388 case ISD::MLOAD: return visitMLOAD(N);
Elena Demikhovskye1eda8a2015-04-30 08:38:48 +00001389 case ISD::MSCATTER: return visitMSCATTER(N);
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00001390 case ISD::MSTORE: return visitMSTORE(N);
Pirama Arumuga Nainardb7c07e22015-04-17 18:36:25 +00001391 case ISD::FP_TO_FP16: return visitFP_TO_FP16(N);
Nate Begeman21158fc2005-09-01 00:19:25 +00001392 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001393 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001394}
1395
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001396SDValue DAGCombiner::combine(SDNode *N) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001397 SDValue RV = visit(N);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001398
1399 // If nothing happened, try a target-specific DAG combine.
Craig Topperc0196b12014-04-14 00:51:57 +00001400 if (!RV.getNode()) {
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001401 assert(N->getOpcode() != ISD::DELETED_NODE &&
1402 "Node was deleted but visit returned NULL!");
1403
1404 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1405 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1406
1407 // Expose the DAG combiner to the target combiner impls.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001408 TargetLowering::DAGCombinerInfo
Nadav Rotemb1dd5242012-12-27 06:47:41 +00001409 DagCombineInfo(DAG, Level, false, this);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001410
1411 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1412 }
1413 }
1414
Evan Chengf1005572010-04-28 07:10:39 +00001415 // If nothing happened still, try promoting the operation.
Craig Topperc0196b12014-04-14 00:51:57 +00001416 if (!RV.getNode()) {
Evan Chengf1005572010-04-28 07:10:39 +00001417 switch (N->getOpcode()) {
1418 default: break;
1419 case ISD::ADD:
1420 case ISD::SUB:
1421 case ISD::MUL:
1422 case ISD::AND:
1423 case ISD::OR:
1424 case ISD::XOR:
1425 RV = PromoteIntBinOp(SDValue(N, 0));
1426 break;
1427 case ISD::SHL:
1428 case ISD::SRA:
1429 case ISD::SRL:
1430 RV = PromoteIntShiftOp(SDValue(N, 0));
1431 break;
1432 case ISD::SIGN_EXTEND:
1433 case ISD::ZERO_EXTEND:
1434 case ISD::ANY_EXTEND:
1435 RV = PromoteExtend(SDValue(N, 0));
1436 break;
1437 case ISD::LOAD:
1438 if (PromoteLoad(SDValue(N, 0)))
1439 RV = SDValue(N, 0);
1440 break;
1441 }
1442 }
1443
Scott Michelcf0da6c2009-02-17 22:15:04 +00001444 // If N is a commutative binary node, try commuting it to enable more
Evan Cheng31604a62008-03-22 01:55:50 +00001445 // sdisel CSE.
Craig Topperc0196b12014-04-14 00:51:57 +00001446 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
Evan Cheng31604a62008-03-22 01:55:50 +00001447 N->getNumValues() == 1) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001448 SDValue N0 = N->getOperand(0);
1449 SDValue N1 = N->getOperand(1);
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001450
Evan Cheng31604a62008-03-22 01:55:50 +00001451 // Constant operands are canonicalized to RHS.
1452 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
Andrea Di Biagio4db1abe2014-06-09 12:32:53 +00001453 SDValue Ops[] = {N1, N0};
1454 SDNode *CSENode;
Nick Lewycky37a17502015-05-13 23:41:47 +00001455 if (const BinaryWithFlagsSDNode *BinNode =
1456 dyn_cast<BinaryWithFlagsSDNode>(N)) {
NAKAMURA Takumid7c0be92015-05-06 14:03:12 +00001457 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
Nick Lewycky37a17502015-05-13 23:41:47 +00001458 BinNode->Flags.hasNoUnsignedWrap(),
1459 BinNode->Flags.hasNoSignedWrap(),
1460 BinNode->Flags.hasExact());
Andrea Di Biagio4db1abe2014-06-09 12:32:53 +00001461 } else {
1462 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1463 }
Evan Chengfe7610f2008-03-24 23:55:16 +00001464 if (CSENode)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001465 return SDValue(CSENode, 0);
Evan Cheng31604a62008-03-22 01:55:50 +00001466 }
1467 }
1468
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001469 return RV;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001470}
Dan Gohman5c6d0c32007-10-08 17:57:15 +00001471
Sanjay Patel50cbfc52014-08-28 16:29:51 +00001472/// Given a node, return its input chain if it has one, otherwise return a null
1473/// sd operand.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001474static SDValue getInputChainForNode(SDNode *N) {
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001475 if (unsigned NumOps = N->getNumOperands()) {
Owen Anderson9f944592009-08-11 20:47:22 +00001476 if (N->getOperand(0).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001477 return N->getOperand(0);
Stephen Lin8e8424e2013-07-09 00:44:49 +00001478 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001479 return N->getOperand(NumOps-1);
1480 for (unsigned i = 1; i < NumOps-1; ++i)
Owen Anderson9f944592009-08-11 20:47:22 +00001481 if (N->getOperand(i).getValueType() == MVT::Other)
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001482 return N->getOperand(i);
1483 }
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001484 return SDValue();
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001485}
1486
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001487SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001488 // If N has two operands, where one has an input chain equal to the other,
1489 // the 'other' chain is redundant.
1490 if (N->getNumOperands() == 2) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00001491 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001492 return N->getOperand(0);
Gabor Greiff304a7a2008-08-28 21:40:38 +00001493 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
Chris Lattner5ab6d8b2006-10-08 22:57:01 +00001494 return N->getOperand(1);
1495 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001496
Chris Lattner48fb92f2007-05-16 06:37:59 +00001497 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001498 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001499 SmallPtrSet<SDNode*, 16> SeenOps;
Chris Lattner48fb92f2007-05-16 06:37:59 +00001500 bool Changed = false; // If we should replace this token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +00001501
Jim Laskey708d0db2006-10-04 16:53:27 +00001502 // Start out with this token factor.
Jim Laskeyd07be232006-09-25 16:29:54 +00001503 TFs.push_back(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001504
Jim Laskey0463e082006-10-07 23:37:56 +00001505 // Iterate through token factors. The TFs grows when new token factors are
Jim Laskey6549d222006-10-05 15:07:25 +00001506 // encountered.
1507 for (unsigned i = 0; i < TFs.size(); ++i) {
1508 SDNode *TF = TFs[i];
Scott Michelcf0da6c2009-02-17 22:15:04 +00001509
Jim Laskey708d0db2006-10-04 16:53:27 +00001510 // Check each of the operands.
1511 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001512 SDValue Op = TF->getOperand(i);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001513
Jim Laskey708d0db2006-10-04 16:53:27 +00001514 switch (Op.getOpcode()) {
1515 case ISD::EntryToken:
Jim Laskey6549d222006-10-05 15:07:25 +00001516 // Entry tokens don't need to be added to the list. They are
Jonas Paulssona25a3f42015-02-10 15:34:29 +00001517 // redundant.
Jim Laskey6549d222006-10-05 15:07:25 +00001518 Changed = true;
Jim Laskey708d0db2006-10-04 16:53:27 +00001519 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +00001520
Jim Laskey708d0db2006-10-04 16:53:27 +00001521 case ISD::TokenFactor:
Nate Begeman879d8f12009-09-15 00:18:30 +00001522 if (Op.hasOneUse() &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00001523 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
Jim Laskey708d0db2006-10-04 16:53:27 +00001524 // Queue up for processing.
Gabor Greiff304a7a2008-08-28 21:40:38 +00001525 TFs.push_back(Op.getNode());
Jim Laskey708d0db2006-10-04 16:53:27 +00001526 // Clean up in case the token factor is removed.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001527 AddToWorklist(Op.getNode());
Jim Laskey708d0db2006-10-04 16:53:27 +00001528 Changed = true;
1529 break;
Jim Laskeyd07be232006-09-25 16:29:54 +00001530 }
Jim Laskey708d0db2006-10-04 16:53:27 +00001531 // Fall thru
Scott Michelcf0da6c2009-02-17 22:15:04 +00001532
Jim Laskey708d0db2006-10-04 16:53:27 +00001533 default:
Chris Lattner48fb92f2007-05-16 06:37:59 +00001534 // Only add if it isn't already in the list.
David Blaikie70573dc2014-11-19 07:49:26 +00001535 if (SeenOps.insert(Op.getNode()).second)
Jim Laskey6549d222006-10-05 15:07:25 +00001536 Ops.push_back(Op);
Chris Lattner48fb92f2007-05-16 06:37:59 +00001537 else
1538 Changed = true;
Jim Laskey708d0db2006-10-04 16:53:27 +00001539 break;
Jim Laskeyd07be232006-09-25 16:29:54 +00001540 }
1541 }
Jim Laskey708d0db2006-10-04 16:53:27 +00001542 }
Wesley Peck527da1b2010-11-23 03:31:01 +00001543
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001544 SDValue Result;
Jim Laskey708d0db2006-10-04 16:53:27 +00001545
Jonas Paulssona25a3f42015-02-10 15:34:29 +00001546 // If we've changed things around then replace token factor.
Jim Laskey708d0db2006-10-04 16:53:27 +00001547 if (Changed) {
Dan Gohman70de4cb2008-01-29 13:02:09 +00001548 if (Ops.empty()) {
Jim Laskey708d0db2006-10-04 16:53:27 +00001549 // The entry token is the only possible outcome.
1550 Result = DAG.getEntryNode();
1551 } else {
1552 // New and improved token factor.
Craig Topper48d114b2014-04-26 18:35:24 +00001553 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
Nate Begeman02b23c62005-10-13 03:11:28 +00001554 }
Bill Wendling9c9a3b62009-01-30 01:13:16 +00001555
Jonas Paulssonbf8d0cc2015-02-11 16:10:31 +00001556 // Add users to worklist if AA is enabled, since it may introduce
1557 // a lot of new chained token factors while removing memory deps.
1558 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1559 : DAG.getSubtarget().useAA();
1560 return CombineTo(N, Result, UseAA /*add to worklist*/);
Nate Begeman02b23c62005-10-13 03:11:28 +00001561 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001562
Jim Laskey708d0db2006-10-04 16:53:27 +00001563 return Result;
Nate Begeman21158fc2005-09-01 00:19:25 +00001564}
1565
Chris Lattneree322b42008-02-13 07:25:05 +00001566/// MERGE_VALUES can always be eliminated.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001567SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001568 WorklistRemover DeadNodes(*this);
Dan Gohman9d26c852009-08-10 23:43:19 +00001569 // Replacing results may cause a different MERGE_VALUES to suddenly
1570 // be CSE'd with N, and carry its uses with it. Iterate until no
1571 // uses remain, to ensure that the node can be safely deleted.
Pete Cooperfe5b84b2012-06-20 19:35:43 +00001572 // First add the users of this node to the work list so that they
1573 // can be tried again once they have new operands.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00001574 AddUsersToWorklist(N);
Dan Gohman9d26c852009-08-10 23:43:19 +00001575 do {
1576 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00001577 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
Dan Gohman9d26c852009-08-10 23:43:19 +00001578 } while (!N->use_empty());
Chandler Carruth18066972014-08-02 10:02:07 +00001579 deleteAndRecombine(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001580 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattneree322b42008-02-13 07:25:05 +00001581}
1582
Matthias Braun1505efb2015-05-18 23:07:27 +00001583static bool isNullConstant(SDValue V) {
1584 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1585 return Const != nullptr && Const->isNullValue();
1586}
1587
Matthias Braun03312192015-05-19 00:25:20 +00001588static bool isAllOnesConstant(SDValue V) {
1589 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1590 return Const != nullptr && Const->isAllOnesValue();
1591}
1592
Matthias Braun887fdfb2015-05-19 00:25:21 +00001593static bool isOneConstant(SDValue V) {
1594 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1595 return Const != nullptr && Const->isOne();
1596}
1597
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001598SDValue DAGCombiner::visitADD(SDNode *N) {
1599 SDValue N0 = N->getOperand(0);
1600 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001601 EVT VT = N0.getValueType();
Dan Gohmana8665142007-06-25 16:23:39 +00001602
1603 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00001604 if (VT.isVector()) {
Simon Pilgrimdcbe1212015-03-29 19:13:40 +00001605 if (SDValue FoldedVOp = SimplifyVBinOp(N))
1606 return FoldedVOp;
Craig Topperd8005db2012-12-10 08:12:29 +00001607
1608 // fold (add x, 0) -> x, vector edition
1609 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1610 return N0;
1611 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1612 return N1;
Dan Gohman80f9f072007-07-13 20:03:40 +00001613 }
Bill Wendling0864a752008-12-10 22:36:00 +00001614
Dan Gohman06563a82007-07-03 14:03:57 +00001615 // fold (add x, undef) -> undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00001616 if (N0.getOpcode() == ISD::UNDEF)
1617 return N0;
1618 if (N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00001619 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00001620 // fold (add c1, c2) -> c1+c2
Matthias Braun00a40762015-02-24 18:52:01 +00001621 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1622 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001623 if (N0C && N1C)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001624 return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00001625 // canonicalize constant to RHS
Simon Pilgrim20b7aba2015-04-04 10:20:31 +00001626 if (isConstantIntBuildVectorOrConstantInt(N0) &&
1627 !isConstantIntBuildVectorOrConstantInt(N1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001628 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00001629 // fold (add x, 0) -> x
Matthias Braun1505efb2015-05-18 23:07:27 +00001630 if (isNullConstant(N1))
Nate Begemand23739d2005-09-06 04:43:02 +00001631 return N0;
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001632 // fold (add Sym, c) -> Sym+c
1633 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001634 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001635 GA->getOpcode() == ISD::GlobalAddress)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001636 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001637 GA->getOffset() +
1638 (uint64_t)N1C->getSExtValue());
Chris Lattner3470b5d2006-01-12 20:22:43 +00001639 // fold ((c1-A)+c2) -> (c1+c2)-A
1640 if (N1C && N0.getOpcode() == ISD::SUB)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001641 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0))) {
1642 SDLoc DL(N);
1643 return DAG.getNode(ISD::SUB, DL, VT,
Dan Gohmanb72127a2008-03-13 22:13:53 +00001644 DAG.getConstant(N1C->getAPIntValue()+
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001645 N0C->getAPIntValue(), DL, VT),
Chris Lattner3470b5d2006-01-12 20:22:43 +00001646 N0.getOperand(1));
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001647 }
Nate Begeman22e251a2006-02-03 06:46:56 +00001648 // reassociate add
Simon Pilgrimd15c2802015-03-29 16:49:51 +00001649 if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1))
Nate Begeman22e251a2006-02-03 06:46:56 +00001650 return RADD;
Nate Begeman21158fc2005-09-01 00:19:25 +00001651 // fold ((0-A) + B) -> B-A
Matthias Braun1505efb2015-05-18 23:07:27 +00001652 if (N0.getOpcode() == ISD::SUB && isNullConstant(N0.getOperand(0)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001653 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
Nate Begeman21158fc2005-09-01 00:19:25 +00001654 // fold (A + (0-B)) -> A-B
Matthias Braun1505efb2015-05-18 23:07:27 +00001655 if (N1.getOpcode() == ISD::SUB && isNullConstant(N1.getOperand(0)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001656 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
Chris Lattner6f3b5772005-09-28 22:28:18 +00001657 // fold (A+(B-A)) -> B
1658 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
Nate Begemand23739d2005-09-06 04:43:02 +00001659 return N1.getOperand(0);
Dale Johannesen73bc0ba2008-11-27 00:43:21 +00001660 // fold ((B-A)+A) -> B
1661 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1662 return N0.getOperand(0);
Dale Johannesen8c766702008-12-02 01:30:54 +00001663 // fold (A+(B-(A+C))) to (B-C)
1664 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001665 N0 == N1.getOperand(1).getOperand(0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001666 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
Dale Johannesen8c766702008-12-02 01:30:54 +00001667 N1.getOperand(1).getOperand(1));
Dale Johannesen8c766702008-12-02 01:30:54 +00001668 // fold (A+(B-(C+A))) to (B-C)
1669 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001670 N0 == N1.getOperand(1).getOperand(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001671 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
Dale Johannesen8c766702008-12-02 01:30:54 +00001672 N1.getOperand(1).getOperand(0));
Dale Johannesenee573fc2008-12-23 23:47:22 +00001673 // fold (A+((B-A)+or-C)) to (B+or-C)
Dale Johannesen54bdec22008-12-02 18:40:40 +00001674 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1675 N1.getOperand(0).getOpcode() == ISD::SUB &&
Bill Wendlingc4423482009-01-30 02:31:17 +00001676 N0 == N1.getOperand(0).getOperand(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001677 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
Bill Wendlingc4423482009-01-30 02:31:17 +00001678 N1.getOperand(0).getOperand(0), N1.getOperand(1));
Dale Johannesen54bdec22008-12-02 18:40:40 +00001679
Dale Johannesen8c766702008-12-02 01:30:54 +00001680 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1681 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1682 SDValue N00 = N0.getOperand(0);
1683 SDValue N01 = N0.getOperand(1);
1684 SDValue N10 = N1.getOperand(0);
1685 SDValue N11 = N1.getOperand(1);
Bill Wendlingc4423482009-01-30 02:31:17 +00001686
1687 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001688 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1689 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1690 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
Dale Johannesen8c766702008-12-02 01:30:54 +00001691 }
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001692
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001693 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1694 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001695
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001696 // fold (a+b) -> (a|b) iff a and b share no bits.
Duncan Sands13237ac2008-06-06 12:08:01 +00001697 if (VT.isInteger() && !VT.isVector()) {
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001698 APInt LHSZero, LHSOne;
1699 APInt RHSZero, RHSOne;
Jay Foada0653a32014-05-14 21:14:37 +00001700 DAG.computeKnownBits(N0, LHSZero, LHSOne);
Bill Wendlingc4423482009-01-30 02:31:17 +00001701
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001702 if (LHSZero.getBoolValue()) {
Jay Foada0653a32014-05-14 21:14:37 +00001703 DAG.computeKnownBits(N1, RHSZero, RHSOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001704
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001705 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1706 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
Owen Anderson60a46782014-01-31 00:51:43 +00001707 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1708 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1709 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1710 }
Chris Lattnerd8c2a48d2006-03-13 06:51:27 +00001711 }
1712 }
Evan Chengeb99bd72006-11-06 08:14:30 +00001713
Dan Gohman954f4902010-01-19 23:30:49 +00001714 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
Matthias Braun0542b5d2015-05-19 00:25:17 +00001715 if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
1716 isNullConstant(N1.getOperand(0).getOperand(0)))
1717 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1718 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1719 N1.getOperand(0).getOperand(1),
1720 N1.getOperand(1)));
1721 if (N0.getOpcode() == ISD::SHL && N0.getOperand(0).getOpcode() == ISD::SUB &&
1722 isNullConstant(N0.getOperand(0).getOperand(0)))
1723 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1724 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1725 N0.getOperand(0).getOperand(1),
1726 N0.getOperand(1)));
Dan Gohman954f4902010-01-19 23:30:49 +00001727
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001728 if (N1.getOpcode() == ISD::AND) {
1729 SDValue AndOp0 = N1.getOperand(0);
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001730 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1731 unsigned DestBits = VT.getScalarType().getSizeInBits();
Wesley Peck527da1b2010-11-23 03:31:01 +00001732
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001733 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1734 // and similar xforms where the inner op is either ~0 or 0.
Matthias Braun887fdfb2015-05-19 00:25:21 +00001735 if (NumSignBits == DestBits && isOneConstant(N1->getOperand(1))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001736 SDLoc DL(N);
Owen Anderson5e65dfb2010-09-21 20:42:50 +00001737 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1738 }
1739 }
1740
Benjamin Kramer1f4dfbb2010-12-22 23:17:45 +00001741 // add (sext i1), X -> sub X, (zext i1)
1742 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1743 N0.getOperand(0).getValueType() == MVT::i1 &&
1744 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00001745 SDLoc DL(N);
Benjamin Kramer1f4dfbb2010-12-22 23:17:45 +00001746 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1747 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1748 }
1749
Jan Veselyaf62cf42014-10-17 14:45:25 +00001750 // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1751 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1752 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1753 if (TN->getVT() == MVT::i1) {
1754 SDLoc DL(N);
1755 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001756 DAG.getConstant(1, DL, VT));
Jan Veselyaf62cf42014-10-17 14:45:25 +00001757 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1758 }
1759 }
1760
Evan Chengf1005572010-04-28 07:10:39 +00001761 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001762}
1763
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001764SDValue DAGCombiner::visitADDC(SDNode *N) {
1765 SDValue N0 = N->getOperand(0);
1766 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001767 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001768
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001769 // If the flag result is dead, turn this into an ADD.
Craig Topper0515cd42012-01-07 18:31:09 +00001770 if (!N->hasAnyUseOfValue(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001771 return CombineTo(N, DAG.getNode(ISD::ADD, 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));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001774
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001775 // canonicalize constant to RHS.
Matthias Braun00a40762015-02-24 18:52:01 +00001776 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1777 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Dan Gohmanb4e26372008-06-23 15:29:14 +00001778 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001779 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001780
Chris Lattner47206662007-03-04 20:40:38 +00001781 // fold (addc x, 0) -> x + no carry out
Matthias Braun1505efb2015-05-18 23:07:27 +00001782 if (isNullConstant(N1))
Dale Johannesen5234d372009-06-02 03:12:52 +00001783 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001784 SDLoc(N), MVT::Glue));
Scott Michelcf0da6c2009-02-17 22:15:04 +00001785
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001786 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001787 APInt LHSZero, LHSOne;
1788 APInt RHSZero, RHSOne;
Jay Foada0653a32014-05-14 21:14:37 +00001789 DAG.computeKnownBits(N0, LHSZero, LHSOne);
Bill Wendling61277572009-01-30 02:38:00 +00001790
Dan Gohmand0ff91d2008-02-20 16:33:30 +00001791 if (LHSZero.getBoolValue()) {
Jay Foada0653a32014-05-14 21:14:37 +00001792 DAG.computeKnownBits(N1, RHSZero, RHSOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001793
Chris Lattner47206662007-03-04 20:40:38 +00001794 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1795 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00001796 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001797 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
Dale Johannesen5234d372009-06-02 03:12:52 +00001798 DAG.getNode(ISD::CARRY_FALSE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00001799 SDLoc(N), MVT::Glue));
Chris Lattner47206662007-03-04 20:40:38 +00001800 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00001801
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001802 return SDValue();
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001803}
1804
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001805SDValue DAGCombiner::visitADDE(SDNode *N) {
1806 SDValue N0 = N->getOperand(0);
1807 SDValue N1 = N->getOperand(1);
1808 SDValue CarryIn = N->getOperand(2);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001809
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001810 // canonicalize constant to RHS
Matthias Braun00a40762015-02-24 18:52:01 +00001811 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1812 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Dan Gohmanb4e26372008-06-23 15:29:14 +00001813 if (N0C && !N1C)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001814 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
Bill Wendling61277572009-01-30 02:38:00 +00001815 N1, N0, CarryIn);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001816
Chris Lattner47206662007-03-04 20:40:38 +00001817 // fold (adde x, y, false) -> (addc x, y)
Dale Johannesen5234d372009-06-02 03:12:52 +00001818 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001819 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00001820
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001821 return SDValue();
Chris Lattnere2e13ca2007-03-04 20:03:15 +00001822}
1823
Eric Christophere5ca1e02011-02-16 04:50:12 +00001824// Since it may not be valid to emit a fold to zero for vector initializers
1825// check if we can before folding.
Andrew Trickef9de2a2013-05-25 02:42:55 +00001826static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
Hal Finkel6c29bd92013-07-09 17:02:45 +00001827 SelectionDAG &DAG,
1828 bool LegalOperations, bool LegalTypes) {
Stephen Lin8e8424e2013-07-09 00:44:49 +00001829 if (!VT.isVector())
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001830 return DAG.getConstant(0, DL, VT);
Daniel Sandersb021c6f2013-11-25 11:14:43 +00001831 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001832 return DAG.getConstant(0, DL, VT);
Eric Christophere5ca1e02011-02-16 04:50:12 +00001833 return SDValue();
1834}
1835
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001836SDValue DAGCombiner::visitSUB(SDNode *N) {
1837 SDValue N0 = N->getOperand(0);
1838 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001839 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001840
Dan Gohmana8665142007-06-25 16:23:39 +00001841 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00001842 if (VT.isVector()) {
Simon Pilgrimdcbe1212015-03-29 19:13:40 +00001843 if (SDValue FoldedVOp = SimplifyVBinOp(N))
1844 return FoldedVOp;
Craig Topperd8005db2012-12-10 08:12:29 +00001845
1846 // fold (sub x, 0) -> x, vector edition
1847 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1848 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00001849 }
Bill Wendling0864a752008-12-10 22:36:00 +00001850
Chris Lattnereeb2bda2005-10-17 01:07:11 +00001851 // fold (sub x, x) -> 0
Eric Christopheref721412011-02-16 01:10:03 +00001852 // FIXME: Refactor this and xor and other similar operations together.
Eric Christophere5ca1e02011-02-16 04:50:12 +00001853 if (N0 == N1)
Hal Finkel6c29bd92013-07-09 17:02:45 +00001854 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
Nate Begeman21158fc2005-09-01 00:19:25 +00001855 // fold (sub c1, c2) -> c1-c2
Matthias Braun00a40762015-02-24 18:52:01 +00001856 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1857 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
Nate Begeman7cea6ef2005-09-02 21:18:40 +00001858 if (N0C && N1C)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001859 return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT, N0C, N1C);
Chris Lattnerc38fb8e2005-10-11 06:07:15 +00001860 // fold (sub x, c) -> (add x, -c)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001861 if (N1C) {
1862 SDLoc DL(N);
1863 return DAG.getNode(ISD::ADD, DL, VT, N0,
1864 DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
1865 }
Evan Cheng88b65bc2010-01-18 21:38:44 +00001866 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
Matthias Braun03312192015-05-19 00:25:20 +00001867 if (isAllOnesConstant(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001868 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
Benjamin Kramer65bb14d2011-01-29 12:34:05 +00001869 // fold A-(A-B) -> B
1870 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1871 return N1.getOperand(1);
Nate Begeman21158fc2005-09-01 00:19:25 +00001872 // fold (A+B)-A -> B
Chris Lattner6f3b5772005-09-28 22:28:18 +00001873 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
Nate Begemand23739d2005-09-06 04:43:02 +00001874 return N0.getOperand(1);
Nate Begeman21158fc2005-09-01 00:19:25 +00001875 // fold (A+B)-B -> A
Chris Lattner6f3b5772005-09-28 22:28:18 +00001876 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
Scott Michelcf0da6c2009-02-17 22:15:04 +00001877 return N0.getOperand(0);
Eric Christopherd6300d22011-07-14 01:12:15 +00001878 // fold C2-(A+C1) -> (C2-C1)-A
Matthias Braun00a40762015-02-24 18:52:01 +00001879 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1880 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
Eric Christopherd6300d22011-07-14 01:12:15 +00001881 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001882 SDLoc DL(N);
Nadav Rotem841c9a82012-09-20 08:53:31 +00001883 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001884 DL, VT);
1885 return DAG.getNode(ISD::SUB, DL, VT, NewC,
Bill Wendlingd1634052012-07-19 00:04:14 +00001886 N1.getOperand(0));
Eric Christopherd6300d22011-07-14 01:12:15 +00001887 }
Dale Johannesenee573fc2008-12-23 23:47:22 +00001888 // fold ((A+(B+or-C))-B) -> A+or-C
Dale Johannesenf51dcef2008-12-16 22:13:49 +00001889 if (N0.getOpcode() == ISD::ADD &&
Dale Johannesenacc84e52008-12-23 23:01:27 +00001890 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1891 N0.getOperand(1).getOpcode() == ISD::ADD) &&
Dale Johannesenf51dcef2008-12-16 22:13:49 +00001892 N0.getOperand(1).getOperand(0) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001893 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001894 N0.getOperand(0), N0.getOperand(1).getOperand(1));
Dale Johannesenacc84e52008-12-23 23:01:27 +00001895 // fold ((A+(C+B))-B) -> A+C
1896 if (N0.getOpcode() == ISD::ADD &&
1897 N0.getOperand(1).getOpcode() == ISD::ADD &&
1898 N0.getOperand(1).getOperand(1) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001899 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001900 N0.getOperand(0), N0.getOperand(1).getOperand(0));
Dale Johannesend2a46852008-12-23 01:59:54 +00001901 // fold ((A-(B-C))-C) -> A-B
1902 if (N0.getOpcode() == ISD::SUB &&
1903 N0.getOperand(1).getOpcode() == ISD::SUB &&
1904 N0.getOperand(1).getOperand(1) == N1)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001905 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
Bill Wendling48ff08e2009-01-30 02:42:10 +00001906 N0.getOperand(0), N0.getOperand(1).getOperand(0));
Bill Wendling48ff08e2009-01-30 02:42:10 +00001907
Dan Gohman06563a82007-07-03 14:03:57 +00001908 // If either operand of a sub is undef, the result is undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00001909 if (N0.getOpcode() == ISD::UNDEF)
1910 return N0;
1911 if (N1.getOpcode() == ISD::UNDEF)
1912 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00001913
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001914 // If the relocation model supports it, consider symbol offsets.
1915 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00001916 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001917 // fold (sub Sym, c) -> Sym-c
1918 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001919 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001920 GA->getOffset() -
1921 (uint64_t)N1C->getSExtValue());
1922 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1923 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1924 if (GA->getGlobal() == GB->getGlobal())
1925 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001926 SDLoc(N), VT);
Dan Gohman2fe6bee2008-10-18 02:06:02 +00001927 }
1928
Jan Veselyaf62cf42014-10-17 14:45:25 +00001929 // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1930 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1931 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1932 if (TN->getVT() == MVT::i1) {
1933 SDLoc DL(N);
1934 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001935 DAG.getConstant(1, DL, VT));
Jan Veselyaf62cf42014-10-17 14:45:25 +00001936 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1937 }
1938 }
1939
Evan Chengf1005572010-04-28 07:10:39 +00001940 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00001941}
1942
Craig Topper43a1bd62012-01-07 09:06:39 +00001943SDValue DAGCombiner::visitSUBC(SDNode *N) {
1944 SDValue N0 = N->getOperand(0);
1945 SDValue N1 = N->getOperand(1);
Craig Topper43a1bd62012-01-07 09:06:39 +00001946 EVT VT = N0.getValueType();
1947
1948 // If the flag result is dead, turn this into an SUB.
Craig Topper0515cd42012-01-07 18:31:09 +00001949 if (!N->hasAnyUseOfValue(1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001950 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1951 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001952 MVT::Glue));
1953
1954 // fold (subc x, x) -> 0 + no borrow
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001955 if (N0 == N1) {
1956 SDLoc DL(N);
1957 return CombineTo(N, DAG.getConstant(0, DL, VT),
1958 DAG.getNode(ISD::CARRY_FALSE, DL,
Craig Topper43a1bd62012-01-07 09:06:39 +00001959 MVT::Glue));
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001960 }
Craig Topper43a1bd62012-01-07 09:06:39 +00001961
1962 // fold (subc x, 0) -> x + no borrow
Matthias Braun1505efb2015-05-18 23:07:27 +00001963 if (isNullConstant(N1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001964 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001965 MVT::Glue));
1966
1967 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
Matthias Braun03312192015-05-19 00:25:20 +00001968 if (isAllOnesConstant(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00001969 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1970 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
Craig Topper43a1bd62012-01-07 09:06:39 +00001971 MVT::Glue));
1972
1973 return SDValue();
1974}
1975
1976SDValue DAGCombiner::visitSUBE(SDNode *N) {
1977 SDValue N0 = N->getOperand(0);
1978 SDValue N1 = N->getOperand(1);
1979 SDValue CarryIn = N->getOperand(2);
1980
1981 // fold (sube x, y, false) -> (subc x, y)
1982 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00001983 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
Craig Topper43a1bd62012-01-07 09:06:39 +00001984
1985 return SDValue();
1986}
1987
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00001988SDValue DAGCombiner::visitMUL(SDNode *N) {
1989 SDValue N0 = N->getOperand(0);
1990 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00001991 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00001992
Dan Gohman06563a82007-07-03 14:03:57 +00001993 // fold (mul x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00001994 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001995 return DAG.getConstant(0, SDLoc(N), VT);
Elena Demikhovsky6769c502013-06-26 10:55:03 +00001996
1997 bool N0IsConst = false;
1998 bool N1IsConst = false;
1999 APInt ConstValue0, ConstValue1;
2000 // fold vector ops
2001 if (VT.isVector()) {
Simon Pilgrimdcbe1212015-03-29 19:13:40 +00002002 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2003 return FoldedVOp;
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002004
2005 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
2006 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
2007 } else {
Benjamin Kramer619c4e52015-04-10 11:24:51 +00002008 N0IsConst = isa<ConstantSDNode>(N0);
2009 if (N0IsConst)
2010 ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2011 N1IsConst = isa<ConstantSDNode>(N1);
2012 if (N1IsConst)
2013 ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002014 }
2015
Nate Begeman21158fc2005-09-01 00:19:25 +00002016 // fold (mul c1, c2) -> c1*c2
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002017 if (N0IsConst && N1IsConst)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002018 return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2019 N0.getNode(), N1.getNode());
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002020
Simon Pilgrim20b7aba2015-04-04 10:20:31 +00002021 // canonicalize constant to RHS (vector doesn't have to splat)
2022 if (isConstantIntBuildVectorOrConstantInt(N0) &&
2023 !isConstantIntBuildVectorOrConstantInt(N1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002024 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00002025 // fold (mul x, 0) -> 0
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002026 if (N1IsConst && ConstValue1 == 0)
Nate Begemand23739d2005-09-06 04:43:02 +00002027 return N1;
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00002028 // We require a splat of the entire scalar bit width for non-contiguous
2029 // bit patterns.
2030 bool IsFullSplat =
2031 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002032 // fold (mul x, 1) -> x
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00002033 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002034 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00002035 // fold (mul x, -1) -> 0-x
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002036 if (N1IsConst && ConstValue1.isAllOnesValue()) {
2037 SDLoc DL(N);
2038 return DAG.getNode(ISD::SUB, DL, VT,
2039 DAG.getConstant(0, DL, VT), N0);
2040 }
Nate Begeman21158fc2005-09-01 00:19:25 +00002041 // fold (mul x, (1 << c)) -> x << c
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002042 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat) {
2043 SDLoc DL(N);
2044 return DAG.getNode(ISD::SHL, DL, VT, N0,
2045 DAG.getConstant(ConstValue1.logBase2(), DL,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002046 getShiftAmountTy(N0.getValueType())));
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002047 }
Chris Lattnera70878d2005-10-30 06:41:49 +00002048 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
Benjamin Kramerd443e4a2013-09-19 13:28:20 +00002049 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002050 unsigned Log2Val = (-ConstValue1).logBase2();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002051 SDLoc DL(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002052 // FIXME: If the input is something that is easily negated (e.g. a
Chris Lattnera70878d2005-10-30 06:41:49 +00002053 // single-use add), we should put the negate there.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002054 return DAG.getNode(ISD::SUB, DL, VT,
2055 DAG.getConstant(0, DL, VT),
2056 DAG.getNode(ISD::SHL, DL, VT, N0,
2057 DAG.getConstant(Log2Val, DL,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002058 getShiftAmountTy(N0.getValueType()))));
Chris Lattner4249b9a2009-03-09 20:22:18 +00002059 }
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002060
2061 APInt Val;
Chris Lattner324871e2006-03-01 03:44:24 +00002062 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
Stephen Lincfe7f352013-07-08 00:37:03 +00002063 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002064 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2065 isa<ConstantSDNode>(N0.getOperand(1)))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002066 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002067 N1, N0.getOperand(1));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002068 AddToWorklist(C3.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002069 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002070 N0.getOperand(0), C3);
Chris Lattner324871e2006-03-01 03:44:24 +00002071 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002072
Chris Lattner324871e2006-03-01 03:44:24 +00002073 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2074 // use.
2075 {
Craig Topperc0196b12014-04-14 00:51:57 +00002076 SDValue Sh(nullptr,0), Y(nullptr,0);
Chris Lattner324871e2006-03-01 03:44:24 +00002077 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
Stephen Lincfe7f352013-07-08 00:37:03 +00002078 if (N0.getOpcode() == ISD::SHL &&
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002079 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2080 isa<ConstantSDNode>(N0.getOperand(1))) &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00002081 N0.getNode()->hasOneUse()) {
Chris Lattner324871e2006-03-01 03:44:24 +00002082 Sh = N0; Y = N1;
Scott Michelcf0da6c2009-02-17 22:15:04 +00002083 } else if (N1.getOpcode() == ISD::SHL &&
Gabor Greife12264b2008-08-30 19:29:20 +00002084 isa<ConstantSDNode>(N1.getOperand(1)) &&
2085 N1.getNode()->hasOneUse()) {
Chris Lattner324871e2006-03-01 03:44:24 +00002086 Sh = N1; Y = N0;
2087 }
Bill Wendlingb48dcf62009-01-30 02:49:26 +00002088
Gabor Greiff304a7a2008-08-28 21:40:38 +00002089 if (Sh.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002090 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002091 Sh.getOperand(0), Y);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002092 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002093 Mul, Sh.getOperand(1));
Chris Lattner324871e2006-03-01 03:44:24 +00002094 }
2095 }
Bill Wendlingb48dcf62009-01-30 02:49:26 +00002096
Chris Lattnerf29f5202006-03-04 23:33:26 +00002097 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
Elena Demikhovsky6769c502013-06-26 10:55:03 +00002098 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2099 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2100 isa<ConstantSDNode>(N0.getOperand(1))))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002101 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2102 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002103 N0.getOperand(0), N1),
Andrew Trickef9de2a2013-05-25 02:42:55 +00002104 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
Bill Wendling091f92f2009-01-30 02:45:56 +00002105 N0.getOperand(1), N1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00002106
Nate Begeman22e251a2006-02-03 06:46:56 +00002107 // reassociate mul
Simon Pilgrimd15c2802015-03-29 16:49:51 +00002108 if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
Nate Begeman22e251a2006-02-03 06:46:56 +00002109 return RMUL;
Dan Gohmana8665142007-06-25 16:23:39 +00002110
Evan Chengf1005572010-04-28 07:10:39 +00002111 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002112}
2113
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002114SDValue DAGCombiner::visitSDIV(SDNode *N) {
2115 SDValue N0 = N->getOperand(0);
2116 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002117 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00002118
Dan Gohmana8665142007-06-25 16:23:39 +00002119 // fold vector ops
Simon Pilgrimdcbe1212015-03-29 19:13:40 +00002120 if (VT.isVector())
2121 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2122 return FoldedVOp;
Scott Michelcf0da6c2009-02-17 22:15:04 +00002123
Nate Begeman21158fc2005-09-01 00:19:25 +00002124 // fold (sdiv c1, c2) -> c1/c2
Matthias Braun00a40762015-02-24 18:52:01 +00002125 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2126 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Matthias Braunc5452342015-05-18 23:18:13 +00002127 if (N0C && N1C && !N1C->isNullValue())
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002128 return DAG.FoldConstantArithmetic(ISD::SDIV, SDLoc(N), VT, N0C, N1C);
Nate Begeman4dd38312005-10-21 00:02:42 +00002129 // fold (sdiv X, 1) -> X
Matthias Braun887fdfb2015-05-19 00:25:21 +00002130 if (N1C && N1C->isOne())
Nate Begeman4dd38312005-10-21 00:02:42 +00002131 return N0;
2132 // fold (sdiv X, -1) -> 0-X
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002133 if (N1C && N1C->isAllOnesValue()) {
2134 SDLoc DL(N);
2135 return DAG.getNode(ISD::SUB, DL, VT,
2136 DAG.getConstant(0, DL, VT), N0);
2137 }
Chris Lattner5bcd0dd82005-10-07 06:10:46 +00002138 // If we know the sign bits of both operands are zero, strength reduce to a
2139 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
Duncan Sands13237ac2008-06-06 12:08:01 +00002140 if (!VT.isVector()) {
Dan Gohman1f372ed2008-02-25 21:11:39 +00002141 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002142 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
Bill Wendling5b663e72009-01-30 02:52:17 +00002143 N0, N1);
Chris Lattner2ee91f42008-01-27 23:32:17 +00002144 }
Benjamin Kramerad016872014-04-26 13:00:53 +00002145
Nate Begeman57b35672006-02-17 07:26:20 +00002146 // fold (sdiv X, pow2) -> simple ops after legalize
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002147 if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2148 (-N1C->getAPIntValue()).isPowerOf2())) {
Nate Begeman4dd38312005-10-21 00:02:42 +00002149 // If dividing by powers of two is cheap, then don't perform the following
2150 // fold.
Sanjay Patel2cdea4c2014-08-21 22:31:48 +00002151 if (TLI.isPow2SDivCheap())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002152 return SDValue();
Bill Wendling5b663e72009-01-30 02:52:17 +00002153
Chad Rosier17020f92014-07-23 14:57:52 +00002154 // Target-specific implementation of sdiv x, pow2.
2155 SDValue Res = BuildSDIVPow2(N);
2156 if (Res.getNode())
2157 return Res;
2158
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002159 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002160 SDLoc DL(N);
Bill Wendling5b663e72009-01-30 02:52:17 +00002161
Chris Lattner471627c2006-02-16 08:02:36 +00002162 // Splat the sign bit into the register
Benjamin Kramerad016872014-04-26 13:00:53 +00002163 SDValue SGN =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002164 DAG.getNode(ISD::SRA, DL, VT, N0,
2165 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
Benjamin Kramerad016872014-04-26 13:00:53 +00002166 getShiftAmountTy(N0.getValueType())));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002167 AddToWorklist(SGN.getNode());
Bill Wendling5b663e72009-01-30 02:52:17 +00002168
Chris Lattner471627c2006-02-16 08:02:36 +00002169 // Add (N0 < 0) ? abs2 - 1 : 0;
Benjamin Kramerad016872014-04-26 13:00:53 +00002170 SDValue SRL =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002171 DAG.getNode(ISD::SRL, DL, VT, SGN,
2172 DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
Benjamin Kramerad016872014-04-26 13:00:53 +00002173 getShiftAmountTy(SGN.getValueType())));
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002174 SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002175 AddToWorklist(SRL.getNode());
2176 AddToWorklist(ADD.getNode()); // Divide by pow2
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002177 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2178 DAG.getConstant(lg2, DL,
2179 getShiftAmountTy(ADD.getValueType())));
Bill Wendling5b663e72009-01-30 02:52:17 +00002180
Nate Begeman4dd38312005-10-21 00:02:42 +00002181 // If we're dividing by a positive value, we're done. Otherwise, we must
2182 // negate the result.
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002183 if (N1C->getAPIntValue().isNonNegative())
Nate Begeman4dd38312005-10-21 00:02:42 +00002184 return SRA;
Bill Wendling5b663e72009-01-30 02:52:17 +00002185
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002186 AddToWorklist(SRA.getNode());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002187 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
Nate Begeman4dd38312005-10-21 00:02:42 +00002188 }
Bill Wendling5b663e72009-01-30 02:52:17 +00002189
Sanjay Pateld399d942015-03-31 16:17:51 +00002190 // If integer divide is expensive and we satisfy the requirements, emit an
Nate Begemanc6f067a2005-10-20 02:15:44 +00002191 // alternate sequence.
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002192 if (N1C && !TLI.isIntDivCheap()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002193 SDValue Op = BuildSDIV(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002194 if (Op.getNode()) return Op;
Nate Begemanc6f067a2005-10-20 02:15:44 +00002195 }
Dan Gohmana8665142007-06-25 16:23:39 +00002196
Dan Gohman06563a82007-07-03 14:03:57 +00002197 // undef / X -> 0
2198 if (N0.getOpcode() == ISD::UNDEF)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002199 return DAG.getConstant(0, SDLoc(N), VT);
Dan Gohman06563a82007-07-03 14:03:57 +00002200 // X / undef -> undef
2201 if (N1.getOpcode() == ISD::UNDEF)
2202 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002203
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002204 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002205}
2206
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002207SDValue DAGCombiner::visitUDIV(SDNode *N) {
2208 SDValue N0 = N->getOperand(0);
2209 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002210 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002211
Dan Gohmana8665142007-06-25 16:23:39 +00002212 // fold vector ops
Simon Pilgrimdcbe1212015-03-29 19:13:40 +00002213 if (VT.isVector())
2214 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2215 return FoldedVOp;
Scott Michelcf0da6c2009-02-17 22:15:04 +00002216
Nate Begeman21158fc2005-09-01 00:19:25 +00002217 // fold (udiv c1, c2) -> c1/c2
Matthias Braun00a40762015-02-24 18:52:01 +00002218 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2219 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002220 if (N0C && N1C && !N1C->isNullValue())
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002221 return DAG.FoldConstantArithmetic(ISD::UDIV, SDLoc(N), VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00002222 // fold (udiv x, (1 << c)) -> x >>u c
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002223 if (N1C && N1C->getAPIntValue().isPowerOf2()) {
2224 SDLoc DL(N);
2225 return DAG.getNode(ISD::SRL, DL, VT, N0,
2226 DAG.getConstant(N1C->getAPIntValue().logBase2(), DL,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002227 getShiftAmountTy(N0.getValueType())));
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002228 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002229 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
Nate Begeman25d178b2006-02-05 07:20:23 +00002230 if (N1.getOpcode() == ISD::SHL) {
2231 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
Dan Gohmanb72127a2008-03-13 22:13:53 +00002232 if (SHC->getAPIntValue().isPowerOf2()) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00002233 EVT ADDVT = N1.getOperand(1).getValueType();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002234 SDLoc DL(N);
2235 SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT,
Bill Wendlingaff3e032009-01-30 02:55:25 +00002236 N1.getOperand(1),
2237 DAG.getConstant(SHC->getAPIntValue()
2238 .logBase2(),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002239 DL, ADDVT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002240 AddToWorklist(Add.getNode());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002241 return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
Nate Begeman25d178b2006-02-05 07:20:23 +00002242 }
2243 }
2244 }
Nate Begemanc6f067a2005-10-20 02:15:44 +00002245 // fold (udiv x, c) -> alternate
Benjamin Kramerda4841b2014-04-26 23:09:49 +00002246 if (N1C && !TLI.isIntDivCheap()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002247 SDValue Op = BuildUDIV(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002248 if (Op.getNode()) return Op;
Chris Lattner9faa5b72005-10-22 18:50:15 +00002249 }
Dan Gohmana8665142007-06-25 16:23:39 +00002250
Dan Gohman06563a82007-07-03 14:03:57 +00002251 // undef / X -> 0
2252 if (N0.getOpcode() == ISD::UNDEF)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002253 return DAG.getConstant(0, SDLoc(N), VT);
Dan Gohman06563a82007-07-03 14:03:57 +00002254 // X / undef -> undef
2255 if (N1.getOpcode() == ISD::UNDEF)
2256 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002257
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002258 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002259}
2260
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002261SDValue DAGCombiner::visitSREM(SDNode *N) {
2262 SDValue N0 = N->getOperand(0);
2263 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002264 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002265
Nate Begeman21158fc2005-09-01 00:19:25 +00002266 // fold (srem c1, c2) -> c1%c2
Matthias Braun00a40762015-02-24 18:52:01 +00002267 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2268 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002269 if (N0C && N1C && !N1C->isNullValue())
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002270 return DAG.FoldConstantArithmetic(ISD::SREM, SDLoc(N), VT, N0C, N1C);
Nate Begeman6828ed92005-10-10 21:26:48 +00002271 // If we know the sign bits of both operands are zero, strength reduce to a
2272 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
Duncan Sands13237ac2008-06-06 12:08:01 +00002273 if (!VT.isVector()) {
Dan Gohman1f372ed2008-02-25 21:11:39 +00002274 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002275 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
Chris Lattnerd0496d02008-01-27 23:21:58 +00002276 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002277
Dan Gohman9a693412007-11-26 23:46:11 +00002278 // If X/C can be simplified by the division-by-constant logic, lower
2279 // X%C to the equivalent of X-X/C*C.
Chris Lattnerd0620d22006-10-12 20:58:32 +00002280 if (N1C && !N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002281 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002282 AddToWorklist(Div.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002283 SDValue OptimizedDiv = combine(Div.getNode());
2284 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002285 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendlingd033af02009-01-30 02:57:00 +00002286 OptimizedDiv, N1);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002287 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002288 AddToWorklist(Mul.getNode());
Dan Gohman9a693412007-11-26 23:46:11 +00002289 return Sub;
2290 }
Chris Lattnerd0620d22006-10-12 20:58:32 +00002291 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002292
Dan Gohman06563a82007-07-03 14:03:57 +00002293 // undef % X -> 0
2294 if (N0.getOpcode() == ISD::UNDEF)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002295 return DAG.getConstant(0, SDLoc(N), VT);
Dan Gohman06563a82007-07-03 14:03:57 +00002296 // X % undef -> undef
2297 if (N1.getOpcode() == ISD::UNDEF)
2298 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002299
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002300 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002301}
2302
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002303SDValue DAGCombiner::visitUREM(SDNode *N) {
2304 SDValue N0 = N->getOperand(0);
2305 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002306 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002307
Nate Begeman21158fc2005-09-01 00:19:25 +00002308 // fold (urem c1, c2) -> c1%c2
Matthias Braun00a40762015-02-24 18:52:01 +00002309 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2310 ConstantSDNode *N1C = isConstOrConstSplat(N1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002311 if (N0C && N1C && !N1C->isNullValue())
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002312 return DAG.FoldConstantArithmetic(ISD::UREM, SDLoc(N), VT, N0C, N1C);
Nate Begeman6828ed92005-10-10 21:26:48 +00002313 // fold (urem x, pow2) -> (and x, pow2-1)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002314 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2()) {
2315 SDLoc DL(N);
2316 return DAG.getNode(ISD::AND, DL, VT, N0,
2317 DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT));
2318 }
Nate Begemanc89fdf12006-02-05 07:36:48 +00002319 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2320 if (N1.getOpcode() == ISD::SHL) {
2321 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
Dan Gohmanb72127a2008-03-13 22:13:53 +00002322 if (SHC->getAPIntValue().isPowerOf2()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002323 SDLoc DL(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002324 SDValue Add =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002325 DAG.getNode(ISD::ADD, DL, VT, N1,
2326 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL,
Dan Gohmanb72127a2008-03-13 22:13:53 +00002327 VT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002328 AddToWorklist(Add.getNode());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002329 return DAG.getNode(ISD::AND, DL, VT, N0, Add);
Nate Begemanc89fdf12006-02-05 07:36:48 +00002330 }
2331 }
2332 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002333
Dan Gohman9a693412007-11-26 23:46:11 +00002334 // If X/C can be simplified by the division-by-constant logic, lower
2335 // X%C to the equivalent of X-X/C*C.
Chris Lattnerd0620d22006-10-12 20:58:32 +00002336 if (N1C && !N1C->isNullValue()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002337 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002338 AddToWorklist(Div.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002339 SDValue OptimizedDiv = combine(Div.getNode());
2340 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002341 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
Bill Wendlingd033af02009-01-30 02:57:00 +00002342 OptimizedDiv, N1);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002343 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002344 AddToWorklist(Mul.getNode());
Dan Gohman9a693412007-11-26 23:46:11 +00002345 return Sub;
2346 }
Chris Lattnerd0620d22006-10-12 20:58:32 +00002347 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002348
Dan Gohman06563a82007-07-03 14:03:57 +00002349 // undef % X -> 0
2350 if (N0.getOpcode() == ISD::UNDEF)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002351 return DAG.getConstant(0, SDLoc(N), VT);
Dan Gohman06563a82007-07-03 14:03:57 +00002352 // X % undef -> undef
2353 if (N1.getOpcode() == ISD::UNDEF)
2354 return N1;
Dan Gohmana8665142007-06-25 16:23:39 +00002355
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002356 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002357}
2358
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002359SDValue DAGCombiner::visitMULHS(SDNode *N) {
2360 SDValue N0 = N->getOperand(0);
2361 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002362 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002363 SDLoc DL(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002364
Nate Begeman21158fc2005-09-01 00:19:25 +00002365 // fold (mulhs x, 0) -> 0
Matthias Braun1505efb2015-05-18 23:07:27 +00002366 if (isNullConstant(N1))
Nate Begemand23739d2005-09-06 04:43:02 +00002367 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00002368 // fold (mulhs x, 1) -> (sra x, size(x)-1)
Matthias Braun887fdfb2015-05-19 00:25:21 +00002369 if (isOneConstant(N1)) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002370 SDLoc DL(N);
2371 return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
Bill Wendlingfaed0652009-01-30 03:00:18 +00002372 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002373 DL,
Owen Andersonb2c80da2011-02-25 21:41:48 +00002374 getShiftAmountTy(N0.getValueType())));
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002375 }
Dan Gohman06563a82007-07-03 14:03:57 +00002376 // fold (mulhs x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002377 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002378 return DAG.getConstant(0, SDLoc(N), VT);
Dan Gohmana8665142007-06-25 16:23:39 +00002379
Chris Lattner10bd29f2010-12-13 08:39:01 +00002380 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2381 // plus a shift.
2382 if (VT.isSimple() && !VT.isVector()) {
2383 MVT Simple = VT.getSimpleVT();
2384 unsigned SimpleSize = Simple.getSizeInBits();
2385 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2386 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2387 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2388 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2389 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
Chris Lattnerb86dcee2010-12-15 05:51:39 +00002390 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002391 DAG.getConstant(SimpleSize, DL,
2392 getShiftAmountTy(N1.getValueType())));
Chris Lattner10bd29f2010-12-13 08:39:01 +00002393 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2394 }
2395 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002396
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002397 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002398}
2399
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002400SDValue DAGCombiner::visitMULHU(SDNode *N) {
2401 SDValue N0 = N->getOperand(0);
2402 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002403 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002404 SDLoc DL(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002405
Nate Begeman21158fc2005-09-01 00:19:25 +00002406 // fold (mulhu x, 0) -> 0
Matthias Braun1505efb2015-05-18 23:07:27 +00002407 if (isNullConstant(N1))
Nate Begemand23739d2005-09-06 04:43:02 +00002408 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00002409 // fold (mulhu x, 1) -> 0
Matthias Braun887fdfb2015-05-19 00:25:21 +00002410 if (isOneConstant(N1))
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002411 return DAG.getConstant(0, DL, N0.getValueType());
Dan Gohman06563a82007-07-03 14:03:57 +00002412 // fold (mulhu x, undef) -> 0
Dan Gohmanfa912822007-07-10 14:20:37 +00002413 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002414 return DAG.getConstant(0, DL, VT);
Dan Gohmana8665142007-06-25 16:23:39 +00002415
Chris Lattner10bd29f2010-12-13 08:39:01 +00002416 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2417 // plus a shift.
2418 if (VT.isSimple() && !VT.isVector()) {
2419 MVT Simple = VT.getSimpleVT();
2420 unsigned SimpleSize = Simple.getSizeInBits();
2421 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2422 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2423 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2424 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2425 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2426 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002427 DAG.getConstant(SimpleSize, DL,
2428 getShiftAmountTy(N1.getValueType())));
Chris Lattner10bd29f2010-12-13 08:39:01 +00002429 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2430 }
2431 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002432
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002433 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00002434}
2435
Sanjay Patel50cbfc52014-08-28 16:29:51 +00002436/// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2437/// give the opcodes for the two computations that are being performed. Return
2438/// true if a simplification was made.
Scott Michelcf0da6c2009-02-17 22:15:04 +00002439SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002440 unsigned HiOp) {
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002441 // If the high half is not needed, just compute the low half.
Evan Chengece4c682007-11-08 09:25:29 +00002442 bool HiExists = N->hasAnyUseOfValue(1);
2443 if (!HiExists &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002444 (!LegalOperations ||
Owen Andersonfb00d5b2014-01-20 18:41:34 +00002445 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
Craig Toppere1d12942014-08-27 05:25:25 +00002446 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
Chris Lattner31e9edc2008-01-26 01:09:19 +00002447 return CombineTo(N, Res, Res);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002448 }
2449
2450 // If the low half is not needed, just compute the high half.
Evan Chengece4c682007-11-08 09:25:29 +00002451 bool LoExists = N->hasAnyUseOfValue(0);
2452 if (!LoExists &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002453 (!LegalOperations ||
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002454 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
Craig Toppere1d12942014-08-27 05:25:25 +00002455 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
Chris Lattner31e9edc2008-01-26 01:09:19 +00002456 return CombineTo(N, Res, Res);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002457 }
2458
Evan Chengece4c682007-11-08 09:25:29 +00002459 // If both halves are used, return as it is.
2460 if (LoExists && HiExists)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002461 return SDValue();
Evan Chengece4c682007-11-08 09:25:29 +00002462
2463 // If the two computed results can be simplified separately, separate them.
Evan Chengece4c682007-11-08 09:25:29 +00002464 if (LoExists) {
Craig Toppere1d12942014-08-27 05:25:25 +00002465 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002466 AddToWorklist(Lo.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002467 SDValue LoOpt = combine(Lo.getNode());
2468 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002469 (!LegalOperations ||
Duncan Sands8651e9c2008-06-13 19:07:40 +00002470 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
Chris Lattner31e9edc2008-01-26 01:09:19 +00002471 return CombineTo(N, LoOpt, LoOpt);
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002472 }
2473
Evan Chengece4c682007-11-08 09:25:29 +00002474 if (HiExists) {
Craig Toppere1d12942014-08-27 05:25:25 +00002475 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002476 AddToWorklist(Hi.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +00002477 SDValue HiOpt = combine(Hi.getNode());
2478 if (HiOpt.getNode() && HiOpt != Hi &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00002479 (!LegalOperations ||
Duncan Sands8651e9c2008-06-13 19:07:40 +00002480 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
Chris Lattner31e9edc2008-01-26 01:09:19 +00002481 return CombineTo(N, HiOpt, HiOpt);
Evan Chengece4c682007-11-08 09:25:29 +00002482 }
Bill Wendling9b3407e2009-01-30 03:08:40 +00002483
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002484 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002485}
2486
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002487SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2488 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002489 if (Res.getNode()) return Res;
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002490
Chris Lattner15090e12010-12-15 06:04:19 +00002491 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002492 SDLoc DL(N);
Chris Lattner15090e12010-12-15 06:04:19 +00002493
Sanjay Pateld399d942015-03-31 16:17:51 +00002494 // If the type is twice as wide is legal, transform the mulhu to a wider
2495 // multiply plus a shift.
Chris Lattner15090e12010-12-15 06:04:19 +00002496 if (VT.isSimple() && !VT.isVector()) {
2497 MVT Simple = VT.getSimpleVT();
2498 unsigned SimpleSize = Simple.getSizeInBits();
2499 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2500 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2501 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2502 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2503 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2504 // Compute the high part as N1.
2505 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002506 DAG.getConstant(SimpleSize, DL,
2507 getShiftAmountTy(Lo.getValueType())));
Chris Lattner15090e12010-12-15 06:04:19 +00002508 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2509 // Compute the low part as N0.
2510 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2511 return CombineTo(N, Lo, Hi);
2512 }
2513 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002514
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002515 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002516}
2517
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002518SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2519 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002520 if (Res.getNode()) return Res;
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002521
Chris Lattner15090e12010-12-15 06:04:19 +00002522 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00002523 SDLoc DL(N);
Owen Andersonb2c80da2011-02-25 21:41:48 +00002524
Sanjay Pateld399d942015-03-31 16:17:51 +00002525 // If the type is twice as wide is legal, transform the mulhu to a wider
2526 // multiply plus a shift.
Chris Lattner15090e12010-12-15 06:04:19 +00002527 if (VT.isSimple() && !VT.isVector()) {
2528 MVT Simple = VT.getSimpleVT();
2529 unsigned SimpleSize = Simple.getSizeInBits();
2530 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2531 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2532 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2533 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2534 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2535 // Compute the high part as N1.
2536 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002537 DAG.getConstant(SimpleSize, DL,
2538 getShiftAmountTy(Lo.getValueType())));
Chris Lattner15090e12010-12-15 06:04:19 +00002539 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2540 // Compute the low part as N0.
2541 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2542 return CombineTo(N, Lo, Hi);
2543 }
2544 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00002545
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002546 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002547}
2548
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002549SDValue DAGCombiner::visitSMULO(SDNode *N) {
2550 // (smulo x, 2) -> (saddo x, x)
2551 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2552 if (C2->getAPIntValue() == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002553 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002554 N->getOperand(0), N->getOperand(0));
2555
2556 return SDValue();
2557}
2558
2559SDValue DAGCombiner::visitUMULO(SDNode *N) {
2560 // (umulo x, 2) -> (uaddo x, x)
2561 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2562 if (C2->getAPIntValue() == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00002563 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
Benjamin Kramer2fd48f22011-05-21 18:31:55 +00002564 N->getOperand(0), N->getOperand(0));
2565
2566 return SDValue();
2567}
2568
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002569SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2570 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002571 if (Res.getNode()) return Res;
Scott Michelcf0da6c2009-02-17 22:15:04 +00002572
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002573 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002574}
2575
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002576SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2577 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
Gabor Greiff304a7a2008-08-28 21:40:38 +00002578 if (Res.getNode()) return Res;
Scott Michelcf0da6c2009-02-17 22:15:04 +00002579
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002580 return SDValue();
Dan Gohman5c6d0c32007-10-08 17:57:15 +00002581}
2582
Sanjay Patel50cbfc52014-08-28 16:29:51 +00002583/// If this is a binary operator with two operands of the same opcode, try to
2584/// simplify it.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002585SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2586 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002587 EVT VT = N0.getValueType();
Chris Lattner8d6fc202006-05-05 05:51:50 +00002588 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
Scott Michelcf0da6c2009-02-17 22:15:04 +00002589
Dan Gohmandd5286d2010-01-14 03:08:49 +00002590 // Bail early if none of these transforms apply.
2591 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2592
Chris Lattner002ee912006-05-05 06:31:05 +00002593 // For each of OP in AND/OR/XOR:
2594 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2595 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2596 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00002597 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
Dan Gohman600f62b2010-06-24 14:30:44 +00002598 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
Nate Begeman9655f842009-12-03 07:11:29 +00002599 //
2600 // do not sink logical op inside of a vector extend, since it may combine
2601 // into a vsetcc.
Evan Cheng166a4e62010-01-06 19:38:29 +00002602 EVT Op0VT = N0.getOperand(0).getValueType();
2603 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
Dan Gohmanad3e5492009-04-08 00:15:30 +00002604 N0.getOpcode() == ISD::SIGN_EXTEND ||
Simon Pilgrimbe24ab32014-12-04 09:44:01 +00002605 N0.getOpcode() == ISD::BSWAP ||
Evan Chengf1bd5fc2010-04-17 06:13:15 +00002606 // Avoid infinite looping with PromoteIntBinOp.
2607 (N0.getOpcode() == ISD::ANY_EXTEND &&
2608 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
Dan Gohman600f62b2010-06-24 14:30:44 +00002609 (N0.getOpcode() == ISD::TRUNCATE &&
2610 (!TLI.isZExtFree(VT, Op0VT) ||
2611 !TLI.isTruncateFree(Op0VT, VT)) &&
2612 TLI.isTypeLegal(Op0VT))) &&
Nate Begeman9655f842009-12-03 07:11:29 +00002613 !VT.isVector() &&
Evan Cheng166a4e62010-01-06 19:38:29 +00002614 Op0VT == N1.getOperand(0).getValueType() &&
2615 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002616 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
Bill Wendling781db7a2009-01-30 19:25:47 +00002617 N0.getOperand(0).getValueType(),
2618 N0.getOperand(0), N1.getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002619 AddToWorklist(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002620 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
Chris Lattner8d6fc202006-05-05 05:51:50 +00002621 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002622
Chris Lattner5ac42932006-05-05 06:10:43 +00002623 // For each of OP in SHL/SRL/SRA/AND...
2624 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2625 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2626 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
Chris Lattner8d6fc202006-05-05 05:51:50 +00002627 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
Chris Lattner5ac42932006-05-05 06:10:43 +00002628 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
Chris Lattner8d6fc202006-05-05 05:51:50 +00002629 N0.getOperand(1) == N1.getOperand(1)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002630 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
Bill Wendling781db7a2009-01-30 19:25:47 +00002631 N0.getOperand(0).getValueType(),
2632 N0.getOperand(0), N1.getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002633 AddToWorklist(ORNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00002634 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Bill Wendling781db7a2009-01-30 19:25:47 +00002635 ORNode, N0.getOperand(1));
Chris Lattner8d6fc202006-05-05 05:51:50 +00002636 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002637
Nadav Rotemb0783502012-04-01 19:31:22 +00002638 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2639 // Only perform this optimization after type legalization and before
2640 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2641 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2642 // we don't want to undo this promotion.
2643 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2644 // on scalars.
Nadav Rotem841c9a82012-09-20 08:53:31 +00002645 if ((N0.getOpcode() == ISD::BITCAST ||
2646 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2647 Level == AfterLegalizeTypes) {
Nadav Rotemb0783502012-04-01 19:31:22 +00002648 SDValue In0 = N0.getOperand(0);
2649 SDValue In1 = N1.getOperand(0);
2650 EVT In0Ty = In0.getValueType();
2651 EVT In1Ty = In1.getValueType();
Andrew Trickef9de2a2013-05-25 02:42:55 +00002652 SDLoc DL(N);
Nadav Rotem841c9a82012-09-20 08:53:31 +00002653 // If both incoming values are integers, and the original types are the
2654 // same.
Nadav Rotemb0783502012-04-01 19:31:22 +00002655 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
Nadav Rotem841c9a82012-09-20 08:53:31 +00002656 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2657 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002658 AddToWorklist(Op.getNode());
Nadav Rotemb0783502012-04-01 19:31:22 +00002659 return BC;
2660 }
2661 }
2662
2663 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2664 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2665 // If both shuffles use the same mask, and both shuffle within a single
2666 // vector, then it is worthwhile to move the swizzle after the operation.
2667 // The type-legalizer generates this pattern when loading illegal
2668 // vector types from memory. In many cases this allows additional shuffle
2669 // optimizations.
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002670 // There are other cases where moving the shuffle after the xor/and/or
2671 // is profitable even if shuffles don't perform a swizzle.
2672 // If both shuffles use the same mask, and both shuffles have the same first
2673 // or second operand, then it might still be profitable to move the shuffle
2674 // after the xor/and/or operation.
2675 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
Nadav Rotemb0783502012-04-01 19:31:22 +00002676 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2677 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
Craig Topper9c3da312012-04-09 07:19:09 +00002678
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002679 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
Craig Topper9c3da312012-04-09 07:19:09 +00002680 "Inputs to shuffles are not the same type");
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00002681
Nadav Rotemb0783502012-04-01 19:31:22 +00002682 // Check that both shuffles use the same mask. The masks are known to be of
2683 // the same length because the result vector type is the same.
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002684 // Check also that shuffles have only one use to avoid introducing extra
2685 // instructions.
2686 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2687 SVN0->getMask().equals(SVN1->getMask())) {
2688 SDValue ShOp = N0->getOperand(1);
Nadav Rotemb0783502012-04-01 19:31:22 +00002689
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002690 // Don't try to fold this node if it requires introducing a
2691 // build vector of all zeros that might be illegal at this stage.
2692 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2693 if (!LegalTypes)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002694 ShOp = DAG.getConstant(0, SDLoc(N), VT);
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002695 else
2696 ShOp = SDValue();
2697 }
2698
2699 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2700 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2701 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2702 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2703 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2704 N0->getOperand(0), N1->getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002705 AddToWorklist(NewNode.getNode());
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002706 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2707 &SVN0->getMask()[0]);
2708 }
2709
2710 // Don't try to fold this node if it requires introducing a
2711 // build vector of all zeros that might be illegal at this stage.
2712 ShOp = N0->getOperand(0);
2713 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2714 if (!LegalTypes)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002715 ShOp = DAG.getConstant(0, SDLoc(N), VT);
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002716 else
2717 ShOp = SDValue();
2718 }
2719
2720 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2721 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2722 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2723 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2724 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2725 N0->getOperand(1), N1->getOperand(1));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00002726 AddToWorklist(NewNode.getNode());
Andrea Di Biagio28f46d92014-03-18 17:12:59 +00002727 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2728 &SVN0->getMask()[0]);
2729 }
Nadav Rotemb0783502012-04-01 19:31:22 +00002730 }
2731 }
Craig Topper9c3da312012-04-09 07:19:09 +00002732
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002733 return SDValue();
Chris Lattner8d6fc202006-05-05 05:51:50 +00002734}
2735
Matthias Braun3ecb5572015-03-06 19:49:06 +00002736/// This contains all DAGCombine rules which reduce two values combined by
2737/// an And operation to a single value. This makes them reusable in the context
2738/// of visitSELECT(). Rules involving constants are not included as
2739/// visitSELECT() already handles those cases.
2740SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2741 SDNode *LocReference) {
2742 EVT VT = N1.getValueType();
2743
2744 // fold (and x, undef) -> 0
2745 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002746 return DAG.getConstant(0, SDLoc(LocReference), VT);
Matthias Braun3ecb5572015-03-06 19:49:06 +00002747 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2748 SDValue LL, LR, RL, RR, CC0, CC1;
2749 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2750 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2751 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2752
2753 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2754 LL.getValueType().isInteger()) {
2755 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
Matthias Braun1505efb2015-05-18 23:07:27 +00002756 if (isNullConstant(LR) && Op1 == ISD::SETEQ) {
Matthias Braun3ecb5572015-03-06 19:49:06 +00002757 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2758 LR.getValueType(), LL, RL);
2759 AddToWorklist(ORNode.getNode());
2760 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2761 }
Matthias Braun03312192015-05-19 00:25:20 +00002762 if (isAllOnesConstant(LR)) {
2763 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2764 if (Op1 == ISD::SETEQ) {
2765 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2766 LR.getValueType(), LL, RL);
2767 AddToWorklist(ANDNode.getNode());
2768 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2769 }
2770 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2771 if (Op1 == ISD::SETGT) {
2772 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2773 LR.getValueType(), LL, RL);
2774 AddToWorklist(ORNode.getNode());
2775 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2776 }
Matthias Braun3ecb5572015-03-06 19:49:06 +00002777 }
2778 }
2779 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2780 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2781 Op0 == Op1 && LL.getValueType().isInteger() &&
Matthias Braun03312192015-05-19 00:25:20 +00002782 Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
2783 (isAllOnesConstant(LR) && isNullConstant(RR)))) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002784 SDLoc DL(N0);
2785 SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
2786 LL, DAG.getConstant(1, DL,
2787 LL.getValueType()));
Matthias Braun3ecb5572015-03-06 19:49:06 +00002788 AddToWorklist(ADDNode.getNode());
2789 return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002790 DAG.getConstant(2, DL, LL.getValueType()),
2791 ISD::SETUGE);
Matthias Braun3ecb5572015-03-06 19:49:06 +00002792 }
2793 // canonicalize equivalent to ll == rl
2794 if (LL == RR && LR == RL) {
2795 Op1 = ISD::getSetCCSwappedOperands(Op1);
2796 std::swap(RL, RR);
2797 }
2798 if (LL == RL && LR == RR) {
2799 bool isInteger = LL.getValueType().isInteger();
2800 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2801 if (Result != ISD::SETCC_INVALID &&
2802 (!LegalOperations ||
2803 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2804 TLI.isOperationLegal(ISD::SETCC,
2805 getSetCCResultType(N0.getSimpleValueType())))))
2806 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2807 LL, LR, Result);
2808 }
2809 }
2810
2811 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2812 VT.getSizeInBits() <= 64) {
2813 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2814 APInt ADDC = ADDI->getAPIntValue();
2815 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2816 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2817 // immediate for an add, but it is legal if its top c2 bits are set,
2818 // transform the ADD so the immediate doesn't need to be materialized
2819 // in a register.
2820 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2821 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2822 SRLI->getZExtValue());
2823 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2824 ADDC |= Mask;
2825 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002826 SDLoc DL(N0);
Matthias Braun3ecb5572015-03-06 19:49:06 +00002827 SDValue NewAdd =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002828 DAG.getNode(ISD::ADD, DL, VT,
2829 N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
Matthias Braun3ecb5572015-03-06 19:49:06 +00002830 CombineTo(N0.getNode(), NewAdd);
2831 // Return N so it doesn't get rechecked!
2832 return SDValue(LocReference, 0);
2833 }
2834 }
2835 }
2836 }
2837 }
2838 }
2839
2840 return SDValue();
2841}
2842
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002843SDValue DAGCombiner::visitAND(SDNode *N) {
2844 SDValue N0 = N->getOperand(0);
2845 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00002846 EVT VT = N1.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00002847
Dan Gohmana8665142007-06-25 16:23:39 +00002848 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00002849 if (VT.isVector()) {
Simon Pilgrimdcbe1212015-03-29 19:13:40 +00002850 if (SDValue FoldedVOp = SimplifyVBinOp(N))
2851 return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00002852
2853 // fold (and x, 0) -> 0, vector edition
2854 if (ISD::isBuildVectorAllZeros(N0.getNode()))
David Xuf7aff682014-09-11 05:10:28 +00002855 // do not return N0, because undef node may exist in N0
2856 return DAG.getConstant(
2857 APInt::getNullValue(
2858 N0.getValueType().getScalarType().getSizeInBits()),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002859 SDLoc(N), N0.getValueType());
Craig Toppera183ddb2012-12-08 22:49:19 +00002860 if (ISD::isBuildVectorAllZeros(N1.getNode()))
David Xuf7aff682014-09-11 05:10:28 +00002861 // do not return N1, because undef node may exist in N1
2862 return DAG.getConstant(
2863 APInt::getNullValue(
2864 N1.getValueType().getScalarType().getSizeInBits()),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002865 SDLoc(N), N1.getValueType());
Craig Toppera183ddb2012-12-08 22:49:19 +00002866
2867 // fold (and x, -1) -> x, vector edition
2868 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2869 return N1;
2870 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2871 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00002872 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00002873
Nate Begeman21158fc2005-09-01 00:19:25 +00002874 // fold (and c1, c2) -> c1&c2
Matthias Braun00a40762015-02-24 18:52:01 +00002875 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2876 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00002877 if (N0C && N1C)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002878 return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00002879 // canonicalize constant to RHS
Simon Pilgrim20b7aba2015-04-04 10:20:31 +00002880 if (isConstantIntBuildVectorOrConstantInt(N0) &&
2881 !isConstantIntBuildVectorOrConstantInt(N1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00002882 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00002883 // fold (and x, -1) -> x
Matthias Braun03312192015-05-19 00:25:20 +00002884 if (isAllOnesConstant(N1))
Nate Begemand23739d2005-09-06 04:43:02 +00002885 return N0;
2886 // if (and x, c) is known to be zero, return 0
Matthias Braun00a40762015-02-24 18:52:01 +00002887 unsigned BitWidth = VT.getScalarType().getSizeInBits();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002888 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1f372ed2008-02-25 21:11:39 +00002889 APInt::getAllOnesValue(BitWidth)))
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002890 return DAG.getConstant(0, SDLoc(N), VT);
Nate Begeman22e251a2006-02-03 06:46:56 +00002891 // reassociate and
Simon Pilgrimd15c2802015-03-29 16:49:51 +00002892 if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
Nate Begeman22e251a2006-02-03 06:46:56 +00002893 return RAND;
Bill Wendlingaf13d822010-03-03 00:35:56 +00002894 // fold (and (or x, C), D) -> D if (C & D) == D
Nate Begemanee065282005-11-02 18:42:59 +00002895 if (N1C && N0.getOpcode() == ISD::OR)
Nate Begeman21158fc2005-09-01 00:19:25 +00002896 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
Dan Gohmanb72127a2008-03-13 22:13:53 +00002897 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
Nate Begemand23739d2005-09-06 04:43:02 +00002898 return N1;
Chris Lattner49beaf42006-02-02 07:17:31 +00002899 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2900 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002901 SDValue N0Op0 = N0.getOperand(0);
Dan Gohman1f372ed2008-02-25 21:11:39 +00002902 APInt Mask = ~N1C->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00002903 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
Dan Gohman1f372ed2008-02-25 21:11:39 +00002904 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00002905 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
Bill Wendling86171912009-01-30 20:43:18 +00002906 N0.getValueType(), N0Op0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002907
Chris Lattner0db2f2c2006-03-01 21:47:21 +00002908 // Replace uses of the AND with uses of the Zero extend node.
2909 CombineTo(N, Zext);
Scott Michelcf0da6c2009-02-17 22:15:04 +00002910
Chris Lattner49beaf42006-02-02 07:17:31 +00002911 // We actually want to replace all uses of the any_extend with the
2912 // zero_extend, to avoid duplicating things. This will later cause this
2913 // AND to be folded.
Gabor Greiff304a7a2008-08-28 21:40:38 +00002914 CombineTo(N0.getNode(), Zext);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00002915 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattner49beaf42006-02-02 07:17:31 +00002916 }
2917 }
Stephen Lincfe7f352013-07-08 00:37:03 +00002918 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
James Molloy862fe492012-02-20 12:02:38 +00002919 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2920 // already be zero by virtue of the width of the base type of the load.
2921 //
2922 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2923 // more cases.
2924 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2925 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2926 N0.getOpcode() == ISD::LOAD) {
2927 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2928 N0 : N0.getOperand(0) );
2929
2930 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2931 // This can be a pure constant or a vector splat, in which case we treat the
2932 // vector as a scalar and use the splat value.
2933 APInt Constant = APInt::getNullValue(1);
2934 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2935 Constant = C->getAPIntValue();
2936 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2937 APInt SplatValue, SplatUndef;
2938 unsigned SplatBitSize;
2939 bool HasAnyUndefs;
2940 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2941 SplatBitSize, HasAnyUndefs);
2942 if (IsSplat) {
2943 // Undef bits can contribute to a possible optimisation if set, so
2944 // set them.
2945 SplatValue |= SplatUndef;
2946
2947 // The splat value may be something like "0x00FFFFFF", which means 0 for
2948 // the first vector value and FF for the rest, repeating. We need a mask
2949 // that will apply equally to all members of the vector, so AND all the
2950 // lanes of the constant together.
2951 EVT VT = Vector->getValueType(0);
2952 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
Silviu Baranga3f40d872012-09-05 08:57:21 +00002953
2954 // If the splat value has been compressed to a bitlength lower
2955 // than the size of the vector lane, we need to re-expand it to
2956 // the lane size.
2957 if (BitWidth > SplatBitSize)
2958 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2959 SplatBitSize < BitWidth;
2960 SplatBitSize = SplatBitSize * 2)
2961 SplatValue |= SplatValue.shl(SplatBitSize);
2962
Andrea Di Biagioc9d79e82015-03-07 12:24:55 +00002963 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
2964 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
2965 if (SplatBitSize % BitWidth == 0) {
2966 Constant = APInt::getAllOnesValue(BitWidth);
2967 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2968 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2969 }
James Molloy862fe492012-02-20 12:02:38 +00002970 }
2971 }
2972
2973 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2974 // actually legal and isn't going to get expanded, else this is a false
2975 // optimisation.
2976 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00002977 Load->getValueType(0),
James Molloy862fe492012-02-20 12:02:38 +00002978 Load->getMemoryVT());
2979
2980 // Resize the constant to the same size as the original memory access before
2981 // extension. If it is still the AllOnesValue then this AND is completely
2982 // unneeded.
2983 Constant =
2984 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2985
2986 bool B;
2987 switch (Load->getExtensionType()) {
2988 default: B = false; break;
2989 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2990 case ISD::ZEXTLOAD:
2991 case ISD::NON_EXTLOAD: B = true; break;
2992 }
2993
2994 if (B && Constant.isAllOnesValue()) {
2995 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2996 // preserve semantics once we get rid of the AND.
2997 SDValue NewLoad(Load, 0);
2998 if (Load->getExtensionType() == ISD::EXTLOAD) {
2999 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
Andrew Trickef9de2a2013-05-25 02:42:55 +00003000 Load->getValueType(0), SDLoc(Load),
James Molloy862fe492012-02-20 12:02:38 +00003001 Load->getChain(), Load->getBasePtr(),
3002 Load->getOffset(), Load->getMemoryVT(),
3003 Load->getMemOperand());
3004 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
Hal Finkel8a311382012-06-20 15:42:48 +00003005 if (Load->getNumValues() == 3) {
3006 // PRE/POST_INC loads have 3 values.
3007 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3008 NewLoad.getValue(2) };
3009 CombineTo(Load, To, 3, true);
3010 } else {
3011 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3012 }
James Molloy862fe492012-02-20 12:02:38 +00003013 }
3014
3015 // Fold the AND away, taking care not to fold to the old load node if we
3016 // replaced it.
3017 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3018
3019 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3020 }
3021 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003022
Chris Lattnerf0032b32006-02-28 06:49:37 +00003023 // fold (and (load x), 255) -> (zextload x, i8)
3024 // fold (and (extload x, i16), 255) -> (zextload x, i8)
Evan Cheng166a4e62010-01-06 19:38:29 +00003025 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3026 if (N1C && (N0.getOpcode() == ISD::LOAD ||
3027 (N0.getOpcode() == ISD::ANY_EXTEND &&
3028 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3029 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3030 LoadSDNode *LN0 = HasAnyExt
3031 ? cast<LoadSDNode>(N0.getOperand(0))
3032 : cast<LoadSDNode>(N0);
Evan Chenge71fe34d2006-10-09 20:57:25 +00003033 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
Tim Northover68239002013-07-02 09:58:53 +00003034 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
Duncan Sands93b66092008-06-09 11:32:28 +00003035 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
Evan Cheng166a4e62010-01-06 19:38:29 +00003036 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
3037 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3038 EVT LoadedVT = LN0->getMemoryVT();
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00003039 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
Duncan Sands93b66092008-06-09 11:32:28 +00003040
Evan Cheng166a4e62010-01-06 19:38:29 +00003041 if (ExtVT == LoadedVT &&
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00003042 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3043 ExtVT))) {
Wesley Peck527da1b2010-11-23 03:31:01 +00003044
3045 SDValue NewLoad =
Andrew Trickef9de2a2013-05-25 02:42:55 +00003046 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
Richard Sandiford39c1ce42013-10-28 11:17:59 +00003047 LN0->getChain(), LN0->getBasePtr(), ExtVT,
3048 LN0->getMemOperand());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003049 AddToWorklist(N);
Chris Lattner88de3842010-01-07 21:53:27 +00003050 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3051 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3052 }
Wesley Peck527da1b2010-11-23 03:31:01 +00003053
Chris Lattner88de3842010-01-07 21:53:27 +00003054 // Do not change the width of a volatile load.
3055 // Do not generate loads of non-round integer types since these can
3056 // be expensive (and would be wrong if the type is not byte sized).
3057 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00003058 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3059 ExtVT))) {
Chris Lattner88de3842010-01-07 21:53:27 +00003060 EVT PtrType = LN0->getOperand(1).getValueType();
Bill Wendling86171912009-01-30 20:43:18 +00003061
Chris Lattner88de3842010-01-07 21:53:27 +00003062 unsigned Alignment = LN0->getAlignment();
3063 SDValue NewPtr = LN0->getBasePtr();
3064
3065 // For big endian targets, we need to add an offset to the pointer
3066 // to load the correct bytes. For little endian systems, we merely
3067 // need to read fewer bytes from the same pointer.
3068 if (TLI.isBigEndian()) {
Evan Cheng166a4e62010-01-06 19:38:29 +00003069 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3070 unsigned EVTStoreBytes = ExtVT.getStoreSize();
3071 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003072 SDLoc DL(LN0);
3073 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3074 NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
Chris Lattner88de3842010-01-07 21:53:27 +00003075 Alignment = MinAlign(Alignment, PtrOff);
Evan Cheng166a4e62010-01-06 19:38:29 +00003076 }
Chris Lattner88de3842010-01-07 21:53:27 +00003077
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003078 AddToWorklist(NewPtr.getNode());
Wesley Peck527da1b2010-11-23 03:31:01 +00003079
Chris Lattner88de3842010-01-07 21:53:27 +00003080 SDValue Load =
Andrew Trickef9de2a2013-05-25 02:42:55 +00003081 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
Chris Lattner88de3842010-01-07 21:53:27 +00003082 LN0->getChain(), NewPtr,
Chris Lattner3d178ed2010-09-21 17:04:51 +00003083 LN0->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +00003084 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
Louis Gerbarg67474e32014-07-31 21:45:05 +00003085 LN0->isInvariant(), Alignment, LN0->getAAInfo());
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003086 AddToWorklist(N);
Chris Lattner88de3842010-01-07 21:53:27 +00003087 CombineTo(LN0, Load, Load.getValue(1));
3088 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Duncan Sands1826ded2007-10-28 12:59:45 +00003089 }
Evan Chenge71fe34d2006-10-09 20:57:25 +00003090 }
Chris Lattnerbdbc4472006-02-28 06:35:35 +00003091 }
3092 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003093
Matthias Braun3ecb5572015-03-06 19:49:06 +00003094 if (SDValue Combined = visitANDLike(N0, N1, N))
3095 return Combined;
3096
3097 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
3098 if (N0.getOpcode() == N1.getOpcode()) {
3099 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3100 if (Tmp.getNode()) return Tmp;
Evan Chenge6a3b032012-07-17 18:54:11 +00003101 }
Evan Chenge6a3b032012-07-17 18:54:11 +00003102
Matthias Braun3ecb5572015-03-06 19:49:06 +00003103 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3104 // fold (and (sra)) -> (and (srl)) when possible.
3105 if (!VT.isVector() &&
3106 SimplifyDemandedBits(SDValue(N, 0)))
3107 return SDValue(N, 0);
3108
3109 // fold (zext_inreg (extload x)) -> (zextload x)
3110 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3111 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3112 EVT MemVT = LN0->getMemoryVT();
3113 // If we zero all the possible extended bits, then we can turn this into
3114 // a zextload if we are running before legalize or the operation is legal.
3115 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3116 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3117 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3118 ((!LegalOperations && !LN0->isVolatile()) ||
3119 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3120 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3121 LN0->getChain(), LN0->getBasePtr(),
3122 MemVT, LN0->getMemOperand());
3123 AddToWorklist(N);
3124 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3125 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3126 }
3127 }
3128 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3129 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3130 N0.hasOneUse()) {
3131 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3132 EVT MemVT = LN0->getMemoryVT();
3133 // If we zero all the possible extended bits, then we can turn this into
3134 // a zextload if we are running before legalize or the operation is legal.
3135 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3136 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3137 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3138 ((!LegalOperations && !LN0->isVolatile()) ||
3139 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3140 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3141 LN0->getChain(), LN0->getBasePtr(),
3142 MemVT, LN0->getMemOperand());
3143 AddToWorklist(N);
3144 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3145 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3146 }
3147 }
Tim Northover819bfb52013-08-27 13:46:45 +00003148 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3149 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3150 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3151 N0.getOperand(1), false);
3152 if (BSwap.getNode())
3153 return BSwap;
3154 }
3155
Evan Chengf1005572010-04-28 07:10:39 +00003156 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00003157}
3158
Sanjay Patel50cbfc52014-08-28 16:29:51 +00003159/// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
Evan Cheng4c0bd962011-06-21 06:01:08 +00003160SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3161 bool DemandHighBits) {
3162 if (!LegalOperations)
3163 return SDValue();
3164
3165 EVT VT = N->getValueType(0);
3166 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3167 return SDValue();
3168 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3169 return SDValue();
3170
3171 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3172 bool LookPassAnd0 = false;
3173 bool LookPassAnd1 = false;
3174 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3175 std::swap(N0, N1);
3176 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3177 std::swap(N0, N1);
3178 if (N0.getOpcode() == ISD::AND) {
3179 if (!N0.getNode()->hasOneUse())
3180 return SDValue();
3181 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3182 if (!N01C || N01C->getZExtValue() != 0xFF00)
3183 return SDValue();
3184 N0 = N0.getOperand(0);
3185 LookPassAnd0 = true;
3186 }
3187
3188 if (N1.getOpcode() == ISD::AND) {
3189 if (!N1.getNode()->hasOneUse())
3190 return SDValue();
3191 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3192 if (!N11C || N11C->getZExtValue() != 0xFF)
3193 return SDValue();
3194 N1 = N1.getOperand(0);
3195 LookPassAnd1 = true;
3196 }
3197
3198 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3199 std::swap(N0, N1);
3200 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3201 return SDValue();
3202 if (!N0.getNode()->hasOneUse() ||
3203 !N1.getNode()->hasOneUse())
3204 return SDValue();
3205
3206 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3207 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3208 if (!N01C || !N11C)
3209 return SDValue();
3210 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3211 return SDValue();
3212
3213 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3214 SDValue N00 = N0->getOperand(0);
3215 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3216 if (!N00.getNode()->hasOneUse())
3217 return SDValue();
3218 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3219 if (!N001C || N001C->getZExtValue() != 0xFF)
3220 return SDValue();
3221 N00 = N00.getOperand(0);
3222 LookPassAnd0 = true;
3223 }
3224
3225 SDValue N10 = N1->getOperand(0);
3226 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3227 if (!N10.getNode()->hasOneUse())
3228 return SDValue();
3229 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3230 if (!N101C || N101C->getZExtValue() != 0xFF00)
3231 return SDValue();
3232 N10 = N10.getOperand(0);
3233 LookPassAnd1 = true;
3234 }
3235
3236 if (N00 != N10)
3237 return SDValue();
3238
Tim Northover819bfb52013-08-27 13:46:45 +00003239 // Make sure everything beyond the low halfword gets set to zero since the SRL
3240 // 16 will clear the top bits.
Evan Cheng4c0bd962011-06-21 06:01:08 +00003241 unsigned OpSizeInBits = VT.getSizeInBits();
Tim Northover819bfb52013-08-27 13:46:45 +00003242 if (DemandHighBits && OpSizeInBits > 16) {
3243 // If the left-shift isn't masked out then the only way this is a bswap is
3244 // if all bits beyond the low 8 are 0. In that case the entire pattern
3245 // reduces to a left shift anyway: leave it for other parts of the combiner.
3246 if (!LookPassAnd0)
3247 return SDValue();
3248
3249 // However, if the right shift isn't masked out then it might be because
3250 // it's not needed. See if we can spot that too.
3251 if (!LookPassAnd1 &&
3252 !DAG.MaskedValueIsZero(
3253 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3254 return SDValue();
3255 }
Eric Christopherd6300d22011-07-14 01:12:15 +00003256
Andrew Trickef9de2a2013-05-25 02:42:55 +00003257 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003258 if (OpSizeInBits > 16) {
3259 SDLoc DL(N);
3260 Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3261 DAG.getConstant(OpSizeInBits - 16, DL,
3262 getShiftAmountTy(VT)));
3263 }
Evan Cheng4c0bd962011-06-21 06:01:08 +00003264 return Res;
3265}
3266
Sanjay Patel50cbfc52014-08-28 16:29:51 +00003267/// Return true if the specified node is an element that makes up a 32-bit
3268/// packed halfword byteswap.
3269/// ((x & 0x000000ff) << 8) |
3270/// ((x & 0x0000ff00) >> 8) |
3271/// ((x & 0x00ff0000) << 8) |
3272/// ((x & 0xff000000) >> 8)
Benjamin Kramer7ad22402014-10-22 19:55:26 +00003273static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
Evan Cheng4c0bd962011-06-21 06:01:08 +00003274 if (!N.getNode()->hasOneUse())
3275 return false;
3276
3277 unsigned Opc = N.getOpcode();
3278 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3279 return false;
3280
3281 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3282 if (!N1C)
3283 return false;
3284
3285 unsigned Num;
3286 switch (N1C->getZExtValue()) {
3287 default:
3288 return false;
3289 case 0xFF: Num = 0; break;
3290 case 0xFF00: Num = 1; break;
3291 case 0xFF0000: Num = 2; break;
3292 case 0xFF000000: Num = 3; break;
3293 }
3294
3295 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3296 SDValue N0 = N.getOperand(0);
3297 if (Opc == ISD::AND) {
3298 if (Num == 0 || Num == 2) {
3299 // (x >> 8) & 0xff
3300 // (x >> 8) & 0xff0000
3301 if (N0.getOpcode() != ISD::SRL)
3302 return false;
3303 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3304 if (!C || C->getZExtValue() != 8)
3305 return false;
3306 } else {
3307 // (x << 8) & 0xff00
3308 // (x << 8) & 0xff000000
3309 if (N0.getOpcode() != ISD::SHL)
3310 return false;
3311 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3312 if (!C || C->getZExtValue() != 8)
3313 return false;
3314 }
3315 } else if (Opc == ISD::SHL) {
3316 // (x & 0xff) << 8
3317 // (x & 0xff0000) << 8
3318 if (Num != 0 && Num != 2)
3319 return false;
3320 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3321 if (!C || C->getZExtValue() != 8)
3322 return false;
3323 } else { // Opc == ISD::SRL
3324 // (x & 0xff00) >> 8
3325 // (x & 0xff000000) >> 8
3326 if (Num != 1 && Num != 3)
3327 return false;
3328 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3329 if (!C || C->getZExtValue() != 8)
3330 return false;
3331 }
3332
3333 if (Parts[Num])
3334 return false;
3335
3336 Parts[Num] = N0.getOperand(0).getNode();
3337 return true;
3338}
3339
Sanjay Patel50cbfc52014-08-28 16:29:51 +00003340/// Match a 32-bit packed halfword bswap. That is
3341/// ((x & 0x000000ff) << 8) |
3342/// ((x & 0x0000ff00) >> 8) |
3343/// ((x & 0x00ff0000) << 8) |
3344/// ((x & 0xff000000) >> 8)
Evan Cheng4c0bd962011-06-21 06:01:08 +00003345/// => (rotl (bswap x), 16)
3346SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3347 if (!LegalOperations)
3348 return SDValue();
3349
3350 EVT VT = N->getValueType(0);
3351 if (VT != MVT::i32)
3352 return SDValue();
3353 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3354 return SDValue();
3355
Evan Cheng4c0bd962011-06-21 06:01:08 +00003356 // Look for either
3357 // (or (or (and), (and)), (or (and), (and)))
3358 // (or (or (or (and), (and)), (and)), (and))
3359 if (N0.getOpcode() != ISD::OR)
3360 return SDValue();
3361 SDValue N00 = N0.getOperand(0);
3362 SDValue N01 = N0.getOperand(1);
Benjamin Kramer7ad22402014-10-22 19:55:26 +00003363 SDNode *Parts[4] = {};
Evan Cheng4c0bd962011-06-21 06:01:08 +00003364
Evan Chengbf0baa92012-12-13 01:34:32 +00003365 if (N1.getOpcode() == ISD::OR &&
3366 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
Evan Cheng4c0bd962011-06-21 06:01:08 +00003367 // (or (or (and), (and)), (or (and), (and)))
3368 SDValue N000 = N00.getOperand(0);
3369 if (!isBSwapHWordElement(N000, Parts))
3370 return SDValue();
3371
3372 SDValue N001 = N00.getOperand(1);
3373 if (!isBSwapHWordElement(N001, Parts))
3374 return SDValue();
3375 SDValue N010 = N01.getOperand(0);
3376 if (!isBSwapHWordElement(N010, Parts))
3377 return SDValue();
3378 SDValue N011 = N01.getOperand(1);
3379 if (!isBSwapHWordElement(N011, Parts))
3380 return SDValue();
3381 } else {
3382 // (or (or (or (and), (and)), (and)), (and))
3383 if (!isBSwapHWordElement(N1, Parts))
3384 return SDValue();
3385 if (!isBSwapHWordElement(N01, Parts))
3386 return SDValue();
3387 if (N00.getOpcode() != ISD::OR)
3388 return SDValue();
3389 SDValue N000 = N00.getOperand(0);
3390 if (!isBSwapHWordElement(N000, Parts))
3391 return SDValue();
3392 SDValue N001 = N00.getOperand(1);
3393 if (!isBSwapHWordElement(N001, Parts))
3394 return SDValue();
3395 }
3396
3397 // Make sure the parts are all coming from the same node.
3398 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3399 return SDValue();
3400
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003401 SDLoc DL(N);
3402 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3403 SDValue(Parts[0], 0));
Evan Cheng4c0bd962011-06-21 06:01:08 +00003404
Kay Tiong Khoo9195a5b2013-09-23 18:43:51 +00003405 // Result of the bswap should be rotated by 16. If it's not legal, then
Evan Cheng4c0bd962011-06-21 06:01:08 +00003406 // do (x << 16) | (x >> 16).
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003407 SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
Evan Cheng4c0bd962011-06-21 06:01:08 +00003408 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003409 return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
Craig Topper5f9791f2012-09-29 07:18:53 +00003410 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003411 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3412 return DAG.getNode(ISD::OR, DL, VT,
3413 DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3414 DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
Evan Cheng4c0bd962011-06-21 06:01:08 +00003415}
3416
Matthias Braun3ecb5572015-03-06 19:49:06 +00003417/// This contains all DAGCombine rules which reduce two values combined by
3418/// an Or operation to a single value \see visitANDLike().
3419SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3420 EVT VT = N1.getValueType();
3421 // fold (or x, undef) -> -1
3422 if (!LegalOperations &&
3423 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3424 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003425 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3426 SDLoc(LocReference), VT);
Matthias Braun3ecb5572015-03-06 19:49:06 +00003427 }
3428 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3429 SDValue LL, LR, RL, RR, CC0, CC1;
3430 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3431 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3432 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3433
Matthias Braun03312192015-05-19 00:25:20 +00003434 if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) {
Matthias Braun3ecb5572015-03-06 19:49:06 +00003435 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3436 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
Matthias Braun1505efb2015-05-18 23:07:27 +00003437 if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
Matthias Braun3ecb5572015-03-06 19:49:06 +00003438 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3439 LR.getValueType(), LL, RL);
3440 AddToWorklist(ORNode.getNode());
3441 return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3442 }
3443 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3444 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
Matthias Braun03312192015-05-19 00:25:20 +00003445 if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
Matthias Braun3ecb5572015-03-06 19:49:06 +00003446 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3447 LR.getValueType(), LL, RL);
3448 AddToWorklist(ANDNode.getNode());
3449 return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3450 }
3451 }
3452 // canonicalize equivalent to ll == rl
3453 if (LL == RR && LR == RL) {
3454 Op1 = ISD::getSetCCSwappedOperands(Op1);
3455 std::swap(RL, RR);
3456 }
3457 if (LL == RL && LR == RR) {
3458 bool isInteger = LL.getValueType().isInteger();
3459 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3460 if (Result != ISD::SETCC_INVALID &&
3461 (!LegalOperations ||
3462 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3463 TLI.isOperationLegal(ISD::SETCC,
3464 getSetCCResultType(N0.getValueType())))))
3465 return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3466 LL, LR, Result);
3467 }
3468 }
3469
3470 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3471 if (N0.getOpcode() == ISD::AND &&
3472 N1.getOpcode() == ISD::AND &&
3473 N0.getOperand(1).getOpcode() == ISD::Constant &&
3474 N1.getOperand(1).getOpcode() == ISD::Constant &&
3475 // Don't increase # computations.
3476 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3477 // We can only do this xform if we know that bits from X that are set in C2
3478 // but not in C1 are already zero. Likewise for Y.
3479 const APInt &LHSMask =
3480 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3481 const APInt &RHSMask =
3482 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3483
3484 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3485 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3486 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3487 N0.getOperand(0), N1.getOperand(0));
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003488 SDLoc DL(LocReference);
3489 return DAG.getNode(ISD::AND, DL, VT, X,
3490 DAG.getConstant(LHSMask | RHSMask, DL, VT));
Matthias Braun3ecb5572015-03-06 19:49:06 +00003491 }
3492 }
3493
3494 // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3495 if (N0.getOpcode() == ISD::AND &&
3496 N1.getOpcode() == ISD::AND &&
3497 N0.getOperand(0) == N1.getOperand(0) &&
3498 // Don't increase # computations.
3499 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3500 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3501 N0.getOperand(1), N1.getOperand(1));
3502 return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3503 }
3504
3505 return SDValue();
3506}
3507
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003508SDValue DAGCombiner::visitOR(SDNode *N) {
3509 SDValue N0 = N->getOperand(0);
3510 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00003511 EVT VT = N1.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003512
Dan Gohmana8665142007-06-25 16:23:39 +00003513 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00003514 if (VT.isVector()) {
Simon Pilgrimdcbe1212015-03-29 19:13:40 +00003515 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3516 return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00003517
3518 // fold (or x, 0) -> x, vector edition
3519 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3520 return N1;
3521 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3522 return N0;
3523
3524 // fold (or x, -1) -> -1, vector edition
3525 if (ISD::isBuildVectorAllOnes(N0.getNode()))
David Xuf7aff682014-09-11 05:10:28 +00003526 // do not return N0, because undef node may exist in N0
3527 return DAG.getConstant(
3528 APInt::getAllOnesValue(
3529 N0.getValueType().getScalarType().getSizeInBits()),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003530 SDLoc(N), N0.getValueType());
Craig Toppera183ddb2012-12-08 22:49:19 +00003531 if (ISD::isBuildVectorAllOnes(N1.getNode()))
David Xuf7aff682014-09-11 05:10:28 +00003532 // do not return N1, because undef node may exist in N1
3533 return DAG.getConstant(
3534 APInt::getAllOnesValue(
3535 N1.getValueType().getScalarType().getSizeInBits()),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003536 SDLoc(N), N1.getValueType());
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003537
3538 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3539 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3540 // Do this only if the resulting shuffle is legal.
3541 if (isa<ShuffleVectorSDNode>(N0) &&
3542 isa<ShuffleVectorSDNode>(N1) &&
Andrea Di Biagio2152a6c2014-07-15 00:02:32 +00003543 // Avoid folding a node with illegal type.
3544 TLI.isTypeLegal(VT) &&
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003545 N0->getOperand(1) == N1->getOperand(1) &&
3546 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3547 bool CanFold = true;
3548 unsigned NumElts = VT.getVectorNumElements();
3549 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3550 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3551 // We construct two shuffle masks:
3552 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3553 // and N1 as the second operand.
3554 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3555 // and N0 as the second operand.
3556 // We do this because OR is commutable and therefore there might be
3557 // two ways to fold this node into a shuffle.
3558 SmallVector<int,4> Mask1;
3559 SmallVector<int,4> Mask2;
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00003560
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003561 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3562 int M0 = SV0->getMaskElt(i);
3563 int M1 = SV1->getMaskElt(i);
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00003564
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003565 // Both shuffle indexes are undef. Propagate Undef.
3566 if (M0 < 0 && M1 < 0) {
3567 Mask1.push_back(M0);
3568 Mask2.push_back(M0);
3569 continue;
3570 }
3571
3572 if (M0 < 0 || M1 < 0 ||
3573 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3574 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3575 CanFold = false;
3576 break;
3577 }
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00003578
Andrea Di Biagio6292a142014-03-06 20:19:52 +00003579 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3580 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3581 }
3582
3583 if (CanFold) {
3584 // Fold this sequence only if the resulting shuffle is 'legal'.
3585 if (TLI.isShuffleMaskLegal(Mask1, VT))
3586 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3587 N1->getOperand(0), &Mask1[0]);
3588 if (TLI.isShuffleMaskLegal(Mask2, VT))
3589 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3590 N0->getOperand(0), &Mask2[0]);
3591 }
3592 }
Dan Gohman80f9f072007-07-13 20:03:40 +00003593 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003594
Nate Begeman21158fc2005-09-01 00:19:25 +00003595 // fold (or c1, c2) -> c1|c2
Matthias Braun00a40762015-02-24 18:52:01 +00003596 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3597 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003598 if (N0C && N1C)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003599 return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003600 // canonicalize constant to RHS
Simon Pilgrim20b7aba2015-04-04 10:20:31 +00003601 if (isConstantIntBuildVectorOrConstantInt(N0) &&
3602 !isConstantIntBuildVectorOrConstantInt(N1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003603 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00003604 // fold (or x, 0) -> x
Matthias Braun1505efb2015-05-18 23:07:27 +00003605 if (isNullConstant(N1))
Nate Begemand23739d2005-09-06 04:43:02 +00003606 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00003607 // fold (or x, -1) -> -1
Matthias Braun03312192015-05-19 00:25:20 +00003608 if (isAllOnesConstant(N1))
Nate Begemand23739d2005-09-06 04:43:02 +00003609 return N1;
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003610 // fold (or x, c) -> c iff (x & ~c) == 0
Dan Gohman1f372ed2008-02-25 21:11:39 +00003611 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
Nate Begemand23739d2005-09-06 04:43:02 +00003612 return N1;
Evan Cheng4c0bd962011-06-21 06:01:08 +00003613
Matthias Braun3ecb5572015-03-06 19:49:06 +00003614 if (SDValue Combined = visitORLike(N0, N1, N))
3615 return Combined;
3616
Evan Cheng4c0bd962011-06-21 06:01:08 +00003617 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3618 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003619 if (BSwap.getNode())
Evan Cheng4c0bd962011-06-21 06:01:08 +00003620 return BSwap;
3621 BSwap = MatchBSwapHWordLow(N, N0, N1);
Craig Topperc0196b12014-04-14 00:51:57 +00003622 if (BSwap.getNode())
Evan Cheng4c0bd962011-06-21 06:01:08 +00003623 return BSwap;
3624
Nate Begeman22e251a2006-02-03 06:46:56 +00003625 // reassociate or
Simon Pilgrimd15c2802015-03-29 16:49:51 +00003626 if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
Nate Begeman22e251a2006-02-03 06:46:56 +00003627 return ROR;
3628 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003629 // iff (c1 & c2) == 0.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003630 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
Chris Lattnerd8c5c062005-10-27 05:06:38 +00003631 isa<ConstantSDNode>(N0.getOperand(1))) {
Chris Lattnerd8c5c062005-10-27 05:06:38 +00003632 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
Juergen Ributzkaf26beda2014-01-25 02:02:55 +00003633 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003634 if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3635 N1C, C1))
Matthias Braunf50ab432015-01-13 22:17:46 +00003636 return DAG.getNode(
3637 ISD::AND, SDLoc(N), VT,
3638 DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3639 return SDValue();
Juergen Ributzkaf26beda2014-01-25 02:02:55 +00003640 }
Nate Begeman85c1cc42005-09-08 20:18:10 +00003641 }
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003642 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
Chris Lattner8d6fc202006-05-05 05:51:50 +00003643 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003644 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00003645 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00003646 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003647
Chris Lattner97614c82006-09-14 20:50:57 +00003648 // See if this is some rotate idiom.
Andrew Trickef9de2a2013-05-25 02:42:55 +00003649 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003650 return SDValue(Rot, 0);
Chris Lattner8d6fc202006-05-05 05:51:50 +00003651
Dan Gohman600f62b2010-06-24 14:30:44 +00003652 // Simplify the operands using demanded-bits information.
3653 if (!VT.isVector() &&
3654 SimplifyDemandedBits(SDValue(N, 0)))
3655 return SDValue(N, 0);
3656
Evan Chengf1005572010-04-28 07:10:39 +00003657 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00003658}
3659
Sanjay Patel50cbfc52014-08-28 16:29:51 +00003660/// Match "(X shl/srl V1) & V2" where V2 may not be present.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003661static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
Chris Lattner97614c82006-09-14 20:50:57 +00003662 if (Op.getOpcode() == ISD::AND) {
Reid Spencerde46e482006-11-02 20:25:50 +00003663 if (isa<ConstantSDNode>(Op.getOperand(1))) {
Chris Lattner97614c82006-09-14 20:50:57 +00003664 Mask = Op.getOperand(1);
3665 Op = Op.getOperand(0);
3666 } else {
3667 return false;
3668 }
3669 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003670
Chris Lattner97614c82006-09-14 20:50:57 +00003671 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3672 Shift = Op;
3673 return true;
3674 }
Bill Wendlingf29b6e12009-01-30 20:59:34 +00003675
Scott Michelcf0da6c2009-02-17 22:15:04 +00003676 return false;
Chris Lattner97614c82006-09-14 20:50:57 +00003677}
3678
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003679// Return true if we can prove that, whenever Neg and Pos are both in the
3680// range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
Richard Sandiford0f264db2014-01-09 10:49:40 +00003681// for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3682//
3683// (or (shift1 X, Neg), (shift2 X, Pos))
3684//
Adam Nemetc6553a82014-03-07 23:56:24 +00003685// reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3686// in direction shift1 by Neg. The range [0, OpSize) means that we only need
3687// to consider shift amounts with defined behavior.
Richard Sandiford0f264db2014-01-09 10:49:40 +00003688static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003689 // If OpSize is a power of 2 then:
3690 //
3691 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3692 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3693 //
3694 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3695 // for the stronger condition:
3696 //
3697 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3698 //
3699 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3700 // we can just replace Neg with Neg' for the rest of the function.
3701 //
3702 // In other cases we check for the even stronger condition:
3703 //
3704 // Neg == OpSize - Pos [B]
3705 //
3706 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3707 // behavior if Pos == 0 (and consequently Neg == OpSize).
Adam Nemetc6553a82014-03-07 23:56:24 +00003708 //
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003709 // We could actually use [A] whenever OpSize is a power of 2, but the
3710 // only extra cases that it would match are those uninteresting ones
3711 // where Neg and Pos are never in range at the same time. E.g. for
3712 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3713 // as well as (sub 32, Pos), but:
3714 //
3715 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3716 //
3717 // always invokes undefined behavior for 32-bit X.
3718 //
3719 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
Adam Nemetc6553a82014-03-07 23:56:24 +00003720 unsigned MaskLoBits = 0;
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003721 if (Neg.getOpcode() == ISD::AND &&
3722 isPowerOf2_64(OpSize) &&
3723 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3724 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3725 Neg = Neg.getOperand(0);
Adam Nemetc6553a82014-03-07 23:56:24 +00003726 MaskLoBits = Log2_64(OpSize);
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003727 }
3728
Richard Sandiford0f264db2014-01-09 10:49:40 +00003729 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3730 if (Neg.getOpcode() != ISD::SUB)
3731 return 0;
3732 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3733 if (!NegC)
3734 return 0;
3735 SDValue NegOp1 = Neg.getOperand(1);
3736
Adam Nemet5117f5d2014-03-07 23:56:28 +00003737 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3738 // Pos'. The truncation is redundant for the purpose of the equality.
3739 if (MaskLoBits &&
3740 Pos.getOpcode() == ISD::AND &&
3741 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3742 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3743 Pos = Pos.getOperand(0);
3744
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003745 // The condition we need is now:
3746 //
3747 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3748 //
3749 // If NegOp1 == Pos then we need:
3750 //
3751 // OpSize & Mask == NegC & Mask
3752 //
3753 // (because "x & Mask" is a truncation and distributes through subtraction).
3754 APInt Width;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003755 if (Pos == NegOp1)
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003756 Width = NegC->getAPIntValue();
Richard Sandiford0f264db2014-01-09 10:49:40 +00003757 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3758 // Then the condition we want to prove becomes:
Richard Sandiford0f264db2014-01-09 10:49:40 +00003759 //
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003760 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3761 //
3762 // which, again because "x & Mask" is a truncation, becomes:
3763 //
3764 // NegC & Mask == (OpSize - PosC) & Mask
3765 // OpSize & Mask == (NegC + PosC) & Mask
3766 else if (Pos.getOpcode() == ISD::ADD &&
3767 Pos.getOperand(0) == NegOp1 &&
3768 Pos.getOperand(1).getOpcode() == ISD::Constant)
3769 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3770 NegC->getAPIntValue());
3771 else
3772 return false;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003773
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003774 // Now we just need to check that OpSize & Mask == Width & Mask.
Adam Nemetc6553a82014-03-07 23:56:24 +00003775 if (MaskLoBits)
3776 // Opsize & Mask is 0 since Mask is Opsize - 1.
3777 return Width.getLoBits(MaskLoBits) == 0;
Richard Sandiford15cfc1c2014-01-09 10:56:42 +00003778 return Width == OpSize;
Richard Sandiford0f264db2014-01-09 10:49:40 +00003779}
3780
Richard Sandiford95c864d2014-01-08 15:40:47 +00003781// A subroutine of MatchRotate used once we have found an OR of two opposite
3782// shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3783// to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3784// former being preferred if supported. InnerPos and InnerNeg are Pos and
3785// Neg with outer conversions stripped away.
3786SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3787 SDValue Neg, SDValue InnerPos,
3788 SDValue InnerNeg, unsigned PosOpcode,
3789 unsigned NegOpcode, SDLoc DL) {
Richard Sandiford95c864d2014-01-08 15:40:47 +00003790 // fold (or (shl x, (*ext y)),
3791 // (srl x, (*ext (sub 32, y)))) ->
3792 // (rotl x, y) or (rotr x, (sub 32, y))
3793 //
3794 // fold (or (shl x, (*ext (sub 32, y))),
3795 // (srl x, (*ext y))) ->
3796 // (rotr x, y) or (rotl x, (sub 32, y))
3797 EVT VT = Shifted.getValueType();
Richard Sandiford0f264db2014-01-09 10:49:40 +00003798 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
Richard Sandiford95c864d2014-01-08 15:40:47 +00003799 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3800 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3801 HasPos ? Pos : Neg).getNode();
3802 }
3803
Craig Topperc0196b12014-04-14 00:51:57 +00003804 return nullptr;
Richard Sandiford95c864d2014-01-08 15:40:47 +00003805}
3806
Chris Lattner97614c82006-09-14 20:50:57 +00003807// MatchRotate - Handle an 'or' of two operands. If this is one of the many
3808// idioms for rotate, and if the target supports rotation instructions, generate
3809// a rot[lr].
Andrew Trickef9de2a2013-05-25 02:42:55 +00003810SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
Duncan Sands8651e9c2008-06-13 19:07:40 +00003811 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
Owen Anderson53aa7a92009-08-10 22:56:29 +00003812 EVT VT = LHS.getValueType();
Craig Topperc0196b12014-04-14 00:51:57 +00003813 if (!TLI.isTypeLegal(VT)) return nullptr;
Chris Lattner97614c82006-09-14 20:50:57 +00003814
3815 // The target must have at least one rotate flavor.
Dan Gohman4aa18462009-01-28 17:46:25 +00003816 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3817 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
Craig Topperc0196b12014-04-14 00:51:57 +00003818 if (!HasROTL && !HasROTR) return nullptr;
Duncan Sands8651e9c2008-06-13 19:07:40 +00003819
Chris Lattner97614c82006-09-14 20:50:57 +00003820 // Match "(X shl/srl V1) & V2" where V2 may not be present.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003821 SDValue LHSShift; // The shift.
3822 SDValue LHSMask; // AND value if any.
Chris Lattner97614c82006-09-14 20:50:57 +00003823 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
Craig Topperc0196b12014-04-14 00:51:57 +00003824 return nullptr; // Not part of a rotate.
Chris Lattner97614c82006-09-14 20:50:57 +00003825
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003826 SDValue RHSShift; // The shift.
3827 SDValue RHSMask; // AND value if any.
Chris Lattner97614c82006-09-14 20:50:57 +00003828 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
Craig Topperc0196b12014-04-14 00:51:57 +00003829 return nullptr; // Not part of a rotate.
Scott Michelcf0da6c2009-02-17 22:15:04 +00003830
Chris Lattner97614c82006-09-14 20:50:57 +00003831 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
Craig Topperc0196b12014-04-14 00:51:57 +00003832 return nullptr; // Not shifting the same value.
Chris Lattner97614c82006-09-14 20:50:57 +00003833
3834 if (LHSShift.getOpcode() == RHSShift.getOpcode())
Craig Topperc0196b12014-04-14 00:51:57 +00003835 return nullptr; // Shifts must disagree.
Scott Michelcf0da6c2009-02-17 22:15:04 +00003836
Chris Lattner97614c82006-09-14 20:50:57 +00003837 // Canonicalize shl to left side in a shl/srl pair.
3838 if (RHSShift.getOpcode() == ISD::SHL) {
3839 std::swap(LHS, RHS);
3840 std::swap(LHSShift, RHSShift);
3841 std::swap(LHSMask , RHSMask );
3842 }
3843
Duncan Sands13237ac2008-06-06 12:08:01 +00003844 unsigned OpSizeInBits = VT.getSizeInBits();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003845 SDValue LHSShiftArg = LHSShift.getOperand(0);
3846 SDValue LHSShiftAmt = LHSShift.getOperand(1);
Kai Nacked09bb462013-09-19 23:00:28 +00003847 SDValue RHSShiftArg = RHSShift.getOperand(0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003848 SDValue RHSShiftAmt = RHSShift.getOperand(1);
Chris Lattner97614c82006-09-14 20:50:57 +00003849
3850 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3851 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
Scott Michel16627a52007-04-02 21:36:32 +00003852 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3853 RHSShiftAmt.getOpcode() == ISD::Constant) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00003854 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3855 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
Chris Lattner97614c82006-09-14 20:50:57 +00003856 if ((LShVal + RShVal) != OpSizeInBits)
Craig Topperc0196b12014-04-14 00:51:57 +00003857 return nullptr;
Chris Lattner97614c82006-09-14 20:50:57 +00003858
Craig Topper65161fa2012-09-29 06:54:22 +00003859 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3860 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003861
Chris Lattner97614c82006-09-14 20:50:57 +00003862 // If there is an AND of either shifted operand, apply it to the result.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003863 if (LHSMask.getNode() || RHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003864 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
Scott Michelcf0da6c2009-02-17 22:15:04 +00003865
Gabor Greiff304a7a2008-08-28 21:40:38 +00003866 if (LHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003867 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3868 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
Chris Lattner97614c82006-09-14 20:50:57 +00003869 }
Gabor Greiff304a7a2008-08-28 21:40:38 +00003870 if (RHSMask.getNode()) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00003871 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3872 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
Chris Lattner97614c82006-09-14 20:50:57 +00003873 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003874
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003875 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, DL, VT));
Chris Lattner97614c82006-09-14 20:50:57 +00003876 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003877
Gabor Greiff304a7a2008-08-28 21:40:38 +00003878 return Rot.getNode();
Chris Lattner97614c82006-09-14 20:50:57 +00003879 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003880
Chris Lattner97614c82006-09-14 20:50:57 +00003881 // If there is a mask here, and we have a variable shift, we can't be sure
3882 // that we're masking out the right stuff.
Gabor Greiff304a7a2008-08-28 21:40:38 +00003883 if (LHSMask.getNode() || RHSMask.getNode())
Craig Topperc0196b12014-04-14 00:51:57 +00003884 return nullptr;
Scott Michelcf0da6c2009-02-17 22:15:04 +00003885
Benjamin Kramer64bdb292013-09-24 14:21:28 +00003886 // If the shift amount is sign/zext/any-extended just peel it off.
3887 SDValue LExtOp0 = LHSShiftAmt;
3888 SDValue RExtOp0 = RHSShiftAmt;
Craig Topper5f9791f2012-09-29 07:18:53 +00003889 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3890 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3891 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3892 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3893 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3894 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3895 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3896 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
Benjamin Kramer64bdb292013-09-24 14:21:28 +00003897 LExtOp0 = LHSShiftAmt.getOperand(0);
3898 RExtOp0 = RHSShiftAmt.getOperand(0);
3899 }
3900
Richard Sandiford95c864d2014-01-08 15:40:47 +00003901 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3902 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3903 if (TryL)
3904 return TryL;
3905
3906 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3907 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3908 if (TryR)
3909 return TryR;
Scott Michelcf0da6c2009-02-17 22:15:04 +00003910
Craig Topperc0196b12014-04-14 00:51:57 +00003911 return nullptr;
Chris Lattner97614c82006-09-14 20:50:57 +00003912}
3913
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003914SDValue DAGCombiner::visitXOR(SDNode *N) {
3915 SDValue N0 = N->getOperand(0);
3916 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00003917 EVT VT = N0.getValueType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00003918
Dan Gohmana8665142007-06-25 16:23:39 +00003919 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00003920 if (VT.isVector()) {
Simon Pilgrimdcbe1212015-03-29 19:13:40 +00003921 if (SDValue FoldedVOp = SimplifyVBinOp(N))
3922 return FoldedVOp;
Craig Toppera183ddb2012-12-08 22:49:19 +00003923
3924 // fold (xor x, 0) -> x, vector edition
3925 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3926 return N1;
3927 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3928 return N0;
Dan Gohman80f9f072007-07-13 20:03:40 +00003929 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003930
Evan Chengdf1690d2008-03-25 20:08:07 +00003931 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3932 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003933 return DAG.getConstant(0, SDLoc(N), VT);
Dan Gohman06563a82007-07-03 14:03:57 +00003934 // fold (xor x, undef) -> undef
Dan Gohmanadb3d372007-07-10 15:19:29 +00003935 if (N0.getOpcode() == ISD::UNDEF)
3936 return N0;
3937 if (N1.getOpcode() == ISD::UNDEF)
Dan Gohman06563a82007-07-03 14:03:57 +00003938 return N1;
Nate Begeman21158fc2005-09-01 00:19:25 +00003939 // fold (xor c1, c2) -> c1^c2
Matthias Braun00a40762015-02-24 18:52:01 +00003940 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3941 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003942 if (N0C && N1C)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003943 return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003944 // canonicalize constant to RHS
Simon Pilgrim20b7aba2015-04-04 10:20:31 +00003945 if (isConstantIntBuildVectorOrConstantInt(N0) &&
3946 !isConstantIntBuildVectorOrConstantInt(N1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00003947 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00003948 // fold (xor x, 0) -> x
Matthias Braun1505efb2015-05-18 23:07:27 +00003949 if (isNullConstant(N1))
Nate Begemand23739d2005-09-06 04:43:02 +00003950 return N0;
Nate Begeman22e251a2006-02-03 06:46:56 +00003951 // reassociate xor
Simon Pilgrimd15c2802015-03-29 16:49:51 +00003952 if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
Nate Begeman22e251a2006-02-03 06:46:56 +00003953 return RXOR;
Bill Wendling49a5ce82008-11-11 08:25:46 +00003954
Nate Begeman21158fc2005-09-01 00:19:25 +00003955 // fold !(x cc y) -> (x !cc y)
Matthias Brauna8558ca2015-02-24 18:51:59 +00003956 SDValue LHS, RHS, CC;
Oliver Stannardd29db9b2014-11-17 10:49:31 +00003957 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
Duncan Sands13237ac2008-06-06 12:08:01 +00003958 bool isInt = LHS.getValueType().isInteger();
Nate Begeman7cea6ef2005-09-02 21:18:40 +00003959 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3960 isInt);
Bill Wendling49a5ce82008-11-11 08:25:46 +00003961
Patrik Hagglundffd057a2012-12-19 10:19:55 +00003962 if (!LegalOperations ||
3963 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
Bill Wendling49a5ce82008-11-11 08:25:46 +00003964 switch (N0.getOpcode()) {
3965 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +00003966 llvm_unreachable("Unhandled SetCC Equivalent!");
Bill Wendling49a5ce82008-11-11 08:25:46 +00003967 case ISD::SETCC:
Andrew Trickef9de2a2013-05-25 02:42:55 +00003968 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
Bill Wendling49a5ce82008-11-11 08:25:46 +00003969 case ISD::SELECT_CC:
Andrew Trickef9de2a2013-05-25 02:42:55 +00003970 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
Bill Wendling49a5ce82008-11-11 08:25:46 +00003971 N0.getOperand(3), NotCC);
3972 }
3973 }
Nate Begeman21158fc2005-09-01 00:19:25 +00003974 }
Bill Wendling49a5ce82008-11-11 08:25:46 +00003975
Chris Lattner58c227b2007-09-10 21:39:07 +00003976 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
Matthias Braun887fdfb2015-05-19 00:25:21 +00003977 if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
Gabor Greife12264b2008-08-30 19:29:20 +00003978 N0.getNode()->hasOneUse() &&
3979 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003980 SDValue V = N0.getOperand(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003981 SDLoc DL(N0);
3982 V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
3983 DAG.getConstant(1, DL, V.getValueType()));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003984 AddToWorklist(V.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003985 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
Chris Lattner58c227b2007-09-10 21:39:07 +00003986 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00003987
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003988 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
Matthias Braun887fdfb2015-05-19 00:25:21 +00003989 if (isOneConstant(N1) && VT == MVT::i1 &&
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003990 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00003991 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00003992 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3993 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
Andrew Trickef9de2a2013-05-25 02:42:55 +00003994 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3995 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
Chandler Carruth3c0012b2014-07-21 08:56:44 +00003996 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00003997 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
Nate Begeman21158fc2005-09-01 00:19:25 +00003998 }
3999 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00004000 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
Matthias Braun03312192015-05-19 00:25:20 +00004001 if (isAllOnesConstant(N1) &&
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00004002 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004003 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
Nate Begeman2cc2c9a2005-09-07 23:25:52 +00004004 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4005 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
Andrew Trickef9de2a2013-05-25 02:42:55 +00004006 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4007 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004008 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004009 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
Nate Begeman21158fc2005-09-01 00:19:25 +00004010 }
4011 }
David Majnemer386ab7f2013-05-08 06:44:42 +00004012 // fold (xor (and x, y), y) -> (and (not x), y)
4013 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
Benjamin Kramerbb1dd732013-11-17 10:40:03 +00004014 N0->getOperand(1) == N1) {
David Majnemer386ab7f2013-05-08 06:44:42 +00004015 SDValue X = N0->getOperand(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00004016 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004017 AddToWorklist(NotX.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004018 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
David Majnemer386ab7f2013-05-08 06:44:42 +00004019 }
Bill Wendling35972a92009-01-30 21:14:50 +00004020 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
Nate Begeman85c1cc42005-09-08 20:18:10 +00004021 if (N1C && N0.getOpcode() == ISD::XOR) {
4022 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
4023 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004024 if (N00C) {
4025 SDLoc DL(N);
4026 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
Bill Wendling35972a92009-01-30 21:14:50 +00004027 DAG.getConstant(N1C->getAPIntValue() ^
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004028 N00C->getAPIntValue(), DL, VT));
4029 }
4030 if (N01C) {
4031 SDLoc DL(N);
4032 return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
Bill Wendling35972a92009-01-30 21:14:50 +00004033 DAG.getConstant(N1C->getAPIntValue() ^
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004034 N01C->getAPIntValue(), DL, VT));
4035 }
Nate Begeman85c1cc42005-09-08 20:18:10 +00004036 }
4037 // fold (xor x, x) -> 0
Eric Christophere5ca1e02011-02-16 04:50:12 +00004038 if (N0 == N1)
Hal Finkel6c29bd92013-07-09 17:02:45 +00004039 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004040
David Majnemere48237d2015-03-18 00:03:36 +00004041 // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4042 // Here is a concrete example of this equivalence:
4043 // i16 x == 14
4044 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000
4045 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4046 //
4047 // =>
4048 //
4049 // i16 ~1 == 0b1111111111111110
4050 // i16 rol(~1, 14) == 0b1011111111111111
4051 //
4052 // Some additional tips to help conceptualize this transform:
4053 // - Try to see the operation as placing a single zero in a value of all ones.
4054 // - There exists no value for x which would allow the result to contain zero.
4055 // - Values of x larger than the bitwidth are undefined and do not require a
4056 // consistent result.
4057 // - Pushing the zero left requires shifting one bits in from the right.
4058 // A rotate left of ~1 is a nice way of achieving the desired result.
Matthias Braun887fdfb2015-05-19 00:25:21 +00004059 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
4060 && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
4061 SDLoc DL(N);
4062 return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4063 N0.getOperand(1));
4064 }
David Majnemere48237d2015-03-18 00:03:36 +00004065
Chris Lattner8d6fc202006-05-05 05:51:50 +00004066 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
4067 if (N0.getOpcode() == N1.getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004068 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00004069 if (Tmp.getNode()) return Tmp;
Nate Begeman049b7482005-09-09 19:49:52 +00004070 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004071
Chris Lattner098c01e2006-04-08 04:15:24 +00004072 // Simplify the expression using non-local knowledge.
Duncan Sands13237ac2008-06-06 12:08:01 +00004073 if (!VT.isVector() &&
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004074 SimplifyDemandedBits(SDValue(N, 0)))
4075 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004076
Evan Chengf1005572010-04-28 07:10:39 +00004077 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004078}
4079
Sanjay Patel50cbfc52014-08-28 16:29:51 +00004080/// Handle transforms common to the three shifts, when the shift amount is a
4081/// constant.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004082SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00004083 // We can't and shouldn't fold opaque constants.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004084 if (Amt->isOpaque())
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00004085 return SDValue();
4086
Gabor Greiff304a7a2008-08-28 21:40:38 +00004087 SDNode *LHS = N->getOperand(0).getNode();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004088 if (!LHS->hasOneUse()) return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004089
Chris Lattner7c709a52007-12-06 07:33:36 +00004090 // We want to pull some binops through shifts, so that we have (and (shift))
4091 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
4092 // thing happens with address calculations, so it's important to canonicalize
4093 // it.
4094 bool HighBitSet = false; // Can we transform this if the high bit is set?
Scott Michelcf0da6c2009-02-17 22:15:04 +00004095
Chris Lattner7c709a52007-12-06 07:33:36 +00004096 switch (LHS->getOpcode()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004097 default: return SDValue();
Chris Lattner7c709a52007-12-06 07:33:36 +00004098 case ISD::OR:
4099 case ISD::XOR:
4100 HighBitSet = false; // We can only transform sra if the high bit is clear.
4101 break;
4102 case ISD::AND:
4103 HighBitSet = true; // We can only transform sra if the high bit is set.
4104 break;
4105 case ISD::ADD:
Scott Michelcf0da6c2009-02-17 22:15:04 +00004106 if (N->getOpcode() != ISD::SHL)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004107 return SDValue(); // only shl(add) not sr[al](add).
Chris Lattner7c709a52007-12-06 07:33:36 +00004108 HighBitSet = false; // We can only transform sra if the high bit is clear.
4109 break;
4110 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004111
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00004112 // We require the RHS of the binop to be a constant and not opaque as well.
Chris Lattner7c709a52007-12-06 07:33:36 +00004113 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00004114 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004115
4116 // FIXME: disable this unless the input to the binop is a shift by a constant.
4117 // If it is not a shift, it pessimizes some common cases like:
Chris Lattnereedaf922007-12-06 07:47:55 +00004118 //
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004119 // void foo(int *X, int i) { X[i & 1235] = 1; }
4120 // int bar(int *X, int i) { return X[i & 255]; }
Gabor Greiff304a7a2008-08-28 21:40:38 +00004121 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004122 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
Chris Lattnereedaf922007-12-06 07:47:55 +00004123 BinOpLHSVal->getOpcode() != ISD::SRA &&
4124 BinOpLHSVal->getOpcode() != ISD::SRL) ||
4125 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004126 return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004127
Owen Anderson53aa7a92009-08-10 22:56:29 +00004128 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004129
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004130 // If this is a signed shift right, and the high bit is modified by the
4131 // logical operation, do not perform the transformation. The highBitSet
4132 // boolean indicates the value of the high bit of the constant which would
4133 // cause it to be modified for this operation.
Chris Lattner7c709a52007-12-06 07:33:36 +00004134 if (N->getOpcode() == ISD::SRA) {
Dan Gohmane1c4f992008-03-03 23:51:38 +00004135 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4136 if (BinOpRHSSignSet != HighBitSet)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004137 return SDValue();
Chris Lattner7c709a52007-12-06 07:33:36 +00004138 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004139
Weiming Zhao7f6daf12014-04-30 21:07:24 +00004140 if (!TLI.isDesirableToCommuteWithShift(LHS))
4141 return SDValue();
4142
Chris Lattner7c709a52007-12-06 07:33:36 +00004143 // Fold the constants, shifting the binop RHS by the shift amount.
Andrew Trickef9de2a2013-05-25 02:42:55 +00004144 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004145 N->getValueType(0),
4146 LHS->getOperand(1), N->getOperand(1));
Juergen Ributzkafa0eba62014-02-06 04:09:06 +00004147 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
Chris Lattner7c709a52007-12-06 07:33:36 +00004148
4149 // Create the new shift.
Eric Christopherd9e8eac2010-12-09 04:48:06 +00004150 SDValue NewShift = DAG.getNode(N->getOpcode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00004151 SDLoc(LHS->getOperand(0)),
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004152 VT, LHS->getOperand(0), N->getOperand(1));
Chris Lattner7c709a52007-12-06 07:33:36 +00004153
4154 // Create the new binop.
Andrew Trickef9de2a2013-05-25 02:42:55 +00004155 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
Chris Lattner7c709a52007-12-06 07:33:36 +00004156}
4157
Adam Nemet67483892014-03-04 23:28:31 +00004158SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4159 assert(N->getOpcode() == ISD::TRUNCATE);
4160 assert(N->getOperand(0).getOpcode() == ISD::AND);
4161
4162 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4163 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4164 SDValue N01 = N->getOperand(0).getOperand(1);
4165
Matt Arsenault985b9de2014-03-17 18:58:01 +00004166 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
Adam Nemet67483892014-03-04 23:28:31 +00004167 EVT TruncVT = N->getValueType(0);
4168 SDValue N00 = N->getOperand(0).getOperand(0);
4169 APInt TruncC = N01C->getAPIntValue();
Matt Arsenault985b9de2014-03-17 18:58:01 +00004170 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004171 SDLoc DL(N);
Adam Nemet67483892014-03-04 23:28:31 +00004172
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004173 return DAG.getNode(ISD::AND, DL, TruncVT,
4174 DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00),
4175 DAG.getConstant(TruncC, DL, TruncVT));
Adam Nemet67483892014-03-04 23:28:31 +00004176 }
4177 }
4178
4179 return SDValue();
4180}
Adam Nemet7f928f12014-03-07 23:56:30 +00004181
4182SDValue DAGCombiner::visitRotate(SDNode *N) {
4183 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4184 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4185 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4186 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4187 if (NewOp1.getNode())
4188 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4189 N->getOperand(0), NewOp1);
4190 }
4191 return SDValue();
4192}
4193
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004194SDValue DAGCombiner::visitSHL(SDNode *N) {
4195 SDValue N0 = N->getOperand(0);
4196 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004197 EVT VT = N0.getValueType();
Matt Arsenault985b9de2014-03-17 18:58:01 +00004198 unsigned OpSizeInBits = VT.getScalarSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004199
Daniel Sandersa1840d22013-11-11 17:23:41 +00004200 // fold vector ops
Matthias Braun00a40762015-02-24 18:52:01 +00004201 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Daniel Sandersa1840d22013-11-11 17:23:41 +00004202 if (VT.isVector()) {
Simon Pilgrimdcbe1212015-03-29 19:13:40 +00004203 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4204 return FoldedVOp;
Quentin Colombet4db08df2014-02-21 23:42:41 +00004205
4206 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4207 // If setcc produces all-one true value then:
4208 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
Matt Arsenault985b9de2014-03-17 18:58:01 +00004209 if (N1CV && N1CV->isConstant()) {
Daniel Sanderscbd44c52014-07-10 10:18:12 +00004210 if (N0.getOpcode() == ISD::AND) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004211 SDValue N00 = N0->getOperand(0);
4212 SDValue N01 = N0->getOperand(1);
4213 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
Quentin Colombet4db08df2014-02-21 23:42:41 +00004214
Daniel Sanderscbd44c52014-07-10 10:18:12 +00004215 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4216 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4217 TargetLowering::ZeroOrNegativeOneBooleanContent) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004218 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4219 N01CV, N1CV))
Matt Arsenault985b9de2014-03-17 18:58:01 +00004220 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4221 }
4222 } else {
4223 N1C = isConstOrConstSplat(N1);
Quentin Colombet4db08df2014-02-21 23:42:41 +00004224 }
4225 }
Daniel Sandersa1840d22013-11-11 17:23:41 +00004226 }
4227
Nate Begeman21158fc2005-09-01 00:19:25 +00004228 // fold (shl c1, c2) -> c1<<c2
Matthias Braun00a40762015-02-24 18:52:01 +00004229 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004230 if (N0C && N1C)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004231 return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00004232 // fold (shl 0, x) -> 0
Matthias Braun1505efb2015-05-18 23:07:27 +00004233 if (isNullConstant(N0))
Nate Begemand23739d2005-09-06 04:43:02 +00004234 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004235 // fold (shl x, c >= size(x)) -> undef
Dan Gohmaneffb8942008-09-12 16:56:44 +00004236 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00004237 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004238 // fold (shl x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004239 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004240 return N0;
Chad Rosier818e1162011-06-14 22:29:10 +00004241 // fold (shl undef, x) -> 0
4242 if (N0.getOpcode() == ISD::UNDEF)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004243 return DAG.getConstant(0, SDLoc(N), VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004244 // if (shl x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004245 if (DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1d459e42009-12-11 21:31:27 +00004246 APInt::getAllOnesValue(OpSizeInBits)))
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004247 return DAG.getConstant(0, SDLoc(N), VT);
Duncan Sands3ed76882009-02-01 18:06:53 +00004248 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004249 if (N1.getOpcode() == ISD::TRUNCATE &&
Adam Nemet67483892014-03-04 23:28:31 +00004250 N1.getOperand(0).getOpcode() == ISD::AND) {
4251 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4252 if (NewOp1.getNode())
4253 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004254 }
4255
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004256 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4257 return SDValue(N, 0);
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004258
4259 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
Matt Arsenault985b9de2014-03-17 18:58:01 +00004260 if (N1C && N0.getOpcode() == ISD::SHL) {
4261 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4262 uint64_t c1 = N0C1->getZExtValue();
4263 uint64_t c2 = N1C->getZExtValue();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004264 SDLoc DL(N);
Matt Arsenault985b9de2014-03-17 18:58:01 +00004265 if (c1 + c2 >= OpSizeInBits)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004266 return DAG.getConstant(0, DL, VT);
4267 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4268 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
Matt Arsenault985b9de2014-03-17 18:58:01 +00004269 }
Nate Begeman21158fc2005-09-01 00:19:25 +00004270 }
Dale Johannesena94e36b2010-12-21 21:55:50 +00004271
4272 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4273 // For this to be valid, the second form must not preserve any of the bits
4274 // that are shifted out by the inner shift in the first form. This means
4275 // the outer shift size must be >= the number of bits added by the ext.
4276 // As a corollary, we don't care what kind of ext it is.
4277 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4278 N0.getOpcode() == ISD::ANY_EXTEND ||
4279 N0.getOpcode() == ISD::SIGN_EXTEND) &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004280 N0.getOperand(0).getOpcode() == ISD::SHL) {
4281 SDValue N0Op0 = N0.getOperand(0);
4282 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4283 uint64_t c1 = N0Op0C1->getZExtValue();
4284 uint64_t c2 = N1C->getZExtValue();
4285 EVT InnerShiftVT = N0Op0.getValueType();
4286 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4287 if (c2 >= OpSizeInBits - InnerShiftSize) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004288 SDLoc DL(N0);
Matt Arsenault985b9de2014-03-17 18:58:01 +00004289 if (c1 + c2 >= OpSizeInBits)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004290 return DAG.getConstant(0, DL, VT);
4291 return DAG.getNode(ISD::SHL, DL, VT,
4292 DAG.getNode(N0.getOpcode(), DL, VT,
Matt Arsenault985b9de2014-03-17 18:58:01 +00004293 N0Op0->getOperand(0)),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004294 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
Matt Arsenault985b9de2014-03-17 18:58:01 +00004295 }
Dale Johannesena94e36b2010-12-21 21:55:50 +00004296 }
4297 }
4298
Andrea Di Biagio56ce9c42013-09-27 11:37:05 +00004299 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4300 // Only fold this if the inner zext has no other uses to avoid increasing
4301 // the total number of instructions.
4302 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004303 N0.getOperand(0).getOpcode() == ISD::SRL) {
4304 SDValue N0Op0 = N0.getOperand(0);
4305 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4306 uint64_t c1 = N0Op0C1->getZExtValue();
4307 if (c1 < VT.getScalarSizeInBits()) {
4308 uint64_t c2 = N1C->getZExtValue();
4309 if (c1 == c2) {
4310 SDValue NewOp0 = N0.getOperand(0);
4311 EVT CountVT = NewOp0.getOperand(1).getValueType();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004312 SDLoc DL(N);
4313 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4314 NewOp0,
4315 DAG.getConstant(c2, DL, CountVT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004316 AddToWorklist(NewSHL.getNode());
Matt Arsenault985b9de2014-03-17 18:58:01 +00004317 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4318 }
Andrea Di Biagio56ce9c42013-09-27 11:37:05 +00004319 }
4320 }
4321 }
4322
Eli Friedman1877ac92011-06-09 22:14:44 +00004323 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4324 // (and (srl x, (sub c1, c2), MASK)
Chandler Carruthe041a302012-01-05 11:05:55 +00004325 // Only fold this if the inner shift has no other uses -- if it does, folding
4326 // this will increase the total number of instructions.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004327 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4328 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4329 uint64_t c1 = N0C1->getZExtValue();
4330 if (c1 < OpSizeInBits) {
4331 uint64_t c2 = N1C->getZExtValue();
4332 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4333 SDValue Shift;
4334 if (c2 > c1) {
4335 Mask = Mask.shl(c2 - c1);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004336 SDLoc DL(N);
4337 Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4338 DAG.getConstant(c2 - c1, DL, N1.getValueType()));
Matt Arsenault985b9de2014-03-17 18:58:01 +00004339 } else {
4340 Mask = Mask.lshr(c1 - c2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004341 SDLoc DL(N);
4342 Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4343 DAG.getConstant(c1 - c2, DL, N1.getValueType()));
Matt Arsenault985b9de2014-03-17 18:58:01 +00004344 }
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004345 SDLoc DL(N0);
4346 return DAG.getNode(ISD::AND, DL, VT, Shift,
4347 DAG.getConstant(Mask, DL, VT));
Eli Friedman1877ac92011-06-09 22:14:44 +00004348 }
Evan Chenga7bb55e2009-07-21 05:40:15 +00004349 }
Nate Begeman21158fc2005-09-01 00:19:25 +00004350 }
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004351 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
Dan Gohman5758e1e2009-08-06 09:18:59 +00004352 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004353 unsigned BitSize = VT.getScalarSizeInBits();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004354 SDLoc DL(N);
Dan Gohman5758e1e2009-08-06 09:18:59 +00004355 SDValue HiBitsMask =
Matt Arsenault985b9de2014-03-17 18:58:01 +00004356 DAG.getConstant(APInt::getHighBitsSet(BitSize,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004357 BitSize - N1C->getZExtValue()),
4358 DL, VT);
4359 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
Dan Gohman5758e1e2009-08-06 09:18:59 +00004360 HiBitsMask);
4361 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004362
Matt Arsenault8239eaa2014-09-11 17:34:19 +00004363 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4364 // Variant of version done on multiply, except mul by a power of 2 is turned
4365 // into a shift.
4366 APInt Val;
4367 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4368 (isa<ConstantSDNode>(N0.getOperand(1)) ||
4369 isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4370 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4371 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4372 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4373 }
4374
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004375 if (N1C) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004376 SDValue NewSHL = visitShiftByConstant(N, N1C);
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004377 if (NewSHL.getNode())
4378 return NewSHL;
4379 }
4380
Evan Chengf1005572010-04-28 07:10:39 +00004381 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004382}
4383
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004384SDValue DAGCombiner::visitSRA(SDNode *N) {
4385 SDValue N0 = N->getOperand(0);
4386 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004387 EVT VT = N0.getValueType();
Dan Gohman1d459e42009-12-11 21:31:27 +00004388 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004389
Daniel Sandersa1840d22013-11-11 17:23:41 +00004390 // fold vector ops
Matthias Braun00a40762015-02-24 18:52:01 +00004391 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Daniel Sandersa1840d22013-11-11 17:23:41 +00004392 if (VT.isVector()) {
Simon Pilgrimdcbe1212015-03-29 19:13:40 +00004393 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4394 return FoldedVOp;
Matt Arsenault985b9de2014-03-17 18:58:01 +00004395
4396 N1C = isConstOrConstSplat(N1);
Daniel Sandersa1840d22013-11-11 17:23:41 +00004397 }
4398
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004399 // fold (sra c1, c2) -> (sra c1, c2)
Matthias Braun00a40762015-02-24 18:52:01 +00004400 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004401 if (N0C && N1C)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004402 return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00004403 // fold (sra 0, x) -> 0
Matthias Braun1505efb2015-05-18 23:07:27 +00004404 if (isNullConstant(N0))
Nate Begemand23739d2005-09-06 04:43:02 +00004405 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004406 // fold (sra -1, x) -> -1
Matthias Braun03312192015-05-19 00:25:20 +00004407 if (isAllOnesConstant(N0))
Nate Begemand23739d2005-09-06 04:43:02 +00004408 return N0;
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004409 // fold (sra x, (setge c, size(x))) -> undef
Dan Gohman1d459e42009-12-11 21:31:27 +00004410 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00004411 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004412 // fold (sra x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004413 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004414 return N0;
Nate Begemanfb5dbad2006-02-17 19:54:08 +00004415 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4416 // sext_inreg.
4417 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
Dan Gohman1d459e42009-12-11 21:31:27 +00004418 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004419 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4420 if (VT.isVector())
4421 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4422 ExtVT, VT.getVectorNumElements());
4423 if ((!LegalOperations ||
4424 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004425 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Dan Gohman6bd3ef82010-01-09 02:13:55 +00004426 N0.getOperand(0), DAG.getValueType(ExtVT));
Nate Begemanfb5dbad2006-02-17 19:54:08 +00004427 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00004428
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004429 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
Chris Lattner0f8a7272006-02-28 06:23:04 +00004430 if (N1C && N0.getOpcode() == ISD::SRA) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004431 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00004432 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
Matt Arsenault985b9de2014-03-17 18:58:01 +00004433 if (Sum >= OpSizeInBits)
4434 Sum = OpSizeInBits - 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004435 SDLoc DL(N);
4436 return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
4437 DAG.getConstant(Sum, DL, N1.getValueType()));
Chris Lattner0f8a7272006-02-28 06:23:04 +00004438 }
4439 }
Christopher Lamb8fe91092008-03-19 08:30:06 +00004440
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004441 // fold (sra (shl X, m), (sub result_size, n))
4442 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
Scott Michelcf0da6c2009-02-17 22:15:04 +00004443 // result_size - n != m.
4444 // If truncate is free for the target sext(shl) is likely to result in better
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004445 // code.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004446 if (N0.getOpcode() == ISD::SHL && N1C) {
Christopher Lamb8fe91092008-03-19 08:30:06 +00004447 // Get the two constanst of the shifts, CN0 = m, CN = n.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004448 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4449 if (N01C) {
4450 LLVMContext &Ctx = *DAG.getContext();
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004451 // Determine what the truncate's result bitsize and type would be.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004452 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4453
4454 if (VT.isVector())
4455 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4456
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004457 // Determine the residual right-shift amount.
Torok Edwinbe6a9a12009-05-23 17:29:48 +00004458 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
Duncan Sands8651e9c2008-06-13 19:07:40 +00004459
Scott Michelcf0da6c2009-02-17 22:15:04 +00004460 // If the shift is not a no-op (in which case this should be just a sign
4461 // extend already), the truncated to type is legal, sign_extend is legal
Dan Gohman4a618822010-02-10 16:03:48 +00004462 // on that type, and the truncate to that type is both legal and free,
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004463 // perform the transform.
Torok Edwinbe6a9a12009-05-23 17:29:48 +00004464 if ((ShiftAmt > 0) &&
Dan Gohman4aa18462009-01-28 17:46:25 +00004465 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4466 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
Evan Cheng7a3e7502008-03-20 02:18:41 +00004467 TLI.isTruncateFree(VT, TruncVT)) {
Christopher Lamb3e9f4972008-03-20 04:31:39 +00004468
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004469 SDLoc DL(N);
4470 SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4471 getShiftAmountTy(N0.getOperand(0).getValueType()));
4472 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4473 N0.getOperand(0), Amt);
4474 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4475 Shift);
4476 return DAG.getNode(ISD::SIGN_EXTEND, DL,
4477 N->getValueType(0), Trunc);
Christopher Lamb8fe91092008-03-19 08:30:06 +00004478 }
4479 }
4480 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004481
Duncan Sands3ed76882009-02-01 18:06:53 +00004482 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004483 if (N1.getOpcode() == ISD::TRUNCATE &&
Adam Nemet67483892014-03-04 23:28:31 +00004484 N1.getOperand(0).getOpcode() == ISD::AND) {
4485 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4486 if (NewOp1.getNode())
4487 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004488 }
4489
Matt Arsenault985b9de2014-03-17 18:58:01 +00004490 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
Benjamin Kramer946e1522011-01-30 16:38:43 +00004491 // if c1 is equal to the number of bits the trunc removes
4492 if (N0.getOpcode() == ISD::TRUNCATE &&
4493 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4494 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4495 N0.getOperand(0).hasOneUse() &&
4496 N0.getOperand(0).getOperand(1).hasOneUse() &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004497 N1C) {
4498 SDValue N0Op0 = N0.getOperand(0);
4499 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4500 unsigned LargeShiftVal = LargeShift->getZExtValue();
4501 EVT LargeVT = N0Op0.getValueType();
Benjamin Kramer946e1522011-01-30 16:38:43 +00004502
Matt Arsenault985b9de2014-03-17 18:58:01 +00004503 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004504 SDLoc DL(N);
Matt Arsenault985b9de2014-03-17 18:58:01 +00004505 SDValue Amt =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004506 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
Matt Arsenault985b9de2014-03-17 18:58:01 +00004507 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004508 SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
Matt Arsenault985b9de2014-03-17 18:58:01 +00004509 N0Op0.getOperand(0), Amt);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004510 return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
Matt Arsenault985b9de2014-03-17 18:58:01 +00004511 }
Benjamin Kramer946e1522011-01-30 16:38:43 +00004512 }
4513 }
4514
Scott Michelcf0da6c2009-02-17 22:15:04 +00004515 // Simplify, based on bits shifted out of the LHS.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004516 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4517 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004518
4519
Nate Begeman21158fc2005-09-01 00:19:25 +00004520 // If the sign bit is known to be zero, switch this to a SRL.
Dan Gohman1f372ed2008-02-25 21:11:39 +00004521 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004522 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
Chris Lattner7c709a52007-12-06 07:33:36 +00004523
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004524 if (N1C) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004525 SDValue NewSRA = visitShiftByConstant(N, N1C);
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004526 if (NewSRA.getNode())
4527 return NewSRA;
4528 }
4529
Evan Chengf1005572010-04-28 07:10:39 +00004530 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004531}
4532
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004533SDValue DAGCombiner::visitSRL(SDNode *N) {
4534 SDValue N0 = N->getOperand(0);
4535 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004536 EVT VT = N0.getValueType();
Dan Gohman1d459e42009-12-11 21:31:27 +00004537 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00004538
Daniel Sandersa1840d22013-11-11 17:23:41 +00004539 // fold vector ops
Matthias Braun00a40762015-02-24 18:52:01 +00004540 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
Daniel Sandersa1840d22013-11-11 17:23:41 +00004541 if (VT.isVector()) {
Simon Pilgrimdcbe1212015-03-29 19:13:40 +00004542 if (SDValue FoldedVOp = SimplifyVBinOp(N))
4543 return FoldedVOp;
Matt Arsenault985b9de2014-03-17 18:58:01 +00004544
4545 N1C = isConstOrConstSplat(N1);
Daniel Sandersa1840d22013-11-11 17:23:41 +00004546 }
4547
Nate Begeman21158fc2005-09-01 00:19:25 +00004548 // fold (srl c1, c2) -> c1 >>u c2
Matthias Braun00a40762015-02-24 18:52:01 +00004549 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004550 if (N0C && N1C)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004551 return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
Nate Begeman21158fc2005-09-01 00:19:25 +00004552 // fold (srl 0, x) -> 0
Matthias Braun1505efb2015-05-18 23:07:27 +00004553 if (isNullConstant(N0))
Nate Begemand23739d2005-09-06 04:43:02 +00004554 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004555 // fold (srl x, c >= size(x)) -> undef
Dan Gohmaneffb8942008-09-12 16:56:44 +00004556 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
Dale Johannesen84935752009-02-06 23:05:02 +00004557 return DAG.getUNDEF(VT);
Nate Begeman21158fc2005-09-01 00:19:25 +00004558 // fold (srl x, 0) -> x
Nate Begeman7cea6ef2005-09-02 21:18:40 +00004559 if (N1C && N1C->isNullValue())
Nate Begemand23739d2005-09-06 04:43:02 +00004560 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00004561 // if (srl x, c) is known to be zero, return 0
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004562 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
Dan Gohman1f372ed2008-02-25 21:11:39 +00004563 APInt::getAllOnesValue(OpSizeInBits)))
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004564 return DAG.getConstant(0, SDLoc(N), VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004565
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004566 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
Matt Arsenault985b9de2014-03-17 18:58:01 +00004567 if (N1C && N0.getOpcode() == ISD::SRL) {
4568 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4569 uint64_t c1 = N01C->getZExtValue();
4570 uint64_t c2 = N1C->getZExtValue();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004571 SDLoc DL(N);
Matt Arsenault985b9de2014-03-17 18:58:01 +00004572 if (c1 + c2 >= OpSizeInBits)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004573 return DAG.getConstant(0, DL, VT);
4574 return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4575 DAG.getConstant(c1 + c2, DL, N1.getValueType()));
Matt Arsenault985b9de2014-03-17 18:58:01 +00004576 }
Nate Begeman21158fc2005-09-01 00:19:25 +00004577 }
Wesley Peck527da1b2010-11-23 03:31:01 +00004578
Dale Johannesencd538af2010-12-17 21:45:49 +00004579 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
Dale Johannesencd538af2010-12-17 21:45:49 +00004580 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4581 N0.getOperand(0).getOpcode() == ISD::SRL &&
Dale Johannesen0a291a32010-12-20 20:10:50 +00004582 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
Owen Andersonb2c80da2011-02-25 21:41:48 +00004583 uint64_t c1 =
Dale Johannesencd538af2010-12-17 21:45:49 +00004584 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4585 uint64_t c2 = N1C->getZExtValue();
Dale Johannesena94e36b2010-12-21 21:55:50 +00004586 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4587 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
Dale Johannesencd538af2010-12-17 21:45:49 +00004588 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
Dale Johannesen0a291a32010-12-20 20:10:50 +00004589 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
Dale Johannesencd538af2010-12-17 21:45:49 +00004590 if (c1 + OpSizeInBits == InnerShiftSize) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004591 SDLoc DL(N0);
Dale Johannesencd538af2010-12-17 21:45:49 +00004592 if (c1 + c2 >= InnerShiftSize)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004593 return DAG.getConstant(0, DL, VT);
4594 return DAG.getNode(ISD::TRUNCATE, DL, VT,
4595 DAG.getNode(ISD::SRL, DL, InnerShiftVT,
Dale Johannesencd538af2010-12-17 21:45:49 +00004596 N0.getOperand(0)->getOperand(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004597 DAG.getConstant(c1 + c2, DL,
4598 ShiftCountVT)));
Dale Johannesencd538af2010-12-17 21:45:49 +00004599 }
4600 }
4601
Chris Lattnerf9b2e3c2010-04-15 05:28:43 +00004602 // fold (srl (shl x, c), c) -> (and x, cst2)
Matt Arsenault985b9de2014-03-17 18:58:01 +00004603 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4604 unsigned BitSize = N0.getScalarValueSizeInBits();
4605 if (BitSize <= 64) {
4606 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004607 SDLoc DL(N);
4608 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4609 DAG.getConstant(~0ULL >> ShAmt, DL, VT));
Matt Arsenault985b9de2014-03-17 18:58:01 +00004610 }
Chris Lattnerf9b2e3c2010-04-15 05:28:43 +00004611 }
Wesley Peck527da1b2010-11-23 03:31:01 +00004612
Michael Liao62ebfd82013-06-21 18:45:27 +00004613 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004614 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4615 // Shifting in all undef bits?
Owen Anderson53aa7a92009-08-10 22:56:29 +00004616 EVT SmallVT = N0.getOperand(0).getValueType();
Matt Arsenault985b9de2014-03-17 18:58:01 +00004617 unsigned BitSize = SmallVT.getScalarSizeInBits();
4618 if (N1C->getZExtValue() >= BitSize)
Dale Johannesen84935752009-02-06 23:05:02 +00004619 return DAG.getUNDEF(VT);
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004620
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004621 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
Owen Andersona5192842011-04-14 17:30:49 +00004622 uint64_t ShiftAmt = N1C->getZExtValue();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004623 SDLoc DL0(N0);
4624 SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
Owen Andersona5192842011-04-14 17:30:49 +00004625 N0.getOperand(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004626 DAG.getConstant(ShiftAmt, DL0,
4627 getShiftAmountTy(SmallVT)));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004628 AddToWorklist(SmallShift.getNode());
Matt Arsenault985b9de2014-03-17 18:58:01 +00004629 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004630 SDLoc DL(N);
4631 return DAG.getNode(ISD::AND, DL, VT,
4632 DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4633 DAG.getConstant(Mask, DL, VT));
Evan Chengf1bd5fc2010-04-17 06:13:15 +00004634 }
Chris Lattner57f8c5a2006-05-05 22:53:17 +00004635 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004636
Chris Lattner2e33fb42006-10-12 20:23:19 +00004637 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4638 // bit, which is unmodified by sra.
Matt Arsenault985b9de2014-03-17 18:58:01 +00004639 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
Chris Lattner2e33fb42006-10-12 20:23:19 +00004640 if (N0.getOpcode() == ISD::SRA)
Andrew Trickef9de2a2013-05-25 02:42:55 +00004641 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
Chris Lattner2e33fb42006-10-12 20:23:19 +00004642 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004643
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00004644 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
Scott Michelcf0da6c2009-02-17 22:15:04 +00004645 if (N1C && N0.getOpcode() == ISD::CTLZ &&
Matt Arsenault985b9de2014-03-17 18:58:01 +00004646 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004647 APInt KnownZero, KnownOne;
Jay Foada0653a32014-05-14 21:14:37 +00004648 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004649
Chris Lattner49932492006-04-02 06:11:11 +00004650 // If any of the input bits are KnownOne, then the input couldn't be all
4651 // zeros, thus the result of the srl will always be zero.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004652 if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004653
Chris Lattner49932492006-04-02 06:11:11 +00004654 // If all of the bits input the to ctlz node are known to be zero, then
4655 // the result of the ctlz is "32" and the result of the shift is one.
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00004656 APInt UnknownBits = ~KnownZero;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004657 if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004658
Chris Lattner49932492006-04-02 06:11:11 +00004659 // Otherwise, check to see if there is exactly one bit input to the ctlz.
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004660 if ((UnknownBits & (UnknownBits - 1)) == 0) {
Chris Lattner49932492006-04-02 06:11:11 +00004661 // Okay, we know that only that the single bit specified by UnknownBits
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004662 // could be set on input to the CTLZ node. If this bit is set, the SRL
4663 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4664 // to an SRL/XOR pair, which is likely to simplify more.
Dan Gohmand0ff91d2008-02-20 16:33:30 +00004665 unsigned ShAmt = UnknownBits.countTrailingZeros();
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004666 SDValue Op = N0.getOperand(0);
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004667
Chris Lattner49932492006-04-02 06:11:11 +00004668 if (ShAmt) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004669 SDLoc DL(N0);
4670 Op = DAG.getNode(ISD::SRL, DL, VT, Op,
4671 DAG.getConstant(ShAmt, DL,
4672 getShiftAmountTy(Op.getValueType())));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004673 AddToWorklist(Op.getNode());
Chris Lattner49932492006-04-02 06:11:11 +00004674 }
Bill Wendlingd51e3ff2009-01-30 21:37:17 +00004675
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004676 SDLoc DL(N);
4677 return DAG.getNode(ISD::XOR, DL, VT,
4678 Op, DAG.getConstant(1, DL, VT));
Chris Lattner49932492006-04-02 06:11:11 +00004679 }
4680 }
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004681
Duncan Sands3ed76882009-02-01 18:06:53 +00004682 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004683 if (N1.getOpcode() == ISD::TRUNCATE &&
Adam Nemet67483892014-03-04 23:28:31 +00004684 N1.getOperand(0).getOpcode() == ISD::AND) {
4685 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4686 if (NewOp1.getNode())
4687 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
Evan Chengcfb7f3a2008-08-30 02:03:58 +00004688 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00004689
Chris Lattnerf03c90b2007-04-18 03:06:49 +00004690 // fold operands of srl based on knowledge that the low bits are not
4691 // demanded.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004692 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4693 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004694
Evan Chengb175de62009-12-18 21:31:31 +00004695 if (N1C) {
Matt Arsenault985b9de2014-03-17 18:58:01 +00004696 SDValue NewSRL = visitShiftByConstant(N, N1C);
Evan Chengb175de62009-12-18 21:31:31 +00004697 if (NewSRL.getNode())
4698 return NewSRL;
4699 }
4700
Dan Gohman600f62b2010-06-24 14:30:44 +00004701 // Attempt to convert a srl of a load into a narrower zero-extending load.
4702 SDValue NarrowLoad = ReduceLoadWidth(N);
4703 if (NarrowLoad.getNode())
4704 return NarrowLoad;
4705
Evan Chengb175de62009-12-18 21:31:31 +00004706 // Here is a common situation. We want to optimize:
4707 //
4708 // %a = ...
4709 // %b = and i32 %a, 2
4710 // %c = srl i32 %b, 1
4711 // brcond i32 %c ...
4712 //
4713 // into
Wesley Peck527da1b2010-11-23 03:31:01 +00004714 //
Evan Chengb175de62009-12-18 21:31:31 +00004715 // %a = ...
4716 // %b = and %a, 2
4717 // %c = setcc eq %b, 0
4718 // brcond %c ...
4719 //
4720 // However when after the source operand of SRL is optimized into AND, the SRL
4721 // itself may not be optimized further. Look for it and add the BRCOND into
4722 // the worklist.
Evan Cheng166a4e62010-01-06 19:38:29 +00004723 if (N->hasOneUse()) {
4724 SDNode *Use = *N->use_begin();
4725 if (Use->getOpcode() == ISD::BRCOND)
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004726 AddToWorklist(Use);
Evan Cheng166a4e62010-01-06 19:38:29 +00004727 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4728 // Also look pass the truncate.
4729 Use = *Use->use_begin();
4730 if (Use->getOpcode() == ISD::BRCOND)
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004731 AddToWorklist(Use);
Evan Cheng166a4e62010-01-06 19:38:29 +00004732 }
4733 }
Evan Chengb175de62009-12-18 21:31:31 +00004734
Evan Chengf1005572010-04-28 07:10:39 +00004735 return SDValue();
Evan Chenge19aa5c2010-04-19 19:29:22 +00004736}
4737
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004738SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4739 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004740 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00004741
4742 // fold (ctlz c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004743 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004744 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004745 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004746}
4747
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004748SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4749 SDValue N0 = N->getOperand(0);
4750 EVT VT = N->getValueType(0);
4751
4752 // fold (ctlz_zero_undef c1) -> c2
4753 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004754 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004755 return SDValue();
4756}
4757
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004758SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4759 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004760 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004761
Nate Begeman21158fc2005-09-01 00:19:25 +00004762 // fold (cttz c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004763 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004764 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004765 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004766}
4767
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004768SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4769 SDValue N0 = N->getOperand(0);
4770 EVT VT = N->getValueType(0);
4771
4772 // fold (cttz_zero_undef c1) -> c2
4773 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004774 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
Chandler Carruth637cc6a2011-12-13 01:56:10 +00004775 return SDValue();
4776}
4777
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004778SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4779 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004780 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004781
Nate Begeman21158fc2005-09-01 00:19:25 +00004782 // fold (ctpop c1) -> c2
Chris Lattner7e7bcf32006-05-06 23:06:26 +00004783 if (isa<ConstantSDNode>(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004784 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004785 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00004786}
4787
Matt Arsenaulta982e4f2015-01-13 00:43:00 +00004788
4789/// \brief Generate Min/Max node
4790static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4791 SDValue True, SDValue False,
4792 ISD::CondCode CC, const TargetLowering &TLI,
4793 SelectionDAG &DAG) {
4794 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4795 return SDValue();
4796
4797 switch (CC) {
4798 case ISD::SETOLT:
4799 case ISD::SETOLE:
4800 case ISD::SETLT:
4801 case ISD::SETLE:
4802 case ISD::SETULT:
4803 case ISD::SETULE: {
4804 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4805 if (TLI.isOperationLegal(Opcode, VT))
4806 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4807 return SDValue();
4808 }
4809 case ISD::SETOGT:
4810 case ISD::SETOGE:
4811 case ISD::SETGT:
4812 case ISD::SETGE:
4813 case ISD::SETUGT:
4814 case ISD::SETUGE: {
4815 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4816 if (TLI.isOperationLegal(Opcode, VT))
4817 return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4818 return SDValue();
4819 }
4820 default:
4821 return SDValue();
4822 }
4823}
4824
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004825SDValue DAGCombiner::visitSELECT(SDNode *N) {
4826 SDValue N0 = N->getOperand(0);
4827 SDValue N1 = N->getOperand(1);
4828 SDValue N2 = N->getOperand(2);
Owen Anderson53aa7a92009-08-10 22:56:29 +00004829 EVT VT = N->getValueType(0);
4830 EVT VT0 = N0.getValueType();
Nate Begemanc760f802005-09-19 22:34:01 +00004831
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004832 // fold (select C, X, X) -> X
Nate Begeman24a7eca2005-09-16 00:54:12 +00004833 if (N1 == N2)
4834 return N1;
Matthias Braun1505efb2015-05-18 23:07:27 +00004835 if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
4836 // fold (select true, X, Y) -> X
4837 // fold (select false, X, Y) -> Y
4838 return !N0C->isNullValue() ? N1 : N2;
4839 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004840 // fold (select C, 1, X) -> (or C, X)
Matthias Braun887fdfb2015-05-19 00:25:21 +00004841 if (VT == MVT::i1 && isOneConstant(N1))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004842 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004843 // fold (select C, 0, 1) -> (xor C, 1)
Daniel Sanderscbd44c52014-07-10 10:18:12 +00004844 // We can't do this reliably if integer based booleans have different contents
4845 // to floating point based booleans. This is because we can't tell whether we
4846 // have an integer-based boolean or a floating-point-based boolean unless we
4847 // can find the SETCC that produced it and inspect its operands. This is
4848 // fairly easy if C is the SETCC node, but it can potentially be
4849 // undiscoverable (or not reasonably discoverable). For example, it could be
4850 // in another basic block or it could require searching a complicated
4851 // expression.
Bob Wilsonc2dc7ee2009-01-22 22:05:48 +00004852 if (VT.isInteger() &&
Daniel Sanderscbd44c52014-07-10 10:18:12 +00004853 (VT0 == MVT::i1 || (VT0.isInteger() &&
4854 TLI.getBooleanContents(false, false) ==
4855 TLI.getBooleanContents(false, true) &&
4856 TLI.getBooleanContents(false, false) ==
4857 TargetLowering::ZeroOrOneBooleanContent)) &&
Matthias Braun887fdfb2015-05-19 00:25:21 +00004858 isNullConstant(N1) && isOneConstant(N2)) {
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004859 SDValue XORNode;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004860 if (VT == VT0) {
4861 SDLoc DL(N);
4862 return DAG.getNode(ISD::XOR, DL, VT0,
4863 N0, DAG.getConstant(1, DL, VT0));
4864 }
4865 SDLoc DL0(N0);
4866 XORNode = DAG.getNode(ISD::XOR, DL0, VT0,
4867 N0, DAG.getConstant(1, DL0, VT0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004868 AddToWorklist(XORNode.getNode());
Duncan Sands11dd4242008-06-08 20:54:56 +00004869 if (VT.bitsGT(VT0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004870 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4871 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
Evan Chengf5a23ab2007-08-18 05:57:05 +00004872 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004873 // fold (select C, 0, X) -> (and (not C), X)
Matthias Braun1505efb2015-05-18 23:07:27 +00004874 if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004875 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004876 AddToWorklist(NOTNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004877 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004878 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004879 // fold (select C, X, 1) -> (or (not C), X)
Matthias Braun887fdfb2015-05-19 00:25:21 +00004880 if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00004881 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00004882 AddToWorklist(NOTNode.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00004883 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
Nate Begeman24a7eca2005-09-16 00:54:12 +00004884 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004885 // fold (select C, X, 0) -> (and C, X)
Matthias Braun1505efb2015-05-18 23:07:27 +00004886 if (VT == MVT::i1 && isNullConstant(N2))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004887 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004888 // fold (select X, X, Y) -> (or X, Y)
4889 // fold (select X, 1, Y) -> (or X, Y)
Matthias Braun887fdfb2015-05-19 00:25:21 +00004890 if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004891 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004892 // fold (select X, Y, X) -> (and X, Y)
4893 // fold (select X, Y, 0) -> (and X, Y)
Matthias Braun0542b5d2015-05-19 00:25:17 +00004894 if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004895 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00004896
Chris Lattner6c14c352005-10-18 06:04:22 +00004897 // If we can fold this based on the true/false value, do so.
4898 if (SimplifySelectOps(N, N1, N2))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004899 return SDValue(N, 0); // Don't revisit N.
Duncan Sands8651e9c2008-06-13 19:07:40 +00004900
Nate Begemanc760f802005-09-19 22:34:01 +00004901 // fold selects based on a setcc into other things, such as min/max/abs
Anton Korobeynikov035eaac2008-02-20 11:10:28 +00004902 if (N0.getOpcode() == ISD::SETCC) {
Matt Arsenaulta982e4f2015-01-13 00:43:00 +00004903 // select x, y (fcmp lt x, y) -> fminnum x, y
4904 // select x, y (fcmp gt x, y) -> fmaxnum x, y
4905 //
4906 // This is OK if we don't care about what happens if either operand is a
4907 // NaN.
4908 //
4909
4910 // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
4911 // no signed zeros as well as no nans.
4912 const TargetOptions &Options = DAG.getTarget().Options;
4913 if (Options.UnsafeFPMath &&
4914 VT.isFloatingPoint() && N0.hasOneUse() &&
4915 DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
4916 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4917
4918 SDValue FMinMax =
4919 combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), N0.getOperand(1),
4920 N1, N2, CC, TLI, DAG);
4921 if (FMinMax)
4922 return FMinMax;
4923 }
4924
Tom Stellard3787b122014-06-10 16:01:29 +00004925 if ((!LegalOperations &&
4926 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00004927 TLI.isOperationLegal(ISD::SELECT_CC, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00004928 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004929 N0.getOperand(0), N0.getOperand(1),
Nate Begeman7e7f4392006-02-01 07:19:44 +00004930 N1, N2, N0.getOperand(2));
Andrew Trickef9de2a2013-05-25 02:42:55 +00004931 return SimplifySelect(SDLoc(N), N0, N1, N2);
Anton Korobeynikov035eaac2008-02-20 11:10:28 +00004932 }
Bill Wendlingb6b6f462009-01-30 22:02:18 +00004933
Matthias Braun898d11e2015-03-06 19:49:10 +00004934 if (VT0 == MVT::i1) {
4935 if (TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4936 // select (and Cond0, Cond1), X, Y
4937 // -> select Cond0, (select Cond1, X, Y), Y
4938 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
4939 SDValue Cond0 = N0->getOperand(0);
4940 SDValue Cond1 = N0->getOperand(1);
4941 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4942 N1.getValueType(), Cond1, N1, N2);
4943 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
4944 InnerSelect, N2);
4945 }
4946 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
4947 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
4948 SDValue Cond0 = N0->getOperand(0);
4949 SDValue Cond1 = N0->getOperand(1);
4950 SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4951 N1.getValueType(), Cond1, N1, N2);
4952 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
4953 InnerSelect);
4954 }
4955 }
4956
4957 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
4958 if (N1->getOpcode() == ISD::SELECT) {
4959 SDValue N1_0 = N1->getOperand(0);
4960 SDValue N1_1 = N1->getOperand(1);
4961 SDValue N1_2 = N1->getOperand(2);
Matthias Brauna283cb32015-04-13 17:16:33 +00004962 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
Matthias Braun898d11e2015-03-06 19:49:10 +00004963 // Create the actual and node if we can generate good code for it.
4964 if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4965 SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
4966 N0, N1_0);
4967 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
4968 N1_1, N2);
4969 }
4970 // Otherwise see if we can optimize the "and" to a better pattern.
4971 if (SDValue Combined = visitANDLike(N0, N1_0, N))
4972 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
4973 N1_1, N2);
4974 }
4975 }
4976 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
4977 if (N2->getOpcode() == ISD::SELECT) {
4978 SDValue N2_0 = N2->getOperand(0);
4979 SDValue N2_1 = N2->getOperand(1);
4980 SDValue N2_2 = N2->getOperand(2);
Matthias Brauna283cb32015-04-13 17:16:33 +00004981 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
Matthias Braun898d11e2015-03-06 19:49:10 +00004982 // Create the actual or node if we can generate good code for it.
4983 if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4984 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
4985 N0, N2_0);
4986 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
4987 N1, N2_2);
4988 }
4989 // Otherwise see if we can optimize to a better pattern.
4990 if (SDValue Combined = visitORLike(N0, N2_0, N))
4991 return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
4992 N1, N2_2);
4993 }
4994 }
4995 }
4996
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00004997 return SDValue();
Nate Begeman24a7eca2005-09-16 00:54:12 +00004998}
4999
Tom Stellard9cbd2c52013-11-22 00:39:23 +00005000static
5001std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5002 SDLoc DL(N);
5003 EVT LoVT, HiVT;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +00005004 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
Tom Stellard9cbd2c52013-11-22 00:39:23 +00005005
5006 // Split the inputs.
5007 SDValue Lo, Hi, LL, LH, RL, RH;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +00005008 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5009 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
Tom Stellard9cbd2c52013-11-22 00:39:23 +00005010
5011 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5012 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5013
5014 return std::make_pair(Lo, Hi);
5015}
5016
Filipe Cabecinhas82111f12014-05-30 23:03:11 +00005017// This function assumes all the vselect's arguments are CONCAT_VECTOR
5018// nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5019static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5020 SDLoc dl(N);
5021 SDValue Cond = N->getOperand(0);
5022 SDValue LHS = N->getOperand(1);
5023 SDValue RHS = N->getOperand(2);
Benjamin Kramerff8b8832014-08-21 13:28:02 +00005024 EVT VT = N->getValueType(0);
Filipe Cabecinhas82111f12014-05-30 23:03:11 +00005025 int NumElems = VT.getVectorNumElements();
5026 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5027 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5028 Cond.getOpcode() == ISD::BUILD_VECTOR);
5029
Benjamin Kramerff8b8832014-08-21 13:28:02 +00005030 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5031 // binary ones here.
5032 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5033 return SDValue();
5034
Filipe Cabecinhas82111f12014-05-30 23:03:11 +00005035 // We're sure we have an even number of elements due to the
5036 // concat_vectors we have as arguments to vselect.
5037 // Skip BV elements until we find one that's not an UNDEF
5038 // After we find an UNDEF element, keep looping until we get to half the
5039 // length of the BV and see if all the non-undef nodes are the same.
5040 ConstantSDNode *BottomHalf = nullptr;
5041 for (int i = 0; i < NumElems / 2; ++i) {
5042 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5043 continue;
5044
5045 if (BottomHalf == nullptr)
5046 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5047 else if (Cond->getOperand(i).getNode() != BottomHalf)
5048 return SDValue();
5049 }
5050
5051 // Do the same for the second half of the BuildVector
5052 ConstantSDNode *TopHalf = nullptr;
5053 for (int i = NumElems / 2; i < NumElems; ++i) {
5054 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5055 continue;
5056
5057 if (TopHalf == nullptr)
5058 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5059 else if (Cond->getOperand(i).getNode() != TopHalf)
5060 return SDValue();
5061 }
5062
5063 assert(TopHalf && BottomHalf &&
5064 "One half of the selector was all UNDEFs and the other was all the "
5065 "same value. This should have been addressed before this function.");
5066 return DAG.getNode(
5067 ISD::CONCAT_VECTORS, dl, VT,
5068 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5069 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5070}
5071
Elena Demikhovskye1eda8a2015-04-30 08:38:48 +00005072SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
5073
5074 if (Level >= AfterLegalizeTypes)
5075 return SDValue();
5076
5077 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
5078 SDValue Mask = MSC->getMask();
5079 SDValue Data = MSC->getValue();
5080 SDLoc DL(N);
5081
5082 // If the MSCATTER data type requires splitting and the mask is provided by a
5083 // SETCC, then split both nodes and its operands before legalization. This
5084 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5085 // and enables future optimizations (e.g. min/max pattern matching on X86).
5086 if (Mask.getOpcode() != ISD::SETCC)
5087 return SDValue();
5088
5089 // Check if any splitting is required.
5090 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5091 TargetLowering::TypeSplitVector)
5092 return SDValue();
5093 SDValue MaskLo, MaskHi, Lo, Hi;
5094 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5095
5096 EVT LoVT, HiVT;
5097 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
5098
5099 SDValue Chain = MSC->getChain();
5100
5101 EVT MemoryVT = MSC->getMemoryVT();
5102 unsigned Alignment = MSC->getOriginalAlignment();
5103
5104 EVT LoMemVT, HiMemVT;
5105 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5106
5107 SDValue DataLo, DataHi;
5108 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5109
5110 SDValue BasePtr = MSC->getBasePtr();
5111 SDValue IndexLo, IndexHi;
5112 std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
5113
5114 MachineMemOperand *MMO = DAG.getMachineFunction().
5115 getMachineMemOperand(MSC->getPointerInfo(),
5116 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
5117 Alignment, MSC->getAAInfo(), MSC->getRanges());
5118
5119 SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
5120 Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
5121 DL, OpsLo, MMO);
5122
5123 SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
5124 Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
5125 DL, OpsHi, MMO);
5126
5127 AddToWorklist(Lo.getNode());
5128 AddToWorklist(Hi.getNode());
5129
5130 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5131}
5132
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00005133SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5134
5135 if (Level >= AfterLegalizeTypes)
5136 return SDValue();
5137
5138 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5139 SDValue Mask = MST->getMask();
Elena Demikhovsky150d9f32015-01-22 12:07:59 +00005140 SDValue Data = MST->getValue();
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00005141 SDLoc DL(N);
5142
5143 // If the MSTORE data type requires splitting and the mask is provided by a
5144 // SETCC, then split both nodes and its operands before legalization. This
5145 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5146 // and enables future optimizations (e.g. min/max pattern matching on X86).
5147 if (Mask.getOpcode() == ISD::SETCC) {
5148
5149 // Check if any splitting is required.
5150 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5151 TargetLowering::TypeSplitVector)
5152 return SDValue();
5153
5154 SDValue MaskLo, MaskHi, Lo, Hi;
5155 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5156
5157 EVT LoVT, HiVT;
5158 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5159
5160 SDValue Chain = MST->getChain();
5161 SDValue Ptr = MST->getBasePtr();
5162
5163 EVT MemoryVT = MST->getMemoryVT();
5164 unsigned Alignment = MST->getOriginalAlignment();
5165
5166 // if Alignment is equal to the vector size,
5167 // take the half of it for the second part
5168 unsigned SecondHalfAlignment =
5169 (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5170 Alignment/2 : Alignment;
5171
5172 EVT LoMemVT, HiMemVT;
5173 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5174
5175 SDValue DataLo, DataHi;
5176 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5177
5178 MachineMemOperand *MMO = DAG.getMachineFunction().
Simon Pilgrimd8820ae2015-02-24 22:08:56 +00005179 getMachineMemOperand(MST->getPointerInfo(),
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00005180 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
5181 Alignment, MST->getAAInfo(), MST->getRanges());
5182
Elena Demikhovsky150d9f32015-01-22 12:07:59 +00005183 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5184 MST->isTruncatingStore());
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00005185
5186 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5187 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005188 DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00005189
5190 MMO = DAG.getMachineFunction().
Simon Pilgrimd8820ae2015-02-24 22:08:56 +00005191 getMachineMemOperand(MST->getPointerInfo(),
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00005192 MachineMemOperand::MOStore, HiMemVT.getStoreSize(),
5193 SecondHalfAlignment, MST->getAAInfo(),
5194 MST->getRanges());
5195
Elena Demikhovsky150d9f32015-01-22 12:07:59 +00005196 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5197 MST->isTruncatingStore());
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00005198
5199 AddToWorklist(Lo.getNode());
5200 AddToWorklist(Hi.getNode());
5201
5202 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5203 }
5204 return SDValue();
5205}
5206
Elena Demikhovskye1eda8a2015-04-30 08:38:48 +00005207SDValue DAGCombiner::visitMGATHER(SDNode *N) {
5208
5209 if (Level >= AfterLegalizeTypes)
5210 return SDValue();
5211
5212 MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
5213 SDValue Mask = MGT->getMask();
5214 SDLoc DL(N);
5215
5216 // If the MGATHER result requires splitting and the mask is provided by a
5217 // SETCC, then split both nodes and its operands before legalization. This
5218 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5219 // and enables future optimizations (e.g. min/max pattern matching on X86).
5220
5221 if (Mask.getOpcode() != ISD::SETCC)
5222 return SDValue();
5223
5224 EVT VT = N->getValueType(0);
5225
5226 // Check if any splitting is required.
5227 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5228 TargetLowering::TypeSplitVector)
5229 return SDValue();
5230
5231 SDValue MaskLo, MaskHi, Lo, Hi;
5232 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5233
5234 SDValue Src0 = MGT->getValue();
5235 SDValue Src0Lo, Src0Hi;
5236 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5237
5238 EVT LoVT, HiVT;
5239 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
5240
5241 SDValue Chain = MGT->getChain();
5242 EVT MemoryVT = MGT->getMemoryVT();
5243 unsigned Alignment = MGT->getOriginalAlignment();
5244
5245 EVT LoMemVT, HiMemVT;
5246 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5247
5248 SDValue BasePtr = MGT->getBasePtr();
5249 SDValue Index = MGT->getIndex();
5250 SDValue IndexLo, IndexHi;
5251 std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
5252
5253 MachineMemOperand *MMO = DAG.getMachineFunction().
5254 getMachineMemOperand(MGT->getPointerInfo(),
5255 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
5256 Alignment, MGT->getAAInfo(), MGT->getRanges());
5257
5258 SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
5259 Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
5260 MMO);
5261
5262 SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
5263 Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
5264 MMO);
5265
5266 AddToWorklist(Lo.getNode());
5267 AddToWorklist(Hi.getNode());
5268
5269 // Build a factor node to remember that this load is independent of the
5270 // other one.
5271 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5272 Hi.getValue(1));
5273
5274 // Legalized the chain result - switch anything that used the old chain to
5275 // use the new one.
5276 DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
5277
5278 SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5279
5280 SDValue RetOps[] = { GatherRes, Chain };
5281 return DAG.getMergeValues(RetOps, DL);
5282}
5283
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00005284SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5285
5286 if (Level >= AfterLegalizeTypes)
5287 return SDValue();
5288
5289 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5290 SDValue Mask = MLD->getMask();
5291 SDLoc DL(N);
5292
5293 // If the MLOAD result requires splitting and the mask is provided by a
5294 // SETCC, then split both nodes and its operands before legalization. This
5295 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5296 // and enables future optimizations (e.g. min/max pattern matching on X86).
5297
5298 if (Mask.getOpcode() == ISD::SETCC) {
5299 EVT VT = N->getValueType(0);
5300
5301 // Check if any splitting is required.
5302 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5303 TargetLowering::TypeSplitVector)
5304 return SDValue();
5305
5306 SDValue MaskLo, MaskHi, Lo, Hi;
5307 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5308
5309 SDValue Src0 = MLD->getSrc0();
5310 SDValue Src0Lo, Src0Hi;
5311 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5312
5313 EVT LoVT, HiVT;
5314 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5315
5316 SDValue Chain = MLD->getChain();
5317 SDValue Ptr = MLD->getBasePtr();
5318 EVT MemoryVT = MLD->getMemoryVT();
5319 unsigned Alignment = MLD->getOriginalAlignment();
5320
5321 // if Alignment is equal to the vector size,
5322 // take the half of it for the second part
5323 unsigned SecondHalfAlignment =
5324 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5325 Alignment/2 : Alignment;
5326
5327 EVT LoMemVT, HiMemVT;
5328 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5329
5330 MachineMemOperand *MMO = DAG.getMachineFunction().
Simon Pilgrimd8820ae2015-02-24 22:08:56 +00005331 getMachineMemOperand(MLD->getPointerInfo(),
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00005332 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
5333 Alignment, MLD->getAAInfo(), MLD->getRanges());
5334
Elena Demikhovsky150d9f32015-01-22 12:07:59 +00005335 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5336 ISD::NON_EXTLOAD);
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00005337
5338 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5339 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005340 DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00005341
5342 MMO = DAG.getMachineFunction().
Simon Pilgrimd8820ae2015-02-24 22:08:56 +00005343 getMachineMemOperand(MLD->getPointerInfo(),
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00005344 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(),
5345 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5346
Elena Demikhovsky150d9f32015-01-22 12:07:59 +00005347 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5348 ISD::NON_EXTLOAD);
Elena Demikhovskyf1de34b2014-12-04 09:40:44 +00005349
5350 AddToWorklist(Lo.getNode());
5351 AddToWorklist(Hi.getNode());
5352
5353 // Build a factor node to remember that this load is independent of the
5354 // other one.
5355 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5356 Hi.getValue(1));
5357
5358 // Legalized the chain result - switch anything that used the old chain to
5359 // use the new one.
5360 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5361
5362 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5363
5364 SDValue RetOps[] = { LoadRes, Chain };
5365 return DAG.getMergeValues(RetOps, DL);
5366 }
5367 return SDValue();
5368}
5369
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00005370SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5371 SDValue N0 = N->getOperand(0);
5372 SDValue N1 = N->getOperand(1);
5373 SDValue N2 = N->getOperand(2);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005374 SDLoc DL(N);
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00005375
5376 // Canonicalize integer abs.
5377 // vselect (setg[te] X, 0), X, -X ->
5378 // vselect (setgt X, -1), X, -X ->
5379 // vselect (setl[te] X, 0), -X, X ->
5380 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5381 if (N0.getOpcode() == ISD::SETCC) {
5382 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5383 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5384 bool isAbs = false;
5385 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5386
5387 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5388 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5389 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5390 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5391 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5392 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5393 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5394
5395 if (isAbs) {
5396 EVT VT = LHS.getValueType();
5397 SDValue Shift = DAG.getNode(
5398 ISD::SRA, DL, VT, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005399 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT));
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00005400 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005401 AddToWorklist(Shift.getNode());
5402 AddToWorklist(Add.getNode());
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00005403 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5404 }
5405 }
5406
Tom Stellard69a7b912015-04-20 19:38:27 +00005407 if (SimplifySelectOps(N, N1, N2))
5408 return SDValue(N, 0); // Don't revisit N.
5409
Tom Stellard9cbd2c52013-11-22 00:39:23 +00005410 // If the VSELECT result requires splitting and the mask is provided by a
5411 // SETCC, then split both nodes and its operands before legalization. This
5412 // prevents the type legalizer from unrolling SETCC into scalar comparisons
5413 // and enables future optimizations (e.g. min/max pattern matching on X86).
5414 if (N0.getOpcode() == ISD::SETCC) {
5415 EVT VT = N->getValueType(0);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00005416
Tom Stellard9cbd2c52013-11-22 00:39:23 +00005417 // Check if any splitting is required.
5418 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5419 TargetLowering::TypeSplitVector)
5420 return SDValue();
Juergen Ributzka34c652d2013-11-13 01:57:54 +00005421
Tom Stellard9cbd2c52013-11-22 00:39:23 +00005422 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +00005423 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5424 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5425 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00005426
Tom Stellard9cbd2c52013-11-22 00:39:23 +00005427 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5428 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00005429
Tom Stellard9cbd2c52013-11-22 00:39:23 +00005430 // Add the new VSELECT nodes to the work list in case they need to be split
5431 // again.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005432 AddToWorklist(Lo.getNode());
5433 AddToWorklist(Hi.getNode());
Tom Stellard9cbd2c52013-11-22 00:39:23 +00005434
5435 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
Juergen Ributzka34c652d2013-11-13 01:57:54 +00005436 }
5437
Andrea Di Biagio23df4e42014-01-08 18:33:04 +00005438 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5439 if (ISD::isBuildVectorAllOnes(N0.getNode()))
5440 return N1;
5441 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5442 if (ISD::isBuildVectorAllZeros(N0.getNode()))
5443 return N2;
5444
Filipe Cabecinhas82111f12014-05-30 23:03:11 +00005445 // The ConvertSelectToConcatVector function is assuming both the above
5446 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5447 // and addressed.
5448 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5449 N2.getOpcode() == ISD::CONCAT_VECTORS &&
5450 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5451 SDValue CV = ConvertSelectToConcatVector(N, DAG);
5452 if (CV.getNode())
5453 return CV;
5454 }
5455
Benjamin Kramerd56ffc72013-04-26 09:19:19 +00005456 return SDValue();
5457}
5458
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005459SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5460 SDValue N0 = N->getOperand(0);
5461 SDValue N1 = N->getOperand(1);
5462 SDValue N2 = N->getOperand(2);
5463 SDValue N3 = N->getOperand(3);
5464 SDValue N4 = N->getOperand(4);
Nate Begemanc760f802005-09-19 22:34:01 +00005465 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
Scott Michelcf0da6c2009-02-17 22:15:04 +00005466
Nate Begemanc760f802005-09-19 22:34:01 +00005467 // fold select_cc lhs, rhs, x, x, cc -> x
5468 if (N2 == N3)
5469 return N2;
Scott Michelcf0da6c2009-02-17 22:15:04 +00005470
Chris Lattner8b68dec2006-09-20 06:19:26 +00005471 // Determine if the condition we're dealing with is constant
Matt Arsenault758659232013-05-18 00:21:46 +00005472 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005473 N0, N1, CC, SDLoc(N), false);
Stephen Lin605207f2013-06-15 04:03:33 +00005474 if (SCC.getNode()) {
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005475 AddToWorklist(SCC.getNode());
Chris Lattner8b68dec2006-09-20 06:19:26 +00005476
Stephen Lin605207f2013-06-15 04:03:33 +00005477 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5478 if (!SCCC->isNullValue())
5479 return N2; // cond always true -> true val
5480 else
5481 return N3; // cond always false -> false val
Mehdi Amini648eff12015-01-14 05:45:24 +00005482 } else if (SCC->getOpcode() == ISD::UNDEF) {
5483 // When the condition is UNDEF, just return the first operand. This is
5484 // coherent the DAG creation, no setcc node is created in this case
5485 return N2;
5486 } else if (SCC.getOpcode() == ISD::SETCC) {
5487 // Fold to a simpler select_cc
Stephen Lin605207f2013-06-15 04:03:33 +00005488 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5489 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5490 SCC.getOperand(2));
Mehdi Amini648eff12015-01-14 05:45:24 +00005491 }
Chris Lattner8b68dec2006-09-20 06:19:26 +00005492 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005493
Chris Lattner6c14c352005-10-18 06:04:22 +00005494 // If we can fold this based on the true/false value, do so.
5495 if (SimplifySelectOps(N, N2, N3))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005496 return SDValue(N, 0); // Don't revisit N.
Scott Michelcf0da6c2009-02-17 22:15:04 +00005497
Nate Begemanc760f802005-09-19 22:34:01 +00005498 // fold select_cc into other things, such as min/max/abs
Andrew Trickef9de2a2013-05-25 02:42:55 +00005499 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
Nate Begeman24a7eca2005-09-16 00:54:12 +00005500}
5501
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005502SDValue DAGCombiner::visitSETCC(SDNode *N) {
Nate Begeman24a7eca2005-09-16 00:54:12 +00005503 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
Dale Johannesenf1163e92009-02-03 00:47:48 +00005504 cast<CondCodeSDNode>(N->getOperand(2))->get(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005505 SDLoc(N));
Nate Begeman24a7eca2005-09-16 00:54:12 +00005506}
5507
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005508// tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
5509// dag node into a ConstantSDNode or a build_vector of constants.
5510// This function is called by the DAGCombiner when visiting sext/zext/aext
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00005511// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005512// Vector extends are not folded if operations are legal; this is to
5513// avoid introducing illegal build_vector dag nodes.
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005514static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5515 SelectionDAG &DAG, bool LegalTypes,
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005516 bool LegalOperations) {
5517 unsigned Opcode = N->getOpcode();
5518 SDValue N0 = N->getOperand(0);
5519 EVT VT = N->getValueType(0);
5520
5521 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5522 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
5523
5524 // fold (sext c1) -> c1
5525 // fold (zext c1) -> c1
5526 // fold (aext c1) -> c1
5527 if (isa<ConstantSDNode>(N0))
5528 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5529
5530 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5531 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5532 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005533 EVT SVT = VT.getScalarType();
5534 if (!(VT.isVector() &&
5535 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005536 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
Craig Topperc0196b12014-04-14 00:51:57 +00005537 return nullptr;
Jim Grosbach2eb60fd2014-04-29 22:41:50 +00005538
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005539 // We can fold this node into a build_vector.
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005540 unsigned VTBits = SVT.getSizeInBits();
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005541 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5542 unsigned ShAmt = VTBits - EVTBits;
5543 SmallVector<SDValue, 8> Elts;
5544 unsigned NumElts = N0->getNumOperands();
5545 SDLoc DL(N);
5546
5547 for (unsigned i=0; i != NumElts; ++i) {
5548 SDValue Op = N0->getOperand(i);
5549 if (Op->getOpcode() == ISD::UNDEF) {
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005550 Elts.push_back(DAG.getUNDEF(SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005551 continue;
5552 }
5553
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005554 SDLoc DL(Op);
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005555 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5556 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5557 if (Opcode == ISD::SIGN_EXTEND)
5558 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005559 DL, SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005560 else
5561 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005562 DL, SVT));
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005563 }
5564
Craig Topper48d114b2014-04-26 18:35:24 +00005565 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005566}
5567
Evan Chenge106e2f2007-10-29 19:58:20 +00005568// ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
Dan Gohman0e8d1992009-04-09 03:51:29 +00005569// "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
Evan Chenge106e2f2007-10-29 19:58:20 +00005570// transformation. Returns true if extension are possible and the above
Scott Michelcf0da6c2009-02-17 22:15:04 +00005571// mentioned transformation is profitable.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005572static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
Evan Chenge106e2f2007-10-29 19:58:20 +00005573 unsigned ExtOpc,
Craig Topperb94011f2013-07-14 04:42:23 +00005574 SmallVectorImpl<SDNode *> &ExtendNodes,
Dan Gohman619ef482009-01-15 19:20:50 +00005575 const TargetLowering &TLI) {
Evan Chenge106e2f2007-10-29 19:58:20 +00005576 bool HasCopyToRegUses = false;
5577 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
Gabor Greife12264b2008-08-30 19:29:20 +00005578 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5579 UE = N0.getNode()->use_end();
Evan Chenge106e2f2007-10-29 19:58:20 +00005580 UI != UE; ++UI) {
Dan Gohman91e5dcb2008-07-27 20:43:25 +00005581 SDNode *User = *UI;
Evan Chenge106e2f2007-10-29 19:58:20 +00005582 if (User == N)
5583 continue;
Dan Gohman0e8d1992009-04-09 03:51:29 +00005584 if (UI.getUse().getResNo() != N0.getResNo())
5585 continue;
Evan Chenge106e2f2007-10-29 19:58:20 +00005586 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
Dan Gohman0e8d1992009-04-09 03:51:29 +00005587 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
Evan Chenge106e2f2007-10-29 19:58:20 +00005588 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5589 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5590 // Sign bits will be lost after a zext.
5591 return false;
5592 bool Add = false;
5593 for (unsigned i = 0; i != 2; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005594 SDValue UseOp = User->getOperand(i);
Evan Chenge106e2f2007-10-29 19:58:20 +00005595 if (UseOp == N0)
5596 continue;
5597 if (!isa<ConstantSDNode>(UseOp))
5598 return false;
5599 Add = true;
5600 }
5601 if (Add)
5602 ExtendNodes.push_back(User);
Dan Gohman0e8d1992009-04-09 03:51:29 +00005603 continue;
Evan Chenge106e2f2007-10-29 19:58:20 +00005604 }
Dan Gohman0e8d1992009-04-09 03:51:29 +00005605 // If truncates aren't free and there are users we can't
5606 // extend, it isn't worthwhile.
5607 if (!isTruncFree)
5608 return false;
5609 // Remember if this value is live-out.
5610 if (User->getOpcode() == ISD::CopyToReg)
5611 HasCopyToRegUses = true;
Evan Chenge106e2f2007-10-29 19:58:20 +00005612 }
5613
5614 if (HasCopyToRegUses) {
5615 bool BothLiveOut = false;
5616 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5617 UI != UE; ++UI) {
Dan Gohman0e8d1992009-04-09 03:51:29 +00005618 SDUse &Use = UI.getUse();
5619 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5620 BothLiveOut = true;
5621 break;
Evan Chenge106e2f2007-10-29 19:58:20 +00005622 }
5623 }
5624 if (BothLiveOut)
5625 // Both unextended and extended values are live out. There had better be
Bob Wilsonf9b96c42010-11-28 06:51:19 +00005626 // a good reason for the transformation.
Evan Chenge106e2f2007-10-29 19:58:20 +00005627 return ExtendNodes.size();
5628 }
5629 return true;
5630}
5631
Craig Toppere0b71182013-07-13 07:43:40 +00005632void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
Andrew Trickef9de2a2013-05-25 02:42:55 +00005633 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005634 ISD::NodeType ExtType) {
5635 // Extend SetCC uses if necessary.
5636 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5637 SDNode *SetCC = SetCCs[i];
5638 SmallVector<SDValue, 4> Ops;
5639
5640 for (unsigned j = 0; j != 2; ++j) {
5641 SDValue SOp = SetCC->getOperand(j);
5642 if (SOp == Trunc)
5643 Ops.push_back(ExtLoad);
5644 else
5645 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5646 }
5647
5648 Ops.push_back(SetCC->getOperand(2));
Craig Topper48d114b2014-04-26 18:35:24 +00005649 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005650 }
5651}
5652
Ahmed Bougachae892d132015-02-05 18:31:02 +00005653// FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5654SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5655 SDValue N0 = N->getOperand(0);
5656 EVT DstVT = N->getValueType(0);
5657 EVT SrcVT = N0.getValueType();
5658
5659 assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5660 N->getOpcode() == ISD::ZERO_EXTEND) &&
5661 "Unexpected node type (not an extend)!");
5662
5663 // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5664 // For example, on a target with legal v4i32, but illegal v8i32, turn:
5665 // (v8i32 (sext (v8i16 (load x))))
5666 // into:
5667 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5668 // (v4i32 (sextload (x + 16)))))
5669 // Where uses of the original load, i.e.:
5670 // (v8i16 (load x))
5671 // are replaced with:
5672 // (v8i16 (truncate
5673 // (v8i32 (concat_vectors (v4i32 (sextload x)),
5674 // (v4i32 (sextload (x + 16)))))))
5675 //
5676 // This combine is only applicable to illegal, but splittable, vectors.
5677 // All legal types, and illegal non-vector types, are handled elsewhere.
5678 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5679 //
5680 if (N0->getOpcode() != ISD::LOAD)
5681 return SDValue();
5682
5683 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5684
5685 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5686 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5687 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5688 return SDValue();
5689
5690 SmallVector<SDNode *, 4> SetCCs;
5691 if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5692 return SDValue();
5693
5694 ISD::LoadExtType ExtType =
5695 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5696
5697 // Try to split the vector types to get down to legal types.
5698 EVT SplitSrcVT = SrcVT;
5699 EVT SplitDstVT = DstVT;
5700 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5701 SplitSrcVT.getVectorNumElements() > 1) {
5702 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5703 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5704 }
5705
5706 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5707 return SDValue();
5708
5709 SDLoc DL(N);
5710 const unsigned NumSplits =
5711 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5712 const unsigned Stride = SplitSrcVT.getStoreSize();
5713 SmallVector<SDValue, 4> Loads;
5714 SmallVector<SDValue, 4> Chains;
5715
5716 SDValue BasePtr = LN0->getBasePtr();
5717 for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5718 const unsigned Offset = Idx * Stride;
5719 const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5720
5721 SDValue SplitLoad = DAG.getExtLoad(
5722 ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5723 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5724 LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5725 Align, LN0->getAAInfo());
5726
5727 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005728 DAG.getConstant(Stride, DL, BasePtr.getValueType()));
Ahmed Bougachae892d132015-02-05 18:31:02 +00005729
5730 Loads.push_back(SplitLoad.getValue(0));
5731 Chains.push_back(SplitLoad.getValue(1));
5732 }
5733
5734 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5735 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5736
5737 CombineTo(N, NewValue);
5738
5739 // Replace uses of the original load (before extension)
5740 // with a truncate of the concatenated sextloaded vectors.
5741 SDValue Trunc =
5742 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5743 CombineTo(N0.getNode(), Trunc, NewChain);
5744 ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5745 (ISD::NodeType)N->getOpcode());
5746 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5747}
5748
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005749SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5750 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00005751 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00005752
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00005753 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5754 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00005755 return SDValue(Res, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005756
Nadav Rotem9450fcf2013-01-20 08:35:56 +00005757 // fold (sext (sext x)) -> (sext x)
5758 // fold (sext (aext x)) -> (sext x)
5759 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005760 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
Nadav Rotem9450fcf2013-01-20 08:35:56 +00005761 N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00005762
Chris Lattnerfce448f2007-02-26 03:13:59 +00005763 if (N0.getOpcode() == ISD::TRUNCATE) {
Dan Gohmanc1a4e212008-05-20 20:56:33 +00005764 // fold (sext (truncate (load x))) -> (sext (smaller load x))
5765 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00005766 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5767 if (NarrowLoad.getNode()) {
Dale Johannesenff384ad2010-05-25 17:50:03 +00005768 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5769 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00005770 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesenff384ad2010-05-25 17:50:03 +00005771 // CombineTo deleted the truncate, if needed, but not what's under it.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00005772 AddToWorklist(oye);
Dale Johannesenff384ad2010-05-25 17:50:03 +00005773 }
Dan Gohmanbe36f5c2009-04-27 02:00:55 +00005774 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00005775 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00005776
Dan Gohmanc1a4e212008-05-20 20:56:33 +00005777 // See if the value being truncated is already sign extended. If so, just
5778 // eliminate the trunc/sext pair.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005779 SDValue Op = N0.getOperand(0);
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005780 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
5781 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
5782 unsigned DestBits = VT.getScalarType().getSizeInBits();
Dan Gohman309d3d52007-06-22 14:59:07 +00005783 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005784
Chris Lattnerfce448f2007-02-26 03:13:59 +00005785 if (OpBits == DestBits) {
5786 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
5787 // bits, it is already ready.
5788 if (NumSignBits > DestBits-MidBits)
5789 return Op;
5790 } else if (OpBits < DestBits) {
5791 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
5792 // bits, just sext from i32.
5793 if (NumSignBits > OpBits-MidBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005794 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
Chris Lattnerfce448f2007-02-26 03:13:59 +00005795 } else {
5796 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
5797 // bits, just truncate to i32.
5798 if (NumSignBits > OpBits-MidBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005799 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chris Lattnera31f0a62006-09-21 06:00:20 +00005800 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005801
Chris Lattnerfce448f2007-02-26 03:13:59 +00005802 // fold (sext (truncate x)) -> (sextinreg x).
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005803 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5804 N0.getValueType())) {
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005805 if (OpBits < DestBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005806 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005807 else if (OpBits > DestBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00005808 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5809 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
Dan Gohman6bd3ef82010-01-09 02:13:55 +00005810 DAG.getValueType(N0.getValueType()));
Chris Lattnerfce448f2007-02-26 03:13:59 +00005811 }
Chris Lattnera31f0a62006-09-21 06:00:20 +00005812 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005813
Evan Chengbce7c472005-12-14 02:19:23 +00005814 // fold (sext (load x)) -> (sext (truncate (sextload x)))
Ahmed Bougachae892d132015-02-05 18:31:02 +00005815 // Only generate vector extloads when 1) they're legal, and 2) they are
5816 // deemed desirable by the target.
5817 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5818 ((!LegalOperations && !VT.isVector() &&
5819 !cast<LoadSDNode>(N0)->isVolatile()) ||
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00005820 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
Evan Chenge106e2f2007-10-29 19:58:20 +00005821 bool DoXform = true;
5822 SmallVector<SDNode*, 4> SetCCs;
5823 if (!N0.hasOneUse())
5824 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
Ahmed Bougachae892d132015-02-05 18:31:02 +00005825 if (VT.isVector())
5826 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
Evan Chenge106e2f2007-10-29 19:58:20 +00005827 if (DoXform) {
5828 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005829 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Dan Gohman0e8d1992009-04-09 03:51:29 +00005830 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005831 LN0->getBasePtr(), N0.getValueType(),
5832 LN0->getMemOperand());
Evan Chenge106e2f2007-10-29 19:58:20 +00005833 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00005834 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00005835 N0.getValueType(), ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005836 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00005837 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005838 ISD::SIGN_EXTEND);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005839 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenge106e2f2007-10-29 19:58:20 +00005840 }
Nate Begeman8caf81d2005-10-12 20:40:40 +00005841 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005842
Ahmed Bougachae892d132015-02-05 18:31:02 +00005843 // fold (sext (load x)) to multiple smaller sextloads.
5844 // Only on illegal but splittable vectors.
5845 if (SDValue ExtLoad = CombineExtLoad(N))
5846 return ExtLoad;
5847
Chris Lattner7dac1082005-12-14 19:05:06 +00005848 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5849 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00005850 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5851 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00005852 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00005853 EVT MemVT = LN0->getMemoryVT();
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005854 if ((!LegalOperations && !LN0->isVolatile()) ||
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00005855 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005856 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00005857 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005858 LN0->getBasePtr(), MemVT,
5859 LN0->getMemOperand());
Jim Laskey26df19a2006-12-15 21:38:30 +00005860 CombineTo(N, ExtLoad);
Gabor Greife12264b2008-08-30 19:29:20 +00005861 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00005862 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00005863 N0.getValueType(), ExtLoad),
Jim Laskey26df19a2006-12-15 21:38:30 +00005864 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00005865 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Jim Laskey26df19a2006-12-15 21:38:30 +00005866 }
Chris Lattner7dac1082005-12-14 19:05:06 +00005867 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005868
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005869 // fold (sext (and/or/xor (load x), cst)) ->
5870 // (and/or/xor (sextload x), (sext cst))
5871 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5872 N0.getOpcode() == ISD::XOR) &&
5873 isa<LoadSDNode>(N0.getOperand(0)) &&
5874 N0.getOperand(1).getOpcode() == ISD::Constant &&
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00005875 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005876 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5877 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
Quentin Colombet0b1a5582014-04-09 20:03:05 +00005878 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005879 bool DoXform = true;
5880 SmallVector<SDNode*, 4> SetCCs;
5881 if (!N0.hasOneUse())
5882 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5883 SetCCs, TLI);
5884 if (DoXform) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005885 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005886 LN0->getChain(), LN0->getBasePtr(),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005887 LN0->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00005888 LN0->getMemOperand());
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005889 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5890 Mask = Mask.sext(VT.getSizeInBits());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005891 SDLoc DL(N);
5892 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
5893 ExtLoad, DAG.getConstant(Mask, DL, VT));
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005894 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00005895 SDLoc(N0.getOperand(0)),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005896 N0.getOperand(0).getValueType(), ExtLoad);
5897 CombineTo(N, And);
5898 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005899 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00005900 ISD::SIGN_EXTEND);
5901 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5902 }
5903 }
5904 }
5905
Chris Lattner65786b02007-04-11 05:32:27 +00005906 if (N0.getOpcode() == ISD::SETCC) {
Daniel Sanderscbd44c52014-07-10 10:18:12 +00005907 EVT N0VT = N0.getOperand(0).getValueType();
Chris Lattner4ac60732009-07-08 00:31:33 +00005908 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
Dan Gohmane82c25e2010-04-30 17:19:19 +00005909 // Only do this before legalize for now.
Owen Anderson2d4cca32013-04-23 18:09:28 +00005910 if (VT.isVector() && !LegalOperations &&
Daniel Sanderscbd44c52014-07-10 10:18:12 +00005911 TLI.getBooleanContents(N0VT) ==
5912 TargetLowering::ZeroOrNegativeOneBooleanContent) {
Nadav Rotem9d376b62012-04-11 08:26:11 +00005913 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5914 // of the same size as the compared operands. Only optimize sext(setcc())
5915 // if this is the case.
Matt Arsenault758659232013-05-18 00:21:46 +00005916 EVT SVT = getSetCCResultType(N0VT);
Nadav Rotem9d376b62012-04-11 08:26:11 +00005917
5918 // We know that the # elements of the results is the same as the
5919 // # elements of the compare (and the # elements of the compare result
5920 // for that matter). Check to see that they are the same size. If so,
5921 // we know that the element size of the sext'd result matches the
5922 // element size of the compare operands.
5923 if (VT.getSizeInBits() == SVT.getSizeInBits())
Andrew Trickef9de2a2013-05-25 02:42:55 +00005924 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00005925 N0.getOperand(1),
5926 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Matt Arsenault04126232013-05-17 21:43:43 +00005927
Dan Gohmane82c25e2010-04-30 17:19:19 +00005928 // If the desired elements are smaller or larger than the source
5929 // elements we can use a matching integer vector type and then
5930 // truncate/sign extend
Matt Arsenault04126232013-05-17 21:43:43 +00005931 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
Craig Topper5f9791f2012-09-29 07:18:53 +00005932 if (SVT == MatchingVectorType) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00005933 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
Craig Topper5f9791f2012-09-29 07:18:53 +00005934 N0.getOperand(0), N0.getOperand(1),
5935 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Andrew Trickef9de2a2013-05-25 02:42:55 +00005936 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
Dan Gohmane82c25e2010-04-30 17:19:19 +00005937 }
Chris Lattner4ac60732009-07-08 00:31:33 +00005938 }
Dan Gohmane82c25e2010-04-30 17:19:19 +00005939
Matt Arsenault5f2a92a2014-01-27 21:41:54 +00005940 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
Dan Gohman5544b0c2010-04-24 01:17:30 +00005941 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005942 SDLoc DL(N);
Dan Gohman5758e1e2009-08-06 09:18:59 +00005943 SDValue NegOne =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005944 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005945 SDValue SCC =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005946 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
5947 NegOne, DAG.getConstant(0, DL, VT),
Chris Lattnera083ffc2007-04-11 06:50:51 +00005948 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00005949 if (SCC.getNode()) return SCC;
Matt Arsenault5f2a92a2014-01-27 21:41:54 +00005950
5951 if (!VT.isVector()) {
5952 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5953 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5954 SDLoc DL(N);
5955 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
Hal Finkel98085952014-10-06 20:19:47 +00005956 SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
Matt Arsenault5f2a92a2014-01-27 21:41:54 +00005957 N0.getOperand(0), N0.getOperand(1), CC);
Hal Finkel98085952014-10-06 20:19:47 +00005958 return DAG.getSelect(DL, VT, SetCC,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005959 NegOne, DAG.getConstant(0, DL, VT));
Matt Arsenault5f2a92a2014-01-27 21:41:54 +00005960 }
Matt Arsenaultd2f03322013-06-14 22:04:37 +00005961 }
Wesley Peck527da1b2010-11-23 03:31:01 +00005962 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00005963
Dan Gohman3eb10f72008-04-28 16:58:24 +00005964 // fold (sext x) -> (zext x) if the sign bit is known zero.
Duncan Sandsdc2dac12008-11-24 14:53:14 +00005965 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
Dan Gohmanc968c1f2008-04-28 18:47:17 +00005966 DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00005967 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00005968
Evan Chengf1005572010-04-28 07:10:39 +00005969 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00005970}
5971
Rafael Espindola8f62b322012-04-09 16:06:03 +00005972// isTruncateOf - If N is a truncate of some other value, return true, record
5973// the value being truncated in Op and which of Op's bits are zero in KnownZero.
5974// This function computes KnownZero to avoid a duplicated call to
Jay Foada0653a32014-05-14 21:14:37 +00005975// computeKnownBits in the caller.
Rafael Espindola8f62b322012-04-09 16:06:03 +00005976static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5977 APInt &KnownZero) {
5978 APInt KnownOne;
5979 if (N->getOpcode() == ISD::TRUNCATE) {
5980 Op = N->getOperand(0);
Jay Foada0653a32014-05-14 21:14:37 +00005981 DAG.computeKnownBits(Op, KnownZero, KnownOne);
Rafael Espindola8f62b322012-04-09 16:06:03 +00005982 return true;
5983 }
5984
5985 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5986 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5987 return false;
5988
5989 SDValue Op0 = N->getOperand(0);
5990 SDValue Op1 = N->getOperand(1);
5991 assert(Op0.getValueType() == Op1.getValueType());
5992
Matthias Braun1505efb2015-05-18 23:07:27 +00005993 if (isNullConstant(Op0))
Rafael Espindola8f62b322012-04-09 16:06:03 +00005994 Op = Op1;
Matthias Braun1505efb2015-05-18 23:07:27 +00005995 else if (isNullConstant(Op1))
Rafael Espindola8f62b322012-04-09 16:06:03 +00005996 Op = Op0;
5997 else
5998 return false;
5999
Jay Foada0653a32014-05-14 21:14:37 +00006000 DAG.computeKnownBits(Op, KnownZero, KnownOne);
Rafael Espindola8f62b322012-04-09 16:06:03 +00006001
6002 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
6003 return false;
6004
6005 return true;
6006}
6007
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006008SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
6009 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006010 EVT VT = N->getValueType(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00006011
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00006012 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6013 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00006014 return SDValue(Res, 0);
6015
Nate Begeman21158fc2005-09-01 00:19:25 +00006016 // fold (zext (zext x)) -> (zext x)
Chris Lattner7e7bcf32006-05-06 23:06:26 +00006017 // fold (zext (aext x)) -> (zext x)
6018 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006019 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00006020 N0.getOperand(0));
Chris Lattnera31f0a62006-09-21 06:00:20 +00006021
Chandler Carruth55b2cde2012-01-11 08:41:08 +00006022 // fold (zext (truncate x)) -> (zext x) or
6023 // (zext (truncate x)) -> (truncate x)
6024 // This is valid when the truncated bits of x are already zero.
6025 // FIXME: We should extend this to work for vectors too.
Rafael Espindola8f62b322012-04-09 16:06:03 +00006026 SDValue Op;
6027 APInt KnownZero;
6028 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
6029 APInt TruncatedBits =
6030 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
6031 APInt(Op.getValueSizeInBits(), 0) :
6032 APInt::getBitsSet(Op.getValueSizeInBits(),
6033 N0.getValueSizeInBits(),
6034 std::min(Op.getValueSizeInBits(),
6035 VT.getSizeInBits()));
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +00006036 if (TruncatedBits == (KnownZero & TruncatedBits)) {
Chandler Carruth55b2cde2012-01-11 08:41:08 +00006037 if (VT.bitsGT(Op.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006038 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00006039 if (VT.bitsLT(Op.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006040 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chandler Carruth55b2cde2012-01-11 08:41:08 +00006041
6042 return Op;
6043 }
6044 }
6045
Evan Cheng464dc9b2007-03-22 01:54:19 +00006046 // fold (zext (truncate (load x))) -> (zext (smaller load x))
6047 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
Dale Johannesen4bbd2ee2007-03-30 21:38:07 +00006048 if (N0.getOpcode() == ISD::TRUNCATE) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00006049 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6050 if (NarrowLoad.getNode()) {
Dale Johannesenff384ad2010-05-25 17:50:03 +00006051 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6052 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00006053 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesenff384ad2010-05-25 17:50:03 +00006054 // CombineTo deleted the truncate, if needed, but not what's under it.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006055 AddToWorklist(oye);
Dale Johannesenff384ad2010-05-25 17:50:03 +00006056 }
Eli Friedman55b0acd2011-04-16 23:25:34 +00006057 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00006058 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00006059 }
6060
Chris Lattnera31f0a62006-09-21 06:00:20 +00006061 // fold (zext (truncate x)) -> (and x, mask)
6062 if (N0.getOpcode() == ISD::TRUNCATE &&
Dan Gohman600f62b2010-06-24 14:30:44 +00006063 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
Dan Gohman68fb0042010-11-03 01:47:46 +00006064
6065 // fold (zext (truncate (load x))) -> (zext (smaller load x))
6066 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
6067 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6068 if (NarrowLoad.getNode()) {
6069 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6070 if (NarrowLoad.getNode() != N0.getNode()) {
6071 CombineTo(N0.getNode(), NarrowLoad);
6072 // CombineTo deleted the truncate, if needed, but not what's under it.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006073 AddToWorklist(oye);
Dan Gohman68fb0042010-11-03 01:47:46 +00006074 }
6075 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6076 }
6077
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006078 SDValue Op = N0.getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00006079 if (Op.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006080 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006081 AddToWorklist(Op.getNode());
Duncan Sands11dd4242008-06-08 20:54:56 +00006082 } else if (Op.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006083 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006084 AddToWorklist(Op.getNode());
Chris Lattnera31f0a62006-09-21 06:00:20 +00006085 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00006086 return DAG.getZeroExtendInReg(Op, SDLoc(N),
Dan Gohman1d459e42009-12-11 21:31:27 +00006087 N0.getValueType().getScalarType());
Chris Lattnera31f0a62006-09-21 06:00:20 +00006088 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006089
Dan Gohmanad3e5492009-04-08 00:15:30 +00006090 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
6091 // if either of the casts is not free.
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00006092 if (N0.getOpcode() == ISD::AND &&
6093 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
Dan Gohmanad3e5492009-04-08 00:15:30 +00006094 N0.getOperand(1).getOpcode() == ISD::Constant &&
6095 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6096 N0.getValueType()) ||
6097 !TLI.isZExtFree(N0.getValueType(), VT))) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006098 SDValue X = N0.getOperand(0).getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00006099 if (X.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006100 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
Duncan Sands11dd4242008-06-08 20:54:56 +00006101 } else if (X.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006102 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00006103 }
Dan Gohmane1c4f992008-03-03 23:51:38 +00006104 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00006105 Mask = Mask.zext(VT.getSizeInBits());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006106 SDLoc DL(N);
6107 return DAG.getNode(ISD::AND, DL, VT,
6108 X, DAG.getConstant(Mask, DL, VT));
Chris Lattner8d8a3bf2006-09-21 06:14:31 +00006109 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006110
Evan Chengbce7c472005-12-14 02:19:23 +00006111 // fold (zext (load x)) -> (zext (truncate (zextload x)))
Ahmed Bougachae892d132015-02-05 18:31:02 +00006112 // Only generate vector extloads when 1) they're legal, and 2) they are
6113 // deemed desirable by the target.
6114 if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6115 ((!LegalOperations && !VT.isVector() &&
6116 !cast<LoadSDNode>(N0)->isVolatile()) ||
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00006117 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
Evan Chenge106e2f2007-10-29 19:58:20 +00006118 bool DoXform = true;
6119 SmallVector<SDNode*, 4> SetCCs;
6120 if (!N0.hasOneUse())
6121 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
Ahmed Bougachae892d132015-02-05 18:31:02 +00006122 if (VT.isVector())
6123 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
Evan Chenge106e2f2007-10-29 19:58:20 +00006124 if (DoXform) {
6125 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006126 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00006127 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00006128 LN0->getBasePtr(), N0.getValueType(),
6129 LN0->getMemOperand());
Evan Chenge106e2f2007-10-29 19:58:20 +00006130 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006131 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Bill Wendlingc4093182009-01-30 22:23:15 +00006132 N0.getValueType(), ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006133 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Bill Wendlingc4093182009-01-30 22:23:15 +00006134
Andrew Trickef9de2a2013-05-25 02:42:55 +00006135 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00006136 ISD::ZERO_EXTEND);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006137 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenge106e2f2007-10-29 19:58:20 +00006138 }
Evan Chengbce7c472005-12-14 02:19:23 +00006139 }
Chris Lattner7dac1082005-12-14 19:05:06 +00006140
Ahmed Bougachae892d132015-02-05 18:31:02 +00006141 // fold (zext (load x)) to multiple smaller zextloads.
6142 // Only on illegal but splittable vectors.
6143 if (SDValue ExtLoad = CombineExtLoad(N))
6144 return ExtLoad;
6145
Nick Lewycky6d677cf2011-06-16 01:15:49 +00006146 // fold (zext (and/or/xor (load x), cst)) ->
6147 // (and/or/xor (zextload x), (zext cst))
6148 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6149 N0.getOpcode() == ISD::XOR) &&
6150 isa<LoadSDNode>(N0.getOperand(0)) &&
6151 N0.getOperand(1).getOpcode() == ISD::Constant &&
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00006152 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
Nick Lewycky6d677cf2011-06-16 01:15:49 +00006153 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6154 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
Quentin Colombet0b1a5582014-04-09 20:03:05 +00006155 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
Nick Lewycky6d677cf2011-06-16 01:15:49 +00006156 bool DoXform = true;
6157 SmallVector<SDNode*, 4> SetCCs;
6158 if (!N0.hasOneUse())
6159 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
6160 SetCCs, TLI);
6161 if (DoXform) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006162 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00006163 LN0->getChain(), LN0->getBasePtr(),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00006164 LN0->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00006165 LN0->getMemOperand());
Nick Lewycky6d677cf2011-06-16 01:15:49 +00006166 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6167 Mask = Mask.zext(VT.getSizeInBits());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006168 SDLoc DL(N);
6169 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6170 ExtLoad, DAG.getConstant(Mask, DL, VT));
Nick Lewycky6d677cf2011-06-16 01:15:49 +00006171 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
Andrew Trickef9de2a2013-05-25 02:42:55 +00006172 SDLoc(N0.getOperand(0)),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00006173 N0.getOperand(0).getValueType(), ExtLoad);
6174 CombineTo(N, And);
6175 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006176 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
Nick Lewycky6d677cf2011-06-16 01:15:49 +00006177 ISD::ZERO_EXTEND);
6178 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6179 }
6180 }
6181 }
6182
Chris Lattner7dac1082005-12-14 19:05:06 +00006183 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6184 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
Gabor Greiff304a7a2008-08-28 21:40:38 +00006185 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6186 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00006187 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman08c0a952009-09-23 21:02:20 +00006188 EVT MemVT = LN0->getMemoryVT();
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006189 if ((!LegalOperations && !LN0->isVolatile()) ||
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00006190 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006191 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
Bill Wendlingc4093182009-01-30 22:23:15 +00006192 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00006193 LN0->getBasePtr(), MemVT,
6194 LN0->getMemOperand());
Duncan Sands8651e9c2008-06-13 19:07:40 +00006195 CombineTo(N, ExtLoad);
Gabor Greife12264b2008-08-30 19:29:20 +00006196 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00006197 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
Bill Wendlingc4093182009-01-30 22:23:15 +00006198 ExtLoad),
Duncan Sands8651e9c2008-06-13 19:07:40 +00006199 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006200 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Duncan Sands8651e9c2008-06-13 19:07:40 +00006201 }
Chris Lattner7dac1082005-12-14 19:05:06 +00006202 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006203
Chris Lattner65786b02007-04-11 05:32:27 +00006204 if (N0.getOpcode() == ISD::SETCC) {
Kevin Qinede9ce12013-12-30 02:05:13 +00006205 if (!LegalOperations && VT.isVector() &&
6206 N0.getValueType().getVectorElementType() == MVT::i1) {
Elena Demikhovsky9d56f1e2014-01-22 12:26:19 +00006207 EVT N0VT = N0.getOperand(0).getValueType();
6208 if (getSetCCResultType(N0VT) == N0.getValueType())
6209 return SDValue();
6210
Evan Chengabd0ad52010-05-19 01:08:17 +00006211 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6212 // Only do this before legalize for now.
Evan Chengabd0ad52010-05-19 01:08:17 +00006213 EVT EltVT = VT.getVectorElementType();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006214 SDLoc DL(N);
Evan Chengabd0ad52010-05-19 01:08:17 +00006215 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006216 DAG.getConstant(1, DL, EltVT));
Dan Gohman4298df62011-05-17 22:20:36 +00006217 if (VT.getSizeInBits() == N0VT.getSizeInBits())
Evan Chengabd0ad52010-05-19 01:08:17 +00006218 // We know that the # elements of the results is the same as the
6219 // # elements of the compare (and the # elements of the compare result
6220 // for that matter). Check to see that they are the same size. If so,
6221 // we know that the element size of the sext'd result matches the
6222 // element size of the compare operands.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006223 return DAG.getNode(ISD::AND, DL, VT,
6224 DAG.getSetCC(DL, VT, N0.getOperand(0),
Evan Chengabd0ad52010-05-19 01:08:17 +00006225 N0.getOperand(1),
6226 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006227 DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
Craig Topper48d114b2014-04-26 18:35:24 +00006228 OneOps));
Dan Gohman4298df62011-05-17 22:20:36 +00006229
6230 // If the desired elements are smaller or larger than the source
6231 // elements we can use a matching integer vector type and then
6232 // truncate/sign extend
6233 EVT MatchingElementType =
6234 EVT::getIntegerVT(*DAG.getContext(),
6235 N0VT.getScalarType().getSizeInBits());
6236 EVT MatchingVectorType =
6237 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6238 N0VT.getVectorNumElements());
6239 SDValue VsetCC =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006240 DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0),
Dan Gohman4298df62011-05-17 22:20:36 +00006241 N0.getOperand(1),
6242 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006243 return DAG.getNode(ISD::AND, DL, VT,
6244 DAG.getSExtOrTrunc(VsetCC, DL, VT),
6245 DAG.getNode(ISD::BUILD_VECTOR, DL, VT, OneOps));
Evan Chengabd0ad52010-05-19 01:08:17 +00006246 }
6247
6248 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006249 SDLoc DL(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006250 SDValue SCC =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006251 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6252 DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
Chris Lattnera083ffc2007-04-11 06:50:51 +00006253 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006254 if (SCC.getNode()) return SCC;
Chris Lattner65786b02007-04-11 05:32:27 +00006255 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006256
Evan Cheng852c4862009-12-15 03:00:32 +00006257 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
Evan Chengca7c6902009-12-15 00:41:36 +00006258 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
Evan Cheng852c4862009-12-15 03:00:32 +00006259 isa<ConstantSDNode>(N0.getOperand(1)) &&
Evan Chengca7c6902009-12-15 00:41:36 +00006260 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6261 N0.hasOneUse()) {
Chris Lattnere95d1952011-02-13 19:09:16 +00006262 SDValue ShAmt = N0.getOperand(1);
6263 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
Evan Cheng852c4862009-12-15 03:00:32 +00006264 if (N0.getOpcode() == ISD::SHL) {
Chris Lattnere95d1952011-02-13 19:09:16 +00006265 SDValue InnerZExt = N0.getOperand(0);
Evan Cheng852c4862009-12-15 03:00:32 +00006266 // If the original shl may be shifting out bits, do not perform this
6267 // transformation.
Chris Lattnere95d1952011-02-13 19:09:16 +00006268 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6269 InnerZExt.getOperand(0).getValueType().getSizeInBits();
6270 if (ShAmtVal > KnownZeroBits)
Evan Cheng852c4862009-12-15 03:00:32 +00006271 return SDValue();
6272 }
Chris Lattnere95d1952011-02-13 19:09:16 +00006273
Andrew Trickef9de2a2013-05-25 02:42:55 +00006274 SDLoc DL(N);
Owen Andersonb2c80da2011-02-25 21:41:48 +00006275
6276 // Ensure that the shift amount is wide enough for the shifted value.
Chris Lattnere95d1952011-02-13 19:09:16 +00006277 if (VT.getSizeInBits() >= 256)
6278 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
Owen Andersonb2c80da2011-02-25 21:41:48 +00006279
Chris Lattnere95d1952011-02-13 19:09:16 +00006280 return DAG.getNode(N0.getOpcode(), DL, VT,
6281 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6282 ShAmt);
Evan Chengca7c6902009-12-15 00:41:36 +00006283 }
6284
Evan Chengf1005572010-04-28 07:10:39 +00006285 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00006286}
6287
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006288SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6289 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006290 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006291
Andrea Di Biagiob6d39af2014-01-28 12:53:56 +00006292 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6293 LegalOperations))
Andrea Di Biagiof09a3572014-01-27 18:45:30 +00006294 return SDValue(Res, 0);
6295
Chris Lattner812646a2006-05-05 05:58:59 +00006296 // fold (aext (aext x)) -> (aext x)
6297 // fold (aext (zext x)) -> (zext x)
6298 // fold (aext (sext x)) -> (sext x)
6299 if (N0.getOpcode() == ISD::ANY_EXTEND ||
6300 N0.getOpcode() == ISD::ZERO_EXTEND ||
6301 N0.getOpcode() == ISD::SIGN_EXTEND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006302 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00006303
Evan Cheng464dc9b2007-03-22 01:54:19 +00006304 // fold (aext (truncate (load x))) -> (aext (smaller load x))
6305 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6306 if (N0.getOpcode() == ISD::TRUNCATE) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00006307 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6308 if (NarrowLoad.getNode()) {
Dale Johannesen60fe2cd2010-05-25 18:47:23 +00006309 SDNode* oye = N0.getNode()->getOperand(0).getNode();
6310 if (NarrowLoad.getNode() != N0.getNode()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00006311 CombineTo(N0.getNode(), NarrowLoad);
Dale Johannesen60fe2cd2010-05-25 18:47:23 +00006312 // CombineTo deleted the truncate, if needed, but not what's under it.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006313 AddToWorklist(oye);
Dale Johannesen60fe2cd2010-05-25 18:47:23 +00006314 }
Eli Friedman55b0acd2011-04-16 23:25:34 +00006315 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga824e792007-03-23 02:16:52 +00006316 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00006317 }
6318
Chris Lattner8746e2c2006-09-20 06:29:17 +00006319 // fold (aext (truncate x))
6320 if (N0.getOpcode() == ISD::TRUNCATE) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006321 SDValue TruncOp = N0.getOperand(0);
Chris Lattner8746e2c2006-09-20 06:29:17 +00006322 if (TruncOp.getValueType() == VT)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00006323 return TruncOp; // x iff x size == zext size.
Duncan Sands11dd4242008-06-08 20:54:56 +00006324 if (TruncOp.getValueType().bitsGT(VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006325 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6326 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
Chris Lattner8746e2c2006-09-20 06:29:17 +00006327 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006328
Dan Gohmanad3e5492009-04-08 00:15:30 +00006329 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6330 // if the trunc is not free.
Chris Lattner082db3f2006-09-21 06:40:43 +00006331 if (N0.getOpcode() == ISD::AND &&
6332 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
Dan Gohmanad3e5492009-04-08 00:15:30 +00006333 N0.getOperand(1).getOpcode() == ISD::Constant &&
6334 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6335 N0.getValueType())) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006336 SDValue X = N0.getOperand(0).getOperand(0);
Duncan Sands11dd4242008-06-08 20:54:56 +00006337 if (X.getValueType().bitsLT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006338 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
Duncan Sands11dd4242008-06-08 20:54:56 +00006339 } else if (X.getValueType().bitsGT(VT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00006340 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
Chris Lattner082db3f2006-09-21 06:40:43 +00006341 }
Dan Gohmane1c4f992008-03-03 23:51:38 +00006342 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
Jay Foad583abbc2010-12-07 08:25:19 +00006343 Mask = Mask.zext(VT.getSizeInBits());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006344 SDLoc DL(N);
6345 return DAG.getNode(ISD::AND, DL, VT,
6346 X, DAG.getConstant(Mask, DL, VT));
Chris Lattner082db3f2006-09-21 06:40:43 +00006347 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006348
Chris Lattner812646a2006-05-05 05:58:59 +00006349 // fold (aext (load x)) -> (aext (truncate (extload x)))
Nadav Rotem502f1b92011-02-24 21:01:34 +00006350 // None of the supported targets knows how to perform load and any_ext
Nadav Rotemb0091302011-02-27 07:40:43 +00006351 // on vectors in one instruction. We only perform this transformation on
6352 // scalars.
Nadav Rotem502f1b92011-02-24 21:01:34 +00006353 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
Quentin Colombet0b1a5582014-04-09 20:03:05 +00006354 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00006355 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
Dan Gohman0e8d1992009-04-09 03:51:29 +00006356 bool DoXform = true;
6357 SmallVector<SDNode*, 4> SetCCs;
6358 if (!N0.hasOneUse())
6359 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6360 if (DoXform) {
6361 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006362 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
Dan Gohman0e8d1992009-04-09 03:51:29 +00006363 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00006364 LN0->getBasePtr(), N0.getValueType(),
6365 LN0->getMemOperand());
Dan Gohman0e8d1992009-04-09 03:51:29 +00006366 CombineTo(N, ExtLoad);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006367 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
Dan Gohman0e8d1992009-04-09 03:51:29 +00006368 N0.getValueType(), ExtLoad);
6369 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00006370 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
Nick Lewycky6d677cf2011-06-16 01:15:49 +00006371 ISD::ANY_EXTEND);
Dan Gohman0e8d1992009-04-09 03:51:29 +00006372 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6373 }
Chris Lattner812646a2006-05-05 05:58:59 +00006374 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006375
Chris Lattner812646a2006-05-05 05:58:59 +00006376 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6377 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6378 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
Evan Cheng8a1d09d2007-03-07 08:07:03 +00006379 if (N0.getOpcode() == ISD::LOAD &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00006380 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Chenge71fe34d2006-10-09 20:57:25 +00006381 N0.hasOneUse()) {
6382 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Matt Arsenaultaaf96232014-04-08 21:40:37 +00006383 ISD::LoadExtType ExtType = LN0->getExtensionType();
Dan Gohman08c0a952009-09-23 21:02:20 +00006384 EVT MemVT = LN0->getMemoryVT();
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00006385 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
Matt Arsenaultaaf96232014-04-08 21:40:37 +00006386 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6387 VT, LN0->getChain(), LN0->getBasePtr(),
6388 MemVT, LN0->getMemOperand());
6389 CombineTo(N, ExtLoad);
6390 CombineTo(N0.getNode(),
6391 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6392 N0.getValueType(), ExtLoad),
6393 ExtLoad.getValue(1));
6394 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6395 }
Chris Lattner812646a2006-05-05 05:58:59 +00006396 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006397
Chris Lattner65786b02007-04-11 05:32:27 +00006398 if (N0.getOpcode() == ISD::SETCC) {
Hao Liuc636d152014-04-22 09:57:06 +00006399 // For vectors:
6400 // aext(setcc) -> vsetcc
6401 // aext(setcc) -> truncate(vsetcc)
6402 // aext(setcc) -> aext(vsetcc)
Evan Chengabd0ad52010-05-19 01:08:17 +00006403 // Only do this before legalize for now.
6404 if (VT.isVector() && !LegalOperations) {
6405 EVT N0VT = N0.getOperand(0).getValueType();
6406 // We know that the # elements of the results is the same as the
6407 // # elements of the compare (and the # elements of the compare result
6408 // for that matter). Check to see that they are the same size. If so,
6409 // we know that the element size of the sext'd result matches the
6410 // element size of the compare operands.
6411 if (VT.getSizeInBits() == N0VT.getSizeInBits())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006412 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00006413 N0.getOperand(1),
6414 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Evan Chengabd0ad52010-05-19 01:08:17 +00006415 // If the desired elements are smaller or larger than the source
6416 // elements we can use a matching integer vector type and then
Hao Liuc636d152014-04-22 09:57:06 +00006417 // truncate/any extend
Evan Chengabd0ad52010-05-19 01:08:17 +00006418 else {
Hao Liuc636d152014-04-22 09:57:06 +00006419 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
Duncan Sands41b4a6b2010-07-12 08:16:59 +00006420 SDValue VsetCC =
Andrew Trickef9de2a2013-05-25 02:42:55 +00006421 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
Duncan Sands41b4a6b2010-07-12 08:16:59 +00006422 N0.getOperand(1),
6423 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Hao Liuc636d152014-04-22 09:57:06 +00006424 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
Evan Chengabd0ad52010-05-19 01:08:17 +00006425 }
6426 }
6427
6428 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006429 SDLoc DL(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006430 SDValue SCC =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006431 SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6432 DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
Chris Lattner18e4ac42007-04-11 16:51:53 +00006433 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006434 if (SCC.getNode())
Chris Lattnerc5f85d32007-04-11 06:43:25 +00006435 return SCC;
Chris Lattner65786b02007-04-11 05:32:27 +00006436 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00006437
Evan Chengf1005572010-04-28 07:10:39 +00006438 return SDValue();
Chris Lattner812646a2006-05-05 05:58:59 +00006439}
6440
Sanjay Patel50cbfc52014-08-28 16:29:51 +00006441/// See if the specified operand can be simplified with the knowledge that only
6442/// the bits specified by Mask are used. If so, return the simpler operand,
6443/// otherwise return a null SDValue.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006444SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
Chris Lattner5e6fe052007-10-13 06:35:54 +00006445 switch (V.getOpcode()) {
6446 default: break;
Lang Hamesb85fcd02011-11-08 18:56:23 +00006447 case ISD::Constant: {
6448 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
Craig Topperc0196b12014-04-14 00:51:57 +00006449 assert(CV && "Const value should be ConstSDNode.");
Lang Hamesb85fcd02011-11-08 18:56:23 +00006450 const APInt &CVal = CV->getAPIntValue();
6451 APInt NewVal = CVal & Mask;
Stephen Lin8e8424e2013-07-09 00:44:49 +00006452 if (NewVal != CVal)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006453 return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
Lang Hamesb85fcd02011-11-08 18:56:23 +00006454 break;
6455 }
Chris Lattner5e6fe052007-10-13 06:35:54 +00006456 case ISD::OR:
6457 case ISD::XOR:
6458 // If the LHS or RHS don't contribute bits to the or, drop them.
6459 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6460 return V.getOperand(1);
6461 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6462 return V.getOperand(0);
6463 break;
Chris Lattnerf47e3062007-10-13 06:58:48 +00006464 case ISD::SRL:
6465 // Only look at single-use SRLs.
Gabor Greiff304a7a2008-08-28 21:40:38 +00006466 if (!V.getNode()->hasOneUse())
Chris Lattnerf47e3062007-10-13 06:58:48 +00006467 break;
6468 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
6469 // See if we can recursively simplify the LHS.
Dan Gohmaneffb8942008-09-12 16:56:44 +00006470 unsigned Amt = RHSC->getZExtValue();
Bill Wendling7bfa43b2009-01-30 22:33:24 +00006471
Dan Gohmanb9fa1d22009-01-03 19:22:06 +00006472 // Watch out for shift count overflow though.
6473 if (Amt >= Mask.getBitWidth()) break;
Dan Gohman1f372ed2008-02-25 21:11:39 +00006474 APInt NewMask = Mask << Amt;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006475 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
Bill Wendling7bfa43b2009-01-30 22:33:24 +00006476 if (SimplifyLHS.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006477 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
Chris Lattnerf47e3062007-10-13 06:58:48 +00006478 SimplifyLHS, V.getOperand(1));
Chris Lattnerf47e3062007-10-13 06:58:48 +00006479 }
Chris Lattner5e6fe052007-10-13 06:35:54 +00006480 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006481 return SDValue();
Chris Lattner5e6fe052007-10-13 06:35:54 +00006482}
6483
Sanjay Patel50cbfc52014-08-28 16:29:51 +00006484/// If the result of a wider load is shifted to right of N bits and then
6485/// truncated to a narrower type and where N is a multiple of number of bits of
6486/// the narrower type, transform it to a narrower load from address + N / num of
6487/// bits of new type. If the result is to be extended, also fold the extension
6488/// to form a extending load.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006489SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
Evan Cheng464dc9b2007-03-22 01:54:19 +00006490 unsigned Opc = N->getOpcode();
Dan Gohman600f62b2010-06-24 14:30:44 +00006491
Evan Cheng464dc9b2007-03-22 01:54:19 +00006492 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006493 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006494 EVT VT = N->getValueType(0);
6495 EVT ExtVT = VT;
Evan Cheng464dc9b2007-03-22 01:54:19 +00006496
Dan Gohman550c9af2008-08-14 20:04:46 +00006497 // This transformation isn't valid for vector loads.
6498 if (VT.isVector())
6499 return SDValue();
6500
Dan Gohman6bd3ef82010-01-09 02:13:55 +00006501 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
Evan Chenga883b582007-03-23 22:13:36 +00006502 // extended to VT.
Evan Cheng464dc9b2007-03-22 01:54:19 +00006503 if (Opc == ISD::SIGN_EXTEND_INREG) {
6504 ExtType = ISD::SEXTLOAD;
Owen Anderson53aa7a92009-08-10 22:56:29 +00006505 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
Dan Gohman600f62b2010-06-24 14:30:44 +00006506 } else if (Opc == ISD::SRL) {
Chris Lattner2a7ff992010-12-21 18:05:22 +00006507 // Another special-case: SRL is basically zero-extending a narrower value.
Dan Gohman600f62b2010-06-24 14:30:44 +00006508 ExtType = ISD::ZEXTLOAD;
6509 N0 = SDValue(N, 0);
6510 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6511 if (!N01) return SDValue();
6512 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6513 VT.getSizeInBits() - N01->getZExtValue());
Evan Cheng464dc9b2007-03-22 01:54:19 +00006514 }
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00006515 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
Richard Osborne272e0842011-01-31 17:41:44 +00006516 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00006517
Owen Anderson53aa7a92009-08-10 22:56:29 +00006518 unsigned EVTBits = ExtVT.getSizeInBits();
Owen Andersonb2c80da2011-02-25 21:41:48 +00006519
Chris Lattner9a499e92010-12-22 08:01:44 +00006520 // Do not generate loads of non-round integer types since these can
6521 // be expensive (and would be wrong if the type is not byte sized).
6522 if (!ExtVT.isRound())
6523 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00006524
Evan Cheng464dc9b2007-03-22 01:54:19 +00006525 unsigned ShAmt = 0;
Chris Lattner9a499e92010-12-22 08:01:44 +00006526 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
Evan Cheng464dc9b2007-03-22 01:54:19 +00006527 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
Dan Gohmaneffb8942008-09-12 16:56:44 +00006528 ShAmt = N01->getZExtValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00006529 // Is the shift amount a multiple of size of VT?
6530 if ((ShAmt & (EVTBits-1)) == 0) {
6531 N0 = N0.getOperand(0);
Eli Friedman1e008c12009-08-19 08:46:10 +00006532 // Is the load width a multiple of size of VT?
6533 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006534 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00006535 }
Wesley Peck527da1b2010-11-23 03:31:01 +00006536
Chris Lattnercafc1e62010-12-22 08:02:57 +00006537 // At this point, we must have a load or else we can't do the transform.
6538 if (!isa<LoadSDNode>(N0)) return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00006539
Chandler Carruthb27041c2012-12-11 00:36:57 +00006540 // Because a SRL must be assumed to *need* to zero-extend the high bits
6541 // (as opposed to anyext the high bits), we can't combine the zextload
6542 // lowering of SRL and an sextload.
6543 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6544 return SDValue();
6545
Chris Lattnera2050552010-10-01 05:36:09 +00006546 // If the shift amount is larger than the input type then we're not
6547 // accessing any of the loaded bytes. If the load was a zextload/extload
6548 // then the result of the shift+trunc is zero/undef (handled elsewhere).
Chris Lattnercafc1e62010-12-22 08:02:57 +00006549 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
Chris Lattnera2050552010-10-01 05:36:09 +00006550 return SDValue();
Evan Cheng464dc9b2007-03-22 01:54:19 +00006551 }
6552 }
6553
Dan Gohman68fb0042010-11-03 01:47:46 +00006554 // If the load is shifted left (and the result isn't shifted back right),
6555 // we can fold the truncate through the shift.
6556 unsigned ShLeftAmt = 0;
6557 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
Chris Lattner222374d2010-12-22 07:36:50 +00006558 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
Dan Gohman68fb0042010-11-03 01:47:46 +00006559 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6560 ShLeftAmt = N01->getZExtValue();
6561 N0 = N0.getOperand(0);
6562 }
6563 }
Owen Andersonb2c80da2011-02-25 21:41:48 +00006564
Chris Lattner222374d2010-12-22 07:36:50 +00006565 // If we haven't found a load, we can't narrow it. Don't transform one with
6566 // multiple uses, this would require adding a new load.
Bill Schmidtd006c692013-01-14 22:04:38 +00006567 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6568 return SDValue();
6569
6570 // Don't change the width of a volatile load.
6571 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6572 if (LN0->isVolatile())
Chris Lattner222374d2010-12-22 07:36:50 +00006573 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00006574
Chris Lattner9a499e92010-12-22 08:01:44 +00006575 // Verify that we are actually reducing a load width here.
Bill Schmidtd006c692013-01-14 22:04:38 +00006576 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
Chris Lattner222374d2010-12-22 07:36:50 +00006577 return SDValue();
Owen Andersonb2c80da2011-02-25 21:41:48 +00006578
Bill Schmidtd006c692013-01-14 22:04:38 +00006579 // For the transform to be legal, the load must produce only two values
6580 // (the value loaded and the chain). Don't transform a pre-increment
Stephen Lincfe7f352013-07-08 00:37:03 +00006581 // load, for example, which produces an extra value. Otherwise the
Bill Schmidtd006c692013-01-14 22:04:38 +00006582 // transformation is not equivalent, and the downstream logic to replace
6583 // uses gets things wrong.
6584 if (LN0->getNumValues() > 2)
6585 return SDValue();
6586
Benjamin Kramerc7332b22013-07-06 14:05:09 +00006587 // If the load that we're shrinking is an extload and we're not just
6588 // discarding the extension we can't simply shrink the load. Bail.
6589 // TODO: It would be possible to merge the extensions in some cases.
6590 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6591 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6592 return SDValue();
6593
Matt Arsenault810cb622014-12-12 00:00:24 +00006594 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6595 return SDValue();
6596
Chris Lattner222374d2010-12-22 07:36:50 +00006597 EVT PtrType = N0.getOperand(1).getValueType();
Bill Wendling7bfa43b2009-01-30 22:33:24 +00006598
Evan Cheng4c6f9172012-06-26 01:19:33 +00006599 if (PtrType == MVT::Untyped || PtrType.isExtended())
6600 // It's not possible to generate a constant of extended or untyped type.
6601 return SDValue();
6602
Chris Lattner222374d2010-12-22 07:36:50 +00006603 // For big endian targets, we need to adjust the offset to the pointer to
6604 // load the correct bytes.
6605 if (TLI.isBigEndian()) {
6606 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6607 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6608 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
Evan Cheng464dc9b2007-03-22 01:54:19 +00006609 }
6610
Chris Lattner222374d2010-12-22 07:36:50 +00006611 uint64_t PtrOff = ShAmt / 8;
6612 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006613 SDLoc DL(LN0);
6614 SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
Chris Lattner222374d2010-12-22 07:36:50 +00006615 PtrType, LN0->getBasePtr(),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006616 DAG.getConstant(PtrOff, DL, PtrType));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006617 AddToWorklist(NewPtr.getNode());
Chris Lattner222374d2010-12-22 07:36:50 +00006618
Chris Lattner9a499e92010-12-22 08:01:44 +00006619 SDValue Load;
6620 if (ExtType == ISD::NON_EXTLOAD)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006621 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
Chris Lattner9a499e92010-12-22 08:01:44 +00006622 LN0->getPointerInfo().getWithOffset(PtrOff),
Pete Cooper82cd9e82011-11-08 18:42:53 +00006623 LN0->isVolatile(), LN0->isNonTemporal(),
Hal Finkelcc39b672014-07-24 12:16:19 +00006624 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
Chris Lattner9a499e92010-12-22 08:01:44 +00006625 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00006626 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
Chris Lattner9a499e92010-12-22 08:01:44 +00006627 LN0->getPointerInfo().getWithOffset(PtrOff),
6628 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
Louis Gerbarg67474e32014-07-31 21:45:05 +00006629 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
Chris Lattner222374d2010-12-22 07:36:50 +00006630
6631 // Replace the old load's chain with the new load's chain.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006632 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00006633 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
Chris Lattner222374d2010-12-22 07:36:50 +00006634
6635 // Shift the result left, if we've swallowed a left shift.
6636 SDValue Result = Load;
6637 if (ShLeftAmt != 0) {
Owen Andersonb2c80da2011-02-25 21:41:48 +00006638 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
Chris Lattner222374d2010-12-22 07:36:50 +00006639 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6640 ShImmTy = VT;
Paul Redmond288604e2013-02-12 15:21:21 +00006641 // If the shift amount is as large as the result size (but, presumably,
6642 // no larger than the source) then the useful bits of the result are
6643 // zero; we can't simply return the shortened shift, because the result
6644 // of that operation is undefined.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006645 SDLoc DL(N0);
Paul Redmond288604e2013-02-12 15:21:21 +00006646 if (ShLeftAmt >= VT.getSizeInBits())
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006647 Result = DAG.getConstant(0, DL, VT);
Paul Redmond288604e2013-02-12 15:21:21 +00006648 else
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006649 Result = DAG.getNode(ISD::SHL, DL, VT,
6650 Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
Chris Lattner222374d2010-12-22 07:36:50 +00006651 }
6652
6653 // Return the new loaded value.
6654 return Result;
Evan Cheng464dc9b2007-03-22 01:54:19 +00006655}
6656
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006657SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6658 SDValue N0 = N->getOperand(0);
6659 SDValue N1 = N->getOperand(1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006660 EVT VT = N->getValueType(0);
6661 EVT EVT = cast<VTSDNode>(N1)->getVT();
Dan Gohman1d459e42009-12-11 21:31:27 +00006662 unsigned VTBits = VT.getScalarType().getSizeInBits();
Dan Gohman6bd3ef82010-01-09 02:13:55 +00006663 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00006664
Nate Begeman21158fc2005-09-01 00:19:25 +00006665 // fold (sext_in_reg c1) -> c1
Chris Lattner29062da2006-05-08 20:59:41 +00006666 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006667 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006668
Chris Lattner2a4d7b82006-05-06 22:43:44 +00006669 // If the input is already sign extended, just drop the extension.
Dan Gohman1d459e42009-12-11 21:31:27 +00006670 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
Chris Lattner1ecb2a22006-05-06 09:30:03 +00006671 return N0;
Scott Michelcf0da6c2009-02-17 22:15:04 +00006672
Nate Begeman7cea6ef2005-09-02 21:18:40 +00006673 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6674 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00006675 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006676 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00006677 N0.getOperand(0), N1);
Chris Lattner446e1ef2006-05-08 21:18:59 +00006678
Dan Gohman345d63c2008-07-31 00:50:31 +00006679 // fold (sext_in_reg (sext x)) -> (sext x)
6680 // fold (sext_in_reg (aext x)) -> (sext x)
6681 // if x is small enough.
6682 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6683 SDValue N00 = N0.getOperand(0);
Evan Chengf037f872010-04-16 22:26:19 +00006684 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6685 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006686 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
Dan Gohman345d63c2008-07-31 00:50:31 +00006687 }
6688
Chris Lattner9ad59152007-04-17 19:03:21 +00006689 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
Dan Gohman1f372ed2008-02-25 21:11:39 +00006690 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006691 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006692
Chris Lattner9ad59152007-04-17 19:03:21 +00006693 // fold operands of sext_in_reg based on knowledge that the top bits are not
6694 // demanded.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006695 if (SimplifyDemandedBits(SDValue(N, 0)))
6696 return SDValue(N, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00006697
Evan Cheng464dc9b2007-03-22 01:54:19 +00006698 // fold (sext_in_reg (load x)) -> (smaller sextload x)
6699 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006700 SDValue NarrowLoad = ReduceLoadWidth(N);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006701 if (NarrowLoad.getNode())
Evan Cheng464dc9b2007-03-22 01:54:19 +00006702 return NarrowLoad;
6703
Bill Wendling7bfa43b2009-01-30 22:33:24 +00006704 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00006705 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
Chris Lattner446e1ef2006-05-08 21:18:59 +00006706 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6707 if (N0.getOpcode() == ISD::SRL) {
6708 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
Dan Gohman1d459e42009-12-11 21:31:27 +00006709 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00006710 // We can turn this into an SRA iff the input to the SRL is already sign
Chris Lattner446e1ef2006-05-08 21:18:59 +00006711 // extended enough.
Dan Gohman309d3d52007-06-22 14:59:07 +00006712 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
Dan Gohman1d459e42009-12-11 21:31:27 +00006713 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006714 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00006715 N0.getOperand(0), N0.getOperand(1));
Chris Lattner446e1ef2006-05-08 21:18:59 +00006716 }
6717 }
Evan Cheng464dc9b2007-03-22 01:54:19 +00006718
Nate Begeman02b23c62005-10-13 03:11:28 +00006719 // fold (sext_inreg (extload x)) -> (sextload x)
Scott Michelcf0da6c2009-02-17 22:15:04 +00006720 if (ISD::isEXTLoad(N0.getNode()) &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00006721 ISD::isUNINDEXEDLoad(N0.getNode()) &&
Dan Gohman47a7d6f2008-01-30 00:15:11 +00006722 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006723 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00006724 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00006725 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006726 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00006727 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00006728 LN0->getBasePtr(), EVT,
6729 LN0->getMemOperand());
Chris Lattnerd39c60f2005-12-14 19:25:30 +00006730 CombineTo(N, ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006731 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006732 AddToWorklist(ExtLoad.getNode());
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006733 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00006734 }
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00006735 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
Gabor Greiff304a7a2008-08-28 21:40:38 +00006736 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
Evan Cheng8a1d09d2007-03-07 08:07:03 +00006737 N0.hasOneUse() &&
Dan Gohman47a7d6f2008-01-30 00:15:11 +00006738 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00006739 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00006740 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00006741 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00006742 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
Bill Wendling7bfa43b2009-01-30 22:33:24 +00006743 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00006744 LN0->getBasePtr(), EVT,
6745 LN0->getMemOperand());
Chris Lattnerd39c60f2005-12-14 19:25:30 +00006746 CombineTo(N, ExtLoad);
Gabor Greiff304a7a2008-08-28 21:40:38 +00006747 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006748 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Nate Begeman02b23c62005-10-13 03:11:28 +00006749 }
Evan Cheng4c0bd962011-06-21 06:01:08 +00006750
6751 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6752 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6753 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6754 N0.getOperand(1), false);
Craig Topperc0196b12014-04-14 00:51:57 +00006755 if (BSwap.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006756 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
Evan Cheng4c0bd962011-06-21 06:01:08 +00006757 BSwap, N1);
6758 }
6759
Andrea Di Biagio46dcddb2013-12-27 20:20:28 +00006760 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6761 // into a build_vector.
6762 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6763 SmallVector<SDValue, 8> Elts;
6764 unsigned NumElts = N0->getNumOperands();
6765 unsigned ShAmt = VTBits - EVTBits;
6766
6767 for (unsigned i = 0; i != NumElts; ++i) {
6768 SDValue Op = N0->getOperand(i);
6769 if (Op->getOpcode() == ISD::UNDEF) {
6770 Elts.push_back(Op);
6771 continue;
6772 }
6773
6774 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
Kevin Qin5cd73c92014-01-06 02:26:10 +00006775 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6776 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006777 SDLoc(Op), Op.getValueType()));
Andrea Di Biagio46dcddb2013-12-27 20:20:28 +00006778 }
6779
Craig Topper48d114b2014-04-26 18:35:24 +00006780 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
Andrea Di Biagio46dcddb2013-12-27 20:20:28 +00006781 }
6782
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006783 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00006784}
6785
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006786SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6787 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00006788 EVT VT = N->getValueType(0);
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006789 bool isLE = TLI.isLittleEndian();
Nate Begeman21158fc2005-09-01 00:19:25 +00006790
6791 // noop truncate
6792 if (N0.getValueType() == N->getValueType(0))
Nate Begemand23739d2005-09-06 04:43:02 +00006793 return N0;
Nate Begeman21158fc2005-09-01 00:19:25 +00006794 // fold (truncate c1) -> c1
Simon Pilgrim09f3ff92015-03-25 22:30:31 +00006795 if (isConstantIntBuildVectorOrConstantInt(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00006796 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
Nate Begeman21158fc2005-09-01 00:19:25 +00006797 // fold (truncate (truncate x)) -> (truncate x)
6798 if (N0.getOpcode() == ISD::TRUNCATE)
Andrew Trickef9de2a2013-05-25 02:42:55 +00006799 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
Nate Begeman21158fc2005-09-01 00:19:25 +00006800 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
Chris Lattner6855d622010-04-07 18:13:33 +00006801 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6802 N0.getOpcode() == ISD::SIGN_EXTEND ||
Chris Lattner907e3922006-05-05 22:56:26 +00006803 N0.getOpcode() == ISD::ANY_EXTEND) {
Duncan Sands11dd4242008-06-08 20:54:56 +00006804 if (N0.getOperand(0).getValueType().bitsLT(VT))
Nate Begeman21158fc2005-09-01 00:19:25 +00006805 // if the source is smaller than the dest, we still need an extend
Andrew Trickef9de2a2013-05-25 02:42:55 +00006806 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00006807 N0.getOperand(0));
Craig Topper5f9791f2012-09-29 07:18:53 +00006808 if (N0.getOperand(0).getValueType().bitsGT(VT))
Nate Begeman21158fc2005-09-01 00:19:25 +00006809 // if the source is larger than the dest, than we just need the truncate
Andrew Trickef9de2a2013-05-25 02:42:55 +00006810 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
Craig Topper5f9791f2012-09-29 07:18:53 +00006811 // if the source and dest are the same type, we can drop both the extend
6812 // and the truncate.
6813 return N0.getOperand(0);
Nate Begeman21158fc2005-09-01 00:19:25 +00006814 }
Evan Chengd63baea2007-03-21 20:14:05 +00006815
Nadav Rotem4f4546b2012-02-05 11:39:23 +00006816 // Fold extract-and-trunc into a narrow extract. For example:
6817 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6818 // i32 y = TRUNCATE(i64 x)
6819 // -- becomes --
6820 // v16i8 b = BITCAST (v2i64 val)
6821 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6822 //
6823 // Note: We only run this optimization after type legalization (which often
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006824 // creates this pattern) and before operation legalization after which
6825 // we need to be more careful about the vector instructions that we generate.
6826 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
Hal Finkelab51ecd2014-02-28 00:26:45 +00006827 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006828
6829 EVT VecTy = N0.getOperand(0).getValueType();
6830 EVT ExTy = N0.getValueType();
6831 EVT TrTy = N->getValueType(0);
6832
6833 unsigned NumElem = VecTy.getVectorNumElements();
6834 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6835
6836 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6837 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6838
6839 SDValue EltNo = N0->getOperand(1);
6840 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6841 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Tom Stellardd42c5942013-08-05 22:22:01 +00006842 EVT IndexTy = TLI.getVectorIdxTy();
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006843 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6844
Andrew Trickef9de2a2013-05-25 02:42:55 +00006845 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006846 NVT, N0.getOperand(0));
6847
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006848 SDLoc DL(N);
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006849 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006850 DL, TrTy, V,
6851 DAG.getConstant(Index, DL, IndexTy));
Nadav Rotem5399f4d2012-02-03 13:18:25 +00006852 }
6853 }
6854
Matt Arsenault3332b702014-07-10 18:21:04 +00006855 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6856 if (N0.getOpcode() == ISD::SELECT) {
6857 EVT SrcVT = N0.getValueType();
6858 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6859 TLI.isTruncateFree(SrcVT, VT)) {
6860 SDLoc SL(N0);
6861 SDValue Cond = N0.getOperand(0);
6862 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6863 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6864 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6865 }
6866 }
6867
Arnold Schwaighofer3f9568e2013-02-20 21:33:32 +00006868 // Fold a series of buildvector, bitcast, and truncate if possible.
6869 // For example fold
6870 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6871 // (2xi32 (buildvector x, y)).
6872 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6873 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6874 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6875 N0.getOperand(0).hasOneUse()) {
6876
6877 SDValue BuildVect = N0.getOperand(0);
6878 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6879 EVT TruncVecEltTy = VT.getVectorElementType();
6880
6881 // Check that the element types match.
6882 if (BuildVectEltTy == TruncVecEltTy) {
6883 // Now we only need to compute the offset of the truncated elements.
6884 unsigned BuildVecNumElts = BuildVect.getNumOperands();
6885 unsigned TruncVecNumElts = VT.getVectorNumElements();
6886 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6887
6888 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6889 "Invalid number of elements");
6890
6891 SmallVector<SDValue, 8> Opnds;
6892 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6893 Opnds.push_back(BuildVect.getOperand(i));
6894
Craig Topper48d114b2014-04-26 18:35:24 +00006895 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
Arnold Schwaighofer3f9568e2013-02-20 21:33:32 +00006896 }
6897 }
6898
Chris Lattner5e6fe052007-10-13 06:35:54 +00006899 // See if we can simplify the input to this truncate through knowledge that
Nadav Rotem502f1b92011-02-24 21:01:34 +00006900 // only the low bits are being used.
6901 // For example "trunc (or (shl x, 8), y)" // -> trunc y
Nadav Rotemb0091302011-02-27 07:40:43 +00006902 // Currently we only perform this optimization on scalars because vectors
Nadav Rotem502f1b92011-02-24 21:01:34 +00006903 // may have different active low bits.
6904 if (!VT.isVector()) {
6905 SDValue Shorter =
6906 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6907 VT.getSizeInBits()));
6908 if (Shorter.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +00006909 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
Nadav Rotem502f1b92011-02-24 21:01:34 +00006910 }
Nate Begeman8caf81d2005-10-12 20:40:40 +00006911 // fold (truncate (load x)) -> (smaller load x)
Evan Chengd63baea2007-03-21 20:14:05 +00006912 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
Dan Gohman600f62b2010-06-24 14:30:44 +00006913 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6914 SDValue Reduced = ReduceLoadWidth(N);
6915 if (Reduced.getNode())
6916 return Reduced;
Richard Sandifordd1093632013-12-11 11:37:27 +00006917 // Handle the case where the load remains an extending load even
6918 // after truncation.
6919 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6920 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6921 if (!LN0->isVolatile() &&
6922 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6923 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6924 VT, LN0->getChain(), LN0->getBasePtr(),
6925 LN0->getMemoryVT(),
6926 LN0->getMemOperand());
6927 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6928 return NewLoad;
6929 }
6930 }
Dan Gohman600f62b2010-06-24 14:30:44 +00006931 }
Michael Liao3ac82012012-10-17 23:45:54 +00006932 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6933 // where ... are all 'undef'.
6934 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6935 SmallVector<EVT, 8> VTs;
6936 SDValue V;
6937 unsigned Idx = 0;
6938 unsigned NumDefs = 0;
6939
6940 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6941 SDValue X = N0.getOperand(i);
6942 if (X.getOpcode() != ISD::UNDEF) {
6943 V = X;
6944 Idx = i;
6945 NumDefs++;
6946 }
6947 // Stop if more than one members are non-undef.
6948 if (NumDefs > 1)
6949 break;
6950 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6951 VT.getVectorElementType(),
6952 X.getValueType().getVectorNumElements()));
6953 }
6954
6955 if (NumDefs == 0)
6956 return DAG.getUNDEF(VT);
6957
6958 if (NumDefs == 1) {
6959 assert(V.getNode() && "The single defined operand is empty!");
6960 SmallVector<SDValue, 8> Opnds;
6961 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6962 if (i != Idx) {
6963 Opnds.push_back(DAG.getUNDEF(VTs[i]));
6964 continue;
6965 }
Andrew Trickef9de2a2013-05-25 02:42:55 +00006966 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00006967 AddToWorklist(NV.getNode());
Michael Liao3ac82012012-10-17 23:45:54 +00006968 Opnds.push_back(NV);
6969 }
Craig Topper48d114b2014-04-26 18:35:24 +00006970 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
Michael Liao3ac82012012-10-17 23:45:54 +00006971 }
6972 }
Dan Gohman600f62b2010-06-24 14:30:44 +00006973
6974 // Simplify the operands using demanded-bits information.
6975 if (!VT.isVector() &&
6976 SimplifyDemandedBits(SDValue(N, 0)))
6977 return SDValue(N, 0);
6978
Evan Chengf1bd5fc2010-04-17 06:13:15 +00006979 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00006980}
6981
Evan Chengb980f6f2008-05-12 23:04:07 +00006982static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006983 SDValue Elt = N->getOperand(i);
Evan Chengb980f6f2008-05-12 23:04:07 +00006984 if (Elt.getOpcode() != ISD::MERGE_VALUES)
Gabor Greiff304a7a2008-08-28 21:40:38 +00006985 return Elt.getNode();
6986 return Elt.getOperand(Elt.getResNo()).getNode();
Evan Chengb980f6f2008-05-12 23:04:07 +00006987}
6988
Sanjay Patel50cbfc52014-08-28 16:29:51 +00006989/// build_pair (load, load) -> load
Scott Michelcf0da6c2009-02-17 22:15:04 +00006990/// if load locations are consecutive.
Owen Anderson53aa7a92009-08-10 22:56:29 +00006991SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
Evan Chengb980f6f2008-05-12 23:04:07 +00006992 assert(N->getOpcode() == ISD::BUILD_PAIR);
6993
Nate Begeman624690c2009-06-05 21:37:30 +00006994 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6995 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
Chris Lattnerf72c3c02010-09-21 16:08:50 +00006996 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
Matt Arsenault58a76392014-02-24 21:01:15 +00006997 LD1->getAddressSpace() != LD2->getAddressSpace())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00006998 return SDValue();
Owen Anderson53aa7a92009-08-10 22:56:29 +00006999 EVT LD1VT = LD1->getValueType(0);
Bill Wendling4e0a6152009-01-30 22:44:24 +00007000
Evan Chengb980f6f2008-05-12 23:04:07 +00007001 if (ISD::isNON_EXTLoad(LD2) &&
7002 LD2->hasOneUse() &&
Duncan Sands8651e9c2008-06-13 19:07:40 +00007003 // If both are volatile this would reduce the number of volatile loads.
7004 // If one is volatile it might be ok, but play conservative and bail out.
Nate Begeman624690c2009-06-05 21:37:30 +00007005 !LD1->isVolatile() &&
7006 !LD2->isVolatile() &&
Evan Chengf5938d52009-12-09 01:36:00 +00007007 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
Nate Begeman624690c2009-06-05 21:37:30 +00007008 unsigned Align = LD1->getAlignment();
Micah Villmowcdfe20b2012-10-08 16:38:25 +00007009 unsigned NewAlign = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +00007010 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
Bill Wendling4e0a6152009-01-30 22:44:24 +00007011
Duncan Sands8651e9c2008-06-13 19:07:40 +00007012 if (NewAlign <= Align &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007013 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00007014 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
Chris Lattnerf72c3c02010-09-21 16:08:50 +00007015 LD1->getBasePtr(), LD1->getPointerInfo(),
Pete Cooper82cd9e82011-11-08 18:42:53 +00007016 false, false, false, Align);
Evan Chengb980f6f2008-05-12 23:04:07 +00007017 }
Bill Wendling4e0a6152009-01-30 22:44:24 +00007018
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007019 return SDValue();
Evan Chengb980f6f2008-05-12 23:04:07 +00007020}
7021
Wesley Peck527da1b2010-11-23 03:31:01 +00007022SDValue DAGCombiner::visitBITCAST(SDNode *N) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007023 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007024 EVT VT = N->getValueType(0);
Chris Lattnera1874602005-12-23 05:30:37 +00007025
Dan Gohmana8665142007-06-25 16:23:39 +00007026 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
7027 // Only do this before legalize, since afterward the target may be depending
7028 // on the bitconvert.
7029 // First check to see if this is all constant.
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007030 if (!LegalTypes &&
Gabor Greiff304a7a2008-08-28 21:40:38 +00007031 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
Duncan Sands13237ac2008-06-06 12:08:01 +00007032 VT.isVector()) {
Juergen Ributzka73844052014-01-13 20:51:35 +00007033 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
Scott Michelcf0da6c2009-02-17 22:15:04 +00007034
Owen Anderson53aa7a92009-08-10 22:56:29 +00007035 EVT DestEltVT = N->getValueType(0).getVectorElementType();
Duncan Sands13237ac2008-06-06 12:08:01 +00007036 assert(!DestEltVT.isVector() &&
Dan Gohmana8665142007-06-25 16:23:39 +00007037 "Element type of vector ValueType must not be vector!");
Bill Wendling4e0a6152009-01-30 22:44:24 +00007038 if (isSimple)
Wesley Peck527da1b2010-11-23 03:31:01 +00007039 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
Dan Gohmana8665142007-06-25 16:23:39 +00007040 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007041
Dan Gohman921ddd62008-09-05 01:58:21 +00007042 // If the input is a constant, let getNode fold it.
Chris Lattnera1874602005-12-23 05:30:37 +00007043 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
Chandler Carruthb65d61a2015-02-10 02:25:56 +00007044 // If we can't allow illegal operations, we need to check that this is just
7045 // a fp -> int or int -> conversion and that the resulting operation will
7046 // be legal.
7047 if (!LegalOperations ||
7048 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
7049 TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
7050 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
7051 TLI.isOperationLegal(ISD::Constant, VT)))
7052 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
Chris Lattnera1874602005-12-23 05:30:37 +00007053 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007054
Bill Wendling4e0a6152009-01-30 22:44:24 +00007055 // (conv (conv x, t1), t2) -> (conv x, t2)
Wesley Peck527da1b2010-11-23 03:31:01 +00007056 if (N0.getOpcode() == ISD::BITCAST)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007057 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00007058 N0.getOperand(0));
Chris Lattnere4e64b62006-04-02 02:53:43 +00007059
Chris Lattner54560f62005-12-23 05:44:41 +00007060 // fold (conv (load x)) -> (load (conv*)x)
Evan Cheng0de312d2007-10-06 08:19:55 +00007061 // If the resultant load doesn't need a higher alignment than the original!
Gabor Greiff304a7a2008-08-28 21:40:38 +00007062 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Duncan Sands8651e9c2008-06-13 19:07:40 +00007063 // Do not change the width of a volatile load.
7064 !cast<LoadSDNode>(N0)->isVolatile() &&
Ulrich Weigandf236bb12014-07-03 15:06:47 +00007065 // Do not remove the cast if the types differ in endian layout.
7066 TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
7067 TLI.hasBigEndianPartOrdering(VT) &&
Matt Arsenaultc5559bb2013-11-15 04:42:23 +00007068 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
7069 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00007070 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Micah Villmowcdfe20b2012-10-08 16:38:25 +00007071 unsigned Align = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +00007072 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
Evan Chenga4cf58a2007-05-07 21:27:48 +00007073 unsigned OrigAlign = LN0->getAlignment();
Bill Wendling4e0a6152009-01-30 22:44:24 +00007074
Evan Chenga4cf58a2007-05-07 21:27:48 +00007075 if (Align <= OrigAlign) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007076 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
Chris Lattnerf72c3c02010-09-21 16:08:50 +00007077 LN0->getBasePtr(), LN0->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +00007078 LN0->isVolatile(), LN0->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00007079 LN0->isInvariant(), OrigAlign,
Hal Finkelcc39b672014-07-24 12:16:19 +00007080 LN0->getAAInfo());
Chandler Carruth7cd15be2014-08-14 08:18:34 +00007081 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
Evan Chenga4cf58a2007-05-07 21:27:48 +00007082 return Load;
7083 }
Chris Lattner54560f62005-12-23 05:44:41 +00007084 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00007085
Bill Wendling4e0a6152009-01-30 22:44:24 +00007086 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7087 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
Chris Lattner888560d2008-01-27 17:42:27 +00007088 // This often reduces constant pool loads.
Tom Stellardc54731a2013-07-23 23:55:03 +00007089 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
7090 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
Nadav Rotem24a822a2012-09-13 14:54:28 +00007091 N0.getNode()->hasOneUse() && VT.isInteger() &&
7092 !VT.isVector() && !N0.getValueType().isVector()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007093 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
Bill Wendling4e0a6152009-01-30 22:44:24 +00007094 N0.getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007095 AddToWorklist(NewConv.getNode());
Scott Michelcf0da6c2009-02-17 22:15:04 +00007096
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007097 SDLoc DL(N);
Duncan Sands13237ac2008-06-06 12:08:01 +00007098 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
Chris Lattner888560d2008-01-27 17:42:27 +00007099 if (N0.getOpcode() == ISD::FNEG)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007100 return DAG.getNode(ISD::XOR, DL, VT,
7101 NewConv, DAG.getConstant(SignBit, DL, VT));
Chris Lattner888560d2008-01-27 17:42:27 +00007102 assert(N0.getOpcode() == ISD::FABS);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007103 return DAG.getNode(ISD::AND, DL, VT,
7104 NewConv, DAG.getConstant(~SignBit, DL, VT));
Chris Lattner888560d2008-01-27 17:42:27 +00007105 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007106
Bill Wendling4e0a6152009-01-30 22:44:24 +00007107 // fold (bitconvert (fcopysign cst, x)) ->
7108 // (or (and (bitconvert x), sign), (and cst, (not sign)))
7109 // Note that we don't handle (copysign x, cst) because this can always be
7110 // folded to an fneg or fabs.
Gabor Greiff304a7a2008-08-28 21:40:38 +00007111 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
Chris Lattner2ee91f42008-01-27 23:32:17 +00007112 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
Duncan Sands13237ac2008-06-06 12:08:01 +00007113 VT.isInteger() && !VT.isVector()) {
7114 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
Owen Anderson117c9e82009-08-12 00:36:31 +00007115 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
Chris Lattner4041ab62010-04-15 04:48:01 +00007116 if (isTypeLegal(IntXVT)) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007117 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling4e0a6152009-01-30 22:44:24 +00007118 IntXVT, N0.getOperand(1));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007119 AddToWorklist(X.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00007120
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007121 // If X has a different width than the result/lhs, sext it or truncate it.
7122 unsigned VTWidth = VT.getSizeInBits();
7123 if (OrigXWidth < VTWidth) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00007124 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007125 AddToWorklist(X.getNode());
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007126 } else if (OrigXWidth > VTWidth) {
7127 // To get the sign bit in the right place, we have to shift it right
7128 // before truncating.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007129 SDLoc DL(X);
7130 X = DAG.getNode(ISD::SRL, DL,
Bill Wendling4e0a6152009-01-30 22:44:24 +00007131 X.getValueType(), X,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007132 DAG.getConstant(OrigXWidth-VTWidth, DL,
7133 X.getValueType()));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007134 AddToWorklist(X.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00007135 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007136 AddToWorklist(X.getNode());
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007137 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007138
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007139 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
Andrew Trickef9de2a2013-05-25 02:42:55 +00007140 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007141 X, DAG.getConstant(SignBit, SDLoc(X), VT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007142 AddToWorklist(X.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00007143
Andrew Trickef9de2a2013-05-25 02:42:55 +00007144 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
Bill Wendling4e0a6152009-01-30 22:44:24 +00007145 VT, N0.getOperand(0));
Andrew Trickef9de2a2013-05-25 02:42:55 +00007146 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007147 Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007148 AddToWorklist(Cst.getNode());
Chris Lattner888560d2008-01-27 17:42:27 +00007149
Andrew Trickef9de2a2013-05-25 02:42:55 +00007150 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007151 }
Chris Lattner888560d2008-01-27 17:42:27 +00007152 }
Evan Chengb980f6f2008-05-12 23:04:07 +00007153
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00007154 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
Evan Chengb980f6f2008-05-12 23:04:07 +00007155 if (N0.getOpcode() == ISD::BUILD_PAIR) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00007156 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
7157 if (CombineLD.getNode())
Evan Chengb980f6f2008-05-12 23:04:07 +00007158 return CombineLD;
7159 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007160
Simon Pilgrim86b034b2015-04-23 08:43:13 +00007161 // Remove double bitcasts from shuffles - this is often a legacy of
7162 // XformToShuffleWithZero being used to combine bitmaskings (of
7163 // float vectors bitcast to integer vectors) into shuffles.
7164 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7165 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7166 N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7167 VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7168 !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7169 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7170
7171 // If operands are a bitcast, peek through if it casts the original VT.
7172 // If operands are a UNDEF or constant, just bitcast back to original VT.
7173 auto PeekThroughBitcast = [&](SDValue Op) {
7174 if (Op.getOpcode() == ISD::BITCAST &&
7175 Op.getOperand(0)->getValueType(0) == VT)
7176 return SDValue(Op.getOperand(0));
7177 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7178 ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7179 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
7180 return SDValue();
7181 };
7182
7183 SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7184 SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7185 if (!(SV0 && SV1))
7186 return SDValue();
7187
7188 int MaskScale =
7189 VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7190 SmallVector<int, 8> NewMask;
7191 for (int M : SVN->getMask())
7192 for (int i = 0; i != MaskScale; ++i)
7193 NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7194
7195 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7196 if (!LegalMask) {
7197 std::swap(SV0, SV1);
7198 ShuffleVectorSDNode::commuteMask(NewMask);
7199 LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7200 }
7201
7202 if (LegalMask)
7203 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7204 }
7205
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007206 return SDValue();
Chris Lattnera1874602005-12-23 05:30:37 +00007207}
7208
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007209SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00007210 EVT VT = N->getValueType(0);
Evan Chengb980f6f2008-05-12 23:04:07 +00007211 return CombineConsecutiveLoads(N, VT);
7212}
7213
Sanjay Patel50cbfc52014-08-28 16:29:51 +00007214/// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7215/// operands. DstEltVT indicates the destination element value type.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007216SDValue DAGCombiner::
Wesley Peck527da1b2010-11-23 03:31:01 +00007217ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
Owen Anderson53aa7a92009-08-10 22:56:29 +00007218 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
Scott Michelcf0da6c2009-02-17 22:15:04 +00007219
Chris Lattnere4e64b62006-04-02 02:53:43 +00007220 // If this is already the right type, we're done.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007221 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00007222
Duncan Sands13237ac2008-06-06 12:08:01 +00007223 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7224 unsigned DstBitSize = DstEltVT.getSizeInBits();
Scott Michelcf0da6c2009-02-17 22:15:04 +00007225
Chris Lattnere4e64b62006-04-02 02:53:43 +00007226 // If this is a conversion of N elements of one type to N elements of another
7227 // type, convert each element. This handles FP<->INT cases.
7228 if (SrcBitSize == DstBitSize) {
Nate Begeman317b9692010-07-27 18:02:18 +00007229 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7230 BV->getValueType(0).getVectorNumElements());
7231
7232 // Due to the FP element handling below calling this routine recursively,
7233 // we can end up with a scalar-to-vector node here.
7234 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007235 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7236 DAG.getNode(ISD::BITCAST, SDLoc(BV),
Nate Begeman317b9692010-07-27 18:02:18 +00007237 DstEltVT, BV->getOperand(0)));
Wesley Peck527da1b2010-11-23 03:31:01 +00007238
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007239 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +00007240 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
Bob Wilson59dbbb22009-04-13 22:05:19 +00007241 SDValue Op = BV->getOperand(i);
7242 // If the vector element type is not legal, the BUILD_VECTOR operands
7243 // are promoted and implicitly truncated. Make that explicit here.
Bob Wilsonda188eb2009-04-20 17:27:09 +00007244 if (Op.getValueType() != SrcEltVT)
Andrew Trickef9de2a2013-05-25 02:42:55 +00007245 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7246 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
Bob Wilson59dbbb22009-04-13 22:05:19 +00007247 DstEltVT, Op));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00007248 AddToWorklist(Ops.back().getNode());
Chris Lattner098c01e2006-04-08 04:15:24 +00007249 }
Craig Topper48d114b2014-04-26 18:35:24 +00007250 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
Chris Lattnere4e64b62006-04-02 02:53:43 +00007251 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007252
Chris Lattnere4e64b62006-04-02 02:53:43 +00007253 // Otherwise, we're growing or shrinking the elements. To avoid having to
7254 // handle annoying details of growing/shrinking FP values, we convert them to
7255 // int first.
Duncan Sands13237ac2008-06-06 12:08:01 +00007256 if (SrcEltVT.isFloatingPoint()) {
Chris Lattnere4e64b62006-04-02 02:53:43 +00007257 // Convert the input float vector to a int vector where the elements are the
7258 // same sizes.
Owen Anderson117c9e82009-08-12 00:36:31 +00007259 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
Wesley Peck527da1b2010-11-23 03:31:01 +00007260 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
Chris Lattnere4e64b62006-04-02 02:53:43 +00007261 SrcEltVT = IntVT;
7262 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007263
Chris Lattnere4e64b62006-04-02 02:53:43 +00007264 // Now we know the input is an integer vector. If the output is a FP type,
7265 // convert to integer first, then to FP of the right size.
Duncan Sands13237ac2008-06-06 12:08:01 +00007266 if (DstEltVT.isFloatingPoint()) {
Owen Anderson117c9e82009-08-12 00:36:31 +00007267 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
Wesley Peck527da1b2010-11-23 03:31:01 +00007268 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
Scott Michelcf0da6c2009-02-17 22:15:04 +00007269
Chris Lattnere4e64b62006-04-02 02:53:43 +00007270 // Next, convert to FP elements of the same size.
Wesley Peck527da1b2010-11-23 03:31:01 +00007271 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
Chris Lattnere4e64b62006-04-02 02:53:43 +00007272 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007273
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007274 SDLoc DL(BV);
7275
Chris Lattnere4e64b62006-04-02 02:53:43 +00007276 // Okay, we know the src/dst types are both integers of differing types.
7277 // Handling growing first.
Duncan Sands13237ac2008-06-06 12:08:01 +00007278 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
Chris Lattnere4e64b62006-04-02 02:53:43 +00007279 if (SrcBitSize < DstBitSize) {
7280 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007281
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007282 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +00007283 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
Chris Lattnere4e64b62006-04-02 02:53:43 +00007284 i += NumInputsPerOutput) {
7285 bool isLE = TLI.isLittleEndian();
Dan Gohmane1c4f992008-03-03 23:51:38 +00007286 APInt NewBits = APInt(DstBitSize, 0);
Chris Lattnere4e64b62006-04-02 02:53:43 +00007287 bool EltIsUndef = true;
7288 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7289 // Shift the previously computed bits over.
7290 NewBits <<= SrcBitSize;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007291 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
Chris Lattnere4e64b62006-04-02 02:53:43 +00007292 if (Op.getOpcode() == ISD::UNDEF) continue;
7293 EltIsUndef = false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007294
Jay Foad583abbc2010-12-07 08:25:19 +00007295 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
Dan Gohmanecd40a32010-04-12 02:24:01 +00007296 zextOrTrunc(SrcBitSize).zext(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00007297 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007298
Chris Lattnere4e64b62006-04-02 02:53:43 +00007299 if (EltIsUndef)
Dale Johannesen84935752009-02-06 23:05:02 +00007300 Ops.push_back(DAG.getUNDEF(DstEltVT));
Chris Lattnere4e64b62006-04-02 02:53:43 +00007301 else
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007302 Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
Chris Lattnere4e64b62006-04-02 02:53:43 +00007303 }
7304
Owen Anderson117c9e82009-08-12 00:36:31 +00007305 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007306 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
Chris Lattnere4e64b62006-04-02 02:53:43 +00007307 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00007308
Chris Lattnere4e64b62006-04-02 02:53:43 +00007309 // Finally, this must be the case where we are shrinking elements: each input
7310 // turns into multiple outputs.
7311 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
Owen Anderson117c9e82009-08-12 00:36:31 +00007312 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7313 NumOutputsPerInput*BV->getNumOperands());
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007314 SmallVector<SDValue, 8> Ops;
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00007315
Dan Gohmana8665142007-06-25 16:23:39 +00007316 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
Chris Lattnere4e64b62006-04-02 02:53:43 +00007317 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00007318 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
Chris Lattnere4e64b62006-04-02 02:53:43 +00007319 continue;
7320 }
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00007321
Jay Foad583abbc2010-12-07 08:25:19 +00007322 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
7323 getAPIntValue().zextOrTrunc(SrcBitSize);
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00007324
Chris Lattnere4e64b62006-04-02 02:53:43 +00007325 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
Jay Foad583abbc2010-12-07 08:25:19 +00007326 APInt ThisVal = OpVal.trunc(DstBitSize);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007327 Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
Dan Gohmane1c4f992008-03-03 23:51:38 +00007328 OpVal = OpVal.lshr(DstBitSize);
Chris Lattnere4e64b62006-04-02 02:53:43 +00007329 }
7330
7331 // For big endian targets, swap the order of the pieces of each element.
Duncan Sands7377f5f2008-02-11 10:37:04 +00007332 if (TLI.isBigEndian())
Chris Lattnere4e64b62006-04-02 02:53:43 +00007333 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7334 }
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00007335
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007336 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
Chris Lattnere4e64b62006-04-02 02:53:43 +00007337}
7338
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007339/// Try to perform FMA combining on a given FADD node.
7340SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007341 SDValue N0 = N->getOperand(0);
7342 SDValue N1 = N->getOperand(1);
7343 EVT VT = N->getValueType(0);
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007344 SDLoc SL(N);
7345
7346 const TargetOptions &Options = DAG.getTarget().Options;
7347 bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7348 Options.UnsafeFPMath);
7349
7350 // Floating-point multiply-add with intermediate rounding.
7351 bool HasFMAD = (LegalOperations &&
7352 TLI.isOperationLegal(ISD::FMAD, VT));
7353
7354 // Floating-point multiply-add without intermediate rounding.
7355 bool HasFMA = ((!LegalOperations ||
7356 TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7357 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7358 UnsafeFPMath);
7359
7360 // No valid opcode, do not combine.
7361 if (!HasFMAD && !HasFMA)
7362 return SDValue();
7363
7364 // Always prefer FMAD to FMA for precision.
7365 unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7366 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7367 bool LookThroughFPExt = TLI.isFPExtFree(VT);
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007368
7369 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7370 if (N0.getOpcode() == ISD::FMUL &&
7371 (Aggressive || N0->hasOneUse())) {
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007372 return DAG.getNode(PreferredFusedOpcode, SL, VT,
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007373 N0.getOperand(0), N0.getOperand(1), N1);
7374 }
7375
7376 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7377 // Note: Commutes FADD operands.
7378 if (N1.getOpcode() == ISD::FMUL &&
7379 (Aggressive || N1->hasOneUse())) {
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007380 return DAG.getNode(PreferredFusedOpcode, SL, VT,
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007381 N1.getOperand(0), N1.getOperand(1), N0);
7382 }
7383
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007384 // Look through FP_EXTEND nodes to do more combining.
7385 if (UnsafeFPMath && LookThroughFPExt) {
7386 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7387 if (N0.getOpcode() == ISD::FP_EXTEND) {
7388 SDValue N00 = N0.getOperand(0);
7389 if (N00.getOpcode() == ISD::FMUL)
7390 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7391 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7392 N00.getOperand(0)),
7393 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7394 N00.getOperand(1)), N1);
7395 }
7396
7397 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7398 // Note: Commutes FADD operands.
7399 if (N1.getOpcode() == ISD::FP_EXTEND) {
7400 SDValue N10 = N1.getOperand(0);
7401 if (N10.getOpcode() == ISD::FMUL)
7402 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7403 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7404 N10.getOperand(0)),
7405 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7406 N10.getOperand(1)), N0);
7407 }
7408 }
7409
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007410 // More folding opportunities when target permits.
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007411 if ((UnsafeFPMath || HasFMAD) && Aggressive) {
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007412 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007413 if (N0.getOpcode() == PreferredFusedOpcode &&
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007414 N0.getOperand(2).getOpcode() == ISD::FMUL) {
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007415 return DAG.getNode(PreferredFusedOpcode, SL, VT,
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007416 N0.getOperand(0), N0.getOperand(1),
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007417 DAG.getNode(PreferredFusedOpcode, SL, VT,
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007418 N0.getOperand(2).getOperand(0),
7419 N0.getOperand(2).getOperand(1),
7420 N1));
7421 }
7422
7423 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007424 if (N1->getOpcode() == PreferredFusedOpcode &&
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007425 N1.getOperand(2).getOpcode() == ISD::FMUL) {
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007426 return DAG.getNode(PreferredFusedOpcode, SL, VT,
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007427 N1.getOperand(0), N1.getOperand(1),
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007428 DAG.getNode(PreferredFusedOpcode, SL, VT,
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007429 N1.getOperand(2).getOperand(0),
7430 N1.getOperand(2).getOperand(1),
7431 N0));
7432 }
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007433
Olivier Sallenavec587bee2015-04-22 14:07:26 +00007434 if (UnsafeFPMath && LookThroughFPExt) {
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007435 // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7436 // -> (fma x, y, (fma (fpext u), (fpext v), z))
7437 auto FoldFAddFMAFPExtFMul = [&] (
7438 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7439 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7440 DAG.getNode(PreferredFusedOpcode, SL, VT,
7441 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7442 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7443 Z));
7444 };
7445 if (N0.getOpcode() == PreferredFusedOpcode) {
7446 SDValue N02 = N0.getOperand(2);
7447 if (N02.getOpcode() == ISD::FP_EXTEND) {
7448 SDValue N020 = N02.getOperand(0);
7449 if (N020.getOpcode() == ISD::FMUL)
7450 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7451 N020.getOperand(0), N020.getOperand(1),
7452 N1);
7453 }
7454 }
7455
7456 // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7457 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
7458 // FIXME: This turns two single-precision and one double-precision
7459 // operation into two double-precision operations, which might not be
7460 // interesting for all targets, especially GPUs.
7461 auto FoldFAddFPExtFMAFMul = [&] (
7462 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7463 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7464 DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7465 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7466 DAG.getNode(PreferredFusedOpcode, SL, VT,
7467 DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7468 DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7469 Z));
7470 };
7471 if (N0.getOpcode() == ISD::FP_EXTEND) {
7472 SDValue N00 = N0.getOperand(0);
7473 if (N00.getOpcode() == PreferredFusedOpcode) {
7474 SDValue N002 = N00.getOperand(2);
7475 if (N002.getOpcode() == ISD::FMUL)
7476 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7477 N002.getOperand(0), N002.getOperand(1),
7478 N1);
7479 }
7480 }
7481
7482 // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7483 // -> (fma y, z, (fma (fpext u), (fpext v), x))
7484 if (N1.getOpcode() == PreferredFusedOpcode) {
7485 SDValue N12 = N1.getOperand(2);
7486 if (N12.getOpcode() == ISD::FP_EXTEND) {
7487 SDValue N120 = N12.getOperand(0);
7488 if (N120.getOpcode() == ISD::FMUL)
7489 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
7490 N120.getOperand(0), N120.getOperand(1),
7491 N0);
7492 }
7493 }
7494
7495 // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
7496 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
7497 // FIXME: This turns two single-precision and one double-precision
7498 // operation into two double-precision operations, which might not be
7499 // interesting for all targets, especially GPUs.
7500 if (N1.getOpcode() == ISD::FP_EXTEND) {
7501 SDValue N10 = N1.getOperand(0);
7502 if (N10.getOpcode() == PreferredFusedOpcode) {
7503 SDValue N102 = N10.getOperand(2);
7504 if (N102.getOpcode() == ISD::FMUL)
7505 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
7506 N102.getOperand(0), N102.getOperand(1),
7507 N0);
7508 }
7509 }
7510 }
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007511 }
7512
7513 return SDValue();
7514}
7515
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007516/// Try to perform FMA combining on a given FSUB node.
7517SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007518 SDValue N0 = N->getOperand(0);
7519 SDValue N1 = N->getOperand(1);
7520 EVT VT = N->getValueType(0);
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007521 SDLoc SL(N);
7522
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007523 const TargetOptions &Options = DAG.getTarget().Options;
7524 bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7525 Options.UnsafeFPMath);
7526
7527 // Floating-point multiply-add with intermediate rounding.
7528 bool HasFMAD = (LegalOperations &&
7529 TLI.isOperationLegal(ISD::FMAD, VT));
7530
7531 // Floating-point multiply-add without intermediate rounding.
7532 bool HasFMA = ((!LegalOperations ||
7533 TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7534 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7535 UnsafeFPMath);
7536
7537 // No valid opcode, do not combine.
7538 if (!HasFMAD && !HasFMA)
7539 return SDValue();
7540
7541 // Always prefer FMAD to FMA for precision.
7542 unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7543 bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7544 bool LookThroughFPExt = TLI.isFPExtFree(VT);
7545
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007546 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7547 if (N0.getOpcode() == ISD::FMUL &&
7548 (Aggressive || N0->hasOneUse())) {
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007549 return DAG.getNode(PreferredFusedOpcode, SL, VT,
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007550 N0.getOperand(0), N0.getOperand(1),
7551 DAG.getNode(ISD::FNEG, SL, VT, N1));
7552 }
7553
7554 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7555 // Note: Commutes FSUB operands.
7556 if (N1.getOpcode() == ISD::FMUL &&
7557 (Aggressive || N1->hasOneUse()))
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007558 return DAG.getNode(PreferredFusedOpcode, SL, VT,
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007559 DAG.getNode(ISD::FNEG, SL, VT,
7560 N1.getOperand(0)),
7561 N1.getOperand(1), N0);
7562
7563 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7564 if (N0.getOpcode() == ISD::FNEG &&
7565 N0.getOperand(0).getOpcode() == ISD::FMUL &&
7566 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7567 SDValue N00 = N0.getOperand(0).getOperand(0);
7568 SDValue N01 = N0.getOperand(0).getOperand(1);
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007569 return DAG.getNode(PreferredFusedOpcode, SL, VT,
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007570 DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7571 DAG.getNode(ISD::FNEG, SL, VT, N1));
7572 }
7573
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007574 // Look through FP_EXTEND nodes to do more combining.
7575 if (UnsafeFPMath && LookThroughFPExt) {
7576 // fold (fsub (fpext (fmul x, y)), z)
7577 // -> (fma (fpext x), (fpext y), (fneg z))
7578 if (N0.getOpcode() == ISD::FP_EXTEND) {
7579 SDValue N00 = N0.getOperand(0);
7580 if (N00.getOpcode() == ISD::FMUL)
7581 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7582 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7583 N00.getOperand(0)),
7584 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7585 N00.getOperand(1)),
7586 DAG.getNode(ISD::FNEG, SL, VT, N1));
7587 }
7588
7589 // fold (fsub x, (fpext (fmul y, z)))
7590 // -> (fma (fneg (fpext y)), (fpext z), x)
7591 // Note: Commutes FSUB operands.
7592 if (N1.getOpcode() == ISD::FP_EXTEND) {
7593 SDValue N10 = N1.getOperand(0);
7594 if (N10.getOpcode() == ISD::FMUL)
7595 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7596 DAG.getNode(ISD::FNEG, SL, VT,
7597 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7598 N10.getOperand(0))),
7599 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7600 N10.getOperand(1)),
7601 N0);
7602 }
7603
7604 // fold (fsub (fpext (fneg (fmul, x, y))), z)
7605 // -> (fneg (fma (fpext x), (fpext y), z))
7606 // Note: This could be removed with appropriate canonicalization of the
7607 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7608 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7609 // from implementing the canonicalization in visitFSUB.
7610 if (N0.getOpcode() == ISD::FP_EXTEND) {
7611 SDValue N00 = N0.getOperand(0);
7612 if (N00.getOpcode() == ISD::FNEG) {
7613 SDValue N000 = N00.getOperand(0);
7614 if (N000.getOpcode() == ISD::FMUL) {
7615 return DAG.getNode(ISD::FNEG, SL, VT,
7616 DAG.getNode(PreferredFusedOpcode, SL, VT,
7617 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7618 N000.getOperand(0)),
7619 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7620 N000.getOperand(1)),
7621 N1));
7622 }
7623 }
7624 }
7625
7626 // fold (fsub (fneg (fpext (fmul, x, y))), z)
7627 // -> (fneg (fma (fpext x)), (fpext y), z)
7628 // Note: This could be removed with appropriate canonicalization of the
7629 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7630 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7631 // from implementing the canonicalization in visitFSUB.
7632 if (N0.getOpcode() == ISD::FNEG) {
7633 SDValue N00 = N0.getOperand(0);
7634 if (N00.getOpcode() == ISD::FP_EXTEND) {
7635 SDValue N000 = N00.getOperand(0);
7636 if (N000.getOpcode() == ISD::FMUL) {
7637 return DAG.getNode(ISD::FNEG, SL, VT,
7638 DAG.getNode(PreferredFusedOpcode, SL, VT,
7639 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7640 N000.getOperand(0)),
7641 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7642 N000.getOperand(1)),
7643 N1));
7644 }
7645 }
7646 }
7647
7648 }
7649
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007650 // More folding opportunities when target permits.
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007651 if ((UnsafeFPMath || HasFMAD) && Aggressive) {
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007652 // fold (fsub (fma x, y, (fmul u, v)), z)
7653 // -> (fma x, y (fma u, v, (fneg z)))
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007654 if (N0.getOpcode() == PreferredFusedOpcode &&
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007655 N0.getOperand(2).getOpcode() == ISD::FMUL) {
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007656 return DAG.getNode(PreferredFusedOpcode, SL, VT,
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007657 N0.getOperand(0), N0.getOperand(1),
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007658 DAG.getNode(PreferredFusedOpcode, SL, VT,
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007659 N0.getOperand(2).getOperand(0),
7660 N0.getOperand(2).getOperand(1),
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007661 DAG.getNode(ISD::FNEG, SL, VT,
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007662 N1)));
7663 }
7664
7665 // fold (fsub x, (fma y, z, (fmul u, v)))
7666 // -> (fma (fneg y), z, (fma (fneg u), v, x))
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007667 if (N1.getOpcode() == PreferredFusedOpcode &&
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007668 N1.getOperand(2).getOpcode() == ISD::FMUL) {
7669 SDValue N20 = N1.getOperand(2).getOperand(0);
7670 SDValue N21 = N1.getOperand(2).getOperand(1);
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007671 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7672 DAG.getNode(ISD::FNEG, SL, VT,
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007673 N1.getOperand(0)),
7674 N1.getOperand(1),
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007675 DAG.getNode(PreferredFusedOpcode, SL, VT,
7676 DAG.getNode(ISD::FNEG, SL, VT, N20),
7677
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007678 N21, N0));
7679 }
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007680
Olivier Sallenavec587bee2015-04-22 14:07:26 +00007681 if (UnsafeFPMath && LookThroughFPExt) {
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007682 // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
7683 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
7684 if (N0.getOpcode() == PreferredFusedOpcode) {
7685 SDValue N02 = N0.getOperand(2);
7686 if (N02.getOpcode() == ISD::FP_EXTEND) {
7687 SDValue N020 = N02.getOperand(0);
7688 if (N020.getOpcode() == ISD::FMUL)
7689 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7690 N0.getOperand(0), N0.getOperand(1),
7691 DAG.getNode(PreferredFusedOpcode, SL, VT,
7692 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7693 N020.getOperand(0)),
7694 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7695 N020.getOperand(1)),
7696 DAG.getNode(ISD::FNEG, SL, VT,
7697 N1)));
7698 }
7699 }
7700
7701 // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
7702 // -> (fma (fpext x), (fpext y),
7703 // (fma (fpext u), (fpext v), (fneg z)))
7704 // FIXME: This turns two single-precision and one double-precision
7705 // operation into two double-precision operations, which might not be
7706 // interesting for all targets, especially GPUs.
7707 if (N0.getOpcode() == ISD::FP_EXTEND) {
7708 SDValue N00 = N0.getOperand(0);
7709 if (N00.getOpcode() == PreferredFusedOpcode) {
7710 SDValue N002 = N00.getOperand(2);
7711 if (N002.getOpcode() == ISD::FMUL)
7712 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7713 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7714 N00.getOperand(0)),
7715 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7716 N00.getOperand(1)),
7717 DAG.getNode(PreferredFusedOpcode, SL, VT,
7718 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7719 N002.getOperand(0)),
7720 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7721 N002.getOperand(1)),
7722 DAG.getNode(ISD::FNEG, SL, VT,
7723 N1)));
7724 }
7725 }
7726
7727 // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
7728 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
7729 if (N1.getOpcode() == PreferredFusedOpcode &&
7730 N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
7731 SDValue N120 = N1.getOperand(2).getOperand(0);
7732 if (N120.getOpcode() == ISD::FMUL) {
7733 SDValue N1200 = N120.getOperand(0);
7734 SDValue N1201 = N120.getOperand(1);
7735 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7736 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
7737 N1.getOperand(1),
7738 DAG.getNode(PreferredFusedOpcode, SL, VT,
7739 DAG.getNode(ISD::FNEG, SL, VT,
7740 DAG.getNode(ISD::FP_EXTEND, SL,
7741 VT, N1200)),
7742 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7743 N1201),
7744 N0));
7745 }
7746 }
7747
7748 // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
7749 // -> (fma (fneg (fpext y)), (fpext z),
7750 // (fma (fneg (fpext u)), (fpext v), x))
7751 // FIXME: This turns two single-precision and one double-precision
7752 // operation into two double-precision operations, which might not be
7753 // interesting for all targets, especially GPUs.
7754 if (N1.getOpcode() == ISD::FP_EXTEND &&
7755 N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
7756 SDValue N100 = N1.getOperand(0).getOperand(0);
7757 SDValue N101 = N1.getOperand(0).getOperand(1);
7758 SDValue N102 = N1.getOperand(0).getOperand(2);
7759 if (N102.getOpcode() == ISD::FMUL) {
7760 SDValue N1020 = N102.getOperand(0);
7761 SDValue N1021 = N102.getOperand(1);
7762 return DAG.getNode(PreferredFusedOpcode, SL, VT,
7763 DAG.getNode(ISD::FNEG, SL, VT,
7764 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7765 N100)),
7766 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
7767 DAG.getNode(PreferredFusedOpcode, SL, VT,
7768 DAG.getNode(ISD::FNEG, SL, VT,
7769 DAG.getNode(ISD::FP_EXTEND, SL,
7770 VT, N1020)),
7771 DAG.getNode(ISD::FP_EXTEND, SL, VT,
7772 N1021),
7773 N0));
7774 }
7775 }
7776 }
Matt Arsenault0dc54c42015-02-20 22:10:33 +00007777 }
7778
7779 return SDValue();
7780}
7781
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007782SDValue DAGCombiner::visitFADD(SDNode *N) {
7783 SDValue N0 = N->getOperand(0);
7784 SDValue N1 = N->getOperand(1);
Nate Begeman418c6e42005-10-18 00:28:13 +00007785 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7786 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007787 EVT VT = N->getValueType(0);
Sanjay Patelcaf51802015-04-29 21:01:41 +00007788 SDLoc DL(N);
Sanjay Patel78614bf2014-08-28 15:53:16 +00007789 const TargetOptions &Options = DAG.getTarget().Options;
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007790
Dan Gohmana8665142007-06-25 16:23:39 +00007791 // fold vector ops
Simon Pilgrimdcbe1212015-03-29 19:13:40 +00007792 if (VT.isVector())
7793 if (SDValue FoldedVOp = SimplifyVBinOp(N))
7794 return FoldedVOp;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007795
Lang Hamesa33db652012-06-14 20:37:15 +00007796 // fold (fadd c1, c2) -> c1 + c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007797 if (N0CFP && N1CFP)
Sanjay Patelcaf51802015-04-29 21:01:41 +00007798 return DAG.getNode(ISD::FADD, DL, VT, N0, N1);
Sanjay Patel8170dea2014-09-08 17:32:19 +00007799
Nate Begeman418c6e42005-10-18 00:28:13 +00007800 // canonicalize constant to RHS
7801 if (N0CFP && !N1CFP)
Sanjay Patelcaf51802015-04-29 21:01:41 +00007802 return DAG.getNode(ISD::FADD, DL, VT, N1, N0);
Sanjay Patel8170dea2014-09-08 17:32:19 +00007803
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00007804 // fold (fadd A, (fneg B)) -> (fsub A, B)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00007805 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
Sanjay Patel8170dea2014-09-08 17:32:19 +00007806 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
Sanjay Patelcaf51802015-04-29 21:01:41 +00007807 return DAG.getNode(ISD::FSUB, DL, VT, N0,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007808 GetNegatedExpression(N1, DAG, LegalOperations));
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007809
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00007810 // fold (fadd (fneg A), B) -> (fsub B, A)
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00007811 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
Sanjay Patel8170dea2014-09-08 17:32:19 +00007812 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
Sanjay Patelcaf51802015-04-29 21:01:41 +00007813 return DAG.getNode(ISD::FSUB, DL, VT, N1,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007814 GetNegatedExpression(N0, DAG, LegalOperations));
Scott Michelcf0da6c2009-02-17 22:15:04 +00007815
Sanjay Patel8170dea2014-09-08 17:32:19 +00007816 // If 'unsafe math' is enabled, fold lots of things.
7817 if (Options.UnsafeFPMath) {
7818 // No FP constant should be created after legalization as Instruction
7819 // Selection pass has a hard time dealing with FP constants.
7820 bool AllowNewConst = (Level < AfterLegalizeDAG);
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007821
Sanjay Patel8170dea2014-09-08 17:32:19 +00007822 // fold (fadd A, 0) -> A
7823 if (N1CFP && N1CFP->getValueAPF().isZero())
7824 return N0;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007825
Sanjay Patel8170dea2014-09-08 17:32:19 +00007826 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
7827 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
7828 isa<ConstantFPSDNode>(N0.getOperand(1)))
Sanjay Patelcaf51802015-04-29 21:01:41 +00007829 return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
7830 DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1));
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007831
Sanjay Patel8170dea2014-09-08 17:32:19 +00007832 // If allowed, fold (fadd (fneg x), x) -> 0.0
7833 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
Sanjay Patelcaf51802015-04-29 21:01:41 +00007834 return DAG.getConstantFP(0.0, DL, VT);
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007835
Sanjay Patel8170dea2014-09-08 17:32:19 +00007836 // If allowed, fold (fadd x, (fneg x)) -> 0.0
7837 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
Sanjay Patelcaf51802015-04-29 21:01:41 +00007838 return DAG.getConstantFP(0.0, DL, VT);
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007839
Sanjay Patel8170dea2014-09-08 17:32:19 +00007840 // We can fold chains of FADD's of the same value into multiplications.
7841 // This transform is not safe in general because we are reducing the number
7842 // of rounding steps.
Sanjay Patel8170dea2014-09-08 17:32:19 +00007843 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
7844 if (N0.getOpcode() == ISD::FMUL) {
7845 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7846 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007847
Sanjay Patel8170dea2014-09-08 17:32:19 +00007848 // (fadd (fmul x, c), x) -> (fmul x, c+1)
7849 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
Sanjay Patelcaf51802015-04-29 21:01:41 +00007850 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007851 DAG.getConstantFP(1.0, DL, VT));
7852 return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP);
Sanjay Patel8170dea2014-09-08 17:32:19 +00007853 }
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007854
Sanjay Patel8170dea2014-09-08 17:32:19 +00007855 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
7856 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
7857 N1.getOperand(0) == N1.getOperand(1) &&
7858 N0.getOperand(0) == N1.getOperand(0)) {
Sanjay Patelcaf51802015-04-29 21:01:41 +00007859 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007860 DAG.getConstantFP(2.0, DL, VT));
Sanjay Patelcaf51802015-04-29 21:01:41 +00007861 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP);
Sanjay Patel8170dea2014-09-08 17:32:19 +00007862 }
Owen Andersoncc61f872012-08-30 23:35:16 +00007863 }
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007864
Sanjay Patel8170dea2014-09-08 17:32:19 +00007865 if (N1.getOpcode() == ISD::FMUL) {
7866 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7867 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007868
Sanjay Patel8170dea2014-09-08 17:32:19 +00007869 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
7870 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
Sanjay Patelcaf51802015-04-29 21:01:41 +00007871 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007872 DAG.getConstantFP(1.0, DL, VT));
7873 return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP);
Sanjay Patel8170dea2014-09-08 17:32:19 +00007874 }
Sanjay Patelf4b7a6b2014-09-08 18:22:51 +00007875
Sanjay Patel8170dea2014-09-08 17:32:19 +00007876 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
7877 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
7878 N0.getOperand(0) == N0.getOperand(1) &&
7879 N1.getOperand(0) == N0.getOperand(0)) {
Sanjay Patelcaf51802015-04-29 21:01:41 +00007880 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007881 DAG.getConstantFP(2.0, DL, VT));
7882 return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP);
Sanjay Patel8170dea2014-09-08 17:32:19 +00007883 }
Owen Andersoncc61f872012-08-30 23:35:16 +00007884 }
Sanjay Patelf4b7a6b2014-09-08 18:22:51 +00007885
Sanjay Patel8170dea2014-09-08 17:32:19 +00007886 if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
7887 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7888 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
7889 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007890 (N0.getOperand(0) == N1)) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007891 return DAG.getNode(ISD::FMUL, DL, VT,
7892 N1, DAG.getConstantFP(3.0, DL, VT));
7893 }
Owen Andersoncc61f872012-08-30 23:35:16 +00007894 }
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007895
Sanjay Patel8170dea2014-09-08 17:32:19 +00007896 if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
7897 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7898 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
7899 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007900 N1.getOperand(0) == N0) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007901 return DAG.getNode(ISD::FMUL, DL, VT,
7902 N0, DAG.getConstantFP(3.0, DL, VT));
7903 }
Owen Andersoncc61f872012-08-30 23:35:16 +00007904 }
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007905
Sanjay Patel8170dea2014-09-08 17:32:19 +00007906 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
7907 if (AllowNewConst &&
7908 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
Stephen Line31f2d22013-06-14 18:17:35 +00007909 N0.getOperand(0) == N0.getOperand(1) &&
Sanjay Patel8170dea2014-09-08 17:32:19 +00007910 N1.getOperand(0) == N1.getOperand(1) &&
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007911 N0.getOperand(0) == N1.getOperand(0)) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007912 return DAG.getNode(ISD::FMUL, DL, VT,
7913 N0.getOperand(0), DAG.getConstantFP(4.0, DL, VT));
7914 }
Owen Andersoncc61f872012-08-30 23:35:16 +00007915 }
Sanjay Patel8170dea2014-09-08 17:32:19 +00007916 } // enable-unsafe-fp-math
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00007917
Lang Hames39fb1d02012-06-19 22:51:23 +00007918 // FADD -> FMA combines:
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007919 SDValue Fused = visitFADDForFMACombine(N);
7920 if (Fused) {
7921 AddToWorklist(Fused.getNode());
7922 return Fused;
Olivier Sallenave04515322015-01-07 20:54:17 +00007923 }
7924
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007925 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00007926}
7927
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007928SDValue DAGCombiner::visitFSUB(SDNode *N) {
7929 SDValue N0 = N->getOperand(0);
7930 SDValue N1 = N->getOperand(1);
Sanjay Patel75cc90e2014-09-05 22:26:22 +00007931 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7932 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007933 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00007934 SDLoc dl(N);
Sanjay Patel78614bf2014-08-28 15:53:16 +00007935 const TargetOptions &Options = DAG.getTarget().Options;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007936
Dan Gohmana8665142007-06-25 16:23:39 +00007937 // fold vector ops
Simon Pilgrimdcbe1212015-03-29 19:13:40 +00007938 if (VT.isVector())
7939 if (SDValue FoldedVOp = SimplifyVBinOp(N))
7940 return FoldedVOp;
Scott Michelcf0da6c2009-02-17 22:15:04 +00007941
Nate Begeman418c6e42005-10-18 00:28:13 +00007942 // fold (fsub c1, c2) -> c1-c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00007943 if (N0CFP && N1CFP)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007944 return DAG.getNode(ISD::FSUB, dl, VT, N0, N1);
Sanjay Patelae402a32014-08-27 20:57:52 +00007945
Bill Wendlingcb9be5d2009-01-30 22:53:48 +00007946 // fold (fsub A, (fneg B)) -> (fadd A, B)
Sanjay Patel78614bf2014-08-28 15:53:16 +00007947 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
Elena Demikhovsky3cb3b002012-08-01 12:06:00 +00007948 return DAG.getNode(ISD::FADD, dl, VT, N0,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00007949 GetNegatedExpression(N1, DAG, LegalOperations));
Scott Michelcf0da6c2009-02-17 22:15:04 +00007950
Sanjay Patelae402a32014-08-27 20:57:52 +00007951 // If 'unsafe math' is enabled, fold lots of things.
Sanjay Patel78614bf2014-08-28 15:53:16 +00007952 if (Options.UnsafeFPMath) {
Sanjay Patelae402a32014-08-27 20:57:52 +00007953 // (fsub A, 0) -> A
7954 if (N1CFP && N1CFP->getValueAPF().isZero())
7955 return N0;
7956
7957 // (fsub 0, B) -> -B
7958 if (N0CFP && N0CFP->getValueAPF().isZero()) {
Sanjay Patel78614bf2014-08-28 15:53:16 +00007959 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
Sanjay Patelae402a32014-08-27 20:57:52 +00007960 return GetNegatedExpression(N1, DAG, LegalOperations);
7961 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7962 return DAG.getNode(ISD::FNEG, dl, VT, N1);
7963 }
7964
7965 // (fsub x, x) -> 0.0
Owen Andersonab63d842012-05-07 20:51:25 +00007966 if (N0 == N1)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007967 return DAG.getConstantFP(0.0f, dl, VT);
Owen Andersonab63d842012-05-07 20:51:25 +00007968
Sanjay Patelae402a32014-08-27 20:57:52 +00007969 // (fsub x, (fadd x, y)) -> (fneg y)
7970 // (fsub x, (fadd y, x)) -> (fneg y)
Bill Wendlingdf170db2012-03-15 05:12:00 +00007971 if (N1.getOpcode() == ISD::FADD) {
7972 SDValue N10 = N1->getOperand(0);
7973 SDValue N11 = N1->getOperand(1);
7974
Sanjay Patel78614bf2014-08-28 15:53:16 +00007975 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
Bill Wendlingdf170db2012-03-15 05:12:00 +00007976 return GetNegatedExpression(N11, DAG, LegalOperations);
Stephen Lin10947502013-07-10 20:47:39 +00007977
Sanjay Patel78614bf2014-08-28 15:53:16 +00007978 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
Bill Wendlingdf170db2012-03-15 05:12:00 +00007979 return GetNegatedExpression(N10, DAG, LegalOperations);
7980 }
7981 }
7982
Lang Hames39fb1d02012-06-19 22:51:23 +00007983 // FSUB -> FMA combines:
Olivier Sallenaveb99c2eb2015-04-20 20:29:40 +00007984 SDValue Fused = visitFSUBForFMACombine(N);
7985 if (Fused) {
7986 AddToWorklist(Fused.getNode());
7987 return Fused;
Lang Hames39fb1d02012-06-19 22:51:23 +00007988 }
7989
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007990 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00007991}
7992
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00007993SDValue DAGCombiner::visitFMUL(SDNode *N) {
7994 SDValue N0 = N->getOperand(0);
7995 SDValue N1 = N->getOperand(1);
Matt Arsenault6cc00422014-08-16 10:14:19 +00007996 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7997 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00007998 EVT VT = N->getValueType(0);
Sanjay Patelcaf51802015-04-29 21:01:41 +00007999 SDLoc DL(N);
Sanjay Patel78614bf2014-08-28 15:53:16 +00008000 const TargetOptions &Options = DAG.getTarget().Options;
Chris Lattner6f3b5772005-09-28 22:28:18 +00008001
Dan Gohmana8665142007-06-25 16:23:39 +00008002 // fold vector ops
Duncan Sands13237ac2008-06-06 12:08:01 +00008003 if (VT.isVector()) {
Sanjay Patel7bd228a2014-09-11 15:45:27 +00008004 // This just handles C1 * C2 for vectors. Other vector folds are below.
Simon Pilgrimdcbe1212015-03-29 19:13:40 +00008005 if (SDValue FoldedVOp = SimplifyVBinOp(N))
Sanjay Patel7bd228a2014-09-11 15:45:27 +00008006 return FoldedVOp;
Dan Gohman80f9f072007-07-13 20:03:40 +00008007 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00008008
Nate Begemanec48a1b2005-10-17 20:40:11 +00008009 // fold (fmul c1, c2) -> c1*c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00008010 if (N0CFP && N1CFP)
Sanjay Patelcaf51802015-04-29 21:01:41 +00008011 return DAG.getNode(ISD::FMUL, DL, VT, N0, N1);
Sanjay Patel394c3332014-09-08 20:16:42 +00008012
Nate Begemanec48a1b2005-10-17 20:40:11 +00008013 // canonicalize constant to RHS
Simon Pilgrimbcf3bc22015-04-05 14:30:37 +00008014 if (isConstantFPBuildVectorOrConstantFP(N0) &&
8015 !isConstantFPBuildVectorOrConstantFP(N1))
Sanjay Patelcaf51802015-04-29 21:01:41 +00008016 return DAG.getNode(ISD::FMUL, DL, VT, N1, N0);
Sanjay Patel394c3332014-09-08 20:16:42 +00008017
Owen Andersonb5f167c2012-05-02 21:32:35 +00008018 // fold (fmul A, 1.0) -> A
8019 if (N1CFP && N1CFP->isExactlyValue(1.0))
8020 return N0;
Matt Arsenault6cc00422014-08-16 10:14:19 +00008021
Sanjay Patel394c3332014-09-08 20:16:42 +00008022 if (Options.UnsafeFPMath) {
8023 // fold (fmul A, 0) -> 0
8024 if (N1CFP && N1CFP->getValueAPF().isZero())
8025 return N1;
8026
8027 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
Sanjay Patel7bd228a2014-09-11 15:45:27 +00008028 if (N0.getOpcode() == ISD::FMUL) {
8029 // Fold scalars or any vector constants (not just splats).
8030 // This fold is done in general by InstCombine, but extra fmul insts
8031 // may have been generated during lowering.
Sanjay Patelb8c907e2015-03-01 00:09:35 +00008032 SDValue N00 = N0.getOperand(0);
Sanjay Patel7bd228a2014-09-11 15:45:27 +00008033 SDValue N01 = N0.getOperand(1);
8034 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
Sanjay Patelb8c907e2015-03-01 00:09:35 +00008035 auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
Sanjay Patel7bd228a2014-09-11 15:45:27 +00008036 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
Sanjay Patelb8c907e2015-03-01 00:09:35 +00008037
8038 // Check 1: Make sure that the first operand of the inner multiply is NOT
8039 // a constant. Otherwise, we may induce infinite looping.
8040 if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
8041 // Check 2: Make sure that the second operand of the inner multiply and
8042 // the second operand of the outer multiply are constants.
8043 if ((N1CFP && isConstOrConstSplatFP(N01)) ||
8044 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
Sanjay Patelcaf51802015-04-29 21:01:41 +00008045 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1);
8046 return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts);
Sanjay Patelb8c907e2015-03-01 00:09:35 +00008047 }
Sanjay Patel7bd228a2014-09-11 15:45:27 +00008048 }
Matt Arsenaultc1a71212014-09-02 19:02:53 +00008049 }
8050
Sanjay Patel394c3332014-09-08 20:16:42 +00008051 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
Matt Arsenaultc1a71212014-09-02 19:02:53 +00008052 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
8053 // during an early run of DAGCombiner can prevent folding with fmuls
8054 // inserted during lowering.
8055 if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
Sanjay Patelcaf51802015-04-29 21:01:41 +00008056 const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
8057 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1);
8058 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts);
Matt Arsenaultc1a71212014-09-02 19:02:53 +00008059 }
8060 }
8061
Nate Begemanec48a1b2005-10-17 20:40:11 +00008062 // fold (fmul X, 2.0) -> (fadd X, X)
8063 if (N1CFP && N1CFP->isExactlyValue(+2.0))
Sanjay Patelcaf51802015-04-29 21:01:41 +00008064 return DAG.getNode(ISD::FADD, DL, VT, N0, N0);
Sanjay Patel394c3332014-09-08 20:16:42 +00008065
Dan Gohmanb7170912009-08-10 16:50:32 +00008066 // fold (fmul X, -1.0) -> (fneg X)
Chris Lattnere49c9742007-05-14 22:04:50 +00008067 if (N1CFP && N1CFP->isExactlyValue(-1.0))
Dan Gohman1f3411d2009-01-22 21:58:43 +00008068 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Sanjay Patelcaf51802015-04-29 21:01:41 +00008069 return DAG.getNode(ISD::FNEG, DL, VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008070
Bill Wendling3dc5d242009-01-30 22:57:07 +00008071 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
Sanjay Patel78614bf2014-08-28 15:53:16 +00008072 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8073 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
Chris Lattnere49c9742007-05-14 22:04:50 +00008074 // Both can be negated for free, check to see if at least one is cheaper
8075 // negated.
8076 if (LHSNeg == 2 || RHSNeg == 2)
Sanjay Patelcaf51802015-04-29 21:01:41 +00008077 return DAG.getNode(ISD::FMUL, DL, VT,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00008078 GetNegatedExpression(N0, DAG, LegalOperations),
8079 GetNegatedExpression(N1, DAG, LegalOperations));
Chris Lattnere49c9742007-05-14 22:04:50 +00008080 }
8081 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00008082
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008083 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00008084}
8085
Owen Anderson41b06652012-05-02 22:17:40 +00008086SDValue DAGCombiner::visitFMA(SDNode *N) {
8087 SDValue N0 = N->getOperand(0);
8088 SDValue N1 = N->getOperand(1);
8089 SDValue N2 = N->getOperand(2);
8090 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8091 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8092 EVT VT = N->getValueType(0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00008093 SDLoc dl(N);
Sanjay Patel78614bf2014-08-28 15:53:16 +00008094 const TargetOptions &Options = DAG.getTarget().Options;
Owen Anderson9d5a8c22014-08-02 08:45:33 +00008095
8096 // Constant fold FMA.
8097 if (isa<ConstantFPSDNode>(N0) &&
8098 isa<ConstantFPSDNode>(N1) &&
8099 isa<ConstantFPSDNode>(N2)) {
8100 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
8101 }
8102
Sanjay Patel78614bf2014-08-28 15:53:16 +00008103 if (Options.UnsafeFPMath) {
Owen Andersonb351c8d2012-11-01 02:00:53 +00008104 if (N0CFP && N0CFP->isZero())
8105 return N2;
8106 if (N1CFP && N1CFP->isZero())
8107 return N2;
8108 }
Owen Anderson41b06652012-05-02 22:17:40 +00008109 if (N0CFP && N0CFP->isExactlyValue(1.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00008110 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
Owen Anderson41b06652012-05-02 22:17:40 +00008111 if (N1CFP && N1CFP->isExactlyValue(1.0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00008112 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
Owen Anderson41b06652012-05-02 22:17:40 +00008113
Owen Andersonc7aaf522012-05-30 18:50:39 +00008114 // Canonicalize (fma c, x, y) -> (fma x, c, y)
Owen Anderson0eda3e12012-05-30 18:54:50 +00008115 if (N0CFP && !N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008116 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
Owen Andersonc7aaf522012-05-30 18:50:39 +00008117
Owen Anderson90e0eaf2012-09-01 06:04:27 +00008118 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
Sanjay Patel78614bf2014-08-28 15:53:16 +00008119 if (Options.UnsafeFPMath && N1CFP &&
Owen Anderson90e0eaf2012-09-01 06:04:27 +00008120 N2.getOpcode() == ISD::FMUL &&
8121 N0 == N2.getOperand(0) &&
8122 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
8123 return DAG.getNode(ISD::FMUL, dl, VT, N0,
8124 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
8125 }
8126
8127
8128 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
Sanjay Patel78614bf2014-08-28 15:53:16 +00008129 if (Options.UnsafeFPMath &&
Owen Anderson90e0eaf2012-09-01 06:04:27 +00008130 N0.getOpcode() == ISD::FMUL && N1CFP &&
8131 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
8132 return DAG.getNode(ISD::FMA, dl, VT,
8133 N0.getOperand(0),
8134 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
8135 N2);
8136 }
8137
8138 // (fma x, 1, y) -> (fadd x, y)
8139 // (fma x, -1, y) -> (fadd (fneg x), y)
8140 if (N1CFP) {
8141 if (N1CFP->isExactlyValue(1.0))
8142 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
8143
8144 if (N1CFP->isExactlyValue(-1.0) &&
8145 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8146 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008147 AddToWorklist(RHSNeg.getNode());
Owen Anderson90e0eaf2012-09-01 06:04:27 +00008148 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
8149 }
8150 }
8151
8152 // (fma x, c, x) -> (fmul x, (c+1))
Sanjay Patel78614bf2014-08-28 15:53:16 +00008153 if (Options.UnsafeFPMath && N1CFP && N0 == N2)
Stephen Lin8e8424e2013-07-09 00:44:49 +00008154 return DAG.getNode(ISD::FMUL, dl, VT, N0,
Owen Anderson90e0eaf2012-09-01 06:04:27 +00008155 DAG.getNode(ISD::FADD, dl, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008156 N1, DAG.getConstantFP(1.0, dl, VT)));
Owen Anderson90e0eaf2012-09-01 06:04:27 +00008157
8158 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
Sanjay Patel78614bf2014-08-28 15:53:16 +00008159 if (Options.UnsafeFPMath && N1CFP &&
Stephen Lin8e8424e2013-07-09 00:44:49 +00008160 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
8161 return DAG.getNode(ISD::FMUL, dl, VT, N0,
Owen Anderson90e0eaf2012-09-01 06:04:27 +00008162 DAG.getNode(ISD::FADD, dl, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008163 N1, DAG.getConstantFP(-1.0, dl, VT)));
Owen Anderson90e0eaf2012-09-01 06:04:27 +00008164
8165
Owen Anderson41b06652012-05-02 22:17:40 +00008166 return SDValue();
8167}
8168
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008169SDValue DAGCombiner::visitFDIV(SDNode *N) {
8170 SDValue N0 = N->getOperand(0);
8171 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00008172 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8173 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00008174 EVT VT = N->getValueType(0);
Sanjay Patelbdf1e382014-09-26 23:01:47 +00008175 SDLoc DL(N);
Sanjay Patel78614bf2014-08-28 15:53:16 +00008176 const TargetOptions &Options = DAG.getTarget().Options;
Chris Lattner6f3b5772005-09-28 22:28:18 +00008177
Dan Gohmana8665142007-06-25 16:23:39 +00008178 // fold vector ops
Simon Pilgrimdcbe1212015-03-29 19:13:40 +00008179 if (VT.isVector())
8180 if (SDValue FoldedVOp = SimplifyVBinOp(N))
8181 return FoldedVOp;
Scott Michelcf0da6c2009-02-17 22:15:04 +00008182
Nate Begeman569c4392006-01-18 22:35:16 +00008183 // fold (fdiv c1, c2) -> c1/c2
Ulrich Weigand3abb3432012-10-29 18:35:49 +00008184 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008185 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008186
Sanjay Patelb67bd262014-09-21 15:19:15 +00008187 if (Options.UnsafeFPMath) {
8188 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8189 if (N1CFP) {
8190 // Compute the reciprocal 1.0 / c2.
8191 APFloat N1APF = N1CFP->getValueAPF();
8192 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8193 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8194 // Only do the transform if the reciprocal is a legal fp immediate that
8195 // isn't too nasty (eg NaN, denormal, ...).
8196 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8197 (!LegalOperations ||
8198 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8199 // backend)... we should handle this gracefully after Legalize.
8200 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8201 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8202 TLI.isFPImmLegal(Recip, VT)))
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008203 return DAG.getNode(ISD::FMUL, DL, VT, N0,
8204 DAG.getConstantFP(Recip, DL, VT));
Sanjay Patelb67bd262014-09-21 15:19:15 +00008205 }
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00008206
Sanjay Patelb67bd262014-09-21 15:19:15 +00008207 // If this FDIV is part of a reciprocal square root, it may be folded
8208 // into a target-specific square root estimate instruction.
Sanjay Patelbdf1e382014-09-26 23:01:47 +00008209 if (N1.getOpcode() == ISD::FSQRT) {
8210 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
Sanjay Patelbdf1e382014-09-26 23:01:47 +00008211 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8212 }
8213 } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8214 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8215 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
Sanjay Patelbdf1e382014-09-26 23:01:47 +00008216 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8217 AddToWorklist(RV.getNode());
8218 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8219 }
8220 } else if (N1.getOpcode() == ISD::FP_ROUND &&
8221 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8222 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
Sanjay Patelbdf1e382014-09-26 23:01:47 +00008223 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
8224 AddToWorklist(RV.getNode());
8225 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8226 }
Sanjay Patel7bc91852014-10-06 19:31:18 +00008227 } else if (N1.getOpcode() == ISD::FMUL) {
8228 // Look through an FMUL. Even though this won't remove the FDIV directly,
8229 // it's still worthwhile to get rid of the FSQRT if possible.
8230 SDValue SqrtOp;
8231 SDValue OtherOp;
8232 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8233 SqrtOp = N1.getOperand(0);
8234 OtherOp = N1.getOperand(1);
8235 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
8236 SqrtOp = N1.getOperand(1);
8237 OtherOp = N1.getOperand(0);
8238 }
8239 if (SqrtOp.getNode()) {
8240 // We found a FSQRT, so try to make this fold:
8241 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
8242 if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
Sanjay Patel7bc91852014-10-06 19:31:18 +00008243 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
8244 AddToWorklist(RV.getNode());
8245 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8246 }
8247 }
Sanjay Patelbdf1e382014-09-26 23:01:47 +00008248 }
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00008249
Sanjay Patelbdf1e382014-09-26 23:01:47 +00008250 // Fold into a reciprocal estimate and multiply instead of a real divide.
8251 if (SDValue RV = BuildReciprocalEstimate(N1)) {
8252 AddToWorklist(RV.getNode());
8253 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8254 }
Duncan Sands5f8397a2012-04-07 20:04:00 +00008255 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00008256
Bill Wendling3dc5d242009-01-30 22:57:07 +00008257 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
Sanjay Patel78614bf2014-08-28 15:53:16 +00008258 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8259 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
Chris Lattnere49c9742007-05-14 22:04:50 +00008260 // Both can be negated for free, check to see if at least one is cheaper
8261 // negated.
8262 if (LHSNeg == 2 || RHSNeg == 2)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008263 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
Duncan Sandsdc2dac12008-11-24 14:53:14 +00008264 GetNegatedExpression(N0, DAG, LegalOperations),
8265 GetNegatedExpression(N1, DAG, LegalOperations));
Chris Lattnere49c9742007-05-14 22:04:50 +00008266 }
8267 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00008268
Hao Liu44e5d7a2014-11-21 06:39:58 +00008269 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8270 // reciprocal.
8271 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8272 // Notice that this is not always beneficial. One reason is different target
8273 // may have different costs for FDIV and FMUL, so sometimes the cost of two
8274 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8275 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8276 if (Options.UnsafeFPMath) {
8277 // Skip if current node is a reciprocal.
8278 if (N0CFP && N0CFP->isExactlyValue(1.0))
8279 return SDValue();
8280
8281 SmallVector<SDNode *, 4> Users;
8282 // Find all FDIV users of the same divisor.
Sanjay Patel64a6da92015-05-19 18:24:33 +00008283 for (auto U : N1->uses()) {
8284 if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1)
8285 Users.push_back(U);
Hao Liu44e5d7a2014-11-21 06:39:58 +00008286 }
8287
8288 if (TLI.combineRepeatedFPDivisors(Users.size())) {
Sanjay Patelad114152015-05-19 19:10:57 +00008289 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008290 SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1);
Hao Liu44e5d7a2014-11-21 06:39:58 +00008291
8292 // Dividend / Divisor -> Dividend * Reciprocal
Sanjay Patel64a6da92015-05-19 18:24:33 +00008293 for (auto U : Users) {
Sanjay Patelad114152015-05-19 19:10:57 +00008294 SDValue Dividend = U->getOperand(0);
8295 if (Dividend != FPOne) {
8296 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
8297 Reciprocal);
Sanjay Patel3c9e3702015-05-19 17:49:14 +00008298 DAG.ReplaceAllUsesWith(U, NewNode.getNode());
Hao Liu44e5d7a2014-11-21 06:39:58 +00008299 }
8300 }
8301 return SDValue();
8302 }
8303 }
8304
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008305 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00008306}
8307
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008308SDValue DAGCombiner::visitFREM(SDNode *N) {
8309 SDValue N0 = N->getOperand(0);
8310 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00008311 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8312 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00008313 EVT VT = N->getValueType(0);
Chris Lattner6f3b5772005-09-28 22:28:18 +00008314
Nate Begeman569c4392006-01-18 22:35:16 +00008315 // fold (frem c1, c2) -> fmod(c1,c2)
Ulrich Weigand3abb3432012-10-29 18:35:49 +00008316 if (N0CFP && N1CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008317 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
Dan Gohmana8665142007-06-25 16:23:39 +00008318
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008319 return SDValue();
Chris Lattner6f3b5772005-09-28 22:28:18 +00008320}
8321
Sanjay Patelbdf1e382014-09-26 23:01:47 +00008322SDValue DAGCombiner::visitFSQRT(SDNode *N) {
Matt Arsenaultbf0db912015-01-13 20:53:23 +00008323 if (DAG.getTarget().Options.UnsafeFPMath &&
8324 !TLI.isFsqrtCheap()) {
Sanjay Patel3d497cd2014-10-09 21:26:35 +00008325 // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
Sanjay Patelbdf1e382014-09-26 23:01:47 +00008326 if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
Sanjay Patel3d497cd2014-10-09 21:26:35 +00008327 EVT VT = RV.getValueType();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008328 SDLoc DL(N);
8329 RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV);
Sanjay Patel3d497cd2014-10-09 21:26:35 +00008330 AddToWorklist(RV.getNode());
Sanjay Patelbdf1e382014-09-26 23:01:47 +00008331
Sanjay Patel3d497cd2014-10-09 21:26:35 +00008332 // Unfortunately, RV is now NaN if the input was exactly 0.
8333 // Select out this case and force the answer to 0.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008334 SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
Sanjay Patel3d497cd2014-10-09 21:26:35 +00008335 SDValue ZeroCmp =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008336 DAG.getSetCC(DL, TLI.getSetCCResultType(*DAG.getContext(), VT),
Sanjay Patel3d497cd2014-10-09 21:26:35 +00008337 N->getOperand(0), Zero, ISD::SETEQ);
8338 AddToWorklist(ZeroCmp.getNode());
8339 AddToWorklist(RV.getNode());
8340
8341 RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008342 DL, VT, ZeroCmp, Zero, RV);
Sanjay Patel3d497cd2014-10-09 21:26:35 +00008343 return RV;
Sanjay Patelbdf1e382014-09-26 23:01:47 +00008344 }
8345 }
8346 return SDValue();
8347}
8348
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008349SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
8350 SDValue N0 = N->getOperand(0);
8351 SDValue N1 = N->getOperand(1);
Chris Lattner3bc40502006-03-05 05:30:57 +00008352 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8353 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
Owen Anderson53aa7a92009-08-10 22:56:29 +00008354 EVT VT = N->getValueType(0);
Chris Lattner3bc40502006-03-05 05:30:57 +00008355
Ulrich Weigand3abb3432012-10-29 18:35:49 +00008356 if (N0CFP && N1CFP) // Constant fold
Andrew Trickef9de2a2013-05-25 02:42:55 +00008357 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008358
Chris Lattner3bc40502006-03-05 05:30:57 +00008359 if (N1CFP) {
Dale Johannesenb6d2bec2007-08-26 01:18:27 +00008360 const APFloat& V = N1CFP->getValueAPF();
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00008361 // copysign(x, c1) -> fabs(x) iff ispos(c1)
8362 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
Dan Gohman1f3411d2009-01-22 21:58:43 +00008363 if (!V.isNegative()) {
8364 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00008365 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Dan Gohman1f3411d2009-01-22 21:58:43 +00008366 } else {
8367 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
Andrew Trickef9de2a2013-05-25 02:42:55 +00008368 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8369 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
Dan Gohman1f3411d2009-01-22 21:58:43 +00008370 }
Chris Lattner3bc40502006-03-05 05:30:57 +00008371 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00008372
Chris Lattner3bc40502006-03-05 05:30:57 +00008373 // copysign(fabs(x), y) -> copysign(x, y)
8374 // copysign(fneg(x), y) -> copysign(x, y)
8375 // copysign(copysign(x,z), y) -> copysign(x, y)
8376 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
8377 N0.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008378 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00008379 N0.getOperand(0), N1);
Chris Lattner3bc40502006-03-05 05:30:57 +00008380
8381 // copysign(x, abs(y)) -> abs(x)
8382 if (N1.getOpcode() == ISD::FABS)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008383 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008384
Chris Lattner3bc40502006-03-05 05:30:57 +00008385 // copysign(x, copysign(y,z)) -> copysign(x, z)
8386 if (N1.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008387 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00008388 N0, N1.getOperand(1));
Scott Michelcf0da6c2009-02-17 22:15:04 +00008389
Chris Lattner3bc40502006-03-05 05:30:57 +00008390 // copysign(x, fp_extend(y)) -> copysign(x, y)
8391 // copysign(x, fp_round(y)) -> copysign(x, y)
8392 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008393 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00008394 N0, N1.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00008395
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008396 return SDValue();
Chris Lattner3bc40502006-03-05 05:30:57 +00008397}
8398
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008399SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
8400 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00008401 EVT VT = N->getValueType(0);
8402 EVT OpVT = N0.getValueType();
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00008403
Nate Begeman21158fc2005-09-01 00:19:25 +00008404 // fold (sint_to_fp c1) -> c1fp
Simon Pilgrim09f3ff92015-03-25 22:30:31 +00008405 if (isConstantIntBuildVectorOrConstantInt(N0) &&
Stuart Hastings6b4007d2011-03-02 19:36:30 +00008406 // ...but only if the target supports immediate floating-point values
Eli Friedman9d448e42011-11-12 00:35:34 +00008407 (!LegalOperations ||
Evan Cheng4c0bd962011-06-21 06:01:08 +00008408 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00008409 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008410
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00008411 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
8412 // but UINT_TO_FP is legal on this target, try to convert.
Dan Gohman4aa18462009-01-28 17:46:25 +00008413 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
8414 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
Scott Michelcf0da6c2009-02-17 22:15:04 +00008415 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00008416 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00008417 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00008418 }
Bill Wendling0bd29742009-01-30 23:15:49 +00008419
Alp Tokercb402912014-01-24 17:20:08 +00008420 // The next optimizations are desirable only if SELECT_CC can be lowered.
Tom Stellard3787b122014-06-10 16:01:29 +00008421 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
Nadav Rotem90560762012-07-23 07:59:50 +00008422 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8423 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
8424 !VT.isVector() &&
8425 (!LegalOperations ||
8426 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008427 SDLoc DL(N);
Nadav Rotem90560762012-07-23 07:59:50 +00008428 SDValue Ops[] =
8429 { N0.getOperand(0), N0.getOperand(1),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008430 DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
Nadav Rotem90560762012-07-23 07:59:50 +00008431 N0.getOperand(2) };
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008432 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
Nadav Rotem90560762012-07-23 07:59:50 +00008433 }
Owen Andersond4b841f2012-07-09 20:31:12 +00008434
Nadav Rotem90560762012-07-23 07:59:50 +00008435 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
8436 // (select_cc x, y, 1.0, 0.0,, cc)
8437 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
8438 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
8439 (!LegalOperations ||
8440 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008441 SDLoc DL(N);
Nadav Rotem90560762012-07-23 07:59:50 +00008442 SDValue Ops[] =
8443 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008444 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
Nadav Rotem90560762012-07-23 07:59:50 +00008445 N0.getOperand(0).getOperand(2) };
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008446 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
Nadav Rotem90560762012-07-23 07:59:50 +00008447 }
Owen Andersond4b841f2012-07-09 20:31:12 +00008448 }
8449
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008450 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00008451}
8452
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008453SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
8454 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00008455 EVT VT = N->getValueType(0);
8456 EVT OpVT = N0.getValueType();
Nate Begeman569c4392006-01-18 22:35:16 +00008457
Nate Begeman21158fc2005-09-01 00:19:25 +00008458 // fold (uint_to_fp c1) -> c1fp
Simon Pilgrim09f3ff92015-03-25 22:30:31 +00008459 if (isConstantIntBuildVectorOrConstantInt(N0) &&
Stuart Hastings6b4007d2011-03-02 19:36:30 +00008460 // ...but only if the target supports immediate floating-point values
Eli Friedman9d448e42011-11-12 00:35:34 +00008461 (!LegalOperations ||
Evan Cheng4c0bd962011-06-21 06:01:08 +00008462 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +00008463 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008464
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00008465 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
8466 // but SINT_TO_FP is legal on this target, try to convert.
Dan Gohman4aa18462009-01-28 17:46:25 +00008467 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
8468 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
Scott Michelcf0da6c2009-02-17 22:15:04 +00008469 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00008470 if (DAG.SignBitIsZero(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00008471 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
Chris Lattnerb1e66ce2008-06-26 00:16:49 +00008472 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00008473
Alp Tokercb402912014-01-24 17:20:08 +00008474 // The next optimizations are desirable only if SELECT_CC can be lowered.
Tom Stellard3787b122014-06-10 16:01:29 +00008475 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
Nadav Rotem90560762012-07-23 07:59:50 +00008476 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
Owen Andersond4b841f2012-07-09 20:31:12 +00008477
Nadav Rotem90560762012-07-23 07:59:50 +00008478 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
8479 (!LegalOperations ||
8480 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008481 SDLoc DL(N);
Nadav Rotem90560762012-07-23 07:59:50 +00008482 SDValue Ops[] =
8483 { N0.getOperand(0), N0.getOperand(1),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008484 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
Nadav Rotem90560762012-07-23 07:59:50 +00008485 N0.getOperand(2) };
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008486 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
Nadav Rotem90560762012-07-23 07:59:50 +00008487 }
8488 }
Owen Andersond4b841f2012-07-09 20:31:12 +00008489
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008490 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00008491}
8492
Mehdi Amini3e0023b2015-02-16 21:47:58 +00008493// Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8494static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8495 SDValue N0 = N->getOperand(0);
8496 EVT VT = N->getValueType(0);
8497
8498 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8499 return SDValue();
8500
8501 SDValue Src = N0.getOperand(0);
8502 EVT SrcVT = Src.getValueType();
8503 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8504 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8505
8506 // We can safely assume the conversion won't overflow the output range,
8507 // because (for example) (uint8_t)18293.f is undefined behavior.
8508
8509 // Since we can assume the conversion won't overflow, our decision as to
8510 // whether the input will fit in the float should depend on the minimum
8511 // of the input range and output range.
8512
8513 // This means this is also safe for a signed input and unsigned output, since
8514 // a negative input would lead to undefined behavior.
8515 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8516 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8517 unsigned ActualSize = std::min(InputSize, OutputSize);
8518 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8519
8520 // We can only fold away the float conversion if the input range can be
8521 // represented exactly in the float range.
8522 if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8523 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8524 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8525 : ISD::ZERO_EXTEND;
8526 return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8527 }
8528 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8529 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8530 if (SrcVT == VT)
8531 return Src;
8532 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
8533 }
8534 return SDValue();
8535}
8536
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008537SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
8538 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00008539 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008540
Nate Begeman21158fc2005-09-01 00:19:25 +00008541 // fold (fp_to_sint c1fp) -> c1
Simon Pilgrim017ca192015-05-02 13:04:07 +00008542 if (isConstantFPBuildVectorOrConstantFP(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00008543 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
Bill Wendling0bd29742009-01-30 23:15:49 +00008544
Mehdi Amini3e0023b2015-02-16 21:47:58 +00008545 return FoldIntToFPToInt(N, DAG);
Nate Begeman21158fc2005-09-01 00:19:25 +00008546}
8547
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008548SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8549 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00008550 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008551
Nate Begeman21158fc2005-09-01 00:19:25 +00008552 // fold (fp_to_uint c1fp) -> c1
Simon Pilgrim017ca192015-05-02 13:04:07 +00008553 if (isConstantFPBuildVectorOrConstantFP(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00008554 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
Bill Wendling0bd29742009-01-30 23:15:49 +00008555
Mehdi Amini3e0023b2015-02-16 21:47:58 +00008556 return FoldIntToFPToInt(N, DAG);
Nate Begeman21158fc2005-09-01 00:19:25 +00008557}
8558
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008559SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8560 SDValue N0 = N->getOperand(0);
8561 SDValue N1 = N->getOperand(1);
Nate Begeman569c4392006-01-18 22:35:16 +00008562 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00008563 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008564
Nate Begeman21158fc2005-09-01 00:19:25 +00008565 // fold (fp_round c1fp) -> c1fp
Ulrich Weigand3abb3432012-10-29 18:35:49 +00008566 if (N0CFP)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008567 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008568
Chris Lattner8bb6cb72006-03-13 06:26:26 +00008569 // fold (fp_round (fp_extend x)) -> x
8570 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
8571 return N0.getOperand(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008572
Chris Lattner0feb1b02008-01-24 06:45:35 +00008573 // fold (fp_round (fp_round x)) -> (fp_round x)
8574 if (N0.getOpcode() == ISD::FP_ROUND) {
Ahmed Bougacha24433a72015-02-12 06:15:29 +00008575 const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
8576 const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
8577 // If the first fp_round isn't a value preserving truncation, it might
8578 // introduce a tie in the second fp_round, that wouldn't occur in the
8579 // single-step fp_round we want to fold to.
8580 // In other words, double rounding isn't the same as rounding.
8581 // Also, this is a value preserving truncation iff both fp_round's are.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008582 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
8583 SDLoc DL(N);
8584 return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
8585 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
8586 }
Chris Lattner0feb1b02008-01-24 06:45:35 +00008587 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00008588
Chris Lattner8bb6cb72006-03-13 06:26:26 +00008589 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
Gabor Greiff304a7a2008-08-28 21:40:38 +00008590 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00008591 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00008592 N0.getOperand(0), N1);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008593 AddToWorklist(Tmp.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00008594 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00008595 Tmp, N0.getOperand(1));
Chris Lattner8bb6cb72006-03-13 06:26:26 +00008596 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00008597
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008598 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00008599}
8600
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008601SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
8602 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00008603 EVT VT = N->getValueType(0);
8604 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
Nate Begeman7cea6ef2005-09-02 21:18:40 +00008605 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008606
Nate Begeman21158fc2005-09-01 00:19:25 +00008607 // fold (fp_round_inreg c1fp) -> c1fp
Chris Lattner4041ab62010-04-15 04:48:01 +00008608 if (N0CFP && isTypeLegal(EVT)) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008609 SDLoc DL(N);
8610 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
8611 return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
Nate Begeman21158fc2005-09-01 00:19:25 +00008612 }
Bill Wendling0bd29742009-01-30 23:15:49 +00008613
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008614 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00008615}
8616
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008617SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
8618 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00008619 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008620
Chris Lattner5919b482007-12-29 06:55:23 +00008621 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
Scott Michelcf0da6c2009-02-17 22:15:04 +00008622 if (N->hasOneUse() &&
Dan Gohman8e4ac9b2009-01-26 04:35:06 +00008623 N->use_begin()->getOpcode() == ISD::FP_ROUND)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008624 return SDValue();
Chris Lattner72733e52008-01-17 07:00:52 +00008625
Nate Begeman21158fc2005-09-01 00:19:25 +00008626 // fold (fp_extend c1fp) -> c1fp
Simon Pilgrim09f3ff92015-03-25 22:30:31 +00008627 if (isConstantFPBuildVectorOrConstantFP(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00008628 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
Chris Lattner72733e52008-01-17 07:00:52 +00008629
Pirama Arumuga Nainardb7c07e22015-04-17 18:36:25 +00008630 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
8631 if (N0.getOpcode() == ISD::FP16_TO_FP &&
8632 TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
8633 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
8634
Chris Lattner72733e52008-01-17 07:00:52 +00008635 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
8636 // value of X.
Gabor Greife12264b2008-08-30 19:29:20 +00008637 if (N0.getOpcode() == ISD::FP_ROUND
8638 && N0.getNode()->getConstantOperandVal(1) == 1) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008639 SDValue In = N0.getOperand(0);
Chris Lattner72733e52008-01-17 07:00:52 +00008640 if (In.getValueType() == VT) return In;
Duncan Sands11dd4242008-06-08 20:54:56 +00008641 if (VT.bitsLT(In.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +00008642 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00008643 In, N0.getOperand(1));
Andrew Trickef9de2a2013-05-25 02:42:55 +00008644 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
Chris Lattner72733e52008-01-17 07:00:52 +00008645 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00008646
Chris Lattner72733e52008-01-17 07:00:52 +00008647 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
Hal Finkeldbc7a8a2013-10-04 22:18:12 +00008648 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00008649 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00008650 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Andrew Trickef9de2a2013-05-25 02:42:55 +00008651 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
Bill Wendling0bd29742009-01-30 23:15:49 +00008652 LN0->getChain(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00008653 LN0->getBasePtr(), N0.getValueType(),
8654 LN0->getMemOperand());
Chris Lattner3d265772006-05-05 21:34:35 +00008655 CombineTo(N, ExtLoad);
Bill Wendling0bd29742009-01-30 23:15:49 +00008656 CombineTo(N0.getNode(),
Andrew Trickef9de2a2013-05-25 02:42:55 +00008657 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008658 N0.getValueType(), ExtLoad,
8659 DAG.getIntPtrConstant(1, SDLoc(N0))),
Chris Lattner3d265772006-05-05 21:34:35 +00008660 ExtLoad.getValue(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008661 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Chris Lattner3d265772006-05-05 21:34:35 +00008662 }
Duncan Sands8651e9c2008-06-13 19:07:40 +00008663
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008664 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00008665}
8666
Sanjay Patelccd26762014-08-28 21:51:37 +00008667SDValue DAGCombiner::visitFCEIL(SDNode *N) {
8668 SDValue N0 = N->getOperand(0);
Sanjay Patelccd26762014-08-28 21:51:37 +00008669 EVT VT = N->getValueType(0);
8670
8671 // fold (fceil c1) -> fceil(c1)
Simon Pilgrim07e063e2015-04-06 17:15:41 +00008672 if (isConstantFPBuildVectorOrConstantFP(N0))
Sanjay Patelccd26762014-08-28 21:51:37 +00008673 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
8674
8675 return SDValue();
8676}
8677
8678SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
8679 SDValue N0 = N->getOperand(0);
Sanjay Patelccd26762014-08-28 21:51:37 +00008680 EVT VT = N->getValueType(0);
8681
8682 // fold (ftrunc c1) -> ftrunc(c1)
Simon Pilgrim07e063e2015-04-06 17:15:41 +00008683 if (isConstantFPBuildVectorOrConstantFP(N0))
Sanjay Patelccd26762014-08-28 21:51:37 +00008684 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
8685
8686 return SDValue();
8687}
8688
8689SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
8690 SDValue N0 = N->getOperand(0);
Sanjay Patelccd26762014-08-28 21:51:37 +00008691 EVT VT = N->getValueType(0);
8692
8693 // fold (ffloor c1) -> ffloor(c1)
Simon Pilgrim07e063e2015-04-06 17:15:41 +00008694 if (isConstantFPBuildVectorOrConstantFP(N0))
Sanjay Patelccd26762014-08-28 21:51:37 +00008695 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
8696
8697 return SDValue();
8698}
8699
8700// FIXME: FNEG and FABS have a lot in common; refactor.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008701SDValue DAGCombiner::visitFNEG(SDNode *N) {
8702 SDValue N0 = N->getOperand(0);
Anton Korobeynikova6faf602009-10-20 21:37:45 +00008703 EVT VT = N->getValueType(0);
Nate Begeman569c4392006-01-18 22:35:16 +00008704
Sanjay Patelccd26762014-08-28 21:51:37 +00008705 // Constant fold FNEG.
Simon Pilgrim09f3ff92015-03-25 22:30:31 +00008706 if (isConstantFPBuildVectorOrConstantFP(N0))
8707 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
Sanjay Patelccd26762014-08-28 21:51:37 +00008708
Owen Anderson2ee7c4d2012-03-06 00:29:31 +00008709 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
8710 &DAG.getTarget().Options))
Duncan Sandsdc2dac12008-11-24 14:53:14 +00008711 return GetNegatedExpression(N0, DAG, LegalOperations);
Dan Gohman9a708232007-07-02 15:48:56 +00008712
Sanjay Patel35d31332014-08-14 15:15:28 +00008713 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
Chris Lattner888560d2008-01-27 17:42:27 +00008714 // constant pool values.
Sanjay Patelccd26762014-08-28 21:51:37 +00008715 if (!TLI.isFNegFree(VT) &&
8716 N0.getOpcode() == ISD::BITCAST &&
Sanjay Patel35d31332014-08-14 15:15:28 +00008717 N0.getNode()->hasOneUse()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008718 SDValue Int = N0.getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00008719 EVT IntVT = Int.getValueType();
Duncan Sands13237ac2008-06-06 12:08:01 +00008720 if (IntVT.isInteger() && !IntVT.isVector()) {
Sanjay Patel35d31332014-08-14 15:15:28 +00008721 APInt SignMask;
8722 if (N0.getValueType().isVector()) {
8723 // For a vector, get a mask such as 0x80... per scalar element
8724 // and splat it.
8725 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8726 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8727 } else {
8728 // For a scalar, just generate 0x80...
8729 SignMask = APInt::getSignBit(IntVT.getSizeInBits());
8730 }
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008731 SDLoc DL0(N0);
8732 Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
8733 DAG.getConstant(SignMask, DL0, IntVT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008734 AddToWorklist(Int.getNode());
Sanjay Patel35d31332014-08-14 15:15:28 +00008735 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
Chris Lattner888560d2008-01-27 17:42:27 +00008736 }
8737 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00008738
Owen Anderson90e0eaf2012-09-01 06:04:27 +00008739 // (fneg (fmul c, x)) -> (fmul -c, x)
8740 if (N0.getOpcode() == ISD::FMUL) {
8741 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
Tim Northover820e0412014-05-02 17:25:02 +00008742 if (CFP1) {
8743 APFloat CVal = CFP1->getValueAPF();
8744 CVal.changeSign();
8745 if (Level >= AfterLegalizeDAG &&
8746 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
8747 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
8748 return DAG.getNode(
8749 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
8750 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
8751 }
Owen Anderson90e0eaf2012-09-01 06:04:27 +00008752 }
8753
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008754 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00008755}
8756
Matt Arsenault7c936902014-10-21 23:01:01 +00008757SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
8758 SDValue N0 = N->getOperand(0);
8759 SDValue N1 = N->getOperand(1);
8760 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8761 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8762
8763 if (N0CFP && N1CFP) {
8764 const APFloat &C0 = N0CFP->getValueAPF();
8765 const APFloat &C1 = N1CFP->getValueAPF();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008766 return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), N->getValueType(0));
Matt Arsenault7c936902014-10-21 23:01:01 +00008767 }
8768
8769 if (N0CFP) {
8770 EVT VT = N->getValueType(0);
8771 // Canonicalize to constant on RHS.
8772 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
8773 }
8774
8775 return SDValue();
8776}
8777
8778SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
8779 SDValue N0 = N->getOperand(0);
8780 SDValue N1 = N->getOperand(1);
8781 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8782 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8783
8784 if (N0CFP && N1CFP) {
8785 const APFloat &C0 = N0CFP->getValueAPF();
8786 const APFloat &C1 = N1CFP->getValueAPF();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008787 return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), N->getValueType(0));
Matt Arsenault7c936902014-10-21 23:01:01 +00008788 }
8789
8790 if (N0CFP) {
8791 EVT VT = N->getValueType(0);
8792 // Canonicalize to constant on RHS.
8793 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
8794 }
8795
8796 return SDValue();
8797}
8798
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008799SDValue DAGCombiner::visitFABS(SDNode *N) {
8800 SDValue N0 = N->getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00008801 EVT VT = N->getValueType(0);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008802
Nate Begeman21158fc2005-09-01 00:19:25 +00008803 // fold (fabs c1) -> fabs(c1)
Simon Pilgrim09f3ff92015-03-25 22:30:31 +00008804 if (isConstantFPBuildVectorOrConstantFP(N0))
Andrew Trickef9de2a2013-05-25 02:42:55 +00008805 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00008806
Nate Begeman21158fc2005-09-01 00:19:25 +00008807 // fold (fabs (fabs x)) -> (fabs x)
Chris Lattner3bc40502006-03-05 05:30:57 +00008808 if (N0.getOpcode() == ISD::FABS)
Nate Begemand23739d2005-09-06 04:43:02 +00008809 return N->getOperand(0);
Sanjay Patelccd26762014-08-28 21:51:37 +00008810
Nate Begeman21158fc2005-09-01 00:19:25 +00008811 // fold (fabs (fneg x)) -> (fabs x)
Chris Lattner3bc40502006-03-05 05:30:57 +00008812 // fold (fabs (fcopysign x, y)) -> (fabs x)
8813 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
Andrew Trickef9de2a2013-05-25 02:42:55 +00008814 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
Scott Michelcf0da6c2009-02-17 22:15:04 +00008815
Sanjay Patel8e5beb62014-08-05 17:35:22 +00008816 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
Chris Lattner888560d2008-01-27 17:42:27 +00008817 // constant pool values.
Stephen Lincfe7f352013-07-08 00:37:03 +00008818 if (!TLI.isFAbsFree(VT) &&
Sanjay Patel8e5beb62014-08-05 17:35:22 +00008819 N0.getOpcode() == ISD::BITCAST &&
8820 N0.getNode()->hasOneUse()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008821 SDValue Int = N0.getOperand(0);
Owen Anderson53aa7a92009-08-10 22:56:29 +00008822 EVT IntVT = Int.getValueType();
Duncan Sands13237ac2008-06-06 12:08:01 +00008823 if (IntVT.isInteger() && !IntVT.isVector()) {
Sanjay Patel8e5beb62014-08-05 17:35:22 +00008824 APInt SignMask;
8825 if (N0.getValueType().isVector()) {
8826 // For a vector, get a mask such as 0x7f... per scalar element
8827 // and splat it.
8828 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8829 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8830 } else {
8831 // For a scalar, just generate 0x7f...
8832 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
8833 }
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008834 SDLoc DL(N0);
8835 Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
8836 DAG.getConstant(SignMask, DL, IntVT));
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008837 AddToWorklist(Int.getNode());
Sanjay Patel8e5beb62014-08-05 17:35:22 +00008838 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
Chris Lattner888560d2008-01-27 17:42:27 +00008839 }
8840 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00008841
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008842 return SDValue();
Nate Begeman21158fc2005-09-01 00:19:25 +00008843}
8844
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008845SDValue DAGCombiner::visitBRCOND(SDNode *N) {
8846 SDValue Chain = N->getOperand(0);
8847 SDValue N1 = N->getOperand(1);
8848 SDValue N2 = N->getOperand(2);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008849
Dan Gohman82e80012009-11-17 00:47:23 +00008850 // If N is a constant we could fold this into a fallthrough or unconditional
8851 // branch. However that doesn't happen very often in normal code, because
8852 // Instcombine/SimplifyCFG should have handled the available opportunities.
8853 // If we did this folding here, it would be necessary to update the
8854 // MachineBasicBlock CFG, which is awkward.
8855
Nate Begeman7e7f4392006-02-01 07:19:44 +00008856 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
8857 // on the target.
Scott Michelcf0da6c2009-02-17 22:15:04 +00008858 if (N1.getOpcode() == ISD::SETCC &&
Tom Stellardb1588fc2013-03-08 15:36:57 +00008859 TLI.isOperationLegalOrCustom(ISD::BR_CC,
8860 N1.getOperand(0).getValueType())) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00008861 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
Bill Wendling306bfc22009-01-30 23:27:35 +00008862 Chain, N1.getOperand(2),
Nate Begeman7e7f4392006-02-01 07:19:44 +00008863 N1.getOperand(0), N1.getOperand(1), N2);
8864 }
Bill Wendling306bfc22009-01-30 23:27:35 +00008865
Evan Chengc8d6cfd2010-10-04 22:41:01 +00008866 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
8867 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
8868 (N1.getOperand(0).hasOneUse() &&
8869 N1.getOperand(0).getOpcode() == ISD::SRL))) {
Craig Topperc0196b12014-04-14 00:51:57 +00008870 SDNode *Trunc = nullptr;
Evan Chengc8d6cfd2010-10-04 22:41:01 +00008871 if (N1.getOpcode() == ISD::TRUNCATE) {
8872 // Look pass the truncate.
8873 Trunc = N1.getNode();
8874 N1 = N1.getOperand(0);
8875 }
Evan Cheng166a4e62010-01-06 19:38:29 +00008876
Bill Wendlingaa28be62009-03-26 06:14:09 +00008877 // Match this pattern so that we can generate simpler code:
8878 //
8879 // %a = ...
8880 // %b = and i32 %a, 2
8881 // %c = srl i32 %b, 1
8882 // brcond i32 %c ...
8883 //
8884 // into
Wesley Peck527da1b2010-11-23 03:31:01 +00008885 //
Bill Wendlingaa28be62009-03-26 06:14:09 +00008886 // %a = ...
Evan Cheng166a4e62010-01-06 19:38:29 +00008887 // %b = and i32 %a, 2
Bill Wendlingaa28be62009-03-26 06:14:09 +00008888 // %c = setcc eq %b, 0
8889 // brcond %c ...
8890 //
8891 // This applies only when the AND constant value has one bit set and the
8892 // SRL constant is equal to the log2 of the AND constant. The back-end is
8893 // smart enough to convert the result into a TEST/JMP sequence.
8894 SDValue Op0 = N1.getOperand(0);
8895 SDValue Op1 = N1.getOperand(1);
8896
8897 if (Op0.getOpcode() == ISD::AND &&
Bill Wendlingaa28be62009-03-26 06:14:09 +00008898 Op1.getOpcode() == ISD::Constant) {
Bill Wendlingaa28be62009-03-26 06:14:09 +00008899 SDValue AndOp1 = Op0.getOperand(1);
8900
8901 if (AndOp1.getOpcode() == ISD::Constant) {
8902 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
8903
8904 if (AndConst.isPowerOf2() &&
8905 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008906 SDLoc DL(N);
Bill Wendlingaa28be62009-03-26 06:14:09 +00008907 SDValue SetCC =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008908 DAG.getSetCC(DL,
Matt Arsenault758659232013-05-18 00:21:46 +00008909 getSetCCResultType(Op0.getValueType()),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008910 Op0, DAG.getConstant(0, DL, Op0.getValueType()),
Bill Wendlingaa28be62009-03-26 06:14:09 +00008911 ISD::SETNE);
8912
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008913 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
Evan Cheng166a4e62010-01-06 19:38:29 +00008914 MVT::Other, Chain, SetCC, N2);
8915 // Don't add the new BRCond into the worklist or else SimplifySelectCC
8916 // will convert it back to (X & C1) >> C2.
8917 CombineTo(N, NewBRCond, false);
8918 // Truncate is dead.
Chandler Carruth18066972014-08-02 10:02:07 +00008919 if (Trunc)
8920 deleteAndRecombine(Trunc);
Bill Wendlingaa28be62009-03-26 06:14:09 +00008921 // Replace the uses of SRL with SETCC
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008922 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008923 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
Chandler Carruth18066972014-08-02 10:02:07 +00008924 deleteAndRecombine(N1.getNode());
Evan Cheng166a4e62010-01-06 19:38:29 +00008925 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Bill Wendlingaa28be62009-03-26 06:14:09 +00008926 }
8927 }
8928 }
Evan Chengc8d6cfd2010-10-04 22:41:01 +00008929
8930 if (Trunc)
8931 // Restore N1 if the above transformation doesn't match.
8932 N1 = N->getOperand(1);
Bill Wendlingaa28be62009-03-26 06:14:09 +00008933 }
Wesley Peck527da1b2010-11-23 03:31:01 +00008934
Evan Cheng228c31f2010-02-27 07:36:59 +00008935 // Transform br(xor(x, y)) -> br(x != y)
8936 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
8937 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
8938 SDNode *TheXor = N1.getNode();
8939 SDValue Op0 = TheXor->getOperand(0);
8940 SDValue Op1 = TheXor->getOperand(1);
8941 if (Op0.getOpcode() == Op1.getOpcode()) {
8942 // Avoid missing important xor optimizations.
8943 SDValue Tmp = visitXOR(TheXor);
Evan Cheng5652a8d2013-01-09 20:56:40 +00008944 if (Tmp.getNode()) {
8945 if (Tmp.getNode() != TheXor) {
8946 DEBUG(dbgs() << "\nReplacing.8 ";
8947 TheXor->dump(&DAG);
8948 dbgs() << "\nWith: ";
8949 Tmp.getNode()->dump(&DAG);
8950 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008951 WorklistRemover DeadNodes(*this);
Evan Cheng5652a8d2013-01-09 20:56:40 +00008952 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
Chandler Carruth18066972014-08-02 10:02:07 +00008953 deleteAndRecombine(TheXor);
Andrew Trickef9de2a2013-05-25 02:42:55 +00008954 return DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng5652a8d2013-01-09 20:56:40 +00008955 MVT::Other, Chain, Tmp, N2);
8956 }
8957
Benjamin Kramer93354432013-03-30 21:28:18 +00008958 // visitXOR has changed XOR's operands or replaced the XOR completely,
8959 // bail out.
8960 return SDValue(N, 0);
Evan Cheng228c31f2010-02-27 07:36:59 +00008961 }
8962 }
8963
8964 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
8965 bool Equal = false;
Matthias Braun887fdfb2015-05-19 00:25:21 +00008966 if (isOneConstant(Op0) && Op0.hasOneUse() &&
8967 Op0.getOpcode() == ISD::XOR) {
8968 TheXor = Op0.getNode();
8969 Equal = true;
8970 }
Evan Cheng228c31f2010-02-27 07:36:59 +00008971
Evan Chengc8d6cfd2010-10-04 22:41:01 +00008972 EVT SetCCVT = N1.getValueType();
Evan Cheng228c31f2010-02-27 07:36:59 +00008973 if (LegalTypes)
Matt Arsenault758659232013-05-18 00:21:46 +00008974 SetCCVT = getSetCCResultType(SetCCVT);
Andrew Trickef9de2a2013-05-25 02:42:55 +00008975 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
Evan Cheng228c31f2010-02-27 07:36:59 +00008976 SetCCVT,
8977 Op0, Op1,
8978 Equal ? ISD::SETEQ : ISD::SETNE);
8979 // Replace the uses of XOR with SETCC
Chandler Carruth3c0012b2014-07-21 08:56:44 +00008980 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00008981 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
Chandler Carruth18066972014-08-02 10:02:07 +00008982 deleteAndRecombine(N1.getNode());
Andrew Trickef9de2a2013-05-25 02:42:55 +00008983 return DAG.getNode(ISD::BRCOND, SDLoc(N),
Evan Cheng228c31f2010-02-27 07:36:59 +00008984 MVT::Other, Chain, SetCC, N2);
8985 }
8986 }
Bill Wendlingaa28be62009-03-26 06:14:09 +00008987
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008988 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +00008989}
8990
Chris Lattnera49e16f2005-10-05 06:47:48 +00008991// Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
8992//
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008993SDValue DAGCombiner::visitBR_CC(SDNode *N) {
Chris Lattnera49e16f2005-10-05 06:47:48 +00008994 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00008995 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
Scott Michelcf0da6c2009-02-17 22:15:04 +00008996
Dan Gohman82e80012009-11-17 00:47:23 +00008997 // If N is a constant we could fold this into a fallthrough or unconditional
8998 // branch. However that doesn't happen very often in normal code, because
8999 // Instcombine/SimplifyCFG should have handled the available opportunities.
9000 // If we did this folding here, it would be necessary to update the
9001 // MachineBasicBlock CFG, which is awkward.
9002
Duncan Sands93b66092008-06-09 11:32:28 +00009003 // Use SimplifySetCC to simplify SETCC's.
Matt Arsenault758659232013-05-18 00:21:46 +00009004 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
Andrew Trickef9de2a2013-05-25 02:42:55 +00009005 CondLHS, CondRHS, CC->get(), SDLoc(N),
Dale Johannesenf1163e92009-02-03 00:47:48 +00009006 false);
Chandler Carruth3c0012b2014-07-21 08:56:44 +00009007 if (Simp.getNode()) AddToWorklist(Simp.getNode());
Chris Lattner6a1b2de2006-10-14 03:52:46 +00009008
Nate Begemanbd7df032005-10-05 21:43:42 +00009009 // fold to a simpler setcc
Gabor Greiff304a7a2008-08-28 21:40:38 +00009010 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
Andrew Trickef9de2a2013-05-25 02:42:55 +00009011 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
Bill Wendling306bfc22009-01-30 23:27:35 +00009012 N->getOperand(0), Simp.getOperand(2),
9013 Simp.getOperand(0), Simp.getOperand(1),
9014 N->getOperand(4));
9015
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009016 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +00009017}
9018
Sanjay Patel50cbfc52014-08-28 16:29:51 +00009019/// Return true if 'Use' is a load or a store that uses N as its base pointer
9020/// and that N may be folded in the load / store addressing mode.
Evan Chengfa832632012-01-13 01:37:24 +00009021static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
9022 SelectionDAG &DAG,
9023 const TargetLowering &TLI) {
9024 EVT VT;
9025 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
9026 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
9027 return false;
Quentin Colombet82291452015-04-24 21:28:00 +00009028 VT = LD->getMemoryVT();
Evan Chengfa832632012-01-13 01:37:24 +00009029 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
9030 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
9031 return false;
Quentin Colombet82291452015-04-24 21:28:00 +00009032 VT = ST->getMemoryVT();
Evan Chengfa832632012-01-13 01:37:24 +00009033 } else
9034 return false;
9035
Chandler Carruth95f83e02013-01-07 15:14:13 +00009036 TargetLowering::AddrMode AM;
Evan Chengfa832632012-01-13 01:37:24 +00009037 if (N->getOpcode() == ISD::ADD) {
9038 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9039 if (Offset)
Evan Cheng80893ce2012-03-06 23:33:32 +00009040 // [reg +/- imm]
Evan Chengfa832632012-01-13 01:37:24 +00009041 AM.BaseOffs = Offset->getSExtValue();
9042 else
Evan Cheng80893ce2012-03-06 23:33:32 +00009043 // [reg +/- reg]
9044 AM.Scale = 1;
Evan Chengfa832632012-01-13 01:37:24 +00009045 } else if (N->getOpcode() == ISD::SUB) {
9046 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9047 if (Offset)
Evan Cheng80893ce2012-03-06 23:33:32 +00009048 // [reg +/- imm]
Evan Chengfa832632012-01-13 01:37:24 +00009049 AM.BaseOffs = -Offset->getSExtValue();
9050 else
Evan Cheng80893ce2012-03-06 23:33:32 +00009051 // [reg +/- reg]
9052 AM.Scale = 1;
Evan Chengfa832632012-01-13 01:37:24 +00009053 } else
9054 return false;
9055
9056 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
9057}
9058
Sanjay Patel50cbfc52014-08-28 16:29:51 +00009059/// Try turning a load/store into a pre-indexed load/store when the base
9060/// pointer is an add or subtract and it has other uses besides the load/store.
9061/// After the transformation, the new indexed load/store has effectively folded
9062/// the add/subtract in and all of its other uses are redirected to the
9063/// new load/store.
Chris Lattnerffad2162006-11-11 00:39:41 +00009064bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
Eli Friedman9d448e42011-11-12 00:35:34 +00009065 if (Level < AfterLegalizeDAG)
Chris Lattnerffad2162006-11-11 00:39:41 +00009066 return false;
9067
9068 bool isLoad = true;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009069 SDValue Ptr;
Owen Anderson53aa7a92009-08-10 22:56:29 +00009070 EVT VT;
Chris Lattnerffad2162006-11-11 00:39:41 +00009071 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009072 if (LD->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00009073 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00009074 VT = LD->getMemoryVT();
Evan Cheng8a1d09d2007-03-07 08:07:03 +00009075 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
Chris Lattnerffad2162006-11-11 00:39:41 +00009076 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
9077 return false;
9078 Ptr = LD->getBasePtr();
9079 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009080 if (ST->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00009081 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00009082 VT = ST->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00009083 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
9084 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
9085 return false;
9086 Ptr = ST->getBasePtr();
9087 isLoad = false;
Bill Wendling306bfc22009-01-30 23:27:35 +00009088 } else {
Chris Lattnerffad2162006-11-11 00:39:41 +00009089 return false;
Bill Wendling306bfc22009-01-30 23:27:35 +00009090 }
Chris Lattnerffad2162006-11-11 00:39:41 +00009091
Chris Lattnereabc15c2006-11-11 00:56:29 +00009092 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
9093 // out. There is no reason to make this a preinc/predec.
9094 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
Gabor Greiff304a7a2008-08-28 21:40:38 +00009095 Ptr.getNode()->hasOneUse())
Chris Lattnereabc15c2006-11-11 00:56:29 +00009096 return false;
Chris Lattnerffad2162006-11-11 00:39:41 +00009097
Chris Lattnereabc15c2006-11-11 00:56:29 +00009098 // Ask the target to do addressing mode selection.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009099 SDValue BasePtr;
9100 SDValue Offset;
Chris Lattnereabc15c2006-11-11 00:56:29 +00009101 ISD::MemIndexedMode AM = ISD::UNINDEXED;
9102 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
9103 return false;
Hal Finkel25819052013-02-08 21:35:47 +00009104
9105 // Backends without true r+i pre-indexed forms may need to pass a
9106 // constant base with a variable offset so that constant coercion
9107 // will work with the patterns in canonical form.
9108 bool Swapped = false;
9109 if (isa<ConstantSDNode>(BasePtr)) {
9110 std::swap(BasePtr, Offset);
9111 Swapped = true;
9112 }
9113
Evan Cheng044a0a82007-05-03 23:52:19 +00009114 // Don't create a indexed load / store with zero offset.
Matthias Braun1505efb2015-05-18 23:07:27 +00009115 if (isNullConstant(Offset))
Evan Cheng044a0a82007-05-03 23:52:19 +00009116 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00009117
Chris Lattnera0a80032006-11-11 01:00:15 +00009118 // Try turning it into a pre-indexed load / store except when:
Evan Chenga4d187b2007-05-24 02:35:39 +00009119 // 1) The new base ptr is a frame index.
9120 // 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 +00009121 // predecessor of the value being stored.
Evan Chenga4d187b2007-05-24 02:35:39 +00009122 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
Chris Lattnereabc15c2006-11-11 00:56:29 +00009123 // that would create a cycle.
Evan Chenga4d187b2007-05-24 02:35:39 +00009124 // 4) All uses are load / store ops that use it as old base ptr.
Chris Lattnerffad2162006-11-11 00:39:41 +00009125
Chris Lattnera0a80032006-11-11 01:00:15 +00009126 // Check #1. Preinc'ing a frame index would require copying the stack pointer
9127 // (plus the implicit offset) to a register to preinc anyway.
Evan Chengcfc05132009-05-06 18:25:01 +00009128 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
Chris Lattnera0a80032006-11-11 01:00:15 +00009129 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00009130
Chris Lattnera0a80032006-11-11 01:00:15 +00009131 // Check #2.
Chris Lattnereabc15c2006-11-11 00:56:29 +00009132 if (!isLoad) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009133 SDValue Val = cast<StoreSDNode>(N)->getValue();
Gabor Greiff304a7a2008-08-28 21:40:38 +00009134 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
Chris Lattnereabc15c2006-11-11 00:56:29 +00009135 return false;
Chris Lattnerffad2162006-11-11 00:39:41 +00009136 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00009137
Hal Finkel25819052013-02-08 21:35:47 +00009138 // If the offset is a constant, there may be other adds of constants that
9139 // can be folded with this one. We should do this to avoid having to keep
9140 // a copy of the original base pointer.
9141 SmallVector<SDNode *, 16> OtherUses;
9142 if (isa<ConstantSDNode>(Offset))
Hal Finkela60e6332015-05-18 15:46:02 +00009143 for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
9144 UE = BasePtr.getNode()->use_end();
9145 UI != UE; ++UI) {
9146 SDUse &Use = UI.getUse();
9147 // Skip the use that is Ptr and uses of other results from BasePtr's
9148 // node (important for nodes that return multiple results).
9149 if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
Hal Finkel25819052013-02-08 21:35:47 +00009150 continue;
9151
Hal Finkela60e6332015-05-18 15:46:02 +00009152 if (Use.getUser()->isPredecessorOf(N))
Hal Finkel25819052013-02-08 21:35:47 +00009153 continue;
9154
Hal Finkela60e6332015-05-18 15:46:02 +00009155 if (Use.getUser()->getOpcode() != ISD::ADD &&
9156 Use.getUser()->getOpcode() != ISD::SUB) {
Hal Finkel25819052013-02-08 21:35:47 +00009157 OtherUses.clear();
9158 break;
9159 }
9160
Hal Finkela60e6332015-05-18 15:46:02 +00009161 SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
Hal Finkel25819052013-02-08 21:35:47 +00009162 if (!isa<ConstantSDNode>(Op1)) {
9163 OtherUses.clear();
9164 break;
9165 }
9166
9167 // FIXME: In some cases, we can be smarter about this.
9168 if (Op1.getValueType() != Offset.getValueType()) {
9169 OtherUses.clear();
9170 break;
9171 }
9172
Hal Finkela60e6332015-05-18 15:46:02 +00009173 OtherUses.push_back(Use.getUser());
Hal Finkel25819052013-02-08 21:35:47 +00009174 }
9175
9176 if (Swapped)
9177 std::swap(BasePtr, Offset);
9178
Evan Chenga4d187b2007-05-24 02:35:39 +00009179 // Now check for #3 and #4.
Chris Lattnereabc15c2006-11-11 00:56:29 +00009180 bool RealUse = false;
Lang Hames5a004992011-07-07 04:31:51 +00009181
9182 // Caches for hasPredecessorHelper
9183 SmallPtrSet<const SDNode *, 32> Visited;
9184 SmallVector<const SDNode *, 16> Worklist;
9185
Jim Grosbache8160032014-04-11 01:13:13 +00009186 for (SDNode *Use : Ptr.getNode()->uses()) {
Chris Lattnereabc15c2006-11-11 00:56:29 +00009187 if (Use == N)
9188 continue;
Lang Hames5a004992011-07-07 04:31:51 +00009189 if (N->hasPredecessorHelper(Use, Visited, Worklist))
Chris Lattnereabc15c2006-11-11 00:56:29 +00009190 return false;
9191
Evan Chengfa832632012-01-13 01:37:24 +00009192 // If Ptr may be folded in addressing mode of other use, then it's
9193 // not profitable to do this transformation.
9194 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
Chris Lattnereabc15c2006-11-11 00:56:29 +00009195 RealUse = true;
9196 }
Bill Wendling306bfc22009-01-30 23:27:35 +00009197
Chris Lattnereabc15c2006-11-11 00:56:29 +00009198 if (!RealUse)
9199 return false;
9200
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009201 SDValue Result;
Chris Lattnereabc15c2006-11-11 00:56:29 +00009202 if (isLoad)
Andrew Trickef9de2a2013-05-25 02:42:55 +00009203 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00009204 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00009205 else
Andrew Trickef9de2a2013-05-25 02:42:55 +00009206 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00009207 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00009208 ++PreIndexedNodes;
9209 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +00009210 DEBUG(dbgs() << "\nReplacing.4 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00009211 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00009212 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00009213 Result.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00009214 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +00009215 WorklistRemover DeadNodes(*this);
Chris Lattnereabc15c2006-11-11 00:56:29 +00009216 if (isLoad) {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00009217 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9218 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
Chris Lattnereabc15c2006-11-11 00:56:29 +00009219 } else {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00009220 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
Chris Lattnereabc15c2006-11-11 00:56:29 +00009221 }
9222
Chris Lattnereabc15c2006-11-11 00:56:29 +00009223 // Finally, since the node is now dead, remove it from the graph.
Chandler Carruth18066972014-08-02 10:02:07 +00009224 deleteAndRecombine(N);
Chris Lattnereabc15c2006-11-11 00:56:29 +00009225
Hal Finkel25819052013-02-08 21:35:47 +00009226 if (Swapped)
9227 std::swap(BasePtr, Offset);
9228
9229 // Replace other uses of BasePtr that can be updated to use Ptr
9230 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9231 unsigned OffsetIdx = 1;
9232 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9233 OffsetIdx = 0;
9234 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
9235 BasePtr.getNode() && "Expected BasePtr operand");
9236
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00009237 // We need to replace ptr0 in the following expression:
9238 // x0 * offset0 + y0 * ptr0 = t0
9239 // knowing that
9240 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
Stephen Lincfe7f352013-07-08 00:37:03 +00009241 //
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00009242 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
9243 // indexed load/store and the expresion that needs to be re-written.
9244 //
9245 // Therefore, we have:
9246 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
Hal Finkel25819052013-02-08 21:35:47 +00009247
9248 ConstantSDNode *CN =
9249 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00009250 int X0, X1, Y0, Y1;
9251 APInt Offset0 = CN->getAPIntValue();
9252 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
Hal Finkel25819052013-02-08 21:35:47 +00009253
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00009254 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
9255 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
9256 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
9257 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
Hal Finkel25819052013-02-08 21:35:47 +00009258
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00009259 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
9260
9261 APInt CNV = Offset0;
9262 if (X0 < 0) CNV = -CNV;
9263 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
9264 else CNV = CNV - Offset1;
9265
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009266 SDLoc DL(OtherUses[i]);
9267
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00009268 // We can now generate the new expression.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009269 SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
Silviu Barangaaf7e8c32013-04-26 15:52:24 +00009270 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
9271
9272 SDValue NewUse = DAG.getNode(Opcode,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009273 DL,
Hal Finkel25819052013-02-08 21:35:47 +00009274 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
9275 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
Chandler Carruth18066972014-08-02 10:02:07 +00009276 deleteAndRecombine(OtherUses[i]);
Hal Finkel25819052013-02-08 21:35:47 +00009277 }
9278
Chris Lattnereabc15c2006-11-11 00:56:29 +00009279 // Replace the uses of Ptr with uses of the updated base value.
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00009280 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
Chandler Carruth18066972014-08-02 10:02:07 +00009281 deleteAndRecombine(Ptr.getNode());
Chris Lattnereabc15c2006-11-11 00:56:29 +00009282
9283 return true;
Chris Lattnerffad2162006-11-11 00:39:41 +00009284}
9285
Sanjay Patel50cbfc52014-08-28 16:29:51 +00009286/// Try to combine a load/store with a add/sub of the base pointer node into a
9287/// post-indexed load/store. The transformation folded the add/subtract into the
9288/// new indexed load/store effectively and all of its uses are redirected to the
9289/// new load/store.
Chris Lattnerffad2162006-11-11 00:39:41 +00009290bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
Eli Friedman9d448e42011-11-12 00:35:34 +00009291 if (Level < AfterLegalizeDAG)
Chris Lattnerffad2162006-11-11 00:39:41 +00009292 return false;
9293
9294 bool isLoad = true;
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009295 SDValue Ptr;
Owen Anderson53aa7a92009-08-10 22:56:29 +00009296 EVT VT;
Chris Lattnerffad2162006-11-11 00:39:41 +00009297 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009298 if (LD->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00009299 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00009300 VT = LD->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00009301 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9302 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9303 return false;
9304 Ptr = LD->getBasePtr();
9305 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
Chris Lattner1ea55cf2008-01-17 19:59:44 +00009306 if (ST->isIndexed())
Evan Cheng28cf4272006-12-16 06:25:23 +00009307 return false;
Dan Gohman47a7d6f2008-01-30 00:15:11 +00009308 VT = ST->getMemoryVT();
Chris Lattnerffad2162006-11-11 00:39:41 +00009309 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9310 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9311 return false;
9312 Ptr = ST->getBasePtr();
9313 isLoad = false;
Bill Wendling306bfc22009-01-30 23:27:35 +00009314 } else {
Chris Lattnerffad2162006-11-11 00:39:41 +00009315 return false;
Bill Wendling306bfc22009-01-30 23:27:35 +00009316 }
Chris Lattnerffad2162006-11-11 00:39:41 +00009317
Gabor Greiff304a7a2008-08-28 21:40:38 +00009318 if (Ptr.getNode()->hasOneUse())
Chris Lattnereabc15c2006-11-11 00:56:29 +00009319 return false;
Scott Michelcf0da6c2009-02-17 22:15:04 +00009320
Jim Grosbache8160032014-04-11 01:13:13 +00009321 for (SDNode *Op : Ptr.getNode()->uses()) {
Chris Lattnereabc15c2006-11-11 00:56:29 +00009322 if (Op == N ||
9323 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
9324 continue;
9325
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009326 SDValue BasePtr;
9327 SDValue Offset;
Chris Lattnereabc15c2006-11-11 00:56:29 +00009328 ISD::MemIndexedMode AM = ISD::UNINDEXED;
9329 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
Evan Cheng044a0a82007-05-03 23:52:19 +00009330 // Don't create a indexed load / store with zero offset.
Matthias Braun1505efb2015-05-18 23:07:27 +00009331 if (isNullConstant(Offset))
Evan Cheng044a0a82007-05-03 23:52:19 +00009332 continue;
Chris Lattnerffad2162006-11-11 00:39:41 +00009333
Chris Lattnereabc15c2006-11-11 00:56:29 +00009334 // Try turning it into a post-indexed load / store except when
Evan Chengfa832632012-01-13 01:37:24 +00009335 // 1) All uses are load / store ops that use it as base ptr (and
9336 // it may be folded as addressing mmode).
Chris Lattnereabc15c2006-11-11 00:56:29 +00009337 // 2) Op must be independent of N, i.e. Op is neither a predecessor
9338 // nor a successor of N. Otherwise, if Op is folded that would
9339 // create a cycle.
9340
Evan Chengcfc05132009-05-06 18:25:01 +00009341 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9342 continue;
9343
Chris Lattnereabc15c2006-11-11 00:56:29 +00009344 // Check for #1.
9345 bool TryNext = false;
Jim Grosbache8160032014-04-11 01:13:13 +00009346 for (SDNode *Use : BasePtr.getNode()->uses()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00009347 if (Use == Ptr.getNode())
Chris Lattnerffad2162006-11-11 00:39:41 +00009348 continue;
9349
Chris Lattnereabc15c2006-11-11 00:56:29 +00009350 // If all the uses are load / store addresses, then don't do the
9351 // transformation.
9352 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
9353 bool RealUse = false;
Jim Grosbache8160032014-04-11 01:13:13 +00009354 for (SDNode *UseUse : Use->uses()) {
Stephen Lincfe7f352013-07-08 00:37:03 +00009355 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
Chris Lattnereabc15c2006-11-11 00:56:29 +00009356 RealUse = true;
9357 }
Chris Lattnerffad2162006-11-11 00:39:41 +00009358
Chris Lattnereabc15c2006-11-11 00:56:29 +00009359 if (!RealUse) {
9360 TryNext = true;
9361 break;
Chris Lattnerffad2162006-11-11 00:39:41 +00009362 }
9363 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00009364 }
Bill Wendling306bfc22009-01-30 23:27:35 +00009365
Chris Lattnereabc15c2006-11-11 00:56:29 +00009366 if (TryNext)
9367 continue;
Chris Lattnerffad2162006-11-11 00:39:41 +00009368
Chris Lattnereabc15c2006-11-11 00:56:29 +00009369 // Check for #2
Evan Cheng567d2e52008-03-04 00:41:45 +00009370 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009371 SDValue Result = isLoad
Andrew Trickef9de2a2013-05-25 02:42:55 +00009372 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00009373 BasePtr, Offset, AM)
Andrew Trickef9de2a2013-05-25 02:42:55 +00009374 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
Bill Wendling306bfc22009-01-30 23:27:35 +00009375 BasePtr, Offset, AM);
Chris Lattnereabc15c2006-11-11 00:56:29 +00009376 ++PostIndexedNodes;
9377 ++NodesCombined;
David Greenefe5c3522010-01-05 01:25:00 +00009378 DEBUG(dbgs() << "\nReplacing.5 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00009379 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00009380 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00009381 Result.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00009382 dbgs() << '\n');
Chandler Carruth3c0012b2014-07-21 08:56:44 +00009383 WorklistRemover DeadNodes(*this);
Chris Lattnereabc15c2006-11-11 00:56:29 +00009384 if (isLoad) {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00009385 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9386 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
Chris Lattnereabc15c2006-11-11 00:56:29 +00009387 } else {
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00009388 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
Chris Lattnerffad2162006-11-11 00:39:41 +00009389 }
Chris Lattnereabc15c2006-11-11 00:56:29 +00009390
Chris Lattnereabc15c2006-11-11 00:56:29 +00009391 // Finally, since the node is now dead, remove it from the graph.
Chandler Carruth18066972014-08-02 10:02:07 +00009392 deleteAndRecombine(N);
Chris Lattnereabc15c2006-11-11 00:56:29 +00009393
9394 // Replace the uses of Use with uses of the updated base value.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009395 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00009396 Result.getValue(isLoad ? 1 : 0));
Chandler Carruth18066972014-08-02 10:02:07 +00009397 deleteAndRecombine(Op);
Chris Lattnereabc15c2006-11-11 00:56:29 +00009398 return true;
Chris Lattnerffad2162006-11-11 00:39:41 +00009399 }
9400 }
9401 }
Bill Wendling306bfc22009-01-30 23:27:35 +00009402
Chris Lattnerffad2162006-11-11 00:39:41 +00009403 return false;
9404}
9405
Hal Finkel51e6fa22014-09-02 06:24:04 +00009406/// \brief Return the base-pointer arithmetic from an indexed \p LD.
9407SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
9408 ISD::MemIndexedMode AM = LD->getAddressingMode();
9409 assert(AM != ISD::UNINDEXED);
9410 SDValue BP = LD->getOperand(1);
9411 SDValue Inc = LD->getOperand(2);
Hal Finkele19006e2014-09-02 16:05:23 +00009412
9413 // Some backends use TargetConstants for load offsets, but don't expect
9414 // TargetConstants in general ADD nodes. We can convert these constants into
9415 // regular Constants (if the constant is not opaque).
9416 assert((Inc.getOpcode() != ISD::TargetConstant ||
9417 !cast<ConstantSDNode>(Inc)->isOpaque()) &&
9418 "Cannot split out indexing using opaque target constants");
9419 if (Inc.getOpcode() == ISD::TargetConstant) {
9420 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009421 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
Hal Finkele19006e2014-09-02 16:05:23 +00009422 ConstInc->getValueType(0));
9423 }
9424
Hal Finkel51e6fa22014-09-02 06:24:04 +00009425 unsigned Opc =
9426 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
9427 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
9428}
9429
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009430SDValue DAGCombiner::visitLOAD(SDNode *N) {
Evan Chenge71fe34d2006-10-09 20:57:25 +00009431 LoadSDNode *LD = cast<LoadSDNode>(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009432 SDValue Chain = LD->getChain();
9433 SDValue Ptr = LD->getBasePtr();
Scott Michelcf0da6c2009-02-17 22:15:04 +00009434
Evan Chenga684cd22007-05-01 00:38:21 +00009435 // If load is not volatile and there are no uses of the loaded value (and
9436 // the updated indexed value in case of indexed loads), change uses of the
9437 // chain value into uses of the chain input (i.e. delete the dead load).
9438 if (!LD->isVolatile()) {
Owen Anderson9f944592009-08-11 20:47:22 +00009439 if (N->getValueType(1) == MVT::Other) {
Evan Chengb68343c2007-05-01 08:53:39 +00009440 // Unindexed loads.
Craig Topper0515cd42012-01-07 18:31:09 +00009441 if (!N->hasAnyUseOfValue(0)) {
Evan Cheng7be15282008-01-16 23:11:54 +00009442 // It's not safe to use the two value CombineTo variant here. e.g.
9443 // v1, chain2 = load chain1, loc
9444 // v2, chain3 = load chain2, loc
9445 // v3 = add v2, c
Chris Lattnere97fa8c2008-01-24 07:57:06 +00009446 // Now we replace use of chain2 with chain1. This makes the second load
9447 // isomorphic to the one we are deleting, and thus makes this load live.
David Greenefe5c3522010-01-05 01:25:00 +00009448 DEBUG(dbgs() << "\nReplacing.6 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00009449 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00009450 dbgs() << "\nWith chain: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00009451 Chain.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00009452 dbgs() << "\n");
Chandler Carruth3c0012b2014-07-21 08:56:44 +00009453 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00009454 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
Bill Wendling306bfc22009-01-30 23:27:35 +00009455
Chandler Carruth18066972014-08-02 10:02:07 +00009456 if (N->use_empty())
9457 deleteAndRecombine(N);
Bill Wendling306bfc22009-01-30 23:27:35 +00009458
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009459 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Cheng7be15282008-01-16 23:11:54 +00009460 }
Evan Chengb68343c2007-05-01 08:53:39 +00009461 } else {
9462 // Indexed loads.
Owen Anderson9f944592009-08-11 20:47:22 +00009463 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
Hal Finkel51e6fa22014-09-02 06:24:04 +00009464
Hal Finkele19006e2014-09-02 16:05:23 +00009465 // If this load has an opaque TargetConstant offset, then we cannot split
9466 // the indexing into an add/sub directly (that TargetConstant may not be
9467 // valid for a different type of node, and we cannot convert an opaque
9468 // target constant into a regular constant).
9469 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
9470 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
Hal Finkel51e6fa22014-09-02 06:24:04 +00009471
9472 if (!N->hasAnyUseOfValue(0) &&
Hal Finkele19006e2014-09-02 16:05:23 +00009473 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
Dale Johannesen84935752009-02-06 23:05:02 +00009474 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
Hal Finkel51e6fa22014-09-02 06:24:04 +00009475 SDValue Index;
Hal Finkele19006e2014-09-02 16:05:23 +00009476 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
Hal Finkel51e6fa22014-09-02 06:24:04 +00009477 Index = SplitIndexingFromLoad(LD);
9478 // Try to fold the base pointer arithmetic into subsequent loads and
9479 // stores.
9480 AddUsersToWorklist(N);
9481 } else
9482 Index = DAG.getUNDEF(N->getValueType(1));
Evan Cheng228c31f2010-02-27 07:36:59 +00009483 DEBUG(dbgs() << "\nReplacing.7 ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00009484 N->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00009485 dbgs() << "\nWith: ";
Chris Lattner4dc3edd2009-08-23 06:35:02 +00009486 Undef.getNode()->dump(&DAG);
David Greenefe5c3522010-01-05 01:25:00 +00009487 dbgs() << " and 2 other values\n");
Chandler Carruth3c0012b2014-07-21 08:56:44 +00009488 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00009489 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
Hal Finkel51e6fa22014-09-02 06:24:04 +00009490 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +00009491 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
Chandler Carruth18066972014-08-02 10:02:07 +00009492 deleteAndRecombine(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009493 return SDValue(N, 0); // Return N so it doesn't get rechecked!
Evan Chenga684cd22007-05-01 00:38:21 +00009494 }
Evan Chenga684cd22007-05-01 00:38:21 +00009495 }
9496 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00009497
Chris Lattnere260ed82005-10-10 22:04:48 +00009498 // If this load is directly stored, replace the load value with the stored
9499 // value.
9500 // TODO: Handle store large -> read small portion.
Jim Laskey0f7c3282006-10-11 17:47:52 +00009501 // TODO: Handle TRUNCSTORE/LOADEXT
Evan Chengadb9c032011-03-11 00:48:56 +00009502 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
Gabor Greiff304a7a2008-08-28 21:40:38 +00009503 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
Evan Chengab51cf22006-10-13 21:14:26 +00009504 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9505 if (PrevST->getBasePtr() == Ptr &&
9506 PrevST->getValue().getValueType() == N->getValueType(0))
Jim Laskey0f7c3282006-10-11 17:47:52 +00009507 return CombineTo(N, Chain.getOperand(1), Chain);
Evan Chengab51cf22006-10-13 21:14:26 +00009508 }
Jim Laskey0f7c3282006-10-11 17:47:52 +00009509 }
Scott Michelcf0da6c2009-02-17 22:15:04 +00009510
Evan Cheng43cd9e32010-04-01 06:04:33 +00009511 // Try to infer better alignment information than the load already has.
9512 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
Evan Cheng4a5b2042011-11-28 22:37:34 +00009513 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
Owen Andersonde89ecf2013-02-05 19:24:39 +00009514 if (Align > LD->getMemOperand()->getBaseAlignment()) {
9515 SDValue NewLoad =
Andrew Trickef9de2a2013-05-25 02:42:55 +00009516 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
Evan Cheng4a5b2042011-11-28 22:37:34 +00009517 LD->getValueType(0),
9518 Chain, Ptr, LD->getPointerInfo(),
9519 LD->getMemoryVT(),
Louis Gerbarg67474e32014-07-31 21:45:05 +00009520 LD->isVolatile(), LD->isNonTemporal(),
9521 LD->isInvariant(), Align, LD->getAAInfo());
Owen Andersondb420122015-03-19 22:48:57 +00009522 if (NewLoad.getNode() != N)
9523 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
Owen Andersonde89ecf2013-02-05 19:24:39 +00009524 }
Evan Cheng43cd9e32010-04-01 06:04:33 +00009525 }
9526 }
9527
Eric Christopherf55d4712014-10-08 23:38:39 +00009528 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9529 : DAG.getSubtarget().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +00009530#ifndef NDEBUG
9531 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9532 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9533 UseAA = false;
9534#endif
Hal Finkelccc18e12014-01-24 18:25:26 +00009535 if (UseAA && LD->isUnindexed()) {
Jim Laskeyd07be232006-09-25 16:29:54 +00009536 // Walk up chain skipping non-aliasing memory nodes.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009537 SDValue BetterChain = FindBetterChain(N, Chain);
Scott Michelcf0da6c2009-02-17 22:15:04 +00009538
Jim Laskey708d0db2006-10-04 16:53:27 +00009539 // If there is a better chain.
Jim Laskeyd07be232006-09-25 16:29:54 +00009540 if (Chain != BetterChain) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009541 SDValue ReplLoad;
Jim Laskey0f7c3282006-10-11 17:47:52 +00009542
Jim Laskeyd07be232006-09-25 16:29:54 +00009543 // Replace the chain to void dependency.
Jim Laskey0f7c3282006-10-11 17:47:52 +00009544 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009545 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009546 BetterChain, Ptr, LD->getMemOperand());
Jim Laskey0f7c3282006-10-11 17:47:52 +00009547 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +00009548 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
Stuart Hastings81c43062011-02-16 16:23:55 +00009549 LD->getValueType(0),
Richard Sandiford39c1ce42013-10-28 11:17:59 +00009550 BetterChain, Ptr, LD->getMemoryVT(),
9551 LD->getMemOperand());
Jim Laskey0f7c3282006-10-11 17:47:52 +00009552 }
Jim Laskeyd07be232006-09-25 16:29:54 +00009553
Jim Laskey708d0db2006-10-04 16:53:27 +00009554 // Create token factor to keep old chain connected.
Andrew Trickef9de2a2013-05-25 02:42:55 +00009555 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
Owen Anderson9f944592009-08-11 20:47:22 +00009556 MVT::Other, Chain, ReplLoad.getValue(1));
Wesley Peck527da1b2010-11-23 03:31:01 +00009557
Nate Begeman879d8f12009-09-15 00:18:30 +00009558 // Make sure the new and old chains are cleaned up.
Chandler Carruth3c0012b2014-07-21 08:56:44 +00009559 AddToWorklist(Token.getNode());
Wesley Peck527da1b2010-11-23 03:31:01 +00009560
Jim Laskeydcf983c2006-10-13 23:32:28 +00009561 // Replace uses with load result and token factor. Don't add users
9562 // to work list.
9563 return CombineTo(N, ReplLoad.getValue(0), Token, false);
Jim Laskeyd07be232006-09-25 16:29:54 +00009564 }
9565 }
9566
Evan Cheng357017f2006-11-03 03:06:21 +00009567 // Try transforming N to an indexed load.
Evan Cheng60c68462006-11-07 09:03:05 +00009568 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009569 return SDValue(N, 0);
Evan Cheng357017f2006-11-03 03:06:21 +00009570
Quentin Colombetde0e0622013-10-11 18:29:42 +00009571 // Try to slice up N to more direct loads if the slices are mapped to
9572 // different register banks or pairing can take place.
9573 if (SliceUpLoad(N))
9574 return SDValue(N, 0);
9575
Dan Gohman2ce6f2a2008-07-27 21:46:04 +00009576 return SDValue();
Chris Lattnere260ed82005-10-10 22:04:48 +00009577}
9578
Quentin Colombetde0e0622013-10-11 18:29:42 +00009579namespace {
9580/// \brief Helper structure used to slice a load in smaller loads.
9581/// Basically a slice is obtained from the following sequence:
9582/// Origin = load Ty1, Base
9583/// Shift = srl Ty1 Origin, CstTy Amount
9584/// Inst = trunc Shift to Ty2
9585///
9586/// Then, it will be rewriten into:
9587/// Slice = load SliceTy, Base + SliceOffset
9588/// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
9589///
9590/// SliceTy is deduced from the number of bits that are actually used to
9591/// build Inst.
9592struct LoadedSlice {
9593 /// \brief Helper structure used to compute the cost of a slice.
9594 struct Cost {
9595 /// Are we optimizing for code size.
9596 bool ForCodeSize;
9597 /// Various cost.
9598 unsigned Loads;
9599 unsigned Truncates;
9600 unsigned CrossRegisterBanksCopies;
9601 unsigned ZExts;
9602 unsigned Shift;
9603
9604 Cost(bool ForCodeSize = false)
9605 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
9606 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
9607
9608 /// \brief Get the cost of one isolated slice.
9609 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
9610 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
9611 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
9612 EVT TruncType = LS.Inst->getValueType(0);
9613 EVT LoadedType = LS.getLoadedType();
9614 if (TruncType != LoadedType &&
9615 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
9616 ZExts = 1;
9617 }
9618
9619 /// \brief Account for slicing gain in the current cost.
9620 /// Slicing provide a few gains like removing a shift or a
9621 /// truncate. This method allows to grow the cost of the original
9622 /// load with the gain from this slice.
9623 void addSliceGain(const LoadedSlice &LS) {
9624 // Each slice saves a truncate.
9625 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
9626 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
9627 LS.Inst->getOperand(0).getValueType()))
9628 ++Truncates;
9629 // If there is a shift amount, this slice gets rid of it.
9630 if (LS.Shift)
9631 ++Shift;
9632 // If this slice can merge a cross register bank copy, account for it.
9633 if (LS.canMergeExpensiveCrossRegisterBankCopy())
9634 ++CrossRegisterBanksCopies;
9635 }
9636
9637 Cost &operator+=(const Cost &RHS) {
9638 Loads += RHS.Loads;
9639 Truncates += RHS.Truncates;
9640 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
9641 ZExts += RHS.ZExts;
9642 Shift += RHS.Shift;
9643 return *this;
9644 }
9645
9646 bool operator==(const Cost &RHS) const {
9647 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9648 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9649 ZExts == RHS.ZExts && Shift == RHS.Shift;
9650 }
9651
9652 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
9653
9654 bool operator<(const Cost &RHS) const {
9655 // Assume cross register banks copies are as expensive as loads.
9656 // FIXME: Do we want some more target hooks?
9657 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
9658 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
9659 // Unless we are optimizing for code size, consider the
9660 // expensive operation first.
9661 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
9662 return ExpensiveOpsLHS < ExpensiveOpsRHS;
9663 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
9664 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
9665 }
9666
9667 bool operator>(const Cost &RHS) const { return RHS < *this; }
9668
9669 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
9670
9671 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
9672 };
9673 // The last instruction that represent the slice. This should be a
9674 // truncate instruction.
9675 SDNode *Inst;
9676 // The original load instruction.
9677 LoadSDNode *Origin;
9678 // The right shift amount in bits from the original load.
9679 unsigned Shift;
9680 // The DAG from which Origin came from.
9681 // This is used to get some contextual information about legal types, etc.
9682 SelectionDAG *DAG;
9683
Craig Topperc0196b12014-04-14 00:51:57 +00009684 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
9685 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
Quentin Colombetde0e0622013-10-11 18:29:42 +00009686 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
9687
Quentin Colombetde0e0622013-10-11 18:29:42 +00009688 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
9689 /// \return Result is \p BitWidth and has used bits set to 1 and
9690 /// not used bits set to 0.
9691 APInt getUsedBits() const {
9692 // Reproduce the trunc(lshr) sequence:
9693 // - Start from the truncated value.
9694 // - Zero extend to the desired bit width.
9695 // - Shift left.
9696 assert(Origin && "No original load to compare against.");
9697 unsigned BitWidth = Origin->getValueSizeInBits(0);
9698 assert(Inst && "This slice is not bound to an instruction");
9699 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
9700 "Extracted slice is bigger than the whole type!");
9701 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
9702 UsedBits.setAllBits();
9703 UsedBits = UsedBits.zext(BitWidth);
9704 UsedBits <<= Shift;
9705 return UsedBits;
9706 }
9707
9708 /// \brief Get the size of the slice to be loaded in bytes.
9709 unsigned getLoadedSize() const {
9710 unsigned SliceSize = getUsedBits().countPopulation();
9711 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
9712 return SliceSize / 8;
9713 }
9714
9715 /// \brief Get the type that will be loaded for this slice.
9716 /// Note: This may not be the final type for the slice.
9717 EVT getLoadedType() const {
9718 assert(DAG && "Missing context");
9719 LLVMContext &Ctxt = *DAG->getContext();
9720 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
9721 }
9722
9723 /// \brief Get the alignment of the load used for this slice.
9724 unsigned getAlignment() const {
9725 unsigned Alignment = Origin->getAlignment();
9726 unsigned Offset = getOffsetFromBase();
9727 if (Offset != 0)
9728 Alignment = MinAlign(Alignment, Alignment + Offset);
9729 return Alignment;
9730 }
9731
9732 /// \brief Check if this slice can be rewritten with legal operations.
9733 bool isLegal() const {
9734 // An invalid slice is not legal.
9735 if (!Origin || !Inst || !DAG)
9736 return false;
9737
9738 // Offsets are for indexed load only, we do not handle that.
9739 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
9740 return false;
9741
9742 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9743
9744 // Check that the type is legal.
9745 EVT SliceType = getLoadedType();
9746 if (!TLI.isTypeLegal(SliceType))
9747 return false;
9748
9749 // Check that the load is legal for this type.
9750 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
9751 return false;
9752
9753 // Check that the offset can be computed.
9754 // 1. Check its type.
9755 EVT PtrType = Origin->getBasePtr().getValueType();
9756 if (PtrType == MVT::Untyped || PtrType.isExtended())
9757 return false;
9758
9759 // 2. Check that it fits in the immediate.
9760 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
9761 return false;
9762
9763 // 3. Check that the computation is legal.
9764 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
9765 return false;
9766
9767 // Check that the zext is legal if it needs one.
9768 EVT TruncateType = Inst->getValueType(0);
9769 if (TruncateType != SliceType &&
9770 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
9771 return false;
9772
9773 return true;
9774 }
9775
9776 /// \brief Get the offset in bytes of this slice in the original chunk of
9777 /// bits.
Craig Topperc0196b12014-04-14 00:51:57 +00009778 /// \pre DAG != nullptr.
Quentin Colombetde0e0622013-10-11 18:29:42 +00009779 uint64_t getOffsetFromBase() const {
9780 assert(DAG && "Missing context.");
9781 bool IsBigEndian =
9782 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
9783 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
9784 uint64_t Offset = Shift / 8;
9785 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
9786 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
9787 "The size of the original loaded type is not a multiple of a"
9788 " byte.");
9789 // If Offset is bigger than TySizeInBytes, it means we are loading all
9790 // zeros. This should have been optimized before in the process.
9791 assert(TySizeInBytes > Offset &&
9792 "Invalid shift amount for given loaded size");
9793 if (IsBigEndian)
9794 Offset = TySizeInBytes - Offset - getLoadedSize();
9795 return Offset;
9796 }
9797
9798 /// \brief Generate the sequence of instructions to load the slice
9799 /// represented by this object and redirect the uses of this slice to
9800 /// this new sequence of instructions.
9801 /// \pre this->Inst && this->Origin are valid Instructions and this
9802 /// object passed the legal check: LoadedSlice::isLegal returned true.
9803 /// \return The last instruction of the sequence used to load the slice.
9804 SDValue loadSlice() const {
9805 assert(Inst && Origin && "Unable to replace a non-existing slice.");
9806 const SDValue &OldBaseAddr = Origin->getBasePtr();
9807 SDValue BaseAddr = OldBaseAddr;
9808 // Get the offset in that chunk of bytes w.r.t. the endianess.
9809 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
9810 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
9811 if (Offset) {
9812 // BaseAddr = BaseAddr + Offset.
9813 EVT ArithType = BaseAddr.getValueType();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009814 SDLoc DL(Origin);
9815 BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
9816 DAG->getConstant(Offset, DL, ArithType));
Quentin Colombetde0e0622013-10-11 18:29:42 +00009817 }
9818
9819 // Create the type of the loaded slice according to its size.
9820 EVT SliceType = getLoadedType();
9821
9822 // Create the load for the slice.
9823 SDValue LastInst = DAG->getLoad(
9824 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
9825 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
9826 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
9827 // If the final type is not the same as the loaded type, this means that
9828 // we have to pad with zero. Create a zero extend for that.
9829 EVT FinalType = Inst->getValueType(0);
9830 if (SliceType != FinalType)
9831 LastInst =
9832 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
9833 return LastInst;
9834 }
9835
9836 /// \brief Check if this slice can be merged with an expensive cross register
9837 /// bank copy. E.g.,
9838 /// i = load i32
9839 /// f = bitcast i32 i to float
9840 bool canMergeExpensiveCrossRegisterBankCopy() const {
9841 if (!Inst || !Inst->hasOneUse())
9842 return false;
9843 SDNode *Use = *Inst->use_begin();
9844 if (Use->getOpcode() != ISD::BITCAST)
9845 return false;
9846 assert(DAG && "Missing context");
9847 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9848 EVT ResVT = Use->getValueType(0);
9849 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
9850 const TargetRegisterClass *ArgRC =
9851 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
9852 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
9853 return false;
9854
9855 // At this point, we know that we perform a cross-register-bank copy.
9856 // Check if it is expensive.
Eric Christopherf55d4712014-10-08 23:38:39 +00009857 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
Quentin Colombetde0e0622013-10-11 18:29:42 +00009858 // Assume bitcasts are cheap, unless both register classes do not
9859 // explicitly share a common sub class.
9860 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
9861 return false;
9862
9863 // Check if it will be merged with the load.
9864 // 1. Check the alignment constraint.
9865 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
9866 ResVT.getTypeForEVT(*DAG->getContext()));
9867
9868 if (RequiredAlignment > getAlignment())
9869 return false;
9870
9871 // 2. Check that the load is a legal operation for that type.
9872 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
9873 return false;
9874
9875 // 3. Check that we do not have a zext in the way.
9876 if (Inst->getValueType(0) != getLoadedType())
9877 return false;
9878
9879 return true;
9880 }
9881};
9882}
9883
Quentin Colombetde0e0622013-10-11 18:29:42 +00009884/// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
9885/// \p UsedBits looks like 0..0 1..1 0..0.
9886static bool areUsedBitsDense(const APInt &UsedBits) {
9887 // If all the bits are one, this is dense!
9888 if (UsedBits.isAllOnesValue())
9889 return true;
9890
9891 // Get rid of the unused bits on the right.
9892 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
9893 // Get rid of the unused bits on the left.
9894 if (NarrowedUsedBits.countLeadingZeros())
9895 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
9896 // Check that the chunk of bits is completely used.
9897 return NarrowedUsedBits.isAllOnesValue();
9898}
9899
9900/// \brief Check whether or not \p First and \p Second are next to each other
9901/// in memory. This means that there is no hole between the bits loaded
9902/// by \p First and the bits loaded by \p Second.
9903static bool areSlicesNextToEachOther(const LoadedSlice &First,
9904 const LoadedSlice &Second) {
9905 assert(First.Origin == Second.Origin && First.Origin &&
9906 "Unable to match different memory origins.");
9907 APInt UsedBits = First.getUsedBits();
9908 assert((UsedBits & Second.getUsedBits()) == 0 &&
9909 "Slices are not supposed to overlap.");
9910 UsedBits |= Second.getUsedBits();
9911 return areUsedBitsDense(UsedBits);
9912}
9913
9914/// \brief Adjust the \p GlobalLSCost according to the target
9915/// paring capabilities and the layout of the slices.
9916/// \pre \p GlobalLSCost should account for at least as many loads as
9917/// there is in the slices in \p LoadedSlices.
9918static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9919 LoadedSlice::Cost &GlobalLSCost) {
9920 unsigned NumberOfSlices = LoadedSlices.size();
9921 // If there is less than 2 elements, no pairing is possible.
9922 if (NumberOfSlices < 2)
9923 return;
9924
9925 // Sort the slices so that elements that are likely to be next to each
9926 // other in memory are next to each other in the list.
Benjamin Kramer3a377bc2014-03-01 11:47:00 +00009927 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
9928 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
9929 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
9930 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
9931 });
Quentin Colombetde0e0622013-10-11 18:29:42 +00009932 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
9933 // First (resp. Second) is the first (resp. Second) potentially candidate
9934 // to be placed in a paired load.
Craig Topperc0196b12014-04-14 00:51:57 +00009935 const LoadedSlice *First = nullptr;
9936 const LoadedSlice *Second = nullptr;
Quentin Colombetde0e0622013-10-11 18:29:42 +00009937 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
9938 // Set the beginning of the pair.
9939 First = Second) {
9940
9941 Second = &LoadedSlices[CurrSlice];
9942
9943 // If First is NULL, it means we start a new pair.
9944 // Get to the next slice.
9945 if (!First)
9946 continue;
9947
9948 EVT LoadedType = First->getLoadedType();
9949
9950 // If the types of the slices are different, we cannot pair them.
9951 if (LoadedType != Second->getLoadedType())
9952 continue;
9953
9954 // Check if the target supplies paired loads for this type.
9955 unsigned RequiredAlignment = 0;
9956 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
9957 // move to the next pair, this type is hopeless.
Craig Topperc0196b12014-04-14 00:51:57 +00009958 Second = nullptr;
Quentin Colombetde0e0622013-10-11 18:29:42 +00009959 continue;
9960 }
9961 // Check if we meet the alignment requirement.
9962 if (RequiredAlignment > First->getAlignment())
9963 continue;
9964
9965 // Check that both loads are next to each other in memory.
9966 if (!areSlicesNextToEachOther(*First, *Second))
9967 continue;
9968
9969 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
9970 --GlobalLSCost.Loads;
9971 // Move to the next pair.
Craig Topperc0196b12014-04-14 00:51:57 +00009972 Second = nullptr;
Quentin Colombetde0e0622013-10-11 18:29:42 +00009973 }
9974}
9975
9976/// \brief Check the profitability of all involved LoadedSlice.
9977/// Currently, it is considered profitable if there is exactly two
9978/// involved slices (1) which are (2) next to each other in memory, and
9979/// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
9980///
9981/// Note: The order of the elements in \p LoadedSlices may be modified, but not
9982/// the elements themselves.
9983///
9984/// FIXME: When the cost model will be mature enough, we can relax
9985/// constraints (1) and (2).
9986static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9987 const APInt &UsedBits, bool ForCodeSize) {
9988 unsigned NumberOfSlices = LoadedSlices.size();
9989 if (StressLoadSlicing)
9990 return NumberOfSlices > 1;
9991
9992 // Check (1).
9993 if (NumberOfSlices != 2)
9994 return false;
9995
9996 // Check (2).
9997 if (!areUsedBitsDense(UsedBits))
9998 return false;
9999
10000 // Check (3).
10001 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
10002 // The original code has one big load.
10003 OrigCost.Loads = 1;
10004 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
10005 const LoadedSlice &LS = LoadedSlices[CurrSlice];
10006 // Accumulate the cost of all the slices.
10007 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
10008 GlobalSlicingCost += SliceCost;
10009
10010 // Account as cost in the original configuration the gain obtained
10011 // with the current slices.
10012 OrigCost.addSliceGain(LS);
10013 }
10014
10015 // If the target supports paired load, adjust the cost accordingly.
10016 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
10017 return OrigCost > GlobalSlicingCost;
10018}
10019
10020/// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
10021/// operations, split it in the various pieces being extracted.
10022///
10023/// This sort of thing is introduced by SROA.
10024/// This slicing takes care not to insert overlapping loads.
10025/// \pre LI is a simple load (i.e., not an atomic or volatile load).
10026bool DAGCombiner::SliceUpLoad(SDNode *N) {
10027 if (Level < AfterLegalizeDAG)
10028 return false;
10029
10030 LoadSDNode *LD = cast<LoadSDNode>(N);
10031 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
10032 !LD->getValueType(0).isInteger())
10033 return false;
10034
10035 // Keep track of already used bits to detect overlapping values.
10036 // In that case, we will just abort the transformation.
10037 APInt UsedBits(LD->getValueSizeInBits(0), 0);
10038
10039 SmallVector<LoadedSlice, 4> LoadedSlices;
10040
10041 // Check if this load is used as several smaller chunks of bits.
10042 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
10043 // of computation for each trunc.
10044 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
10045 UI != UIEnd; ++UI) {
10046 // Skip the uses of the chain.
10047 if (UI.getUse().getResNo() != 0)
10048 continue;
10049
10050 SDNode *User = *UI;
10051 unsigned Shift = 0;
10052
10053 // Check if this is a trunc(lshr).
10054 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
10055 isa<ConstantSDNode>(User->getOperand(1))) {
10056 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
10057 User = *User->use_begin();
10058 }
10059
10060 // At this point, User is a Truncate, iff we encountered, trunc or
10061 // trunc(lshr).
10062 if (User->getOpcode() != ISD::TRUNCATE)
10063 return false;
10064
10065 // The width of the type must be a power of 2 and greater than 8-bits.
10066 // Otherwise the load cannot be represented in LLVM IR.
Alp Tokerf907b892013-12-05 05:44:44 +000010067 // Moreover, if we shifted with a non-8-bits multiple, the slice
Alp Tokercb402912014-01-24 17:20:08 +000010068 // will be across several bytes. We do not support that.
Quentin Colombetde0e0622013-10-11 18:29:42 +000010069 unsigned Width = User->getValueSizeInBits(0);
10070 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
10071 return 0;
10072
10073 // Build the slice for this chain of computations.
10074 LoadedSlice LS(User, LD, Shift, &DAG);
10075 APInt CurrentUsedBits = LS.getUsedBits();
10076
10077 // Check if this slice overlaps with another.
10078 if ((CurrentUsedBits & UsedBits) != 0)
10079 return false;
10080 // Update the bits used globally.
10081 UsedBits |= CurrentUsedBits;
10082
10083 // Check if the new slice would be legal.
10084 if (!LS.isLegal())
10085 return false;
10086
10087 // Record the slice.
10088 LoadedSlices.push_back(LS);
10089 }
10090
10091 // Abort slicing if it does not seem to be profitable.
10092 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
10093 return false;
10094
10095 ++SlicedLoads;
10096
10097 // Rewrite each chain to use an independent load.
10098 // By construction, each chain can be represented by a unique load.
10099
10100 // Prepare the argument for the new token factor for all the slices.
10101 SmallVector<SDValue, 8> ArgChains;
10102 for (SmallVectorImpl<LoadedSlice>::const_iterator
10103 LSIt = LoadedSlices.begin(),
10104 LSItEnd = LoadedSlices.end();
10105 LSIt != LSItEnd; ++LSIt) {
10106 SDValue SliceInst = LSIt->loadSlice();
10107 CombineTo(LSIt->Inst, SliceInst, true);
10108 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
10109 SliceInst = SliceInst.getOperand(0);
10110 assert(SliceInst->getOpcode() == ISD::LOAD &&
10111 "It takes more than a zext to get to the loaded slice!!");
10112 ArgChains.push_back(SliceInst.getValue(1));
10113 }
10114
10115 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
Craig Topper48d114b2014-04-26 18:35:24 +000010116 ArgChains);
Quentin Colombetde0e0622013-10-11 18:29:42 +000010117 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10118 return true;
10119}
10120
Sanjay Patel50cbfc52014-08-28 16:29:51 +000010121/// Check to see if V is (and load (ptr), imm), where the load is having
10122/// specific bytes cleared out. If so, return the byte size being masked out
10123/// and the shift amount.
Chris Lattner4041ab62010-04-15 04:48:01 +000010124static std::pair<unsigned, unsigned>
10125CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10126 std::pair<unsigned, unsigned> Result(0, 0);
Wesley Peck527da1b2010-11-23 03:31:01 +000010127
Chris Lattner4041ab62010-04-15 04:48:01 +000010128 // Check for the structure we're looking for.
10129 if (V->getOpcode() != ISD::AND ||
10130 !isa<ConstantSDNode>(V->getOperand(1)) ||
10131 !ISD::isNormalLoad(V->getOperand(0).getNode()))
10132 return Result;
Wesley Peck527da1b2010-11-23 03:31:01 +000010133
Chris Lattner3245afd2010-04-15 06:10:49 +000010134 // Check the chain and pointer.
Chris Lattner4041ab62010-04-15 04:48:01 +000010135 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
Chris Lattner3245afd2010-04-15 06:10:49 +000010136 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
Wesley Peck527da1b2010-11-23 03:31:01 +000010137
Chris Lattner3245afd2010-04-15 06:10:49 +000010138 // The store should be chained directly to the load or be an operand of a
10139 // tokenfactor.
10140 if (LD == Chain.getNode())
10141 ; // ok.
10142 else if (Chain->getOpcode() != ISD::TokenFactor)
10143 return Result; // Fail.
10144 else {
10145 bool isOk = false;
10146 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
10147 if (Chain->getOperand(i).getNode() == LD) {
10148 isOk = true;
10149 break;
10150 }
10151 if (!isOk) return Result;
10152 }
Wesley Peck527da1b2010-11-23 03:31:01 +000010153
Chris Lattner4041ab62010-04-15 04:48:01 +000010154 // This only handles simple types.
10155 if (V.getValueType() != MVT::i16 &&
10156 V.getValueType() != MVT::i32 &&
10157 V.getValueType() != MVT::i64)
10158 return Result;
10159
10160 // Check the constant mask. Invert it so that the bits being masked out are
10161 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
10162 // follow the sign bit for uniformity.
10163 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +000010164 unsigned NotMaskLZ = countLeadingZeros(NotMask);
Chris Lattner4041ab62010-04-15 04:48:01 +000010165 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +000010166 unsigned NotMaskTZ = countTrailingZeros(NotMask);
Chris Lattner4041ab62010-04-15 04:48:01 +000010167 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
10168 if (NotMaskLZ == 64) return Result; // All zero mask.
Wesley Peck527da1b2010-11-23 03:31:01 +000010169
Chris Lattner4041ab62010-04-15 04:48:01 +000010170 // See if we have a continuous run of bits. If so, we have 0*1+0*
Benjamin Kramer5f6a9072015-02-12 15:35:40 +000010171 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
Chris Lattner4041ab62010-04-15 04:48:01 +000010172 return Result;
10173
10174 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10175 if (V.getValueType() != MVT::i64 && NotMaskLZ)
10176 NotMaskLZ -= 64-V.getValueSizeInBits();
Wesley Peck527da1b2010-11-23 03:31:01 +000010177
Chris Lattner4041ab62010-04-15 04:48:01 +000010178 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10179 switch (MaskedBytes) {
Wesley Peck527da1b2010-11-23 03:31:01 +000010180 case 1:
10181 case 2:
Chris Lattner4041ab62010-04-15 04:48:01 +000010182 case 4: break;
10183 default: return Result; // All one mask, or 5-byte mask.
10184 }
Wesley Peck527da1b2010-11-23 03:31:01 +000010185
Chris Lattner4041ab62010-04-15 04:48:01 +000010186 // Verify that the first bit starts at a multiple of mask so that the access
10187 // is aligned the same as the access width.
10188 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
Wesley Peck527da1b2010-11-23 03:31:01 +000010189
Chris Lattner4041ab62010-04-15 04:48:01 +000010190 Result.first = MaskedBytes;
10191 Result.second = NotMaskTZ/8;
10192 return Result;
10193}
10194
10195
Sanjay Patel50cbfc52014-08-28 16:29:51 +000010196/// Check to see if IVal is something that provides a value as specified by
10197/// MaskInfo. If so, replace the specified store with a narrower store of
10198/// truncated IVal.
Chris Lattner4041ab62010-04-15 04:48:01 +000010199static SDNode *
10200ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10201 SDValue IVal, StoreSDNode *St,
10202 DAGCombiner *DC) {
10203 unsigned NumBytes = MaskInfo.first;
10204 unsigned ByteShift = MaskInfo.second;
10205 SelectionDAG &DAG = DC->getDAG();
Wesley Peck527da1b2010-11-23 03:31:01 +000010206
Chris Lattner4041ab62010-04-15 04:48:01 +000010207 // Check to see if IVal is all zeros in the part being masked in by the 'or'
10208 // that uses this. If not, this is not a replacement.
10209 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10210 ByteShift*8, (ByteShift+NumBytes)*8);
Craig Topperc0196b12014-04-14 00:51:57 +000010211 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
Wesley Peck527da1b2010-11-23 03:31:01 +000010212
Chris Lattner4041ab62010-04-15 04:48:01 +000010213 // Check that it is legal on the target to do this. It is legal if the new
10214 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10215 // legalization.
10216 MVT VT = MVT::getIntegerVT(NumBytes*8);
10217 if (!DC->isTypeLegal(VT))
Craig Topperc0196b12014-04-14 00:51:57 +000010218 return nullptr;
Wesley Peck527da1b2010-11-23 03:31:01 +000010219
Chris Lattner4041ab62010-04-15 04:48:01 +000010220 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
10221 // shifted by ByteShift and truncated down to NumBytes.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010222 if (ByteShift) {
10223 SDLoc DL(IVal);
10224 IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10225 DAG.getConstant(ByteShift*8, DL,
Owen Andersonb2c80da2011-02-25 21:41:48 +000010226 DC->getShiftAmountTy(IVal.getValueType())));
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010227 }
Chris Lattner4041ab62010-04-15 04:48:01 +000010228
10229 // Figure out the offset for the store and the alignment of the access.
10230 unsigned StOffset;
10231 unsigned NewAlign = St->getAlignment();
10232
10233 if (DAG.getTargetLoweringInfo().isLittleEndian())
10234 StOffset = ByteShift;
10235 else
10236 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
Wesley Peck527da1b2010-11-23 03:31:01 +000010237
Chris Lattner4041ab62010-04-15 04:48:01 +000010238 SDValue Ptr = St->getBasePtr();
10239 if (StOffset) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010240 SDLoc DL(IVal);
10241 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
10242 Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
Chris Lattner4041ab62010-04-15 04:48:01 +000010243 NewAlign = MinAlign(NewAlign, StOffset);
10244 }
Wesley Peck527da1b2010-11-23 03:31:01 +000010245
Chris Lattner4041ab62010-04-15 04:48:01 +000010246 // Truncate down to the new size.
Andrew Trickef9de2a2013-05-25 02:42:55 +000010247 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
Wesley Peck527da1b2010-11-23 03:31:01 +000010248
Chris Lattner4041ab62010-04-15 04:48:01 +000010249 ++OpsNarrowed;
Andrew Trickef9de2a2013-05-25 02:42:55 +000010250 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
Chris Lattner676c61d2010-09-21 18:41:36 +000010251 St->getPointerInfo().getWithOffset(StOffset),
Chris Lattner4041ab62010-04-15 04:48:01 +000010252 false, false, NewAlign).getNode();
10253}
10254
Evan Chenga9cda8a2009-05-28 00:35:15 +000010255
Sanjay Patel50cbfc52014-08-28 16:29:51 +000010256/// Look for sequence of load / op / store where op is one of 'or', 'xor', and
10257/// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
10258/// narrowing the load and store if it would end up being a win for performance
10259/// or code size.
Evan Chenga9cda8a2009-05-28 00:35:15 +000010260SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
10261 StoreSDNode *ST = cast<StoreSDNode>(N);
Evan Cheng6673ff02009-05-28 18:41:02 +000010262 if (ST->isVolatile())
10263 return SDValue();
10264
Evan Chenga9cda8a2009-05-28 00:35:15 +000010265 SDValue Chain = ST->getChain();
10266 SDValue Value = ST->getValue();
10267 SDValue Ptr = ST->getBasePtr();
Owen Anderson53aa7a92009-08-10 22:56:29 +000010268 EVT VT = Value.getValueType();
Evan Chenga9cda8a2009-05-28 00:35:15 +000010269
10270 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
Evan Cheng6673ff02009-05-28 18:41:02 +000010271 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +000010272
10273 unsigned Opc = Value.getOpcode();
Wesley Peck527da1b2010-11-23 03:31:01 +000010274
Chris Lattner4041ab62010-04-15 04:48:01 +000010275 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
10276 // is a byte mask indicating a consecutive number of bytes, check to see if
10277 // Y is known to provide just those bytes. If so, we try to replace the
10278 // load + replace + store sequence with a single (narrower) store, which makes
10279 // the load dead.
10280 if (Opc == ISD::OR) {
10281 std::pair<unsigned, unsigned> MaskedLoad;
10282 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
10283 if (MaskedLoad.first)
10284 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10285 Value.getOperand(1), ST,this))
10286 return SDValue(NewST, 0);
Wesley Peck527da1b2010-11-23 03:31:01 +000010287
Chris Lattner4041ab62010-04-15 04:48:01 +000010288 // Or is commutative, so try swapping X and Y.
10289 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10290 if (MaskedLoad.first)
10291 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10292 Value.getOperand(0), ST,this))
10293 return SDValue(NewST, 0);
10294 }
Wesley Peck527da1b2010-11-23 03:31:01 +000010295
Evan Chenga9cda8a2009-05-28 00:35:15 +000010296 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10297 Value.getOperand(1).getOpcode() != ISD::Constant)
Evan Cheng6673ff02009-05-28 18:41:02 +000010298 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +000010299
10300 SDValue N0 = Value.getOperand(0);
Dan Gohman3c9b5f32010-09-02 21:18:42 +000010301 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10302 Chain == SDValue(N0.getNode(), 1)) {
Evan Chenga9cda8a2009-05-28 00:35:15 +000010303 LoadSDNode *LD = cast<LoadSDNode>(N0);
Chris Lattnerf72c3c02010-09-21 16:08:50 +000010304 if (LD->getBasePtr() != Ptr ||
10305 LD->getPointerInfo().getAddrSpace() !=
10306 ST->getPointerInfo().getAddrSpace())
Evan Cheng6673ff02009-05-28 18:41:02 +000010307 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +000010308
10309 // Find the type to narrow it the load / op / store to.
10310 SDValue N1 = Value.getOperand(1);
10311 unsigned BitWidth = N1.getValueSizeInBits();
10312 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10313 if (Opc == ISD::AND)
10314 Imm ^= APInt::getAllOnesValue(BitWidth);
Evan Cheng86cdb4b2009-05-28 23:52:18 +000010315 if (Imm == 0 || Imm.isAllOnesValue())
10316 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +000010317 unsigned ShAmt = Imm.countTrailingZeros();
10318 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10319 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
Owen Anderson117c9e82009-08-12 00:36:31 +000010320 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
Elena Demikhovsky150d9f32015-01-22 12:07:59 +000010321 // The narrowing should be profitable, the load/store operation should be
Elena Demikhovsky9c264622015-01-22 09:39:08 +000010322 // legal (or custom) and the store size should be equal to the NewVT width.
Evan Chenga9cda8a2009-05-28 00:35:15 +000010323 while (NewBW < BitWidth &&
Elena Demikhovsky9c264622015-01-22 09:39:08 +000010324 (NewVT.getStoreSizeInBits() != NewBW ||
10325 !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
10326 !TLI.isNarrowingProfitable(VT, NewVT))) {
Evan Chenga9cda8a2009-05-28 00:35:15 +000010327 NewBW = NextPowerOf2(NewBW);
Owen Anderson117c9e82009-08-12 00:36:31 +000010328 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
Evan Chenga9cda8a2009-05-28 00:35:15 +000010329 }
Evan Cheng6673ff02009-05-28 18:41:02 +000010330 if (NewBW >= BitWidth)
10331 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +000010332
10333 // If the lsb changed does not start at the type bitwidth boundary,
10334 // start at the previous one.
10335 if (ShAmt % NewBW)
10336 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
Manman Ren82751a12012-12-12 01:13:50 +000010337 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
10338 std::min(BitWidth, ShAmt + NewBW));
Evan Chenga9cda8a2009-05-28 00:35:15 +000010339 if ((Imm & Mask) == Imm) {
10340 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
10341 if (Opc == ISD::AND)
10342 NewImm ^= APInt::getAllOnesValue(NewBW);
10343 uint64_t PtrOff = ShAmt / 8;
10344 // For big endian targets, we need to adjust the offset to the pointer to
10345 // load the correct bytes.
10346 if (TLI.isBigEndian())
Evan Cheng6673ff02009-05-28 18:41:02 +000010347 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
Evan Chenga9cda8a2009-05-28 00:35:15 +000010348
10349 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
Chris Lattner229907c2011-07-18 04:54:35 +000010350 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
Micah Villmowcdfe20b2012-10-08 16:38:25 +000010351 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
Evan Cheng6673ff02009-05-28 18:41:02 +000010352 return SDValue();
10353
Andrew Trickef9de2a2013-05-25 02:42:55 +000010354 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
Evan Chenga9cda8a2009-05-28 00:35:15 +000010355 Ptr.getValueType(), Ptr,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010356 DAG.getConstant(PtrOff, SDLoc(LD),
10357 Ptr.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000010358 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
Evan Chenga9cda8a2009-05-28 00:35:15 +000010359 LD->getChain(), NewPtr,
Chris Lattnerf72c3c02010-09-21 16:08:50 +000010360 LD->getPointerInfo().getWithOffset(PtrOff),
David Greene39c6d012010-02-15 17:00:31 +000010361 LD->isVolatile(), LD->isNonTemporal(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +000010362 LD->isInvariant(), NewAlign,
Hal Finkelcc39b672014-07-24 12:16:19 +000010363 LD->getAAInfo());
Andrew Trickef9de2a2013-05-25 02:42:55 +000010364 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010365 DAG.getConstant(NewImm, SDLoc(Value),
10366 NewVT));
Andrew Trickef9de2a2013-05-25 02:42:55 +000010367 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
Evan Chenga9cda8a2009-05-28 00:35:15 +000010368 NewVal, NewPtr,
Chris Lattnerf72c3c02010-09-21 16:08:50 +000010369 ST->getPointerInfo().getWithOffset(PtrOff),
David Greene39c6d012010-02-15 17:00:31 +000010370 false, false, NewAlign);
Evan Chenga9cda8a2009-05-28 00:35:15 +000010371
Chandler Carruth3c0012b2014-07-21 08:56:44 +000010372 AddToWorklist(NewPtr.getNode());
10373 AddToWorklist(NewLD.getNode());
10374 AddToWorklist(NewVal.getNode());
10375 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +000010376 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
Evan Chenga9cda8a2009-05-28 00:35:15 +000010377 ++OpsNarrowed;
10378 return NewST;
10379 }
10380 }
10381
Evan Cheng6673ff02009-05-28 18:41:02 +000010382 return SDValue();
Evan Chenga9cda8a2009-05-28 00:35:15 +000010383}
10384
Sanjay Patel50cbfc52014-08-28 16:29:51 +000010385/// For a given floating point load / store pair, if the load value isn't used
10386/// by any other operations, then consider transforming the pair to integer
10387/// load / store operations if the target deems the transformation profitable.
Evan Chengd42641c2011-02-02 01:06:55 +000010388SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
10389 StoreSDNode *ST = cast<StoreSDNode>(N);
10390 SDValue Chain = ST->getChain();
10391 SDValue Value = ST->getValue();
10392 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
10393 Value.hasOneUse() &&
10394 Chain == SDValue(Value.getNode(), 1)) {
10395 LoadSDNode *LD = cast<LoadSDNode>(Value);
10396 EVT VT = LD->getMemoryVT();
10397 if (!VT.isFloatingPoint() ||
10398 VT != ST->getMemoryVT() ||
10399 LD->isNonTemporal() ||
10400 ST->isNonTemporal() ||
10401 LD->getPointerInfo().getAddrSpace() != 0 ||
10402 ST->getPointerInfo().getAddrSpace() != 0)
10403 return SDValue();
10404
10405 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
10406 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
10407 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
10408 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
10409 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
10410 return SDValue();
10411
10412 unsigned LDAlign = LD->getAlignment();
10413 unsigned STAlign = ST->getAlignment();
Chris Lattner229907c2011-07-18 04:54:35 +000010414 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
Micah Villmowcdfe20b2012-10-08 16:38:25 +000010415 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
Evan Chengd42641c2011-02-02 01:06:55 +000010416 if (LDAlign < ABIAlign || STAlign < ABIAlign)
10417 return SDValue();
10418
Andrew Trickef9de2a2013-05-25 02:42:55 +000010419 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
Evan Chengd42641c2011-02-02 01:06:55 +000010420 LD->getChain(), LD->getBasePtr(),
10421 LD->getPointerInfo(),
Pete Cooper82cd9e82011-11-08 18:42:53 +000010422 false, false, false, LDAlign);
Evan Chengd42641c2011-02-02 01:06:55 +000010423
Andrew Trickef9de2a2013-05-25 02:42:55 +000010424 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
Evan Chengd42641c2011-02-02 01:06:55 +000010425 NewLD, ST->getBasePtr(),
10426 ST->getPointerInfo(),
10427 false, false, STAlign);
10428
Chandler Carruth3c0012b2014-07-21 08:56:44 +000010429 AddToWorklist(NewLD.getNode());
10430 AddToWorklist(NewST.getNode());
10431 WorklistRemover DeadNodes(*this);
Jakob Stoklund Olesenbeb94692012-04-20 22:08:46 +000010432 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
Evan Chengd42641c2011-02-02 01:06:55 +000010433 ++LdStFP2Int;
10434 return NewST;
10435 }
10436
10437 return SDValue();
10438}
10439
Benjamin Kramer51f6096c2015-03-23 12:30:58 +000010440namespace {
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010441/// Helper struct to parse and store a memory address as base + index + offset.
10442/// We ignore sign extensions when it is safe to do so.
10443/// The following two expressions are not equivalent. To differentiate we need
10444/// to store whether there was a sign extension involved in the index
10445/// computation.
10446/// (load (i64 add (i64 copyfromreg %c)
10447/// (i64 signextend (add (i8 load %index)
10448/// (i8 1))))
10449/// vs
10450///
10451/// (load (i64 add (i64 copyfromreg %c)
10452/// (i64 signextend (i32 add (i32 signextend (i8 load %index))
10453/// (i32 1)))))
10454struct BaseIndexOffset {
10455 SDValue Base;
10456 SDValue Index;
10457 int64_t Offset;
10458 bool IsIndexSignExt;
10459
10460 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
10461
10462 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
10463 bool IsIndexSignExt) :
10464 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
10465
10466 bool equalBaseIndex(const BaseIndexOffset &Other) {
10467 return Other.Base == Base && Other.Index == Index &&
10468 Other.IsIndexSignExt == IsIndexSignExt;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010469 }
10470
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010471 /// Parses tree in Ptr for base, index, offset addresses.
10472 static BaseIndexOffset match(SDValue Ptr) {
10473 bool IsIndexSignExt = false;
10474
Juergen Ributzka3db39dc2013-08-21 21:53:38 +000010475 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
10476 // instruction, then it could be just the BASE or everything else we don't
10477 // know how to handle. Just use Ptr as BASE and give up.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010478 if (Ptr->getOpcode() != ISD::ADD)
10479 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10480
Juergen Ributzka3db39dc2013-08-21 21:53:38 +000010481 // We know that we have at least an ADD instruction. Try to pattern match
10482 // the simple case of BASE + OFFSET.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010483 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
10484 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
10485 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10486 IsIndexSignExt);
10487 }
10488
Juergen Ributzka3db39dc2013-08-21 21:53:38 +000010489 // Inside a loop the current BASE pointer is calculated using an ADD and a
Juergen Ributzka11c52c62013-08-28 22:33:58 +000010490 // MUL instruction. In this case Ptr is the actual BASE pointer.
Juergen Ributzka3db39dc2013-08-21 21:53:38 +000010491 // (i64 add (i64 %array_ptr)
10492 // (i64 mul (i64 %induction_var)
10493 // (i64 %element_size)))
Juergen Ributzka11c52c62013-08-28 22:33:58 +000010494 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
Juergen Ributzka3db39dc2013-08-21 21:53:38 +000010495 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
Juergen Ributzka3db39dc2013-08-21 21:53:38 +000010496
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010497 // Look at Base + Index + Offset cases.
10498 SDValue Base = Ptr->getOperand(0);
10499 SDValue IndexOffset = Ptr->getOperand(1);
10500
10501 // Skip signextends.
10502 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10503 IndexOffset = IndexOffset->getOperand(0);
10504 IsIndexSignExt = true;
10505 }
10506
10507 // Either the case of Base + Index (no offset) or something else.
10508 if (IndexOffset->getOpcode() != ISD::ADD)
10509 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10510
10511 // Now we have the case of Base + Index + offset.
10512 SDValue Index = IndexOffset->getOperand(0);
10513 SDValue Offset = IndexOffset->getOperand(1);
10514
10515 if (!isa<ConstantSDNode>(Offset))
10516 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10517
10518 // Ignore signextends.
10519 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10520 Index = Index->getOperand(0);
10521 IsIndexSignExt = true;
10522 } else IsIndexSignExt = false;
10523
10524 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10525 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10526 }
10527};
Benjamin Kramer51f6096c2015-03-23 12:30:58 +000010528} // namespace
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010529
Sanjay Patel37c41c12015-01-22 18:21:26 +000010530bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
10531 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
Quentin Colombet308b1712015-01-27 23:58:01 +000010532 unsigned NumElem, bool IsConstantSrc, bool UseVector) {
Sanjay Patel37c41c12015-01-22 18:21:26 +000010533 // Make sure we have something to merge.
Quentin Colombet308b1712015-01-27 23:58:01 +000010534 if (NumElem < 2)
Sanjay Patel37c41c12015-01-22 18:21:26 +000010535 return false;
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000010536
Sanjay Patel37c41c12015-01-22 18:21:26 +000010537 int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10538 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
Akira Hatanakac6fab802015-04-08 20:34:53 +000010539 unsigned LatestNodeUsed = 0;
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000010540
Quentin Colombet308b1712015-01-27 23:58:01 +000010541 for (unsigned i=0; i < NumElem; ++i) {
Sanjay Patel37c41c12015-01-22 18:21:26 +000010542 // Find a chain for the new wide-store operand. Notice that some
10543 // of the store nodes that we found may not be selected for inclusion
10544 // in the wide store. The chain we use needs to be the chain of the
Akira Hatanakac6fab802015-04-08 20:34:53 +000010545 // latest store node which is *used* and replaced by the wide store.
10546 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
10547 LatestNodeUsed = i;
Sanjay Patel37c41c12015-01-22 18:21:26 +000010548 }
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000010549
Akira Hatanakac6fab802015-04-08 20:34:53 +000010550 // The latest Node in the DAG.
10551 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
Sanjay Patel37c41c12015-01-22 18:21:26 +000010552 SDLoc DL(StoreNodes[0].MemNode);
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000010553
Sanjay Patel37c41c12015-01-22 18:21:26 +000010554 SDValue StoredVal;
10555 if (UseVector) {
Quentin Colombet308b1712015-01-27 23:58:01 +000010556 // Find a legal type for the vector store.
10557 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
Sanjay Patel37c41c12015-01-22 18:21:26 +000010558 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
10559 if (IsConstantSrc) {
10560 // A vector store with a constant source implies that the constant is
10561 // zero; we only handle merging stores of constant zeros because the zero
10562 // can be materialized without a load.
10563 // It may be beneficial to loosen this restriction to allow non-zero
10564 // store merging.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010565 StoredVal = DAG.getConstant(0, DL, Ty);
Sanjay Patel37c41c12015-01-22 18:21:26 +000010566 } else {
10567 SmallVector<SDValue, 8> Ops;
Quentin Colombet308b1712015-01-27 23:58:01 +000010568 for (unsigned i = 0; i < NumElem ; ++i) {
Sanjay Patel37c41c12015-01-22 18:21:26 +000010569 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10570 SDValue Val = St->getValue();
Quentin Colombet308b1712015-01-27 23:58:01 +000010571 // All of the operands of a BUILD_VECTOR must have the same type.
Sanjay Patel37c41c12015-01-22 18:21:26 +000010572 if (Val.getValueType() != MemVT)
10573 return false;
10574 Ops.push_back(Val);
10575 }
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000010576
Sanjay Patel37c41c12015-01-22 18:21:26 +000010577 // Build the extracted vector elements back into a vector.
Quentin Colombet308b1712015-01-27 23:58:01 +000010578 StoredVal = DAG.getNode(ISD::BUILD_VECTOR, DL, Ty, Ops);
Sanjay Patel37c41c12015-01-22 18:21:26 +000010579 }
10580 } else {
10581 // We should always use a vector store when merging extracted vector
10582 // elements, so this path implies a store of constants.
10583 assert(IsConstantSrc && "Merged vector elements should use vector store");
10584
Quentin Colombet308b1712015-01-27 23:58:01 +000010585 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
Sanjay Patel37c41c12015-01-22 18:21:26 +000010586 APInt StoreInt(StoreBW, 0);
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000010587
Sanjay Patel37c41c12015-01-22 18:21:26 +000010588 // Construct a single integer constant which is made of the smaller
10589 // constant inputs.
10590 bool IsLE = TLI.isLittleEndian();
Quentin Colombet308b1712015-01-27 23:58:01 +000010591 for (unsigned i = 0; i < NumElem ; ++i) {
10592 unsigned Idx = IsLE ? (NumElem - 1 - i) : i;
Sanjay Patel37c41c12015-01-22 18:21:26 +000010593 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
10594 SDValue Val = St->getValue();
10595 StoreInt <<= ElementSizeBytes*8;
10596 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
10597 StoreInt |= C->getAPIntValue().zext(StoreBW);
10598 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
10599 StoreInt |= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
10600 } else {
10601 llvm_unreachable("Invalid constant element type");
10602 }
10603 }
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000010604
Sanjay Patel37c41c12015-01-22 18:21:26 +000010605 // Create the new Load and Store operations.
10606 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010607 StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
Sanjay Patel37c41c12015-01-22 18:21:26 +000010608 }
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000010609
Akira Hatanakac6fab802015-04-08 20:34:53 +000010610 SDValue NewStore = DAG.getStore(LatestOp->getChain(), DL, StoredVal,
Sanjay Patel37c41c12015-01-22 18:21:26 +000010611 FirstInChain->getBasePtr(),
10612 FirstInChain->getPointerInfo(),
10613 false, false,
10614 FirstInChain->getAlignment());
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000010615
Akira Hatanakac6fab802015-04-08 20:34:53 +000010616 // Replace the last store with the new store
10617 CombineTo(LatestOp, NewStore);
Sanjay Patel37c41c12015-01-22 18:21:26 +000010618 // Erase all other stores.
Quentin Colombet308b1712015-01-27 23:58:01 +000010619 for (unsigned i = 0; i < NumElem ; ++i) {
Akira Hatanakac6fab802015-04-08 20:34:53 +000010620 if (StoreNodes[i].MemNode == LatestOp)
Sanjay Patel37c41c12015-01-22 18:21:26 +000010621 continue;
10622 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10623 // ReplaceAllUsesWith will replace all uses that existed when it was
10624 // called, but graph optimizations may cause new ones to appear. For
10625 // example, the case in pr14333 looks like
10626 //
10627 // St's chain -> St -> another store -> X
10628 //
10629 // And the only difference from St to the other store is the chain.
10630 // When we change it's chain to be St's chain they become identical,
10631 // get CSEed and the net result is that X is now a use of St.
10632 // Since we know that St is redundant, just iterate.
10633 while (!St->use_empty())
10634 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
10635 deleteAndRecombine(St);
10636 }
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000010637
Sanjay Patel37c41c12015-01-22 18:21:26 +000010638 return true;
10639}
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010640
James Y Knight284e7b32015-05-08 13:47:01 +000010641static bool allowableAlignment(const SelectionDAG &DAG,
10642 const TargetLowering &TLI, EVT EVTTy,
10643 unsigned AS, unsigned Align) {
10644 if (TLI.allowsMisalignedMemoryAccesses(EVTTy, AS, Align))
10645 return true;
10646
10647 Type *Ty = EVTTy.getTypeForEVT(*DAG.getContext());
10648 unsigned ABIAlignment = TLI.getDataLayout()->getPrefTypeAlignment(Ty);
10649 return (Align >= ABIAlignment);
10650}
10651
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010652bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
Paul Robinson093d6e12015-02-26 18:47:57 +000010653 if (OptLevel == CodeGenOpt::None)
10654 return false;
10655
Quentin Colombet308b1712015-01-27 23:58:01 +000010656 EVT MemVT = St->getMemoryVT();
10657 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
Duncan P. N. Exon Smith70eb9c52015-02-14 01:44:41 +000010658 bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
10659 Attribute::NoImplicitFloat);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010660
James Y Knightfca02be2015-05-09 03:13:37 +000010661 // This function cannot currently deal with non-byte-sized memory sizes.
10662 if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
10663 return false;
10664
Quentin Colombet308b1712015-01-27 23:58:01 +000010665 // Don't merge vectors into wider inputs.
10666 if (MemVT.isVector() || !MemVT.isSimple())
10667 return false;
10668
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010669 // Perform an early exit check. Do not bother looking at stored values that
Sanjay Patel37c41c12015-01-22 18:21:26 +000010670 // are not constants, loads, or extracted vector elements.
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010671 SDValue StoredVal = St->getValue();
10672 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
Sanjay Patel37c41c12015-01-22 18:21:26 +000010673 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
10674 isa<ConstantFPSDNode>(StoredVal);
Quentin Colombet308b1712015-01-27 23:58:01 +000010675 bool IsExtractVecEltSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT);
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000010676
Quentin Colombet308b1712015-01-27 23:58:01 +000010677 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecEltSrc)
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010678 return false;
10679
10680 // Only look at ends of store sequences.
Chandler Carruth94bd5532014-07-25 07:23:23 +000010681 SDValue Chain = SDValue(St, 0);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010682 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
10683 return false;
10684
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010685 // This holds the base pointer, index, and the offset in bytes from the base
10686 // pointer.
10687 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010688
10689 // We must have a base and an offset.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010690 if (!BasePtr.Base.getNode())
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010691 return false;
10692
10693 // Do not handle stores to undef base pointers.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010694 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010695 return false;
10696
Nadav Rotem307d7672012-11-29 00:00:08 +000010697 // Save the LoadSDNodes that we find in the chain.
10698 // We need to make sure that these nodes do not interfere with
10699 // any of the store nodes.
10700 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
10701
10702 // Save the StoreSDNodes that we find in the chain.
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010703 SmallVector<MemOpLink, 8> StoreNodes;
Nadav Rotem307d7672012-11-29 00:00:08 +000010704
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010705 // Walk up the chain and look for nodes with offsets from the same
10706 // base pointer. Stop when reaching an instruction with a different kind
10707 // or instruction which has a different base pointer.
10708 unsigned Seq = 0;
10709 StoreSDNode *Index = St;
10710 while (Index) {
10711 // If the chain has more than one use, then we can't reorder the mem ops.
Matt Arsenault197a1e22014-07-25 07:56:42 +000010712 if (Index != St && !SDValue(Index, 0)->hasOneUse())
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010713 break;
10714
10715 // Find the base pointer and offset for this memory node.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010716 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010717
10718 // Check that the base pointer is the same as the original one.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010719 if (!Ptr.equalBaseIndex(BasePtr))
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010720 break;
10721
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010722 // The memory operands must not be volatile.
10723 if (Index->isVolatile() || Index->isIndexed())
10724 break;
10725
10726 // No truncation.
10727 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
10728 if (St->isTruncatingStore())
10729 break;
10730
10731 // The stored memory type must be the same.
10732 if (Index->getMemoryVT() != MemVT)
10733 break;
10734
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010735 // We found a potential memory operand to merge.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010736 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010737
Nadav Rotem307d7672012-11-29 00:00:08 +000010738 // Find the next memory operand in the chain. If the next operand in the
10739 // chain is a store then move up and continue the scan with the next
10740 // memory operand. If the next operand is a load save it and use alias
10741 // information to check if it interferes with anything.
10742 SDNode *NextInChain = Index->getChain().getNode();
10743 while (1) {
Nadav Rotemac450eb2012-12-06 17:34:13 +000010744 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
Nadav Rotem307d7672012-11-29 00:00:08 +000010745 // We found a store node. Use it for the next iteration.
Nadav Rotemac450eb2012-12-06 17:34:13 +000010746 Index = STn;
Nadav Rotem307d7672012-11-29 00:00:08 +000010747 break;
10748 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
Bill Wendling9200bb02013-11-25 18:05:22 +000010749 if (Ldn->isVolatile()) {
Craig Topperc0196b12014-04-14 00:51:57 +000010750 Index = nullptr;
Bill Wendling9200bb02013-11-25 18:05:22 +000010751 break;
10752 }
10753
Nadav Rotem307d7672012-11-29 00:00:08 +000010754 // Save the load node for later. Continue the scan.
10755 AliasLoadNodes.push_back(Ldn);
10756 NextInChain = Ldn->getChain().getNode();
10757 continue;
10758 } else {
Craig Topperc0196b12014-04-14 00:51:57 +000010759 Index = nullptr;
Nadav Rotem307d7672012-11-29 00:00:08 +000010760 break;
10761 }
10762 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010763 }
10764
10765 // Check if there is anything to merge.
10766 if (StoreNodes.size() < 2)
10767 return false;
10768
10769 // Sort the memory operands according to their distance from the base pointer.
10770 std::sort(StoreNodes.begin(), StoreNodes.end(),
Benjamin Kramer3a377bc2014-03-01 11:47:00 +000010771 [](MemOpLink LHS, MemOpLink RHS) {
10772 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
10773 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
10774 LHS.SequenceNum > RHS.SequenceNum);
10775 });
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010776
10777 // Scan the memory operations on the chain and find the first non-consecutive
10778 // store memory address.
10779 unsigned LastConsecutiveStore = 0;
10780 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
Nadav Rotemac450eb2012-12-06 17:34:13 +000010781 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
10782
10783 // Check that the addresses are consecutive starting from the second
10784 // element in the list of stores.
10785 if (i > 0) {
10786 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
10787 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10788 break;
10789 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010790
Nadav Rotem307d7672012-11-29 00:00:08 +000010791 bool Alias = false;
10792 // Check if this store interferes with any of the loads that we found.
10793 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
10794 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
10795 Alias = true;
10796 break;
10797 }
Nadav Rotem307d7672012-11-29 00:00:08 +000010798 // We found a load that alias with this store. Stop the sequence.
10799 if (Alias)
10800 break;
10801
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010802 // Mark this node as useful.
10803 LastConsecutiveStore = i;
10804 }
10805
10806 // The node with the lowest store address.
10807 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
James Y Knight284e7b32015-05-08 13:47:01 +000010808 unsigned FirstStoreAS = FirstInChain->getAddressSpace();
10809 unsigned FirstStoreAlign = FirstInChain->getAlignment();
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010810
10811 // Store the constants into memory as one consecutive store.
Sanjay Patel37c41c12015-01-22 18:21:26 +000010812 if (IsConstantSrc) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010813 unsigned LastLegalType = 0;
Nadav Rotemb27777f2012-10-04 22:35:15 +000010814 unsigned LastLegalVectorType = 0;
10815 bool NonZero = false;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010816 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10817 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10818 SDValue StoredVal = St->getValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +000010819
10820 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
Benjamin Kramer62f7fb92012-10-05 18:19:44 +000010821 NonZero |= !C->isNullValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +000010822 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
Benjamin Kramer62f7fb92012-10-05 18:19:44 +000010823 NonZero |= !C->getConstantFPValue()->isNullValue();
Nadav Rotemb27777f2012-10-04 22:35:15 +000010824 } else {
Alp Tokerf907b892013-12-05 05:44:44 +000010825 // Non-constant.
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010826 break;
Nadav Rotemb27777f2012-10-04 22:35:15 +000010827 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010828
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010829 // Find a legal type for the constant store.
10830 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10831 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
James Y Knight284e7b32015-05-08 13:47:01 +000010832 if (TLI.isTypeLegal(StoreTy) &&
10833 allowableAlignment(DAG, TLI, StoreTy, FirstStoreAS,
10834 FirstStoreAlign)) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010835 LastLegalType = i+1;
Arnold Schwaighoferd6c6e862013-04-02 15:58:51 +000010836 // Or check whether a truncstore is legal.
James Y Knight284e7b32015-05-08 13:47:01 +000010837 } else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10838 TargetLowering::TypePromoteInteger) {
Arnold Schwaighoferd6c6e862013-04-02 15:58:51 +000010839 EVT LegalizedStoredValueTy =
10840 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
James Y Knight284e7b32015-05-08 13:47:01 +000010841 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
10842 allowableAlignment(DAG, TLI, LegalizedStoredValueTy, FirstStoreAS,
10843 FirstStoreAlign)) {
10844 LastLegalType = i + 1;
10845 }
Arnold Schwaighoferd6c6e862013-04-02 15:58:51 +000010846 }
Nadav Rotemb27777f2012-10-04 22:35:15 +000010847
10848 // Find a legal type for the vector store.
10849 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
James Y Knight284e7b32015-05-08 13:47:01 +000010850 if (TLI.isTypeLegal(Ty) &&
10851 allowableAlignment(DAG, TLI, Ty, FirstStoreAS, FirstStoreAlign)) {
Nadav Rotemb27777f2012-10-04 22:35:15 +000010852 LastLegalVectorType = i + 1;
James Y Knight284e7b32015-05-08 13:47:01 +000010853 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010854 }
10855
Bob Wilson3365b802012-12-20 01:36:20 +000010856 // We only use vectors if the constant is known to be zero and the
10857 // function is not marked with the noimplicitfloat attribute.
Nadav Rotem495b1a42013-02-14 18:28:52 +000010858 if (NonZero || NoVectors)
Nadav Rotemb27777f2012-10-04 22:35:15 +000010859 LastLegalVectorType = 0;
10860
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010861 // Check if we found a legal integer type to store.
Nadav Rotemb27777f2012-10-04 22:35:15 +000010862 if (LastLegalType == 0 && LastLegalVectorType == 0)
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010863 return false;
10864
Nadav Rotem495b1a42013-02-14 18:28:52 +000010865 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
Nadav Rotemb27777f2012-10-04 22:35:15 +000010866 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
10867
Sanjay Patel37c41c12015-01-22 18:21:26 +000010868 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10869 true, UseVector);
10870 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010871
Sanjay Patel37c41c12015-01-22 18:21:26 +000010872 // When extracting multiple vector elements, try to store them
10873 // in one vector store rather than a sequence of scalar stores.
Quentin Colombet308b1712015-01-27 23:58:01 +000010874 if (IsExtractVecEltSrc) {
10875 unsigned NumElem = 0;
Sanjay Patel37c41c12015-01-22 18:21:26 +000010876 for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
10877 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
Quentin Colombet308b1712015-01-27 23:58:01 +000010878 SDValue StoredVal = St->getValue();
Sanjay Patel37c41c12015-01-22 18:21:26 +000010879 // This restriction could be loosened.
10880 // Bail out if any stored values are not elements extracted from a vector.
10881 // It should be possible to handle mixed sources, but load sources need
10882 // more careful handling (see the block of code below that handles
10883 // consecutive loads).
Quentin Colombet308b1712015-01-27 23:58:01 +000010884 if (StoredVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
Sanjay Patel37c41c12015-01-22 18:21:26 +000010885 return false;
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000010886
Nadav Rotemb27777f2012-10-04 22:35:15 +000010887 // Find a legal type for the vector store.
Quentin Colombet308b1712015-01-27 23:58:01 +000010888 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
James Y Knight284e7b32015-05-08 13:47:01 +000010889 if (TLI.isTypeLegal(Ty) &&
10890 allowableAlignment(DAG, TLI, Ty, FirstStoreAS, FirstStoreAlign))
Quentin Colombet308b1712015-01-27 23:58:01 +000010891 NumElem = i + 1;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010892 }
10893
Quentin Colombet308b1712015-01-27 23:58:01 +000010894 return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
Sanjay Patel37c41c12015-01-22 18:21:26 +000010895 false, true);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010896 }
10897
10898 // Below we handle the case of multiple consecutive stores that
10899 // come from multiple consecutive loads. We merge them into a single
10900 // wide load and a single wide store.
10901
10902 // Look for load nodes which are used by the stored values.
10903 SmallVector<MemOpLink, 8> LoadNodes;
10904
10905 // Find acceptable loads. Loads need to have the same chain (token factor),
10906 // must not be zext, volatile, indexed, and they must be consecutive.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010907 BaseIndexOffset LdBasePtr;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010908 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10909 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10910 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
10911 if (!Ld) break;
10912
10913 // Loads must only have one use.
10914 if (!Ld->hasNUsesOfValue(1, 0))
10915 break;
10916
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010917 // The memory operands must not be volatile.
10918 if (Ld->isVolatile() || Ld->isIndexed())
10919 break;
10920
10921 // We do not accept ext loads.
10922 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
10923 break;
10924
10925 // The stored memory type must be the same.
10926 if (Ld->getMemoryVT() != MemVT)
10927 break;
10928
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010929 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010930 // If this is not the first ptr that we check.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010931 if (LdBasePtr.Base.getNode()) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010932 // The base ptr must be the same.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010933 if (!LdPtr.equalBaseIndex(LdBasePtr))
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010934 break;
10935 } else {
10936 // Check that all other base pointers are the same as this one.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010937 LdBasePtr = LdPtr;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010938 }
10939
10940 // We found a potential memory operand to merge.
Arnold Schwaighofer67523662013-04-01 18:12:58 +000010941 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010942 }
10943
10944 if (LoadNodes.size() < 2)
10945 return false;
10946
James Molloyce45be02014-08-02 14:51:24 +000010947 // If we have load/store pair instructions and we only have two values,
10948 // don't bother.
10949 unsigned RequiredAlignment;
10950 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
10951 St->getAlignment() >= RequiredAlignment)
10952 return false;
10953
James Y Knight284e7b32015-05-08 13:47:01 +000010954 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
10955 unsigned FirstLoadAS = FirstLoad->getAddressSpace();
10956 unsigned FirstLoadAlign = FirstLoad->getAlignment();
10957
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010958 // Scan the memory operations on the chain and find the first non-consecutive
10959 // load memory address. These variables hold the index in the store node
10960 // array.
10961 unsigned LastConsecutiveLoad = 0;
10962 // This variable refers to the size and not index in the array.
10963 unsigned LastLegalVectorType = 0;
10964 unsigned LastLegalIntegerType = 0;
10965 StartAddress = LoadNodes[0].OffsetFromBase;
James Y Knight284e7b32015-05-08 13:47:01 +000010966 SDValue FirstChain = FirstLoad->getChain();
Nadav Rotemac920662012-10-03 19:30:31 +000010967 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
10968 // All loads much share the same chain.
10969 if (LoadNodes[i].MemNode->getChain() != FirstChain)
10970 break;
Nadav Rotem495b1a42013-02-14 18:28:52 +000010971
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010972 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
10973 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10974 break;
10975 LastConsecutiveLoad = i;
10976
10977 // Find a legal type for the vector store.
10978 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
James Y Knight284e7b32015-05-08 13:47:01 +000010979 if (TLI.isTypeLegal(StoreTy) &&
10980 allowableAlignment(DAG, TLI, StoreTy, FirstStoreAS, FirstStoreAlign) &&
10981 allowableAlignment(DAG, TLI, StoreTy, FirstLoadAS, FirstLoadAlign)) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010982 LastLegalVectorType = i + 1;
James Y Knight284e7b32015-05-08 13:47:01 +000010983 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010984
10985 // Find a legal type for the integer store.
10986 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10987 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
James Y Knight284e7b32015-05-08 13:47:01 +000010988 if (TLI.isTypeLegal(StoreTy) &&
10989 allowableAlignment(DAG, TLI, StoreTy, FirstStoreAS, FirstStoreAlign) &&
10990 allowableAlignment(DAG, TLI, StoreTy, FirstLoadAS, FirstLoadAlign))
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000010991 LastLegalIntegerType = i + 1;
Arnold Schwaighoferd6c6e862013-04-02 15:58:51 +000010992 // Or check whether a truncstore and extload is legal.
10993 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10994 TargetLowering::TypePromoteInteger) {
10995 EVT LegalizedStoredValueTy =
10996 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
10997 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +000010998 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
10999 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
James Y Knight284e7b32015-05-08 13:47:01 +000011000 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11001 allowableAlignment(DAG, TLI, LegalizedStoredValueTy, FirstStoreAS,
11002 FirstStoreAlign) &&
11003 allowableAlignment(DAG, TLI, LegalizedStoredValueTy, FirstLoadAS,
11004 FirstLoadAlign))
Arnold Schwaighoferd6c6e862013-04-02 15:58:51 +000011005 LastLegalIntegerType = i+1;
11006 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000011007 }
11008
11009 // Only use vector types if the vector type is larger than the integer type.
11010 // If they are the same, use integers.
Nadav Rotem495b1a42013-02-14 18:28:52 +000011011 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000011012 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
11013
11014 // We add +1 here because the LastXXX variables refer to location while
11015 // the NumElem refers to array/index size.
11016 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
11017 NumElem = std::min(LastLegalType, NumElem);
11018
11019 if (NumElem < 2)
11020 return false;
11021
Akira Hatanakac6fab802015-04-08 20:34:53 +000011022 // The latest Node in the DAG.
11023 unsigned LatestNodeUsed = 0;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000011024 for (unsigned i=1; i<NumElem; ++i) {
11025 // Find a chain for the new wide-store operand. Notice that some
11026 // of the store nodes that we found may not be selected for inclusion
11027 // in the wide store. The chain we use needs to be the chain of the
Akira Hatanakac6fab802015-04-08 20:34:53 +000011028 // latest store node which is *used* and replaced by the wide store.
11029 if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11030 LatestNodeUsed = i;
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000011031 }
11032
Akira Hatanakac6fab802015-04-08 20:34:53 +000011033 LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11034
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000011035 // Find if it is better to use vectors or integers to load and store
11036 // to memory.
11037 EVT JointMemOpVT;
11038 if (UseVectorTy) {
11039 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
11040 } else {
11041 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
11042 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
11043 }
11044
Andrew Trickef9de2a2013-05-25 02:42:55 +000011045 SDLoc LoadDL(LoadNodes[0].MemNode);
11046 SDLoc StoreDL(StoreNodes[0].MemNode);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000011047
James Y Knight284e7b32015-05-08 13:47:01 +000011048 SDValue NewLoad = DAG.getLoad(
11049 JointMemOpVT, LoadDL, FirstLoad->getChain(), FirstLoad->getBasePtr(),
11050 FirstLoad->getPointerInfo(), false, false, false, FirstLoadAlign);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000011051
James Y Knight284e7b32015-05-08 13:47:01 +000011052 SDValue NewStore = DAG.getStore(
11053 LatestOp->getChain(), StoreDL, NewLoad, FirstInChain->getBasePtr(),
11054 FirstInChain->getPointerInfo(), false, false, FirstStoreAlign);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000011055
Nadav Rotemac920662012-10-03 19:30:31 +000011056 // Replace one of the loads with the new load.
11057 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
11058 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
11059 SDValue(NewLoad.getNode(), 1));
11060
11061 // Remove the rest of the load chains.
11062 for (unsigned i = 1; i < NumElem ; ++i) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000011063 // Replace all chain users of the old load nodes with the chain of the new
11064 // load node.
11065 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
Nadav Rotemac920662012-10-03 19:30:31 +000011066 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
11067 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000011068
Akira Hatanakac6fab802015-04-08 20:34:53 +000011069 // Replace the last store with the new store.
11070 CombineTo(LatestOp, NewStore);
Nadav Rotemac920662012-10-03 19:30:31 +000011071 // Erase all other stores.
11072 for (unsigned i = 0; i < NumElem ; ++i) {
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000011073 // Remove all Store nodes.
Akira Hatanakac6fab802015-04-08 20:34:53 +000011074 if (StoreNodes[i].MemNode == LatestOp)
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000011075 continue;
11076 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11077 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
Chandler Carruth18066972014-08-02 10:02:07 +000011078 deleteAndRecombine(St);
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000011079 }
11080
11081 return true;
11082}
11083
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011084SDValue DAGCombiner::visitSTORE(SDNode *N) {
Evan Chengab51cf22006-10-13 21:14:26 +000011085 StoreSDNode *ST = cast<StoreSDNode>(N);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011086 SDValue Chain = ST->getChain();
11087 SDValue Value = ST->getValue();
11088 SDValue Ptr = ST->getBasePtr();
Scott Michelcf0da6c2009-02-17 22:15:04 +000011089
Evan Chenga4cf58a2007-05-07 21:27:48 +000011090 // If this is a store of a bit convert, store the input value if the
Evan Chengf325c2a2007-05-09 21:49:47 +000011091 // resultant store does not need a higher alignment than the original.
Wesley Peck527da1b2010-11-23 03:31:01 +000011092 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +000011093 ST->isUnindexed()) {
Dan Gohmane7fe80f2009-02-20 23:29:13 +000011094 unsigned OrigAlign = ST->getAlignment();
Owen Anderson53aa7a92009-08-10 22:56:29 +000011095 EVT SVT = Value.getOperand(0).getValueType();
Micah Villmowcdfe20b2012-10-08 16:38:25 +000011096 unsigned Align = TLI.getDataLayout()->
Owen Anderson117c9e82009-08-12 00:36:31 +000011097 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
Duncan Sands8651e9c2008-06-13 19:07:40 +000011098 if (Align <= OrigAlign &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +000011099 ((!LegalOperations && !ST->isVolatile()) ||
Dan Gohman4aa18462009-01-28 17:46:25 +000011100 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
Andrew Trickef9de2a2013-05-25 02:42:55 +000011101 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
Chris Lattner676c61d2010-09-21 18:41:36 +000011102 Ptr, ST->getPointerInfo(), ST->isVolatile(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +000011103 ST->isNonTemporal(), OrigAlign,
Hal Finkelcc39b672014-07-24 12:16:19 +000011104 ST->getAAInfo());
Jim Laskeyd07be232006-09-25 16:29:54 +000011105 }
Owen Andersona5192842011-04-14 17:30:49 +000011106
Chris Lattner41c80e82011-04-09 02:32:02 +000011107 // Turn 'store undef, Ptr' -> nothing.
11108 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
11109 return Chain;
Duncan Sands8651e9c2008-06-13 19:07:40 +000011110
Nate Begeman8e20c762006-12-11 02:23:46 +000011111 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
Nate Begeman8e20c762006-12-11 02:23:46 +000011112 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
Duncan Sands8651e9c2008-06-13 19:07:40 +000011113 // NOTE: If the original store is volatile, this transform must not increase
11114 // the number of stores. For example, on x86-32 an f64 can be stored in one
11115 // processor operation but an i64 (which is not legal) requires two. So the
11116 // transform should not be done in this case.
Evan Cheng21836982006-12-11 17:25:19 +000011117 if (Value.getOpcode() != ISD::TargetConstantFP) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011118 SDValue Tmp;
Craig Topperd9c27832013-08-15 02:44:19 +000011119 switch (CFP->getSimpleValueType(0).SimpleTy) {
Torok Edwinfbcc6632009-07-14 16:55:14 +000011120 default: llvm_unreachable("Unknown FP type");
Pete Cooper5b614222012-06-21 18:00:39 +000011121 case MVT::f16: // We don't do this for these yet.
11122 case MVT::f80:
Owen Anderson9f944592009-08-11 20:47:22 +000011123 case MVT::f128:
11124 case MVT::ppcf128:
Dale Johannesenaf12b572007-09-18 18:36:59 +000011125 break;
Owen Anderson9f944592009-08-11 20:47:22 +000011126 case MVT::f32:
Chris Lattner4041ab62010-04-15 04:48:01 +000011127 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
Owen Anderson9f944592009-08-11 20:47:22 +000011128 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000011129 ;
Dale Johannesen028084e2007-09-12 03:30:33 +000011130 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000011131 bitcastToAPInt().getZExtValue(), SDLoc(CFP),
11132 MVT::i32);
Andrew Trickef9de2a2013-05-25 02:42:55 +000011133 return DAG.getStore(Chain, SDLoc(N), Tmp,
Richard Sandiford39c1ce42013-10-28 11:17:59 +000011134 Ptr, ST->getMemOperand());
Chris Lattnerb7524b62006-12-12 04:16:14 +000011135 }
11136 break;
Owen Anderson9f944592009-08-11 20:47:22 +000011137 case MVT::f64:
Chris Lattner4041ab62010-04-15 04:48:01 +000011138 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
Dan Gohman4aa18462009-01-28 17:46:25 +000011139 !ST->isVolatile()) ||
Owen Anderson9f944592009-08-11 20:47:22 +000011140 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000011141 ;
Dale Johannesen54306fe2008-10-09 18:53:47 +000011142 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000011143 getZExtValue(), SDLoc(CFP), MVT::i64);
Andrew Trickef9de2a2013-05-25 02:42:55 +000011144 return DAG.getStore(Chain, SDLoc(N), Tmp,
Richard Sandiford39c1ce42013-10-28 11:17:59 +000011145 Ptr, ST->getMemOperand());
Chris Lattner41c80e82011-04-09 02:32:02 +000011146 }
Owen Andersona5192842011-04-14 17:30:49 +000011147
Chris Lattner41c80e82011-04-09 02:32:02 +000011148 if (!ST->isVolatile() &&
11149 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
Duncan Sands1826ded2007-10-28 12:59:45 +000011150 // Many FP stores are not made apparent until after legalize, e.g. for
Chris Lattnerb7524b62006-12-12 04:16:14 +000011151 // argument passing. Since this is so common, custom legalize the
11152 // 64-bit integer store into two 32-bit stores.
Dale Johannesen54306fe2008-10-09 18:53:47 +000011153 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000011154 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
11155 SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
Duncan Sands7377f5f2008-02-11 10:37:04 +000011156 if (TLI.isBigEndian()) std::swap(Lo, Hi);
Chris Lattnerb7524b62006-12-12 04:16:14 +000011157
Dan Gohman2af30632007-07-09 22:18:38 +000011158 unsigned Alignment = ST->getAlignment();
11159 bool isVolatile = ST->isVolatile();
David Greene39c6d012010-02-15 17:00:31 +000011160 bool isNonTemporal = ST->isNonTemporal();
Hal Finkelcc39b672014-07-24 12:16:19 +000011161 AAMDNodes AAInfo = ST->getAAInfo();
Dan Gohman2af30632007-07-09 22:18:38 +000011162
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000011163 SDLoc DL(N);
11164
Andrew Trickef9de2a2013-05-25 02:42:55 +000011165 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
Chris Lattner676c61d2010-09-21 18:41:36 +000011166 Ptr, ST->getPointerInfo(),
David Greene39c6d012010-02-15 17:00:31 +000011167 isVolatile, isNonTemporal,
Hal Finkelcc39b672014-07-24 12:16:19 +000011168 ST->getAlignment(), AAInfo);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000011169 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
11170 DAG.getConstant(4, DL, Ptr.getValueType()));
Duncan Sands1826ded2007-10-28 12:59:45 +000011171 Alignment = MinAlign(Alignment, 4U);
Andrew Trickef9de2a2013-05-25 02:42:55 +000011172 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
Chris Lattner676c61d2010-09-21 18:41:36 +000011173 Ptr, ST->getPointerInfo().getWithOffset(4),
11174 isVolatile, isNonTemporal,
Hal Finkelcc39b672014-07-24 12:16:19 +000011175 Alignment, AAInfo);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000011176 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
Bill Wendling27d9dd42009-01-30 23:36:47 +000011177 St0, St1);
Chris Lattnerb7524b62006-12-12 04:16:14 +000011178 }
Bill Wendling27d9dd42009-01-30 23:36:47 +000011179
Chris Lattnerb7524b62006-12-12 04:16:14 +000011180 break;
Evan Cheng21836982006-12-11 17:25:19 +000011181 }
Nate Begeman8e20c762006-12-11 02:23:46 +000011182 }
Nate Begeman8e20c762006-12-11 02:23:46 +000011183 }
11184
Evan Cheng43cd9e32010-04-01 06:04:33 +000011185 // Try to infer better alignment information than the store already has.
11186 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
Evan Cheng4a5b2042011-11-28 22:37:34 +000011187 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
Owen Andersondb420122015-03-19 22:48:57 +000011188 if (Align > ST->getAlignment()) {
11189 SDValue NewStore =
11190 DAG.getTruncStore(Chain, SDLoc(N), Value,
Evan Cheng4a5b2042011-11-28 22:37:34 +000011191 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
Richard Sandiford39c1ce42013-10-28 11:17:59 +000011192 ST->isVolatile(), ST->isNonTemporal(), Align,
Hal Finkelcc39b672014-07-24 12:16:19 +000011193 ST->getAAInfo());
Owen Andersondb420122015-03-19 22:48:57 +000011194 if (NewStore.getNode() != N)
11195 return CombineTo(ST, NewStore, true);
11196 }
Evan Cheng43cd9e32010-04-01 06:04:33 +000011197 }
11198 }
11199
Evan Chengd42641c2011-02-02 01:06:55 +000011200 // Try transforming a pair floating point load / store ops to integer
11201 // load / store ops.
11202 SDValue NewST = TransformFPLoadStorePair(N);
11203 if (NewST.getNode())
11204 return NewST;
11205
Eric Christopherf55d4712014-10-08 23:38:39 +000011206 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11207 : DAG.getSubtarget().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +000011208#ifndef NDEBUG
11209 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11210 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11211 UseAA = false;
11212#endif
Hal Finkelccc18e12014-01-24 18:25:26 +000011213 if (UseAA && ST->isUnindexed()) {
Jim Laskeyd07be232006-09-25 16:29:54 +000011214 // Walk up chain skipping non-aliasing memory nodes.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011215 SDValue BetterChain = FindBetterChain(N, Chain);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011216
Jim Laskey708d0db2006-10-04 16:53:27 +000011217 // If there is a better chain.
Jim Laskeyd07be232006-09-25 16:29:54 +000011218 if (Chain != BetterChain) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011219 SDValue ReplStore;
Nate Begeman879d8f12009-09-15 00:18:30 +000011220
11221 // Replace the chain to avoid dependency.
Jim Laskey3bf4f3b2006-10-14 12:14:27 +000011222 if (ST->isTruncatingStore()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011223 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
Richard Sandiford39c1ce42013-10-28 11:17:59 +000011224 ST->getMemoryVT(), ST->getMemOperand());
Jim Laskey3bf4f3b2006-10-14 12:14:27 +000011225 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011226 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
Richard Sandiford39c1ce42013-10-28 11:17:59 +000011227 ST->getMemOperand());
Jim Laskey3bf4f3b2006-10-14 12:14:27 +000011228 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011229
Jim Laskeyd07be232006-09-25 16:29:54 +000011230 // Create token to keep both nodes around.
Andrew Trickef9de2a2013-05-25 02:42:55 +000011231 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
Owen Anderson9f944592009-08-11 20:47:22 +000011232 MVT::Other, Chain, ReplStore);
Bill Wendling27d9dd42009-01-30 23:36:47 +000011233
Nate Begeman879d8f12009-09-15 00:18:30 +000011234 // Make sure the new and old chains are cleaned up.
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011235 AddToWorklist(Token.getNode());
Nate Begeman879d8f12009-09-15 00:18:30 +000011236
Jim Laskeydcf983c2006-10-13 23:32:28 +000011237 // Don't add users to work list.
11238 return CombineTo(N, Token, false);
Jim Laskeyd07be232006-09-25 16:29:54 +000011239 }
Jim Laskey5d19d592006-09-21 16:28:59 +000011240 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011241
Evan Cheng33157702006-11-05 09:31:14 +000011242 // Try transforming N to an indexed store.
Evan Cheng60c68462006-11-07 09:03:05 +000011243 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011244 return SDValue(N, 0);
Evan Cheng33157702006-11-05 09:31:14 +000011245
Chris Lattner3f9c6a72007-12-29 06:26:16 +000011246 // FIXME: is there such a thing as a truncating indexed store?
Chris Lattner1ea55cf2008-01-17 19:59:44 +000011247 if (ST->isTruncatingStore() && ST->isUnindexed() &&
Nadav Rotemd2d9bdb2011-06-15 11:19:12 +000011248 Value.getValueType().isInteger()) {
Chris Lattner5e6fe052007-10-13 06:35:54 +000011249 // See if we can simplify the input to this truncstore with knowledge that
11250 // only the low bits are being used. For example:
11251 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
Scott Michelcf0da6c2009-02-17 22:15:04 +000011252 SDValue Shorter =
Dan Gohman1f372ed2008-02-25 21:11:39 +000011253 GetDemandedBits(Value,
Nadav Rotemd2d9bdb2011-06-15 11:19:12 +000011254 APInt::getLowBitsSet(
11255 Value.getValueType().getScalarType().getSizeInBits(),
11256 ST->getMemoryVT().getScalarType().getSizeInBits()));
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011257 AddToWorklist(Value.getNode());
Gabor Greiff304a7a2008-08-28 21:40:38 +000011258 if (Shorter.getNode())
Andrew Trickef9de2a2013-05-25 02:42:55 +000011259 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
Richard Sandiford39c1ce42013-10-28 11:17:59 +000011260 Ptr, ST->getMemoryVT(), ST->getMemOperand());
Scott Michelcf0da6c2009-02-17 22:15:04 +000011261
Chris Lattnerf47e3062007-10-13 06:58:48 +000011262 // Otherwise, see if we can simplify the operation with
11263 // SimplifyDemandedBits, which only works if the value has a single use.
Dan Gohmanae2b6fb2008-02-27 00:25:32 +000011264 if (SimplifyDemandedBits(Value,
Eric Christopherd9e8eac2010-12-09 04:48:06 +000011265 APInt::getLowBitsSet(
11266 Value.getValueType().getScalarType().getSizeInBits(),
11267 ST->getMemoryVT().getScalarType().getSizeInBits())))
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011268 return SDValue(N, 0);
Chris Lattner5e6fe052007-10-13 06:35:54 +000011269 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011270
Chris Lattner3f9c6a72007-12-29 06:26:16 +000011271 // If this is a load followed by a store to the same location, then the store
11272 // is dead/noop.
11273 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
Dan Gohman47a7d6f2008-01-30 00:15:11 +000011274 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +000011275 ST->isUnindexed() && !ST->isVolatile() &&
Chris Lattner51b01bf2008-01-08 23:08:06 +000011276 // There can't be any side effects between the load and store, such as
11277 // a call or store.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011278 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
Chris Lattner3f9c6a72007-12-29 06:26:16 +000011279 // The store is dead, remove it.
11280 return Chain;
11281 }
11282 }
Duncan Sands8651e9c2008-06-13 19:07:40 +000011283
James Molloy463db9a2014-09-27 17:02:54 +000011284 // If this is a store followed by a store with the same value to the same
11285 // location, then the store is dead/noop.
11286 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
11287 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
11288 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
11289 ST1->isUnindexed() && !ST1->isVolatile()) {
11290 // The store is dead, remove it.
11291 return Chain;
11292 }
11293 }
11294
Chris Lattner1ea55cf2008-01-17 19:59:44 +000011295 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
11296 // truncating store. We can do this even if this is already a truncstore.
11297 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
Gabor Greiff304a7a2008-08-28 21:40:38 +000011298 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
Chris Lattner1ea55cf2008-01-17 19:59:44 +000011299 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
Dan Gohman47a7d6f2008-01-30 00:15:11 +000011300 ST->getMemoryVT())) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000011301 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
Richard Sandiford39c1ce42013-10-28 11:17:59 +000011302 Ptr, ST->getMemoryVT(), ST->getMemOperand());
Chris Lattner1ea55cf2008-01-17 19:59:44 +000011303 }
Duncan Sands8651e9c2008-06-13 19:07:40 +000011304
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000011305 // Only perform this optimization before the types are legal, because we
Nadav Rotemb27777f2012-10-04 22:35:15 +000011306 // don't want to perform this optimization on every DAGCombine invocation.
Nadav Rotem1157e142012-12-02 17:14:09 +000011307 if (!LegalTypes) {
11308 bool EverChanged = false;
11309
11310 do {
11311 // There can be multiple store sequences on the same chain.
11312 // Keep trying to merge store sequences until we are unable to do so
11313 // or until we merge the last store on the chain.
11314 bool Changed = MergeConsecutiveStores(ST);
11315 EverChanged |= Changed;
11316 if (!Changed) break;
11317 } while (ST->getOpcode() != ISD::DELETED_NODE);
11318
11319 if (EverChanged)
11320 return SDValue(N, 0);
11321 }
Nadav Rotem7cbc12a2012-10-03 16:11:15 +000011322
Evan Chenga9cda8a2009-05-28 00:35:15 +000011323 return ReduceLoadOpStoreWidth(N);
Chris Lattner04c73702005-10-10 22:31:19 +000011324}
11325
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011326SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
11327 SDValue InVec = N->getOperand(0);
11328 SDValue InVal = N->getOperand(1);
11329 SDValue EltNo = N->getOperand(2);
Andrew Trickef9de2a2013-05-25 02:42:55 +000011330 SDLoc dl(N);
Scott Michelcf0da6c2009-02-17 22:15:04 +000011331
Bob Wilson42603952010-05-19 23:42:58 +000011332 // If the inserted element is an UNDEF, just use the input vector.
11333 if (InVal.getOpcode() == ISD::UNDEF)
11334 return InVec;
11335
Nadav Rotemdb2f5482011-02-12 14:40:33 +000011336 EVT VT = InVec.getValueType();
11337
Owen Andersonb2c80da2011-02-25 21:41:48 +000011338 // If we can't generate a legal BUILD_VECTOR, exit
Nadav Rotemdb2f5482011-02-12 14:40:33 +000011339 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
11340 return SDValue();
11341
Eli Friedmanb7910b72011-09-09 21:04:06 +000011342 // Check that we know which element is being inserted
11343 if (!isa<ConstantSDNode>(EltNo))
11344 return SDValue();
11345 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +000011346
Andrea Di Biagiof99dd642014-06-09 16:54:41 +000011347 // Canonicalize insert_vector_elt dag nodes.
11348 // Example:
11349 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
11350 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
11351 //
11352 // Do this only if the child insert_vector node has one use; also
11353 // do this only if indices are both constants and Idx1 < Idx0.
11354 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
11355 && isa<ConstantSDNode>(InVec.getOperand(2))) {
11356 unsigned OtherElt =
11357 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
11358 if (Elt < OtherElt) {
11359 // Swap nodes.
11360 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
11361 InVec.getOperand(0), InVal, EltNo);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011362 AddToWorklist(NewOp.getNode());
Andrea Di Biagiof99dd642014-06-09 16:54:41 +000011363 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
11364 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
11365 }
11366 }
11367
Eli Friedmanb7910b72011-09-09 21:04:06 +000011368 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
11369 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
11370 // vector elements.
11371 SmallVector<SDValue, 8> Ops;
Quentin Colombet6bf4baa2013-07-30 00:24:09 +000011372 // Do not combine these two vectors if the output vector will not replace
11373 // the input vector.
11374 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
Eli Friedmanb7910b72011-09-09 21:04:06 +000011375 Ops.append(InVec.getNode()->op_begin(),
11376 InVec.getNode()->op_end());
11377 } else if (InVec.getOpcode() == ISD::UNDEF) {
11378 unsigned NElts = VT.getVectorNumElements();
11379 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
11380 } else {
11381 return SDValue();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011382 }
Eli Friedmanb7910b72011-09-09 21:04:06 +000011383
11384 // Insert the element
11385 if (Elt < Ops.size()) {
11386 // All the operands of BUILD_VECTOR must have the same type;
11387 // we enforce that here.
11388 EVT OpVT = Ops[0].getValueType();
11389 if (InVal.getValueType() != OpVT)
11390 InVal = OpVT.bitsGT(InVal.getValueType()) ?
11391 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
11392 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
11393 Ops[Elt] = InVal;
11394 }
11395
11396 // Return the new vector
Craig Topper48d114b2014-04-26 18:35:24 +000011397 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
Chris Lattner5336a592006-03-19 01:27:56 +000011398}
11399
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +000011400SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
11401 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
11402 EVT ResultVT = EVE->getValueType(0);
11403 EVT VecEltVT = InVecVT.getVectorElementType();
11404 unsigned Align = OriginalLoad->getAlignment();
11405 unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
11406 VecEltVT.getTypeForEVT(*DAG.getContext()));
11407
11408 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
11409 return SDValue();
11410
11411 Align = NewAlign;
11412
11413 SDValue NewPtr = OriginalLoad->getBasePtr();
11414 SDValue Offset;
11415 EVT PtrType = NewPtr.getValueType();
11416 MachinePointerInfo MPI;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000011417 SDLoc DL(EVE);
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +000011418 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
11419 int Elt = ConstEltNo->getZExtValue();
11420 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000011421 Offset = DAG.getConstant(PtrOff, DL, PtrType);
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +000011422 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
11423 } else {
Ulrich Weigand9958c482015-05-05 19:34:10 +000011424 Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +000011425 Offset = DAG.getNode(
Ulrich Weigand9958c482015-05-05 19:34:10 +000011426 ISD::MUL, DL, PtrType, Offset,
11427 DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +000011428 MPI = OriginalLoad->getPointerInfo();
11429 }
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000011430 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +000011431
11432 // The replacement we need to do here is a little tricky: we need to
11433 // replace an extractelement of a load with a load.
11434 // Use ReplaceAllUsesOfValuesWith to do the replacement.
11435 // Note that this replacement assumes that the extractvalue is the only
11436 // use of the load; that's okay because we don't want to perform this
11437 // transformation in other cases anyway.
11438 SDValue Load;
11439 SDValue Chain;
11440 if (ResultVT.bitsGT(VecEltVT)) {
11441 // If the result type of vextract is wider than the load, then issue an
11442 // extending load instead.
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +000011443 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
11444 VecEltVT)
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +000011445 ? ISD::ZEXTLOAD
11446 : ISD::EXTLOAD;
11447 Load = DAG.getExtLoad(
11448 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
11449 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11450 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11451 Chain = Load.getValue(1);
11452 } else {
11453 Load = DAG.getLoad(
11454 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
11455 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11456 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11457 Chain = Load.getValue(1);
11458 if (ResultVT.bitsLT(VecEltVT))
11459 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
11460 else
11461 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
11462 }
11463 WorklistRemover DeadNodes(*this);
11464 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
11465 SDValue To[] = { Load, Chain };
11466 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
11467 // Since we're explicitly calling ReplaceAllUses, add the new node to the
11468 // worklist explicitly as well.
11469 AddToWorklist(Load.getNode());
11470 AddUsersToWorklist(Load.getNode()); // Add users too
11471 // Make sure to revisit this node to clean it up; it will usually be dead.
11472 AddToWorklist(EVE);
11473 ++OpsNarrowed;
11474 return SDValue(EVE, 0);
11475}
11476
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011477SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
Mon P Wangca6d6de2009-01-17 00:07:25 +000011478 // (vextract (scalar_to_vector val, 0) -> val
11479 SDValue InVec = N->getOperand(0);
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000011480 EVT VT = InVec.getValueType();
11481 EVT NVT = N->getValueType(0);
Mon P Wangca6d6de2009-01-17 00:07:25 +000011482
Duncan Sands6be291a2011-05-09 08:03:33 +000011483 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
11484 // Check if the result type doesn't match the inserted element type. A
11485 // SCALAR_TO_VECTOR may truncate the inserted element and the
11486 // EXTRACT_VECTOR_ELT may widen the extracted vector.
11487 SDValue InOp = InVec.getOperand(0);
Duncan Sands6be291a2011-05-09 08:03:33 +000011488 if (InOp.getValueType() != NVT) {
11489 assert(InOp.getValueType().isInteger() && NVT.isInteger());
Andrew Trickef9de2a2013-05-25 02:42:55 +000011490 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
Duncan Sands6be291a2011-05-09 08:03:33 +000011491 }
11492 return InOp;
11493 }
Evan Cheng1120279a2008-05-13 08:35:03 +000011494
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000011495 SDValue EltNo = N->getOperand(1);
11496 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
11497
11498 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
11499 // We only perform this optimization before the op legalization phase because
Nadav Rotem841c9a82012-09-20 08:53:31 +000011500 // we may introduce new vector instructions which are not backed by TD
11501 // patterns. For example on AVX, extracting elements from a wide vector
Hal Finkel02807592014-03-31 11:43:19 +000011502 // without using extract_subvector. However, if we can find an underlying
11503 // scalar value, then we can always use that.
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000011504 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
Hal Finkel02807592014-03-31 11:43:19 +000011505 && ConstEltNo) {
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000011506 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11507 int NumElem = VT.getVectorNumElements();
11508 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
11509 // Find the new index to extract from.
11510 int OrigElt = SVOp->getMaskElt(Elt);
11511
11512 // Extracting an undef index is undef.
11513 if (OrigElt == -1)
11514 return DAG.getUNDEF(NVT);
11515
11516 // Select the right vector half to extract from.
Hal Finkel02807592014-03-31 11:43:19 +000011517 SDValue SVInVec;
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000011518 if (OrigElt < NumElem) {
Hal Finkel02807592014-03-31 11:43:19 +000011519 SVInVec = InVec->getOperand(0);
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000011520 } else {
Hal Finkel02807592014-03-31 11:43:19 +000011521 SVInVec = InVec->getOperand(1);
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000011522 OrigElt -= NumElem;
11523 }
11524
Hal Finkel02807592014-03-31 11:43:19 +000011525 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
11526 SDValue InOp = SVInVec.getOperand(OrigElt);
11527 if (InOp.getValueType() != NVT) {
11528 assert(InOp.getValueType().isInteger() && NVT.isInteger());
11529 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
11530 }
11531
11532 return InOp;
11533 }
11534
11535 // FIXME: We should handle recursing on other vector shuffles and
11536 // scalar_to_vector here as well.
11537
11538 if (!LegalOperations) {
11539 EVT IndexTy = TLI.getVectorIdxTy();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000011540 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
11541 DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
Hal Finkel02807592014-03-31 11:43:19 +000011542 }
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000011543 }
11544
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +000011545 bool BCNumEltsChanged = false;
11546 EVT ExtVT = VT.getVectorElementType();
11547 EVT LVT = ExtVT;
11548
11549 // If the result of load has to be truncated, then it's not necessarily
11550 // profitable.
11551 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
11552 return SDValue();
11553
11554 if (InVec.getOpcode() == ISD::BITCAST) {
11555 // Don't duplicate a load with other uses.
11556 if (!InVec.hasOneUse())
11557 return SDValue();
11558
11559 EVT BCVT = InVec.getOperand(0).getValueType();
11560 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
11561 return SDValue();
11562 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
11563 BCNumEltsChanged = true;
11564 InVec = InVec.getOperand(0);
11565 ExtVT = BCVT.getVectorElementType();
11566 }
11567
11568 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
11569 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
11570 ISD::isNormalLoad(InVec.getNode()) &&
11571 !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
11572 SDValue Index = N->getOperand(1);
11573 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
11574 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
11575 OrigLoad);
11576 }
11577
Evan Cheng1120279a2008-05-13 08:35:03 +000011578 // Perform only after legalization to ensure build_vector / vector_shuffle
11579 // optimizations have already been done.
Duncan Sandsdc2dac12008-11-24 14:53:14 +000011580 if (!LegalOperations) return SDValue();
Evan Cheng1120279a2008-05-13 08:35:03 +000011581
Mon P Wangca6d6de2009-01-17 00:07:25 +000011582 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
11583 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
11584 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
Evan Cheng0de312d2007-10-06 08:19:55 +000011585
Nadav Rotemfb6ddee2012-01-17 21:44:01 +000011586 if (ConstEltNo) {
Eric Christopherfcc9e682010-11-03 09:36:40 +000011587 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
Evan Cheng0de312d2007-10-06 08:19:55 +000011588
Craig Topperc0196b12014-04-14 00:51:57 +000011589 LoadSDNode *LN0 = nullptr;
11590 const ShuffleVectorSDNode *SVN = nullptr;
Bill Wendling27d9dd42009-01-30 23:36:47 +000011591 if (ISD::isNormalLoad(InVec.getNode())) {
Evan Cheng1120279a2008-05-13 08:35:03 +000011592 LN0 = cast<LoadSDNode>(InVec);
Bill Wendling27d9dd42009-01-30 23:36:47 +000011593 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
Owen Anderson53aa7a92009-08-10 22:56:29 +000011594 InVec.getOperand(0).getValueType() == ExtVT &&
Bill Wendling27d9dd42009-01-30 23:36:47 +000011595 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
Eli Friedmane96286c2011-12-26 22:49:32 +000011596 // Don't duplicate a load with other uses.
11597 if (!InVec.hasOneUse())
11598 return SDValue();
11599
Evan Cheng1120279a2008-05-13 08:35:03 +000011600 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
Nate Begeman5f829d82009-04-29 05:20:52 +000011601 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
Evan Cheng1120279a2008-05-13 08:35:03 +000011602 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
11603 // =>
11604 // (load $addr+1*size)
Scott Michelcf0da6c2009-02-17 22:15:04 +000011605
Eli Friedmane96286c2011-12-26 22:49:32 +000011606 // Don't duplicate a load with other uses.
11607 if (!InVec.hasOneUse())
11608 return SDValue();
11609
Mon P Wangb5eb7202008-12-11 00:26:16 +000011610 // If the bit convert changed the number of elements, it is unsafe
11611 // to examine the mask.
11612 if (BCNumEltsChanged)
11613 return SDValue();
Nate Begeman5f829d82009-04-29 05:20:52 +000011614
11615 // Select the input vector, guarding against out of range extract vector.
11616 unsigned NumElems = VT.getVectorNumElements();
Eric Christopherfcc9e682010-11-03 09:36:40 +000011617 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
Nate Begeman5f829d82009-04-29 05:20:52 +000011618 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
11619
Eli Friedmane96286c2011-12-26 22:49:32 +000011620 if (InVec.getOpcode() == ISD::BITCAST) {
11621 // Don't duplicate a load with other uses.
11622 if (!InVec.hasOneUse())
11623 return SDValue();
11624
Evan Cheng1120279a2008-05-13 08:35:03 +000011625 InVec = InVec.getOperand(0);
Eli Friedmane96286c2011-12-26 22:49:32 +000011626 }
Gabor Greiff304a7a2008-08-28 21:40:38 +000011627 if (ISD::isNormalLoad(InVec.getNode())) {
Evan Cheng1120279a2008-05-13 08:35:03 +000011628 LN0 = cast<LoadSDNode>(InVec);
Ted Kremenekd87bd772010-04-08 18:49:30 +000011629 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000011630 EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
Evan Cheng0de312d2007-10-06 08:19:55 +000011631 }
11632 }
Bill Wendling27d9dd42009-01-30 23:36:47 +000011633
Eli Friedmane96286c2011-12-26 22:49:32 +000011634 // Make sure we found a non-volatile load and the extractelement is
11635 // the only use.
Nadav Rotem8a7beb82011-05-11 14:40:50 +000011636 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011637 return SDValue();
Evan Cheng1120279a2008-05-13 08:35:03 +000011638
Eric Christopherc6418b12010-11-03 20:44:42 +000011639 // If Idx was -1 above, Elt is going to be -1, so just return undef.
11640 if (Elt == -1)
Eli Friedmancbd3ba92011-07-25 22:25:42 +000011641 return DAG.getUNDEF(LVT);
Eric Christopherc6418b12010-11-03 20:44:42 +000011642
Michael J. Spencer6b2f5b42014-08-11 23:49:33 +000011643 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
Evan Cheng0de312d2007-10-06 08:19:55 +000011644 }
Bill Wendling27d9dd42009-01-30 23:36:47 +000011645
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011646 return SDValue();
Evan Cheng0de312d2007-10-06 08:19:55 +000011647}
Evan Cheng0de312d2007-10-06 08:19:55 +000011648
Michael Liao6d106b72012-10-23 23:06:52 +000011649// Simplify (build_vec (ext )) to (bitcast (build_vec ))
11650SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
11651 // We perform this optimization post type-legalization because
11652 // the type-legalizer often scalarizes integer-promoted vectors.
11653 // Performing this optimization before may create bit-casts which
11654 // will be type-legalized to complex code sequences.
11655 // We perform this optimization only before the operation legalizer because we
11656 // may introduce illegal operations.
11657 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
11658 return SDValue();
11659
Dan Gohmana8665142007-06-25 16:23:39 +000011660 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +000011661 SDLoc dl(N);
Owen Anderson53aa7a92009-08-10 22:56:29 +000011662 EVT VT = N->getValueType(0);
Nadav Rotema62368c2012-07-15 08:38:23 +000011663
Nadav Rotembf6568b2011-10-29 21:23:04 +000011664 // Check to see if this is a BUILD_VECTOR of a bunch of values
11665 // which come from any_extend or zero_extend nodes. If so, we can create
11666 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
Nadav Rotemf3103612011-10-31 20:08:25 +000011667 // optimizations. We do not handle sign-extend because we can't fill the sign
11668 // using shuffles.
Nadav Rotembf6568b2011-10-29 21:23:04 +000011669 EVT SourceType = MVT::Other;
Craig Topper02cb0fb2012-01-17 09:09:48 +000011670 bool AllAnyExt = true;
Nadav Rotema62368c2012-07-15 08:38:23 +000011671
Craig Topper02cb0fb2012-01-17 09:09:48 +000011672 for (unsigned i = 0; i != NumInScalars; ++i) {
Nadav Rotembf6568b2011-10-29 21:23:04 +000011673 SDValue In = N->getOperand(i);
11674 // Ignore undef inputs.
11675 if (In.getOpcode() == ISD::UNDEF) continue;
11676
11677 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
11678 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
11679
Nadav Rotemf3103612011-10-31 20:08:25 +000011680 // Abort if the element is not an extension.
Nadav Rotembf6568b2011-10-29 21:23:04 +000011681 if (!ZeroExt && !AnyExt) {
Nadav Rotemf3103612011-10-31 20:08:25 +000011682 SourceType = MVT::Other;
Nadav Rotembf6568b2011-10-29 21:23:04 +000011683 break;
11684 }
11685
11686 // The input is a ZeroExt or AnyExt. Check the original type.
11687 EVT InTy = In.getOperand(0).getValueType();
11688
11689 // Check that all of the widened source types are the same.
11690 if (SourceType == MVT::Other)
Nadav Rotemf3103612011-10-31 20:08:25 +000011691 // First time.
Nadav Rotembf6568b2011-10-29 21:23:04 +000011692 SourceType = InTy;
11693 else if (InTy != SourceType) {
11694 // Multiple income types. Abort.
Nadav Rotemf3103612011-10-31 20:08:25 +000011695 SourceType = MVT::Other;
Nadav Rotembf6568b2011-10-29 21:23:04 +000011696 break;
11697 }
11698
11699 // Check if all of the extends are ANY_EXTENDs.
Craig Topper02cb0fb2012-01-17 09:09:48 +000011700 AllAnyExt &= AnyExt;
Nadav Rotembf6568b2011-10-29 21:23:04 +000011701 }
11702
Nadav Rotemf3103612011-10-31 20:08:25 +000011703 // In order to have valid types, all of the inputs must be extended from the
11704 // same source type and all of the inputs must be any or zero extend.
11705 // Scalar sizes must be a power of two.
Michael Liao6d106b72012-10-23 23:06:52 +000011706 EVT OutScalarTy = VT.getScalarType();
Nadav Rotem34ca89a2012-02-12 15:05:31 +000011707 bool ValidTypes = SourceType != MVT::Other &&
Nadav Rotemf3103612011-10-31 20:08:25 +000011708 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
11709 isPowerOf2_32(SourceType.getSizeInBits());
11710
Nadav Rotem6fd1d322012-03-15 08:49:06 +000011711 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
11712 // turn into a single shuffle instruction.
Michael Liao6d106b72012-10-23 23:06:52 +000011713 if (!ValidTypes)
11714 return SDValue();
Nadav Rotembf6568b2011-10-29 21:23:04 +000011715
Michael Liao6d106b72012-10-23 23:06:52 +000011716 bool isLE = TLI.isLittleEndian();
11717 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
11718 assert(ElemRatio > 1 && "Invalid element size ratio");
11719 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000011720 DAG.getConstant(0, SDLoc(N), SourceType);
Nadav Rotembf6568b2011-10-29 21:23:04 +000011721
Michael Liao6d106b72012-10-23 23:06:52 +000011722 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
11723 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
Nadav Rotembf6568b2011-10-29 21:23:04 +000011724
Michael Liao6d106b72012-10-23 23:06:52 +000011725 // Populate the new build_vector
Jakub Staszaka6addc22012-10-24 00:38:25 +000011726 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
Michael Liao6d106b72012-10-23 23:06:52 +000011727 SDValue Cast = N->getOperand(i);
11728 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
11729 Cast.getOpcode() == ISD::ZERO_EXTEND ||
11730 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
11731 SDValue In;
11732 if (Cast.getOpcode() == ISD::UNDEF)
11733 In = DAG.getUNDEF(SourceType);
11734 else
11735 In = Cast->getOperand(0);
11736 unsigned Index = isLE ? (i * ElemRatio) :
11737 (i * ElemRatio + (ElemRatio - 1));
Nadav Rotembf6568b2011-10-29 21:23:04 +000011738
Michael Liao6d106b72012-10-23 23:06:52 +000011739 assert(Index < Ops.size() && "Invalid index");
11740 Ops[Index] = In;
Nadav Rotembf6568b2011-10-29 21:23:04 +000011741 }
Chris Lattner5336a592006-03-19 01:27:56 +000011742
Michael Liao6d106b72012-10-23 23:06:52 +000011743 // The type of the new BUILD_VECTOR node.
11744 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
11745 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
11746 "Invalid vector size");
11747 // Check if the new vector type is legal.
11748 if (!isTypeLegal(VecVT)) return SDValue();
11749
11750 // Make the new BUILD_VECTOR.
Craig Topper48d114b2014-04-26 18:35:24 +000011751 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
Michael Liao6d106b72012-10-23 23:06:52 +000011752
11753 // The new BUILD_VECTOR node has the potential to be further optimized.
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011754 AddToWorklist(BV.getNode());
Michael Liao6d106b72012-10-23 23:06:52 +000011755 // Bitcast to the desired type.
11756 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
11757}
11758
Michael Liao59229792012-10-24 04:14:18 +000011759SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
11760 EVT VT = N->getValueType(0);
11761
11762 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +000011763 SDLoc dl(N);
Michael Liao59229792012-10-24 04:14:18 +000011764
11765 EVT SrcVT = MVT::Other;
11766 unsigned Opcode = ISD::DELETED_NODE;
11767 unsigned NumDefs = 0;
11768
11769 for (unsigned i = 0; i != NumInScalars; ++i) {
11770 SDValue In = N->getOperand(i);
11771 unsigned Opc = In.getOpcode();
11772
11773 if (Opc == ISD::UNDEF)
11774 continue;
11775
11776 // If all scalar values are floats and converted from integers.
11777 if (Opcode == ISD::DELETED_NODE &&
11778 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
11779 Opcode = Opc;
Michael Liao59229792012-10-24 04:14:18 +000011780 }
Tom Stellard567f8862013-01-02 22:13:01 +000011781
Michael Liao59229792012-10-24 04:14:18 +000011782 if (Opc != Opcode)
11783 return SDValue();
11784
11785 EVT InVT = In.getOperand(0).getValueType();
11786
11787 // If all scalar values are typed differently, bail out. It's chosen to
11788 // simplify BUILD_VECTOR of integer types.
11789 if (SrcVT == MVT::Other)
11790 SrcVT = InVT;
11791 if (SrcVT != InVT)
11792 return SDValue();
11793 NumDefs++;
11794 }
11795
11796 // If the vector has just one element defined, it's not worth to fold it into
11797 // a vectorized one.
11798 if (NumDefs < 2)
11799 return SDValue();
11800
11801 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
11802 && "Should only handle conversion from integer to float.");
11803 assert(SrcVT != MVT::Other && "Cannot determine source type!");
11804
11805 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
Tom Stellard567f8862013-01-02 22:13:01 +000011806
11807 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
11808 return SDValue();
11809
Hal Finkele2dd84e2015-02-22 16:10:22 +000011810 // Just because the floating-point vector type is legal does not necessarily
11811 // mean that the corresponding integer vector type is.
11812 if (!isTypeLegal(NVT))
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000011813 return SDValue();
Hal Finkele2dd84e2015-02-22 16:10:22 +000011814
Michael Liao59229792012-10-24 04:14:18 +000011815 SmallVector<SDValue, 8> Opnds;
11816 for (unsigned i = 0; i != NumInScalars; ++i) {
11817 SDValue In = N->getOperand(i);
11818
11819 if (In.getOpcode() == ISD::UNDEF)
11820 Opnds.push_back(DAG.getUNDEF(SrcVT));
11821 else
11822 Opnds.push_back(In.getOperand(0));
11823 }
Craig Topper48d114b2014-04-26 18:35:24 +000011824 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000011825 AddToWorklist(BV.getNode());
Michael Liao59229792012-10-24 04:14:18 +000011826
11827 return DAG.getNode(Opcode, dl, VT, BV);
11828}
11829
Michael Liao6d106b72012-10-23 23:06:52 +000011830SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
11831 unsigned NumInScalars = N->getNumOperands();
Andrew Trickef9de2a2013-05-25 02:42:55 +000011832 SDLoc dl(N);
Michael Liao6d106b72012-10-23 23:06:52 +000011833 EVT VT = N->getValueType(0);
11834
11835 // A vector built entirely of undefs is undef.
11836 if (ISD::allOperandsUndef(N))
11837 return DAG.getUNDEF(VT);
11838
Simon Pilgrim2dcbe742015-03-07 16:34:55 +000011839 if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
Michael Liao6d106b72012-10-23 23:06:52 +000011840 return V;
11841
Simon Pilgrim2dcbe742015-03-07 16:34:55 +000011842 if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
Michael Liao59229792012-10-24 04:14:18 +000011843 return V;
11844
Dan Gohmana8665142007-06-25 16:23:39 +000011845 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
11846 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
11847 // at most two distinct vectors, turn this into a shuffle node.
Duncan Sands3fb2fc62012-03-19 15:35:44 +000011848
Andrea Di Biagioc7c52412014-09-30 15:30:22 +000011849 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
11850 if (!isTypeLegal(VT))
11851 return SDValue();
11852
Duncan Sands3fb2fc62012-03-19 15:35:44 +000011853 // May only combine to shuffle after legalize if shuffle is legal.
Owen Anderson3eb910b2014-08-28 17:49:58 +000011854 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
Duncan Sands3fb2fc62012-03-19 15:35:44 +000011855 return SDValue();
11856
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000011857 SDValue VecIn1, VecIn2;
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011858 bool UsesZeroVector = false;
Chris Lattnerc9992542006-03-28 20:28:38 +000011859 for (unsigned i = 0; i != NumInScalars; ++i) {
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011860 SDValue Op = N->getOperand(i);
Chris Lattnerc9992542006-03-28 20:28:38 +000011861 // Ignore undef inputs.
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011862 if (Op.getOpcode() == ISD::UNDEF) continue;
11863
11864 // See if we can combine this build_vector into a blend with a zero vector.
Matthias Braun1505efb2015-05-18 23:07:27 +000011865 if (!VecIn2.getNode() && (isNullConstant(Op) ||
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011866 (Op.getOpcode() == ISD::ConstantFP &&
11867 cast<ConstantFPSDNode>(Op.getNode())->getValueAPF().isZero()))) {
11868 UsesZeroVector = true;
11869 continue;
11870 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011871
Dan Gohmana8665142007-06-25 16:23:39 +000011872 // If this input is something other than a EXTRACT_VECTOR_ELT with a
Chris Lattnerc9992542006-03-28 20:28:38 +000011873 // constant index, bail out.
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011874 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11875 !isa<ConstantSDNode>(Op.getOperand(1))) {
Craig Topperc0196b12014-04-14 00:51:57 +000011876 VecIn1 = VecIn2 = SDValue(nullptr, 0);
Chris Lattnerc9992542006-03-28 20:28:38 +000011877 break;
11878 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011879
Nadav Rotem34ca89a2012-02-12 15:05:31 +000011880 // We allow up to two distinct input vectors.
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011881 SDValue ExtractedFromVec = Op.getOperand(0);
Chris Lattnerc9992542006-03-28 20:28:38 +000011882 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
11883 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +000011884
Craig Topperc0196b12014-04-14 00:51:57 +000011885 if (!VecIn1.getNode()) {
Chris Lattnerc9992542006-03-28 20:28:38 +000011886 VecIn1 = ExtractedFromVec;
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011887 } else if (!VecIn2.getNode() && !UsesZeroVector) {
Chris Lattnerc9992542006-03-28 20:28:38 +000011888 VecIn2 = ExtractedFromVec;
11889 } else {
11890 // Too many inputs.
Craig Topperc0196b12014-04-14 00:51:57 +000011891 VecIn1 = VecIn2 = SDValue(nullptr, 0);
Chris Lattnerc9992542006-03-28 20:28:38 +000011892 break;
11893 }
11894 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011895
Jim Grosbach2eb60fd2014-04-29 22:41:50 +000011896 // If everything is good, we can make a shuffle operation.
Gabor Greiff304a7a2008-08-28 21:40:38 +000011897 if (VecIn1.getNode()) {
Michael Kupersteinf4536ea2014-12-23 08:59:45 +000011898 unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011899 SmallVector<int, 8> Mask;
Chris Lattnerc9992542006-03-28 20:28:38 +000011900 for (unsigned i = 0; i != NumInScalars; ++i) {
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011901 unsigned Opcode = N->getOperand(i).getOpcode();
11902 if (Opcode == ISD::UNDEF) {
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011903 Mask.push_back(-1);
Chris Lattnerc9992542006-03-28 20:28:38 +000011904 continue;
11905 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011906
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011907 // Operands can also be zero.
11908 if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
11909 assert(UsesZeroVector &&
11910 (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
11911 "Unexpected node found!");
11912 Mask.push_back(NumInScalars+i);
11913 continue;
11914 }
11915
Rafael Espindolab93db662009-04-24 12:40:33 +000011916 // If extracting from the first vector, just use the index directly.
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011917 SDValue Extract = N->getOperand(i);
Mon P Wang523c0852009-03-17 06:33:10 +000011918 SDValue ExtVal = Extract.getOperand(1);
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011919 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
Chris Lattnerc9992542006-03-28 20:28:38 +000011920 if (Extract.getOperand(0) == VecIn1) {
Nate Begeman5f829d82009-04-29 05:20:52 +000011921 Mask.push_back(ExtIndex);
Chris Lattnerc9992542006-03-28 20:28:38 +000011922 continue;
11923 }
11924
Michael Kupersteinf4536ea2014-12-23 08:59:45 +000011925 // Otherwise, use InIdx + InputVecSize
11926 Mask.push_back(InNumElements + ExtIndex);
Chris Lattnerc9992542006-03-28 20:28:38 +000011927 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011928
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011929 // Avoid introducing illegal shuffles with zero.
11930 if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
11931 return SDValue();
11932
Nadav Rotem34ca89a2012-02-12 15:05:31 +000011933 // We can't generate a shuffle node with mismatched input and output types.
11934 // Attempt to transform a single input vector to the correct type.
11935 if ((VT != VecIn1.getValueType())) {
James Molloy1e5c6112012-09-10 14:01:21 +000011936 // If the input vector type has a different base type to the output
11937 // vector type, bail out.
Michael Kupersteinf4536ea2014-12-23 08:59:45 +000011938 EVT VTElemType = VT.getVectorElementType();
11939 if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
11940 (VecIn2.getNode() &&
11941 (VecIn2.getValueType().getVectorElementType() != VTElemType)))
James Molloy1e5c6112012-09-10 14:01:21 +000011942 return SDValue();
11943
Michael Kuperstein047b1a02014-12-17 12:32:17 +000011944 // If the input vector is too small, widen it.
11945 // We only support widening of vectors which are half the size of the
11946 // output registers. For example XMM->YMM widening on X86 with AVX.
11947 EVT VecInT = VecIn1.getValueType();
11948 if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
Michael Kupersteinf4536ea2014-12-23 08:59:45 +000011949 // If we only have one small input, widen it by adding undef values.
11950 if (!VecIn2.getNode())
11951 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
11952 DAG.getUNDEF(VecIn1.getValueType()));
11953 else if (VecIn1.getValueType() == VecIn2.getValueType()) {
11954 // If we have two small inputs of the same type, try to concat them.
11955 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
11956 VecIn2 = SDValue(nullptr, 0);
11957 } else
11958 return SDValue();
Michael Kuperstein047b1a02014-12-17 12:32:17 +000011959 } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
11960 // If the input vector is too large, try to split it.
Michael Kupersteinf4536ea2014-12-23 08:59:45 +000011961 // We don't support having two input vectors that are too large.
Michael Kupersteinfb956972015-03-04 07:27:39 +000011962 // If the zero vector was used, we can not split the vector,
11963 // since we'd need 3 inputs.
11964 if (UsesZeroVector || VecIn2.getNode())
Michael Kupersteinf4536ea2014-12-23 08:59:45 +000011965 return SDValue();
11966
Michael Kuperstein047b1a02014-12-17 12:32:17 +000011967 if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
11968 return SDValue();
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000011969
Michael Kuperstein047b1a02014-12-17 12:32:17 +000011970 // Try to replace VecIn1 with two extract_subvectors
11971 // No need to update the masks, they should still be correct.
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000011972 VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000011973 DAG.getConstant(VT.getVectorNumElements(), dl, TLI.getVectorIdxTy()));
Michael Kuperstein047b1a02014-12-17 12:32:17 +000011974 VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000011975 DAG.getConstant(0, dl, TLI.getVectorIdxTy()));
Michael Kupersteinf4536ea2014-12-23 08:59:45 +000011976 } else
Michael Kuperstein047b1a02014-12-17 12:32:17 +000011977 return SDValue();
Nadav Rotem34ca89a2012-02-12 15:05:31 +000011978 }
11979
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011980 if (UsesZeroVector)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000011981 VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) :
11982 DAG.getConstantFP(0.0, dl, VT);
Andrea Di Biagio0225b5b2014-11-21 14:32:06 +000011983 else
11984 // If VecIn2 is unused then change it to undef.
11985 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
Nadav Rotem34ca89a2012-02-12 15:05:31 +000011986
Nadav Rotem841c9a82012-09-20 08:53:31 +000011987 // Check that we were able to transform all incoming values to the same
11988 // type.
Nadav Rotem0c650642012-02-13 12:42:26 +000011989 if (VecIn2.getValueType() != VecIn1.getValueType() ||
11990 VecIn1.getValueType() != VT)
11991 return SDValue();
11992
Dan Gohmana8665142007-06-25 16:23:39 +000011993 // Return the new VECTOR_SHUFFLE node.
Nate Begeman8d6d4b92009-04-27 18:41:29 +000011994 SDValue Ops[2];
Chris Lattnerc24a1d32006-08-08 02:23:42 +000011995 Ops[0] = VecIn1;
Nadav Rotem34ca89a2012-02-12 15:05:31 +000011996 Ops[1] = VecIn2;
Michael Liao6d106b72012-10-23 23:06:52 +000011997 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
Chris Lattnerc9992542006-03-28 20:28:38 +000011998 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000011999
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012000 return SDValue();
Chris Lattnerc9992542006-03-28 20:28:38 +000012001}
12002
Ahmed Bougachac984b902015-04-16 02:39:14 +000012003static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
12004 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12005 EVT OpVT = N->getOperand(0).getValueType();
12006
12007 // If the operands are legal vectors, leave them alone.
12008 if (TLI.isTypeLegal(OpVT))
12009 return SDValue();
12010
12011 SDLoc DL(N);
12012 EVT VT = N->getValueType(0);
12013 SmallVector<SDValue, 8> Ops;
12014
12015 EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
12016 SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12017
12018 // Keep track of what we encounter.
12019 bool AnyInteger = false;
12020 bool AnyFP = false;
12021 for (const SDValue &Op : N->ops()) {
12022 if (ISD::BITCAST == Op.getOpcode() &&
12023 !Op.getOperand(0).getValueType().isVector())
12024 Ops.push_back(Op.getOperand(0));
12025 else if (ISD::UNDEF == Op.getOpcode())
12026 Ops.push_back(ScalarUndef);
12027 else
12028 return SDValue();
12029
12030 // Note whether we encounter an integer or floating point scalar.
12031 // If it's neither, bail out, it could be something weird like x86mmx.
12032 EVT LastOpVT = Ops.back().getValueType();
12033 if (LastOpVT.isFloatingPoint())
12034 AnyFP = true;
12035 else if (LastOpVT.isInteger())
12036 AnyInteger = true;
12037 else
12038 return SDValue();
12039 }
12040
12041 // If any of the operands is a floating point scalar bitcast to a vector,
12042 // use floating point types throughout, and bitcast everything.
12043 // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
12044 if (AnyFP) {
12045 SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
12046 ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12047 if (AnyInteger) {
12048 for (SDValue &Op : Ops) {
12049 if (Op.getValueType() == SVT)
12050 continue;
12051 if (Op.getOpcode() == ISD::UNDEF)
12052 Op = ScalarUndef;
12053 else
12054 Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op);
12055 }
12056 }
12057 }
12058
12059 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
12060 VT.getSizeInBits() / SVT.getSizeInBits());
12061 return DAG.getNode(ISD::BITCAST, DL, VT,
12062 DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops));
12063}
12064
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012065SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
Dan Gohmana8665142007-06-25 16:23:39 +000012066 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
12067 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
12068 // inputs come from at most two distinct vectors, turn this into a shuffle
12069 // node.
12070
12071 // If we only have one input vector, we don't need to do any concatenation.
Bill Wendling27d9dd42009-01-30 23:36:47 +000012072 if (N->getNumOperands() == 1)
Dan Gohmana8665142007-06-25 16:23:39 +000012073 return N->getOperand(0);
Dan Gohmana8665142007-06-25 16:23:39 +000012074
Nadav Rotem01892102012-07-14 21:30:27 +000012075 // Check if all of the operands are undefs.
Nadav Rotemd369d4b2013-10-25 06:41:18 +000012076 EVT VT = N->getValueType(0);
Nadav Rotema62368c2012-07-15 08:38:23 +000012077 if (ISD::allOperandsUndef(N))
Nadav Rotemd369d4b2013-10-25 06:41:18 +000012078 return DAG.getUNDEF(VT);
12079
Ahmed Bougachadf437372015-04-09 20:04:47 +000012080 // Optimize concat_vectors where all but the first of the vectors are undef.
12081 if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
12082 return Op.getOpcode() == ISD::UNDEF;
12083 })) {
Nadav Rotemd369d4b2013-10-25 06:41:18 +000012084 SDValue In = N->getOperand(0);
Nadav Rotem6eee0802013-12-10 01:13:59 +000012085 assert(In.getValueType().isVector() && "Must concat vectors");
Nadav Rotemd369d4b2013-10-25 06:41:18 +000012086
12087 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
12088 if (In->getOpcode() == ISD::BITCAST &&
12089 !In->getOperand(0)->getValueType(0).isVector()) {
12090 SDValue Scalar = In->getOperand(0);
Ahmed Bougachadf437372015-04-09 20:04:47 +000012091
12092 // If the bitcast type isn't legal, it might be a trunc of a legal type;
12093 // look through the trunc so we can still do the transform:
12094 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
12095 if (Scalar->getOpcode() == ISD::TRUNCATE &&
12096 !TLI.isTypeLegal(Scalar.getValueType()) &&
12097 TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
12098 Scalar = Scalar->getOperand(0);
12099
Nadav Rotemd369d4b2013-10-25 06:41:18 +000012100 EVT SclTy = Scalar->getValueType(0);
12101
12102 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
12103 return SDValue();
12104
12105 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
12106 VT.getSizeInBits() / SclTy.getSizeInBits());
12107 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
12108 return SDValue();
12109
12110 SDLoc dl = SDLoc(N);
12111 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
12112 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
12113 }
12114 }
Nadav Rotem01892102012-07-14 21:30:27 +000012115
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000012116 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
12117 // We have already tested above for an UNDEF only concatenation.
Robert Lougher7d9084f2014-02-11 15:42:46 +000012118 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
12119 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000012120 auto IsBuildVectorOrUndef = [](const SDValue &Op) {
12121 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
12122 };
12123 bool AllBuildVectorsOrUndefs =
12124 std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
12125 if (AllBuildVectorsOrUndefs) {
Robert Lougher7d9084f2014-02-11 15:42:46 +000012126 SmallVector<SDValue, 8> Opnds;
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000012127 EVT SVT = VT.getScalarType();
Robert Lougher7d9084f2014-02-11 15:42:46 +000012128
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000012129 EVT MinVT = SVT;
12130 if (!SVT.isFloatingPoint()) {
Hao Liu71224b02014-07-10 03:41:50 +000012131 // If BUILD_VECTOR are from built from integer, they may have different
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000012132 // operand types. Get the smallest type and truncate all operands to it.
12133 bool FoundMinVT = false;
12134 for (const SDValue &Op : N->ops())
12135 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12136 EVT OpSVT = Op.getOperand(0)->getValueType(0);
12137 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
12138 FoundMinVT = true;
12139 }
12140 assert(FoundMinVT && "Concat vector type mismatch");
Hao Liu71224b02014-07-10 03:41:50 +000012141 }
Robert Lougher7d9084f2014-02-11 15:42:46 +000012142
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000012143 for (const SDValue &Op : N->ops()) {
12144 EVT OpVT = Op.getValueType();
12145 unsigned NumElts = OpVT.getVectorNumElements();
12146
12147 if (ISD::UNDEF == Op.getOpcode())
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +000012148 Opnds.append(NumElts, DAG.getUNDEF(MinVT));
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000012149
12150 if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12151 if (SVT.isFloatingPoint()) {
12152 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +000012153 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000012154 } else {
12155 for (unsigned i = 0; i != NumElts; ++i)
12156 Opnds.push_back(
12157 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
12158 }
12159 }
12160 }
12161
12162 assert(VT.getVectorNumElements() == Opnds.size() &&
12163 "Concat vector type mismatch");
Craig Topper48d114b2014-04-26 18:35:24 +000012164 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
Robert Lougher7d9084f2014-02-11 15:42:46 +000012165 }
12166
Ahmed Bougachac984b902015-04-16 02:39:14 +000012167 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
12168 if (SDValue V = combineConcatVectorOfScalars(N, DAG))
12169 return V;
12170
Nadav Roteme5a2dda2013-05-01 19:18:51 +000012171 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
12172 // nodes often generate nop CONCAT_VECTOR nodes.
12173 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
12174 // place the incoming vectors at the exact same location.
12175 SDValue SingleSource = SDValue();
12176 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
12177
12178 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12179 SDValue Op = N->getOperand(i);
12180
12181 if (Op.getOpcode() == ISD::UNDEF)
12182 continue;
12183
12184 // Check if this is the identity extract:
12185 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12186 return SDValue();
12187
12188 // Find the single incoming vector for the extract_subvector.
12189 if (SingleSource.getNode()) {
12190 if (Op.getOperand(0) != SingleSource)
12191 return SDValue();
12192 } else {
12193 SingleSource = Op.getOperand(0);
Michael Kupersteinac868752013-05-06 08:06:13 +000012194
12195 // Check the source type is the same as the type of the result.
12196 // If not, this concat may extend the vector, so we can not
12197 // optimize it away.
12198 if (SingleSource.getValueType() != N->getValueType(0))
12199 return SDValue();
Nadav Roteme5a2dda2013-05-01 19:18:51 +000012200 }
12201
12202 unsigned IdentityIndex = i * PartNumElem;
12203 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12204 // The extract index must be constant.
12205 if (!CS)
12206 return SDValue();
Stephen Lincfe7f352013-07-08 00:37:03 +000012207
Nadav Roteme5a2dda2013-05-01 19:18:51 +000012208 // Check that we are reading from the identity index.
12209 if (CS->getZExtValue() != IdentityIndex)
12210 return SDValue();
12211 }
12212
12213 if (SingleSource.getNode())
12214 return SingleSource;
Stephen Lincfe7f352013-07-08 00:37:03 +000012215
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012216 return SDValue();
Dan Gohmana8665142007-06-25 16:23:39 +000012217}
12218
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +000012219SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
12220 EVT NVT = N->getValueType(0);
12221 SDValue V = N->getOperand(0);
12222
Michael Liao7a442c802012-10-17 20:48:33 +000012223 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
12224 // Combine:
12225 // (extract_subvec (concat V1, V2, ...), i)
12226 // Into:
12227 // Vi if possible
Jack Carterd4e96152013-10-17 01:34:33 +000012228 // Only operand 0 is checked as 'concat' assumes all inputs of the same
12229 // type.
Michael Liao2c235802012-10-19 03:17:00 +000012230 if (V->getOperand(0).getValueType() != NVT)
12231 return SDValue();
Benjamin Kramer619c4e52015-04-10 11:24:51 +000012232 unsigned Idx = N->getConstantOperandVal(1);
Michael Liao7a442c802012-10-17 20:48:33 +000012233 unsigned NumElems = NVT.getVectorNumElements();
12234 assert((Idx % NumElems) == 0 &&
12235 "IDX in concat is not a multiple of the result vector length.");
12236 return V->getOperand(Idx / NumElems);
12237 }
12238
Michael Liaobb05a1d2013-03-25 23:47:35 +000012239 // Skip bitcasting
12240 if (V->getOpcode() == ISD::BITCAST)
12241 V = V.getOperand(0);
12242
12243 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000012244 SDLoc dl(N);
Michael Liaobb05a1d2013-03-25 23:47:35 +000012245 // Handle only simple case where vector being inserted and vector
12246 // being extracted are of same type, and are half size of larger vectors.
12247 EVT BigVT = V->getOperand(0).getValueType();
12248 EVT SmallVT = V->getOperand(1).getValueType();
12249 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
12250 return SDValue();
12251
12252 // Only handle cases where both indexes are constants with the same type.
12253 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
12254 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
12255
12256 if (InsIdx && ExtIdx &&
12257 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
12258 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
12259 // Combine:
12260 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
12261 // Into:
12262 // indices are equal or bit offsets are equal => V1
12263 // otherwise => (extract_subvec V1, ExtIdx)
12264 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
12265 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
12266 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
12267 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
12268 DAG.getNode(ISD::BITCAST, dl,
12269 N->getOperand(0).getValueType(),
12270 V->getOperand(0)), N->getOperand(1));
12271 }
12272 }
12273
Bruno Cardoso Lopes6cb23f62011-09-20 23:19:33 +000012274 return SDValue();
12275}
12276
Chandler Carruthdaa1ff92014-10-05 19:14:34 +000012277static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
12278 SDValue V, SelectionDAG &DAG) {
12279 SDLoc DL(V);
12280 EVT VT = V.getValueType();
12281
12282 switch (V.getOpcode()) {
12283 default:
12284 return V;
12285
12286 case ISD::CONCAT_VECTORS: {
12287 EVT OpVT = V->getOperand(0).getValueType();
12288 int OpSize = OpVT.getVectorNumElements();
12289 SmallBitVector OpUsedElements(OpSize, false);
12290 bool FoundSimplification = false;
12291 SmallVector<SDValue, 4> NewOps;
12292 NewOps.reserve(V->getNumOperands());
12293 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
12294 SDValue Op = V->getOperand(i);
12295 bool OpUsed = false;
12296 for (int j = 0; j < OpSize; ++j)
12297 if (UsedElements[i * OpSize + j]) {
12298 OpUsedElements[j] = true;
12299 OpUsed = true;
12300 }
12301 NewOps.push_back(
12302 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
12303 : DAG.getUNDEF(OpVT));
12304 FoundSimplification |= Op == NewOps.back();
12305 OpUsedElements.reset();
12306 }
12307 if (FoundSimplification)
12308 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
12309 return V;
12310 }
12311
12312 case ISD::INSERT_SUBVECTOR: {
12313 SDValue BaseV = V->getOperand(0);
12314 SDValue SubV = V->getOperand(1);
12315 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
12316 if (!IdxN)
12317 return V;
12318
12319 int SubSize = SubV.getValueType().getVectorNumElements();
12320 int Idx = IdxN->getZExtValue();
12321 bool SubVectorUsed = false;
12322 SmallBitVector SubUsedElements(SubSize, false);
12323 for (int i = 0; i < SubSize; ++i)
12324 if (UsedElements[i + Idx]) {
12325 SubVectorUsed = true;
12326 SubUsedElements[i] = true;
12327 UsedElements[i + Idx] = false;
12328 }
12329
12330 // Now recurse on both the base and sub vectors.
12331 SDValue SimplifiedSubV =
12332 SubVectorUsed
12333 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
12334 : DAG.getUNDEF(SubV.getValueType());
12335 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
12336 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
12337 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
12338 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
12339 return V;
12340 }
12341 }
12342}
12343
12344static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
12345 SDValue N1, SelectionDAG &DAG) {
12346 EVT VT = SVN->getValueType(0);
12347 int NumElts = VT.getVectorNumElements();
12348 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
12349 for (int M : SVN->getMask())
12350 if (M >= 0 && M < NumElts)
12351 N0UsedElements[M] = true;
12352 else if (M >= NumElts)
12353 N1UsedElements[M - NumElts] = true;
12354
12355 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
12356 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
12357 if (S0 == N0 && S1 == N1)
12358 return SDValue();
12359
12360 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
12361}
12362
Mehdi Amini37f316a2015-01-17 01:35:56 +000012363// Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
12364// or turn a shuffle of a single concat into simpler shuffle then concat.
Benjamin Kramerbbae9912013-04-09 17:41:43 +000012365static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
12366 EVT VT = N->getValueType(0);
12367 unsigned NumElts = VT.getVectorNumElements();
12368
12369 SDValue N0 = N->getOperand(0);
12370 SDValue N1 = N->getOperand(1);
12371 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12372
12373 SmallVector<SDValue, 4> Ops;
12374 EVT ConcatVT = N0.getOperand(0).getValueType();
12375 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
12376 unsigned NumConcats = NumElts / NumElemsPerConcat;
12377
Mehdi Amini37f316a2015-01-17 01:35:56 +000012378 // Special case: shuffle(concat(A,B)) can be more efficiently represented
12379 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
12380 // half vector elements.
12381 if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
12382 std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
12383 SVN->getMask().end(), [](int i) { return i == -1; })) {
12384 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
12385 ArrayRef<int>(SVN->getMask().begin(), NumElemsPerConcat));
12386 N1 = DAG.getUNDEF(ConcatVT);
12387 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
12388 }
12389
Benjamin Kramerbbae9912013-04-09 17:41:43 +000012390 // Look at every vector that's inserted. We're looking for exact
12391 // subvector-sized copies from a concatenated vector
12392 for (unsigned I = 0; I != NumConcats; ++I) {
12393 // Make sure we're dealing with a copy.
12394 unsigned Begin = I * NumElemsPerConcat;
Hao Liubc601962013-05-13 02:07:05 +000012395 bool AllUndef = true, NoUndef = true;
12396 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
12397 if (SVN->getMaskElt(J) >= 0)
12398 AllUndef = false;
12399 else
12400 NoUndef = false;
Benjamin Kramerbbae9912013-04-09 17:41:43 +000012401 }
12402
Hao Liubc601962013-05-13 02:07:05 +000012403 if (NoUndef) {
Hao Liubc601962013-05-13 02:07:05 +000012404 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
12405 return SDValue();
12406
12407 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
12408 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
12409 return SDValue();
12410
12411 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
12412 if (FirstElt < N0.getNumOperands())
12413 Ops.push_back(N0.getOperand(FirstElt));
12414 else
12415 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
12416
12417 } else if (AllUndef) {
12418 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
12419 } else { // Mixed with general masks and undefs, can't do optimization.
12420 return SDValue();
12421 }
Benjamin Kramerbbae9912013-04-09 17:41:43 +000012422 }
12423
Craig Topper48d114b2014-04-26 18:35:24 +000012424 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
Benjamin Kramerbbae9912013-04-09 17:41:43 +000012425}
12426
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012427SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000012428 EVT VT = N->getValueType(0);
Nate Begeman8d6d4b92009-04-27 18:41:29 +000012429 unsigned NumElts = VT.getVectorNumElements();
Chris Lattner39dcf1a2006-03-31 22:16:43 +000012430
Mon P Wang25f01062008-11-10 04:46:22 +000012431 SDValue N0 = N->getOperand(0);
Craig Topper279c77b2012-01-04 08:07:43 +000012432 SDValue N1 = N->getOperand(1);
Mon P Wang25f01062008-11-10 04:46:22 +000012433
Craig Topper5894fe42012-04-09 05:16:56 +000012434 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
Mon P Wang25f01062008-11-10 04:46:22 +000012435
Craig Topper279c77b2012-01-04 08:07:43 +000012436 // Canonicalize shuffle undef, undef -> undef
12437 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
12438 return DAG.getUNDEF(VT);
12439
12440 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12441
12442 // Canonicalize shuffle v, v -> v, undef
12443 if (N0 == N1) {
12444 SmallVector<int, 8> NewMask;
12445 for (unsigned i = 0; i != NumElts; ++i) {
12446 int Idx = SVN->getMaskElt(i);
12447 if (Idx >= (int)NumElts) Idx -= NumElts;
12448 NewMask.push_back(Idx);
12449 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000012450 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
Craig Topper279c77b2012-01-04 08:07:43 +000012451 &NewMask[0]);
12452 }
12453
12454 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
12455 if (N0.getOpcode() == ISD::UNDEF) {
12456 SmallVector<int, 8> NewMask;
12457 for (unsigned i = 0; i != NumElts; ++i) {
12458 int Idx = SVN->getMaskElt(i);
Craig Toppere3ad4832012-04-09 05:55:33 +000012459 if (Idx >= 0) {
Craig Topper309dfef2013-08-08 07:38:55 +000012460 if (Idx >= (int)NumElts)
Craig Toppere3ad4832012-04-09 05:55:33 +000012461 Idx -= NumElts;
Craig Topper309dfef2013-08-08 07:38:55 +000012462 else
12463 Idx = -1; // remove reference to lhs
Craig Toppere3ad4832012-04-09 05:55:33 +000012464 }
12465 NewMask.push_back(Idx);
Craig Topper279c77b2012-01-04 08:07:43 +000012466 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000012467 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
Craig Topper279c77b2012-01-04 08:07:43 +000012468 &NewMask[0]);
12469 }
12470
12471 // Remove references to rhs if it is undef
12472 if (N1.getOpcode() == ISD::UNDEF) {
12473 bool Changed = false;
12474 SmallVector<int, 8> NewMask;
12475 for (unsigned i = 0; i != NumElts; ++i) {
12476 int Idx = SVN->getMaskElt(i);
12477 if (Idx >= (int)NumElts) {
12478 Idx = -1;
12479 Changed = true;
12480 }
12481 NewMask.push_back(Idx);
12482 }
12483 if (Changed)
Andrew Trickef9de2a2013-05-25 02:42:55 +000012484 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
Craig Topper279c77b2012-01-04 08:07:43 +000012485 }
Evan Cheng8472e0c2006-07-20 22:44:41 +000012486
Bob Wilsonf63da122010-10-28 17:06:14 +000012487 // If it is a splat, check if the argument vector is another splat or a
Michael Kuperstein25e34d12015-01-22 13:07:28 +000012488 // build_vector.
Bob Wilsonf63da122010-10-28 17:06:14 +000012489 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
Gabor Greiff304a7a2008-08-28 21:40:38 +000012490 SDNode *V = N0.getNode();
Evan Cheng7c970b92006-07-21 08:25:53 +000012491
Dan Gohmana8665142007-06-25 16:23:39 +000012492 // If this is a bit convert that changes the element type of the vector but
Evan Chengf3ae00a2006-10-16 22:49:37 +000012493 // not the number of vector elements, look through it. Be careful not to
12494 // look though conversions that change things like v4f32 to v2f64.
Wesley Peck527da1b2010-11-23 03:31:01 +000012495 if (V->getOpcode() == ISD::BITCAST) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012496 SDValue ConvInput = V->getOperand(0);
Evan Chengb8ff2232008-07-22 20:42:56 +000012497 if (ConvInput.getValueType().isVector() &&
12498 ConvInput.getValueType().getVectorNumElements() == NumElts)
Gabor Greiff304a7a2008-08-28 21:40:38 +000012499 V = ConvInput.getNode();
Evan Chengf3ae00a2006-10-16 22:49:37 +000012500 }
12501
Dan Gohmana8665142007-06-25 16:23:39 +000012502 if (V->getOpcode() == ISD::BUILD_VECTOR) {
Bob Wilsonf63da122010-10-28 17:06:14 +000012503 assert(V->getNumOperands() == NumElts &&
12504 "BUILD_VECTOR has wrong number of operands");
12505 SDValue Base;
12506 bool AllSame = true;
12507 for (unsigned i = 0; i != NumElts; ++i) {
12508 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
12509 Base = V->getOperand(i);
12510 break;
Evan Cheng7c970b92006-07-21 08:25:53 +000012511 }
Evan Cheng7c970b92006-07-21 08:25:53 +000012512 }
Bob Wilsonf63da122010-10-28 17:06:14 +000012513 // Splat of <u, u, u, u>, return <u, u, u, u>
12514 if (!Base.getNode())
12515 return N0;
12516 for (unsigned i = 0; i != NumElts; ++i) {
12517 if (V->getOperand(i) != Base) {
12518 AllSame = false;
12519 break;
12520 }
12521 }
12522 // Splat of <x, x, x, x>, return <x, x, x, x>
12523 if (AllSame)
12524 return N0;
Michael Kuperstein25e34d12015-01-22 13:07:28 +000012525
Sanjay Patelab7e86e2015-02-17 16:54:32 +000012526 // Canonicalize any other splat as a build_vector.
Michael Kuperstein25e34d12015-01-22 13:07:28 +000012527 const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
Sanjay Patelab7e86e2015-02-17 16:54:32 +000012528 SmallVector<SDValue, 8> Ops(NumElts, Splatted);
12529 SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
12530 V->getValueType(0), Ops);
Michael Kuperstein25e34d12015-01-22 13:07:28 +000012531
Sanjay Patelab7e86e2015-02-17 16:54:32 +000012532 // We may have jumped through bitcasts, so the type of the
12533 // BUILD_VECTOR may not match the type of the shuffle.
12534 if (V->getValueType(0) != VT)
Sanjay Pateld95dd9e2015-03-26 16:55:17 +000012535 NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
Sanjay Patelab7e86e2015-02-17 16:54:32 +000012536 return NewBV;
Evan Cheng7c970b92006-07-21 08:25:53 +000012537 }
12538 }
Nadav Rotemb0783502012-04-01 19:31:22 +000012539
Chandler Carruthdaa1ff92014-10-05 19:14:34 +000012540 // There are various patterns used to build up a vector from smaller vectors,
12541 // subvectors, or elements. Scan chains of these and replace unused insertions
12542 // or components with undef.
12543 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
12544 return S;
12545
Benjamin Kramerbbae9912013-04-09 17:41:43 +000012546 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12547 Level < AfterLegalizeVectorOps &&
12548 (N1.getOpcode() == ISD::UNDEF ||
12549 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
12550 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
12551 SDValue V = partitionShuffleOfConcats(N, DAG);
12552
12553 if (V.getNode())
12554 return V;
12555 }
12556
Simon Pilgrimed2ba33ba2015-04-03 10:02:21 +000012557 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
12558 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
12559 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
12560 SmallVector<SDValue, 8> Ops;
12561 for (int M : SVN->getMask()) {
12562 SDValue Op = DAG.getUNDEF(VT.getScalarType());
12563 if (M >= 0) {
12564 int Idx = M % NumElts;
12565 SDValue &S = (M < (int)NumElts ? N0 : N1);
12566 if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
12567 Op = S.getOperand(Idx);
12568 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
12569 if (Idx == 0)
12570 Op = S.getOperand(0);
12571 } else {
12572 // Operand can't be combined - bail out.
12573 break;
12574 }
12575 }
12576 Ops.push_back(Op);
12577 }
12578 if (Ops.size() == VT.getVectorNumElements()) {
12579 // BUILD_VECTOR requires all inputs to be of the same type, find the
12580 // maximum type and extend them all.
12581 EVT SVT = VT.getScalarType();
12582 if (SVT.isInteger())
12583 for (SDValue &Op : Ops)
12584 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
12585 if (SVT != VT.getScalarType())
12586 for (SDValue &Op : Ops)
12587 Op = TLI.isZExtFree(Op.getValueType(), SVT)
12588 ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
12589 : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
12590 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops);
12591 }
12592 }
12593
Simon Pilgrim7189084b2015-03-05 17:14:04 +000012594 // If this shuffle only has a single input that is a bitcasted shuffle,
12595 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
12596 // back to their original types.
12597 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
12598 N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
12599 TLI.isTypeLegal(VT)) {
12600
12601 // Peek through the bitcast only if there is one user.
12602 SDValue BC0 = N0;
12603 while (BC0.getOpcode() == ISD::BITCAST) {
12604 if (!BC0.hasOneUse())
12605 break;
12606 BC0 = BC0.getOperand(0);
12607 }
12608
12609 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
12610 if (Scale == 1)
12611 return SmallVector<int, 8>(Mask.begin(), Mask.end());
12612
12613 SmallVector<int, 8> NewMask;
12614 for (int M : Mask)
12615 for (int s = 0; s != Scale; ++s)
12616 NewMask.push_back(M < 0 ? -1 : Scale * M + s);
12617 return NewMask;
12618 };
12619
12620 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
12621 EVT SVT = VT.getScalarType();
12622 EVT InnerVT = BC0->getValueType(0);
12623 EVT InnerSVT = InnerVT.getScalarType();
12624
12625 // Determine which shuffle works with the smaller scalar type.
12626 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
12627 EVT ScaleSVT = ScaleVT.getScalarType();
12628
12629 if (TLI.isTypeLegal(ScaleVT) &&
12630 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
12631 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
12632
12633 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12634 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12635
12636 // Scale the shuffle masks to the smaller scalar type.
12637 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
12638 SmallVector<int, 8> InnerMask =
12639 ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
12640 SmallVector<int, 8> OuterMask =
12641 ScaleShuffleMask(SVN->getMask(), OuterScale);
12642
12643 // Merge the shuffle masks.
12644 SmallVector<int, 8> NewMask;
12645 for (int M : OuterMask)
12646 NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
12647
12648 // Test for shuffle mask legality over both commutations.
12649 SDValue SV0 = BC0->getOperand(0);
12650 SDValue SV1 = BC0->getOperand(1);
12651 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12652 if (!LegalMask) {
Simon Pilgrim7189084b2015-03-05 17:14:04 +000012653 std::swap(SV0, SV1);
Simon Pilgrim8c58c062015-03-07 22:33:11 +000012654 ShuffleVectorSDNode::commuteMask(NewMask);
Simon Pilgrim7189084b2015-03-05 17:14:04 +000012655 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12656 }
12657
12658 if (LegalMask) {
12659 SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
12660 SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
12661 return DAG.getNode(
12662 ISD::BITCAST, SDLoc(N), VT,
12663 DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
12664 }
12665 }
12666 }
12667 }
12668
Andrea Di Biagio0fb20132014-07-21 07:30:54 +000012669 // Canonicalize shuffles according to rules:
12670 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
12671 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
12672 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000012673 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
Andrea Di Biagio0fb20132014-07-21 07:30:54 +000012674 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
12675 TLI.isTypeLegal(VT)) {
12676 // The incoming shuffle must be of the same type as the result of the
12677 // current shuffle.
12678 assert(N1->getOperand(0).getValueType() == VT &&
12679 "Shuffle types don't match");
12680
12681 SDValue SV0 = N1->getOperand(0);
12682 SDValue SV1 = N1->getOperand(1);
12683 bool HasSameOp0 = N0 == SV0;
12684 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
12685 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
12686 // Commute the operands of this shuffle so that next rule
12687 // will trigger.
12688 return DAG.getCommutedVectorShuffle(*SVN);
12689 }
12690
Andrea Di Biagio3960a952014-07-14 22:46:26 +000012691 // Try to fold according to rules:
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000012692 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12693 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12694 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
Andrea Di Biagio3960a952014-07-14 22:46:26 +000012695 // Don't try to fold shuffles with illegal type.
Chandler Carruth499d7332015-02-15 07:01:10 +000012696 // Only fold if this shuffle is the only user of the other shuffle.
12697 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
12698 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
Andrea Di Biagio3960a952014-07-14 22:46:26 +000012699 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
12700
12701 // The incoming shuffle must be of the same type as the result of the
12702 // current shuffle.
12703 assert(OtherSV->getOperand(0).getValueType() == VT &&
12704 "Shuffle types don't match");
12705
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000012706 SDValue SV0, SV1;
Andrea Di Biagio3960a952014-07-14 22:46:26 +000012707 SmallVector<int, 4> Mask;
12708 // Compute the combined shuffle mask for a shuffle with SV0 as the first
12709 // operand, and SV1 as the second operand.
12710 for (unsigned i = 0; i != NumElts; ++i) {
12711 int Idx = SVN->getMaskElt(i);
12712 if (Idx < 0) {
12713 // Propagate Undef.
12714 Mask.push_back(Idx);
12715 continue;
12716 }
12717
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000012718 SDValue CurrentVec;
Andrea Di Biagiobd5555c2014-07-15 13:26:28 +000012719 if (Idx < (int)NumElts) {
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000012720 // This shuffle index refers to the inner shuffle N0. Lookup the inner
12721 // shuffle mask to identify which vector is actually referenced.
Andrea Di Biagio3960a952014-07-14 22:46:26 +000012722 Idx = OtherSV->getMaskElt(Idx);
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000012723 if (Idx < 0) {
12724 // Propagate Undef.
12725 Mask.push_back(Idx);
12726 continue;
12727 }
Andrea Di Biagio3960a952014-07-14 22:46:26 +000012728
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000012729 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
12730 : OtherSV->getOperand(1);
12731 } else {
12732 // This shuffle index references an element within N1.
12733 CurrentVec = N1;
12734 }
12735
12736 // Simple case where 'CurrentVec' is UNDEF.
12737 if (CurrentVec.getOpcode() == ISD::UNDEF) {
12738 Mask.push_back(-1);
12739 continue;
12740 }
12741
12742 // Canonicalize the shuffle index. We don't know yet if CurrentVec
12743 // will be the first or second operand of the combined shuffle.
12744 Idx = Idx % NumElts;
12745 if (!SV0.getNode() || SV0 == CurrentVec) {
12746 // Ok. CurrentVec is the left hand side.
12747 // Update the mask accordingly.
12748 SV0 = CurrentVec;
12749 Mask.push_back(Idx);
12750 continue;
12751 }
12752
12753 // Bail out if we cannot convert the shuffle pair into a single shuffle.
12754 if (SV1.getNode() && SV1 != CurrentVec)
12755 return SDValue();
12756
12757 // Ok. CurrentVec is the right hand side.
12758 // Update the mask accordingly.
12759 SV1 = CurrentVec;
12760 Mask.push_back(Idx + NumElts);
Andrea Di Biagio3960a952014-07-14 22:46:26 +000012761 }
12762
Andrea Di Biagiob23bad12014-08-16 00:29:44 +000012763 // Check if all indices in Mask are Undef. In case, propagate Undef.
12764 bool isUndefMask = true;
12765 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
12766 isUndefMask &= Mask[i] < 0;
12767
12768 if (isUndefMask)
12769 return DAG.getUNDEF(VT);
12770
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000012771 if (!SV0.getNode())
12772 SV0 = DAG.getUNDEF(VT);
12773 if (!SV1.getNode())
12774 SV1 = DAG.getUNDEF(VT);
12775
Andrea Di Biagio3960a952014-07-14 22:46:26 +000012776 // Avoid introducing shuffles with illegal mask.
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000012777 if (!TLI.isShuffleMaskLegal(Mask, VT)) {
Simon Pilgrim8c58c062015-03-07 22:33:11 +000012778 ShuffleVectorSDNode::commuteMask(Mask);
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000012779
12780 if (!TLI.isShuffleMaskLegal(Mask, VT))
12781 return SDValue();
Simon Pilgrimd8820ae2015-02-24 22:08:56 +000012782
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000012783 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
12784 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
12785 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
12786 std::swap(SV0, SV1);
Andrea Di Biagiobd5555c2014-07-15 13:26:28 +000012787 }
Andrea Di Biagioe13a0b82014-11-15 22:56:25 +000012788
Andrea Di Biagio26e8f4d2014-11-21 11:33:07 +000012789 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12790 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12791 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12792 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
Andrea Di Biagio3960a952014-07-14 22:46:26 +000012793 }
12794
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012795 return SDValue();
Chris Lattner39dcf1a2006-03-31 22:16:43 +000012796}
12797
Simon Pilgrimbede80a2015-03-07 05:52:42 +000012798SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
12799 SDValue InVal = N->getOperand(0);
12800 EVT VT = N->getValueType(0);
12801
12802 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
12803 // with a VECTOR_SHUFFLE.
12804 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12805 SDValue InVec = InVal->getOperand(0);
12806 SDValue EltNo = InVal->getOperand(1);
12807
12808 // FIXME: We could support implicit truncation if the shuffle can be
12809 // scaled to a smaller vector scalar type.
12810 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
12811 if (C0 && VT == InVec.getValueType() &&
12812 VT.getScalarType() == InVal.getValueType()) {
12813 SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
12814 int Elt = C0->getZExtValue();
12815 NewMask[0] = Elt;
12816
12817 if (TLI.isShuffleMaskLegal(NewMask, VT))
12818 return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
12819 NewMask);
12820 }
12821 }
12822
12823 return SDValue();
12824}
12825
Manman Ren413a6cb2014-01-31 01:10:35 +000012826SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
12827 SDValue N0 = N->getOperand(0);
12828 SDValue N2 = N->getOperand(2);
12829
12830 // If the input vector is a concatenation, and the insert replaces
12831 // one of the halves, we can optimize into a single concat_vectors.
12832 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12833 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
12834 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
12835 EVT VT = N->getValueType(0);
12836
12837 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12838 // (concat_vectors Z, Y)
12839 if (InsIdx == 0)
12840 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12841 N->getOperand(1), N0.getOperand(1));
12842
12843 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12844 // (concat_vectors X, Z)
12845 if (InsIdx == VT.getVectorNumElements()/2)
12846 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12847 N0.getOperand(0), N->getOperand(1));
12848 }
12849
12850 return SDValue();
12851}
12852
Pirama Arumuga Nainardb7c07e22015-04-17 18:36:25 +000012853SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
12854 SDValue N0 = N->getOperand(0);
12855
12856 // fold (fp_to_fp16 (fp16_to_fp op)) -> op
12857 if (N0->getOpcode() == ISD::FP16_TO_FP)
12858 return N0->getOperand(0);
12859
12860 return SDValue();
12861}
12862
Sanjay Patel50cbfc52014-08-28 16:29:51 +000012863/// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
12864/// with the destination vector and a zero vector.
Dan Gohmana8665142007-06-25 16:23:39 +000012865/// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
Evan Chenga320abc2006-04-20 08:56:16 +000012866/// vector_shuffle V, Zero, <0, 4, 2, 4>
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012867SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000012868 EVT VT = N->getValueType(0);
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012869 SDValue LHS = N->getOperand(0);
12870 SDValue RHS = N->getOperand(1);
Simon Pilgrim257849f2015-03-17 22:19:08 +000012871 SDLoc dl(N);
Craig Toppere5893f62012-04-09 05:59:53 +000012872
Simon Pilgrim257849f2015-03-17 22:19:08 +000012873 // Make sure we're not running after operation legalization where it
12874 // may have custom lowered the vector shuffles.
12875 if (LegalOperations)
12876 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000012877
Simon Pilgrim257849f2015-03-17 22:19:08 +000012878 if (N->getOpcode() != ISD::AND)
12879 return SDValue();
12880
12881 if (RHS.getOpcode() == ISD::BITCAST)
12882 RHS = RHS.getOperand(0);
12883
12884 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
12885 SmallVector<int, 8> Indices;
12886 unsigned NumElts = RHS.getNumOperands();
12887
12888 for (unsigned i = 0; i != NumElts; ++i) {
12889 SDValue Elt = RHS.getOperand(i);
Matthias Braun03312192015-05-19 00:25:20 +000012890 if (isAllOnesConstant(Elt))
12891 Indices.push_back(i);
12892 else if (isNullConstant(Elt))
12893 Indices.push_back(NumElts+i);
12894 else
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012895 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000012896 }
Simon Pilgrim257849f2015-03-17 22:19:08 +000012897
12898 // Let's see if the target supports this vector_shuffle.
12899 EVT RVT = RHS.getValueType();
12900 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
12901 return SDValue();
12902
12903 // Return the new VECTOR_SHUFFLE node.
12904 EVT EltVT = RVT.getVectorElementType();
12905 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000012906 DAG.getConstant(0, dl, EltVT));
12907 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, RVT, ZeroOps);
Simon Pilgrim257849f2015-03-17 22:19:08 +000012908 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
12909 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
12910 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
Evan Chenga320abc2006-04-20 08:56:16 +000012911 }
Bill Wendling31b50992009-01-30 23:59:18 +000012912
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012913 return SDValue();
Evan Chenga320abc2006-04-20 08:56:16 +000012914}
12915
Sanjay Patel50cbfc52014-08-28 16:29:51 +000012916/// Visit a binary vector operation, like ADD.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012917SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
Bob Wilson54081442010-12-17 23:06:49 +000012918 assert(N->getValueType(0).isVector() &&
12919 "SimplifyVBinOp only works on vectors!");
Dan Gohmana8665142007-06-25 16:23:39 +000012920
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012921 SDValue LHS = N->getOperand(0);
12922 SDValue RHS = N->getOperand(1);
Simon Pilgrim2dcbe742015-03-07 16:34:55 +000012923
12924 if (SDValue Shuffle = XformToShuffleWithZero(N))
12925 return Shuffle;
Evan Chenga320abc2006-04-20 08:56:16 +000012926
Dan Gohmana8665142007-06-25 16:23:39 +000012927 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
Chris Lattner0442a182006-04-02 03:25:57 +000012928 // this operation.
Scott Michelcf0da6c2009-02-17 22:15:04 +000012929 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
Dan Gohmana8665142007-06-25 16:23:39 +000012930 RHS.getOpcode() == ISD::BUILD_VECTOR) {
Juergen Ributzka73844052014-01-13 20:51:35 +000012931 // Check if both vectors are constants. If not bail out.
Andrea Di Biagiod7c03ec2014-01-15 19:51:32 +000012932 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
12933 cast<BuildVectorSDNode>(RHS)->isConstant()))
Juergen Ributzka73844052014-01-13 20:51:35 +000012934 return SDValue();
12935
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012936 SmallVector<SDValue, 8> Ops;
Dan Gohmana8665142007-06-25 16:23:39 +000012937 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012938 SDValue LHSOp = LHS.getOperand(i);
12939 SDValue RHSOp = RHS.getOperand(i);
Bill Wendling31b50992009-01-30 23:59:18 +000012940
Evan Cheng64d28462006-05-31 06:08:35 +000012941 // Can't fold divide by zero.
Dan Gohmana8665142007-06-25 16:23:39 +000012942 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
12943 N->getOpcode() == ISD::FDIV) {
Matthias Braun1505efb2015-05-18 23:07:27 +000012944 if (isNullConstant(RHSOp) || (RHSOp.getOpcode() == ISD::ConstantFP &&
Gabor Greiff304a7a2008-08-28 21:40:38 +000012945 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
Evan Cheng64d28462006-05-31 06:08:35 +000012946 break;
12947 }
Bill Wendling31b50992009-01-30 23:59:18 +000012948
Bob Wilson54081442010-12-17 23:06:49 +000012949 EVT VT = LHSOp.getValueType();
Bob Wilson68156192011-10-18 17:34:47 +000012950 EVT RVT = RHSOp.getValueType();
12951 if (RVT != VT) {
12952 // Integer BUILD_VECTOR operands may have types larger than the element
12953 // size (e.g., when the element type is not legal). Prior to type
12954 // legalization, the types may not match between the two BUILD_VECTORS.
12955 // Truncate one of the operands to make them match.
12956 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000012957 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
Bob Wilson68156192011-10-18 17:34:47 +000012958 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +000012959 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
Bob Wilson68156192011-10-18 17:34:47 +000012960 VT = RVT;
12961 }
12962 }
Andrew Trickef9de2a2013-05-25 02:42:55 +000012963 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
Evan Cheng48f0de92010-05-18 00:03:40 +000012964 LHSOp, RHSOp);
12965 if (FoldOp.getOpcode() != ISD::UNDEF &&
12966 FoldOp.getOpcode() != ISD::Constant &&
12967 FoldOp.getOpcode() != ISD::ConstantFP)
12968 break;
12969 Ops.push_back(FoldOp);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000012970 AddToWorklist(FoldOp.getNode());
Chris Lattner0442a182006-04-02 03:25:57 +000012971 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000012972
Bob Wilson54081442010-12-17 23:06:49 +000012973 if (Ops.size() == LHS.getNumOperands())
Craig Topper48d114b2014-04-26 18:35:24 +000012974 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
Chris Lattner0442a182006-04-02 03:25:57 +000012975 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000012976
Andrea Di Biagio446a5272014-05-30 23:17:53 +000012977 // Type legalization might introduce new shuffles in the DAG.
12978 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
12979 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
12980 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
12981 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
12982 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
12983 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
12984 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
12985 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
12986
12987 if (SVN0->getMask().equals(SVN1->getMask())) {
12988 EVT VT = N->getValueType(0);
12989 SDValue UndefVector = LHS.getOperand(1);
12990 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
12991 LHS.getOperand(0), RHS.getOperand(0));
Chandler Carruth3c0012b2014-07-21 08:56:44 +000012992 AddUsersToWorklist(N);
Andrea Di Biagio446a5272014-05-30 23:17:53 +000012993 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
12994 &SVN0->getMask()[0]);
12995 }
12996 }
12997
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000012998 return SDValue();
Chris Lattner0442a182006-04-02 03:25:57 +000012999}
13000
Andrew Trickef9de2a2013-05-25 02:42:55 +000013001SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
Bill Wendling31b50992009-01-30 23:59:18 +000013002 SDValue N1, SDValue N2){
Nate Begeman2042aa52005-10-08 00:29:44 +000013003 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
Scott Michelcf0da6c2009-02-17 22:15:04 +000013004
Bill Wendling31b50992009-01-30 23:59:18 +000013005 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
Nate Begeman2042aa52005-10-08 00:29:44 +000013006 cast<CondCodeSDNode>(N0.getOperand(2))->get());
Bill Wendling31b50992009-01-30 23:59:18 +000013007
Nate Begeman2042aa52005-10-08 00:29:44 +000013008 // If we got a simplified select_cc node back from SimplifySelectCC, then
13009 // break it down into a new SETCC node, and a new SELECT node, and then return
13010 // the SELECT node, since we were called with a SELECT node.
Gabor Greiff304a7a2008-08-28 21:40:38 +000013011 if (SCC.getNode()) {
Nate Begeman2042aa52005-10-08 00:29:44 +000013012 // Check to see if we got a select_cc back (to turn into setcc/select).
13013 // Otherwise, just return whatever node we got back, like fabs.
13014 if (SCC.getOpcode() == ISD::SELECT_CC) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000013015 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000013016 N0.getValueType(),
Scott Michelcf0da6c2009-02-17 22:15:04 +000013017 SCC.getOperand(0), SCC.getOperand(1),
Bill Wendling31b50992009-01-30 23:59:18 +000013018 SCC.getOperand(4));
Chandler Carruth3c0012b2014-07-21 08:56:44 +000013019 AddToWorklist(SETCC.getNode());
Chandler Carruth40dbd382014-08-04 21:29:59 +000013020 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
13021 SCC.getOperand(2), SCC.getOperand(3));
Nate Begeman2042aa52005-10-08 00:29:44 +000013022 }
Bill Wendling31b50992009-01-30 23:59:18 +000013023
Nate Begeman2042aa52005-10-08 00:29:44 +000013024 return SCC;
13025 }
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000013026 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +000013027}
13028
Sanjay Patel50cbfc52014-08-28 16:29:51 +000013029/// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
13030/// being selected between, see if we can simplify the select. Callers of this
13031/// should assume that TheSelect is deleted if this returns true. As such, they
13032/// should return the appropriate thing (e.g. the node) back to the top-level of
13033/// the DAG combiner loop to avoid it being looked at.
Scott Michelcf0da6c2009-02-17 22:15:04 +000013034bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000013035 SDValue RHS) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000013036
Tom Stellard69a7b912015-04-20 19:38:27 +000013037 // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13038 // The select + setcc is redundant, because fsqrt returns NaN for X < -0.
13039 if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
13040 if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
13041 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
13042 SDValue Sqrt = RHS;
13043 ISD::CondCode CC;
13044 SDValue CmpLHS;
13045 const ConstantFPSDNode *NegZero = nullptr;
13046
13047 if (TheSelect->getOpcode() == ISD::SELECT_CC) {
13048 CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
13049 CmpLHS = TheSelect->getOperand(0);
13050 NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1));
13051 } else {
13052 // SELECT or VSELECT
13053 SDValue Cmp = TheSelect->getOperand(0);
13054 if (Cmp.getOpcode() == ISD::SETCC) {
13055 CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
13056 CmpLHS = Cmp.getOperand(0);
13057 NegZero = isConstOrConstSplatFP(Cmp.getOperand(1));
13058 }
13059 }
13060 if (NegZero && NegZero->isNegative() && NegZero->isZero() &&
13061 Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
13062 CC == ISD::SETULT || CC == ISD::SETLT)) {
13063 // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13064 CombineTo(TheSelect, Sqrt);
13065 return true;
13066 }
13067 }
13068 }
Nadav Rotema49a02a2011-02-11 19:57:47 +000013069 // Cannot simplify select with vector condition
13070 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
13071
Chris Lattner6c14c352005-10-18 06:04:22 +000013072 // If this is a select from two identical things, try to pull the operation
13073 // through the select.
Chris Lattner254c4452010-09-21 15:46:59 +000013074 if (LHS.getOpcode() != RHS.getOpcode() ||
13075 !LHS.hasOneUse() || !RHS.hasOneUse())
13076 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000013077
Chris Lattner254c4452010-09-21 15:46:59 +000013078 // If this is a load and the token chain is identical, replace the select
13079 // of two loads with a load through a select of the address to load from.
13080 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
13081 // constants have been dropped into the constant pool.
13082 if (LHS.getOpcode() == ISD::LOAD) {
13083 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
13084 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
Wesley Peck527da1b2010-11-23 03:31:01 +000013085
Chris Lattner254c4452010-09-21 15:46:59 +000013086 // Token chains must be identical.
13087 if (LHS.getOperand(0) != RHS.getOperand(0) ||
Duncan Sands8651e9c2008-06-13 19:07:40 +000013088 // Do not let this transformation reduce the number of volatile loads.
Chris Lattner254c4452010-09-21 15:46:59 +000013089 LLD->isVolatile() || RLD->isVolatile() ||
Hal Finkel0d49cf22015-04-22 11:32:25 +000013090 // FIXME: If either is a pre/post inc/dec load,
13091 // we'd need to split out the address adjustment.
13092 LLD->isIndexed() || RLD->isIndexed() ||
Chris Lattner254c4452010-09-21 15:46:59 +000013093 // If this is an EXTLOAD, the VT's must match.
13094 LLD->getMemoryVT() != RLD->getMemoryVT() ||
Duncan Sands12f3b3b2010-11-18 20:05:18 +000013095 // If this is an EXTLOAD, the kind of extension must match.
13096 (LLD->getExtensionType() != RLD->getExtensionType() &&
13097 // The only exception is if one of the extensions is anyext.
13098 LLD->getExtensionType() != ISD::EXTLOAD &&
13099 RLD->getExtensionType() != ISD::EXTLOAD) ||
Dan Gohmanba8735d2009-10-31 14:14:04 +000013100 // FIXME: this discards src value information. This is
13101 // over-conservative. It would be beneficial to be able to remember
Mon P Wangec57c812010-01-11 20:12:49 +000013102 // both potential memory locations. Since we are discarding
13103 // src value info, don't do the transformation if the memory
13104 // locations are not in the default address space.
Chris Lattner254c4452010-09-21 15:46:59 +000013105 LLD->getPointerInfo().getAddrSpace() != 0 ||
Pete Cooper10a3ae72013-02-12 03:14:50 +000013106 RLD->getPointerInfo().getAddrSpace() != 0 ||
13107 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
13108 LLD->getBasePtr().getValueType()))
Chris Lattner254c4452010-09-21 15:46:59 +000013109 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000013110
Chris Lattnere3267522010-09-21 15:58:55 +000013111 // Check that the select condition doesn't reach either load. If so,
13112 // folding this will induce a cycle into the DAG. If not, this is safe to
13113 // xform, so create a select of the addresses.
Chris Lattner254c4452010-09-21 15:46:59 +000013114 SDValue Addr;
13115 if (TheSelect->getOpcode() == ISD::SELECT) {
Chris Lattnere3267522010-09-21 15:58:55 +000013116 SDNode *CondNode = TheSelect->getOperand(0).getNode();
13117 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
13118 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
13119 return false;
Nadav Rotemd5f88592012-10-18 18:06:48 +000013120 // The loads must not depend on one another.
13121 if (LLD->isPredecessorOf(RLD) ||
13122 RLD->isPredecessorOf(LLD))
13123 return false;
Matt Arsenaultd2f03322013-06-14 22:04:37 +000013124 Addr = DAG.getSelect(SDLoc(TheSelect),
13125 LLD->getBasePtr().getValueType(),
13126 TheSelect->getOperand(0), LLD->getBasePtr(),
13127 RLD->getBasePtr());
Chris Lattner254c4452010-09-21 15:46:59 +000013128 } else { // Otherwise SELECT_CC
Chris Lattnere3267522010-09-21 15:58:55 +000013129 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
13130 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
13131
13132 if ((LLD->hasAnyUseOfValue(1) &&
13133 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
Chris Lattner1cc25e82012-03-27 16:27:21 +000013134 (RLD->hasAnyUseOfValue(1) &&
13135 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
Chris Lattnere3267522010-09-21 15:58:55 +000013136 return false;
Wesley Peck527da1b2010-11-23 03:31:01 +000013137
Andrew Trickef9de2a2013-05-25 02:42:55 +000013138 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
Chris Lattnere3267522010-09-21 15:58:55 +000013139 LLD->getBasePtr().getValueType(),
13140 TheSelect->getOperand(0),
13141 TheSelect->getOperand(1),
13142 LLD->getBasePtr(), RLD->getBasePtr(),
13143 TheSelect->getOperand(4));
Chris Lattner254c4452010-09-21 15:46:59 +000013144 }
13145
Chris Lattnere3267522010-09-21 15:58:55 +000013146 SDValue Load;
Louis Gerbarg4fc09b32014-07-30 18:24:41 +000013147 // It is safe to replace the two loads if they have different alignments,
13148 // but the new load must be the minimum (most restrictive) alignment of the
13149 // inputs.
Louis Gerbarge8f9c782014-10-30 22:21:03 +000013150 bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
Louis Gerbarg09b8cde2014-07-31 22:57:46 +000013151 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
Chris Lattnere3267522010-09-21 15:58:55 +000013152 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
13153 Load = DAG.getLoad(TheSelect->getValueType(0),
Andrew Trickef9de2a2013-05-25 02:42:55 +000013154 SDLoc(TheSelect),
Hal Finkelcc39b672014-07-24 12:16:19 +000013155 // FIXME: Discards pointer and AA info.
Chris Lattnere3267522010-09-21 15:58:55 +000013156 LLD->getChain(), Addr, MachinePointerInfo(),
13157 LLD->isVolatile(), LLD->isNonTemporal(),
Louis Gerbarg67474e32014-07-31 21:45:05 +000013158 isInvariant, Alignment);
Chris Lattnere3267522010-09-21 15:58:55 +000013159 } else {
Duncan Sandsc92331b2010-11-18 21:16:28 +000013160 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
13161 RLD->getExtensionType() : LLD->getExtensionType(),
Andrew Trickef9de2a2013-05-25 02:42:55 +000013162 SDLoc(TheSelect),
Stuart Hastings81c43062011-02-16 16:23:55 +000013163 TheSelect->getValueType(0),
Hal Finkelcc39b672014-07-24 12:16:19 +000013164 // FIXME: Discards pointer and AA info.
Chris Lattnere3267522010-09-21 15:58:55 +000013165 LLD->getChain(), Addr, MachinePointerInfo(),
13166 LLD->getMemoryVT(), LLD->isVolatile(),
Louis Gerbarg67474e32014-07-31 21:45:05 +000013167 LLD->isNonTemporal(), isInvariant, Alignment);
Chris Lattner6c14c352005-10-18 06:04:22 +000013168 }
Chris Lattnere3267522010-09-21 15:58:55 +000013169
13170 // Users of the select now use the result of the load.
13171 CombineTo(TheSelect, Load);
13172
13173 // Users of the old loads now use the new load's chain. We know the
13174 // old-load value is dead now.
13175 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
13176 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
13177 return true;
Chris Lattner6c14c352005-10-18 06:04:22 +000013178 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000013179
Chris Lattner6c14c352005-10-18 06:04:22 +000013180 return false;
13181}
13182
Sanjay Patel50cbfc52014-08-28 16:29:51 +000013183/// Simplify an expression of the form (N0 cond N1) ? N2 : N3
Chris Lattner43d63772009-03-11 05:08:08 +000013184/// where 'cond' is the comparison specified by CC.
Andrew Trickef9de2a2013-05-25 02:42:55 +000013185SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000013186 SDValue N2, SDValue N3,
13187 ISD::CondCode CC, bool NotExtCompare) {
Chris Lattner43d63772009-03-11 05:08:08 +000013188 // (x ? y : y) -> y.
13189 if (N2 == N3) return N2;
Wesley Peck527da1b2010-11-23 03:31:01 +000013190
Owen Anderson53aa7a92009-08-10 22:56:29 +000013191 EVT VT = N2.getValueType();
Gabor Greiff304a7a2008-08-28 21:40:38 +000013192 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
13193 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000013194
13195 // Determine if the condition we're dealing with is constant
Matt Arsenault758659232013-05-18 00:21:46 +000013196 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
Dale Johannesenf1163e92009-02-03 00:47:48 +000013197 N0, N1, CC, DL, false);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000013198 if (SCC.getNode()) AddToWorklist(SCC.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000013199
Matthias Braun1505efb2015-05-18 23:07:27 +000013200 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
13201 // fold select_cc true, x, y -> x
13202 // fold select_cc false, x, y -> y
13203 return !SCCC->isNullValue() ? N2 : N3;
13204 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000013205
Nate Begeman2042aa52005-10-08 00:29:44 +000013206 // Check to see if we can simplify the select into an fabs node
13207 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
13208 // Allow either -0.0 or 0.0
Dale Johannesen2cfcf702007-08-25 22:10:57 +000013209 if (CFP->getValueAPF().isZero()) {
Nate Begeman2042aa52005-10-08 00:29:44 +000013210 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
13211 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
13212 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
13213 N2 == N3.getOperand(0))
Bill Wendling31b50992009-01-30 23:59:18 +000013214 return DAG.getNode(ISD::FABS, DL, VT, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +000013215
Nate Begeman2042aa52005-10-08 00:29:44 +000013216 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
13217 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
13218 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
13219 N2.getOperand(0) == N3)
Bill Wendling31b50992009-01-30 23:59:18 +000013220 return DAG.getNode(ISD::FABS, DL, VT, N3);
Nate Begeman2042aa52005-10-08 00:29:44 +000013221 }
13222 }
Wesley Peck527da1b2010-11-23 03:31:01 +000013223
Chris Lattner43d63772009-03-11 05:08:08 +000013224 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
13225 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
13226 // in it. This is a win when the constant is not otherwise available because
13227 // it replaces two constant pool loads with one. We only do this if the FP
13228 // type is known to be legal, because if it isn't, then we are before legalize
13229 // types an we want the other legalization to happen first (e.g. to avoid
Mon P Wangc8671562009-03-14 00:25:19 +000013230 // messing with soft float) and if the ConstantFP is not legal, because if
13231 // it is legal, we may not need to store the FP constant in a constant pool.
Chris Lattner43d63772009-03-11 05:08:08 +000013232 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
13233 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
13234 if (TLI.isTypeLegal(N2.getValueType()) &&
Mon P Wangc8671562009-03-14 00:25:19 +000013235 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
Tim Northover863a7892014-04-16 09:03:09 +000013236 TargetLowering::Legal &&
13237 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
13238 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
Chris Lattner43d63772009-03-11 05:08:08 +000013239 // If both constants have multiple uses, then we won't need to do an
13240 // extra load, they are likely around in registers for other users.
13241 (TV->hasOneUse() || FV->hasOneUse())) {
13242 Constant *Elts[] = {
13243 const_cast<ConstantFP*>(FV->getConstantFPValue()),
13244 const_cast<ConstantFP*>(TV->getConstantFPValue())
13245 };
Chris Lattner229907c2011-07-18 04:54:35 +000013246 Type *FPTy = Elts[0]->getType();
Micah Villmowcdfe20b2012-10-08 16:38:25 +000013247 const DataLayout &TD = *TLI.getDataLayout();
Wesley Peck527da1b2010-11-23 03:31:01 +000013248
Chris Lattner43d63772009-03-11 05:08:08 +000013249 // Create a ConstantArray of the two constants.
Jay Foad83be3612011-06-22 09:24:39 +000013250 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
Chris Lattner43d63772009-03-11 05:08:08 +000013251 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
13252 TD.getPrefTypeAlignment(FPTy));
Evan Cheng1fb8aed2009-03-13 07:51:59 +000013253 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
Chris Lattner43d63772009-03-11 05:08:08 +000013254
13255 // Get the offsets to the 0 and 1 element of the array so that we can
13256 // select between them.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000013257 SDValue Zero = DAG.getIntPtrConstant(0, DL);
Duncan Sandsaf9eaa82009-05-09 07:06:46 +000013258 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000013259 SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
Wesley Peck527da1b2010-11-23 03:31:01 +000013260
Chris Lattner43d63772009-03-11 05:08:08 +000013261 SDValue Cond = DAG.getSetCC(DL,
Matt Arsenault758659232013-05-18 00:21:46 +000013262 getSetCCResultType(N0.getValueType()),
Chris Lattner43d63772009-03-11 05:08:08 +000013263 N0, N1, CC);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000013264 AddToWorklist(Cond.getNode());
Matt Arsenaultd2f03322013-06-14 22:04:37 +000013265 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
13266 Cond, One, Zero);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000013267 AddToWorklist(CstOffset.getNode());
Tom Stellard838e2342013-08-26 15:06:10 +000013268 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
Chris Lattner43d63772009-03-11 05:08:08 +000013269 CstOffset);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000013270 AddToWorklist(CPIdx.getNode());
Chris Lattner43d63772009-03-11 05:08:08 +000013271 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
Chris Lattnera35499e2010-09-21 07:32:19 +000013272 MachinePointerInfo::getConstantPool(), false,
Pete Cooper82cd9e82011-11-08 18:42:53 +000013273 false, false, Alignment);
Chris Lattner43d63772009-03-11 05:08:08 +000013274 }
Wesley Peck527da1b2010-11-23 03:31:01 +000013275 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000013276
Nate Begeman2042aa52005-10-08 00:29:44 +000013277 // Check to see if we can perform the "gzip trick", transforming
Bill Wendling31b50992009-01-30 23:59:18 +000013278 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
Matthias Braun887fdfb2015-05-19 00:25:21 +000013279 if (isNullConstant(N3) && CC == ISD::SETLT &&
13280 (isNullConstant(N1) || // (a < 0) ? b : 0
13281 (isOneConstant(N1) && N0 == N2))) { // (a < 1) ? a : 0
Owen Anderson53aa7a92009-08-10 22:56:29 +000013282 EVT XType = N0.getValueType();
13283 EVT AType = N2.getValueType();
Duncan Sands11dd4242008-06-08 20:54:56 +000013284 if (XType.bitsGE(AType)) {
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +000013285 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
Nate Begeman6828ed92005-10-10 21:26:48 +000013286 // single-bit constant.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000013287 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
Dan Gohmanb72127a2008-03-13 22:13:53 +000013288 unsigned ShCtV = N2C->getAPIntValue().logBase2();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000013289 ShCtV = XType.getSizeInBits() - ShCtV - 1;
13290 SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
Owen Andersonb2c80da2011-02-25 21:41:48 +000013291 getShiftAmountTy(N0.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000013292 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000013293 XType, N0, ShCt);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000013294 AddToWorklist(Shift.getNode());
Bill Wendling31b50992009-01-30 23:59:18 +000013295
Duncan Sands11dd4242008-06-08 20:54:56 +000013296 if (XType.bitsGT(AType)) {
Bill Wendling3b585af2009-01-31 03:12:48 +000013297 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000013298 AddToWorklist(Shift.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000013299 }
Bill Wendling31b50992009-01-30 23:59:18 +000013300
13301 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
Nate Begeman2042aa52005-10-08 00:29:44 +000013302 }
Bill Wendling31b50992009-01-30 23:59:18 +000013303
Andrew Trickef9de2a2013-05-25 02:42:55 +000013304 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
Bill Wendling31b50992009-01-30 23:59:18 +000013305 XType, N0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000013306 DAG.getConstant(XType.getSizeInBits() - 1,
13307 SDLoc(N0),
Owen Andersonb2c80da2011-02-25 21:41:48 +000013308 getShiftAmountTy(N0.getValueType())));
Chandler Carruth3c0012b2014-07-21 08:56:44 +000013309 AddToWorklist(Shift.getNode());
Bill Wendling31b50992009-01-30 23:59:18 +000013310
Duncan Sands11dd4242008-06-08 20:54:56 +000013311 if (XType.bitsGT(AType)) {
Bill Wendling3b585af2009-01-31 03:12:48 +000013312 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000013313 AddToWorklist(Shift.getNode());
Nate Begeman2042aa52005-10-08 00:29:44 +000013314 }
Bill Wendling31b50992009-01-30 23:59:18 +000013315
13316 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
Nate Begeman2042aa52005-10-08 00:29:44 +000013317 }
13318 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000013319
Owen Anderson3231d132010-09-22 22:58:22 +000013320 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
13321 // where y is has a single bit set.
13322 // A plaintext description would be, we can turn the SELECT_CC into an AND
13323 // when the condition can be materialized as an all-ones register. Any
13324 // single bit-test can be materialized as an all-ones register with
13325 // shift-left and shift-right-arith.
13326 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
Matthias Braun1505efb2015-05-18 23:07:27 +000013327 N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
Owen Anderson3231d132010-09-22 22:58:22 +000013328 SDValue AndLHS = N0->getOperand(0);
13329 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
13330 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
13331 // Shift the tested bit over the sign bit.
13332 APInt AndMask = ConstAndRHS->getAPIntValue();
13333 SDValue ShlAmt =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000013334 DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
Owen Andersonb2c80da2011-02-25 21:41:48 +000013335 getShiftAmountTy(AndLHS.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000013336 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
Wesley Peck527da1b2010-11-23 03:31:01 +000013337
Owen Anderson3231d132010-09-22 22:58:22 +000013338 // Now arithmetic right shift it all the way over, so the result is either
13339 // all-ones, or zero.
13340 SDValue ShrAmt =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000013341 DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
Owen Andersonb2c80da2011-02-25 21:41:48 +000013342 getShiftAmountTy(Shl.getValueType()));
Andrew Trickef9de2a2013-05-25 02:42:55 +000013343 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
Wesley Peck527da1b2010-11-23 03:31:01 +000013344
Owen Anderson3231d132010-09-22 22:58:22 +000013345 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
13346 }
13347 }
13348
Nate Begeman6828ed92005-10-10 21:26:48 +000013349 // fold select C, 16, 0 -> shl C, 4
Matthias Braun1505efb2015-05-18 23:07:27 +000013350 if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
Daniel Sanderscbd44c52014-07-10 10:18:12 +000013351 TLI.getBooleanContents(N0.getValueType()) ==
13352 TargetLowering::ZeroOrOneBooleanContent) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000013353
Chris Lattnera083ffc2007-04-11 06:50:51 +000013354 // If the caller doesn't want us to simplify this into a zext of a compare,
13355 // don't do it.
Matthias Braun887fdfb2015-05-19 00:25:21 +000013356 if (NotExtCompare && N2C->isOne())
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000013357 return SDValue();
Scott Michelcf0da6c2009-02-17 22:15:04 +000013358
Nate Begeman6828ed92005-10-10 21:26:48 +000013359 // Get a SetCC of the condition
Owen Anderson15fd6ac2012-11-03 00:17:26 +000013360 // NOTE: Don't create a SETCC if it's not legal on this target.
13361 if (!LegalOperations ||
13362 TLI.isOperationLegal(ISD::SETCC,
Matt Arsenault758659232013-05-18 00:21:46 +000013363 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
Owen Anderson15fd6ac2012-11-03 00:17:26 +000013364 SDValue Temp, SCC;
13365 // cast from setcc result type to select result type
13366 if (LegalTypes) {
Matt Arsenault758659232013-05-18 00:21:46 +000013367 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000013368 N0, N1, CC);
13369 if (N2.getValueType().bitsLT(SCC.getValueType()))
Andrew Trickef9de2a2013-05-25 02:42:55 +000013370 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000013371 N2.getValueType());
13372 else
Andrew Trickef9de2a2013-05-25 02:42:55 +000013373 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
Owen Anderson15fd6ac2012-11-03 00:17:26 +000013374 N2.getValueType(), SCC);
13375 } else {
Andrew Trickef9de2a2013-05-25 02:42:55 +000013376 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
13377 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
Bill Wendling31b50992009-01-30 23:59:18 +000013378 N2.getValueType(), SCC);
Owen Anderson15fd6ac2012-11-03 00:17:26 +000013379 }
13380
Chandler Carruth3c0012b2014-07-21 08:56:44 +000013381 AddToWorklist(SCC.getNode());
13382 AddToWorklist(Temp.getNode());
Owen Anderson15fd6ac2012-11-03 00:17:26 +000013383
Matthias Braun887fdfb2015-05-19 00:25:21 +000013384 if (N2C->isOne())
Owen Anderson15fd6ac2012-11-03 00:17:26 +000013385 return Temp;
13386
13387 // shl setcc result by log2 n2c
Jack Carterd4e96152013-10-17 01:34:33 +000013388 return DAG.getNode(
13389 ISD::SHL, DL, N2.getValueType(), Temp,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000013390 DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
Jack Carterd4e96152013-10-17 01:34:33 +000013391 getShiftAmountTy(Temp.getValueType())));
Nate Begemanabac6162006-02-18 02:40:58 +000013392 }
Nate Begeman6828ed92005-10-10 21:26:48 +000013393 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000013394
Nate Begeman2042aa52005-10-08 00:29:44 +000013395 // Check to see if this is the equivalent of setcc
13396 // FIXME: Turn all of these into setcc if setcc if setcc is legal
13397 // otherwise, go ahead with the folds.
Matthias Braun887fdfb2015-05-19 00:25:21 +000013398 if (0 && isNullConstant(N3) && isOneConstant(N2)) {
Owen Anderson53aa7a92009-08-10 22:56:29 +000013399 EVT XType = N0.getValueType();
Duncan Sandsdc2dac12008-11-24 14:53:14 +000013400 if (!LegalOperations ||
Matt Arsenault758659232013-05-18 00:21:46 +000013401 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
13402 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
Nate Begeman2042aa52005-10-08 00:29:44 +000013403 if (Res.getValueType() != VT)
Bill Wendling31b50992009-01-30 23:59:18 +000013404 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
Nate Begeman2042aa52005-10-08 00:29:44 +000013405 return Res;
13406 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000013407
Bill Wendling31b50992009-01-30 23:59:18 +000013408 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
Matthias Braun1505efb2015-05-18 23:07:27 +000013409 if (isNullConstant(N1) && CC == ISD::SETEQ &&
Duncan Sandsdc2dac12008-11-24 14:53:14 +000013410 (!LegalOperations ||
Duncan Sandsb1bfff52008-06-14 17:48:34 +000013411 TLI.isOperationLegal(ISD::CTLZ, XType))) {
Andrew Trickef9de2a2013-05-25 02:42:55 +000013412 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
Scott Michelcf0da6c2009-02-17 22:15:04 +000013413 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
Duncan Sands13237ac2008-06-06 12:08:01 +000013414 DAG.getConstant(Log2_32(XType.getSizeInBits()),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000013415 SDLoc(Ctlz),
Owen Andersonb2c80da2011-02-25 21:41:48 +000013416 getShiftAmountTy(Ctlz.getValueType())));
Nate Begeman2042aa52005-10-08 00:29:44 +000013417 }
Bill Wendling31b50992009-01-30 23:59:18 +000013418 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
Matthias Braun1505efb2015-05-18 23:07:27 +000013419 if (isNullConstant(N1) && CC == ISD::SETGT) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000013420 SDLoc DL(N0);
13421 SDValue NegN0 = DAG.getNode(ISD::SUB, DL,
13422 XType, DAG.getConstant(0, DL, XType), N0);
13423 SDValue NotN0 = DAG.getNOT(DL, N0, XType);
Bill Wendling31b50992009-01-30 23:59:18 +000013424 return DAG.getNode(ISD::SRL, DL, XType,
Bill Wendlinga6c75ff2009-02-01 11:19:36 +000013425 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000013426 DAG.getConstant(XType.getSizeInBits() - 1, DL,
Owen Andersonb2c80da2011-02-25 21:41:48 +000013427 getShiftAmountTy(XType)));
Nate Begeman2042aa52005-10-08 00:29:44 +000013428 }
Bill Wendling31b50992009-01-30 23:59:18 +000013429 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
Matthias Braun03312192015-05-19 00:25:20 +000013430 if (isAllOnesConstant(N1) && CC == ISD::SETGT) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000013431 SDLoc DL(N0);
13432 SDValue Sign = DAG.getNode(ISD::SRL, DL, XType, N0,
13433 DAG.getConstant(XType.getSizeInBits() - 1, DL,
Owen Andersonb2c80da2011-02-25 21:41:48 +000013434 getShiftAmountTy(N0.getValueType())));
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000013435 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, DL,
13436 XType));
Nate Begeman2042aa52005-10-08 00:29:44 +000013437 }
13438 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000013439
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000013440 // Check to see if this is an integer abs.
13441 // select_cc setg[te] X, 0, X, -X ->
13442 // select_cc setgt X, -1, X, -X ->
13443 // select_cc setl[te] X, 0, -X, X ->
13444 // select_cc setlt X, 1, -X, X ->
Nate Begeman2042aa52005-10-08 00:29:44 +000013445 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000013446 if (N1C) {
Craig Topperc0196b12014-04-14 00:51:57 +000013447 ConstantSDNode *SubC = nullptr;
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000013448 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
13449 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
13450 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
13451 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
13452 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
13453 (N1C->isOne() && CC == ISD::SETLT)) &&
13454 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
13455 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
13456
Owen Anderson53aa7a92009-08-10 22:56:29 +000013457 EVT XType = N0.getValueType();
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000013458 if (SubC && SubC->isNullValue() && XType.isInteger()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000013459 SDLoc DL(N0);
13460 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000013461 N0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000013462 DAG.getConstant(XType.getSizeInBits() - 1, DL,
Owen Andersonb2c80da2011-02-25 21:41:48 +000013463 getShiftAmountTy(N0.getValueType())));
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000013464 SDValue Add = DAG.getNode(ISD::ADD, DL,
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000013465 XType, N0, Shift);
Chandler Carruth3c0012b2014-07-21 08:56:44 +000013466 AddToWorklist(Shift.getNode());
13467 AddToWorklist(Add.getNode());
Benjamin Kramer0ae3f082010-07-08 12:09:56 +000013468 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
Nate Begeman2042aa52005-10-08 00:29:44 +000013469 }
13470 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000013471
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000013472 return SDValue();
Nate Begemanc760f802005-09-19 22:34:01 +000013473}
13474
Sanjay Patel50cbfc52014-08-28 16:29:51 +000013475/// This is a stub for TargetLowering::SimplifySetCC.
Owen Anderson53aa7a92009-08-10 22:56:29 +000013476SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000013477 SDValue N1, ISD::CondCode Cond,
Andrew Trickef9de2a2013-05-25 02:42:55 +000013478 SDLoc DL, bool foldBooleans) {
Scott Michelcf0da6c2009-02-17 22:15:04 +000013479 TargetLowering::DAGCombinerInfo
Nadav Rotemb1dd5242012-12-27 06:47:41 +000013480 DagCombineInfo(DAG, Level, false, this);
Dale Johannesenf1163e92009-02-03 00:47:48 +000013481 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
Nate Begeman24a7eca2005-09-16 00:54:12 +000013482}
13483
Sanjay Patel50cbfc52014-08-28 16:29:51 +000013484/// Given an ISD::SDIV node expressing a divide by constant, return
Chad Rosier17020f92014-07-23 14:57:52 +000013485/// a DAG expression to select that will generate the same value by multiplying
Sanjay Patelbb292212014-09-15 19:47:44 +000013486/// by a magic number.
13487/// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000013488SDValue DAGCombiner::BuildSDIV(SDNode *N) {
Benjamin Kramerda4841b2014-04-26 23:09:49 +000013489 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13490 if (!C)
13491 return SDValue();
Benjamin Kramer4dae5982014-04-26 12:06:28 +000013492
13493 // Avoid division by zero.
Matthias Braun1505efb2015-05-18 23:07:27 +000013494 if (C->isNullValue())
Benjamin Kramer4dae5982014-04-26 12:06:28 +000013495 return SDValue();
13496
Andrew Lenharth0e57b2c2006-06-12 16:07:18 +000013497 std::vector<SDNode*> Built;
Benjamin Kramerda4841b2014-04-26 23:09:49 +000013498 SDValue S =
13499 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000013500
Benjamin Kramerda4841b2014-04-26 23:09:49 +000013501 for (SDNode *N : Built)
Chandler Carruth3c0012b2014-07-21 08:56:44 +000013502 AddToWorklist(N);
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000013503 return S;
Nate Begemanc6f067a2005-10-20 02:15:44 +000013504}
13505
Sanjay Patel50cbfc52014-08-28 16:29:51 +000013506/// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
13507/// DAG expression that will generate the same value by right shifting.
Chad Rosier17020f92014-07-23 14:57:52 +000013508SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
13509 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13510 if (!C)
13511 return SDValue();
13512
13513 // Avoid division by zero.
Matthias Braun1505efb2015-05-18 23:07:27 +000013514 if (C->isNullValue())
Chad Rosier17020f92014-07-23 14:57:52 +000013515 return SDValue();
13516
13517 std::vector<SDNode *> Built;
13518 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
13519
13520 for (SDNode *N : Built)
13521 AddToWorklist(N);
13522 return S;
13523}
13524
Sanjay Patel50cbfc52014-08-28 16:29:51 +000013525/// Given an ISD::UDIV node expressing a divide by constant, return a DAG
13526/// expression that will generate the same value by multiplying by a magic
Sanjay Patelbb292212014-09-15 19:47:44 +000013527/// number.
13528/// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000013529SDValue DAGCombiner::BuildUDIV(SDNode *N) {
Benjamin Kramerda4841b2014-04-26 23:09:49 +000013530 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13531 if (!C)
13532 return SDValue();
Benjamin Kramer4dae5982014-04-26 12:06:28 +000013533
13534 // Avoid division by zero.
Matthias Braun1505efb2015-05-18 23:07:27 +000013535 if (C->isNullValue())
Benjamin Kramer4dae5982014-04-26 12:06:28 +000013536 return SDValue();
13537
Andrew Lenharth0e57b2c2006-06-12 16:07:18 +000013538 std::vector<SDNode*> Built;
Benjamin Kramerda4841b2014-04-26 23:09:49 +000013539 SDValue S =
13540 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
Nate Begemanc6f067a2005-10-20 02:15:44 +000013541
Benjamin Kramerda4841b2014-04-26 23:09:49 +000013542 for (SDNode *N : Built)
Chandler Carruth3c0012b2014-07-21 08:56:44 +000013543 AddToWorklist(N);
Andrew Lenharth1dc9ec52006-05-16 17:42:15 +000013544 return S;
Nate Begemanc6f067a2005-10-20 02:15:44 +000013545}
13546
Sanjay Patelbdf1e382014-09-26 23:01:47 +000013547SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
13548 if (Level >= AfterLegalizeDAG)
13549 return SDValue();
13550
Sanjay Patelb67bd262014-09-21 15:19:15 +000013551 // Expose the DAG combiner to the target combiner implementations.
13552 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
Sanjay Patelb67bd262014-09-21 15:19:15 +000013553
Sanjay Patelab7f4602014-09-30 20:44:23 +000013554 unsigned Iterations = 0;
Sanjay Patel8fde95c2014-09-30 20:28:48 +000013555 if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
Sanjay Patelab7f4602014-09-30 20:44:23 +000013556 if (Iterations) {
13557 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13558 // For the reciprocal, we need to find the zero of the function:
13559 // F(X) = A X - 1 [which has a zero at X = 1/A]
13560 // =>
13561 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
13562 // does not require additional intermediate precision]
13563 EVT VT = Op.getValueType();
13564 SDLoc DL(Op);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000013565 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
Sanjay Patelbdf1e382014-09-26 23:01:47 +000013566
Sanjay Patelbdf1e382014-09-26 23:01:47 +000013567 AddToWorklist(Est.getNode());
Sanjay Patelbdf1e382014-09-26 23:01:47 +000013568
Sanjay Patelab7f4602014-09-30 20:44:23 +000013569 // Newton iterations: Est = Est + Est (1 - Arg * Est)
13570 for (unsigned i = 0; i < Iterations; ++i) {
13571 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
13572 AddToWorklist(NewEst.getNode());
13573
13574 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
13575 AddToWorklist(NewEst.getNode());
13576
13577 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13578 AddToWorklist(NewEst.getNode());
13579
13580 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
13581 AddToWorklist(Est.getNode());
13582 }
13583 }
Sanjay Patelbdf1e382014-09-26 23:01:47 +000013584 return Est;
13585 }
13586
13587 return SDValue();
13588}
13589
Sanjay Patel957efc232014-10-24 17:02:16 +000013590/// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13591/// For the reciprocal sqrt, we need to find the zero of the function:
13592/// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13593/// =>
13594/// X_{i+1} = X_i (1.5 - A X_i^2 / 2)
13595/// As a result, we precompute A/2 prior to the iteration loop.
13596SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
13597 unsigned Iterations) {
13598 EVT VT = Arg.getValueType();
13599 SDLoc DL(Arg);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000013600 SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +000013601
Sanjay Patel957efc232014-10-24 17:02:16 +000013602 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
13603 // this entire sequence requires only one FP constant.
13604 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
13605 AddToWorklist(HalfArg.getNode());
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +000013606
Sanjay Patel957efc232014-10-24 17:02:16 +000013607 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
13608 AddToWorklist(HalfArg.getNode());
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +000013609
Sanjay Patel957efc232014-10-24 17:02:16 +000013610 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
13611 for (unsigned i = 0; i < Iterations; ++i) {
13612 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13613 AddToWorklist(NewEst.getNode());
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +000013614
Sanjay Patel957efc232014-10-24 17:02:16 +000013615 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
13616 AddToWorklist(NewEst.getNode());
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +000013617
Sanjay Patel957efc232014-10-24 17:02:16 +000013618 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
13619 AddToWorklist(NewEst.getNode());
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +000013620
Sanjay Patel957efc232014-10-24 17:02:16 +000013621 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13622 AddToWorklist(Est.getNode());
13623 }
13624 return Est;
13625}
13626
13627/// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13628/// For the reciprocal sqrt, we need to find the zero of the function:
13629/// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13630/// =>
13631/// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
13632SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
13633 unsigned Iterations) {
13634 EVT VT = Arg.getValueType();
13635 SDLoc DL(Arg);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000013636 SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
13637 SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
Sanjay Patel957efc232014-10-24 17:02:16 +000013638
13639 // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
13640 for (unsigned i = 0; i < Iterations; ++i) {
13641 SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
13642 AddToWorklist(HalfEst.getNode());
13643
13644 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13645 AddToWorklist(Est.getNode());
13646
13647 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
13648 AddToWorklist(Est.getNode());
13649
13650 Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
13651 AddToWorklist(Est.getNode());
13652
13653 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
13654 AddToWorklist(Est.getNode());
13655 }
13656 return Est;
13657}
13658
Sanjay Patelbdf1e382014-09-26 23:01:47 +000013659SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
13660 if (Level >= AfterLegalizeDAG)
13661 return SDValue();
13662
13663 // Expose the DAG combiner to the target combiner implementations.
13664 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
Sanjay Patelab7f4602014-09-30 20:44:23 +000013665 unsigned Iterations = 0;
Sanjay Patel957efc232014-10-24 17:02:16 +000013666 bool UseOneConstNR = false;
13667 if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
13668 AddToWorklist(Est.getNode());
Sanjay Patelab7f4602014-09-30 20:44:23 +000013669 if (Iterations) {
Sanjay Patel957efc232014-10-24 17:02:16 +000013670 Est = UseOneConstNR ?
13671 BuildRsqrtNROneConst(Op, Est, Iterations) :
13672 BuildRsqrtNRTwoConst(Op, Est, Iterations);
Sanjay Patelab7f4602014-09-30 20:44:23 +000013673 }
Sanjay Patelbdf1e382014-09-26 23:01:47 +000013674 return Est;
Sanjay Patelb67bd262014-09-21 15:19:15 +000013675 }
13676
13677 return SDValue();
13678}
13679
Sanjay Patel50cbfc52014-08-28 16:29:51 +000013680/// Return true if base is a frame index, which is known not to alias with
13681/// anything but itself. Provides base object and offset as results.
Nate Begeman18150d52009-09-25 06:05:26 +000013682static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
Roman Divacky93383442012-09-05 22:15:49 +000013683 const GlobalValue *&GV, const void *&CV) {
Jim Laskey0463e082006-10-07 23:37:56 +000013684 // Assume it is a primitive operation.
Craig Topperc0196b12014-04-14 00:51:57 +000013685 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
Scott Michelcf0da6c2009-02-17 22:15:04 +000013686
Jim Laskey0463e082006-10-07 23:37:56 +000013687 // If it's an adding a simple constant then integrate the offset.
13688 if (Base.getOpcode() == ISD::ADD) {
13689 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
13690 Base = Base.getOperand(0);
Dan Gohmaneffb8942008-09-12 16:56:44 +000013691 Offset += C->getZExtValue();
Jim Laskey0463e082006-10-07 23:37:56 +000013692 }
13693 }
Wesley Peck527da1b2010-11-23 03:31:01 +000013694
Nate Begeman18150d52009-09-25 06:05:26 +000013695 // Return the underlying GlobalValue, and update the Offset. Return false
13696 // for GlobalAddressSDNode since the same GlobalAddress may be represented
13697 // by multiple nodes with different offsets.
13698 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
13699 GV = G->getGlobal();
13700 Offset += G->getOffset();
13701 return false;
13702 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000013703
Nate Begeman18150d52009-09-25 06:05:26 +000013704 // Return the underlying Constant value, and update the Offset. Return false
13705 // for ConstantSDNodes since the same constant pool entry may be represented
13706 // by multiple nodes with different offsets.
13707 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
Roman Divacky93383442012-09-05 22:15:49 +000013708 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
13709 : (const void *)C->getConstVal();
Nate Begeman18150d52009-09-25 06:05:26 +000013710 Offset += C->getOffset();
13711 return false;
13712 }
Jim Laskey0463e082006-10-07 23:37:56 +000013713 // If it's any of the following then it can't alias with anything but itself.
Nate Begeman18150d52009-09-25 06:05:26 +000013714 return isa<FrameIndexSDNode>(Base);
Jim Laskey0463e082006-10-07 23:37:56 +000013715}
13716
Sanjay Patel50cbfc52014-08-28 16:29:51 +000013717/// Return true if there is any possibility that the two addresses overlap.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013718bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
Jim Laskey0463e082006-10-07 23:37:56 +000013719 // If they are the same then they must be aliases.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013720 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
Scott Michelcf0da6c2009-02-17 22:15:04 +000013721
Richard Sandiford981fdeb2013-10-28 12:00:00 +000013722 // If they are both volatile then they cannot be reordered.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013723 if (Op0->isVolatile() && Op1->isVolatile()) return true;
Richard Sandiford981fdeb2013-10-28 12:00:00 +000013724
Jim Laskey0463e082006-10-07 23:37:56 +000013725 // Gather base node and offset information.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000013726 SDValue Base1, Base2;
Jim Laskey0463e082006-10-07 23:37:56 +000013727 int64_t Offset1, Offset2;
Dan Gohmanbcaf6812010-04-15 01:51:59 +000013728 const GlobalValue *GV1, *GV2;
Roman Divacky93383442012-09-05 22:15:49 +000013729 const void *CV1, *CV2;
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013730 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
13731 Base1, Offset1, GV1, CV1);
13732 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
13733 Base2, Offset2, GV2, CV2);
Scott Michelcf0da6c2009-02-17 22:15:04 +000013734
Nate Begeman18150d52009-09-25 06:05:26 +000013735 // If they have a same base address then check to see if they overlap.
13736 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013737 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13738 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
Scott Michelcf0da6c2009-02-17 22:15:04 +000013739
Owen Anderson272ff942010-09-20 20:39:59 +000013740 // It is possible for different frame indices to alias each other, mostly
13741 // when tail call optimization reuses return address slots for arguments.
13742 // To catch this case, look up the actual index of frame indices to compute
13743 // the real alias relationship.
13744 if (isFrameIndex1 && isFrameIndex2) {
13745 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13746 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
13747 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013748 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13749 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
Owen Anderson272ff942010-09-20 20:39:59 +000013750 }
13751
Wesley Peck527da1b2010-11-23 03:31:01 +000013752 // Otherwise, if we know what the bases are, and they aren't identical, then
Owen Anderson272ff942010-09-20 20:39:59 +000013753 // we know they cannot alias.
Nate Begeman18150d52009-09-25 06:05:26 +000013754 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
13755 return false;
Jim Laskeya15b0eb2006-10-18 12:29:57 +000013756
Nate Begeman879d8f12009-09-15 00:18:30 +000013757 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
13758 // compared to the size and offset of the access, we may be able to prove they
13759 // do not alias. This check is conservative for now to catch cases created by
13760 // splitting vector types.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013761 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
13762 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
13763 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
13764 Op1->getMemoryVT().getSizeInBits() >> 3) &&
13765 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
13766 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
13767 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
Wesley Peck527da1b2010-11-23 03:31:01 +000013768
Nate Begeman879d8f12009-09-15 00:18:30 +000013769 // There is no overlap between these relatively aligned accesses of similar
13770 // size, return no alias.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013771 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
13772 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
Nate Begeman879d8f12009-09-15 00:18:30 +000013773 return false;
13774 }
Wesley Peck527da1b2010-11-23 03:31:01 +000013775
Eric Christopherf55d4712014-10-08 23:38:39 +000013776 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
13777 ? CombinerGlobalAA
13778 : DAG.getSubtarget().useAA();
Hal Finkel9b2617a2014-01-25 17:32:39 +000013779#ifndef NDEBUG
13780 if (CombinerAAOnlyFunc.getNumOccurrences() &&
13781 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
13782 UseAA = false;
13783#endif
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013784 if (UseAA &&
13785 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
Jim Laskey55e4dca2006-10-18 19:08:31 +000013786 // Use alias analysis information.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013787 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
13788 Op1->getSrcValueOffset());
13789 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
13790 Op0->getSrcValueOffset() - MinOffset;
13791 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
13792 Op1->getSrcValueOffset() - MinOffset;
Scott Michelcf0da6c2009-02-17 22:15:04 +000013793 AliasAnalysis::AliasResult AAResult =
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013794 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
13795 Overlap1,
Hal Finkelcc39b672014-07-24 12:16:19 +000013796 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013797 AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
13798 Overlap2,
Hal Finkelcc39b672014-07-24 12:16:19 +000013799 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
Jim Laskey55e4dca2006-10-18 19:08:31 +000013800 if (AAResult == AliasAnalysis::NoAlias)
13801 return false;
13802 }
Jim Laskeya15b0eb2006-10-18 12:29:57 +000013803
13804 // Otherwise we have to assume they alias.
13805 return true;
Jim Laskey0463e082006-10-07 23:37:56 +000013806}
13807
Sanjay Patel50cbfc52014-08-28 16:29:51 +000013808/// Walk up chain skipping non-aliasing memory nodes,
Jim Laskey708d0db2006-10-04 16:53:27 +000013809/// looking for aliasing nodes and adding them to the Aliases vector.
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000013810void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
Craig Topperb94011f2013-07-14 04:42:23 +000013811 SmallVectorImpl<SDValue> &Aliases) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000013812 SmallVector<SDValue, 8> Chains; // List of chains to visit.
Nate Begeman879d8f12009-09-15 00:18:30 +000013813 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
Scott Michelcf0da6c2009-02-17 22:15:04 +000013814
Jim Laskeyd07be232006-09-25 16:29:54 +000013815 // Get alias information for node.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013816 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
Jim Laskeyd07be232006-09-25 16:29:54 +000013817
Jim Laskey708d0db2006-10-04 16:53:27 +000013818 // Starting off.
Jim Laskey6549d222006-10-05 15:07:25 +000013819 Chains.push_back(OriginalChain);
Nate Begemana3ed9ed2009-10-12 05:53:58 +000013820 unsigned Depth = 0;
Wesley Peck527da1b2010-11-23 03:31:01 +000013821
Jim Laskey6549d222006-10-05 15:07:25 +000013822 // Look at each chain and determine if it is an alias. If so, add it to the
13823 // aliases list. If not, then continue up the chain looking for the next
Scott Michelcf0da6c2009-02-17 22:15:04 +000013824 // candidate.
Jim Laskey6549d222006-10-05 15:07:25 +000013825 while (!Chains.empty()) {
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000013826 SDValue Chain = Chains.back();
Jim Laskey6549d222006-10-05 15:07:25 +000013827 Chains.pop_back();
Wesley Peck527da1b2010-11-23 03:31:01 +000013828
13829 // For TokenFactor nodes, look at each operand and only continue up the
13830 // chain until we find two aliases. If we've seen two aliases, assume we'll
Nate Begemana3ed9ed2009-10-12 05:53:58 +000013831 // find more and revert to original chain since the xform is unlikely to be
13832 // profitable.
Wesley Peck527da1b2010-11-23 03:31:01 +000013833 //
13834 // FIXME: The depth check could be made to return the last non-aliasing
Nate Begemana3ed9ed2009-10-12 05:53:58 +000013835 // chain we found before we hit a tokenfactor rather than the original
13836 // chain.
13837 if (Depth > 6 || Aliases.size() == 2) {
13838 Aliases.clear();
13839 Aliases.push_back(OriginalChain);
Hal Finkel51a98382014-01-24 20:12:02 +000013840 return;
Nate Begemana3ed9ed2009-10-12 05:53:58 +000013841 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000013842
Nate Begeman879d8f12009-09-15 00:18:30 +000013843 // Don't bother if we've been before.
David Blaikie70573dc2014-11-19 07:49:26 +000013844 if (!Visited.insert(Chain.getNode()).second)
Nate Begeman879d8f12009-09-15 00:18:30 +000013845 continue;
Scott Michelcf0da6c2009-02-17 22:15:04 +000013846
Jim Laskey6549d222006-10-05 15:07:25 +000013847 switch (Chain.getOpcode()) {
13848 case ISD::EntryToken:
13849 // Entry token is ideal chain operand, but handled in FindBetterChain.
13850 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +000013851
Jim Laskey6549d222006-10-05 15:07:25 +000013852 case ISD::LOAD:
13853 case ISD::STORE: {
13854 // Get alias information for Chain.
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013855 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
13856 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
Scott Michelcf0da6c2009-02-17 22:15:04 +000013857
Jim Laskey6549d222006-10-05 15:07:25 +000013858 // If chain is alias then stop here.
13859 if (!(IsLoad && IsOpLoad) &&
Nick Lewyckyaad475b2014-04-15 07:22:52 +000013860 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
Jim Laskey6549d222006-10-05 15:07:25 +000013861 Aliases.push_back(Chain);
13862 } else {
13863 // Look further up the chain.
Scott Michelcf0da6c2009-02-17 22:15:04 +000013864 Chains.push_back(Chain.getOperand(0));
Nate Begemana3ed9ed2009-10-12 05:53:58 +000013865 ++Depth;
Jim Laskeyd07be232006-09-25 16:29:54 +000013866 }
Jim Laskey6549d222006-10-05 15:07:25 +000013867 break;
13868 }
Scott Michelcf0da6c2009-02-17 22:15:04 +000013869
Jim Laskey6549d222006-10-05 15:07:25 +000013870 case ISD::TokenFactor:
Nate Begeman879d8f12009-09-15 00:18:30 +000013871 // We have to check each of the operands of the token factor for "small"
13872 // token factors, so we queue them up. Adding the operands to the queue
13873 // (stack) in reverse order maintains the original order and increases the
13874 // likelihood that getNode will find a matching token factor (CSE.)
13875 if (Chain.getNumOperands() > 16) {
13876 Aliases.push_back(Chain);
13877 break;
13878 }
Jim Laskey6549d222006-10-05 15:07:25 +000013879 for (unsigned n = Chain.getNumOperands(); n;)
13880 Chains.push_back(Chain.getOperand(--n));
Nate Begemana3ed9ed2009-10-12 05:53:58 +000013881 ++Depth;
Jim Laskey6549d222006-10-05 15:07:25 +000013882 break;
Scott Michelcf0da6c2009-02-17 22:15:04 +000013883
Jim Laskey6549d222006-10-05 15:07:25 +000013884 default:
13885 // For all other instructions we will just have to take what we can get.
13886 Aliases.push_back(Chain);
13887 break;
Jim Laskeyd07be232006-09-25 16:29:54 +000013888 }
13889 }
Hal Finkel51a98382014-01-24 20:12:02 +000013890
13891 // We need to be careful here to also search for aliases through the
13892 // value operand of a store, etc. Consider the following situation:
13893 // Token1 = ...
13894 // L1 = load Token1, %52
13895 // S1 = store Token1, L1, %51
13896 // L2 = load Token1, %52+8
13897 // S2 = store Token1, L2, %51+8
13898 // Token2 = Token(S1, S2)
13899 // L3 = load Token2, %53
13900 // S3 = store Token2, L3, %52
13901 // L4 = load Token2, %53+8
13902 // S4 = store Token2, L4, %52+8
13903 // If we search for aliases of S3 (which loads address %52), and we look
13904 // only through the chain, then we'll miss the trivial dependence on L1
13905 // (which also loads from %52). We then might change all loads and
13906 // stores to use Token1 as their chain operand, which could result in
13907 // copying %53 into %52 before copying %52 into %51 (which should
13908 // happen first).
13909 //
13910 // The problem is, however, that searching for such data dependencies
13911 // can become expensive, and the cost is not directly related to the
13912 // chain depth. Instead, we'll rule out such configurations here by
13913 // insisting that we've visited all chain users (except for users
13914 // of the original chain, which is not necessary). When doing this,
13915 // we need to look through nodes we don't care about (otherwise, things
13916 // like register copies will interfere with trivial cases).
13917
13918 SmallVector<const SDNode *, 16> Worklist;
Craig Topper46276792014-08-24 23:23:06 +000013919 for (const SDNode *N : Visited)
13920 if (N != OriginalChain.getNode())
13921 Worklist.push_back(N);
Hal Finkel51a98382014-01-24 20:12:02 +000013922
13923 while (!Worklist.empty()) {
13924 const SDNode *M = Worklist.pop_back_val();
13925
13926 // We have already visited M, and want to make sure we've visited any uses
13927 // of M that we care about. For uses that we've not visisted, and don't
13928 // care about, queue them to the worklist.
13929
13930 for (SDNode::use_iterator UI = M->use_begin(),
13931 UIE = M->use_end(); UI != UIE; ++UI)
David Blaikie70573dc2014-11-19 07:49:26 +000013932 if (UI.getUse().getValueType() == MVT::Other &&
13933 Visited.insert(*UI).second) {
Hal Finkel51a98382014-01-24 20:12:02 +000013934 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
13935 // We've not visited this use, and we care about it (it could have an
13936 // ordering dependency with the original node).
13937 Aliases.clear();
13938 Aliases.push_back(OriginalChain);
13939 return;
13940 }
13941
13942 // We've not visited this use, but we don't care about it. Mark it as
13943 // visited and enqueue it to the worklist.
13944 Worklist.push_back(*UI);
13945 }
13946 }
Jim Laskey708d0db2006-10-04 16:53:27 +000013947}
13948
Sanjay Patel50cbfc52014-08-28 16:29:51 +000013949/// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
13950/// (aliasing node.)
Dan Gohman2ce6f2a2008-07-27 21:46:04 +000013951SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
13952 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
Scott Michelcf0da6c2009-02-17 22:15:04 +000013953
Jim Laskey708d0db2006-10-04 16:53:27 +000013954 // Accumulate all the aliases to this node.
13955 GatherAllAliases(N, OldChain, Aliases);
Scott Michelcf0da6c2009-02-17 22:15:04 +000013956
Dan Gohman4298df62011-05-17 22:20:36 +000013957 // If no operands then chain to entry token.
13958 if (Aliases.size() == 0)
Jim Laskey708d0db2006-10-04 16:53:27 +000013959 return DAG.getEntryNode();
Dan Gohman4298df62011-05-17 22:20:36 +000013960
13961 // If a single operand then chain to it. We don't need to revisit it.
13962 if (Aliases.size() == 1)
Jim Laskey708d0db2006-10-04 16:53:27 +000013963 return Aliases[0];
Wesley Peck527da1b2010-11-23 03:31:01 +000013964
Jim Laskey708d0db2006-10-04 16:53:27 +000013965 // Construct a custom tailored token factor.
Craig Topper48d114b2014-04-26 18:35:24 +000013966 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
Jim Laskeyd07be232006-09-25 16:29:54 +000013967}
13968
Sanjay Patel50cbfc52014-08-28 16:29:51 +000013969/// This is the entry point for the file.
Bill Wendling084669a2009-04-29 00:15:41 +000013970void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
Bill Wendling026e5d72009-04-29 23:29:43 +000013971 CodeGenOpt::Level OptLevel) {
Sanjay Patel50cbfc52014-08-28 16:29:51 +000013972 /// This is the main entry point to this class.
Bill Wendling084669a2009-04-29 00:15:41 +000013973 DAGCombiner(*this, AA, OptLevel).Run(Level);
Nate Begeman21158fc2005-09-01 00:19:25 +000013974}